entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "P: \"Sign up\"\n SIGNIN: \"Sign in\"\n PASSWORD: \"Password\"\n REPEAT_PASSWORD: \"Repeat password\"\n DONOT", "end": 359, "score": 0.999481737613678, "start": 351, "tag": "PASSWORD", "value": "Password" }, { "context": "n\"\n PASSWORD: \"Password\"\n REPEAT_PASSWORD: \"Repeat password\"\n DONOT_WASTE_TIME: \"Do not waste time\"\n RE", "end": 398, "score": 0.9992258548736572, "start": 383, "tag": "PASSWORD", "value": "Repeat password" }, { "context": "L: \"My perfil\"\n EMAIL: \"Email\"\n FIRSTNAME: \"First name\"\n LASTNAME: \"Last name\"\n BIRTHDAY: \"Birthda", "end": 3034, "score": 0.9974033832550049, "start": 3024, "tag": "NAME", "value": "First name" }, { "context": "Email\"\n FIRSTNAME: \"First name\"\n LASTNAME: \"Last name\"\n BIRTHDAY: \"Birthday\"\n RADIUS_DISTANCE: \"R", "end": 3060, "score": 0.9986015558242798, "start": 3051, "tag": "NAME", "value": "Last name" }, { "context": "Registrarse\"\n SIGNIN: \"Acceder\"\n PASSWORD: \"Contraseña\"\n REPEAT_PASSWORD: \"Repetir contraseña\"\n DO", "end": 4554, "score": 0.9992154836654663, "start": 4544, "tag": "PASSWORD", "value": "Contraseña" }, { "context": "\n PASSWORD: \"Contraseña\"\n REPEAT_PASSWORD: \"Repetir contraseña\"\n DONOT_WASTE_TIME: \"No pierda más el tiempo\"\n", "end": 4596, "score": 0.9975660443305969, "start": 4578, "tag": "PASSWORD", "value": "Repetir contraseña" }, { "context": "Dirección:\"\n OUR_PHONE: \"Teléfono:\"\n NAME: \"Nombre\"\n NAME_PLACEHOLDER: \"Introduzca su nombre\"\n ", "end": 7141, "score": 0.9990896582603455, "start": 7135, "tag": "NAME", "value": "Nombre" }, { "context": "\"\n EMAIL: \"Correo electrónico\"\n FIRSTNAME: \"Nombre\"\n LASTNAME: \"Apellidos\"\n BIRTHDAY: \"Fecha d", "end": 7485, "score": 0.9997129440307617, "start": 7479, "tag": "NAME", "value": "Nombre" }, { "context": "ectrónico\"\n FIRSTNAME: \"Nombre\"\n LASTNAME: \"Apellidos\"\n BIRTHDAY: \"Fecha de nacimiento\"\n RADIUS_D", "end": 7511, "score": 0.9996907114982605, "start": 7502, "tag": "NAME", "value": "Apellidos" }, { "context": "alId\n RESERVE: \"Reservar\"\n COMMENTS: \"Comentarios\"\n DESCRIPTION: \"Descripción\"\n DESCRIPTION_P", "end": 8088, "score": 0.5420679450035095, "start": 8083, "tag": "NAME", "value": "arios" }, { "context": "ALS: \"Eskeintzak\"\n FIND: \"Aurkitu\"\n ABOUT: \"Guri bruz\"\n CONTACT: \"Kontaktua\"\n WELCOME: \"Ongi etor", "end": 8753, "score": 0.993213951587677, "start": 8744, "tag": "NAME", "value": "Guri bruz" }, { "context": "\"Kontua sortu\"\n SIGNIN: \"Sartu\"\n PASSWORD: \"Pasahitza\"\n REPEAT_PASSWORD: \"Pasahitza errepikatu\"\n ", "end": 8923, "score": 0.9993493556976318, "start": 8914, "tag": "PASSWORD", "value": "Pasahitza" }, { "context": "\"\n PASSWORD: \"Pasahitza\"\n REPEAT_PASSWORD: \"Pasahitza errepikatu\"\n DONOT_WASTE_TIME: \"Denbora gehiagorik ez gal", "end": 8967, "score": 0.9992868900299072, "start": 8947, "tag": "PASSWORD", "value": "Pasahitza errepikatu" }, { "context": "ITLE: \"KONTUA SORTU\"\n PASSWORDS_DO_NOT_MATCH: \"Sarturiko pasahitzak ez datoz bat\"\n SHOP_NAME_HAS_TO_BE_PROVIDED: \"Dendaren izen", "end": 9356, "score": 0.902216374874115, "start": 9323, "tag": "PASSWORD", "value": "Sarturiko pasahitzak ez datoz bat" }, { "context": "satu eta arineketan joan zaitez!\"\n\n\n MY_BUYS: \"Nire erosketak\"\n NO_BUYS: \"Ez duzu erosketarik egin\"\n BUYE", "end": 10724, "score": 0.8378135561943054, "start": 10710, "tag": "NAME", "value": "Nire erosketak" }, { "context": " \"Ez dago gertuko eskaintzarik\"\n MY_COMMENTS: \"Nire iruzkinak\"\n NO_COMMENTS: \"Ez duzu iruzkinik idatz", "end": 11036, "score": 0.6592102646827698, "start": 11029, "tag": "NAME", "value": "Nire ir" }, { "context": " \"Erreserba kodea\"\n\n #contact\n CONTACT_US: \"Gurekin harremanetan jarri\"\n ADDRESS: \"Helbidea:\"\n OUR_PHONE: \"Telefon", "end": 11216, "score": 0.9997601509094238, "start": 11190, "tag": "NAME", "value": "Gurekin harremanetan jarri" }, { "context": "Helbidea:\"\n OUR_PHONE: \"Telefonoa:\"\n NAME: \"Izena\"\n NAME_PLACEHOLDER: \"Sartu zure izena\"\n EMA", "end": 11287, "score": 0.999646008014679, "start": 11282, "tag": "NAME", "value": "Izena" }, { "context": "efonoa:\"\n NAME: \"Izena\"\n NAME_PLACEHOLDER: \"Sartu zure izena\"\n EMAIL_PLACEHOLDER: \"Sartu zure helbidea\"\n ", "end": 11328, "score": 0.9980708956718445, "start": 11312, "tag": "NAME", "value": "Sartu zure izena" }, { "context": "OLDER: \"Sartu zure izena\"\n EMAIL_PLACEHOLDER: \"Sartu zure helbidea\"\n PHONE: \"Telefonoa\"\n PHONE_PLACEHOLDER: \"S", "end": 11373, "score": 0.994751513004303, "start": 11354, "tag": "NAME", "value": "Sartu zure helbidea" }, { "context": " SEND: \"Bidali\"\n\n # / profile\n MY_PERFIL: \"Nire profila\"\n EMAIL: \"Helbide elektronikoa\"\n FIRSTNAME:", "end": 11556, "score": 0.9988781809806824, "start": 11544, "tag": "NAME", "value": "Nire profila" }, { "context": " EMAIL: \"Helbide elektronikoa\"\n FIRSTNAME: \"Izena\"\n LASTNAME: \"Abizenak\"\n BIRTHDAY: \"Jaiotze ", "end": 11613, "score": 0.9998092651367188, "start": 11608, "tag": "NAME", "value": "Izena" }, { "context": "ektronikoa\"\n FIRSTNAME: \"Izena\"\n LASTNAME: \"Abizenak\"\n BIRTHDAY: \"Jaiotze data\"\n RADIUS_DISTANCE", "end": 11638, "score": 0.9998336434364319, "start": 11630, "tag": "NAME", "value": "Abizenak" }, { "context": "ia eremua\"\n\n #deals\n DEALNAME_PLACEHOLDER: \"Eskaintzaren izena...\"\n SEARCH_BY: \"Parametro hauengatik bilat", "end": 11984, "score": 0.8834453225135803, "start": 11969, "tag": "NAME", "value": "Eskaintzaren iz" }, { "context": "CEHOLDER: \"Eskaintzaren izena...\"\n SEARCH_BY: \"Parametro hauengatik bilatu:\"\n ALL_CATEGORIES: \"Kategoria guztiak\"\n ANY", "end": 12035, "score": 0.9973632097244263, "start": 12008, "tag": "NAME", "value": "Parametro hauengatik bilatu" }, { "context": "ozein prezio\"\n\n # deal/:dealId\n RESERVE: \"Erreserbatu\"\n COMMENTS: \"Iruzkinak\"\n DESCRIPTION: \"Desk", "end": 12155, "score": 0.7636817097663879, "start": 12146, "tag": "NAME", "value": "reserbatu" }, { "context": ":dealId\n RESERVE: \"Erreserbatu\"\n COMMENTS: \"Iruzkinak\"\n DESCRIPTION: \"Deskribapena\"\n DESCRIPTION_", "end": 12181, "score": 0.9497843980789185, "start": 12172, "tag": "NAME", "value": "Iruzkinak" } ]
assets/translations.coffee
gertu/gertu
1
angular.module("mean").config ["$translateProvider", ($translateProvider) -> $translateProvider.translations "en-US", # / HOME: "Home" DEALS: "Deals" FIND: "Find" ABOUT: "About" CONTACT: "Contact" WELCOME: "Welcome" PROFILE: "Profile" SIGNOUT: "Logout" SIGNUP: "Sign up" SIGNIN: "Sign in" PASSWORD: "Password" REPEAT_PASSWORD: "Repeat password" DONOT_WASTE_TIME: "Do not waste time" REGISTER_FOR_FREE: "Register for free and start taking advantage" REGISTER_NOW: "Register now" WHAT_WE_HAVE: "What we have" DONOT_LOSE_CHANCE: "Do not miss the opportunity to take advantage of them" I_AM_A_SHOP: "I'm a shop" SIGNUP_FORM_TITLE: "SIGN UP" PASSWORDS_DO_NOT_MATCH: "The passwords do not match" SHOP_NAME_HAS_TO_BE_PROVIDED: "The name must be required" EMAIL_HAS_TO_BE_PROVIDED: "The email must be required" PASSWORD_HAS_TO_BE_PROVIDED: "The password must be required" EMAIL_ALREADY_EXISTS: "This email is in use, please you check another one" NO_SHOP_HAS_BEEN_FOUND: "Does not exist any shop with these credentials" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "The email and password must required for login" UNKNOWN_ERROR: "Unknown error" FOR_FREE: "We do not charge anything" GET_IN: "Enter and discover the deals" DONT_HESITATE: "Do not think twice" ACTIVE_DEALS: "active deals" RESERVED_DEALS: "reserved deals" ACTIVE_USERS: "active users" ACTIVE_SHOPS: "active shops" STEP_FIND: "Find" STEP_FIND_DESC: "Find out in the deals list one you like the most. There are thousands to choose, don't let yours go away" STEP_RESERVE: "Reserve" STEP_RESERVE_DESC: "Once chosen, you simply have to reserve it and you will be assigned a reserve number; it's important you don't lose it" STEP_REDEEM: "Redeem" STEP_REDEEM_DESC: "Go to the shop that offers the deal and show the shop assistant your reservation number. Once validated you will be able to redeem it" STEP_ENJOY: "Enjoy!" STEP_ENJOY_DESC: "With the deal redeemed and in your hands, it's time to enjoy it. So don't think any more about it and run to enjoy it!" MY_BUYS: "My buys" NO_BUYS: "You have not bought any deal yet" BUYED: "Buyed the " MY_RESERVES: "My reserves" NO_RESERVES: "You have not got any pending reserve" RESERVED: "Reserved the " NEARBY_DEALS: "Nearby deals" NO_NEAR_DEALS: "You have not got any nearby deal" MY_COMMENTS: "My comments" NO_COMMENTS: "You have not writed any comment yet" YOU_ARE_IN: "You are in " RESERVE_CODE: "Reserve code" #contact CONTACT_US: "Contact us" ADDRESS: "Address:" OUR_PHONE: "Phone:" NAME: "Name" NAME_PLACEHOLDER: "Enter your name" EMAIL_PLACEHOLDER: "Enter your email" PHONE: "Phone" PHONE_PLACEHOLDER: "Enter your phone" MESSAGE_PLACEHOLDER: "Enter your comments" SEND: "Send" # /profile MY_PERFIL: "My perfil" EMAIL: "Email" FIRSTNAME: "First name" LASTNAME: "Last name" BIRTHDAY: "Birthday" RADIUS_DISTANCE: "Radius distance" METERS: "meters" SAVE: "Save" UPLOAD: "Upload image" CHANGE_IMAGE: "Change image" SAVING: "Saving..." UPLOADING: "Uploading..." RADIUS_DISTANCE_TOOLTIP: "Meter radius from your position that they find the deals" #deals DEALNAME_PLACEHOLDER: "Deal name..." SEARCH_BY: "Search by:" ALL_CATEGORIES: "All categories" ANY_PRICE: "Any price" #deal/:dealId RESERVE: "Reserve" COMMENTS: "Comments" DESCRIPTION: "Description" DESCRIPTION_PLACEHOLDER: "Description of the deal..." RATING: "Rating" COMMENT_200: "Comment has been added!" COMMENT_401: "You must login to leave a comment" COMMENT_404: "Unknown user" COMMENT_409: "Sorry, but you have already post a comment in this deal" COMMENT_422: "Remember that the rating and description are necessary for leave a comment" COMMENT_500: "It has been impossible to add your comment, please try again in a few minutes" ################################################################################ ################################################################################ $translateProvider.translations "es-ES", # / HOME: "Inicio" DEALS: "Ofertas" FIND: "Buscar" ABOUT: "Acerca de" CONTACT: "Contacto" WELCOME: "Bienvenido" PROFILE: "Perfil" SIGNOUT: "Cerrar sesión" SIGNUP: "Registrarse" SIGNIN: "Acceder" PASSWORD: "Contraseña" REPEAT_PASSWORD: "Repetir contraseña" DONOT_WASTE_TIME: "No pierda más el tiempo" REGISTER_FOR_FREE: "Regístrese gratuitamente y empiece a aprovecharse" REGISTER_NOW: "Regístrese ahora" WHAT_WE_HAVE: "Lo que tenemos" DONOT_LOSE_CHANCE: "No pierda la oportunidad de aprovecharlas" I_AM_A_SHOP: "Soy empresa" SIGNUP_FORM_TITLE: "CREAR UNA CUENTA" PASSWORDS_DO_NOT_MATCH: "Las contraseñas suministradas no coinciden" SHOP_NAME_HAS_TO_BE_PROVIDED: "Debe proporcionar un nombre para el comercio" EMAIL_HAS_TO_BE_PROVIDED: "Debe proporcionar un email para el comercio" PASSWORD_HAS_TO_BE_PROVIDED: "Debe proporcionar una contraseña para el comercio" EMAIL_ALREADY_EXISTS: "Ya existe un comercio con ese email. Por favor, proporcione otro." NO_SHOP_HAS_BEEN_FOUND: "No se ha encontrado ningún comercio con los credenciales suministrados" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "Debe indicar una contraseña y un email para poder acceder" UNKNOWN_ERROR: "Error desconocido" FOR_FREE: "No cobramos nada" GET_IN: "Entre y descubra las ofertas" DONT_HESITATE: "No lo piense más" ACTIVE_DEALS: "ofertas activas" RESERVED_DEALS: "ofertas reservadas" ACTIVE_USERS: "usuarios activos" ACTIVE_SHOPS: "tiendas asociadas" STEP_FIND: "Busca" STEP_FIND_DESC: "Busca dentro de nuestra lista de ofertas la que más te guste. Hay miles entre las que elegir, no dejes que se escape la tuya" STEP_RESERVE: "Reserva" STEP_RESERVE_DESC: "Una vez elegida, simplemente tienes que reservarla y se te asignará un número de reserva; es muy importante que no lo pierdas" STEP_REDEEM: "Canjea" STEP_REDEEM_DESC: "Acércate a la tienda que ofrece la oferta y muéstrale al dependiente tu número de reserva. Una vez validado podrás canjearla" STEP_ENJOY: "¡Disfruta!" STEP_ENJOY_DESC: "Con la oferta ya canjeada y en tu poder, es hora de disfrutar de ella. Así que no lo pienses más y ¡corre a disfrutar de ella!" MY_BUYS: "Mis compras" NO_BUYS: "No has realizado ninguna compra" BUYED: "Comprado el " MY_RESERVES: "Mis reservas" NO_RESERVES: "No tienes ninguna reserva pendiente" RESERVED: "Reservado el " NEARBY_DEALS: "Ofertas cercanas" NO_NEAR_DEALS: "No hay ofertas cercanas" MY_COMMENTS: "Mis comentarios" NO_COMMENTS: "No tienes comentarios aún" YOU_ARE_IN: "Usted se encuentra en " RESERVE_CODE: "Codigo de reserva" #contact CONTACT_US: "Contacte con nosotros" ADDRESS: "Dirección:" OUR_PHONE: "Teléfono:" NAME: "Nombre" NAME_PLACEHOLDER: "Introduzca su nombre" EMAIL_PLACEHOLDER: "Introduzca su correo electrónico" PHONE: "Teléfono" PHONE_PLACEHOLDER: "Introduzca su teléfono" MESSAGE_PLACEHOLDER: "Introduzca su comentario" SEND: "Enviar" # / profile MY_PERFIL: "Mi perfil" EMAIL: "Correo electrónico" FIRSTNAME: "Nombre" LASTNAME: "Apellidos" BIRTHDAY: "Fecha de nacimiento" RADIUS_DISTANCE: "Radio de detección" METERS: "metros" SAVE: "Guardar" UPLOAD: "Subir imagen" CHANGE_IMAGE: "Cambiar imagen" SAVING: "Guardando..." UPLOADING: "Subiendo..." RADIUS_DISTANCE_TOOLTIP: "Metros a la redonda, desde tu posición, en los que se buscarán ofertas" #deals DEALNAME_PLACEHOLDER: "Nombre de oferta..." SEARCH_BY: "Buscar por:" ALL_CATEGORIES: "Todas las categorías" ANY_PRICE: "Cualquier precio" # deal/:dealId RESERVE: "Reservar" COMMENTS: "Comentarios" DESCRIPTION: "Descripción" DESCRIPTION_PLACEHOLDER: "Descripción de la oferta..." RATING: "Puntuación" COMMENT_200: "¡El comentario ha sido añadido!" COMMENT_401: "Para dejar un comentario debe iniciar sesión" COMMENT_404: "Usuario desconocido" COMMENT_409: "Lo sentimos, usted ya comentó esta oferta" COMMENT_422: "Recuerde que son necesarios tanto una puntuación como un breve comentario" COMMENT_500: "Ha sido imposible añadir el comentario, por favor inténtelo de nuevo en unos minutos" $translateProvider.translations "eu", # / HOME: "Hasiera" DEALS: "Eskeintzak" FIND: "Aurkitu" ABOUT: "Guri bruz" CONTACT: "Kontaktua" WELCOME: "Ongi etorri" PROFILE: "Profila" SIGNOUT: "Irten" SIGNUP: "Kontua sortu" SIGNIN: "Sartu" PASSWORD: "Pasahitza" REPEAT_PASSWORD: "Pasahitza errepikatu" DONOT_WASTE_TIME: "Denbora gehiagorik ez galdu" REGISTER_FOR_FREE: "Sortu kontua dohainik eta hasi erabiltzan" REGISTER_NOW: "Kontua sortu" WHAT_WE_HAVE: "Bertan aurkituko duzuna" DONOT_LOSE_CHANCE: "Ez galdu onura hauek izateko aukera" I_AM_A_SHOP: "Denda naiz" SIGNUP_FORM_TITLE: "KONTUA SORTU" PASSWORDS_DO_NOT_MATCH: "Sarturiko pasahitzak ez datoz bat" SHOP_NAME_HAS_TO_BE_PROVIDED: "Dendaren izena sartu behar duzu" EMAIL_HAS_TO_BE_PROVIDED: "Dendarendako email bat sartu behar duzu" PASSWORD_HAS_TO_BE_PROVIDED: "Dendaren pasahitza sartu behar duzu" EMAIL_ALREADY_EXISTS: "Bada helbide hau erabiltzen ari den denda. Mesedez, sartu beste bat." NO_SHOP_HAS_BEEN_FOUND: "Ez da dendarik aurkitu sartutako datuekin" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "Helbide eta pasahitz bat beharrezkoa da sartzeko" UNKNOWN_ERROR: "Akats ezezaguna" FOR_FREE: "Ez dugu ezer kobratzen" GET_IN: "Sartu eta eskaintzez gozatu" DONT_HESITATE: "Ez pentsatu gehiago" ACTIVE_DEALS: "uskaintzak" RESERVED_DEALS: "eskaintza erreserba" ACTIVE_USERS: "erabiltzaile" ACTIVE_SHOPS: "denda" STEP_FIND: "Aurkitu" STEP_FIND_DESC: "Gure eskaintzen artean gehien gustuko duzuna bilatu. Hamaika eskaintza ditugu, lortu zurea." STEP_RESERVE: "Erreserba" STEP_RESERVE_DESC: "Behin aukeratutakoan, erreserba egin eta zenbaki bat egokituko zaizu" STEP_REDEEM: "Trukatu" STEP_REDEEM_DESC: "Gerturatu eskaintzaren dendara eta erakutsi zure kodea. Baieztatu ostean trukatu ahal izango duzu" STEP_ENJOY: "Gozatu!" STEP_ENJOY_DESC: "Behin eskaintza eskuratuta, gozatzen hasi zaitezke. Beraz, ez gehiago pentsatu eta arineketan joan zaitez!" MY_BUYS: "Nire erosketak" NO_BUYS: "Ez duzu erosketarik egin" BUYED: "Erosketa eguna: " MY_RESERVES: "Nire erreserbak" NO_RESERVES: "Ez duzu erreserbarik trukatzeko" RESERVED: "Erreserbatutako eguna: " NEARBY_DEALS: "Gertuko eskaintzak" NO_NEAR_DEALS: "Ez dago gertuko eskaintzarik" MY_COMMENTS: "Nire iruzkinak" NO_COMMENTS: "Ez duzu iruzkinik idatzi" YOU_ARE_IN: "Zure kokapena: " RESERVE_CODE: "Erreserba kodea" #contact CONTACT_US: "Gurekin harremanetan jarri" ADDRESS: "Helbidea:" OUR_PHONE: "Telefonoa:" NAME: "Izena" NAME_PLACEHOLDER: "Sartu zure izena" EMAIL_PLACEHOLDER: "Sartu zure helbidea" PHONE: "Telefonoa" PHONE_PLACEHOLDER: "Sartu zure telefonoa" MESSAGE_PLACEHOLDER: "Idatzi zure iruzkina" SEND: "Bidali" # / profile MY_PERFIL: "Nire profila" EMAIL: "Helbide elektronikoa" FIRSTNAME: "Izena" LASTNAME: "Abizenak" BIRTHDAY: "Jaiotze data" RADIUS_DISTANCE: "Kokapen eremua" METERS: "metro" SAVE: "Gorde" UPLOAD: "Irudia igo" CHANGE_IMAGE: "Irudia aldatu" SAVING: "Gordetzen..." UPLOADING: "Igotzen..." RADIUS_DISTANCE_TOOLTIP: "Eskaintzak aurkitzeko distantzia eremua" #deals DEALNAME_PLACEHOLDER: "Eskaintzaren izena..." SEARCH_BY: "Parametro hauengatik bilatu:" ALL_CATEGORIES: "Kategoria guztiak" ANY_PRICE: "Edozein prezio" # deal/:dealId RESERVE: "Erreserbatu" COMMENTS: "Iruzkinak" DESCRIPTION: "Deskribapena" DESCRIPTION_PLACEHOLDER: "Eskeintzaren deskribapena..." RATING: "Puntuazioa" COMMENT_200: "Iruzkina gehitua izan da!" COMMENT_401: "Iruzkina idazteko saioa hasi beharra duzu" COMMENT_404: "Erabiltzaile ezezaguna" COMMENT_409: "Barkatu, eskaintza hau komentatu duzu jada" COMMENT_422: "Bai puntuazioa, bai deskribapena beharrezkoak dira" COMMENT_500: "Iruzkina gehitzea ezinezkoa izan da, mesedez saia zaitze hemenidk minutu batzuetara" $translateProvider.preferredLanguage (if navigator.language is "es" then "es-ES" else navigator.language) ]
152712
angular.module("mean").config ["$translateProvider", ($translateProvider) -> $translateProvider.translations "en-US", # / HOME: "Home" DEALS: "Deals" FIND: "Find" ABOUT: "About" CONTACT: "Contact" WELCOME: "Welcome" PROFILE: "Profile" SIGNOUT: "Logout" SIGNUP: "Sign up" SIGNIN: "Sign in" PASSWORD: "<PASSWORD>" REPEAT_PASSWORD: "<PASSWORD>" DONOT_WASTE_TIME: "Do not waste time" REGISTER_FOR_FREE: "Register for free and start taking advantage" REGISTER_NOW: "Register now" WHAT_WE_HAVE: "What we have" DONOT_LOSE_CHANCE: "Do not miss the opportunity to take advantage of them" I_AM_A_SHOP: "I'm a shop" SIGNUP_FORM_TITLE: "SIGN UP" PASSWORDS_DO_NOT_MATCH: "The passwords do not match" SHOP_NAME_HAS_TO_BE_PROVIDED: "The name must be required" EMAIL_HAS_TO_BE_PROVIDED: "The email must be required" PASSWORD_HAS_TO_BE_PROVIDED: "The password must be required" EMAIL_ALREADY_EXISTS: "This email is in use, please you check another one" NO_SHOP_HAS_BEEN_FOUND: "Does not exist any shop with these credentials" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "The email and password must required for login" UNKNOWN_ERROR: "Unknown error" FOR_FREE: "We do not charge anything" GET_IN: "Enter and discover the deals" DONT_HESITATE: "Do not think twice" ACTIVE_DEALS: "active deals" RESERVED_DEALS: "reserved deals" ACTIVE_USERS: "active users" ACTIVE_SHOPS: "active shops" STEP_FIND: "Find" STEP_FIND_DESC: "Find out in the deals list one you like the most. There are thousands to choose, don't let yours go away" STEP_RESERVE: "Reserve" STEP_RESERVE_DESC: "Once chosen, you simply have to reserve it and you will be assigned a reserve number; it's important you don't lose it" STEP_REDEEM: "Redeem" STEP_REDEEM_DESC: "Go to the shop that offers the deal and show the shop assistant your reservation number. Once validated you will be able to redeem it" STEP_ENJOY: "Enjoy!" STEP_ENJOY_DESC: "With the deal redeemed and in your hands, it's time to enjoy it. So don't think any more about it and run to enjoy it!" MY_BUYS: "My buys" NO_BUYS: "You have not bought any deal yet" BUYED: "Buyed the " MY_RESERVES: "My reserves" NO_RESERVES: "You have not got any pending reserve" RESERVED: "Reserved the " NEARBY_DEALS: "Nearby deals" NO_NEAR_DEALS: "You have not got any nearby deal" MY_COMMENTS: "My comments" NO_COMMENTS: "You have not writed any comment yet" YOU_ARE_IN: "You are in " RESERVE_CODE: "Reserve code" #contact CONTACT_US: "Contact us" ADDRESS: "Address:" OUR_PHONE: "Phone:" NAME: "Name" NAME_PLACEHOLDER: "Enter your name" EMAIL_PLACEHOLDER: "Enter your email" PHONE: "Phone" PHONE_PLACEHOLDER: "Enter your phone" MESSAGE_PLACEHOLDER: "Enter your comments" SEND: "Send" # /profile MY_PERFIL: "My perfil" EMAIL: "Email" FIRSTNAME: "<NAME>" LASTNAME: "<NAME>" BIRTHDAY: "Birthday" RADIUS_DISTANCE: "Radius distance" METERS: "meters" SAVE: "Save" UPLOAD: "Upload image" CHANGE_IMAGE: "Change image" SAVING: "Saving..." UPLOADING: "Uploading..." RADIUS_DISTANCE_TOOLTIP: "Meter radius from your position that they find the deals" #deals DEALNAME_PLACEHOLDER: "Deal name..." SEARCH_BY: "Search by:" ALL_CATEGORIES: "All categories" ANY_PRICE: "Any price" #deal/:dealId RESERVE: "Reserve" COMMENTS: "Comments" DESCRIPTION: "Description" DESCRIPTION_PLACEHOLDER: "Description of the deal..." RATING: "Rating" COMMENT_200: "Comment has been added!" COMMENT_401: "You must login to leave a comment" COMMENT_404: "Unknown user" COMMENT_409: "Sorry, but you have already post a comment in this deal" COMMENT_422: "Remember that the rating and description are necessary for leave a comment" COMMENT_500: "It has been impossible to add your comment, please try again in a few minutes" ################################################################################ ################################################################################ $translateProvider.translations "es-ES", # / HOME: "Inicio" DEALS: "Ofertas" FIND: "Buscar" ABOUT: "Acerca de" CONTACT: "Contacto" WELCOME: "Bienvenido" PROFILE: "Perfil" SIGNOUT: "Cerrar sesión" SIGNUP: "Registrarse" SIGNIN: "Acceder" PASSWORD: "<PASSWORD>" REPEAT_PASSWORD: "<PASSWORD>" DONOT_WASTE_TIME: "No pierda más el tiempo" REGISTER_FOR_FREE: "Regístrese gratuitamente y empiece a aprovecharse" REGISTER_NOW: "Regístrese ahora" WHAT_WE_HAVE: "Lo que tenemos" DONOT_LOSE_CHANCE: "No pierda la oportunidad de aprovecharlas" I_AM_A_SHOP: "Soy empresa" SIGNUP_FORM_TITLE: "CREAR UNA CUENTA" PASSWORDS_DO_NOT_MATCH: "Las contraseñas suministradas no coinciden" SHOP_NAME_HAS_TO_BE_PROVIDED: "Debe proporcionar un nombre para el comercio" EMAIL_HAS_TO_BE_PROVIDED: "Debe proporcionar un email para el comercio" PASSWORD_HAS_TO_BE_PROVIDED: "Debe proporcionar una contraseña para el comercio" EMAIL_ALREADY_EXISTS: "Ya existe un comercio con ese email. Por favor, proporcione otro." NO_SHOP_HAS_BEEN_FOUND: "No se ha encontrado ningún comercio con los credenciales suministrados" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "Debe indicar una contraseña y un email para poder acceder" UNKNOWN_ERROR: "Error desconocido" FOR_FREE: "No cobramos nada" GET_IN: "Entre y descubra las ofertas" DONT_HESITATE: "No lo piense más" ACTIVE_DEALS: "ofertas activas" RESERVED_DEALS: "ofertas reservadas" ACTIVE_USERS: "usuarios activos" ACTIVE_SHOPS: "tiendas asociadas" STEP_FIND: "Busca" STEP_FIND_DESC: "Busca dentro de nuestra lista de ofertas la que más te guste. Hay miles entre las que elegir, no dejes que se escape la tuya" STEP_RESERVE: "Reserva" STEP_RESERVE_DESC: "Una vez elegida, simplemente tienes que reservarla y se te asignará un número de reserva; es muy importante que no lo pierdas" STEP_REDEEM: "Canjea" STEP_REDEEM_DESC: "Acércate a la tienda que ofrece la oferta y muéstrale al dependiente tu número de reserva. Una vez validado podrás canjearla" STEP_ENJOY: "¡Disfruta!" STEP_ENJOY_DESC: "Con la oferta ya canjeada y en tu poder, es hora de disfrutar de ella. Así que no lo pienses más y ¡corre a disfrutar de ella!" MY_BUYS: "Mis compras" NO_BUYS: "No has realizado ninguna compra" BUYED: "Comprado el " MY_RESERVES: "Mis reservas" NO_RESERVES: "No tienes ninguna reserva pendiente" RESERVED: "Reservado el " NEARBY_DEALS: "Ofertas cercanas" NO_NEAR_DEALS: "No hay ofertas cercanas" MY_COMMENTS: "Mis comentarios" NO_COMMENTS: "No tienes comentarios aún" YOU_ARE_IN: "Usted se encuentra en " RESERVE_CODE: "Codigo de reserva" #contact CONTACT_US: "Contacte con nosotros" ADDRESS: "Dirección:" OUR_PHONE: "Teléfono:" NAME: "<NAME>" NAME_PLACEHOLDER: "Introduzca su nombre" EMAIL_PLACEHOLDER: "Introduzca su correo electrónico" PHONE: "Teléfono" PHONE_PLACEHOLDER: "Introduzca su teléfono" MESSAGE_PLACEHOLDER: "Introduzca su comentario" SEND: "Enviar" # / profile MY_PERFIL: "Mi perfil" EMAIL: "Correo electrónico" FIRSTNAME: "<NAME>" LASTNAME: "<NAME>" BIRTHDAY: "Fecha de nacimiento" RADIUS_DISTANCE: "Radio de detección" METERS: "metros" SAVE: "Guardar" UPLOAD: "Subir imagen" CHANGE_IMAGE: "Cambiar imagen" SAVING: "Guardando..." UPLOADING: "Subiendo..." RADIUS_DISTANCE_TOOLTIP: "Metros a la redonda, desde tu posición, en los que se buscarán ofertas" #deals DEALNAME_PLACEHOLDER: "Nombre de oferta..." SEARCH_BY: "Buscar por:" ALL_CATEGORIES: "Todas las categorías" ANY_PRICE: "Cualquier precio" # deal/:dealId RESERVE: "Reservar" COMMENTS: "Coment<NAME>" DESCRIPTION: "Descripción" DESCRIPTION_PLACEHOLDER: "Descripción de la oferta..." RATING: "Puntuación" COMMENT_200: "¡El comentario ha sido añadido!" COMMENT_401: "Para dejar un comentario debe iniciar sesión" COMMENT_404: "Usuario desconocido" COMMENT_409: "Lo sentimos, usted ya comentó esta oferta" COMMENT_422: "Recuerde que son necesarios tanto una puntuación como un breve comentario" COMMENT_500: "Ha sido imposible añadir el comentario, por favor inténtelo de nuevo en unos minutos" $translateProvider.translations "eu", # / HOME: "Hasiera" DEALS: "Eskeintzak" FIND: "Aurkitu" ABOUT: "<NAME>" CONTACT: "Kontaktua" WELCOME: "Ongi etorri" PROFILE: "Profila" SIGNOUT: "Irten" SIGNUP: "Kontua sortu" SIGNIN: "Sartu" PASSWORD: "<PASSWORD>" REPEAT_PASSWORD: "<PASSWORD>" DONOT_WASTE_TIME: "Denbora gehiagorik ez galdu" REGISTER_FOR_FREE: "Sortu kontua dohainik eta hasi erabiltzan" REGISTER_NOW: "Kontua sortu" WHAT_WE_HAVE: "Bertan aurkituko duzuna" DONOT_LOSE_CHANCE: "Ez galdu onura hauek izateko aukera" I_AM_A_SHOP: "Denda naiz" SIGNUP_FORM_TITLE: "KONTUA SORTU" PASSWORDS_DO_NOT_MATCH: "<PASSWORD>" SHOP_NAME_HAS_TO_BE_PROVIDED: "Dendaren izena sartu behar duzu" EMAIL_HAS_TO_BE_PROVIDED: "Dendarendako email bat sartu behar duzu" PASSWORD_HAS_TO_BE_PROVIDED: "Dendaren pasahitza sartu behar duzu" EMAIL_ALREADY_EXISTS: "Bada helbide hau erabiltzen ari den denda. Mesedez, sartu beste bat." NO_SHOP_HAS_BEEN_FOUND: "Ez da dendarik aurkitu sartutako datuekin" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "Helbide eta pasahitz bat beharrezkoa da sartzeko" UNKNOWN_ERROR: "Akats ezezaguna" FOR_FREE: "Ez dugu ezer kobratzen" GET_IN: "Sartu eta eskaintzez gozatu" DONT_HESITATE: "Ez pentsatu gehiago" ACTIVE_DEALS: "uskaintzak" RESERVED_DEALS: "eskaintza erreserba" ACTIVE_USERS: "erabiltzaile" ACTIVE_SHOPS: "denda" STEP_FIND: "Aurkitu" STEP_FIND_DESC: "Gure eskaintzen artean gehien gustuko duzuna bilatu. Hamaika eskaintza ditugu, lortu zurea." STEP_RESERVE: "Erreserba" STEP_RESERVE_DESC: "Behin aukeratutakoan, erreserba egin eta zenbaki bat egokituko zaizu" STEP_REDEEM: "Trukatu" STEP_REDEEM_DESC: "Gerturatu eskaintzaren dendara eta erakutsi zure kodea. Baieztatu ostean trukatu ahal izango duzu" STEP_ENJOY: "Gozatu!" STEP_ENJOY_DESC: "Behin eskaintza eskuratuta, gozatzen hasi zaitezke. Beraz, ez gehiago pentsatu eta arineketan joan zaitez!" MY_BUYS: "<NAME>" NO_BUYS: "Ez duzu erosketarik egin" BUYED: "Erosketa eguna: " MY_RESERVES: "Nire erreserbak" NO_RESERVES: "Ez duzu erreserbarik trukatzeko" RESERVED: "Erreserbatutako eguna: " NEARBY_DEALS: "Gertuko eskaintzak" NO_NEAR_DEALS: "Ez dago gertuko eskaintzarik" MY_COMMENTS: "<NAME>uzkinak" NO_COMMENTS: "Ez duzu iruzkinik idatzi" YOU_ARE_IN: "Zure kokapena: " RESERVE_CODE: "Erreserba kodea" #contact CONTACT_US: "<NAME>" ADDRESS: "Helbidea:" OUR_PHONE: "Telefonoa:" NAME: "<NAME>" NAME_PLACEHOLDER: "<NAME>" EMAIL_PLACEHOLDER: "<NAME>" PHONE: "Telefonoa" PHONE_PLACEHOLDER: "Sartu zure telefonoa" MESSAGE_PLACEHOLDER: "Idatzi zure iruzkina" SEND: "Bidali" # / profile MY_PERFIL: "<NAME>" EMAIL: "Helbide elektronikoa" FIRSTNAME: "<NAME>" LASTNAME: "<NAME>" BIRTHDAY: "Jaiotze data" RADIUS_DISTANCE: "Kokapen eremua" METERS: "metro" SAVE: "Gorde" UPLOAD: "Irudia igo" CHANGE_IMAGE: "Irudia aldatu" SAVING: "Gordetzen..." UPLOADING: "Igotzen..." RADIUS_DISTANCE_TOOLTIP: "Eskaintzak aurkitzeko distantzia eremua" #deals DEALNAME_PLACEHOLDER: "<NAME>ena..." SEARCH_BY: "<NAME>:" ALL_CATEGORIES: "Kategoria guztiak" ANY_PRICE: "Edozein prezio" # deal/:dealId RESERVE: "Er<NAME>" COMMENTS: "<NAME>" DESCRIPTION: "Deskribapena" DESCRIPTION_PLACEHOLDER: "Eskeintzaren deskribapena..." RATING: "Puntuazioa" COMMENT_200: "Iruzkina gehitua izan da!" COMMENT_401: "Iruzkina idazteko saioa hasi beharra duzu" COMMENT_404: "Erabiltzaile ezezaguna" COMMENT_409: "Barkatu, eskaintza hau komentatu duzu jada" COMMENT_422: "Bai puntuazioa, bai deskribapena beharrezkoak dira" COMMENT_500: "Iruzkina gehitzea ezinezkoa izan da, mesedez saia zaitze hemenidk minutu batzuetara" $translateProvider.preferredLanguage (if navigator.language is "es" then "es-ES" else navigator.language) ]
true
angular.module("mean").config ["$translateProvider", ($translateProvider) -> $translateProvider.translations "en-US", # / HOME: "Home" DEALS: "Deals" FIND: "Find" ABOUT: "About" CONTACT: "Contact" WELCOME: "Welcome" PROFILE: "Profile" SIGNOUT: "Logout" SIGNUP: "Sign up" SIGNIN: "Sign in" PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" REPEAT_PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" DONOT_WASTE_TIME: "Do not waste time" REGISTER_FOR_FREE: "Register for free and start taking advantage" REGISTER_NOW: "Register now" WHAT_WE_HAVE: "What we have" DONOT_LOSE_CHANCE: "Do not miss the opportunity to take advantage of them" I_AM_A_SHOP: "I'm a shop" SIGNUP_FORM_TITLE: "SIGN UP" PASSWORDS_DO_NOT_MATCH: "The passwords do not match" SHOP_NAME_HAS_TO_BE_PROVIDED: "The name must be required" EMAIL_HAS_TO_BE_PROVIDED: "The email must be required" PASSWORD_HAS_TO_BE_PROVIDED: "The password must be required" EMAIL_ALREADY_EXISTS: "This email is in use, please you check another one" NO_SHOP_HAS_BEEN_FOUND: "Does not exist any shop with these credentials" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "The email and password must required for login" UNKNOWN_ERROR: "Unknown error" FOR_FREE: "We do not charge anything" GET_IN: "Enter and discover the deals" DONT_HESITATE: "Do not think twice" ACTIVE_DEALS: "active deals" RESERVED_DEALS: "reserved deals" ACTIVE_USERS: "active users" ACTIVE_SHOPS: "active shops" STEP_FIND: "Find" STEP_FIND_DESC: "Find out in the deals list one you like the most. There are thousands to choose, don't let yours go away" STEP_RESERVE: "Reserve" STEP_RESERVE_DESC: "Once chosen, you simply have to reserve it and you will be assigned a reserve number; it's important you don't lose it" STEP_REDEEM: "Redeem" STEP_REDEEM_DESC: "Go to the shop that offers the deal and show the shop assistant your reservation number. Once validated you will be able to redeem it" STEP_ENJOY: "Enjoy!" STEP_ENJOY_DESC: "With the deal redeemed and in your hands, it's time to enjoy it. So don't think any more about it and run to enjoy it!" MY_BUYS: "My buys" NO_BUYS: "You have not bought any deal yet" BUYED: "Buyed the " MY_RESERVES: "My reserves" NO_RESERVES: "You have not got any pending reserve" RESERVED: "Reserved the " NEARBY_DEALS: "Nearby deals" NO_NEAR_DEALS: "You have not got any nearby deal" MY_COMMENTS: "My comments" NO_COMMENTS: "You have not writed any comment yet" YOU_ARE_IN: "You are in " RESERVE_CODE: "Reserve code" #contact CONTACT_US: "Contact us" ADDRESS: "Address:" OUR_PHONE: "Phone:" NAME: "Name" NAME_PLACEHOLDER: "Enter your name" EMAIL_PLACEHOLDER: "Enter your email" PHONE: "Phone" PHONE_PLACEHOLDER: "Enter your phone" MESSAGE_PLACEHOLDER: "Enter your comments" SEND: "Send" # /profile MY_PERFIL: "My perfil" EMAIL: "Email" FIRSTNAME: "PI:NAME:<NAME>END_PI" LASTNAME: "PI:NAME:<NAME>END_PI" BIRTHDAY: "Birthday" RADIUS_DISTANCE: "Radius distance" METERS: "meters" SAVE: "Save" UPLOAD: "Upload image" CHANGE_IMAGE: "Change image" SAVING: "Saving..." UPLOADING: "Uploading..." RADIUS_DISTANCE_TOOLTIP: "Meter radius from your position that they find the deals" #deals DEALNAME_PLACEHOLDER: "Deal name..." SEARCH_BY: "Search by:" ALL_CATEGORIES: "All categories" ANY_PRICE: "Any price" #deal/:dealId RESERVE: "Reserve" COMMENTS: "Comments" DESCRIPTION: "Description" DESCRIPTION_PLACEHOLDER: "Description of the deal..." RATING: "Rating" COMMENT_200: "Comment has been added!" COMMENT_401: "You must login to leave a comment" COMMENT_404: "Unknown user" COMMENT_409: "Sorry, but you have already post a comment in this deal" COMMENT_422: "Remember that the rating and description are necessary for leave a comment" COMMENT_500: "It has been impossible to add your comment, please try again in a few minutes" ################################################################################ ################################################################################ $translateProvider.translations "es-ES", # / HOME: "Inicio" DEALS: "Ofertas" FIND: "Buscar" ABOUT: "Acerca de" CONTACT: "Contacto" WELCOME: "Bienvenido" PROFILE: "Perfil" SIGNOUT: "Cerrar sesión" SIGNUP: "Registrarse" SIGNIN: "Acceder" PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" REPEAT_PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" DONOT_WASTE_TIME: "No pierda más el tiempo" REGISTER_FOR_FREE: "Regístrese gratuitamente y empiece a aprovecharse" REGISTER_NOW: "Regístrese ahora" WHAT_WE_HAVE: "Lo que tenemos" DONOT_LOSE_CHANCE: "No pierda la oportunidad de aprovecharlas" I_AM_A_SHOP: "Soy empresa" SIGNUP_FORM_TITLE: "CREAR UNA CUENTA" PASSWORDS_DO_NOT_MATCH: "Las contraseñas suministradas no coinciden" SHOP_NAME_HAS_TO_BE_PROVIDED: "Debe proporcionar un nombre para el comercio" EMAIL_HAS_TO_BE_PROVIDED: "Debe proporcionar un email para el comercio" PASSWORD_HAS_TO_BE_PROVIDED: "Debe proporcionar una contraseña para el comercio" EMAIL_ALREADY_EXISTS: "Ya existe un comercio con ese email. Por favor, proporcione otro." NO_SHOP_HAS_BEEN_FOUND: "No se ha encontrado ningún comercio con los credenciales suministrados" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "Debe indicar una contraseña y un email para poder acceder" UNKNOWN_ERROR: "Error desconocido" FOR_FREE: "No cobramos nada" GET_IN: "Entre y descubra las ofertas" DONT_HESITATE: "No lo piense más" ACTIVE_DEALS: "ofertas activas" RESERVED_DEALS: "ofertas reservadas" ACTIVE_USERS: "usuarios activos" ACTIVE_SHOPS: "tiendas asociadas" STEP_FIND: "Busca" STEP_FIND_DESC: "Busca dentro de nuestra lista de ofertas la que más te guste. Hay miles entre las que elegir, no dejes que se escape la tuya" STEP_RESERVE: "Reserva" STEP_RESERVE_DESC: "Una vez elegida, simplemente tienes que reservarla y se te asignará un número de reserva; es muy importante que no lo pierdas" STEP_REDEEM: "Canjea" STEP_REDEEM_DESC: "Acércate a la tienda que ofrece la oferta y muéstrale al dependiente tu número de reserva. Una vez validado podrás canjearla" STEP_ENJOY: "¡Disfruta!" STEP_ENJOY_DESC: "Con la oferta ya canjeada y en tu poder, es hora de disfrutar de ella. Así que no lo pienses más y ¡corre a disfrutar de ella!" MY_BUYS: "Mis compras" NO_BUYS: "No has realizado ninguna compra" BUYED: "Comprado el " MY_RESERVES: "Mis reservas" NO_RESERVES: "No tienes ninguna reserva pendiente" RESERVED: "Reservado el " NEARBY_DEALS: "Ofertas cercanas" NO_NEAR_DEALS: "No hay ofertas cercanas" MY_COMMENTS: "Mis comentarios" NO_COMMENTS: "No tienes comentarios aún" YOU_ARE_IN: "Usted se encuentra en " RESERVE_CODE: "Codigo de reserva" #contact CONTACT_US: "Contacte con nosotros" ADDRESS: "Dirección:" OUR_PHONE: "Teléfono:" NAME: "PI:NAME:<NAME>END_PI" NAME_PLACEHOLDER: "Introduzca su nombre" EMAIL_PLACEHOLDER: "Introduzca su correo electrónico" PHONE: "Teléfono" PHONE_PLACEHOLDER: "Introduzca su teléfono" MESSAGE_PLACEHOLDER: "Introduzca su comentario" SEND: "Enviar" # / profile MY_PERFIL: "Mi perfil" EMAIL: "Correo electrónico" FIRSTNAME: "PI:NAME:<NAME>END_PI" LASTNAME: "PI:NAME:<NAME>END_PI" BIRTHDAY: "Fecha de nacimiento" RADIUS_DISTANCE: "Radio de detección" METERS: "metros" SAVE: "Guardar" UPLOAD: "Subir imagen" CHANGE_IMAGE: "Cambiar imagen" SAVING: "Guardando..." UPLOADING: "Subiendo..." RADIUS_DISTANCE_TOOLTIP: "Metros a la redonda, desde tu posición, en los que se buscarán ofertas" #deals DEALNAME_PLACEHOLDER: "Nombre de oferta..." SEARCH_BY: "Buscar por:" ALL_CATEGORIES: "Todas las categorías" ANY_PRICE: "Cualquier precio" # deal/:dealId RESERVE: "Reservar" COMMENTS: "ComentPI:NAME:<NAME>END_PI" DESCRIPTION: "Descripción" DESCRIPTION_PLACEHOLDER: "Descripción de la oferta..." RATING: "Puntuación" COMMENT_200: "¡El comentario ha sido añadido!" COMMENT_401: "Para dejar un comentario debe iniciar sesión" COMMENT_404: "Usuario desconocido" COMMENT_409: "Lo sentimos, usted ya comentó esta oferta" COMMENT_422: "Recuerde que son necesarios tanto una puntuación como un breve comentario" COMMENT_500: "Ha sido imposible añadir el comentario, por favor inténtelo de nuevo en unos minutos" $translateProvider.translations "eu", # / HOME: "Hasiera" DEALS: "Eskeintzak" FIND: "Aurkitu" ABOUT: "PI:NAME:<NAME>END_PI" CONTACT: "Kontaktua" WELCOME: "Ongi etorri" PROFILE: "Profila" SIGNOUT: "Irten" SIGNUP: "Kontua sortu" SIGNIN: "Sartu" PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" REPEAT_PASSWORD: "PI:PASSWORD:<PASSWORD>END_PI" DONOT_WASTE_TIME: "Denbora gehiagorik ez galdu" REGISTER_FOR_FREE: "Sortu kontua dohainik eta hasi erabiltzan" REGISTER_NOW: "Kontua sortu" WHAT_WE_HAVE: "Bertan aurkituko duzuna" DONOT_LOSE_CHANCE: "Ez galdu onura hauek izateko aukera" I_AM_A_SHOP: "Denda naiz" SIGNUP_FORM_TITLE: "KONTUA SORTU" PASSWORDS_DO_NOT_MATCH: "PI:PASSWORD:<PASSWORD>END_PI" SHOP_NAME_HAS_TO_BE_PROVIDED: "Dendaren izena sartu behar duzu" EMAIL_HAS_TO_BE_PROVIDED: "Dendarendako email bat sartu behar duzu" PASSWORD_HAS_TO_BE_PROVIDED: "Dendaren pasahitza sartu behar duzu" EMAIL_ALREADY_EXISTS: "Bada helbide hau erabiltzen ari den denda. Mesedez, sartu beste bat." NO_SHOP_HAS_BEEN_FOUND: "Ez da dendarik aurkitu sartutako datuekin" PASSWORD_AND_EMAIL_HAVE_TO_BE_PROVIDED: "Helbide eta pasahitz bat beharrezkoa da sartzeko" UNKNOWN_ERROR: "Akats ezezaguna" FOR_FREE: "Ez dugu ezer kobratzen" GET_IN: "Sartu eta eskaintzez gozatu" DONT_HESITATE: "Ez pentsatu gehiago" ACTIVE_DEALS: "uskaintzak" RESERVED_DEALS: "eskaintza erreserba" ACTIVE_USERS: "erabiltzaile" ACTIVE_SHOPS: "denda" STEP_FIND: "Aurkitu" STEP_FIND_DESC: "Gure eskaintzen artean gehien gustuko duzuna bilatu. Hamaika eskaintza ditugu, lortu zurea." STEP_RESERVE: "Erreserba" STEP_RESERVE_DESC: "Behin aukeratutakoan, erreserba egin eta zenbaki bat egokituko zaizu" STEP_REDEEM: "Trukatu" STEP_REDEEM_DESC: "Gerturatu eskaintzaren dendara eta erakutsi zure kodea. Baieztatu ostean trukatu ahal izango duzu" STEP_ENJOY: "Gozatu!" STEP_ENJOY_DESC: "Behin eskaintza eskuratuta, gozatzen hasi zaitezke. Beraz, ez gehiago pentsatu eta arineketan joan zaitez!" MY_BUYS: "PI:NAME:<NAME>END_PI" NO_BUYS: "Ez duzu erosketarik egin" BUYED: "Erosketa eguna: " MY_RESERVES: "Nire erreserbak" NO_RESERVES: "Ez duzu erreserbarik trukatzeko" RESERVED: "Erreserbatutako eguna: " NEARBY_DEALS: "Gertuko eskaintzak" NO_NEAR_DEALS: "Ez dago gertuko eskaintzarik" MY_COMMENTS: "PI:NAME:<NAME>END_PIuzkinak" NO_COMMENTS: "Ez duzu iruzkinik idatzi" YOU_ARE_IN: "Zure kokapena: " RESERVE_CODE: "Erreserba kodea" #contact CONTACT_US: "PI:NAME:<NAME>END_PI" ADDRESS: "Helbidea:" OUR_PHONE: "Telefonoa:" NAME: "PI:NAME:<NAME>END_PI" NAME_PLACEHOLDER: "PI:NAME:<NAME>END_PI" EMAIL_PLACEHOLDER: "PI:NAME:<NAME>END_PI" PHONE: "Telefonoa" PHONE_PLACEHOLDER: "Sartu zure telefonoa" MESSAGE_PLACEHOLDER: "Idatzi zure iruzkina" SEND: "Bidali" # / profile MY_PERFIL: "PI:NAME:<NAME>END_PI" EMAIL: "Helbide elektronikoa" FIRSTNAME: "PI:NAME:<NAME>END_PI" LASTNAME: "PI:NAME:<NAME>END_PI" BIRTHDAY: "Jaiotze data" RADIUS_DISTANCE: "Kokapen eremua" METERS: "metro" SAVE: "Gorde" UPLOAD: "Irudia igo" CHANGE_IMAGE: "Irudia aldatu" SAVING: "Gordetzen..." UPLOADING: "Igotzen..." RADIUS_DISTANCE_TOOLTIP: "Eskaintzak aurkitzeko distantzia eremua" #deals DEALNAME_PLACEHOLDER: "PI:NAME:<NAME>END_PIena..." SEARCH_BY: "PI:NAME:<NAME>END_PI:" ALL_CATEGORIES: "Kategoria guztiak" ANY_PRICE: "Edozein prezio" # deal/:dealId RESERVE: "ErPI:NAME:<NAME>END_PI" COMMENTS: "PI:NAME:<NAME>END_PI" DESCRIPTION: "Deskribapena" DESCRIPTION_PLACEHOLDER: "Eskeintzaren deskribapena..." RATING: "Puntuazioa" COMMENT_200: "Iruzkina gehitua izan da!" COMMENT_401: "Iruzkina idazteko saioa hasi beharra duzu" COMMENT_404: "Erabiltzaile ezezaguna" COMMENT_409: "Barkatu, eskaintza hau komentatu duzu jada" COMMENT_422: "Bai puntuazioa, bai deskribapena beharrezkoak dira" COMMENT_500: "Iruzkina gehitzea ezinezkoa izan da, mesedez saia zaitze hemenidk minutu batzuetara" $translateProvider.preferredLanguage (if navigator.language is "es" then "es-ES" else navigator.language) ]
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 197, "score": 0.9998757243156433, "start": 180, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.com\n\nThis softwa", "end": 213, "score": 0.9999293088912964, "start": 200, "tag": "EMAIL", "value": "ben@pxljs.com" } ]
examples/helloworld.coffee
OniDaito/pxljs
1
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> white = new PXL.Colour.RGBA.WHITE() v0 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(-1,-1,0) v1 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3( 0, 1,0) v2 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3( 1,-1,0) t = new PXL.Geometry.Triangle v0,v1,v2 q = new PXL.Geometry.Quad() q.vertices[0].c = new PXL.Colour.RGBA 1.0, 0.0, 0.0, 1.0 q.vertices[1].c = new PXL.Colour.RGBA 0.0, 1.0, 0.0, 1.0 q.vertices[2].c = new PXL.Colour.RGBA 0.0, 0.0, 1.0, 1.0 @n0 = new PXL.Node t @n1 = new PXL.Node q @n2 = new PXL.Node t @n0.add @n2 @n0.matrix.translate new PXL.Math.Vec3(-1.1,0,0) @n1.matrix.translate new PXL.Math.Vec3(1.1,0,0) @n2.matrix.scale new PXL.Math.Vec3(0.5,0.5,0.5) @n2.matrix.translate new PXL.Math.Vec3(0.0,1.5,0.0) @c = new PXL.Camera.PerspCamera() uniformMaterial = new PXL.Material.BasicColourMaterial white @n0.add uniformMaterial vertexMaterial = new PXL.Material.VertexColourMaterial() @n1.add vertexMaterial @topnode = new PXL.Node @topnode.add @n0 @topnode.add @n1 @topnode.add @c uber = new PXL.GL.UberShader @topnode @topnode.add uber draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @topnode.draw() params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
6364
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> white = new PXL.Colour.RGBA.WHITE() v0 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(-1,-1,0) v1 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3( 0, 1,0) v2 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3( 1,-1,0) t = new PXL.Geometry.Triangle v0,v1,v2 q = new PXL.Geometry.Quad() q.vertices[0].c = new PXL.Colour.RGBA 1.0, 0.0, 0.0, 1.0 q.vertices[1].c = new PXL.Colour.RGBA 0.0, 1.0, 0.0, 1.0 q.vertices[2].c = new PXL.Colour.RGBA 0.0, 0.0, 1.0, 1.0 @n0 = new PXL.Node t @n1 = new PXL.Node q @n2 = new PXL.Node t @n0.add @n2 @n0.matrix.translate new PXL.Math.Vec3(-1.1,0,0) @n1.matrix.translate new PXL.Math.Vec3(1.1,0,0) @n2.matrix.scale new PXL.Math.Vec3(0.5,0.5,0.5) @n2.matrix.translate new PXL.Math.Vec3(0.0,1.5,0.0) @c = new PXL.Camera.PerspCamera() uniformMaterial = new PXL.Material.BasicColourMaterial white @n0.add uniformMaterial vertexMaterial = new PXL.Material.VertexColourMaterial() @n1.add vertexMaterial @topnode = new PXL.Node @topnode.add @n0 @topnode.add @n1 @topnode.add @c uber = new PXL.GL.UberShader @topnode @topnode.add uber draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @topnode.draw() params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
true
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> white = new PXL.Colour.RGBA.WHITE() v0 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(-1,-1,0) v1 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3( 0, 1,0) v2 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3( 1,-1,0) t = new PXL.Geometry.Triangle v0,v1,v2 q = new PXL.Geometry.Quad() q.vertices[0].c = new PXL.Colour.RGBA 1.0, 0.0, 0.0, 1.0 q.vertices[1].c = new PXL.Colour.RGBA 0.0, 1.0, 0.0, 1.0 q.vertices[2].c = new PXL.Colour.RGBA 0.0, 0.0, 1.0, 1.0 @n0 = new PXL.Node t @n1 = new PXL.Node q @n2 = new PXL.Node t @n0.add @n2 @n0.matrix.translate new PXL.Math.Vec3(-1.1,0,0) @n1.matrix.translate new PXL.Math.Vec3(1.1,0,0) @n2.matrix.scale new PXL.Math.Vec3(0.5,0.5,0.5) @n2.matrix.translate new PXL.Math.Vec3(0.0,1.5,0.0) @c = new PXL.Camera.PerspCamera() uniformMaterial = new PXL.Material.BasicColourMaterial white @n0.add uniformMaterial vertexMaterial = new PXL.Material.VertexColourMaterial() @n1.add vertexMaterial @topnode = new PXL.Node @topnode.add @n0 @topnode.add @n1 @topnode.add @c uber = new PXL.GL.UberShader @topnode @topnode.add uber draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @topnode.draw() params = canvas : 'webgl-canvas' context : @ init : init debug : true draw : draw cgl = new PXL.App params
[ { "context": " dieVals.push [@key, @node.innerHTML] if @key is 'item.id'\n\n context = new Batman\n helpers.render source,", "end": 457, "score": 0.8650086522102356, "start": 450, "tag": "KEY", "value": "item.id" } ]
tests/batman/view/iterator_binding_test.coffee
Shipow/batman
1
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View iterator bindings' asyncTest 'it should destroy nodes and their bindings if items have been removed before render is complete', 1, -> source = '<div data-foreach-item="items"><span data-bind="item.id"></span></div>' dieVals = [] Batman.DOM.AbstractBinding::die = -> dieVals.push [@key, @node.innerHTML] if @key is 'item.id' context = new Batman helpers.render source, context , (node) -> context.set 'items', new Batman.Set({id: 4}, {id: 5}, {id: 6}) context.set 'items', new Batman.Set({id: 7}, {id: 8}, {id: 9}) delay -> deepEqual dieVals, [['item.id', '4'], ['item.id', '5'], ['item.id', '6']] QUnit.start()
152289
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View iterator bindings' asyncTest 'it should destroy nodes and their bindings if items have been removed before render is complete', 1, -> source = '<div data-foreach-item="items"><span data-bind="item.id"></span></div>' dieVals = [] Batman.DOM.AbstractBinding::die = -> dieVals.push [@key, @node.innerHTML] if @key is '<KEY>' context = new Batman helpers.render source, context , (node) -> context.set 'items', new Batman.Set({id: 4}, {id: 5}, {id: 6}) context.set 'items', new Batman.Set({id: 7}, {id: 8}, {id: 9}) delay -> deepEqual dieVals, [['item.id', '4'], ['item.id', '5'], ['item.id', '6']] QUnit.start()
true
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View iterator bindings' asyncTest 'it should destroy nodes and their bindings if items have been removed before render is complete', 1, -> source = '<div data-foreach-item="items"><span data-bind="item.id"></span></div>' dieVals = [] Batman.DOM.AbstractBinding::die = -> dieVals.push [@key, @node.innerHTML] if @key is 'PI:KEY:<KEY>END_PI' context = new Batman helpers.render source, context , (node) -> context.set 'items', new Batman.Set({id: 4}, {id: 5}, {id: 6}) context.set 'items', new Batman.Set({id: 7}, {id: 8}, {id: 9}) delay -> deepEqual dieVals, [['item.id', '4'], ['item.id', '5'], ['item.id', '6']] QUnit.start()
[ { "context": " -> @_searches_path()\n\n data:\n i18n_key: \"ShowVolumes\"\n\n onconfig: ->\n @set \"pending\", true\n\n ", "end": 374, "score": 0.7768822908401489, "start": 363, "tag": "KEY", "value": "ShowVolumes" } ]
app/assets/javascripts/app/components/ShowVolumes/index.js.coffee
ubpb/katalog
0
#= require app/Component do(app = (window.app ?= {})) -> app.components.ShowVolumes = app.Component.extend computed: api_v1_scope_searches_path: -> @_path_helper_factory("/api/v1/scopes/:scope_id/searches") scope_searches_path: -> @_path_helper_factory("/:scope_id/searches") volume_path: -> @_searches_path() data: i18n_key: "ShowVolumes" onconfig: -> @set "pending", true oninit: -> if @get("superorder_id")? $.ajax url: @_api_searches_path(), type: "GET" success: (search_result) => @set("show_volumes_link", search_result.hits.length > 0).then => @set "pending", false else @set "pending", false template: """ {{#if pending}} <span class="state loading"> <i class="fa fa-spinner fa-spin" /> </span> {{else}} {{#if show_volumes_link}} <a href="{{volume_path}}">{{t(".show_volumes")}}</a> {{else}} – {{/if}} {{/if}} """ _api_searches_path: (options = {}) -> options.facets ?= false options.search_request ?= @_superorder_search_request() @get("api_v1_scope_searches_path")(@get("scope.id"), options) _searches_path: (options = {}) -> options.search_request ?= @_superorder_search_request() @get("scope_searches_path")(@get("scope.id"), options) _superorder_search_request: (superorder_id = @get("superorder_id")) -> queries: [ type: "query_string" query: superorder_id fields: ["superorder"] ] sort: [{"field":"volume_count_sort2","order":"asc"}]
21906
#= require app/Component do(app = (window.app ?= {})) -> app.components.ShowVolumes = app.Component.extend computed: api_v1_scope_searches_path: -> @_path_helper_factory("/api/v1/scopes/:scope_id/searches") scope_searches_path: -> @_path_helper_factory("/:scope_id/searches") volume_path: -> @_searches_path() data: i18n_key: "<KEY>" onconfig: -> @set "pending", true oninit: -> if @get("superorder_id")? $.ajax url: @_api_searches_path(), type: "GET" success: (search_result) => @set("show_volumes_link", search_result.hits.length > 0).then => @set "pending", false else @set "pending", false template: """ {{#if pending}} <span class="state loading"> <i class="fa fa-spinner fa-spin" /> </span> {{else}} {{#if show_volumes_link}} <a href="{{volume_path}}">{{t(".show_volumes")}}</a> {{else}} – {{/if}} {{/if}} """ _api_searches_path: (options = {}) -> options.facets ?= false options.search_request ?= @_superorder_search_request() @get("api_v1_scope_searches_path")(@get("scope.id"), options) _searches_path: (options = {}) -> options.search_request ?= @_superorder_search_request() @get("scope_searches_path")(@get("scope.id"), options) _superorder_search_request: (superorder_id = @get("superorder_id")) -> queries: [ type: "query_string" query: superorder_id fields: ["superorder"] ] sort: [{"field":"volume_count_sort2","order":"asc"}]
true
#= require app/Component do(app = (window.app ?= {})) -> app.components.ShowVolumes = app.Component.extend computed: api_v1_scope_searches_path: -> @_path_helper_factory("/api/v1/scopes/:scope_id/searches") scope_searches_path: -> @_path_helper_factory("/:scope_id/searches") volume_path: -> @_searches_path() data: i18n_key: "PI:KEY:<KEY>END_PI" onconfig: -> @set "pending", true oninit: -> if @get("superorder_id")? $.ajax url: @_api_searches_path(), type: "GET" success: (search_result) => @set("show_volumes_link", search_result.hits.length > 0).then => @set "pending", false else @set "pending", false template: """ {{#if pending}} <span class="state loading"> <i class="fa fa-spinner fa-spin" /> </span> {{else}} {{#if show_volumes_link}} <a href="{{volume_path}}">{{t(".show_volumes")}}</a> {{else}} – {{/if}} {{/if}} """ _api_searches_path: (options = {}) -> options.facets ?= false options.search_request ?= @_superorder_search_request() @get("api_v1_scope_searches_path")(@get("scope.id"), options) _searches_path: (options = {}) -> options.search_request ?= @_superorder_search_request() @get("scope_searches_path")(@get("scope.id"), options) _superorder_search_request: (superorder_id = @get("superorder_id")) -> queries: [ type: "query_string" query: superorder_id fields: ["superorder"] ] sort: [{"field":"volume_count_sort2","order":"asc"}]
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9988716244697571, "start": 12, "tag": "NAME", "value": "Joyent" } ]
lib/_debugger.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Setup input/output streams # # Parser/Serializer for V8 debugger protocol # http://code.google.com/p/v8/wiki/DebuggerProtocol # # Usage: # p = new Protocol(); # # p.onResponse = function(res) { # // do stuff with response from V8 # }; # # socket.setEncoding('utf8'); # socket.on('data', function(s) { # // Pass strings into the protocol # p.execute(s); # }); # # Protocol = -> @_newRes() return # pass thru # JSON parse body? # Done! Client = -> net.Stream.call this protocol = @protocol = new Protocol(this) @_reqCallbacks = [] socket = this @currentFrame = NO_FRAME @currentSourceLine = -1 @handles = {} @scripts = {} @breakpoints = [] # Note that 'Protocol' requires strings instead of Buffers. socket.setEncoding "utf8" socket.on "data", (d) -> protocol.execute d return protocol.onResponse = @_onResponse.bind(this) return # Request a list of scripts for our own storage. # ??? # This event is not used anywhere right now, perhaps somewhere in the # future? # TODO: We have a cache of handle's we've already seen in this.handles # This can be used if we're careful. # This is like reqEval, except it will look up the expression in each of the # scopes associated with the current frame. # Only need to eval in global scope. # Otherwise we need to get the current frame to see which scopes it has. # ?? # Finds the first scope in the array in which the expression evals. # Just eval in global scope. # reqBacktrace(cb) # TODO: from, to, bottom # reqSetExceptionBreak(type, cb) # TODO: from, to, bottom # Returns an array of objects like this: # # { handle: 11, # type: 'script', # name: 'node.js', # id: 14, # lineOffset: 0, # columnOffset: 0, # lineCount: 562, # sourceStart: '(function(process) {\n\n ', # sourceLength: 15939, # scriptType: 2, # compilationType: 0, # context: { ref: 10 }, # text: 'node.js (lines: 562)' } # # client.next(1, cb); # The handle looks something like this: # { handle: 8, # type: 'object', # className: 'Object', # constructorFunction: { ref: 9 }, # protoObject: { ref: 4 }, # prototypeObject: { ref: 2 }, # properties: [ { name: 'hello', propertyType: 1, ref: 10 } ], # text: '#<an Object>' } # For now ignore the className and constructor and prototype. # TJ's method of object inspection would probably be good for this: # https://groups.google.com/forum/?pli=1#!topic/nodejs-dev/4gkWBOimiOg # Skip the 'length' property. # looks like this: # { type: 'frame', # index: 0, # receiver: { ref: 1 }, # func: { ref: 0 }, # script: { ref: 7 }, # constructCall: false, # atReturn: false, # debuggerFrame: false, # arguments: [], # locals: [], # position: 160, # line: 7, # column: 2, # sourceLineText: ' debugger;', # scopes: [ { type: 1, index: 0 }, { type: 0, index: 1 } ], # text: '#00 blah() /home/ryan/projects/node/test-debug.js l...' } SourceUnderline = (sourceText, position, repl) -> return "" unless sourceText head = sourceText.slice(0, position) tail = sourceText.slice(position) # Colourize char if stdout supports colours tail = tail.replace(/(.+?)([^\w]|$)/, "\u001b[32m$1\u001b[39m$2") if repl.useColors # Return source line with coloured char at `position` [ head tail ].join "" SourceInfo = (body) -> result = (if body.exception then "exception in " else "break in ") if body.script if body.script.name name = body.script.name dir = path.resolve() + "/" # Change path to relative, if possible name = name.slice(dir.length) if name.indexOf(dir) is 0 result += name else result += "[unnamed]" result += ":" result += body.sourceLine + 1 result += "\n" + body.exception.text if body.exception result # This class is the repl-enabled debugger interface which is invoked on # "node debug" Interface = (stdin, stdout, args) -> # Two eval modes are available: controlEval and debugEval # But controlEval is used by default # Emulate Ctrl+C if we're emulating terminal # Do not print useless warning # Kill child process when main process dies # Handle all possible exits defineProperty = (key, protoKey) -> # Check arity fn = proto[protoKey].bind(self) if proto[protoKey].length is 0 Object.defineProperty self.repl.context, key, get: fn enumerable: true configurable: false else self.repl.context[key] = fn return self = this @stdin = stdin @stdout = stdout @args = args opts = prompt: "debug> " input: @stdin output: @stdout eval: @controlEval.bind(this) useGlobal: false ignoreUndefined: true if parseInt(process.env["NODE_NO_READLINE"], 10) opts.terminal = false else if parseInt(process.env["NODE_FORCE_READLINE"], 10) opts.terminal = true unless @stdout.isTTY process.on "SIGINT", -> self.repl.rli.emit "SIGINT" return opts.useColors = false if parseInt(process.env["NODE_DISABLE_COLORS"], 10) @repl = repl.start(opts) repl._builtinLibs.splice repl._builtinLibs.indexOf("repl"), 1 @repl.on "exit", -> process.exit 0 return process.on "exit", @killChild.bind(this) process.once "SIGTERM", process.exit.bind(process, 0) process.once "SIGHUP", process.exit.bind(process, 0) proto = Interface:: ignored = [ "pause" "resume" "exitRepl" "handleBreak" "requireConnection" "killChild" "trySpawn" "controlEval" "debugEval" "print" "childPrint" "clearline" ] shortcut = run: "r" cont: "c" next: "n" step: "s" out: "o" backtrace: "bt" setBreakpoint: "sb" clearBreakpoint: "cb" pause_: "pause" # Copy all prototype methods in repl context # Setup them as getters if possible for i of proto if Object::hasOwnProperty.call(proto, i) and ignored.indexOf(i) is -1 defineProperty i, i defineProperty shortcut[i], i if shortcut[i] @killed = false @waiting = null @paused = 0 @context = @repl.context @history = debug: [] control: [] @breakpoints = [] @_watchers = [] # Run script automatically @pause() # XXX Need to figure out why we need this delay setTimeout (-> self.run -> self.resume() return return ), 10 return # Stream control # Clear current line # Print text to output stream # Format and print text from child process # Errors formatting # Debugger's `break` event handler # Save execution context's data # Print break data # Show watchers' values # And list source # Internal method for checking connection state # Evals # Used for debugger's commands evaluation and execution # Repeat last command if empty line are going to be evaluated # Repl should not ask for next command # if current one was asynchronous. # Add a callback for asynchronous command # (it will be automatically invoked by .resume() method # Used for debugger's remote evaluation (`repl`) commands # Repl asked for scope variables # Request remote evaluation globally or in current frame # Request object by handles (and it's sub-properties) # Utils # Adds spaces and prefix to number # maxN is a maximum number we should have space for leftPad = (n, prefix, maxN) -> s = n.toString() nchars = Math.max(2, String(maxN).length) + 1 nspaces = nchars - s.length - 1 i = 0 while i < nspaces prefix += " " i++ prefix + s "use strict" util = require("util") path = require("path") net = require("net") vm = require("vm") module = require("module") repl = module.requireRepl() inherits = util.inherits assert = require("assert") spawn = require("child_process").spawn exports.start = (argv, stdin, stdout) -> argv or (argv = process.argv.slice(2)) if argv.length < 1 console.error "Usage: node debug script.js" process.exit 1 stdin = stdin or process.stdin stdout = stdout or process.stdout args = ["--debug-brk"].concat(argv) interface_ = new Interface(stdin, stdout, args) stdin.resume() process.on "uncaughtException", (e) -> console.error "There was an internal error in Node's debugger. " + "Please report this bug." console.error e.message console.error e.stack interface_.child.kill() if interface_.child process.exit 1 return return exports.port = 5858 exports.Protocol = Protocol Protocol::_newRes = (raw) -> @res = raw: raw or "" headers: {} @state = "headers" @reqSeq = 1 @execute "" return Protocol::execute = (d) -> res = @res res.raw += d switch @state when "headers" endHeaderIndex = res.raw.indexOf("\r\n\r\n") break if endHeaderIndex < 0 rawHeader = res.raw.slice(0, endHeaderIndex) endHeaderByteIndex = Buffer.byteLength(rawHeader, "utf8") lines = rawHeader.split("\r\n") i = 0 while i < lines.length kv = lines[i].split(/: +/) res.headers[kv[0]] = kv[1] i++ @contentLength = +res.headers["Content-Length"] @bodyStartByteIndex = endHeaderByteIndex + 4 @state = "body" len = Buffer.byteLength(res.raw, "utf8") break if len - @bodyStartByteIndex < @contentLength when "body" resRawByteLength = Buffer.byteLength(res.raw, "utf8") if resRawByteLength - @bodyStartByteIndex >= @contentLength buf = new Buffer(resRawByteLength) buf.write res.raw, 0, resRawByteLength, "utf8" res.body = buf.slice(@bodyStartByteIndex, @bodyStartByteIndex + @contentLength).toString("utf8") res.body = (if res.body.length then JSON.parse(res.body) else {}) @onResponse res @_newRes buf.slice(@bodyStartByteIndex + @contentLength).toString("utf8") else throw new Error("Unknown state") return Protocol::serialize = (req) -> req.type = "request" req.seq = @reqSeq++ json = JSON.stringify(req) "Content-Length: " + Buffer.byteLength(json, "utf8") + "\r\n\r\n" + json NO_FRAME = -1 inherits Client, net.Stream exports.Client = Client Client::_addHandle = (desc) -> return if not util.isObject(desc) or not util.isNumber(desc.handle) @handles[desc.handle] = desc @_addScript desc if desc.type is "script" return natives = process.binding("natives") Client::_addScript = (desc) -> @scripts[desc.id] = desc desc.isNative = (desc.name.replace(".js", "") of natives) or desc.name is "node.js" if desc.name return Client::_removeScript = (desc) -> @scripts[desc.id] = `undefined` return Client::_onResponse = (res) -> cb = undefined index = -1 @_reqCallbacks.some (fn, i) -> if fn.request_seq is res.body.request_seq cb = fn index = i true self = this handled = false if res.headers.Type is "connect" self.reqScripts() self.emit "ready" handled = true else if res.body and res.body.event is "break" @emit "break", res.body handled = true else if res.body and res.body.event is "exception" @emit "exception", res.body handled = true else if res.body and res.body.event is "afterCompile" @_addHandle res.body.body.script handled = true else if res.body and res.body.event is "scriptCollected" @_removeScript res.body.body.script handled = true else handled = true if res.body and res.body.event is "compileError" if cb @_reqCallbacks.splice index, 1 handled = true err = res.success is false and (res.message or true) or res.body.success is false and (res.body.message or true) cb err, res.body and res.body.body or res.body, res @emit "unhandledResponse", res.body unless handled return Client::req = (req, cb) -> @write @protocol.serialize(req) cb.request_seq = req.seq @_reqCallbacks.push cb return Client::reqVersion = (cb) -> cb = cb or -> @req command: "version" , (err, body, res) -> return cb(err) if err cb null, res.body.body.V8Version, res.body.running return return Client::reqLookup = (refs, cb) -> self = this req = command: "lookup" arguments: handles: refs cb = cb or -> @req req, (err, res) -> return cb(err) if err for ref of res self._addHandle res[ref] if util.isObject(res[ref]) cb null, res return return Client::reqScopes = (cb) -> self = this req = command: "scopes" arguments: {} cb = cb or -> @req req, (err, res) -> return cb(err) if err refs = res.scopes.map((scope) -> scope.object.ref ) self.reqLookup refs, (err, res) -> return cb(err) if err globals = Object.keys(res).map((key) -> res[key].properties.map (prop) -> prop.name ) cb null, globals.reverse() return return return Client::reqEval = (expression, cb) -> self = this if @currentFrame is NO_FRAME @reqFrameEval expression, NO_FRAME, cb return cb = cb or -> @reqBacktrace (err, bt) -> return cb(null, {}) if err or not bt.frames frame = bt.frames[self.currentFrame] evalFrames = frame.scopes.map((s) -> return unless s x = bt.frames[s.index] return unless x x.index ) self._reqFramesEval expression, evalFrames, cb return return Client::_reqFramesEval = (expression, evalFrames, cb) -> if evalFrames.length is 0 @reqFrameEval expression, NO_FRAME, cb return self = this i = evalFrames.shift() cb = cb or -> @reqFrameEval expression, i, (err, res) -> return cb(null, res) unless err self._reqFramesEval expression, evalFrames, cb return return Client::reqFrameEval = (expression, frame, cb) -> self = this req = command: "evaluate" arguments: expression: expression if frame is NO_FRAME req.arguments.global = true else req.arguments.frame = frame cb = cb or -> @req req, (err, res) -> self._addHandle res unless err cb err, res return return Client::reqBacktrace = (cb) -> @req command: "backtrace" arguments: inlineRefs: true , cb return Client::reqSetExceptionBreak = (type, cb) -> @req command: "setexceptionbreak" arguments: type: type enabled: true , cb return Client::reqScripts = (cb) -> self = this cb = cb or -> @req command: "scripts" , (err, res) -> return cb(err) if err i = 0 while i < res.length self._addHandle res[i] i++ cb null return return Client::reqContinue = (cb) -> @currentFrame = NO_FRAME @req command: "continue" , cb return Client::listbreakpoints = (cb) -> @req command: "listbreakpoints" , cb return Client::setBreakpoint = (req, cb) -> req = command: "setbreakpoint" arguments: req @req req, cb return Client::clearBreakpoint = (req, cb) -> req = command: "clearbreakpoint" arguments: req @req req, cb return Client::reqSource = (from, to, cb) -> req = command: "source" fromLine: from toLine: to @req req, cb return Client::step = (action, count, cb) -> req = command: "continue" arguments: stepaction: action stepcount: count @currentFrame = NO_FRAME @req req, cb return Client::mirrorObject = (handle, depth, cb) -> self = this val = undefined if handle.type is "object" propertyRefs = handle.properties.map((p) -> p.ref ) cb = cb or -> @reqLookup propertyRefs, (err, res) -> waitForOthers = -> if --waiting is 0 and cb keyValues.forEach (kv) -> mirror[kv.name] = kv.value return cb null, mirror return if err console.error "problem with reqLookup" cb null, handle return mirror = undefined waiting = 1 if handle.className is "Array" mirror = [] else if handle.className is "Date" mirror = new Date(handle.value) else mirror = {} keyValues = [] handle.properties.forEach (prop, i) -> value = res[prop.ref] mirrorValue = undefined if value mirrorValue = (if value.value then value.value else value.text) else mirrorValue = "[?]" return if util.isArray(mirror) and not util.isNumber(prop.name) keyValues[i] = name: prop.name value: mirrorValue if value and value.handle and depth > 0 waiting++ self.mirrorObject value, depth - 1, (err, result) -> keyValues[i].value = result unless err waitForOthers() return return waitForOthers() return return else if handle.type is "function" val = -> else if handle.type is "null" val = null else unless util.isUndefined(handle.value) val = handle.value else if handle.type is "undefined" val = `undefined` else val = handle process.nextTick -> cb null, val return return Client::fullTrace = (cb) -> self = this cb = cb or -> @reqBacktrace (err, trace) -> return cb(err) if err return cb(Error("No frames")) if trace.totalFrames <= 0 refs = [] i = 0 while i < trace.frames.length frame = trace.frames[i] refs.push frame.script.ref refs.push frame.func.ref refs.push frame.receiver.ref i++ self.reqLookup refs, (err, res) -> return cb(err) if err i = 0 while i < trace.frames.length frame = trace.frames[i] frame.script = res[frame.script.ref] frame.func = res[frame.func.ref] frame.receiver = res[frame.receiver.ref] i++ cb null, trace return return return commands = [ [ "run (r)" "cont (c)" "next (n)" "step (s)" "out (o)" "backtrace (bt)" "setBreakpoint (sb)" "clearBreakpoint (cb)" ] [ "watch" "unwatch" "watchers" "repl" "restart" "kill" "list" "scripts" "breakOnException" "breakpoints" "version" ] ] helpMessage = "Commands: " + commands.map((group) -> group.join ", " ).join(",\n") Interface::pause = -> return this if @killed or @paused++ > 0 @repl.rli.pause() @stdin.pause() this Interface::resume = (silent) -> return this if @killed or @paused is 0 or --@paused isnt 0 @repl.rli.resume() @repl.displayPrompt() if silent isnt true @stdin.resume() if @waiting @waiting() @waiting = null this Interface::clearline = -> if @stdout.isTTY @stdout.cursorTo 0 @stdout.clearLine 1 else @stdout.write "\b" return Interface::print = (text, oneline) -> return if @killed @clearline() @stdout.write (if util.isString(text) then text else util.inspect(text)) @stdout.write "\n" if oneline isnt true return Interface::childPrint = (text) -> @print text.toString().split(/\r\n|\r|\n/g).filter((chunk) -> chunk ).map((chunk) -> "< " + chunk ).join("\n") @repl.displayPrompt true return Interface::error = (text) -> @print text @resume() return Interface::handleBreak = (r) -> self = this @pause() @client.currentSourceLine = r.sourceLine @client.currentSourceLineText = r.sourceLineText @client.currentSourceColumn = r.sourceColumn @client.currentFrame = 0 @client.currentScript = r.script and r.script.name @print SourceInfo(r) @watchers true, (err) -> return self.error(err) if err self.list 2 self.resume true return return Interface::requireConnection = -> unless @client @error "App isn't running... Try `run` instead" return false true Interface::controlEval = (code, context, filename, callback) -> try code = @repl.rli.history[0] + "\n" if code is "\n" if @repl.rli.history and @repl.rli.history.length > 0 result = vm.runInContext(code, context, filename) return callback(null, result) if @paused is 0 @waiting = -> callback null, result return catch e callback e return Interface::debugEval = (code, context, filename, callback) -> return unless @requireConnection() self = this client = @client if code is ".scope" client.reqScopes callback return frame = (if client.currentFrame is NO_FRAME then frame else `undefined`) self.pause() client.reqFrameEval code, frame, (err, res) -> if err callback err self.resume true return client.mirrorObject res, 3, (err, mirror) -> callback null, mirror self.resume true return return return # Commands # Print help message Interface::help = -> @print helpMessage return # Run script Interface::run = -> callback = arguments[0] if @child @error "App is already running... Try `restart` instead" callback and callback(true) else @trySpawn callback return # Restart script Interface::restart = -> return unless @requireConnection() self = this self.pause() self.killChild() # XXX need to wait a little bit for the restart to work? setTimeout (-> self.trySpawn() self.resume() return ), 1000 return # Print version Interface::version = -> return unless @requireConnection() self = this @pause() @client.reqVersion (err, v) -> if err self.error err else self.print v self.resume() return return # List source code Interface::list = (delta) -> return unless @requireConnection() delta or (delta = 5) self = this client = @client from = client.currentSourceLine - delta + 1 to = client.currentSourceLine + delta + 1 self.pause() client.reqSource from, to, (err, res) -> if err or not res self.error "You can't list source code right now" self.resume() return lines = res.source.split("\n") i = 0 while i < lines.length lineno = res.fromLine + i + 1 continue if lineno < from or lineno > to current = lineno is 1 + client.currentSourceLine breakpoint = client.breakpoints.some((bp) -> (bp.scriptReq is client.currentScript or bp.script is client.currentScript) and bp.line is lineno ) if lineno is 1 # The first line needs to have the module wrapper filtered out of # it. wrapper = module.wrapper[0] lines[i] = lines[i].slice(wrapper.length) client.currentSourceColumn -= wrapper.length # Highlight executing statement line = undefined if current line = SourceUnderline(lines[i], client.currentSourceColumn, self.repl) else line = lines[i] prefixChar = " " if current prefixChar = ">" else prefixChar = "*" if breakpoint self.print leftPad(lineno, prefixChar, to) + " " + line i++ self.resume() return return # Print backtrace Interface::backtrace = -> return unless @requireConnection() self = this client = @client self.pause() client.fullTrace (err, bt) -> if err self.error "Can't request backtrace now" self.resume() return if bt.totalFrames is 0 self.print "(empty stack)" else trace = [] firstFrameNative = bt.frames[0].script.isNative i = 0 while i < bt.frames.length frame = bt.frames[i] break if not firstFrameNative and frame.script.isNative text = "#" + i + " " text += frame.func.inferredName + " " if frame.func.inferredName and frame.func.inferredName.length > 0 text += path.basename(frame.script.name) + ":" text += (frame.line + 1) + ":" + (frame.column + 1) trace.push text i++ self.print trace.join("\n") self.resume() return return # First argument tells if it should display internal node scripts or not # (available only for internal debugger's functions) Interface::scripts = -> return unless @requireConnection() client = @client displayNatives = arguments[0] or false scripts = [] @pause() for id of client.scripts script = client.scripts[id] scripts.push ((if script.name is client.currentScript then "* " else " ")) + id + ": " + path.basename(script.name) if displayNatives or script.name is client.currentScript or not script.isNative if util.isObject(script) and script.name @print scripts.join("\n") @resume() return # Continue execution of script Interface::cont = -> return unless @requireConnection() @pause() self = this @client.reqContinue (err) -> self.error err if err self.resume() return return # Step commands generator Interface.stepGenerator = (type, count) -> -> return unless @requireConnection() self = this self.pause() self.client.step type, count, (err, res) -> self.error err if err self.resume() return return # Jump to next command Interface::next = Interface.stepGenerator("next", 1) # Step in Interface::step = Interface.stepGenerator("in", 1) # Step out Interface::out = Interface.stepGenerator("out", 1) # Watch Interface::watch = (expr) -> @_watchers.push expr return # Unwatch Interface::unwatch = (expr) -> index = @_watchers.indexOf(expr) # Unwatch by expression # or # Unwatch by watcher number @_watchers.splice (if index isnt -1 then index else +expr), 1 return # List watchers Interface::watchers = -> wait = -> if --waiting is 0 self.print "Watchers:" if verbose self._watchers.forEach (watcher, i) -> self.print leftPad(i, " ", self._watchers.length - 1) + ": " + watcher + " = " + JSON.stringify(values[i]) return self.print "" if verbose self.resume() callback null return self = this verbose = arguments[0] or false callback = arguments[1] or -> waiting = @_watchers.length values = [] @pause() unless waiting @resume() return callback() @_watchers.forEach (watcher, i) -> self.debugEval watcher, null, null, (err, value) -> values[i] = (if err then "<error>" else value) wait() return return return # Break on exception Interface::breakOnException = breakOnException = -> return unless @requireConnection() self = this # Break on exceptions @pause() @client.reqSetExceptionBreak "all", (err, res) -> self.resume() return return # Add breakpoint Interface::setBreakpoint = (script, line, condition, silent) -> return unless @requireConnection() self = this scriptId = undefined ambiguous = undefined # setBreakpoint() should insert breakpoint on current line if util.isUndefined(script) script = @client.currentScript line = @client.currentSourceLine + 1 # setBreakpoint(line-number) should insert breakpoint in current script if util.isUndefined(line) and util.isNumber(script) line = script script = @client.currentScript if /\(\)$/.test(script) # setBreakpoint('functionname()'); req = type: "function" target: script.replace(/\(\)$/, "") condition: condition else # setBreakpoint('scriptname') if script isnt +script and not @client.scripts[script] scripts = @client.scripts keys = Object.keys(scripts) v = 0 while v < keys.length id = keys[v] if scripts[id] and scripts[id].name and scripts[id].name.indexOf(script) isnt -1 ambiguous = true if scriptId scriptId = id v++ else scriptId = script return @error("Script name is ambiguous") if ambiguous return @error("Line should be a positive value") if line <= 0 req = undefined if scriptId req = type: "scriptId" target: scriptId line: line - 1 condition: condition else @print "Warning: script '" + script + "' was not loaded yet." escapedPath = script.replace(/([/\\.?*()^${}|[\]])/g, "\\$1") scriptPathRegex = "^(.*[\\/\\\\])?" + escapedPath + "$" req = type: "scriptRegExp" target: scriptPathRegex line: line - 1 condition: condition self.pause() self.client.setBreakpoint req, (err, res) -> if err self.error err unless silent else self.list 5 unless silent # Try load scriptId and line from response unless scriptId scriptId = res.script_id line = res.line + 1 # Remember this breakpoint even if scriptId is not resolved yet self.client.breakpoints.push id: res.breakpoint scriptId: scriptId script: (self.client.scripts[scriptId] or {}).name line: line condition: condition scriptReq: script self.resume() return return # Clear breakpoint Interface::clearBreakpoint = (script, line) -> return unless @requireConnection() ambiguous = undefined breakpoint = undefined index = undefined @client.breakpoints.some (bp, i) -> if bp.scriptId is script or bp.scriptReq is script or (bp.script and bp.script.indexOf(script) isnt -1) ambiguous = true unless util.isUndefined(index) if bp.line is line index = i breakpoint = bp.id true return @error("Script name is ambiguous") if ambiguous return @error("Script : " + script + " not found") if util.isUndefined(breakpoint) self = this req = breakpoint: breakpoint self.pause() self.client.clearBreakpoint req, (err, res) -> if err self.error err else self.client.breakpoints.splice index, 1 self.list 5 self.resume() return return # Show breakpoints Interface::breakpoints = -> return unless @requireConnection() @pause() self = this @client.listbreakpoints (err, res) -> if err self.error err else self.print res self.resume() return return # Pause child process Interface::pause_ = -> return unless @requireConnection() self = this cmd = "process._debugPause();" @pause() @client.reqFrameEval cmd, NO_FRAME, (err, res) -> if err self.error err else self.resume() return return # Kill child process Interface::kill = -> return unless @child @killChild() return # Activate debug repl Interface::repl = -> return unless @requireConnection() self = this self.print "Press Ctrl + C to leave debug repl" # Don't display any default messages listeners = @repl.rli.listeners("SIGINT").slice(0) @repl.rli.removeAllListeners "SIGINT" # Exit debug repl on Ctrl + C @repl.rli.once "SIGINT", -> # Restore all listeners process.nextTick -> listeners.forEach (listener) -> self.repl.rli.on "SIGINT", listener return return # Exit debug repl self.exitRepl() return # Set new @repl.eval = @debugEval.bind(this) @repl.context = {} # Swap history @history.control = @repl.rli.history @repl.rli.history = @history.debug @repl.rli.setPrompt "> " @repl.displayPrompt() return # Exit debug repl Interface::exitRepl = -> # Restore eval @repl.eval = @controlEval.bind(this) # Swap history @history.debug = @repl.rli.history @repl.rli.history = @history.control @repl.context = @context @repl.rli.setPrompt "debug> " @repl.displayPrompt() return # Quit Interface::quit = -> @killChild() process.exit 0 return # Kills child process Interface::killChild = -> if @child @child.kill() @child = null if @client # Save breakpoints @breakpoints = @client.breakpoints @client.destroy() @client = null return # Spawns child process (and restores breakpoints) Interface::trySpawn = (cb) -> # Connecting to remote debugger # `node debug localhost:5858` # TODO Do we really need to handle it? # `node debug -p pid` # TODO Do we really need to handle it? # Start debugger on custom port # `node debug --port=5858 app.js` # Restore breakpoints connectError = -> # If it's failed to connect 4 times then don't catch the next error client.removeListener "error", connectError if connectionAttempts >= 10 setTimeout attemptConnect, 500 return attemptConnect = -> ++connectionAttempts self.stdout.write "." client.connect port, host return self = this breakpoints = @breakpoints or [] port = exports.port host = "localhost" childArgs = @args @killChild() assert not @child if @args.length is 2 match = @args[1].match(/^([^:]+):(\d+)$/) if match host = match[1] port = parseInt(match[2], 10) @child = kill: -> else if @args.length is 3 if @args[1] is "-p" and /^\d+$/.test(@args[2]) @child = kill: -> process._debugProcess parseInt(@args[2], 10) else match = @args[1].match(/^--port=(\d+)$/) if match port = parseInt(match[1], 10) childArgs = ["--debug-brk=" + port].concat(@args.slice(2)) @child = spawn(process.execPath, childArgs) @child.stdout.on "data", @childPrint.bind(this) @child.stderr.on "data", @childPrint.bind(this) @pause() client = self.client = new Client() connectionAttempts = 0 client.once "ready", -> self.stdout.write " ok\n" breakpoints.forEach (bp) -> self.print "Restoring breakpoint " + bp.scriptReq + ":" + bp.line self.setBreakpoint bp.scriptReq, bp.line, bp.condition, true return client.on "close", -> self.pause() self.print "program terminated" self.resume() self.client = null self.killChild() return cb() if cb self.resume() return client.on "unhandledResponse", (res) -> self.pause() self.print "\nunhandled res:" + JSON.stringify(res) self.resume() return client.on "break", (res) -> self.handleBreak res.body return client.on "exception", (res) -> self.handleBreak res.body return client.on "error", connectError @child.stderr.once "data", -> setImmediate -> self.print "connecting to port " + port + "..", true attemptConnect() return return return
89248
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Setup input/output streams # # Parser/Serializer for V8 debugger protocol # http://code.google.com/p/v8/wiki/DebuggerProtocol # # Usage: # p = new Protocol(); # # p.onResponse = function(res) { # // do stuff with response from V8 # }; # # socket.setEncoding('utf8'); # socket.on('data', function(s) { # // Pass strings into the protocol # p.execute(s); # }); # # Protocol = -> @_newRes() return # pass thru # JSON parse body? # Done! Client = -> net.Stream.call this protocol = @protocol = new Protocol(this) @_reqCallbacks = [] socket = this @currentFrame = NO_FRAME @currentSourceLine = -1 @handles = {} @scripts = {} @breakpoints = [] # Note that 'Protocol' requires strings instead of Buffers. socket.setEncoding "utf8" socket.on "data", (d) -> protocol.execute d return protocol.onResponse = @_onResponse.bind(this) return # Request a list of scripts for our own storage. # ??? # This event is not used anywhere right now, perhaps somewhere in the # future? # TODO: We have a cache of handle's we've already seen in this.handles # This can be used if we're careful. # This is like reqEval, except it will look up the expression in each of the # scopes associated with the current frame. # Only need to eval in global scope. # Otherwise we need to get the current frame to see which scopes it has. # ?? # Finds the first scope in the array in which the expression evals. # Just eval in global scope. # reqBacktrace(cb) # TODO: from, to, bottom # reqSetExceptionBreak(type, cb) # TODO: from, to, bottom # Returns an array of objects like this: # # { handle: 11, # type: 'script', # name: 'node.js', # id: 14, # lineOffset: 0, # columnOffset: 0, # lineCount: 562, # sourceStart: '(function(process) {\n\n ', # sourceLength: 15939, # scriptType: 2, # compilationType: 0, # context: { ref: 10 }, # text: 'node.js (lines: 562)' } # # client.next(1, cb); # The handle looks something like this: # { handle: 8, # type: 'object', # className: 'Object', # constructorFunction: { ref: 9 }, # protoObject: { ref: 4 }, # prototypeObject: { ref: 2 }, # properties: [ { name: 'hello', propertyType: 1, ref: 10 } ], # text: '#<an Object>' } # For now ignore the className and constructor and prototype. # TJ's method of object inspection would probably be good for this: # https://groups.google.com/forum/?pli=1#!topic/nodejs-dev/4gkWBOimiOg # Skip the 'length' property. # looks like this: # { type: 'frame', # index: 0, # receiver: { ref: 1 }, # func: { ref: 0 }, # script: { ref: 7 }, # constructCall: false, # atReturn: false, # debuggerFrame: false, # arguments: [], # locals: [], # position: 160, # line: 7, # column: 2, # sourceLineText: ' debugger;', # scopes: [ { type: 1, index: 0 }, { type: 0, index: 1 } ], # text: '#00 blah() /home/ryan/projects/node/test-debug.js l...' } SourceUnderline = (sourceText, position, repl) -> return "" unless sourceText head = sourceText.slice(0, position) tail = sourceText.slice(position) # Colourize char if stdout supports colours tail = tail.replace(/(.+?)([^\w]|$)/, "\u001b[32m$1\u001b[39m$2") if repl.useColors # Return source line with coloured char at `position` [ head tail ].join "" SourceInfo = (body) -> result = (if body.exception then "exception in " else "break in ") if body.script if body.script.name name = body.script.name dir = path.resolve() + "/" # Change path to relative, if possible name = name.slice(dir.length) if name.indexOf(dir) is 0 result += name else result += "[unnamed]" result += ":" result += body.sourceLine + 1 result += "\n" + body.exception.text if body.exception result # This class is the repl-enabled debugger interface which is invoked on # "node debug" Interface = (stdin, stdout, args) -> # Two eval modes are available: controlEval and debugEval # But controlEval is used by default # Emulate Ctrl+C if we're emulating terminal # Do not print useless warning # Kill child process when main process dies # Handle all possible exits defineProperty = (key, protoKey) -> # Check arity fn = proto[protoKey].bind(self) if proto[protoKey].length is 0 Object.defineProperty self.repl.context, key, get: fn enumerable: true configurable: false else self.repl.context[key] = fn return self = this @stdin = stdin @stdout = stdout @args = args opts = prompt: "debug> " input: @stdin output: @stdout eval: @controlEval.bind(this) useGlobal: false ignoreUndefined: true if parseInt(process.env["NODE_NO_READLINE"], 10) opts.terminal = false else if parseInt(process.env["NODE_FORCE_READLINE"], 10) opts.terminal = true unless @stdout.isTTY process.on "SIGINT", -> self.repl.rli.emit "SIGINT" return opts.useColors = false if parseInt(process.env["NODE_DISABLE_COLORS"], 10) @repl = repl.start(opts) repl._builtinLibs.splice repl._builtinLibs.indexOf("repl"), 1 @repl.on "exit", -> process.exit 0 return process.on "exit", @killChild.bind(this) process.once "SIGTERM", process.exit.bind(process, 0) process.once "SIGHUP", process.exit.bind(process, 0) proto = Interface:: ignored = [ "pause" "resume" "exitRepl" "handleBreak" "requireConnection" "killChild" "trySpawn" "controlEval" "debugEval" "print" "childPrint" "clearline" ] shortcut = run: "r" cont: "c" next: "n" step: "s" out: "o" backtrace: "bt" setBreakpoint: "sb" clearBreakpoint: "cb" pause_: "pause" # Copy all prototype methods in repl context # Setup them as getters if possible for i of proto if Object::hasOwnProperty.call(proto, i) and ignored.indexOf(i) is -1 defineProperty i, i defineProperty shortcut[i], i if shortcut[i] @killed = false @waiting = null @paused = 0 @context = @repl.context @history = debug: [] control: [] @breakpoints = [] @_watchers = [] # Run script automatically @pause() # XXX Need to figure out why we need this delay setTimeout (-> self.run -> self.resume() return return ), 10 return # Stream control # Clear current line # Print text to output stream # Format and print text from child process # Errors formatting # Debugger's `break` event handler # Save execution context's data # Print break data # Show watchers' values # And list source # Internal method for checking connection state # Evals # Used for debugger's commands evaluation and execution # Repeat last command if empty line are going to be evaluated # Repl should not ask for next command # if current one was asynchronous. # Add a callback for asynchronous command # (it will be automatically invoked by .resume() method # Used for debugger's remote evaluation (`repl`) commands # Repl asked for scope variables # Request remote evaluation globally or in current frame # Request object by handles (and it's sub-properties) # Utils # Adds spaces and prefix to number # maxN is a maximum number we should have space for leftPad = (n, prefix, maxN) -> s = n.toString() nchars = Math.max(2, String(maxN).length) + 1 nspaces = nchars - s.length - 1 i = 0 while i < nspaces prefix += " " i++ prefix + s "use strict" util = require("util") path = require("path") net = require("net") vm = require("vm") module = require("module") repl = module.requireRepl() inherits = util.inherits assert = require("assert") spawn = require("child_process").spawn exports.start = (argv, stdin, stdout) -> argv or (argv = process.argv.slice(2)) if argv.length < 1 console.error "Usage: node debug script.js" process.exit 1 stdin = stdin or process.stdin stdout = stdout or process.stdout args = ["--debug-brk"].concat(argv) interface_ = new Interface(stdin, stdout, args) stdin.resume() process.on "uncaughtException", (e) -> console.error "There was an internal error in Node's debugger. " + "Please report this bug." console.error e.message console.error e.stack interface_.child.kill() if interface_.child process.exit 1 return return exports.port = 5858 exports.Protocol = Protocol Protocol::_newRes = (raw) -> @res = raw: raw or "" headers: {} @state = "headers" @reqSeq = 1 @execute "" return Protocol::execute = (d) -> res = @res res.raw += d switch @state when "headers" endHeaderIndex = res.raw.indexOf("\r\n\r\n") break if endHeaderIndex < 0 rawHeader = res.raw.slice(0, endHeaderIndex) endHeaderByteIndex = Buffer.byteLength(rawHeader, "utf8") lines = rawHeader.split("\r\n") i = 0 while i < lines.length kv = lines[i].split(/: +/) res.headers[kv[0]] = kv[1] i++ @contentLength = +res.headers["Content-Length"] @bodyStartByteIndex = endHeaderByteIndex + 4 @state = "body" len = Buffer.byteLength(res.raw, "utf8") break if len - @bodyStartByteIndex < @contentLength when "body" resRawByteLength = Buffer.byteLength(res.raw, "utf8") if resRawByteLength - @bodyStartByteIndex >= @contentLength buf = new Buffer(resRawByteLength) buf.write res.raw, 0, resRawByteLength, "utf8" res.body = buf.slice(@bodyStartByteIndex, @bodyStartByteIndex + @contentLength).toString("utf8") res.body = (if res.body.length then JSON.parse(res.body) else {}) @onResponse res @_newRes buf.slice(@bodyStartByteIndex + @contentLength).toString("utf8") else throw new Error("Unknown state") return Protocol::serialize = (req) -> req.type = "request" req.seq = @reqSeq++ json = JSON.stringify(req) "Content-Length: " + Buffer.byteLength(json, "utf8") + "\r\n\r\n" + json NO_FRAME = -1 inherits Client, net.Stream exports.Client = Client Client::_addHandle = (desc) -> return if not util.isObject(desc) or not util.isNumber(desc.handle) @handles[desc.handle] = desc @_addScript desc if desc.type is "script" return natives = process.binding("natives") Client::_addScript = (desc) -> @scripts[desc.id] = desc desc.isNative = (desc.name.replace(".js", "") of natives) or desc.name is "node.js" if desc.name return Client::_removeScript = (desc) -> @scripts[desc.id] = `undefined` return Client::_onResponse = (res) -> cb = undefined index = -1 @_reqCallbacks.some (fn, i) -> if fn.request_seq is res.body.request_seq cb = fn index = i true self = this handled = false if res.headers.Type is "connect" self.reqScripts() self.emit "ready" handled = true else if res.body and res.body.event is "break" @emit "break", res.body handled = true else if res.body and res.body.event is "exception" @emit "exception", res.body handled = true else if res.body and res.body.event is "afterCompile" @_addHandle res.body.body.script handled = true else if res.body and res.body.event is "scriptCollected" @_removeScript res.body.body.script handled = true else handled = true if res.body and res.body.event is "compileError" if cb @_reqCallbacks.splice index, 1 handled = true err = res.success is false and (res.message or true) or res.body.success is false and (res.body.message or true) cb err, res.body and res.body.body or res.body, res @emit "unhandledResponse", res.body unless handled return Client::req = (req, cb) -> @write @protocol.serialize(req) cb.request_seq = req.seq @_reqCallbacks.push cb return Client::reqVersion = (cb) -> cb = cb or -> @req command: "version" , (err, body, res) -> return cb(err) if err cb null, res.body.body.V8Version, res.body.running return return Client::reqLookup = (refs, cb) -> self = this req = command: "lookup" arguments: handles: refs cb = cb or -> @req req, (err, res) -> return cb(err) if err for ref of res self._addHandle res[ref] if util.isObject(res[ref]) cb null, res return return Client::reqScopes = (cb) -> self = this req = command: "scopes" arguments: {} cb = cb or -> @req req, (err, res) -> return cb(err) if err refs = res.scopes.map((scope) -> scope.object.ref ) self.reqLookup refs, (err, res) -> return cb(err) if err globals = Object.keys(res).map((key) -> res[key].properties.map (prop) -> prop.name ) cb null, globals.reverse() return return return Client::reqEval = (expression, cb) -> self = this if @currentFrame is NO_FRAME @reqFrameEval expression, NO_FRAME, cb return cb = cb or -> @reqBacktrace (err, bt) -> return cb(null, {}) if err or not bt.frames frame = bt.frames[self.currentFrame] evalFrames = frame.scopes.map((s) -> return unless s x = bt.frames[s.index] return unless x x.index ) self._reqFramesEval expression, evalFrames, cb return return Client::_reqFramesEval = (expression, evalFrames, cb) -> if evalFrames.length is 0 @reqFrameEval expression, NO_FRAME, cb return self = this i = evalFrames.shift() cb = cb or -> @reqFrameEval expression, i, (err, res) -> return cb(null, res) unless err self._reqFramesEval expression, evalFrames, cb return return Client::reqFrameEval = (expression, frame, cb) -> self = this req = command: "evaluate" arguments: expression: expression if frame is NO_FRAME req.arguments.global = true else req.arguments.frame = frame cb = cb or -> @req req, (err, res) -> self._addHandle res unless err cb err, res return return Client::reqBacktrace = (cb) -> @req command: "backtrace" arguments: inlineRefs: true , cb return Client::reqSetExceptionBreak = (type, cb) -> @req command: "setexceptionbreak" arguments: type: type enabled: true , cb return Client::reqScripts = (cb) -> self = this cb = cb or -> @req command: "scripts" , (err, res) -> return cb(err) if err i = 0 while i < res.length self._addHandle res[i] i++ cb null return return Client::reqContinue = (cb) -> @currentFrame = NO_FRAME @req command: "continue" , cb return Client::listbreakpoints = (cb) -> @req command: "listbreakpoints" , cb return Client::setBreakpoint = (req, cb) -> req = command: "setbreakpoint" arguments: req @req req, cb return Client::clearBreakpoint = (req, cb) -> req = command: "clearbreakpoint" arguments: req @req req, cb return Client::reqSource = (from, to, cb) -> req = command: "source" fromLine: from toLine: to @req req, cb return Client::step = (action, count, cb) -> req = command: "continue" arguments: stepaction: action stepcount: count @currentFrame = NO_FRAME @req req, cb return Client::mirrorObject = (handle, depth, cb) -> self = this val = undefined if handle.type is "object" propertyRefs = handle.properties.map((p) -> p.ref ) cb = cb or -> @reqLookup propertyRefs, (err, res) -> waitForOthers = -> if --waiting is 0 and cb keyValues.forEach (kv) -> mirror[kv.name] = kv.value return cb null, mirror return if err console.error "problem with reqLookup" cb null, handle return mirror = undefined waiting = 1 if handle.className is "Array" mirror = [] else if handle.className is "Date" mirror = new Date(handle.value) else mirror = {} keyValues = [] handle.properties.forEach (prop, i) -> value = res[prop.ref] mirrorValue = undefined if value mirrorValue = (if value.value then value.value else value.text) else mirrorValue = "[?]" return if util.isArray(mirror) and not util.isNumber(prop.name) keyValues[i] = name: prop.name value: mirrorValue if value and value.handle and depth > 0 waiting++ self.mirrorObject value, depth - 1, (err, result) -> keyValues[i].value = result unless err waitForOthers() return return waitForOthers() return return else if handle.type is "function" val = -> else if handle.type is "null" val = null else unless util.isUndefined(handle.value) val = handle.value else if handle.type is "undefined" val = `undefined` else val = handle process.nextTick -> cb null, val return return Client::fullTrace = (cb) -> self = this cb = cb or -> @reqBacktrace (err, trace) -> return cb(err) if err return cb(Error("No frames")) if trace.totalFrames <= 0 refs = [] i = 0 while i < trace.frames.length frame = trace.frames[i] refs.push frame.script.ref refs.push frame.func.ref refs.push frame.receiver.ref i++ self.reqLookup refs, (err, res) -> return cb(err) if err i = 0 while i < trace.frames.length frame = trace.frames[i] frame.script = res[frame.script.ref] frame.func = res[frame.func.ref] frame.receiver = res[frame.receiver.ref] i++ cb null, trace return return return commands = [ [ "run (r)" "cont (c)" "next (n)" "step (s)" "out (o)" "backtrace (bt)" "setBreakpoint (sb)" "clearBreakpoint (cb)" ] [ "watch" "unwatch" "watchers" "repl" "restart" "kill" "list" "scripts" "breakOnException" "breakpoints" "version" ] ] helpMessage = "Commands: " + commands.map((group) -> group.join ", " ).join(",\n") Interface::pause = -> return this if @killed or @paused++ > 0 @repl.rli.pause() @stdin.pause() this Interface::resume = (silent) -> return this if @killed or @paused is 0 or --@paused isnt 0 @repl.rli.resume() @repl.displayPrompt() if silent isnt true @stdin.resume() if @waiting @waiting() @waiting = null this Interface::clearline = -> if @stdout.isTTY @stdout.cursorTo 0 @stdout.clearLine 1 else @stdout.write "\b" return Interface::print = (text, oneline) -> return if @killed @clearline() @stdout.write (if util.isString(text) then text else util.inspect(text)) @stdout.write "\n" if oneline isnt true return Interface::childPrint = (text) -> @print text.toString().split(/\r\n|\r|\n/g).filter((chunk) -> chunk ).map((chunk) -> "< " + chunk ).join("\n") @repl.displayPrompt true return Interface::error = (text) -> @print text @resume() return Interface::handleBreak = (r) -> self = this @pause() @client.currentSourceLine = r.sourceLine @client.currentSourceLineText = r.sourceLineText @client.currentSourceColumn = r.sourceColumn @client.currentFrame = 0 @client.currentScript = r.script and r.script.name @print SourceInfo(r) @watchers true, (err) -> return self.error(err) if err self.list 2 self.resume true return return Interface::requireConnection = -> unless @client @error "App isn't running... Try `run` instead" return false true Interface::controlEval = (code, context, filename, callback) -> try code = @repl.rli.history[0] + "\n" if code is "\n" if @repl.rli.history and @repl.rli.history.length > 0 result = vm.runInContext(code, context, filename) return callback(null, result) if @paused is 0 @waiting = -> callback null, result return catch e callback e return Interface::debugEval = (code, context, filename, callback) -> return unless @requireConnection() self = this client = @client if code is ".scope" client.reqScopes callback return frame = (if client.currentFrame is NO_FRAME then frame else `undefined`) self.pause() client.reqFrameEval code, frame, (err, res) -> if err callback err self.resume true return client.mirrorObject res, 3, (err, mirror) -> callback null, mirror self.resume true return return return # Commands # Print help message Interface::help = -> @print helpMessage return # Run script Interface::run = -> callback = arguments[0] if @child @error "App is already running... Try `restart` instead" callback and callback(true) else @trySpawn callback return # Restart script Interface::restart = -> return unless @requireConnection() self = this self.pause() self.killChild() # XXX need to wait a little bit for the restart to work? setTimeout (-> self.trySpawn() self.resume() return ), 1000 return # Print version Interface::version = -> return unless @requireConnection() self = this @pause() @client.reqVersion (err, v) -> if err self.error err else self.print v self.resume() return return # List source code Interface::list = (delta) -> return unless @requireConnection() delta or (delta = 5) self = this client = @client from = client.currentSourceLine - delta + 1 to = client.currentSourceLine + delta + 1 self.pause() client.reqSource from, to, (err, res) -> if err or not res self.error "You can't list source code right now" self.resume() return lines = res.source.split("\n") i = 0 while i < lines.length lineno = res.fromLine + i + 1 continue if lineno < from or lineno > to current = lineno is 1 + client.currentSourceLine breakpoint = client.breakpoints.some((bp) -> (bp.scriptReq is client.currentScript or bp.script is client.currentScript) and bp.line is lineno ) if lineno is 1 # The first line needs to have the module wrapper filtered out of # it. wrapper = module.wrapper[0] lines[i] = lines[i].slice(wrapper.length) client.currentSourceColumn -= wrapper.length # Highlight executing statement line = undefined if current line = SourceUnderline(lines[i], client.currentSourceColumn, self.repl) else line = lines[i] prefixChar = " " if current prefixChar = ">" else prefixChar = "*" if breakpoint self.print leftPad(lineno, prefixChar, to) + " " + line i++ self.resume() return return # Print backtrace Interface::backtrace = -> return unless @requireConnection() self = this client = @client self.pause() client.fullTrace (err, bt) -> if err self.error "Can't request backtrace now" self.resume() return if bt.totalFrames is 0 self.print "(empty stack)" else trace = [] firstFrameNative = bt.frames[0].script.isNative i = 0 while i < bt.frames.length frame = bt.frames[i] break if not firstFrameNative and frame.script.isNative text = "#" + i + " " text += frame.func.inferredName + " " if frame.func.inferredName and frame.func.inferredName.length > 0 text += path.basename(frame.script.name) + ":" text += (frame.line + 1) + ":" + (frame.column + 1) trace.push text i++ self.print trace.join("\n") self.resume() return return # First argument tells if it should display internal node scripts or not # (available only for internal debugger's functions) Interface::scripts = -> return unless @requireConnection() client = @client displayNatives = arguments[0] or false scripts = [] @pause() for id of client.scripts script = client.scripts[id] scripts.push ((if script.name is client.currentScript then "* " else " ")) + id + ": " + path.basename(script.name) if displayNatives or script.name is client.currentScript or not script.isNative if util.isObject(script) and script.name @print scripts.join("\n") @resume() return # Continue execution of script Interface::cont = -> return unless @requireConnection() @pause() self = this @client.reqContinue (err) -> self.error err if err self.resume() return return # Step commands generator Interface.stepGenerator = (type, count) -> -> return unless @requireConnection() self = this self.pause() self.client.step type, count, (err, res) -> self.error err if err self.resume() return return # Jump to next command Interface::next = Interface.stepGenerator("next", 1) # Step in Interface::step = Interface.stepGenerator("in", 1) # Step out Interface::out = Interface.stepGenerator("out", 1) # Watch Interface::watch = (expr) -> @_watchers.push expr return # Unwatch Interface::unwatch = (expr) -> index = @_watchers.indexOf(expr) # Unwatch by expression # or # Unwatch by watcher number @_watchers.splice (if index isnt -1 then index else +expr), 1 return # List watchers Interface::watchers = -> wait = -> if --waiting is 0 self.print "Watchers:" if verbose self._watchers.forEach (watcher, i) -> self.print leftPad(i, " ", self._watchers.length - 1) + ": " + watcher + " = " + JSON.stringify(values[i]) return self.print "" if verbose self.resume() callback null return self = this verbose = arguments[0] or false callback = arguments[1] or -> waiting = @_watchers.length values = [] @pause() unless waiting @resume() return callback() @_watchers.forEach (watcher, i) -> self.debugEval watcher, null, null, (err, value) -> values[i] = (if err then "<error>" else value) wait() return return return # Break on exception Interface::breakOnException = breakOnException = -> return unless @requireConnection() self = this # Break on exceptions @pause() @client.reqSetExceptionBreak "all", (err, res) -> self.resume() return return # Add breakpoint Interface::setBreakpoint = (script, line, condition, silent) -> return unless @requireConnection() self = this scriptId = undefined ambiguous = undefined # setBreakpoint() should insert breakpoint on current line if util.isUndefined(script) script = @client.currentScript line = @client.currentSourceLine + 1 # setBreakpoint(line-number) should insert breakpoint in current script if util.isUndefined(line) and util.isNumber(script) line = script script = @client.currentScript if /\(\)$/.test(script) # setBreakpoint('functionname()'); req = type: "function" target: script.replace(/\(\)$/, "") condition: condition else # setBreakpoint('scriptname') if script isnt +script and not @client.scripts[script] scripts = @client.scripts keys = Object.keys(scripts) v = 0 while v < keys.length id = keys[v] if scripts[id] and scripts[id].name and scripts[id].name.indexOf(script) isnt -1 ambiguous = true if scriptId scriptId = id v++ else scriptId = script return @error("Script name is ambiguous") if ambiguous return @error("Line should be a positive value") if line <= 0 req = undefined if scriptId req = type: "scriptId" target: scriptId line: line - 1 condition: condition else @print "Warning: script '" + script + "' was not loaded yet." escapedPath = script.replace(/([/\\.?*()^${}|[\]])/g, "\\$1") scriptPathRegex = "^(.*[\\/\\\\])?" + escapedPath + "$" req = type: "scriptRegExp" target: scriptPathRegex line: line - 1 condition: condition self.pause() self.client.setBreakpoint req, (err, res) -> if err self.error err unless silent else self.list 5 unless silent # Try load scriptId and line from response unless scriptId scriptId = res.script_id line = res.line + 1 # Remember this breakpoint even if scriptId is not resolved yet self.client.breakpoints.push id: res.breakpoint scriptId: scriptId script: (self.client.scripts[scriptId] or {}).name line: line condition: condition scriptReq: script self.resume() return return # Clear breakpoint Interface::clearBreakpoint = (script, line) -> return unless @requireConnection() ambiguous = undefined breakpoint = undefined index = undefined @client.breakpoints.some (bp, i) -> if bp.scriptId is script or bp.scriptReq is script or (bp.script and bp.script.indexOf(script) isnt -1) ambiguous = true unless util.isUndefined(index) if bp.line is line index = i breakpoint = bp.id true return @error("Script name is ambiguous") if ambiguous return @error("Script : " + script + " not found") if util.isUndefined(breakpoint) self = this req = breakpoint: breakpoint self.pause() self.client.clearBreakpoint req, (err, res) -> if err self.error err else self.client.breakpoints.splice index, 1 self.list 5 self.resume() return return # Show breakpoints Interface::breakpoints = -> return unless @requireConnection() @pause() self = this @client.listbreakpoints (err, res) -> if err self.error err else self.print res self.resume() return return # Pause child process Interface::pause_ = -> return unless @requireConnection() self = this cmd = "process._debugPause();" @pause() @client.reqFrameEval cmd, NO_FRAME, (err, res) -> if err self.error err else self.resume() return return # Kill child process Interface::kill = -> return unless @child @killChild() return # Activate debug repl Interface::repl = -> return unless @requireConnection() self = this self.print "Press Ctrl + C to leave debug repl" # Don't display any default messages listeners = @repl.rli.listeners("SIGINT").slice(0) @repl.rli.removeAllListeners "SIGINT" # Exit debug repl on Ctrl + C @repl.rli.once "SIGINT", -> # Restore all listeners process.nextTick -> listeners.forEach (listener) -> self.repl.rli.on "SIGINT", listener return return # Exit debug repl self.exitRepl() return # Set new @repl.eval = @debugEval.bind(this) @repl.context = {} # Swap history @history.control = @repl.rli.history @repl.rli.history = @history.debug @repl.rli.setPrompt "> " @repl.displayPrompt() return # Exit debug repl Interface::exitRepl = -> # Restore eval @repl.eval = @controlEval.bind(this) # Swap history @history.debug = @repl.rli.history @repl.rli.history = @history.control @repl.context = @context @repl.rli.setPrompt "debug> " @repl.displayPrompt() return # Quit Interface::quit = -> @killChild() process.exit 0 return # Kills child process Interface::killChild = -> if @child @child.kill() @child = null if @client # Save breakpoints @breakpoints = @client.breakpoints @client.destroy() @client = null return # Spawns child process (and restores breakpoints) Interface::trySpawn = (cb) -> # Connecting to remote debugger # `node debug localhost:5858` # TODO Do we really need to handle it? # `node debug -p pid` # TODO Do we really need to handle it? # Start debugger on custom port # `node debug --port=5858 app.js` # Restore breakpoints connectError = -> # If it's failed to connect 4 times then don't catch the next error client.removeListener "error", connectError if connectionAttempts >= 10 setTimeout attemptConnect, 500 return attemptConnect = -> ++connectionAttempts self.stdout.write "." client.connect port, host return self = this breakpoints = @breakpoints or [] port = exports.port host = "localhost" childArgs = @args @killChild() assert not @child if @args.length is 2 match = @args[1].match(/^([^:]+):(\d+)$/) if match host = match[1] port = parseInt(match[2], 10) @child = kill: -> else if @args.length is 3 if @args[1] is "-p" and /^\d+$/.test(@args[2]) @child = kill: -> process._debugProcess parseInt(@args[2], 10) else match = @args[1].match(/^--port=(\d+)$/) if match port = parseInt(match[1], 10) childArgs = ["--debug-brk=" + port].concat(@args.slice(2)) @child = spawn(process.execPath, childArgs) @child.stdout.on "data", @childPrint.bind(this) @child.stderr.on "data", @childPrint.bind(this) @pause() client = self.client = new Client() connectionAttempts = 0 client.once "ready", -> self.stdout.write " ok\n" breakpoints.forEach (bp) -> self.print "Restoring breakpoint " + bp.scriptReq + ":" + bp.line self.setBreakpoint bp.scriptReq, bp.line, bp.condition, true return client.on "close", -> self.pause() self.print "program terminated" self.resume() self.client = null self.killChild() return cb() if cb self.resume() return client.on "unhandledResponse", (res) -> self.pause() self.print "\nunhandled res:" + JSON.stringify(res) self.resume() return client.on "break", (res) -> self.handleBreak res.body return client.on "exception", (res) -> self.handleBreak res.body return client.on "error", connectError @child.stderr.once "data", -> setImmediate -> self.print "connecting to port " + port + "..", true attemptConnect() return return return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Setup input/output streams # # Parser/Serializer for V8 debugger protocol # http://code.google.com/p/v8/wiki/DebuggerProtocol # # Usage: # p = new Protocol(); # # p.onResponse = function(res) { # // do stuff with response from V8 # }; # # socket.setEncoding('utf8'); # socket.on('data', function(s) { # // Pass strings into the protocol # p.execute(s); # }); # # Protocol = -> @_newRes() return # pass thru # JSON parse body? # Done! Client = -> net.Stream.call this protocol = @protocol = new Protocol(this) @_reqCallbacks = [] socket = this @currentFrame = NO_FRAME @currentSourceLine = -1 @handles = {} @scripts = {} @breakpoints = [] # Note that 'Protocol' requires strings instead of Buffers. socket.setEncoding "utf8" socket.on "data", (d) -> protocol.execute d return protocol.onResponse = @_onResponse.bind(this) return # Request a list of scripts for our own storage. # ??? # This event is not used anywhere right now, perhaps somewhere in the # future? # TODO: We have a cache of handle's we've already seen in this.handles # This can be used if we're careful. # This is like reqEval, except it will look up the expression in each of the # scopes associated with the current frame. # Only need to eval in global scope. # Otherwise we need to get the current frame to see which scopes it has. # ?? # Finds the first scope in the array in which the expression evals. # Just eval in global scope. # reqBacktrace(cb) # TODO: from, to, bottom # reqSetExceptionBreak(type, cb) # TODO: from, to, bottom # Returns an array of objects like this: # # { handle: 11, # type: 'script', # name: 'node.js', # id: 14, # lineOffset: 0, # columnOffset: 0, # lineCount: 562, # sourceStart: '(function(process) {\n\n ', # sourceLength: 15939, # scriptType: 2, # compilationType: 0, # context: { ref: 10 }, # text: 'node.js (lines: 562)' } # # client.next(1, cb); # The handle looks something like this: # { handle: 8, # type: 'object', # className: 'Object', # constructorFunction: { ref: 9 }, # protoObject: { ref: 4 }, # prototypeObject: { ref: 2 }, # properties: [ { name: 'hello', propertyType: 1, ref: 10 } ], # text: '#<an Object>' } # For now ignore the className and constructor and prototype. # TJ's method of object inspection would probably be good for this: # https://groups.google.com/forum/?pli=1#!topic/nodejs-dev/4gkWBOimiOg # Skip the 'length' property. # looks like this: # { type: 'frame', # index: 0, # receiver: { ref: 1 }, # func: { ref: 0 }, # script: { ref: 7 }, # constructCall: false, # atReturn: false, # debuggerFrame: false, # arguments: [], # locals: [], # position: 160, # line: 7, # column: 2, # sourceLineText: ' debugger;', # scopes: [ { type: 1, index: 0 }, { type: 0, index: 1 } ], # text: '#00 blah() /home/ryan/projects/node/test-debug.js l...' } SourceUnderline = (sourceText, position, repl) -> return "" unless sourceText head = sourceText.slice(0, position) tail = sourceText.slice(position) # Colourize char if stdout supports colours tail = tail.replace(/(.+?)([^\w]|$)/, "\u001b[32m$1\u001b[39m$2") if repl.useColors # Return source line with coloured char at `position` [ head tail ].join "" SourceInfo = (body) -> result = (if body.exception then "exception in " else "break in ") if body.script if body.script.name name = body.script.name dir = path.resolve() + "/" # Change path to relative, if possible name = name.slice(dir.length) if name.indexOf(dir) is 0 result += name else result += "[unnamed]" result += ":" result += body.sourceLine + 1 result += "\n" + body.exception.text if body.exception result # This class is the repl-enabled debugger interface which is invoked on # "node debug" Interface = (stdin, stdout, args) -> # Two eval modes are available: controlEval and debugEval # But controlEval is used by default # Emulate Ctrl+C if we're emulating terminal # Do not print useless warning # Kill child process when main process dies # Handle all possible exits defineProperty = (key, protoKey) -> # Check arity fn = proto[protoKey].bind(self) if proto[protoKey].length is 0 Object.defineProperty self.repl.context, key, get: fn enumerable: true configurable: false else self.repl.context[key] = fn return self = this @stdin = stdin @stdout = stdout @args = args opts = prompt: "debug> " input: @stdin output: @stdout eval: @controlEval.bind(this) useGlobal: false ignoreUndefined: true if parseInt(process.env["NODE_NO_READLINE"], 10) opts.terminal = false else if parseInt(process.env["NODE_FORCE_READLINE"], 10) opts.terminal = true unless @stdout.isTTY process.on "SIGINT", -> self.repl.rli.emit "SIGINT" return opts.useColors = false if parseInt(process.env["NODE_DISABLE_COLORS"], 10) @repl = repl.start(opts) repl._builtinLibs.splice repl._builtinLibs.indexOf("repl"), 1 @repl.on "exit", -> process.exit 0 return process.on "exit", @killChild.bind(this) process.once "SIGTERM", process.exit.bind(process, 0) process.once "SIGHUP", process.exit.bind(process, 0) proto = Interface:: ignored = [ "pause" "resume" "exitRepl" "handleBreak" "requireConnection" "killChild" "trySpawn" "controlEval" "debugEval" "print" "childPrint" "clearline" ] shortcut = run: "r" cont: "c" next: "n" step: "s" out: "o" backtrace: "bt" setBreakpoint: "sb" clearBreakpoint: "cb" pause_: "pause" # Copy all prototype methods in repl context # Setup them as getters if possible for i of proto if Object::hasOwnProperty.call(proto, i) and ignored.indexOf(i) is -1 defineProperty i, i defineProperty shortcut[i], i if shortcut[i] @killed = false @waiting = null @paused = 0 @context = @repl.context @history = debug: [] control: [] @breakpoints = [] @_watchers = [] # Run script automatically @pause() # XXX Need to figure out why we need this delay setTimeout (-> self.run -> self.resume() return return ), 10 return # Stream control # Clear current line # Print text to output stream # Format and print text from child process # Errors formatting # Debugger's `break` event handler # Save execution context's data # Print break data # Show watchers' values # And list source # Internal method for checking connection state # Evals # Used for debugger's commands evaluation and execution # Repeat last command if empty line are going to be evaluated # Repl should not ask for next command # if current one was asynchronous. # Add a callback for asynchronous command # (it will be automatically invoked by .resume() method # Used for debugger's remote evaluation (`repl`) commands # Repl asked for scope variables # Request remote evaluation globally or in current frame # Request object by handles (and it's sub-properties) # Utils # Adds spaces and prefix to number # maxN is a maximum number we should have space for leftPad = (n, prefix, maxN) -> s = n.toString() nchars = Math.max(2, String(maxN).length) + 1 nspaces = nchars - s.length - 1 i = 0 while i < nspaces prefix += " " i++ prefix + s "use strict" util = require("util") path = require("path") net = require("net") vm = require("vm") module = require("module") repl = module.requireRepl() inherits = util.inherits assert = require("assert") spawn = require("child_process").spawn exports.start = (argv, stdin, stdout) -> argv or (argv = process.argv.slice(2)) if argv.length < 1 console.error "Usage: node debug script.js" process.exit 1 stdin = stdin or process.stdin stdout = stdout or process.stdout args = ["--debug-brk"].concat(argv) interface_ = new Interface(stdin, stdout, args) stdin.resume() process.on "uncaughtException", (e) -> console.error "There was an internal error in Node's debugger. " + "Please report this bug." console.error e.message console.error e.stack interface_.child.kill() if interface_.child process.exit 1 return return exports.port = 5858 exports.Protocol = Protocol Protocol::_newRes = (raw) -> @res = raw: raw or "" headers: {} @state = "headers" @reqSeq = 1 @execute "" return Protocol::execute = (d) -> res = @res res.raw += d switch @state when "headers" endHeaderIndex = res.raw.indexOf("\r\n\r\n") break if endHeaderIndex < 0 rawHeader = res.raw.slice(0, endHeaderIndex) endHeaderByteIndex = Buffer.byteLength(rawHeader, "utf8") lines = rawHeader.split("\r\n") i = 0 while i < lines.length kv = lines[i].split(/: +/) res.headers[kv[0]] = kv[1] i++ @contentLength = +res.headers["Content-Length"] @bodyStartByteIndex = endHeaderByteIndex + 4 @state = "body" len = Buffer.byteLength(res.raw, "utf8") break if len - @bodyStartByteIndex < @contentLength when "body" resRawByteLength = Buffer.byteLength(res.raw, "utf8") if resRawByteLength - @bodyStartByteIndex >= @contentLength buf = new Buffer(resRawByteLength) buf.write res.raw, 0, resRawByteLength, "utf8" res.body = buf.slice(@bodyStartByteIndex, @bodyStartByteIndex + @contentLength).toString("utf8") res.body = (if res.body.length then JSON.parse(res.body) else {}) @onResponse res @_newRes buf.slice(@bodyStartByteIndex + @contentLength).toString("utf8") else throw new Error("Unknown state") return Protocol::serialize = (req) -> req.type = "request" req.seq = @reqSeq++ json = JSON.stringify(req) "Content-Length: " + Buffer.byteLength(json, "utf8") + "\r\n\r\n" + json NO_FRAME = -1 inherits Client, net.Stream exports.Client = Client Client::_addHandle = (desc) -> return if not util.isObject(desc) or not util.isNumber(desc.handle) @handles[desc.handle] = desc @_addScript desc if desc.type is "script" return natives = process.binding("natives") Client::_addScript = (desc) -> @scripts[desc.id] = desc desc.isNative = (desc.name.replace(".js", "") of natives) or desc.name is "node.js" if desc.name return Client::_removeScript = (desc) -> @scripts[desc.id] = `undefined` return Client::_onResponse = (res) -> cb = undefined index = -1 @_reqCallbacks.some (fn, i) -> if fn.request_seq is res.body.request_seq cb = fn index = i true self = this handled = false if res.headers.Type is "connect" self.reqScripts() self.emit "ready" handled = true else if res.body and res.body.event is "break" @emit "break", res.body handled = true else if res.body and res.body.event is "exception" @emit "exception", res.body handled = true else if res.body and res.body.event is "afterCompile" @_addHandle res.body.body.script handled = true else if res.body and res.body.event is "scriptCollected" @_removeScript res.body.body.script handled = true else handled = true if res.body and res.body.event is "compileError" if cb @_reqCallbacks.splice index, 1 handled = true err = res.success is false and (res.message or true) or res.body.success is false and (res.body.message or true) cb err, res.body and res.body.body or res.body, res @emit "unhandledResponse", res.body unless handled return Client::req = (req, cb) -> @write @protocol.serialize(req) cb.request_seq = req.seq @_reqCallbacks.push cb return Client::reqVersion = (cb) -> cb = cb or -> @req command: "version" , (err, body, res) -> return cb(err) if err cb null, res.body.body.V8Version, res.body.running return return Client::reqLookup = (refs, cb) -> self = this req = command: "lookup" arguments: handles: refs cb = cb or -> @req req, (err, res) -> return cb(err) if err for ref of res self._addHandle res[ref] if util.isObject(res[ref]) cb null, res return return Client::reqScopes = (cb) -> self = this req = command: "scopes" arguments: {} cb = cb or -> @req req, (err, res) -> return cb(err) if err refs = res.scopes.map((scope) -> scope.object.ref ) self.reqLookup refs, (err, res) -> return cb(err) if err globals = Object.keys(res).map((key) -> res[key].properties.map (prop) -> prop.name ) cb null, globals.reverse() return return return Client::reqEval = (expression, cb) -> self = this if @currentFrame is NO_FRAME @reqFrameEval expression, NO_FRAME, cb return cb = cb or -> @reqBacktrace (err, bt) -> return cb(null, {}) if err or not bt.frames frame = bt.frames[self.currentFrame] evalFrames = frame.scopes.map((s) -> return unless s x = bt.frames[s.index] return unless x x.index ) self._reqFramesEval expression, evalFrames, cb return return Client::_reqFramesEval = (expression, evalFrames, cb) -> if evalFrames.length is 0 @reqFrameEval expression, NO_FRAME, cb return self = this i = evalFrames.shift() cb = cb or -> @reqFrameEval expression, i, (err, res) -> return cb(null, res) unless err self._reqFramesEval expression, evalFrames, cb return return Client::reqFrameEval = (expression, frame, cb) -> self = this req = command: "evaluate" arguments: expression: expression if frame is NO_FRAME req.arguments.global = true else req.arguments.frame = frame cb = cb or -> @req req, (err, res) -> self._addHandle res unless err cb err, res return return Client::reqBacktrace = (cb) -> @req command: "backtrace" arguments: inlineRefs: true , cb return Client::reqSetExceptionBreak = (type, cb) -> @req command: "setexceptionbreak" arguments: type: type enabled: true , cb return Client::reqScripts = (cb) -> self = this cb = cb or -> @req command: "scripts" , (err, res) -> return cb(err) if err i = 0 while i < res.length self._addHandle res[i] i++ cb null return return Client::reqContinue = (cb) -> @currentFrame = NO_FRAME @req command: "continue" , cb return Client::listbreakpoints = (cb) -> @req command: "listbreakpoints" , cb return Client::setBreakpoint = (req, cb) -> req = command: "setbreakpoint" arguments: req @req req, cb return Client::clearBreakpoint = (req, cb) -> req = command: "clearbreakpoint" arguments: req @req req, cb return Client::reqSource = (from, to, cb) -> req = command: "source" fromLine: from toLine: to @req req, cb return Client::step = (action, count, cb) -> req = command: "continue" arguments: stepaction: action stepcount: count @currentFrame = NO_FRAME @req req, cb return Client::mirrorObject = (handle, depth, cb) -> self = this val = undefined if handle.type is "object" propertyRefs = handle.properties.map((p) -> p.ref ) cb = cb or -> @reqLookup propertyRefs, (err, res) -> waitForOthers = -> if --waiting is 0 and cb keyValues.forEach (kv) -> mirror[kv.name] = kv.value return cb null, mirror return if err console.error "problem with reqLookup" cb null, handle return mirror = undefined waiting = 1 if handle.className is "Array" mirror = [] else if handle.className is "Date" mirror = new Date(handle.value) else mirror = {} keyValues = [] handle.properties.forEach (prop, i) -> value = res[prop.ref] mirrorValue = undefined if value mirrorValue = (if value.value then value.value else value.text) else mirrorValue = "[?]" return if util.isArray(mirror) and not util.isNumber(prop.name) keyValues[i] = name: prop.name value: mirrorValue if value and value.handle and depth > 0 waiting++ self.mirrorObject value, depth - 1, (err, result) -> keyValues[i].value = result unless err waitForOthers() return return waitForOthers() return return else if handle.type is "function" val = -> else if handle.type is "null" val = null else unless util.isUndefined(handle.value) val = handle.value else if handle.type is "undefined" val = `undefined` else val = handle process.nextTick -> cb null, val return return Client::fullTrace = (cb) -> self = this cb = cb or -> @reqBacktrace (err, trace) -> return cb(err) if err return cb(Error("No frames")) if trace.totalFrames <= 0 refs = [] i = 0 while i < trace.frames.length frame = trace.frames[i] refs.push frame.script.ref refs.push frame.func.ref refs.push frame.receiver.ref i++ self.reqLookup refs, (err, res) -> return cb(err) if err i = 0 while i < trace.frames.length frame = trace.frames[i] frame.script = res[frame.script.ref] frame.func = res[frame.func.ref] frame.receiver = res[frame.receiver.ref] i++ cb null, trace return return return commands = [ [ "run (r)" "cont (c)" "next (n)" "step (s)" "out (o)" "backtrace (bt)" "setBreakpoint (sb)" "clearBreakpoint (cb)" ] [ "watch" "unwatch" "watchers" "repl" "restart" "kill" "list" "scripts" "breakOnException" "breakpoints" "version" ] ] helpMessage = "Commands: " + commands.map((group) -> group.join ", " ).join(",\n") Interface::pause = -> return this if @killed or @paused++ > 0 @repl.rli.pause() @stdin.pause() this Interface::resume = (silent) -> return this if @killed or @paused is 0 or --@paused isnt 0 @repl.rli.resume() @repl.displayPrompt() if silent isnt true @stdin.resume() if @waiting @waiting() @waiting = null this Interface::clearline = -> if @stdout.isTTY @stdout.cursorTo 0 @stdout.clearLine 1 else @stdout.write "\b" return Interface::print = (text, oneline) -> return if @killed @clearline() @stdout.write (if util.isString(text) then text else util.inspect(text)) @stdout.write "\n" if oneline isnt true return Interface::childPrint = (text) -> @print text.toString().split(/\r\n|\r|\n/g).filter((chunk) -> chunk ).map((chunk) -> "< " + chunk ).join("\n") @repl.displayPrompt true return Interface::error = (text) -> @print text @resume() return Interface::handleBreak = (r) -> self = this @pause() @client.currentSourceLine = r.sourceLine @client.currentSourceLineText = r.sourceLineText @client.currentSourceColumn = r.sourceColumn @client.currentFrame = 0 @client.currentScript = r.script and r.script.name @print SourceInfo(r) @watchers true, (err) -> return self.error(err) if err self.list 2 self.resume true return return Interface::requireConnection = -> unless @client @error "App isn't running... Try `run` instead" return false true Interface::controlEval = (code, context, filename, callback) -> try code = @repl.rli.history[0] + "\n" if code is "\n" if @repl.rli.history and @repl.rli.history.length > 0 result = vm.runInContext(code, context, filename) return callback(null, result) if @paused is 0 @waiting = -> callback null, result return catch e callback e return Interface::debugEval = (code, context, filename, callback) -> return unless @requireConnection() self = this client = @client if code is ".scope" client.reqScopes callback return frame = (if client.currentFrame is NO_FRAME then frame else `undefined`) self.pause() client.reqFrameEval code, frame, (err, res) -> if err callback err self.resume true return client.mirrorObject res, 3, (err, mirror) -> callback null, mirror self.resume true return return return # Commands # Print help message Interface::help = -> @print helpMessage return # Run script Interface::run = -> callback = arguments[0] if @child @error "App is already running... Try `restart` instead" callback and callback(true) else @trySpawn callback return # Restart script Interface::restart = -> return unless @requireConnection() self = this self.pause() self.killChild() # XXX need to wait a little bit for the restart to work? setTimeout (-> self.trySpawn() self.resume() return ), 1000 return # Print version Interface::version = -> return unless @requireConnection() self = this @pause() @client.reqVersion (err, v) -> if err self.error err else self.print v self.resume() return return # List source code Interface::list = (delta) -> return unless @requireConnection() delta or (delta = 5) self = this client = @client from = client.currentSourceLine - delta + 1 to = client.currentSourceLine + delta + 1 self.pause() client.reqSource from, to, (err, res) -> if err or not res self.error "You can't list source code right now" self.resume() return lines = res.source.split("\n") i = 0 while i < lines.length lineno = res.fromLine + i + 1 continue if lineno < from or lineno > to current = lineno is 1 + client.currentSourceLine breakpoint = client.breakpoints.some((bp) -> (bp.scriptReq is client.currentScript or bp.script is client.currentScript) and bp.line is lineno ) if lineno is 1 # The first line needs to have the module wrapper filtered out of # it. wrapper = module.wrapper[0] lines[i] = lines[i].slice(wrapper.length) client.currentSourceColumn -= wrapper.length # Highlight executing statement line = undefined if current line = SourceUnderline(lines[i], client.currentSourceColumn, self.repl) else line = lines[i] prefixChar = " " if current prefixChar = ">" else prefixChar = "*" if breakpoint self.print leftPad(lineno, prefixChar, to) + " " + line i++ self.resume() return return # Print backtrace Interface::backtrace = -> return unless @requireConnection() self = this client = @client self.pause() client.fullTrace (err, bt) -> if err self.error "Can't request backtrace now" self.resume() return if bt.totalFrames is 0 self.print "(empty stack)" else trace = [] firstFrameNative = bt.frames[0].script.isNative i = 0 while i < bt.frames.length frame = bt.frames[i] break if not firstFrameNative and frame.script.isNative text = "#" + i + " " text += frame.func.inferredName + " " if frame.func.inferredName and frame.func.inferredName.length > 0 text += path.basename(frame.script.name) + ":" text += (frame.line + 1) + ":" + (frame.column + 1) trace.push text i++ self.print trace.join("\n") self.resume() return return # First argument tells if it should display internal node scripts or not # (available only for internal debugger's functions) Interface::scripts = -> return unless @requireConnection() client = @client displayNatives = arguments[0] or false scripts = [] @pause() for id of client.scripts script = client.scripts[id] scripts.push ((if script.name is client.currentScript then "* " else " ")) + id + ": " + path.basename(script.name) if displayNatives or script.name is client.currentScript or not script.isNative if util.isObject(script) and script.name @print scripts.join("\n") @resume() return # Continue execution of script Interface::cont = -> return unless @requireConnection() @pause() self = this @client.reqContinue (err) -> self.error err if err self.resume() return return # Step commands generator Interface.stepGenerator = (type, count) -> -> return unless @requireConnection() self = this self.pause() self.client.step type, count, (err, res) -> self.error err if err self.resume() return return # Jump to next command Interface::next = Interface.stepGenerator("next", 1) # Step in Interface::step = Interface.stepGenerator("in", 1) # Step out Interface::out = Interface.stepGenerator("out", 1) # Watch Interface::watch = (expr) -> @_watchers.push expr return # Unwatch Interface::unwatch = (expr) -> index = @_watchers.indexOf(expr) # Unwatch by expression # or # Unwatch by watcher number @_watchers.splice (if index isnt -1 then index else +expr), 1 return # List watchers Interface::watchers = -> wait = -> if --waiting is 0 self.print "Watchers:" if verbose self._watchers.forEach (watcher, i) -> self.print leftPad(i, " ", self._watchers.length - 1) + ": " + watcher + " = " + JSON.stringify(values[i]) return self.print "" if verbose self.resume() callback null return self = this verbose = arguments[0] or false callback = arguments[1] or -> waiting = @_watchers.length values = [] @pause() unless waiting @resume() return callback() @_watchers.forEach (watcher, i) -> self.debugEval watcher, null, null, (err, value) -> values[i] = (if err then "<error>" else value) wait() return return return # Break on exception Interface::breakOnException = breakOnException = -> return unless @requireConnection() self = this # Break on exceptions @pause() @client.reqSetExceptionBreak "all", (err, res) -> self.resume() return return # Add breakpoint Interface::setBreakpoint = (script, line, condition, silent) -> return unless @requireConnection() self = this scriptId = undefined ambiguous = undefined # setBreakpoint() should insert breakpoint on current line if util.isUndefined(script) script = @client.currentScript line = @client.currentSourceLine + 1 # setBreakpoint(line-number) should insert breakpoint in current script if util.isUndefined(line) and util.isNumber(script) line = script script = @client.currentScript if /\(\)$/.test(script) # setBreakpoint('functionname()'); req = type: "function" target: script.replace(/\(\)$/, "") condition: condition else # setBreakpoint('scriptname') if script isnt +script and not @client.scripts[script] scripts = @client.scripts keys = Object.keys(scripts) v = 0 while v < keys.length id = keys[v] if scripts[id] and scripts[id].name and scripts[id].name.indexOf(script) isnt -1 ambiguous = true if scriptId scriptId = id v++ else scriptId = script return @error("Script name is ambiguous") if ambiguous return @error("Line should be a positive value") if line <= 0 req = undefined if scriptId req = type: "scriptId" target: scriptId line: line - 1 condition: condition else @print "Warning: script '" + script + "' was not loaded yet." escapedPath = script.replace(/([/\\.?*()^${}|[\]])/g, "\\$1") scriptPathRegex = "^(.*[\\/\\\\])?" + escapedPath + "$" req = type: "scriptRegExp" target: scriptPathRegex line: line - 1 condition: condition self.pause() self.client.setBreakpoint req, (err, res) -> if err self.error err unless silent else self.list 5 unless silent # Try load scriptId and line from response unless scriptId scriptId = res.script_id line = res.line + 1 # Remember this breakpoint even if scriptId is not resolved yet self.client.breakpoints.push id: res.breakpoint scriptId: scriptId script: (self.client.scripts[scriptId] or {}).name line: line condition: condition scriptReq: script self.resume() return return # Clear breakpoint Interface::clearBreakpoint = (script, line) -> return unless @requireConnection() ambiguous = undefined breakpoint = undefined index = undefined @client.breakpoints.some (bp, i) -> if bp.scriptId is script or bp.scriptReq is script or (bp.script and bp.script.indexOf(script) isnt -1) ambiguous = true unless util.isUndefined(index) if bp.line is line index = i breakpoint = bp.id true return @error("Script name is ambiguous") if ambiguous return @error("Script : " + script + " not found") if util.isUndefined(breakpoint) self = this req = breakpoint: breakpoint self.pause() self.client.clearBreakpoint req, (err, res) -> if err self.error err else self.client.breakpoints.splice index, 1 self.list 5 self.resume() return return # Show breakpoints Interface::breakpoints = -> return unless @requireConnection() @pause() self = this @client.listbreakpoints (err, res) -> if err self.error err else self.print res self.resume() return return # Pause child process Interface::pause_ = -> return unless @requireConnection() self = this cmd = "process._debugPause();" @pause() @client.reqFrameEval cmd, NO_FRAME, (err, res) -> if err self.error err else self.resume() return return # Kill child process Interface::kill = -> return unless @child @killChild() return # Activate debug repl Interface::repl = -> return unless @requireConnection() self = this self.print "Press Ctrl + C to leave debug repl" # Don't display any default messages listeners = @repl.rli.listeners("SIGINT").slice(0) @repl.rli.removeAllListeners "SIGINT" # Exit debug repl on Ctrl + C @repl.rli.once "SIGINT", -> # Restore all listeners process.nextTick -> listeners.forEach (listener) -> self.repl.rli.on "SIGINT", listener return return # Exit debug repl self.exitRepl() return # Set new @repl.eval = @debugEval.bind(this) @repl.context = {} # Swap history @history.control = @repl.rli.history @repl.rli.history = @history.debug @repl.rli.setPrompt "> " @repl.displayPrompt() return # Exit debug repl Interface::exitRepl = -> # Restore eval @repl.eval = @controlEval.bind(this) # Swap history @history.debug = @repl.rli.history @repl.rli.history = @history.control @repl.context = @context @repl.rli.setPrompt "debug> " @repl.displayPrompt() return # Quit Interface::quit = -> @killChild() process.exit 0 return # Kills child process Interface::killChild = -> if @child @child.kill() @child = null if @client # Save breakpoints @breakpoints = @client.breakpoints @client.destroy() @client = null return # Spawns child process (and restores breakpoints) Interface::trySpawn = (cb) -> # Connecting to remote debugger # `node debug localhost:5858` # TODO Do we really need to handle it? # `node debug -p pid` # TODO Do we really need to handle it? # Start debugger on custom port # `node debug --port=5858 app.js` # Restore breakpoints connectError = -> # If it's failed to connect 4 times then don't catch the next error client.removeListener "error", connectError if connectionAttempts >= 10 setTimeout attemptConnect, 500 return attemptConnect = -> ++connectionAttempts self.stdout.write "." client.connect port, host return self = this breakpoints = @breakpoints or [] port = exports.port host = "localhost" childArgs = @args @killChild() assert not @child if @args.length is 2 match = @args[1].match(/^([^:]+):(\d+)$/) if match host = match[1] port = parseInt(match[2], 10) @child = kill: -> else if @args.length is 3 if @args[1] is "-p" and /^\d+$/.test(@args[2]) @child = kill: -> process._debugProcess parseInt(@args[2], 10) else match = @args[1].match(/^--port=(\d+)$/) if match port = parseInt(match[1], 10) childArgs = ["--debug-brk=" + port].concat(@args.slice(2)) @child = spawn(process.execPath, childArgs) @child.stdout.on "data", @childPrint.bind(this) @child.stderr.on "data", @childPrint.bind(this) @pause() client = self.client = new Client() connectionAttempts = 0 client.once "ready", -> self.stdout.write " ok\n" breakpoints.forEach (bp) -> self.print "Restoring breakpoint " + bp.scriptReq + ":" + bp.line self.setBreakpoint bp.scriptReq, bp.line, bp.condition, true return client.on "close", -> self.pause() self.print "program terminated" self.resume() self.client = null self.killChild() return cb() if cb self.resume() return client.on "unhandledResponse", (res) -> self.pause() self.print "\nunhandled res:" + JSON.stringify(res) self.resume() return client.on "break", (res) -> self.handleBreak res.body return client.on "exception", (res) -> self.handleBreak res.body return client.on "error", connectError @child.stderr.once "data", -> setImmediate -> self.print "connecting to port " + port + "..", true attemptConnect() return return return
[ { "context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'SoCo'\n\n constructor: (layer, length) ->\n super(lay", "end": 211, "score": 0.9880164861679077, "start": 207, "tag": "KEY", "value": "SoCo" } ]
lib/psd/layer_info/solid_color.coffee
aleczratiu/psd.js
0
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' Color = require '../color.coffee' module.exports = class SolidColor extends LayerInfo @shouldParse: (key) -> key is 'SoCo' constructor: (layer, length) -> super(layer, length) @clr = [0, 0, 0] parse: -> @file.seek 4, true @data = new Descriptor(@file).parse() c = @colorData() if @data['Clr '].class.id == 'RGBC' @clr = [Math.round(c['Rd ']), Math.round(c['Grn ']), Math.round(c['Bl '])] else @clr = Color.cmykToRgb(2.55 * c['Cyn '], 2.55 * c['Mgnt'], 2.55 * c['Ylw '], 2.55 * c['Blck']) colorData: -> @data['Clr '] color: -> @clr
48314
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' Color = require '../color.coffee' module.exports = class SolidColor extends LayerInfo @shouldParse: (key) -> key is '<KEY>' constructor: (layer, length) -> super(layer, length) @clr = [0, 0, 0] parse: -> @file.seek 4, true @data = new Descriptor(@file).parse() c = @colorData() if @data['Clr '].class.id == 'RGBC' @clr = [Math.round(c['Rd ']), Math.round(c['Grn ']), Math.round(c['Bl '])] else @clr = Color.cmykToRgb(2.55 * c['Cyn '], 2.55 * c['Mgnt'], 2.55 * c['Ylw '], 2.55 * c['Blck']) colorData: -> @data['Clr '] color: -> @clr
true
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' Color = require '../color.coffee' module.exports = class SolidColor extends LayerInfo @shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI' constructor: (layer, length) -> super(layer, length) @clr = [0, 0, 0] parse: -> @file.seek 4, true @data = new Descriptor(@file).parse() c = @colorData() if @data['Clr '].class.id == 'RGBC' @clr = [Math.round(c['Rd ']), Math.round(c['Grn ']), Math.round(c['Bl '])] else @clr = Color.cmykToRgb(2.55 * c['Cyn '], 2.55 * c['Mgnt'], 2.55 * c['Ylw '], 2.55 * c['Blck']) colorData: -> @data['Clr '] color: -> @clr
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 215, "score": 0.9998437166213989, "start": 198, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.com\n\n This so", "end": 231, "score": 0.9999313354492188, "start": 218, "tag": "EMAIL", "value": "ben@pxljs.com" }, { "context": " : () ->\n new RGBA(0.0,0.0,0.0,1.0)\n\n # **@MAGNOLIA** - Static function that returns the landlord's f", "end": 1414, "score": 0.7737295031547546, "start": 1409, "tag": "USERNAME", "value": "NOLIA" }, { "context": " @BLACK : () ->\n new RGB(0.0,0.0,0.0)\n\n # **@MAGNOLIA** - Static function that returns the landlord's f", "end": 2632, "score": 0.9965829849243164, "start": 2624, "tag": "USERNAME", "value": "MAGNOLIA" } ]
src/colour/colour.coffee
OniDaito/pxljs
1
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### # ## RGBA # The default colour - four floats 0 -> 1 for representing colour class RGBA DIM : 4 # **@constructor** # - **r** - A Number - Range 0 to 1 - Default 1.0 # - **g** - A Number - Range 0 to 1 - Default 1.0 # - **b** - A Number - Range 0 to 1 - Default 1.0 # - **a** - A Number - Range 0 to 1 - Default 1.0 constructor: (@r=1.0, @g=1.0, @b=1.0, @a=1.0) -> # Check for byte colours if @r > 1.0 @r = @r / 255 if @g > 1.0 @g = @g / 255 if @b > 1.0 @b = @b / 255 if @a > 1.0 @a = @a / 255 # **flatten** - used in the shader class to flatten the variables into a nice list # - returns a List of Number - Length 4 - [r,g,b,a] flatten: -> [@r,@g,@b,@a] # **@WHITE** - Static function that returns the default white # - returns a new RGBA @WHITE : () -> new RGBA(1.0,1.0,1.0,1.0) # **@BLACK** - Static function that returns all zeros including alpha (not black I guess?) # - returns a new RGBA @BLACK : () -> new RGBA(0.0,0.0,0.0,1.0) # **@MAGNOLIA** - Static function that returns the landlord's favourite # - returns a new RGBA @MAGNOLIA : () -> new RGBA(1.0,1.0,0.9,1.0) # **copy** # - **col** - a RGBA # - returns this copy: (col) -> @r = col.r @g = col.g @b = col.b @a = col.a @ # **clone** # - returns a new RGBA clone : () -> new RGBA @r,@g,@b,@a # ## RGB # Class for colours with no alpha class RGB DIM : 3 # **@constructor** # - **r** - A Number - Range 0 to 1 - Default 1.0 # - **g** - A Number - Range 0 to 1 - Default 1.0 # - **b** - A Number - Range 0 to 1 - Default 1.0 constructor: (@r, @g, @b) -> if @r > 1.0 @r = @r / 255 if @b > 1.0 @g = @g / 255 if @g > 1.0 @b = @b / 255 # **flatten** - used in the shader class to flatten the variables into a nice list # - returns a List of Number - Length 3 - [r,g,b] flatten: -> [@r,@g,@b] # **@WHITE** - Static function that returns the default white # - returns a new RGB @WHITE : () -> new RGB(1.0,1.0,1.0) # **@BLACK** - Static function that returns all zeros including alpha (not black I guess?) # - returns a new RGB @BLACK : () -> new RGB(0.0,0.0,0.0) # **@MAGNOLIA** - Static function that returns the landlord's favourite # - returns a new RGBA @MAGNOLIA : () -> new RGBA(1.0,1.0,0.9) # **copy** # - **col** - a RGBA # - returns this copy : (c) -> @r = c.r @g = c.g @b = c.b @ # **clone** # - returns a new RGBA clone : () -> new RGB @r,@g,@b module.exports = RGBA: RGBA RGB : RGB
172130
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### # ## RGBA # The default colour - four floats 0 -> 1 for representing colour class RGBA DIM : 4 # **@constructor** # - **r** - A Number - Range 0 to 1 - Default 1.0 # - **g** - A Number - Range 0 to 1 - Default 1.0 # - **b** - A Number - Range 0 to 1 - Default 1.0 # - **a** - A Number - Range 0 to 1 - Default 1.0 constructor: (@r=1.0, @g=1.0, @b=1.0, @a=1.0) -> # Check for byte colours if @r > 1.0 @r = @r / 255 if @g > 1.0 @g = @g / 255 if @b > 1.0 @b = @b / 255 if @a > 1.0 @a = @a / 255 # **flatten** - used in the shader class to flatten the variables into a nice list # - returns a List of Number - Length 4 - [r,g,b,a] flatten: -> [@r,@g,@b,@a] # **@WHITE** - Static function that returns the default white # - returns a new RGBA @WHITE : () -> new RGBA(1.0,1.0,1.0,1.0) # **@BLACK** - Static function that returns all zeros including alpha (not black I guess?) # - returns a new RGBA @BLACK : () -> new RGBA(0.0,0.0,0.0,1.0) # **@MAGNOLIA** - Static function that returns the landlord's favourite # - returns a new RGBA @MAGNOLIA : () -> new RGBA(1.0,1.0,0.9,1.0) # **copy** # - **col** - a RGBA # - returns this copy: (col) -> @r = col.r @g = col.g @b = col.b @a = col.a @ # **clone** # - returns a new RGBA clone : () -> new RGBA @r,@g,@b,@a # ## RGB # Class for colours with no alpha class RGB DIM : 3 # **@constructor** # - **r** - A Number - Range 0 to 1 - Default 1.0 # - **g** - A Number - Range 0 to 1 - Default 1.0 # - **b** - A Number - Range 0 to 1 - Default 1.0 constructor: (@r, @g, @b) -> if @r > 1.0 @r = @r / 255 if @b > 1.0 @g = @g / 255 if @g > 1.0 @b = @b / 255 # **flatten** - used in the shader class to flatten the variables into a nice list # - returns a List of Number - Length 3 - [r,g,b] flatten: -> [@r,@g,@b] # **@WHITE** - Static function that returns the default white # - returns a new RGB @WHITE : () -> new RGB(1.0,1.0,1.0) # **@BLACK** - Static function that returns all zeros including alpha (not black I guess?) # - returns a new RGB @BLACK : () -> new RGB(0.0,0.0,0.0) # **@MAGNOLIA** - Static function that returns the landlord's favourite # - returns a new RGBA @MAGNOLIA : () -> new RGBA(1.0,1.0,0.9) # **copy** # - **col** - a RGBA # - returns this copy : (c) -> @r = c.r @g = c.g @b = c.b @ # **clone** # - returns a new RGBA clone : () -> new RGB @r,@g,@b module.exports = RGBA: RGBA RGB : RGB
true
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### # ## RGBA # The default colour - four floats 0 -> 1 for representing colour class RGBA DIM : 4 # **@constructor** # - **r** - A Number - Range 0 to 1 - Default 1.0 # - **g** - A Number - Range 0 to 1 - Default 1.0 # - **b** - A Number - Range 0 to 1 - Default 1.0 # - **a** - A Number - Range 0 to 1 - Default 1.0 constructor: (@r=1.0, @g=1.0, @b=1.0, @a=1.0) -> # Check for byte colours if @r > 1.0 @r = @r / 255 if @g > 1.0 @g = @g / 255 if @b > 1.0 @b = @b / 255 if @a > 1.0 @a = @a / 255 # **flatten** - used in the shader class to flatten the variables into a nice list # - returns a List of Number - Length 4 - [r,g,b,a] flatten: -> [@r,@g,@b,@a] # **@WHITE** - Static function that returns the default white # - returns a new RGBA @WHITE : () -> new RGBA(1.0,1.0,1.0,1.0) # **@BLACK** - Static function that returns all zeros including alpha (not black I guess?) # - returns a new RGBA @BLACK : () -> new RGBA(0.0,0.0,0.0,1.0) # **@MAGNOLIA** - Static function that returns the landlord's favourite # - returns a new RGBA @MAGNOLIA : () -> new RGBA(1.0,1.0,0.9,1.0) # **copy** # - **col** - a RGBA # - returns this copy: (col) -> @r = col.r @g = col.g @b = col.b @a = col.a @ # **clone** # - returns a new RGBA clone : () -> new RGBA @r,@g,@b,@a # ## RGB # Class for colours with no alpha class RGB DIM : 3 # **@constructor** # - **r** - A Number - Range 0 to 1 - Default 1.0 # - **g** - A Number - Range 0 to 1 - Default 1.0 # - **b** - A Number - Range 0 to 1 - Default 1.0 constructor: (@r, @g, @b) -> if @r > 1.0 @r = @r / 255 if @b > 1.0 @g = @g / 255 if @g > 1.0 @b = @b / 255 # **flatten** - used in the shader class to flatten the variables into a nice list # - returns a List of Number - Length 3 - [r,g,b] flatten: -> [@r,@g,@b] # **@WHITE** - Static function that returns the default white # - returns a new RGB @WHITE : () -> new RGB(1.0,1.0,1.0) # **@BLACK** - Static function that returns all zeros including alpha (not black I guess?) # - returns a new RGB @BLACK : () -> new RGB(0.0,0.0,0.0) # **@MAGNOLIA** - Static function that returns the landlord's favourite # - returns a new RGBA @MAGNOLIA : () -> new RGBA(1.0,1.0,0.9) # **copy** # - **col** - a RGBA # - returns this copy : (c) -> @r = c.r @g = c.g @b = c.b @ # **clone** # - returns a new RGBA clone : () -> new RGB @r,@g,@b module.exports = RGBA: RGBA RGB : RGB
[ { "context": "ew_pages.sort (a, b) ->\n keyA = new Date(a.date_value)\n keyB = new Date(b.d", "end": 1521, "score": 0.8729104995727539, "start": 1517, "tag": "KEY", "value": "Date" }, { "context": " new Date(a.date_value)\n keyB = new Date(b.date_value)\n\n # Compare the 2 dat", "end": 1568, "score": 0.8040013313293457, "start": 1563, "tag": "KEY", "value": "Date(" }, { "context": "ate_value)\n keyB = new Date(b.date_value)\n\n # Compare the 2 dates\n ", "end": 1580, "score": 0.6985486149787903, "start": 1575, "tag": "KEY", "value": "value" } ]
html/coffee/blog_more.coffee
sebastianmaier/sebastianmaier.net
0
$(document).ready -> #Config template_id = '#news_template' more_button_id = '#next' date_id = "text_h5" picture_id = "picture-blog1" headline_id = "text_h2" teaser_id = "text_a" articles_per_page = 5 #Config End page_counter = 1 template = Hogan.compile($(template_id).html()) load_next_content = -> page_counter += 1 new_pages = [] Smooster.folder.id($(template_id).attr('data-a-id')) Smooster.folder.per_page(articles_per_page) Smooster.folder.page(page_counter) Smooster.folder.pages().done (result) -> $.each result, (index, value) -> Smooster.page.get(value.id, Smooster.folder._id).done (result) -> data = id: value.id url: result.url date_value: result.date date: Smooster.page.find_name_in_content_elements(result.contentElements, date_id).body picture: Smooster.page.find_name_in_content_elements(result.contentElements, picture_id).body headline: Smooster.page.find_name_in_content_elements(result.contentElements, headline_id).body teaser: Smooster.page.find_name_in_content_elements(result.contentElements, teaser_id).body new_pages.push(data) myTimer = setInterval(-> if $(result).length == $(new_pages).length clearInterval(myTimer); new_pages.sort (a, b) -> keyA = new Date(a.date_value) keyB = new Date(b.date_value) # Compare the 2 dates return 1 if keyA < keyB return -1 if keyA > keyB 0 $.each new_pages, (index, value) -> x = template.render(value) $('#blog_posts').append(x) , 10) $(more_button_id).click (event) => event.preventDefault() load_next_content()
198734
$(document).ready -> #Config template_id = '#news_template' more_button_id = '#next' date_id = "text_h5" picture_id = "picture-blog1" headline_id = "text_h2" teaser_id = "text_a" articles_per_page = 5 #Config End page_counter = 1 template = Hogan.compile($(template_id).html()) load_next_content = -> page_counter += 1 new_pages = [] Smooster.folder.id($(template_id).attr('data-a-id')) Smooster.folder.per_page(articles_per_page) Smooster.folder.page(page_counter) Smooster.folder.pages().done (result) -> $.each result, (index, value) -> Smooster.page.get(value.id, Smooster.folder._id).done (result) -> data = id: value.id url: result.url date_value: result.date date: Smooster.page.find_name_in_content_elements(result.contentElements, date_id).body picture: Smooster.page.find_name_in_content_elements(result.contentElements, picture_id).body headline: Smooster.page.find_name_in_content_elements(result.contentElements, headline_id).body teaser: Smooster.page.find_name_in_content_elements(result.contentElements, teaser_id).body new_pages.push(data) myTimer = setInterval(-> if $(result).length == $(new_pages).length clearInterval(myTimer); new_pages.sort (a, b) -> keyA = new <KEY>(a.date_value) keyB = new <KEY>b.date_<KEY>) # Compare the 2 dates return 1 if keyA < keyB return -1 if keyA > keyB 0 $.each new_pages, (index, value) -> x = template.render(value) $('#blog_posts').append(x) , 10) $(more_button_id).click (event) => event.preventDefault() load_next_content()
true
$(document).ready -> #Config template_id = '#news_template' more_button_id = '#next' date_id = "text_h5" picture_id = "picture-blog1" headline_id = "text_h2" teaser_id = "text_a" articles_per_page = 5 #Config End page_counter = 1 template = Hogan.compile($(template_id).html()) load_next_content = -> page_counter += 1 new_pages = [] Smooster.folder.id($(template_id).attr('data-a-id')) Smooster.folder.per_page(articles_per_page) Smooster.folder.page(page_counter) Smooster.folder.pages().done (result) -> $.each result, (index, value) -> Smooster.page.get(value.id, Smooster.folder._id).done (result) -> data = id: value.id url: result.url date_value: result.date date: Smooster.page.find_name_in_content_elements(result.contentElements, date_id).body picture: Smooster.page.find_name_in_content_elements(result.contentElements, picture_id).body headline: Smooster.page.find_name_in_content_elements(result.contentElements, headline_id).body teaser: Smooster.page.find_name_in_content_elements(result.contentElements, teaser_id).body new_pages.push(data) myTimer = setInterval(-> if $(result).length == $(new_pages).length clearInterval(myTimer); new_pages.sort (a, b) -> keyA = new PI:KEY:<KEY>END_PI(a.date_value) keyB = new PI:KEY:<KEY>END_PIb.date_PI:KEY:<KEY>END_PI) # Compare the 2 dates return 1 if keyA < keyB return -1 if keyA > keyB 0 $.each new_pages, (index, value) -> x = template.render(value) $('#blog_posts').append(x) , 10) $(more_button_id).click (event) => event.preventDefault() load_next_content()
[ { "context": " delay = 0\n id = 0\n delays = []\n seed = 'addbulb'\n for i in [0...parts.length*2]\n delays.p", "end": 3184, "score": 0.5461387634277344, "start": 3177, "tag": "PASSWORD", "value": "addbulb" } ]
project_code/prod/app/src/coffee/m11s/bulbs/bodyitems.coffee
kikko/devart-template
6
class mk.m11s.bulbs.BodyItems extends mk.m11s.base.BodyItems setupItems: -> mk.m11s.bulbs.BulbSocket.symbol = @assets.symbols.bulbs['bulb_socket'] @colorOff = @settings.palette.lightBlue @colorOn = @settings.palette.lightRed @bulbs = [] @addBodyBulbs() @addHeadBulb() @rope = null @mode = -1 @MODE_RAYS = 0 @MODE_CONNECT = 1 @MODE_FLOATING = 2 @MODE_DIGI = 3 @MODE_LIFT = 4 @NUM_MODES = 5 @bLockLight = false @lifModeIsDown = false clean: -> super() setBackgroundColor '#black' onMusicEvent : (evId) -> switch evId when 0 @addRope() break update : (dt) -> super dt switch @mode when @MODE_CONNECT for b in @bulbs b.updateConnections(dt) b.connectToNearbyBulbs(@bulbs) return when @MODE_RAYS b.updateRedBlink(dt) for b in @bulbs return when @MODE_FLOATING b.updateFloating(dt) for b in @bulbs return setupMode : -> switch @mode when @MODE_CONNECT @hidePerso() when @MODE_RAYS mk.m11s.bulbs.BulbSocket::wiggle = 0.2 b.setupRay() for b in @bulbs when @MODE_LIFT @onLightsOn(false) @bLockLight = true @lift (@lifModeIsDown=!@lifModeIsDown) when @MODE_FLOATING b.startFloating() for b in @bulbs when @MODE_DIGI @hidePerso() @addDigiBack() hidePerso : -> p.view.visible = false for p in @parts showPerso : -> p.view.visible = true for p in @parts cleanMode: -> switch @mode when @MODE_CONNECT @showPerso() b.removeConnections() for b in @bulbs B = mk.m11s.bulbs.Bulb B::maxConnection*=2 when @MODE_RAYS mk.m11s.bulbs.BulbSocket::wiggle = 1 b.removeRay() for b in @bulbs mk.m11s.bulbs.Bulb::maxRays *= 2 when @MODE_FLOATING b.stopFloating() for b in @bulbs mk.m11s.bulbs.Bulb::floatPower += 0.35 when @MODE_DIGI @showPerso() @removeDigiBack() lift: (up=true) -> canvas = document.getElementById('paperjs-canvas') dst = Math.min(window.viewport.height, window.innerHeight) dst *= 0.98 if !up then dst *= -1 backTween = new TWEEN.Tween({y:dst}) .to({y:0}, 2000) .easing( TWEEN.Easing.Quadratic.Out ) .onStart(-> mk.Scene::sfx.play 'liftIn' ) .onUpdate(-> canvas.style.top = @y+'px' ) .onComplete(=> @bLockLight = false @onLightsOff() ) tween = new TWEEN.Tween({y:0}) .to({y:-dst}, 2000) .chain(backTween) .onStart(-> mk.Scene::sfx.play 'liftOut' ) .easing( TWEEN.Easing.Quadratic.In ) .onUpdate(-> canvas.style.top = @y+'px' ).start window.currentTime addDigiBack: -> @digiback = new mk.m11s.bulbs.DigiBack @joints[NiTE.HEAD] @items.push @digiback removeDigiBack: -> db = @digiback db.hide => db.clean() @items.splice @items.indexOf(db),1 addBodyBulbs: -> parts = @getPartsExcluding ['head', 'torso', 'pelvis'] delay = 0 id = 0 delays = [] seed = 'addbulb' for i in [0...parts.length*2] delays.push (500*Math.random())*i + 500 for p in parts for i in [1..2] # delay++ did = Math.floor(rng(seed)*delays.length) delay = delays.splice(did,1)[0] do (p,i,delay) => delayed delay, => bulb = new mk.m11s.bulbs.Bulb p, i * 0.33, @colorOff, @colorOn, @bulbs.length @items.push bulb @bulbs.push bulb bulb.id = id++ mk.Scene::sfx.play 'bulbShow'+rngi(seed,1,2) return addHeadBulb: -> bulb = new mk.m11s.bulbs.Bulb @getPart('head'), 0, @colorOff, @colorOn, @bulbs.length @items.push bulb @bulbs.push bulb addRope: -> @rope = new mk.m11s.bulbs.Rope @getJoints([NiTE.LEFT_HAND, NiTE.RIGHT_HAND]), @settings.palette @rope.onLightsOff = @onLightsOn @rope.onLightsOn = @onLightsOff @items.push @rope mk.Scene::sfx.play 'ropeFalls' onLightsOn:(changeMode=true)=> if @bLockLight then return mk.Scene::sfx.play 'ropeGrabbed' setBackgroundColor '#fff' b.lightsOn() for b in @bulbs if @digiback @digiback.lightOn if changeMode @cleanMode() # if @mode is -1 then @mode = 3 # else @mode++ # @mode = @MODE_RAYS @mode++ # @mode = @MODE_FLOATING if @mode >= @NUM_MODES @mode = 0 @setupMode() @rope.yoyo @mode onLightsOff: => if @bLockLight then return mk.Scene::sfx.play 'ropeReleased' if @digiback @digiback.lightOff setBackgroundColor @settings.getHexColor 'background' b.lightsOff() for b in @bulbs
56745
class mk.m11s.bulbs.BodyItems extends mk.m11s.base.BodyItems setupItems: -> mk.m11s.bulbs.BulbSocket.symbol = @assets.symbols.bulbs['bulb_socket'] @colorOff = @settings.palette.lightBlue @colorOn = @settings.palette.lightRed @bulbs = [] @addBodyBulbs() @addHeadBulb() @rope = null @mode = -1 @MODE_RAYS = 0 @MODE_CONNECT = 1 @MODE_FLOATING = 2 @MODE_DIGI = 3 @MODE_LIFT = 4 @NUM_MODES = 5 @bLockLight = false @lifModeIsDown = false clean: -> super() setBackgroundColor '#black' onMusicEvent : (evId) -> switch evId when 0 @addRope() break update : (dt) -> super dt switch @mode when @MODE_CONNECT for b in @bulbs b.updateConnections(dt) b.connectToNearbyBulbs(@bulbs) return when @MODE_RAYS b.updateRedBlink(dt) for b in @bulbs return when @MODE_FLOATING b.updateFloating(dt) for b in @bulbs return setupMode : -> switch @mode when @MODE_CONNECT @hidePerso() when @MODE_RAYS mk.m11s.bulbs.BulbSocket::wiggle = 0.2 b.setupRay() for b in @bulbs when @MODE_LIFT @onLightsOn(false) @bLockLight = true @lift (@lifModeIsDown=!@lifModeIsDown) when @MODE_FLOATING b.startFloating() for b in @bulbs when @MODE_DIGI @hidePerso() @addDigiBack() hidePerso : -> p.view.visible = false for p in @parts showPerso : -> p.view.visible = true for p in @parts cleanMode: -> switch @mode when @MODE_CONNECT @showPerso() b.removeConnections() for b in @bulbs B = mk.m11s.bulbs.Bulb B::maxConnection*=2 when @MODE_RAYS mk.m11s.bulbs.BulbSocket::wiggle = 1 b.removeRay() for b in @bulbs mk.m11s.bulbs.Bulb::maxRays *= 2 when @MODE_FLOATING b.stopFloating() for b in @bulbs mk.m11s.bulbs.Bulb::floatPower += 0.35 when @MODE_DIGI @showPerso() @removeDigiBack() lift: (up=true) -> canvas = document.getElementById('paperjs-canvas') dst = Math.min(window.viewport.height, window.innerHeight) dst *= 0.98 if !up then dst *= -1 backTween = new TWEEN.Tween({y:dst}) .to({y:0}, 2000) .easing( TWEEN.Easing.Quadratic.Out ) .onStart(-> mk.Scene::sfx.play 'liftIn' ) .onUpdate(-> canvas.style.top = @y+'px' ) .onComplete(=> @bLockLight = false @onLightsOff() ) tween = new TWEEN.Tween({y:0}) .to({y:-dst}, 2000) .chain(backTween) .onStart(-> mk.Scene::sfx.play 'liftOut' ) .easing( TWEEN.Easing.Quadratic.In ) .onUpdate(-> canvas.style.top = @y+'px' ).start window.currentTime addDigiBack: -> @digiback = new mk.m11s.bulbs.DigiBack @joints[NiTE.HEAD] @items.push @digiback removeDigiBack: -> db = @digiback db.hide => db.clean() @items.splice @items.indexOf(db),1 addBodyBulbs: -> parts = @getPartsExcluding ['head', 'torso', 'pelvis'] delay = 0 id = 0 delays = [] seed = '<PASSWORD>' for i in [0...parts.length*2] delays.push (500*Math.random())*i + 500 for p in parts for i in [1..2] # delay++ did = Math.floor(rng(seed)*delays.length) delay = delays.splice(did,1)[0] do (p,i,delay) => delayed delay, => bulb = new mk.m11s.bulbs.Bulb p, i * 0.33, @colorOff, @colorOn, @bulbs.length @items.push bulb @bulbs.push bulb bulb.id = id++ mk.Scene::sfx.play 'bulbShow'+rngi(seed,1,2) return addHeadBulb: -> bulb = new mk.m11s.bulbs.Bulb @getPart('head'), 0, @colorOff, @colorOn, @bulbs.length @items.push bulb @bulbs.push bulb addRope: -> @rope = new mk.m11s.bulbs.Rope @getJoints([NiTE.LEFT_HAND, NiTE.RIGHT_HAND]), @settings.palette @rope.onLightsOff = @onLightsOn @rope.onLightsOn = @onLightsOff @items.push @rope mk.Scene::sfx.play 'ropeFalls' onLightsOn:(changeMode=true)=> if @bLockLight then return mk.Scene::sfx.play 'ropeGrabbed' setBackgroundColor '#fff' b.lightsOn() for b in @bulbs if @digiback @digiback.lightOn if changeMode @cleanMode() # if @mode is -1 then @mode = 3 # else @mode++ # @mode = @MODE_RAYS @mode++ # @mode = @MODE_FLOATING if @mode >= @NUM_MODES @mode = 0 @setupMode() @rope.yoyo @mode onLightsOff: => if @bLockLight then return mk.Scene::sfx.play 'ropeReleased' if @digiback @digiback.lightOff setBackgroundColor @settings.getHexColor 'background' b.lightsOff() for b in @bulbs
true
class mk.m11s.bulbs.BodyItems extends mk.m11s.base.BodyItems setupItems: -> mk.m11s.bulbs.BulbSocket.symbol = @assets.symbols.bulbs['bulb_socket'] @colorOff = @settings.palette.lightBlue @colorOn = @settings.palette.lightRed @bulbs = [] @addBodyBulbs() @addHeadBulb() @rope = null @mode = -1 @MODE_RAYS = 0 @MODE_CONNECT = 1 @MODE_FLOATING = 2 @MODE_DIGI = 3 @MODE_LIFT = 4 @NUM_MODES = 5 @bLockLight = false @lifModeIsDown = false clean: -> super() setBackgroundColor '#black' onMusicEvent : (evId) -> switch evId when 0 @addRope() break update : (dt) -> super dt switch @mode when @MODE_CONNECT for b in @bulbs b.updateConnections(dt) b.connectToNearbyBulbs(@bulbs) return when @MODE_RAYS b.updateRedBlink(dt) for b in @bulbs return when @MODE_FLOATING b.updateFloating(dt) for b in @bulbs return setupMode : -> switch @mode when @MODE_CONNECT @hidePerso() when @MODE_RAYS mk.m11s.bulbs.BulbSocket::wiggle = 0.2 b.setupRay() for b in @bulbs when @MODE_LIFT @onLightsOn(false) @bLockLight = true @lift (@lifModeIsDown=!@lifModeIsDown) when @MODE_FLOATING b.startFloating() for b in @bulbs when @MODE_DIGI @hidePerso() @addDigiBack() hidePerso : -> p.view.visible = false for p in @parts showPerso : -> p.view.visible = true for p in @parts cleanMode: -> switch @mode when @MODE_CONNECT @showPerso() b.removeConnections() for b in @bulbs B = mk.m11s.bulbs.Bulb B::maxConnection*=2 when @MODE_RAYS mk.m11s.bulbs.BulbSocket::wiggle = 1 b.removeRay() for b in @bulbs mk.m11s.bulbs.Bulb::maxRays *= 2 when @MODE_FLOATING b.stopFloating() for b in @bulbs mk.m11s.bulbs.Bulb::floatPower += 0.35 when @MODE_DIGI @showPerso() @removeDigiBack() lift: (up=true) -> canvas = document.getElementById('paperjs-canvas') dst = Math.min(window.viewport.height, window.innerHeight) dst *= 0.98 if !up then dst *= -1 backTween = new TWEEN.Tween({y:dst}) .to({y:0}, 2000) .easing( TWEEN.Easing.Quadratic.Out ) .onStart(-> mk.Scene::sfx.play 'liftIn' ) .onUpdate(-> canvas.style.top = @y+'px' ) .onComplete(=> @bLockLight = false @onLightsOff() ) tween = new TWEEN.Tween({y:0}) .to({y:-dst}, 2000) .chain(backTween) .onStart(-> mk.Scene::sfx.play 'liftOut' ) .easing( TWEEN.Easing.Quadratic.In ) .onUpdate(-> canvas.style.top = @y+'px' ).start window.currentTime addDigiBack: -> @digiback = new mk.m11s.bulbs.DigiBack @joints[NiTE.HEAD] @items.push @digiback removeDigiBack: -> db = @digiback db.hide => db.clean() @items.splice @items.indexOf(db),1 addBodyBulbs: -> parts = @getPartsExcluding ['head', 'torso', 'pelvis'] delay = 0 id = 0 delays = [] seed = 'PI:PASSWORD:<PASSWORD>END_PI' for i in [0...parts.length*2] delays.push (500*Math.random())*i + 500 for p in parts for i in [1..2] # delay++ did = Math.floor(rng(seed)*delays.length) delay = delays.splice(did,1)[0] do (p,i,delay) => delayed delay, => bulb = new mk.m11s.bulbs.Bulb p, i * 0.33, @colorOff, @colorOn, @bulbs.length @items.push bulb @bulbs.push bulb bulb.id = id++ mk.Scene::sfx.play 'bulbShow'+rngi(seed,1,2) return addHeadBulb: -> bulb = new mk.m11s.bulbs.Bulb @getPart('head'), 0, @colorOff, @colorOn, @bulbs.length @items.push bulb @bulbs.push bulb addRope: -> @rope = new mk.m11s.bulbs.Rope @getJoints([NiTE.LEFT_HAND, NiTE.RIGHT_HAND]), @settings.palette @rope.onLightsOff = @onLightsOn @rope.onLightsOn = @onLightsOff @items.push @rope mk.Scene::sfx.play 'ropeFalls' onLightsOn:(changeMode=true)=> if @bLockLight then return mk.Scene::sfx.play 'ropeGrabbed' setBackgroundColor '#fff' b.lightsOn() for b in @bulbs if @digiback @digiback.lightOn if changeMode @cleanMode() # if @mode is -1 then @mode = 3 # else @mode++ # @mode = @MODE_RAYS @mode++ # @mode = @MODE_FLOATING if @mode >= @NUM_MODES @mode = 0 @setupMode() @rope.yoyo @mode onLightsOff: => if @bLockLight then return mk.Scene::sfx.play 'ropeReleased' if @digiback @digiback.lightOff setBackgroundColor @settings.getHexColor 'background' b.lightsOff() for b in @bulbs
[ { "context": "ectedUser._id\n scope.permission.keys = (key._id for key in scope.selectedKeys)\n scope.perm", "end": 3217, "score": 0.8820520639419556, "start": 3215, "tag": "KEY", "value": "id" } ]
client/directives/permissionForm.coffee
valueflowquality/gi-security-update
0
angular.module('gi.security').directive 'permissionForm' , ['$q', '$timeout', '$http', '$filter', 'Resource', 'giUser', 'Permission' , ($q, $timeout, $http, $filter, Resource, User, Permission) -> restrict: 'E' templateUrl: 'gi-permissionForm.html' scope: permission: '=' submit: '&' destroy: '&' submitText: '@' link: (scope, elm, attrs) -> scope.resourceTypes = [] scope.keys = [] scope.selectedKeys = [] scope.users = [] scope.showDelete = true scope.showDeleteModal = false scope.restrictions = Permission.restrictions scope.$watch 'permission', (newVal, oldVal) -> refreshPermissionFields() scope.$watch 'selectedResourceType', (newVal, oldVal) -> if newVal?.name scope.selectedKeys = [] getRelatedKeys newVal.name pluralise = (str) -> if str? result = str.toLowerCase() suffix = 'y' if result.indexOf(suffix, result.length - suffix.length) isnt -1 result = result.substring(0, result.length - 1) + 'ies' else result += 's' result else str getRelatedKeys = (name) -> uri = '/api/' + pluralise(name) $http.get(uri).success (data) -> scope.selectedKeys = [] scope.keys = data angular.forEach scope.keys, (key) -> key.id = key._id getSelectedKeys() scope.deletePermission = -> scope.destroy {permission: scope.permission} scope.showDeleteModal = false scope.confirmDelete = -> scope.showDeleteModal = true getUsers = -> deferred = $q.defer() User.all (users) -> scope.users = users angular.forEach scope.users, (user) -> user.id = user._id deferred.resolve() return deferred.promise getResources = -> deferred = $q.defer() Resource.all().then (resources) -> scope.resourceTypes = resources angular.forEach scope.resourceTypes, (resource) -> resource.id = resource._id deferred.resolve() return deferred.promise getSelectedResourceType = () -> scope.selectedResourceType = {} if scope.permission if scope.permission.resourceType angular.forEach scope.resourceTypes, (resource) -> if resource.name is scope.permission.resourceType scope.selectedResourceType = resource getSelectedUser = () -> scope.selectedUser = {} if scope.permission if scope.permission.userId angular.forEach scope.users, (user) -> if user._id is scope.permission.userId scope.selectedUser = user getSelectedKeys = () -> scope.selectedKeys = [] if scope.permission and scope.permission.keys? scope.selectedKeys = $filter('filter')(scope.keys, (key) -> scope.permission.keys.indexOf(key._id) isnt -1 ) refreshPermissionFields = () -> $timeout getSelectedResourceType $timeout getSelectedUser $timeout getSelectedKeys scope.save = () -> if scope.permission scope.permission.userId = scope.selectedUser._id scope.permission.keys = (key._id for key in scope.selectedKeys) scope.permission.resourceType = scope.selectedResourceType.name scope.submit {permission: scope.permission} $q.all([getResources(), getUsers()]).then () -> refreshPermissionFields() ]
40862
angular.module('gi.security').directive 'permissionForm' , ['$q', '$timeout', '$http', '$filter', 'Resource', 'giUser', 'Permission' , ($q, $timeout, $http, $filter, Resource, User, Permission) -> restrict: 'E' templateUrl: 'gi-permissionForm.html' scope: permission: '=' submit: '&' destroy: '&' submitText: '@' link: (scope, elm, attrs) -> scope.resourceTypes = [] scope.keys = [] scope.selectedKeys = [] scope.users = [] scope.showDelete = true scope.showDeleteModal = false scope.restrictions = Permission.restrictions scope.$watch 'permission', (newVal, oldVal) -> refreshPermissionFields() scope.$watch 'selectedResourceType', (newVal, oldVal) -> if newVal?.name scope.selectedKeys = [] getRelatedKeys newVal.name pluralise = (str) -> if str? result = str.toLowerCase() suffix = 'y' if result.indexOf(suffix, result.length - suffix.length) isnt -1 result = result.substring(0, result.length - 1) + 'ies' else result += 's' result else str getRelatedKeys = (name) -> uri = '/api/' + pluralise(name) $http.get(uri).success (data) -> scope.selectedKeys = [] scope.keys = data angular.forEach scope.keys, (key) -> key.id = key._id getSelectedKeys() scope.deletePermission = -> scope.destroy {permission: scope.permission} scope.showDeleteModal = false scope.confirmDelete = -> scope.showDeleteModal = true getUsers = -> deferred = $q.defer() User.all (users) -> scope.users = users angular.forEach scope.users, (user) -> user.id = user._id deferred.resolve() return deferred.promise getResources = -> deferred = $q.defer() Resource.all().then (resources) -> scope.resourceTypes = resources angular.forEach scope.resourceTypes, (resource) -> resource.id = resource._id deferred.resolve() return deferred.promise getSelectedResourceType = () -> scope.selectedResourceType = {} if scope.permission if scope.permission.resourceType angular.forEach scope.resourceTypes, (resource) -> if resource.name is scope.permission.resourceType scope.selectedResourceType = resource getSelectedUser = () -> scope.selectedUser = {} if scope.permission if scope.permission.userId angular.forEach scope.users, (user) -> if user._id is scope.permission.userId scope.selectedUser = user getSelectedKeys = () -> scope.selectedKeys = [] if scope.permission and scope.permission.keys? scope.selectedKeys = $filter('filter')(scope.keys, (key) -> scope.permission.keys.indexOf(key._id) isnt -1 ) refreshPermissionFields = () -> $timeout getSelectedResourceType $timeout getSelectedUser $timeout getSelectedKeys scope.save = () -> if scope.permission scope.permission.userId = scope.selectedUser._id scope.permission.keys = (key._<KEY> for key in scope.selectedKeys) scope.permission.resourceType = scope.selectedResourceType.name scope.submit {permission: scope.permission} $q.all([getResources(), getUsers()]).then () -> refreshPermissionFields() ]
true
angular.module('gi.security').directive 'permissionForm' , ['$q', '$timeout', '$http', '$filter', 'Resource', 'giUser', 'Permission' , ($q, $timeout, $http, $filter, Resource, User, Permission) -> restrict: 'E' templateUrl: 'gi-permissionForm.html' scope: permission: '=' submit: '&' destroy: '&' submitText: '@' link: (scope, elm, attrs) -> scope.resourceTypes = [] scope.keys = [] scope.selectedKeys = [] scope.users = [] scope.showDelete = true scope.showDeleteModal = false scope.restrictions = Permission.restrictions scope.$watch 'permission', (newVal, oldVal) -> refreshPermissionFields() scope.$watch 'selectedResourceType', (newVal, oldVal) -> if newVal?.name scope.selectedKeys = [] getRelatedKeys newVal.name pluralise = (str) -> if str? result = str.toLowerCase() suffix = 'y' if result.indexOf(suffix, result.length - suffix.length) isnt -1 result = result.substring(0, result.length - 1) + 'ies' else result += 's' result else str getRelatedKeys = (name) -> uri = '/api/' + pluralise(name) $http.get(uri).success (data) -> scope.selectedKeys = [] scope.keys = data angular.forEach scope.keys, (key) -> key.id = key._id getSelectedKeys() scope.deletePermission = -> scope.destroy {permission: scope.permission} scope.showDeleteModal = false scope.confirmDelete = -> scope.showDeleteModal = true getUsers = -> deferred = $q.defer() User.all (users) -> scope.users = users angular.forEach scope.users, (user) -> user.id = user._id deferred.resolve() return deferred.promise getResources = -> deferred = $q.defer() Resource.all().then (resources) -> scope.resourceTypes = resources angular.forEach scope.resourceTypes, (resource) -> resource.id = resource._id deferred.resolve() return deferred.promise getSelectedResourceType = () -> scope.selectedResourceType = {} if scope.permission if scope.permission.resourceType angular.forEach scope.resourceTypes, (resource) -> if resource.name is scope.permission.resourceType scope.selectedResourceType = resource getSelectedUser = () -> scope.selectedUser = {} if scope.permission if scope.permission.userId angular.forEach scope.users, (user) -> if user._id is scope.permission.userId scope.selectedUser = user getSelectedKeys = () -> scope.selectedKeys = [] if scope.permission and scope.permission.keys? scope.selectedKeys = $filter('filter')(scope.keys, (key) -> scope.permission.keys.indexOf(key._id) isnt -1 ) refreshPermissionFields = () -> $timeout getSelectedResourceType $timeout getSelectedUser $timeout getSelectedKeys scope.save = () -> if scope.permission scope.permission.userId = scope.selectedUser._id scope.permission.keys = (key._PI:KEY:<KEY>END_PI for key in scope.selectedKeys) scope.permission.resourceType = scope.selectedResourceType.name scope.submit {permission: scope.permission} $q.all([getResources(), getUsers()]).then () -> refreshPermissionFields() ]
[ { "context": "cal\n\n@namespace Quo.Gestures\n@class Swipe\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\n", "end": 205, "score": 0.9998941421508789, "start": 184, "tag": "NAME", "value": "Javier Jimenez Villar" }, { "context": "ures\n@class Swipe\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\nQuo.Gestures.add\n", "end": 222, "score": 0.9999351501464844, "start": 207, "tag": "EMAIL", "value": "javi@tapquo.com" }, { "context": "@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\nQuo.Gestures.add\n name : \"", "end": 235, "score": 0.99724942445755, "start": 227, "tag": "USERNAME", "value": "@soyjavi" } ]
source/quo.gestures.swipe.coffee
lguzzon/QuoJS
558
### Quo Swipe Gestures: swipe, swiping, swipeLeft, swipeRight, swipeUp, swipeDown New gestures added: swipingHorizontal, swipingVertical @namespace Quo.Gestures @class Swipe @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi ### "use strict" Quo.Gestures.add name : "swipe" events : ["swipe", "swipeLeft", "swipeRight", "swipeUp", "swipeDown", "swiping", "swipingHorizontal", "swipingVertical"] handler : do (base = Quo.Gestures) -> GAP = Math.round(20 / window.devicePixelRatio) _target = null _start = null _start_axis = null _last = null start = (target, data) -> if data.length is 1 _target = target _start = data[0] _last = null move = (target, data) -> if data.length is 1 delta = x: (data[0].x - _start.x), y: (data[0].y - _start.y) is_first = _last is null _last = x: data[0].x, y: data[0].y, delta: delta _check(true, is_first) else _last = null cancel = end = (target, data) -> unless _last? if data.length >= 1 delta = x: data[0].x - _start.x y: data[0].y - _start.y _last = x: data[0].x y: data[0].y delta: delta if _last _check(false) _last = null _check = (moving, first_move = false) -> if moving if first_move then _start_axis = _getInitialAxis(_last.delta.x, _last.delta.y) if _start_axis isnt null base.trigger(_target, "swiping#{_start_axis}", _last) base.trigger(_target, "swiping", _last) else directions = [] if Math.abs(_last.delta.y) > GAP directions.push (if _last.delta.y < 0 then "Up" else "Down") else directions.push (if _last.delta.x < 0 then "Left" else "Right") if Math.abs(_last.delta.x) > GAP if directions.length base.trigger(_target, "swipe", _last) base.trigger(_target, "swipe#{direction}", _last) for direction in directions _getInitialAxis = (x, y) -> axis = null if Math.round(Math.abs(x / y)) >= 2 then axis = "Horizontal" else if Math.round(Math.abs(y / x)) >= 2 then axis = "Vertical" return axis start: start move: move end: end
26258
### Quo Swipe Gestures: swipe, swiping, swipeLeft, swipeRight, swipeUp, swipeDown New gestures added: swipingHorizontal, swipingVertical @namespace Quo.Gestures @class Swipe @author <NAME> <<EMAIL>> || @soyjavi ### "use strict" Quo.Gestures.add name : "swipe" events : ["swipe", "swipeLeft", "swipeRight", "swipeUp", "swipeDown", "swiping", "swipingHorizontal", "swipingVertical"] handler : do (base = Quo.Gestures) -> GAP = Math.round(20 / window.devicePixelRatio) _target = null _start = null _start_axis = null _last = null start = (target, data) -> if data.length is 1 _target = target _start = data[0] _last = null move = (target, data) -> if data.length is 1 delta = x: (data[0].x - _start.x), y: (data[0].y - _start.y) is_first = _last is null _last = x: data[0].x, y: data[0].y, delta: delta _check(true, is_first) else _last = null cancel = end = (target, data) -> unless _last? if data.length >= 1 delta = x: data[0].x - _start.x y: data[0].y - _start.y _last = x: data[0].x y: data[0].y delta: delta if _last _check(false) _last = null _check = (moving, first_move = false) -> if moving if first_move then _start_axis = _getInitialAxis(_last.delta.x, _last.delta.y) if _start_axis isnt null base.trigger(_target, "swiping#{_start_axis}", _last) base.trigger(_target, "swiping", _last) else directions = [] if Math.abs(_last.delta.y) > GAP directions.push (if _last.delta.y < 0 then "Up" else "Down") else directions.push (if _last.delta.x < 0 then "Left" else "Right") if Math.abs(_last.delta.x) > GAP if directions.length base.trigger(_target, "swipe", _last) base.trigger(_target, "swipe#{direction}", _last) for direction in directions _getInitialAxis = (x, y) -> axis = null if Math.round(Math.abs(x / y)) >= 2 then axis = "Horizontal" else if Math.round(Math.abs(y / x)) >= 2 then axis = "Vertical" return axis start: start move: move end: end
true
### Quo Swipe Gestures: swipe, swiping, swipeLeft, swipeRight, swipeUp, swipeDown New gestures added: swipingHorizontal, swipingVertical @namespace Quo.Gestures @class Swipe @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi ### "use strict" Quo.Gestures.add name : "swipe" events : ["swipe", "swipeLeft", "swipeRight", "swipeUp", "swipeDown", "swiping", "swipingHorizontal", "swipingVertical"] handler : do (base = Quo.Gestures) -> GAP = Math.round(20 / window.devicePixelRatio) _target = null _start = null _start_axis = null _last = null start = (target, data) -> if data.length is 1 _target = target _start = data[0] _last = null move = (target, data) -> if data.length is 1 delta = x: (data[0].x - _start.x), y: (data[0].y - _start.y) is_first = _last is null _last = x: data[0].x, y: data[0].y, delta: delta _check(true, is_first) else _last = null cancel = end = (target, data) -> unless _last? if data.length >= 1 delta = x: data[0].x - _start.x y: data[0].y - _start.y _last = x: data[0].x y: data[0].y delta: delta if _last _check(false) _last = null _check = (moving, first_move = false) -> if moving if first_move then _start_axis = _getInitialAxis(_last.delta.x, _last.delta.y) if _start_axis isnt null base.trigger(_target, "swiping#{_start_axis}", _last) base.trigger(_target, "swiping", _last) else directions = [] if Math.abs(_last.delta.y) > GAP directions.push (if _last.delta.y < 0 then "Up" else "Down") else directions.push (if _last.delta.x < 0 then "Left" else "Right") if Math.abs(_last.delta.x) > GAP if directions.length base.trigger(_target, "swipe", _last) base.trigger(_target, "swipe#{direction}", _last) for direction in directions _getInitialAxis = (x, y) -> axis = null if Math.round(Math.abs(x / y)) >= 2 then axis = "Horizontal" else if Math.round(Math.abs(y / x)) >= 2 then axis = "Vertical" return axis start: start move: move end: end
[ { "context": "# grunt-processhtml\n# https://github.com/dciccale/grunt-processhtml\n#\n# Copyright (c) 2013-2014 Den", "end": 49, "score": 0.9994943141937256, "start": 41, "tag": "USERNAME", "value": "dciccale" }, { "context": "cale/grunt-processhtml\n#\n# Copyright (c) 2013-2014 Denis Ciccale (@tdecs)\n# Licensed under the MIT license.\n# http", "end": 109, "score": 0.9998693466186523, "start": 96, "tag": "NAME", "value": "Denis Ciccale" }, { "context": "cesshtml\n#\n# Copyright (c) 2013-2014 Denis Ciccale (@tdecs)\n# Licensed under the MIT license.\n# https://gith", "end": 117, "score": 0.9996815323829651, "start": 110, "tag": "USERNAME", "value": "(@tdecs" }, { "context": "ensed under the MIT license.\n# https://github.com/dciccale/grunt-processhtml/blob/master/LICENSE-MIT\n\n\"use s", "end": 182, "score": 0.9992673993110657, "start": 174, "tag": "USERNAME", "value": "dciccale" }, { "context": " options:\n data:\n msg: \"hey\"\n test: \"text_$&_text\"\n files:\n", "end": 2907, "score": 0.6626526713371277, "start": 2904, "tag": "NAME", "value": "hey" } ]
Gruntfile.coffee
makovich/grunt-processhtml
0
# grunt-processhtml # https://github.com/dciccale/grunt-processhtml # # Copyright (c) 2013-2014 Denis Ciccale (@tdecs) # Licensed under the MIT license. # https://github.com/dciccale/grunt-processhtml/blob/master/LICENSE-MIT "use strict" module.exports = -> @initConfig jshint: all: ["tasks/**/*.js", "<%= nodeunit.tests %>"] options: jshintrc: ".jshintrc" processhtml: dev: options: data: message: "This is dev target" files: "test/fixtures/dev/index.processed.html": ["test/fixtures/index.html"] dist: options: process: true data: title: "My app" message: "This is dist target" files: "test/fixtures/dist/index.processed.html": ["test/fixtures/index.html"] custom: options: templateSettings: interpolate: /{{([\s\S]+?)}}/g data: message: "This has custom delimiters for the template" files: "test/fixtures/custom/custom.processed.html": ["test/fixtures/custom.html"] marker: options: commentMarker: 'process' data: message: "This uses a custom comment marker" files: "test/fixtures/commentMarker/commentMarker.processed.html": ["test/fixtures/commentMarker.html"] strip: options: strip: true files: "test/fixtures/strip/strip.processed.html": ["test/fixtures/strip.html"] inline: options: environment: null files: "test/fixtures/inline/inline.processed.html": ["test/fixtures/inline.html"] ### The following three tests are for describing multiple targets ### mult_one: files: "test/fixtures/multiple/mult_one.processed.html": ["test/fixtures/multiple.html"] mult_two: files: "test/fixtures/multiple/mult_two.processed.html": ["test/fixtures/multiple.html"] mult_three: files: "test/fixtures/multiple/mult_three.processed.html": ["test/fixtures/multiple.html"] include_js: files: "test/fixtures/include/include.processed.html": ["test/fixtures/include.html"] conditional_ie: files: "test/fixtures/conditional_ie/conditional_ie.processed.html": ["test/fixtures/conditional_ie.html"] recursive: options: recursive: true files: "test/fixtures/recursive/recursive.processed.html": ["test/fixtures/recursive.html"] custom_blocktype: options: customBlockTypes: ['test/fixtures/custom_blocktype.js'] files: "test/fixtures/custom_blocktype/custom_blocktype.processed.html": ["test/fixtures/custom_blocktype.html"] template: options: data: msg: "hey" test: "text_$&_text" files: "test/fixtures/template/template.processed.html": ["test/fixtures/template.html"] nodeunit: tests: ["test/*_test.js"] @loadTasks "tasks" @loadNpmTasks "grunt-contrib-jshint" @loadNpmTasks "grunt-contrib-nodeunit" @loadNpmTasks "grunt-release" @registerTask "test", ["processhtml", "nodeunit"] @registerTask "default", ["jshint", "test"]
155819
# grunt-processhtml # https://github.com/dciccale/grunt-processhtml # # Copyright (c) 2013-2014 <NAME> (@tdecs) # Licensed under the MIT license. # https://github.com/dciccale/grunt-processhtml/blob/master/LICENSE-MIT "use strict" module.exports = -> @initConfig jshint: all: ["tasks/**/*.js", "<%= nodeunit.tests %>"] options: jshintrc: ".jshintrc" processhtml: dev: options: data: message: "This is dev target" files: "test/fixtures/dev/index.processed.html": ["test/fixtures/index.html"] dist: options: process: true data: title: "My app" message: "This is dist target" files: "test/fixtures/dist/index.processed.html": ["test/fixtures/index.html"] custom: options: templateSettings: interpolate: /{{([\s\S]+?)}}/g data: message: "This has custom delimiters for the template" files: "test/fixtures/custom/custom.processed.html": ["test/fixtures/custom.html"] marker: options: commentMarker: 'process' data: message: "This uses a custom comment marker" files: "test/fixtures/commentMarker/commentMarker.processed.html": ["test/fixtures/commentMarker.html"] strip: options: strip: true files: "test/fixtures/strip/strip.processed.html": ["test/fixtures/strip.html"] inline: options: environment: null files: "test/fixtures/inline/inline.processed.html": ["test/fixtures/inline.html"] ### The following three tests are for describing multiple targets ### mult_one: files: "test/fixtures/multiple/mult_one.processed.html": ["test/fixtures/multiple.html"] mult_two: files: "test/fixtures/multiple/mult_two.processed.html": ["test/fixtures/multiple.html"] mult_three: files: "test/fixtures/multiple/mult_three.processed.html": ["test/fixtures/multiple.html"] include_js: files: "test/fixtures/include/include.processed.html": ["test/fixtures/include.html"] conditional_ie: files: "test/fixtures/conditional_ie/conditional_ie.processed.html": ["test/fixtures/conditional_ie.html"] recursive: options: recursive: true files: "test/fixtures/recursive/recursive.processed.html": ["test/fixtures/recursive.html"] custom_blocktype: options: customBlockTypes: ['test/fixtures/custom_blocktype.js'] files: "test/fixtures/custom_blocktype/custom_blocktype.processed.html": ["test/fixtures/custom_blocktype.html"] template: options: data: msg: "<NAME>" test: "text_$&_text" files: "test/fixtures/template/template.processed.html": ["test/fixtures/template.html"] nodeunit: tests: ["test/*_test.js"] @loadTasks "tasks" @loadNpmTasks "grunt-contrib-jshint" @loadNpmTasks "grunt-contrib-nodeunit" @loadNpmTasks "grunt-release" @registerTask "test", ["processhtml", "nodeunit"] @registerTask "default", ["jshint", "test"]
true
# grunt-processhtml # https://github.com/dciccale/grunt-processhtml # # Copyright (c) 2013-2014 PI:NAME:<NAME>END_PI (@tdecs) # Licensed under the MIT license. # https://github.com/dciccale/grunt-processhtml/blob/master/LICENSE-MIT "use strict" module.exports = -> @initConfig jshint: all: ["tasks/**/*.js", "<%= nodeunit.tests %>"] options: jshintrc: ".jshintrc" processhtml: dev: options: data: message: "This is dev target" files: "test/fixtures/dev/index.processed.html": ["test/fixtures/index.html"] dist: options: process: true data: title: "My app" message: "This is dist target" files: "test/fixtures/dist/index.processed.html": ["test/fixtures/index.html"] custom: options: templateSettings: interpolate: /{{([\s\S]+?)}}/g data: message: "This has custom delimiters for the template" files: "test/fixtures/custom/custom.processed.html": ["test/fixtures/custom.html"] marker: options: commentMarker: 'process' data: message: "This uses a custom comment marker" files: "test/fixtures/commentMarker/commentMarker.processed.html": ["test/fixtures/commentMarker.html"] strip: options: strip: true files: "test/fixtures/strip/strip.processed.html": ["test/fixtures/strip.html"] inline: options: environment: null files: "test/fixtures/inline/inline.processed.html": ["test/fixtures/inline.html"] ### The following three tests are for describing multiple targets ### mult_one: files: "test/fixtures/multiple/mult_one.processed.html": ["test/fixtures/multiple.html"] mult_two: files: "test/fixtures/multiple/mult_two.processed.html": ["test/fixtures/multiple.html"] mult_three: files: "test/fixtures/multiple/mult_three.processed.html": ["test/fixtures/multiple.html"] include_js: files: "test/fixtures/include/include.processed.html": ["test/fixtures/include.html"] conditional_ie: files: "test/fixtures/conditional_ie/conditional_ie.processed.html": ["test/fixtures/conditional_ie.html"] recursive: options: recursive: true files: "test/fixtures/recursive/recursive.processed.html": ["test/fixtures/recursive.html"] custom_blocktype: options: customBlockTypes: ['test/fixtures/custom_blocktype.js'] files: "test/fixtures/custom_blocktype/custom_blocktype.processed.html": ["test/fixtures/custom_blocktype.html"] template: options: data: msg: "PI:NAME:<NAME>END_PI" test: "text_$&_text" files: "test/fixtures/template/template.processed.html": ["test/fixtures/template.html"] nodeunit: tests: ["test/*_test.js"] @loadTasks "tasks" @loadNpmTasks "grunt-contrib-jshint" @loadNpmTasks "grunt-contrib-nodeunit" @loadNpmTasks "grunt-release" @registerTask "test", ["processhtml", "nodeunit"] @registerTask "default", ["jshint", "test"]
[ { "context": "###\n# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>\n# Copyright (C) 2014-2017 Jesús Es", "end": 43, "score": 0.9998846054077148, "start": 30, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>\n# Copyright (C) 2014-2017 Jesús Espino Garcia <j", "end": 57, "score": 0.9999236464500427, "start": 45, "tag": "EMAIL", "value": "niwi@niwi.nz" }, { "context": "ey Antukh <niwi@niwi.nz>\n# Copyright (C) 2014-2017 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014-2017 Da", "end": 104, "score": 0.999881386756897, "start": 85, "tag": "NAME", "value": "Jesús Espino Garcia" }, { "context": "z>\n# Copyright (C) 2014-2017 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014-2017 David Barragán Merino ", "end": 124, "score": 0.999926745891571, "start": 106, "tag": "EMAIL", "value": "jespinog@gmail.com" }, { "context": "cia <jespinog@gmail.com>\n# Copyright (C) 2014-2017 David Barragán Merino <bameda@dbarragan.com>\n# Copyright (C) 2014-2017 ", "end": 173, "score": 0.9998911023139954, "start": 152, "tag": "NAME", "value": "David Barragán Merino" }, { "context": "\n# Copyright (C) 2014-2017 David Barragán Merino <bameda@dbarragan.com>\n# Copyright (C) 2014-2017 Alejandro Alonso <alej", "end": 195, "score": 0.9999308586120605, "start": 175, "tag": "EMAIL", "value": "bameda@dbarragan.com" }, { "context": "o <bameda@dbarragan.com>\n# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>\n# Copyright (C) 2", "end": 239, "score": 0.999889075756073, "start": 223, "tag": "NAME", "value": "Alejandro Alonso" }, { "context": ".com>\n# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>\n# Copyright (C) 2014-2017 Juan Francisco Alcánta", "end": 270, "score": 0.9999247193336487, "start": 241, "tag": "EMAIL", "value": "alejandro.alonso@kaleidos.net" }, { "context": "dro.alonso@kaleidos.net>\n# Copyright (C) 2014-2017 Juan Francisco Alcántara <juanfran.alcantara@kaleidos.net>\n# Copyright (C)", "end": 322, "score": 0.9998888373374939, "start": 298, "tag": "NAME", "value": "Juan Francisco Alcántara" }, { "context": "Copyright (C) 2014-2017 Juan Francisco Alcántara <juanfran.alcantara@kaleidos.net>\n# Copyright (C) 2014-2017 Xavi Julian <xavier.ju", "end": 355, "score": 0.9999247193336487, "start": 324, "tag": "EMAIL", "value": "juanfran.alcantara@kaleidos.net" }, { "context": ".alcantara@kaleidos.net>\n# Copyright (C) 2014-2017 Xavi Julian <xavier.julian@kaleidos.net>\n#\n# This program is ", "end": 394, "score": 0.9998823404312134, "start": 383, "tag": "NAME", "value": "Xavi Julian" }, { "context": "eidos.net>\n# Copyright (C) 2014-2017 Xavi Julian <xavier.julian@kaleidos.net>\n#\n# This program is free software: you can redis", "end": 422, "score": 0.9999231696128845, "start": 396, "tag": "EMAIL", "value": "xavier.julian@kaleidos.net" } ]
app/coffee/modules/common/sections.coffee
threefoldtech/Threefold-Circles-front
0
### # Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014-2017 David Barragán Merino <bameda@dbarragan.com> # Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net> # Copyright (C) 2014-2017 Juan Francisco Alcántara <juanfran.alcantara@kaleidos.net> # Copyright (C) 2014-2017 Xavi Julian <xavier.julian@kaleidos.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/common/sections.coffee ### module = angular.module("taigaCommon") class SectionsService extends taiga.Service @.$inject = ["$translate", "tgCurrentUserService"] SECTIONS = { 1: {id: 1, title: 'TIMELINE', path:'timeline', enabled: ''} 2: {id: 2, title: 'EPICS', path:'epics', enabled: 'is_epics_activated'} 3: {id: 3, title: 'BACKLOG', path:'backlog', enabled: 'is_backlog_activated'} 4: {id: 4, title: 'KANBAN', path:'kanban', enabled: 'is_kanban_activated'} 5: {id: 5, title: 'ISSUES', path:'issues', enabled: 'is_issues_activated'} 6: {id: 6, title: 'WIKI', path:'wiki', enabled: 'is_wiki_activated'} } constructor: (@translate, @currentUserService) -> super() _.map(SECTIONS, (x) => x.title = @translate.instant("PROJECT.SECTION.#{x.title}")) list: () -> return SECTIONS getPath: (projectSlug, sectionId) -> defaultHomePage = "timeline" projects = @currentUserService.projects?.get("all") if not projects return defaultHomePage project = projects.find (p) -> return p.get('slug') == projectSlug if not project return defaultHomePage if not sectionId sectionId = project.get('my_homepage') section = _.find(SECTIONS, {"id": sectionId}) if !section or project?.get(section.enabled) is not true return defaultHomePage return section.path module.service("$tgSections", SectionsService)
152943
### # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/common/sections.coffee ### module = angular.module("taigaCommon") class SectionsService extends taiga.Service @.$inject = ["$translate", "tgCurrentUserService"] SECTIONS = { 1: {id: 1, title: 'TIMELINE', path:'timeline', enabled: ''} 2: {id: 2, title: 'EPICS', path:'epics', enabled: 'is_epics_activated'} 3: {id: 3, title: 'BACKLOG', path:'backlog', enabled: 'is_backlog_activated'} 4: {id: 4, title: 'KANBAN', path:'kanban', enabled: 'is_kanban_activated'} 5: {id: 5, title: 'ISSUES', path:'issues', enabled: 'is_issues_activated'} 6: {id: 6, title: 'WIKI', path:'wiki', enabled: 'is_wiki_activated'} } constructor: (@translate, @currentUserService) -> super() _.map(SECTIONS, (x) => x.title = @translate.instant("PROJECT.SECTION.#{x.title}")) list: () -> return SECTIONS getPath: (projectSlug, sectionId) -> defaultHomePage = "timeline" projects = @currentUserService.projects?.get("all") if not projects return defaultHomePage project = projects.find (p) -> return p.get('slug') == projectSlug if not project return defaultHomePage if not sectionId sectionId = project.get('my_homepage') section = _.find(SECTIONS, {"id": sectionId}) if !section or project?.get(section.enabled) is not true return defaultHomePage return section.path module.service("$tgSections", SectionsService)
true
### # Copyright (C) 2014-2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014-2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014-2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014-2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014-2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014-2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/common/sections.coffee ### module = angular.module("taigaCommon") class SectionsService extends taiga.Service @.$inject = ["$translate", "tgCurrentUserService"] SECTIONS = { 1: {id: 1, title: 'TIMELINE', path:'timeline', enabled: ''} 2: {id: 2, title: 'EPICS', path:'epics', enabled: 'is_epics_activated'} 3: {id: 3, title: 'BACKLOG', path:'backlog', enabled: 'is_backlog_activated'} 4: {id: 4, title: 'KANBAN', path:'kanban', enabled: 'is_kanban_activated'} 5: {id: 5, title: 'ISSUES', path:'issues', enabled: 'is_issues_activated'} 6: {id: 6, title: 'WIKI', path:'wiki', enabled: 'is_wiki_activated'} } constructor: (@translate, @currentUserService) -> super() _.map(SECTIONS, (x) => x.title = @translate.instant("PROJECT.SECTION.#{x.title}")) list: () -> return SECTIONS getPath: (projectSlug, sectionId) -> defaultHomePage = "timeline" projects = @currentUserService.projects?.get("all") if not projects return defaultHomePage project = projects.find (p) -> return p.get('slug') == projectSlug if not project return defaultHomePage if not sectionId sectionId = project.get('my_homepage') section = _.find(SECTIONS, {"id": sectionId}) if !section or project?.get(section.enabled) is not true return defaultHomePage return section.path module.service("$tgSections", SectionsService)
[ { "context": "\n\t\t\"/account\": \"user_edit\"\n\t\t\"/forgot_password\": \"user_password\"\n\t\t\"/users/:id\": user_profile\n\t\t\"/users/:id/edit\"", "end": 4521, "score": 0.9991653561592102, "start": 4508, "tag": "PASSWORD", "value": "user_password" } ]
client/lib/router.coffee
ananta-IO/marq
1
(-> # PAGE_SUBS = # questions_answer: 'answerQuestionsReady' # questions_answered: 'answeredQuestionsReady' # questions_asked: 'askedQuestionsReady' # questions_page: 'singleQuestionReady' question = (id) -> Session.set('selectedQuestionId', id) 'questionsShow' Meteor.Router.add "/": "questionsAnswer" "/about": "about" "/answer": "questionsAnswer" "/ask": "questionsNew" "/faq": "faq" "/results": "questionsIndex" "/privacy": "privacy" "/profile": "questionsIndex" "/questions": "questionsIndex" "/questions/answer": "questionsAnswer" "/questions/new": "questionsNew" "/questions/:id": question "/settings": "settings" "/tos": "tos" "*": "404" Meteor.Router.filters isAdmin: (page) -> (if isAdmin(Meteor.user()) then page else "no_rights") # awaitSubscription: (page) -> # if Session.equals(PAGE_SUBS[page], true) then page else 'loading' # Meteor.Router.filter 'awaitSubscription', {only: ['questions_answer', 'questions_answered', 'questions_asked', 'questions_page']} Meteor.Router.filter "isAdmin", only: ["settings"] Meteor.startup -> Meteor.autorun -> # grab the current page from the router, so this re-runs every time it changes Meteor.Router.page() # console.log "-------- Request Start --------" # console.log "" # log this request with mixpanel, etc analyticsRequest() if analytics.track # console.log "track" # console.log window.location.href analytics.track "page viewed", href: window.location.href scrollToTop(0) )() ### START (-> # XXX: could we just work this out programmatically based on the name? # -- fix this along with the general problem of subscription mess PAGE_SUBS = posts_top: "topPostsReady" posts_new: "newPostsReady" posts_pending: "pendingPostsReady" posts_digest: "digestPostsReady" post_page: "singlePostReady" post_edit: "singlePostReady" comment_page: "commentReady" comment_reply: "commentReady" comment_edit: "commentReady" # specific router functions digest = (year, month, day) -> if typeof day is "undefined" # we can get into an infinite reactive loop with the subscription filter # if we keep setting the date even when it's barely changed Session.set "currentDate", new Date() if new Date() - Session.get("currentDate") > 60 * 1000 else Session.set "currentDate", new Date(year, month - 1, day) # a manual version of awaitSubscription; the sub can be loading # with a new day, but the data is already there (as the subscription is # for three days) if postsForSub.digestPosts().length is 0 and Session.equals(PAGE_SUBS["post_digest"], false) "loading" else "posts_digest" post = (id, commentId) -> Session.set "selectedPostId", id Session.set "scrollToCommentId", commentId if typeof commentId isnt "undefined" # XXX: should use the Session for these # on post page, we show the comment tree Session.set "showChildComments", true "post_page" post_edit = (id) -> Session.set "selectedPostId", id "post_edit" comment = (id) -> Session.set "selectedCommentId", id "comment_page" comment_reply = (id) -> Session.set "selectedCommentId", id "comment_reply" comment_edit = (id) -> Session.set "selectedCommentId", id "comment_edit" # XXX: do these two really not want to set it to undefined (or null)? user_profile = (id) -> Session.set "selectedUserId", id if typeof id isnt `undefined` "user_profile" user_edit = (id) -> Session.set "selectedUserId", id if typeof id isnt `undefined` "user_edit" # XXX: not sure if the '/' trailing routes are needed any more Meteor.Router.add "/": "posts_top" "/top": "posts_top" "/top/": "posts_top" "/top/:page": "posts_top" "/new": "posts_new" "/new/": "posts_new" "/new/:page": "posts_new" "/pending": "posts_pending" "/digest/:year/:month/:day": digest "/digest": digest "/digest/": digest "/test": "test" "/signin": "user_signin" "/signup": "user_signup" "/submit": "post_submit" "/invite": "no_invite" "/posts/deleted": "post_deleted" "/posts/:id/edit": post_edit "/posts/:id/comment/:comment_id": post "/posts/:id/": post "/posts/:id": post "/comments/deleted": "comment_deleted" "/comments/:id": comment "/comments/:id/reply": comment_reply "/comments/:id/edit": comment_edit "/settings": "settings" "/admin": "admin" "/categories": "categories" "/users": "users" "/account": "user_edit" "/forgot_password": "user_password" "/users/:id": user_profile "/users/:id/edit": user_edit "/:year/:month/:day": digest Meteor.Router.filters requireLogin: (page) -> if Meteor.loggingIn() "loading" else if Meteor.user() page else "user_signin" canView: (page) -> error = canView(Meteor.user(), true) return page if error is true # a problem.. make sure we are logged in return "loading" if Meteor.loggingIn() # otherwise the error tells us what to show. error canPost: (page) -> error = canPost(Meteor.user(), true) return page if error is true # a problem.. make sure we are logged in return "loading" if Meteor.loggingIn() # otherwise the error tells us what to show. error canEdit: (page) -> if page is "comment_edit" item = Comments.findOne(Session.get("selectedCommentId")) else item = Posts.findOne(Session.get("selectedPostId")) error = canEdit(Meteor.user(), item, true) return page if error is true # a problem.. make sure the item has loaded and we have logged in return "loading" if not item or Meteor.loggingIn() # otherwise the error tells us what to show. error isLoggedOut: (page) -> (if Meteor.user() then "already_logged_in" else page) isAdmin: (page) -> (if isAdmin(Meteor.user()) then page else "no_rights") awaitSubscription: (page) -> (if Session.equals(PAGE_SUBS[page], true) then page else "loading") # if the user is logged in but their profile isn't filled out enough requireProfile: (page) -> user = Meteor.user() if user and not Meteor.loggingIn() and not userProfileComplete(user) Session.set "selectedUserId", user._id "user_email" else page # if we are on a page that requires a post, as set in selectedPostId requirePost: (page) -> if Posts.findOne(Session.get("selectedPostId")) page else unless Session.get("postReady") "loading" else "not_found" # Meteor.Router.filter "requireProfile" Meteor.Router.filter "awaitSubscription", only: ["posts_top", "posts_new", "posts_pending"] Meteor.Router.filter "requireLogin", only: ["comment_reply", "post_submit"] Meteor.Router.filter "canView", only: ["posts_top", "posts_new", "posts_digest"] Meteor.Router.filter "isLoggedOut", only: ["user_signin", "user_signup"] Meteor.Router.filter "canPost", only: ["posts_pending", "comment_reply", "post_submit"] Meteor.Router.filter "canEdit", only: ["post_edit", "comment_edit"] Meteor.Router.filter "requirePost", only: ["post_page", "post_edit"] Meteor.Router.filter "isAdmin", only: ["posts_pending", "users", "settings", "categories", "admin"] Meteor.startup -> Meteor.autorun -> # grab the current page from the router, so this re-runs every time it changes Meteor.Router.page() console.log "------ Request start --------" # openedComments is an Array that tracks which comments # have been expanded by the user, to make sure they stay expanded Session.set "openedComments", null Session.set "requestTimestamp", new Date() # currentScroll stores the position of the user in the page Session.set "currentScroll", null document.title = getSetting("title") # set all errors who have already been seen to not show anymore clearSeenErrors() # log this request with mixpanel, etc analyticsRequest() # if there are any pending events, log them too if eventBuffer = Session.get("eventBuffer") _.each eventBuffer, (e) -> console.log "in buffer: ", e trackEvent e.event, e.properties )() END ###
133441
(-> # PAGE_SUBS = # questions_answer: 'answerQuestionsReady' # questions_answered: 'answeredQuestionsReady' # questions_asked: 'askedQuestionsReady' # questions_page: 'singleQuestionReady' question = (id) -> Session.set('selectedQuestionId', id) 'questionsShow' Meteor.Router.add "/": "questionsAnswer" "/about": "about" "/answer": "questionsAnswer" "/ask": "questionsNew" "/faq": "faq" "/results": "questionsIndex" "/privacy": "privacy" "/profile": "questionsIndex" "/questions": "questionsIndex" "/questions/answer": "questionsAnswer" "/questions/new": "questionsNew" "/questions/:id": question "/settings": "settings" "/tos": "tos" "*": "404" Meteor.Router.filters isAdmin: (page) -> (if isAdmin(Meteor.user()) then page else "no_rights") # awaitSubscription: (page) -> # if Session.equals(PAGE_SUBS[page], true) then page else 'loading' # Meteor.Router.filter 'awaitSubscription', {only: ['questions_answer', 'questions_answered', 'questions_asked', 'questions_page']} Meteor.Router.filter "isAdmin", only: ["settings"] Meteor.startup -> Meteor.autorun -> # grab the current page from the router, so this re-runs every time it changes Meteor.Router.page() # console.log "-------- Request Start --------" # console.log "" # log this request with mixpanel, etc analyticsRequest() if analytics.track # console.log "track" # console.log window.location.href analytics.track "page viewed", href: window.location.href scrollToTop(0) )() ### START (-> # XXX: could we just work this out programmatically based on the name? # -- fix this along with the general problem of subscription mess PAGE_SUBS = posts_top: "topPostsReady" posts_new: "newPostsReady" posts_pending: "pendingPostsReady" posts_digest: "digestPostsReady" post_page: "singlePostReady" post_edit: "singlePostReady" comment_page: "commentReady" comment_reply: "commentReady" comment_edit: "commentReady" # specific router functions digest = (year, month, day) -> if typeof day is "undefined" # we can get into an infinite reactive loop with the subscription filter # if we keep setting the date even when it's barely changed Session.set "currentDate", new Date() if new Date() - Session.get("currentDate") > 60 * 1000 else Session.set "currentDate", new Date(year, month - 1, day) # a manual version of awaitSubscription; the sub can be loading # with a new day, but the data is already there (as the subscription is # for three days) if postsForSub.digestPosts().length is 0 and Session.equals(PAGE_SUBS["post_digest"], false) "loading" else "posts_digest" post = (id, commentId) -> Session.set "selectedPostId", id Session.set "scrollToCommentId", commentId if typeof commentId isnt "undefined" # XXX: should use the Session for these # on post page, we show the comment tree Session.set "showChildComments", true "post_page" post_edit = (id) -> Session.set "selectedPostId", id "post_edit" comment = (id) -> Session.set "selectedCommentId", id "comment_page" comment_reply = (id) -> Session.set "selectedCommentId", id "comment_reply" comment_edit = (id) -> Session.set "selectedCommentId", id "comment_edit" # XXX: do these two really not want to set it to undefined (or null)? user_profile = (id) -> Session.set "selectedUserId", id if typeof id isnt `undefined` "user_profile" user_edit = (id) -> Session.set "selectedUserId", id if typeof id isnt `undefined` "user_edit" # XXX: not sure if the '/' trailing routes are needed any more Meteor.Router.add "/": "posts_top" "/top": "posts_top" "/top/": "posts_top" "/top/:page": "posts_top" "/new": "posts_new" "/new/": "posts_new" "/new/:page": "posts_new" "/pending": "posts_pending" "/digest/:year/:month/:day": digest "/digest": digest "/digest/": digest "/test": "test" "/signin": "user_signin" "/signup": "user_signup" "/submit": "post_submit" "/invite": "no_invite" "/posts/deleted": "post_deleted" "/posts/:id/edit": post_edit "/posts/:id/comment/:comment_id": post "/posts/:id/": post "/posts/:id": post "/comments/deleted": "comment_deleted" "/comments/:id": comment "/comments/:id/reply": comment_reply "/comments/:id/edit": comment_edit "/settings": "settings" "/admin": "admin" "/categories": "categories" "/users": "users" "/account": "user_edit" "/forgot_password": "<PASSWORD>" "/users/:id": user_profile "/users/:id/edit": user_edit "/:year/:month/:day": digest Meteor.Router.filters requireLogin: (page) -> if Meteor.loggingIn() "loading" else if Meteor.user() page else "user_signin" canView: (page) -> error = canView(Meteor.user(), true) return page if error is true # a problem.. make sure we are logged in return "loading" if Meteor.loggingIn() # otherwise the error tells us what to show. error canPost: (page) -> error = canPost(Meteor.user(), true) return page if error is true # a problem.. make sure we are logged in return "loading" if Meteor.loggingIn() # otherwise the error tells us what to show. error canEdit: (page) -> if page is "comment_edit" item = Comments.findOne(Session.get("selectedCommentId")) else item = Posts.findOne(Session.get("selectedPostId")) error = canEdit(Meteor.user(), item, true) return page if error is true # a problem.. make sure the item has loaded and we have logged in return "loading" if not item or Meteor.loggingIn() # otherwise the error tells us what to show. error isLoggedOut: (page) -> (if Meteor.user() then "already_logged_in" else page) isAdmin: (page) -> (if isAdmin(Meteor.user()) then page else "no_rights") awaitSubscription: (page) -> (if Session.equals(PAGE_SUBS[page], true) then page else "loading") # if the user is logged in but their profile isn't filled out enough requireProfile: (page) -> user = Meteor.user() if user and not Meteor.loggingIn() and not userProfileComplete(user) Session.set "selectedUserId", user._id "user_email" else page # if we are on a page that requires a post, as set in selectedPostId requirePost: (page) -> if Posts.findOne(Session.get("selectedPostId")) page else unless Session.get("postReady") "loading" else "not_found" # Meteor.Router.filter "requireProfile" Meteor.Router.filter "awaitSubscription", only: ["posts_top", "posts_new", "posts_pending"] Meteor.Router.filter "requireLogin", only: ["comment_reply", "post_submit"] Meteor.Router.filter "canView", only: ["posts_top", "posts_new", "posts_digest"] Meteor.Router.filter "isLoggedOut", only: ["user_signin", "user_signup"] Meteor.Router.filter "canPost", only: ["posts_pending", "comment_reply", "post_submit"] Meteor.Router.filter "canEdit", only: ["post_edit", "comment_edit"] Meteor.Router.filter "requirePost", only: ["post_page", "post_edit"] Meteor.Router.filter "isAdmin", only: ["posts_pending", "users", "settings", "categories", "admin"] Meteor.startup -> Meteor.autorun -> # grab the current page from the router, so this re-runs every time it changes Meteor.Router.page() console.log "------ Request start --------" # openedComments is an Array that tracks which comments # have been expanded by the user, to make sure they stay expanded Session.set "openedComments", null Session.set "requestTimestamp", new Date() # currentScroll stores the position of the user in the page Session.set "currentScroll", null document.title = getSetting("title") # set all errors who have already been seen to not show anymore clearSeenErrors() # log this request with mixpanel, etc analyticsRequest() # if there are any pending events, log them too if eventBuffer = Session.get("eventBuffer") _.each eventBuffer, (e) -> console.log "in buffer: ", e trackEvent e.event, e.properties )() END ###
true
(-> # PAGE_SUBS = # questions_answer: 'answerQuestionsReady' # questions_answered: 'answeredQuestionsReady' # questions_asked: 'askedQuestionsReady' # questions_page: 'singleQuestionReady' question = (id) -> Session.set('selectedQuestionId', id) 'questionsShow' Meteor.Router.add "/": "questionsAnswer" "/about": "about" "/answer": "questionsAnswer" "/ask": "questionsNew" "/faq": "faq" "/results": "questionsIndex" "/privacy": "privacy" "/profile": "questionsIndex" "/questions": "questionsIndex" "/questions/answer": "questionsAnswer" "/questions/new": "questionsNew" "/questions/:id": question "/settings": "settings" "/tos": "tos" "*": "404" Meteor.Router.filters isAdmin: (page) -> (if isAdmin(Meteor.user()) then page else "no_rights") # awaitSubscription: (page) -> # if Session.equals(PAGE_SUBS[page], true) then page else 'loading' # Meteor.Router.filter 'awaitSubscription', {only: ['questions_answer', 'questions_answered', 'questions_asked', 'questions_page']} Meteor.Router.filter "isAdmin", only: ["settings"] Meteor.startup -> Meteor.autorun -> # grab the current page from the router, so this re-runs every time it changes Meteor.Router.page() # console.log "-------- Request Start --------" # console.log "" # log this request with mixpanel, etc analyticsRequest() if analytics.track # console.log "track" # console.log window.location.href analytics.track "page viewed", href: window.location.href scrollToTop(0) )() ### START (-> # XXX: could we just work this out programmatically based on the name? # -- fix this along with the general problem of subscription mess PAGE_SUBS = posts_top: "topPostsReady" posts_new: "newPostsReady" posts_pending: "pendingPostsReady" posts_digest: "digestPostsReady" post_page: "singlePostReady" post_edit: "singlePostReady" comment_page: "commentReady" comment_reply: "commentReady" comment_edit: "commentReady" # specific router functions digest = (year, month, day) -> if typeof day is "undefined" # we can get into an infinite reactive loop with the subscription filter # if we keep setting the date even when it's barely changed Session.set "currentDate", new Date() if new Date() - Session.get("currentDate") > 60 * 1000 else Session.set "currentDate", new Date(year, month - 1, day) # a manual version of awaitSubscription; the sub can be loading # with a new day, but the data is already there (as the subscription is # for three days) if postsForSub.digestPosts().length is 0 and Session.equals(PAGE_SUBS["post_digest"], false) "loading" else "posts_digest" post = (id, commentId) -> Session.set "selectedPostId", id Session.set "scrollToCommentId", commentId if typeof commentId isnt "undefined" # XXX: should use the Session for these # on post page, we show the comment tree Session.set "showChildComments", true "post_page" post_edit = (id) -> Session.set "selectedPostId", id "post_edit" comment = (id) -> Session.set "selectedCommentId", id "comment_page" comment_reply = (id) -> Session.set "selectedCommentId", id "comment_reply" comment_edit = (id) -> Session.set "selectedCommentId", id "comment_edit" # XXX: do these two really not want to set it to undefined (or null)? user_profile = (id) -> Session.set "selectedUserId", id if typeof id isnt `undefined` "user_profile" user_edit = (id) -> Session.set "selectedUserId", id if typeof id isnt `undefined` "user_edit" # XXX: not sure if the '/' trailing routes are needed any more Meteor.Router.add "/": "posts_top" "/top": "posts_top" "/top/": "posts_top" "/top/:page": "posts_top" "/new": "posts_new" "/new/": "posts_new" "/new/:page": "posts_new" "/pending": "posts_pending" "/digest/:year/:month/:day": digest "/digest": digest "/digest/": digest "/test": "test" "/signin": "user_signin" "/signup": "user_signup" "/submit": "post_submit" "/invite": "no_invite" "/posts/deleted": "post_deleted" "/posts/:id/edit": post_edit "/posts/:id/comment/:comment_id": post "/posts/:id/": post "/posts/:id": post "/comments/deleted": "comment_deleted" "/comments/:id": comment "/comments/:id/reply": comment_reply "/comments/:id/edit": comment_edit "/settings": "settings" "/admin": "admin" "/categories": "categories" "/users": "users" "/account": "user_edit" "/forgot_password": "PI:PASSWORD:<PASSWORD>END_PI" "/users/:id": user_profile "/users/:id/edit": user_edit "/:year/:month/:day": digest Meteor.Router.filters requireLogin: (page) -> if Meteor.loggingIn() "loading" else if Meteor.user() page else "user_signin" canView: (page) -> error = canView(Meteor.user(), true) return page if error is true # a problem.. make sure we are logged in return "loading" if Meteor.loggingIn() # otherwise the error tells us what to show. error canPost: (page) -> error = canPost(Meteor.user(), true) return page if error is true # a problem.. make sure we are logged in return "loading" if Meteor.loggingIn() # otherwise the error tells us what to show. error canEdit: (page) -> if page is "comment_edit" item = Comments.findOne(Session.get("selectedCommentId")) else item = Posts.findOne(Session.get("selectedPostId")) error = canEdit(Meteor.user(), item, true) return page if error is true # a problem.. make sure the item has loaded and we have logged in return "loading" if not item or Meteor.loggingIn() # otherwise the error tells us what to show. error isLoggedOut: (page) -> (if Meteor.user() then "already_logged_in" else page) isAdmin: (page) -> (if isAdmin(Meteor.user()) then page else "no_rights") awaitSubscription: (page) -> (if Session.equals(PAGE_SUBS[page], true) then page else "loading") # if the user is logged in but their profile isn't filled out enough requireProfile: (page) -> user = Meteor.user() if user and not Meteor.loggingIn() and not userProfileComplete(user) Session.set "selectedUserId", user._id "user_email" else page # if we are on a page that requires a post, as set in selectedPostId requirePost: (page) -> if Posts.findOne(Session.get("selectedPostId")) page else unless Session.get("postReady") "loading" else "not_found" # Meteor.Router.filter "requireProfile" Meteor.Router.filter "awaitSubscription", only: ["posts_top", "posts_new", "posts_pending"] Meteor.Router.filter "requireLogin", only: ["comment_reply", "post_submit"] Meteor.Router.filter "canView", only: ["posts_top", "posts_new", "posts_digest"] Meteor.Router.filter "isLoggedOut", only: ["user_signin", "user_signup"] Meteor.Router.filter "canPost", only: ["posts_pending", "comment_reply", "post_submit"] Meteor.Router.filter "canEdit", only: ["post_edit", "comment_edit"] Meteor.Router.filter "requirePost", only: ["post_page", "post_edit"] Meteor.Router.filter "isAdmin", only: ["posts_pending", "users", "settings", "categories", "admin"] Meteor.startup -> Meteor.autorun -> # grab the current page from the router, so this re-runs every time it changes Meteor.Router.page() console.log "------ Request start --------" # openedComments is an Array that tracks which comments # have been expanded by the user, to make sure they stay expanded Session.set "openedComments", null Session.set "requestTimestamp", new Date() # currentScroll stores the position of the user in the page Session.set "currentScroll", null document.title = getSetting("title") # set all errors who have already been seen to not show anymore clearSeenErrors() # log this request with mixpanel, etc analyticsRequest() # if there are any pending events, log them too if eventBuffer = Session.get("eventBuffer") _.each eventBuffer, (e) -> console.log "in buffer: ", e trackEvent e.event, e.properties )() END ###
[ { "context": "tion\nstubOptions = {\n host : '0.0.0.0'\n user : 'user'\n password : 'secret'\n}\n\n# Module testing\ndescri", "end": 162, "score": 0.7593947649002075, "start": 158, "tag": "USERNAME", "value": "user" }, { "context": "\n host : '0.0.0.0'\n user : 'user'\n password : 'secret'\n}\n\n# Module testing\ndescribe 'MysqlAdapter', ->\n", "end": 184, "score": 0.9993125200271606, "start": 178, "tag": "PASSWORD", "value": "secret" } ]
ud/node_modules/mysql-connection-pool/test/mysqlAdapterTest.coffee
dev-mean/AppJK
0
# Lib dependencies MysqlAdapter = require('../lib/MysqlAdapter') # Stub DB options used to configure connection stubOptions = { host : '0.0.0.0' user : 'user' password : 'secret' } # Module testing describe 'MysqlAdapter', -> describe '#new', -> adapter = undefined beforeEach -> spyOn(MysqlAdapter.prototype, 'configure') adapter = new MysqlAdapter() it 'should return a MysqlAdapter object', -> expect(adapter.constructor).toBe(MysqlAdapter) it 'should configure', -> expect(adapter.configure).toHaveBeenCalled() describe '#configure', -> adapter = undefined beforeEach -> adapter = new MysqlAdapter(stubOptions) it 'should set local config', -> expect(adapter.config).toBe(stubOptions) it 'should set a connection object', -> expect(adapter.connection).toBeDefined() # TODO: use a spy to determine if set describe '#open (while open)', -> it 'should return false', -> describe '#open (while unopened)', -> it 'should set open state', -> it 'should attempt to open connection', -> it 'should return true', -> describe '#close (while closed)', -> it 'should return false', -> describe '#close (while open)', -> it 'should set closed state', -> it 'should close the connection', -> it 'should return true', -> describe '#query', -> it 'should make query against connection', ->
52885
# Lib dependencies MysqlAdapter = require('../lib/MysqlAdapter') # Stub DB options used to configure connection stubOptions = { host : '0.0.0.0' user : 'user' password : '<PASSWORD>' } # Module testing describe 'MysqlAdapter', -> describe '#new', -> adapter = undefined beforeEach -> spyOn(MysqlAdapter.prototype, 'configure') adapter = new MysqlAdapter() it 'should return a MysqlAdapter object', -> expect(adapter.constructor).toBe(MysqlAdapter) it 'should configure', -> expect(adapter.configure).toHaveBeenCalled() describe '#configure', -> adapter = undefined beforeEach -> adapter = new MysqlAdapter(stubOptions) it 'should set local config', -> expect(adapter.config).toBe(stubOptions) it 'should set a connection object', -> expect(adapter.connection).toBeDefined() # TODO: use a spy to determine if set describe '#open (while open)', -> it 'should return false', -> describe '#open (while unopened)', -> it 'should set open state', -> it 'should attempt to open connection', -> it 'should return true', -> describe '#close (while closed)', -> it 'should return false', -> describe '#close (while open)', -> it 'should set closed state', -> it 'should close the connection', -> it 'should return true', -> describe '#query', -> it 'should make query against connection', ->
true
# Lib dependencies MysqlAdapter = require('../lib/MysqlAdapter') # Stub DB options used to configure connection stubOptions = { host : '0.0.0.0' user : 'user' password : 'PI:PASSWORD:<PASSWORD>END_PI' } # Module testing describe 'MysqlAdapter', -> describe '#new', -> adapter = undefined beforeEach -> spyOn(MysqlAdapter.prototype, 'configure') adapter = new MysqlAdapter() it 'should return a MysqlAdapter object', -> expect(adapter.constructor).toBe(MysqlAdapter) it 'should configure', -> expect(adapter.configure).toHaveBeenCalled() describe '#configure', -> adapter = undefined beforeEach -> adapter = new MysqlAdapter(stubOptions) it 'should set local config', -> expect(adapter.config).toBe(stubOptions) it 'should set a connection object', -> expect(adapter.connection).toBeDefined() # TODO: use a spy to determine if set describe '#open (while open)', -> it 'should return false', -> describe '#open (while unopened)', -> it 'should set open state', -> it 'should attempt to open connection', -> it 'should return true', -> describe '#close (while closed)', -> it 'should return false', -> describe '#close (while open)', -> it 'should set closed state', -> it 'should close the connection', -> it 'should return true', -> describe '#query', -> it 'should make query against connection', ->
[ { "context": "thod getWrap\n ###\n getWrap: (x,y,d) ->\n key = \"#{x}-#{y}\"\n if @wrapNodes[key]?\n return @wrapNodes[k", "end": 2022, "score": 0.9990355372428894, "start": 2011, "tag": "KEY", "value": "\"#{x}-#{y}\"" }, { "context": "ar.cleanNode(@wrapNodes[key])\n else\n key = \"#{x}-#{y}-#{d}\"\n unless @wrapNodes[key]?\n @wrapNodes[", "end": 2257, "score": 0.9984031319618225, "start": 2241, "tag": "KEY", "value": "\"#{x}-#{y}-#{d}\"" } ]
src/main/coffeescript/nz/Graph.coffee
fukuyama/nineteen
2
###* * @file Graph.coffee * A*用グラフクラス ### ###* nineteen namespace. * @namespace nz ### # node.js と ブラウザでの this.nz を同じインスタンスにする _g = window ? global nz = _g.nz = _g.nz ? {} _g = undefined _NEIGHBORS = [ [ [[ 0,-1, 0],[ 0, 0, 5],[ 0, 0, 1],[ 0, 1, 0]] [[ 1, 0, 1],[ 0, 0, 0],[ 0, 0, 2],[-1, 1, 1]] [[ 1, 1, 2],[ 0, 0, 1],[ 0, 0, 3],[-1, 0, 2]] [[ 0, 1, 3],[ 0, 0, 2],[ 0, 0, 4],[ 0,-1, 3]] [[-1, 1, 4],[ 0, 0, 3],[ 0, 0, 5],[ 1, 0, 4]] [[-1, 0, 5],[ 0, 0, 4],[ 0, 0, 0],[ 1, 1, 5]] ] [ [[ 0,-1, 0],[ 0, 0, 5],[ 0, 0, 1],[ 0, 1, 0]] [[ 1,-1, 1],[ 0, 0, 0],[ 0, 0, 2],[-1, 0, 1]] [[ 1, 0, 2],[ 0, 0, 1],[ 0, 0, 3],[-1,-1, 2]] [[ 0, 1, 3],[ 0, 0, 2],[ 0, 0, 4],[ 0,-1, 3]] [[-1, 0, 4],[ 0, 0, 3],[ 0, 0, 5],[ 1,-1, 4]] [[-1,-1, 5],[ 0, 0, 4],[ 0, 0, 0],[ 1, 0, 5]] ] ] class nz.Graph ###* コンストラクタ. * @classdesc A*用グラフクラス * @constructor nz.Graph ### constructor: (param = {}) -> { mapdata chipdata } = param @width = mapdata.width @height = mapdata.height @nodes = [] @grid = [] @grid[x] = [] for x in [0...mapdata.width] for y in [0...mapdata.height] for x in [0...mapdata.width] unless y == mapdata.height - 1 and x % 2 == 0 chipid = mapdata.data[y][x] node = new nz.GridNode(x,y,chipdata[chipid]) @grid[x][y] = node @nodes.push(node) @clear() ###* クリア * @memberof nz.Graph# * @method clear ### clear: -> @cleanWrap() for node in @nodes node.clean() return ###* ダーティノードの削除 * @memberof nz.Graph# * @method cleanDirty ### cleanDirty: -> return ###* ダーティノードのマーク * @memberof nz.Graph# * @method markDirty * @param {Object} node ### markDirty: (node) -> return ###* ラップクラスの削除 * @memberof nz.Graph# * @method cleanWrap ### cleanWrap: -> @wrapNodes = {} return ###* ラップクラスの取得 * @memberof nz.Graph# * @method getWrap ### getWrap: (x,y,d) -> key = "#{x}-#{y}" if @wrapNodes[key]? return @wrapNodes[key] unless d? unless @wrapNodes[key]? @wrapNodes[key] = new nz.GridNodeWrap(@grid[x][y]) astar.cleanNode(@wrapNodes[key]) else key = "#{x}-#{y}-#{d}" unless @wrapNodes[key]? @wrapNodes[key] = new nz.GridNodeWrap(@grid[x][y],d) astar.cleanNode(@wrapNodes[key]) @wrapNodes[key] neighbors: (w) -> #self = @ #return _NEIGHBORS[w.mapx % 2][w.direction] # .filter (o) -> # [x,y,d] = o # self.grid[x + w.mapx]?[y + w.mapy]? # .map (o) -> # [x,y,d] = o # self.getWrap(x + w.mapx,y + w.mapy,d) #ret = [] #for [x,y,d] in _NEIGHBORS[w.mapx % 2][w.direction] # x += w.mapx # y += w.mapy # if @grid[x]?[y]? # ret.push @getWrap(x,y,d) #return ret for [x,y,d] in _NEIGHBORS[w.mapx % 2][w.direction] when @grid[x + w.mapx]?[y + w.mapy]? @getWrap(x + w.mapx, y + w.mapy, d) toString: -> graphString = [] for nodes in @grid rowDebug = [] for node in nodes rowDebug.push(node.weight) graphString.push(rowDebug.join(" ")) return graphString.join("\n") searchRoute: (sd,sx,sy,ex,ey,op={}) -> route = [] start = @getWrap sx,sy,sd end = @getWrap ex,ey # 壁じゃなかったら探索 if (not end.isWall()) or op.closest unless op.closest? op.closest = false unless op.heuristic? op.heuristic = nz.Graph.heuristic unless op.grid? op.grid = [] for g in op.grid @grid[g.mapx][g.mapy].options = g.options if op.graph? @options = op.graph result = astar.search(@, start, end, op) pd = sd for wrap in result route.push { mapx: wrap.mapx mapy: wrap.mapy cost: wrap.g back: wrap.back direction: if wrap.direction < 0 then pd else wrap.direction } pd = wrap.direction for g in op.grid @grid[g.mapx][g.mapy].options = undefined @options = undefined @cleanWrap() return route nz.Graph.heuristic = (wrap1,wrap2) -> hx = Math.abs(wrap1.mapx - wrap2.mapx) hy = Math.abs(wrap1.mapy - wrap2.mapy) #hr = Math.floor(hx / 2) hr = Math.ceil(hx / 2) direction = wrap1.node.calcDirectionTo(wrap2) hd = nz.Graph.directionCost(wrap1.direction,direction) if hy == hr hy = 0 else if hy < hr if hy != 0 hy = 1 if hd == 1 hd = 0 else hy -= hr #console.log "#{wrap1.mapx} #{wrap1.mapy} #{wrap2.mapx} #{wrap2.mapy} #{hx} #{hy} #{hd} #{direction}" hx + hy + hd ###* 対象の方向 * @param {Object} c1 元 * @param {Object} c2 対象 ### nz.Graph.direction = (c1,c2) -> dis = nz.Graph.distance c1,c2 r = Math.floor(dis / 2) dir = 0 if (c2.mapx - r) <= c1.mapx and c1.mapx <= (c2.mapx + r) dir = 0 if c1.mapy > c2.mapy dir = 3 if c1.mapy < c2.mapy else if c1.mapx > c2.mapx # 左側 if c1.mapy == c2.mapy dir = if c1.mapx % 2 == 0 then 5 else 4 else if c1.mapy > c2.mapy dir = 5 else if c1.mapy < c2.mapy dir = 4 else if c1.mapx < c2.mapx # 右側 if c1.mapy == c2.mapy dir = if c1.mapx % 2 == 0 then 1 else 2 else if c1.mapy > c2.mapy dir = 1 else if c1.mapy < c2.mapy dir = 2 return dir ###* 距離 * @param {Object} c1 元 * @param {Object} c2 対象 ### nz.Graph.distance = (c1,c2) -> hx = Math.abs(c1.mapx - c2.mapx) hy = Math.abs(c1.mapy - c2.mapy) hr = Math.ceil(hx / 2) return hx if hy < hr if hx % 2 == 1 if c1.mapx % 2 == 1 if c1.mapy <= c2.mapy hy += 1 else if c1.mapy >= c2.mapy hy += 1 return hx + hy - hr ###* 方向転換にかかるコストを計算 * @param {number} direction1 方向1 * @param {number} direction2 方向2 ### nz.Graph.directionCost = (direction1,direction2) -> Math.abs(3 - Math.abs((direction2 - direction1 - 3) % 6)) # mapx = _FRONT_POS[mapx % 2][direction][0] # mapy = _FRONT_POS[mapx % 2][direction][1] _FRONT_POS = [ [[ 0,-1],[ 1, 0],[ 1, 1],[ 0, 1],[-1, 1],[-1, 0]] [[ 0,-1],[ 1,-1],[ 1, 0],[ 0, 1],[-1, 0],[-1,-1]] ] ###* 向いている目の前の座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @return {Object} 目の前の座標 ### nz.Graph.frontPosition = (p) -> d = (p.direction + 6) % 6 t = p.mapx % 2 return { mapx: p.mapx + _FRONT_POS[t][d][0] mapy: p.mapy + _FRONT_POS[t][d][1] direction: d } ###* 向いている方向に対する後ろの座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @return {Object} 後ろの座標 ### nz.Graph.backPosition = (p) -> r = nz.Graph.frontPosition { mapx: p.mapx mapy: p.mapy direction: p.direction + 3 } r.direction = p.direction return r ###* ヘックス状のライン座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @param {number} p.distance 距離 * @return {Array<Object>} 座標配列 ### nz.Graph.hexLine = (p) -> for n in [0 ... p.distance] p = @frontPosition(p) ###* 方向に対する座標エリアを取得する。 * 時計まわりに30度のエリアを探す。 * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @param {number} p.distance 距離 * @return {Array<Object>} 座標配列 ### nz.Graph.frontArea = (p) -> r = [] for a,i in @hexLine(p) r.push a a.direction += 2 a.distance = i + 1 Array.prototype.push.apply r, @hexLine(a) return r
11756
###* * @file Graph.coffee * A*用グラフクラス ### ###* nineteen namespace. * @namespace nz ### # node.js と ブラウザでの this.nz を同じインスタンスにする _g = window ? global nz = _g.nz = _g.nz ? {} _g = undefined _NEIGHBORS = [ [ [[ 0,-1, 0],[ 0, 0, 5],[ 0, 0, 1],[ 0, 1, 0]] [[ 1, 0, 1],[ 0, 0, 0],[ 0, 0, 2],[-1, 1, 1]] [[ 1, 1, 2],[ 0, 0, 1],[ 0, 0, 3],[-1, 0, 2]] [[ 0, 1, 3],[ 0, 0, 2],[ 0, 0, 4],[ 0,-1, 3]] [[-1, 1, 4],[ 0, 0, 3],[ 0, 0, 5],[ 1, 0, 4]] [[-1, 0, 5],[ 0, 0, 4],[ 0, 0, 0],[ 1, 1, 5]] ] [ [[ 0,-1, 0],[ 0, 0, 5],[ 0, 0, 1],[ 0, 1, 0]] [[ 1,-1, 1],[ 0, 0, 0],[ 0, 0, 2],[-1, 0, 1]] [[ 1, 0, 2],[ 0, 0, 1],[ 0, 0, 3],[-1,-1, 2]] [[ 0, 1, 3],[ 0, 0, 2],[ 0, 0, 4],[ 0,-1, 3]] [[-1, 0, 4],[ 0, 0, 3],[ 0, 0, 5],[ 1,-1, 4]] [[-1,-1, 5],[ 0, 0, 4],[ 0, 0, 0],[ 1, 0, 5]] ] ] class nz.Graph ###* コンストラクタ. * @classdesc A*用グラフクラス * @constructor nz.Graph ### constructor: (param = {}) -> { mapdata chipdata } = param @width = mapdata.width @height = mapdata.height @nodes = [] @grid = [] @grid[x] = [] for x in [0...mapdata.width] for y in [0...mapdata.height] for x in [0...mapdata.width] unless y == mapdata.height - 1 and x % 2 == 0 chipid = mapdata.data[y][x] node = new nz.GridNode(x,y,chipdata[chipid]) @grid[x][y] = node @nodes.push(node) @clear() ###* クリア * @memberof nz.Graph# * @method clear ### clear: -> @cleanWrap() for node in @nodes node.clean() return ###* ダーティノードの削除 * @memberof nz.Graph# * @method cleanDirty ### cleanDirty: -> return ###* ダーティノードのマーク * @memberof nz.Graph# * @method markDirty * @param {Object} node ### markDirty: (node) -> return ###* ラップクラスの削除 * @memberof nz.Graph# * @method cleanWrap ### cleanWrap: -> @wrapNodes = {} return ###* ラップクラスの取得 * @memberof nz.Graph# * @method getWrap ### getWrap: (x,y,d) -> key = <KEY> if @wrapNodes[key]? return @wrapNodes[key] unless d? unless @wrapNodes[key]? @wrapNodes[key] = new nz.GridNodeWrap(@grid[x][y]) astar.cleanNode(@wrapNodes[key]) else key = <KEY> unless @wrapNodes[key]? @wrapNodes[key] = new nz.GridNodeWrap(@grid[x][y],d) astar.cleanNode(@wrapNodes[key]) @wrapNodes[key] neighbors: (w) -> #self = @ #return _NEIGHBORS[w.mapx % 2][w.direction] # .filter (o) -> # [x,y,d] = o # self.grid[x + w.mapx]?[y + w.mapy]? # .map (o) -> # [x,y,d] = o # self.getWrap(x + w.mapx,y + w.mapy,d) #ret = [] #for [x,y,d] in _NEIGHBORS[w.mapx % 2][w.direction] # x += w.mapx # y += w.mapy # if @grid[x]?[y]? # ret.push @getWrap(x,y,d) #return ret for [x,y,d] in _NEIGHBORS[w.mapx % 2][w.direction] when @grid[x + w.mapx]?[y + w.mapy]? @getWrap(x + w.mapx, y + w.mapy, d) toString: -> graphString = [] for nodes in @grid rowDebug = [] for node in nodes rowDebug.push(node.weight) graphString.push(rowDebug.join(" ")) return graphString.join("\n") searchRoute: (sd,sx,sy,ex,ey,op={}) -> route = [] start = @getWrap sx,sy,sd end = @getWrap ex,ey # 壁じゃなかったら探索 if (not end.isWall()) or op.closest unless op.closest? op.closest = false unless op.heuristic? op.heuristic = nz.Graph.heuristic unless op.grid? op.grid = [] for g in op.grid @grid[g.mapx][g.mapy].options = g.options if op.graph? @options = op.graph result = astar.search(@, start, end, op) pd = sd for wrap in result route.push { mapx: wrap.mapx mapy: wrap.mapy cost: wrap.g back: wrap.back direction: if wrap.direction < 0 then pd else wrap.direction } pd = wrap.direction for g in op.grid @grid[g.mapx][g.mapy].options = undefined @options = undefined @cleanWrap() return route nz.Graph.heuristic = (wrap1,wrap2) -> hx = Math.abs(wrap1.mapx - wrap2.mapx) hy = Math.abs(wrap1.mapy - wrap2.mapy) #hr = Math.floor(hx / 2) hr = Math.ceil(hx / 2) direction = wrap1.node.calcDirectionTo(wrap2) hd = nz.Graph.directionCost(wrap1.direction,direction) if hy == hr hy = 0 else if hy < hr if hy != 0 hy = 1 if hd == 1 hd = 0 else hy -= hr #console.log "#{wrap1.mapx} #{wrap1.mapy} #{wrap2.mapx} #{wrap2.mapy} #{hx} #{hy} #{hd} #{direction}" hx + hy + hd ###* 対象の方向 * @param {Object} c1 元 * @param {Object} c2 対象 ### nz.Graph.direction = (c1,c2) -> dis = nz.Graph.distance c1,c2 r = Math.floor(dis / 2) dir = 0 if (c2.mapx - r) <= c1.mapx and c1.mapx <= (c2.mapx + r) dir = 0 if c1.mapy > c2.mapy dir = 3 if c1.mapy < c2.mapy else if c1.mapx > c2.mapx # 左側 if c1.mapy == c2.mapy dir = if c1.mapx % 2 == 0 then 5 else 4 else if c1.mapy > c2.mapy dir = 5 else if c1.mapy < c2.mapy dir = 4 else if c1.mapx < c2.mapx # 右側 if c1.mapy == c2.mapy dir = if c1.mapx % 2 == 0 then 1 else 2 else if c1.mapy > c2.mapy dir = 1 else if c1.mapy < c2.mapy dir = 2 return dir ###* 距離 * @param {Object} c1 元 * @param {Object} c2 対象 ### nz.Graph.distance = (c1,c2) -> hx = Math.abs(c1.mapx - c2.mapx) hy = Math.abs(c1.mapy - c2.mapy) hr = Math.ceil(hx / 2) return hx if hy < hr if hx % 2 == 1 if c1.mapx % 2 == 1 if c1.mapy <= c2.mapy hy += 1 else if c1.mapy >= c2.mapy hy += 1 return hx + hy - hr ###* 方向転換にかかるコストを計算 * @param {number} direction1 方向1 * @param {number} direction2 方向2 ### nz.Graph.directionCost = (direction1,direction2) -> Math.abs(3 - Math.abs((direction2 - direction1 - 3) % 6)) # mapx = _FRONT_POS[mapx % 2][direction][0] # mapy = _FRONT_POS[mapx % 2][direction][1] _FRONT_POS = [ [[ 0,-1],[ 1, 0],[ 1, 1],[ 0, 1],[-1, 1],[-1, 0]] [[ 0,-1],[ 1,-1],[ 1, 0],[ 0, 1],[-1, 0],[-1,-1]] ] ###* 向いている目の前の座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @return {Object} 目の前の座標 ### nz.Graph.frontPosition = (p) -> d = (p.direction + 6) % 6 t = p.mapx % 2 return { mapx: p.mapx + _FRONT_POS[t][d][0] mapy: p.mapy + _FRONT_POS[t][d][1] direction: d } ###* 向いている方向に対する後ろの座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @return {Object} 後ろの座標 ### nz.Graph.backPosition = (p) -> r = nz.Graph.frontPosition { mapx: p.mapx mapy: p.mapy direction: p.direction + 3 } r.direction = p.direction return r ###* ヘックス状のライン座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @param {number} p.distance 距離 * @return {Array<Object>} 座標配列 ### nz.Graph.hexLine = (p) -> for n in [0 ... p.distance] p = @frontPosition(p) ###* 方向に対する座標エリアを取得する。 * 時計まわりに30度のエリアを探す。 * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @param {number} p.distance 距離 * @return {Array<Object>} 座標配列 ### nz.Graph.frontArea = (p) -> r = [] for a,i in @hexLine(p) r.push a a.direction += 2 a.distance = i + 1 Array.prototype.push.apply r, @hexLine(a) return r
true
###* * @file Graph.coffee * A*用グラフクラス ### ###* nineteen namespace. * @namespace nz ### # node.js と ブラウザでの this.nz を同じインスタンスにする _g = window ? global nz = _g.nz = _g.nz ? {} _g = undefined _NEIGHBORS = [ [ [[ 0,-1, 0],[ 0, 0, 5],[ 0, 0, 1],[ 0, 1, 0]] [[ 1, 0, 1],[ 0, 0, 0],[ 0, 0, 2],[-1, 1, 1]] [[ 1, 1, 2],[ 0, 0, 1],[ 0, 0, 3],[-1, 0, 2]] [[ 0, 1, 3],[ 0, 0, 2],[ 0, 0, 4],[ 0,-1, 3]] [[-1, 1, 4],[ 0, 0, 3],[ 0, 0, 5],[ 1, 0, 4]] [[-1, 0, 5],[ 0, 0, 4],[ 0, 0, 0],[ 1, 1, 5]] ] [ [[ 0,-1, 0],[ 0, 0, 5],[ 0, 0, 1],[ 0, 1, 0]] [[ 1,-1, 1],[ 0, 0, 0],[ 0, 0, 2],[-1, 0, 1]] [[ 1, 0, 2],[ 0, 0, 1],[ 0, 0, 3],[-1,-1, 2]] [[ 0, 1, 3],[ 0, 0, 2],[ 0, 0, 4],[ 0,-1, 3]] [[-1, 0, 4],[ 0, 0, 3],[ 0, 0, 5],[ 1,-1, 4]] [[-1,-1, 5],[ 0, 0, 4],[ 0, 0, 0],[ 1, 0, 5]] ] ] class nz.Graph ###* コンストラクタ. * @classdesc A*用グラフクラス * @constructor nz.Graph ### constructor: (param = {}) -> { mapdata chipdata } = param @width = mapdata.width @height = mapdata.height @nodes = [] @grid = [] @grid[x] = [] for x in [0...mapdata.width] for y in [0...mapdata.height] for x in [0...mapdata.width] unless y == mapdata.height - 1 and x % 2 == 0 chipid = mapdata.data[y][x] node = new nz.GridNode(x,y,chipdata[chipid]) @grid[x][y] = node @nodes.push(node) @clear() ###* クリア * @memberof nz.Graph# * @method clear ### clear: -> @cleanWrap() for node in @nodes node.clean() return ###* ダーティノードの削除 * @memberof nz.Graph# * @method cleanDirty ### cleanDirty: -> return ###* ダーティノードのマーク * @memberof nz.Graph# * @method markDirty * @param {Object} node ### markDirty: (node) -> return ###* ラップクラスの削除 * @memberof nz.Graph# * @method cleanWrap ### cleanWrap: -> @wrapNodes = {} return ###* ラップクラスの取得 * @memberof nz.Graph# * @method getWrap ### getWrap: (x,y,d) -> key = PI:KEY:<KEY>END_PI if @wrapNodes[key]? return @wrapNodes[key] unless d? unless @wrapNodes[key]? @wrapNodes[key] = new nz.GridNodeWrap(@grid[x][y]) astar.cleanNode(@wrapNodes[key]) else key = PI:KEY:<KEY>END_PI unless @wrapNodes[key]? @wrapNodes[key] = new nz.GridNodeWrap(@grid[x][y],d) astar.cleanNode(@wrapNodes[key]) @wrapNodes[key] neighbors: (w) -> #self = @ #return _NEIGHBORS[w.mapx % 2][w.direction] # .filter (o) -> # [x,y,d] = o # self.grid[x + w.mapx]?[y + w.mapy]? # .map (o) -> # [x,y,d] = o # self.getWrap(x + w.mapx,y + w.mapy,d) #ret = [] #for [x,y,d] in _NEIGHBORS[w.mapx % 2][w.direction] # x += w.mapx # y += w.mapy # if @grid[x]?[y]? # ret.push @getWrap(x,y,d) #return ret for [x,y,d] in _NEIGHBORS[w.mapx % 2][w.direction] when @grid[x + w.mapx]?[y + w.mapy]? @getWrap(x + w.mapx, y + w.mapy, d) toString: -> graphString = [] for nodes in @grid rowDebug = [] for node in nodes rowDebug.push(node.weight) graphString.push(rowDebug.join(" ")) return graphString.join("\n") searchRoute: (sd,sx,sy,ex,ey,op={}) -> route = [] start = @getWrap sx,sy,sd end = @getWrap ex,ey # 壁じゃなかったら探索 if (not end.isWall()) or op.closest unless op.closest? op.closest = false unless op.heuristic? op.heuristic = nz.Graph.heuristic unless op.grid? op.grid = [] for g in op.grid @grid[g.mapx][g.mapy].options = g.options if op.graph? @options = op.graph result = astar.search(@, start, end, op) pd = sd for wrap in result route.push { mapx: wrap.mapx mapy: wrap.mapy cost: wrap.g back: wrap.back direction: if wrap.direction < 0 then pd else wrap.direction } pd = wrap.direction for g in op.grid @grid[g.mapx][g.mapy].options = undefined @options = undefined @cleanWrap() return route nz.Graph.heuristic = (wrap1,wrap2) -> hx = Math.abs(wrap1.mapx - wrap2.mapx) hy = Math.abs(wrap1.mapy - wrap2.mapy) #hr = Math.floor(hx / 2) hr = Math.ceil(hx / 2) direction = wrap1.node.calcDirectionTo(wrap2) hd = nz.Graph.directionCost(wrap1.direction,direction) if hy == hr hy = 0 else if hy < hr if hy != 0 hy = 1 if hd == 1 hd = 0 else hy -= hr #console.log "#{wrap1.mapx} #{wrap1.mapy} #{wrap2.mapx} #{wrap2.mapy} #{hx} #{hy} #{hd} #{direction}" hx + hy + hd ###* 対象の方向 * @param {Object} c1 元 * @param {Object} c2 対象 ### nz.Graph.direction = (c1,c2) -> dis = nz.Graph.distance c1,c2 r = Math.floor(dis / 2) dir = 0 if (c2.mapx - r) <= c1.mapx and c1.mapx <= (c2.mapx + r) dir = 0 if c1.mapy > c2.mapy dir = 3 if c1.mapy < c2.mapy else if c1.mapx > c2.mapx # 左側 if c1.mapy == c2.mapy dir = if c1.mapx % 2 == 0 then 5 else 4 else if c1.mapy > c2.mapy dir = 5 else if c1.mapy < c2.mapy dir = 4 else if c1.mapx < c2.mapx # 右側 if c1.mapy == c2.mapy dir = if c1.mapx % 2 == 0 then 1 else 2 else if c1.mapy > c2.mapy dir = 1 else if c1.mapy < c2.mapy dir = 2 return dir ###* 距離 * @param {Object} c1 元 * @param {Object} c2 対象 ### nz.Graph.distance = (c1,c2) -> hx = Math.abs(c1.mapx - c2.mapx) hy = Math.abs(c1.mapy - c2.mapy) hr = Math.ceil(hx / 2) return hx if hy < hr if hx % 2 == 1 if c1.mapx % 2 == 1 if c1.mapy <= c2.mapy hy += 1 else if c1.mapy >= c2.mapy hy += 1 return hx + hy - hr ###* 方向転換にかかるコストを計算 * @param {number} direction1 方向1 * @param {number} direction2 方向2 ### nz.Graph.directionCost = (direction1,direction2) -> Math.abs(3 - Math.abs((direction2 - direction1 - 3) % 6)) # mapx = _FRONT_POS[mapx % 2][direction][0] # mapy = _FRONT_POS[mapx % 2][direction][1] _FRONT_POS = [ [[ 0,-1],[ 1, 0],[ 1, 1],[ 0, 1],[-1, 1],[-1, 0]] [[ 0,-1],[ 1,-1],[ 1, 0],[ 0, 1],[-1, 0],[-1,-1]] ] ###* 向いている目の前の座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @return {Object} 目の前の座標 ### nz.Graph.frontPosition = (p) -> d = (p.direction + 6) % 6 t = p.mapx % 2 return { mapx: p.mapx + _FRONT_POS[t][d][0] mapy: p.mapy + _FRONT_POS[t][d][1] direction: d } ###* 向いている方向に対する後ろの座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @return {Object} 後ろの座標 ### nz.Graph.backPosition = (p) -> r = nz.Graph.frontPosition { mapx: p.mapx mapy: p.mapy direction: p.direction + 3 } r.direction = p.direction return r ###* ヘックス状のライン座標を取得する * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @param {number} p.distance 距離 * @return {Array<Object>} 座標配列 ### nz.Graph.hexLine = (p) -> for n in [0 ... p.distance] p = @frontPosition(p) ###* 方向に対する座標エリアを取得する。 * 時計まわりに30度のエリアを探す。 * @param {Object} p パラメータ * @param {number} p.mapx X座標 * @param {number} p.mapy Y座標 * @param {number} p.direction 方向 * @param {number} p.distance 距離 * @return {Array<Object>} 座標配列 ### nz.Graph.frontArea = (p) -> r = [] for a,i in @hexLine(p) r.push a a.direction += 2 a.distance = i + 1 Array.prototype.push.apply r, @hexLine(a) return r
[ { "context": "s\",\"Prov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"", "end": 505, "score": 0.787792444229126, "start": 502, "tag": "NAME", "value": "Dan" }, { "context": "ov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"", "end": 511, "score": 0.6863702535629272, "start": 508, "tag": "NAME", "value": "Hos" }, { "context": "ccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"", "end": 518, "score": 0.8613941073417664, "start": 514, "tag": "NAME", "value": "Joel" }, { "context": "ong\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\"", "end": 522, "score": 0.5767709016799927, "start": 521, "tag": "NAME", "value": "A" }, { "context": "sa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",", "end": 530, "score": 0.5761348605155945, "start": 528, "tag": "NAME", "value": "Ob" }, { "context": "r\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Mat", "end": 540, "score": 0.8612357378005981, "start": 535, "tag": "NAME", "value": "Jonah" }, { "context": ",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Ma", "end": 546, "score": 0.8278111815452576, "start": 543, "tag": "NAME", "value": "Mic" }, { "context": "\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",", "end": 550, "score": 0.6470872163772583, "start": 549, "tag": "NAME", "value": "N" }, { "context": "d\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",", "end": 584, "score": 0.6360145211219788, "start": 581, "tag": "NAME", "value": "Mal" }, { "context": "nah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",", "end": 591, "score": 0.931046724319458, "start": 587, "tag": "NAME", "value": "Matt" }, { "context": "ic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"", "end": 598, "score": 0.9508596062660217, "start": 594, "tag": "NAME", "value": "Mark" }, { "context": "h\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"Eph\",\"P", "end": 605, "score": 0.8754208087921143, "start": 601, "tag": "NAME", "value": "Luke" }, { "context": "\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"Eph\",\"Phil\",\"C", "end": 612, "score": 0.7131298780441284, "start": 608, "tag": "NAME", "value": "John" }, { "context": " handle book: Rev (et)\", ->\n\t\t`\n\t\texpect(p.parse(\"Johannese Ilmutus 1:1\").osis()).toEqual(\"Rev.1.1\")\n\t\texpect(p.parse", "end": 7368, "score": 0.9715840220451355, "start": 7351, "tag": "NAME", "value": "Johannese Ilmutus" }, { "context": "\")\n\t\tp.include_apocrypha(false)\n\t\texpect(p.parse(\"JOHANNESE ILMUTUS 1:1\").osis()).toEqual(\"Rev.1.1\")\n\t\texpect(p.parse", "end": 7576, "score": 0.9713503122329712, "start": 7559, "tag": "NAME", "value": "JOHANNESE ILMUTUS" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Josh (et)\", ->\n\t\t`\n\t\texpect(p.parse(\"Joosua 1:1\").osis", "end": 9087, "score": 0.9130702018737793, "start": 9083, "tag": "NAME", "value": "Josh" }, { "context": "handle book: Josh (et)\", ->\n\t\t`\n\t\texpect(p.parse(\"Joosua 1:1\").osis()).toEqual(\"Josh.1.1\")\n\t\texpect(p.", "end": 9122, "score": 0.5062721371650696, "start": 9120, "tag": "NAME", "value": "Jo" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Matt (et)\", ->\n\t\t`\n\t\texpect(p.parse(\"Matteuse 1:1\").os", "end": 34193, "score": 0.6724035739898682, "start": 34189, "tag": "NAME", "value": "Matt" }, { "context": "(\"1John.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book 2John (et)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bc", "end": 36697, "score": 0.7702662944793701, "start": 36696, "tag": "NAME", "value": "2" }, { "context": "p.include_apocrypha true\n\tit \"should handle book: 2John (et)\", ->\n\t\t`\n\t\texpect(p.parse(\"2 Johannese 1", "end": 36957, "score": 0.7810595631599426, "start": 36956, "tag": "NAME", "value": "2" }, { "context": "(\"2John.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book 3John (et)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bc", "end": 37404, "score": 0.7914503812789917, "start": 37403, "tag": "NAME", "value": "3" }, { "context": "p.include_apocrypha true\n\tit \"should handle book: 3John (et)\", ->\n\t\t`\n\t\texpect(p.parse(\"3 Johannese 1", "end": 37664, "score": 0.5762545466423035, "start": 37663, "tag": "NAME", "value": "3" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: John (et)\", ->\n\t\t`\n\t\texpect(p.parse(\"Johannese 1:1\").o", "end": 38373, "score": 0.6847646832466125, "start": 38369, "tag": "NAME", "value": "John" } ]
lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/et/spec.coffee
saiba-mais/bible-lessons
0
bcv_parser = require("../../js/et_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","Dan","Hos","Joel","Amos","Obad","Jonah","Mic","Nah","Hab","Zeph","Hag","Zech","Mal","Matt","Mark","Luke","John","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (et)", -> ` expect(p.parse("1 Moosese 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1Ms 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("1 MOOSESE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1MS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (et)", -> ` expect(p.parse("2 Moosese 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2Ms 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("2 MOOSESE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2MS 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (et)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (et)", -> ` expect(p.parse("3 Moosese 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3Ms 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("3 MOOSESE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3MS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (et)", -> ` expect(p.parse("4 Moosese 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4Ms 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("4 MOOSESE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4MS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (et)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (et)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (et)", -> ` expect(p.parse("Nutulaulud 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Nl 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("NUTULAULUD 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("NL 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (et)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (et)", -> ` expect(p.parse("Johannese Ilmutus 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ilm 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("JOHANNESE ILMUTUS 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("ILM 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (et)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (et)", -> ` expect(p.parse("5 Moosese 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5Ms 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("5 MOOSESE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5MS 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book Josh (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Josh (et)", -> ` expect(p.parse("Joosua 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jos 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOOSUA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (et)", -> ` expect(p.parse("Kohtumoistjate 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Kohtumōistjate 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Km 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("KOHTUMOISTJATE 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("KOHTUMŌISTJATE 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("KM 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (et)", -> ` expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutt 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTT 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (et)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (et)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (et)", -> ` expect(p.parse("Jesaja 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Js 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("JESAJA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("JS 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (et)", -> ` expect(p.parse("2 Saamueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sm 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("2 SAAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (et)", -> ` expect(p.parse("1 Saamueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sm 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("1 SAAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (et)", -> ` expect(p.parse("2 Kuningate 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kn 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("2 KUNINGATE 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KN 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (et)", -> ` expect(p.parse("1 Kuningate 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kn 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("1 KUNINGATE 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KN 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (et)", -> ` expect(p.parse("2 Ajaraamat 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Aj 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("2 AJARAAMAT 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2AJ 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (et)", -> ` expect(p.parse("1 Ajaraamat 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Aj 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("1 AJARAAMAT 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1AJ 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (et)", -> ` expect(p.parse("Esra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("ESRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (et)", -> ` expect(p.parse("Nehemja 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Ne 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMJA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NE 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (et)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (et)", -> ` expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (et)", -> ` expect(p.parse("Iiob 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ii 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("IIOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("II 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (et)", -> ` expect(p.parse("Laulud 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("LAULUD 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (et)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (et)", -> ` expect(p.parse("Opetussonad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Opetussōnad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Ōpetussonad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Ōpetussōnad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Op 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Õp 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("OPETUSSONAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OPETUSSŌNAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ŌPETUSSONAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ŌPETUSSŌNAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OP 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ÕP 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (et)", -> ` expect(p.parse("Koguja 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Kg 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("KOGUJA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("KG 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (et)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (et)", -> ` expect(p.parse("Ulemlaul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ülemlaul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ül 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("ULEMLAUL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("ÜLEMLAUL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("UL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("ÜL 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (et)", -> ` expect(p.parse("Jeremija 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("JEREMIJA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (et)", -> ` expect(p.parse("Hesekiel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Hs 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("HESEKIEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("HS 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book Dan (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Dan (et)", -> ` expect(p.parse("Taaniel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Tn 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("TAANIEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("TN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (et)", -> ` expect(p.parse("Hoosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ho 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HO 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (et)", -> ` expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (et)", -> ` expect(p.parse("Aamos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AAMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (et)", -> ` expect(p.parse("Obadja 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADJA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jonah (et)", -> ` expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Joona 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jn 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JOONA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JN 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mic (et)", -> ` expect(p.parse("Miika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (et)", -> ` expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (et)", -> ` expect(p.parse("Habakuk 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Ha 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUK 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HA 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (et)", -> ` expect(p.parse("Sefanja 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANJA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (et)", -> ` expect(p.parse("Haggai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hg 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (et)", -> ` expect(p.parse("Sakarja 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sk 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SAKARJA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (et)", -> ` expect(p.parse("Malakia 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Ml 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKIA 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("ML 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book Matt (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Matt (et)", -> ` expect(p.parse("Matteuse 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("MATTEUSE 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (et)", -> ` expect(p.parse("Markuse 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("MARKUSE 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book Luke (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Luke (et)", -> ` expect(p.parse("Luuka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1John (et)", -> ` expect(p.parse("1 Johannese 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1Jh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("1 JOHANNESE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (et)", -> ` expect(p.parse("2 Johannese 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2Jh 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("2 JOHANNESE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JH 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (et)", -> ` expect(p.parse("3 Johannese 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3Jh 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("3 JOHANNESE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JH 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: John (et)", -> ` expect(p.parse("Johannese 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("JOHANNESE 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("JH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (et)", -> ` expect(p.parse("Apostlite Teod 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Ap 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("APOSTLITE TEOD 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("AP 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (et)", -> ` expect(p.parse("Roomlastele 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rm 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("ROOMLASTELE 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (et)", -> ` expect(p.parse("2 Korintlastele 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Kr 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("2 KORINTLASTELE 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2KR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (et)", -> ` expect(p.parse("1 Korintlastele 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Kr 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("1 KORINTLASTELE 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1KR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (et)", -> ` expect(p.parse("Galaatlastele 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gl 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("GALAATLASTELE 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (et)", -> ` expect(p.parse("Efeslastele 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("EFESLASTELE 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phil (et)", -> ` expect(p.parse("Filiplastele 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fl 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FILIPLASTELE 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (et)", -> ` expect(p.parse("Colossians 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kl 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("COLOSSIANS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (et)", -> ` expect(p.parse("2 Tessalooniklastele 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Ts 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("2 TESSALOONIKLASTELE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2TS 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (et)", -> ` expect(p.parse("1 Tessalooniklastele 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Ts 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("1 TESSALOONIKLASTELE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1TS 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (et)", -> ` expect(p.parse("2 Timoteosele 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tm 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("2 TIMOTEOSELE 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (et)", -> ` expect(p.parse("1 Timoteosele 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tm 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("1 TIMOTEOSELE 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (et)", -> ` expect(p.parse("Tiitusele 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("TIITUSELE 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (et)", -> ` expect(p.parse("Fileemonile 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("FILEEMONILE 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (et)", -> ` expect(p.parse("Heebrealastele 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("HEEBREALASTELE 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (et)", -> ` expect(p.parse("Jaakobuse 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jk 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("JAAKOBUSE 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (et)", -> ` expect(p.parse("2 Peetruse 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pt 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("2 PEETRUSE 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PT 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (et)", -> ` expect(p.parse("1 Peetruse 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pt 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("1 PEETRUSE 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PT 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (et)", -> ` expect(p.parse("Juuda Kiri 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jd 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("JUUDA KIRI 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (et)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (et)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (et)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (et)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (et)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (et)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (et)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (et)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["et"] it "should handle ranges (et)", -> expect(p.parse("Titus 1:1 et 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1et2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 ET 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (et)", -> expect(p.parse("Titus 1:1, peatükk 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 PEATÜKK 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, peatukk 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 PEATUKK 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (et)", -> expect(p.parse("Exod 1:1 salm 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm SALM 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (et)", -> expect(p.parse("Exod 1:1 ja 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 JA 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (et)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (et)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (et)", -> expect(p.parse("Lev 1 (EEP)").osis_and_translations()).toEqual [["Lev.1", "EEP"]] expect(p.parse("lev 1 eep").osis_and_translations()).toEqual [["Lev.1", "EEP"]] it "should handle boundaries (et)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
19185
bcv_parser = require("../../js/et_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","<NAME>","<NAME>","<NAME>","<NAME>mos","<NAME>ad","<NAME>","<NAME>","<NAME>ah","Hab","Zeph","Hag","Zech","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (et)", -> ` expect(p.parse("1 Moosese 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1Ms 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("1 MOOSESE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1MS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (et)", -> ` expect(p.parse("2 Moosese 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2Ms 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("2 MOOSESE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2MS 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (et)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (et)", -> ` expect(p.parse("3 Moosese 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3Ms 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("3 MOOSESE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3MS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (et)", -> ` expect(p.parse("4 Moosese 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4Ms 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("4 MOOSESE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4MS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (et)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (et)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (et)", -> ` expect(p.parse("Nutulaulud 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Nl 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("NUTULAULUD 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("NL 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (et)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (et)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ilm 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("<NAME> 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("ILM 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (et)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (et)", -> ` expect(p.parse("5 Moosese 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5Ms 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("5 MOOSESE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5MS 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book Josh (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (et)", -> ` expect(p.parse("<NAME>osua 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jos 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOOSUA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (et)", -> ` expect(p.parse("Kohtumoistjate 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Kohtumōistjate 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Km 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("KOHTUMOISTJATE 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("KOHTUMŌISTJATE 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("KM 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (et)", -> ` expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutt 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTT 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (et)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (et)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (et)", -> ` expect(p.parse("Jesaja 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Js 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("JESAJA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("JS 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (et)", -> ` expect(p.parse("2 Saamueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sm 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("2 SAAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (et)", -> ` expect(p.parse("1 Saamueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sm 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("1 SAAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (et)", -> ` expect(p.parse("2 Kuningate 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kn 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("2 KUNINGATE 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KN 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (et)", -> ` expect(p.parse("1 Kuningate 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kn 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("1 KUNINGATE 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KN 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (et)", -> ` expect(p.parse("2 Ajaraamat 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Aj 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("2 AJARAAMAT 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2AJ 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (et)", -> ` expect(p.parse("1 Ajaraamat 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Aj 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("1 AJARAAMAT 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1AJ 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (et)", -> ` expect(p.parse("Esra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("ESRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (et)", -> ` expect(p.parse("Nehemja 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Ne 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMJA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NE 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (et)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (et)", -> ` expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (et)", -> ` expect(p.parse("Iiob 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ii 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("IIOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("II 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (et)", -> ` expect(p.parse("Laulud 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("LAULUD 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (et)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (et)", -> ` expect(p.parse("Opetussonad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Opetussōnad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Ōpetussonad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Ōpetussōnad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Op 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Õp 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("OPETUSSONAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OPETUSSŌNAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ŌPETUSSONAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ŌPETUSSŌNAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OP 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ÕP 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (et)", -> ` expect(p.parse("Koguja 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Kg 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("KOGUJA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("KG 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (et)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (et)", -> ` expect(p.parse("Ulemlaul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ülemlaul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ül 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("ULEMLAUL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("ÜLEMLAUL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("UL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("ÜL 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (et)", -> ` expect(p.parse("Jeremija 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("JEREMIJA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (et)", -> ` expect(p.parse("Hesekiel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Hs 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("HESEKIEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("HS 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book Dan (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Dan (et)", -> ` expect(p.parse("Taaniel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Tn 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("TAANIEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("TN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (et)", -> ` expect(p.parse("Hoosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ho 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HO 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (et)", -> ` expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (et)", -> ` expect(p.parse("Aamos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AAMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (et)", -> ` expect(p.parse("Obadja 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADJA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jonah (et)", -> ` expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Joona 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jn 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JOONA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JN 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mic (et)", -> ` expect(p.parse("Miika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (et)", -> ` expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (et)", -> ` expect(p.parse("Habakuk 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Ha 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUK 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HA 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (et)", -> ` expect(p.parse("Sefanja 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANJA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (et)", -> ` expect(p.parse("Haggai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hg 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (et)", -> ` expect(p.parse("Sakarja 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sk 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SAKARJA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (et)", -> ` expect(p.parse("Malakia 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Ml 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKIA 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("ML 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book Matt (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (et)", -> ` expect(p.parse("Matteuse 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("MATTEUSE 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (et)", -> ` expect(p.parse("Markuse 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("MARKUSE 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book Luke (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Luke (et)", -> ` expect(p.parse("Luuka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1John (et)", -> ` expect(p.parse("1 Johannese 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1Jh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("1 JOHANNESE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book <NAME>John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>John (et)", -> ` expect(p.parse("2 Johannese 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2Jh 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("2 JOHANNESE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JH 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book <NAME>John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>John (et)", -> ` expect(p.parse("3 Johannese 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3Jh 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("3 JOHANNESE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JH 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (et)", -> ` expect(p.parse("Johannese 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("JOHANNESE 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("JH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (et)", -> ` expect(p.parse("Apostlite Teod 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Ap 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("APOSTLITE TEOD 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("AP 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (et)", -> ` expect(p.parse("Roomlastele 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rm 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("ROOMLASTELE 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (et)", -> ` expect(p.parse("2 Korintlastele 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Kr 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("2 KORINTLASTELE 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2KR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (et)", -> ` expect(p.parse("1 Korintlastele 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Kr 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("1 KORINTLASTELE 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1KR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (et)", -> ` expect(p.parse("Galaatlastele 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gl 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("GALAATLASTELE 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (et)", -> ` expect(p.parse("Efeslastele 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("EFESLASTELE 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phil (et)", -> ` expect(p.parse("Filiplastele 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fl 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FILIPLASTELE 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (et)", -> ` expect(p.parse("Colossians 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kl 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("COLOSSIANS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (et)", -> ` expect(p.parse("2 Tessalooniklastele 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Ts 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("2 TESSALOONIKLASTELE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2TS 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (et)", -> ` expect(p.parse("1 Tessalooniklastele 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Ts 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("1 TESSALOONIKLASTELE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1TS 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (et)", -> ` expect(p.parse("2 Timoteosele 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tm 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("2 TIMOTEOSELE 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (et)", -> ` expect(p.parse("1 Timoteosele 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tm 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("1 TIMOTEOSELE 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (et)", -> ` expect(p.parse("Tiitusele 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("TIITUSELE 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (et)", -> ` expect(p.parse("Fileemonile 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("FILEEMONILE 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (et)", -> ` expect(p.parse("Heebrealastele 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("HEEBREALASTELE 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (et)", -> ` expect(p.parse("Jaakobuse 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jk 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("JAAKOBUSE 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (et)", -> ` expect(p.parse("2 Peetruse 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pt 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("2 PEETRUSE 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PT 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (et)", -> ` expect(p.parse("1 Peetruse 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pt 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("1 PEETRUSE 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PT 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (et)", -> ` expect(p.parse("Juuda Kiri 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jd 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("JUUDA KIRI 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (et)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (et)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (et)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (et)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (et)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (et)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (et)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (et)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["et"] it "should handle ranges (et)", -> expect(p.parse("Titus 1:1 et 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1et2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 ET 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (et)", -> expect(p.parse("Titus 1:1, peatükk 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 PEATÜKK 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, peatukk 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 PEATUKK 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (et)", -> expect(p.parse("Exod 1:1 salm 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm SALM 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (et)", -> expect(p.parse("Exod 1:1 ja 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 JA 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (et)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (et)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (et)", -> expect(p.parse("Lev 1 (EEP)").osis_and_translations()).toEqual [["Lev.1", "EEP"]] expect(p.parse("lev 1 eep").osis_and_translations()).toEqual [["Lev.1", "EEP"]] it "should handle boundaries (et)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
true
bcv_parser = require("../../js/et_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PImos","PI:NAME:<NAME>END_PIad","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIah","Hab","Zeph","Hag","Zech","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (et)", -> ` expect(p.parse("1 Moosese 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1Ms 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("1 MOOSESE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1MS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (et)", -> ` expect(p.parse("2 Moosese 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2Ms 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("2 MOOSESE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2MS 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (et)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (et)", -> ` expect(p.parse("3 Moosese 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3Ms 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("3 MOOSESE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3MS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (et)", -> ` expect(p.parse("4 Moosese 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4Ms 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("4 MOOSESE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4MS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (et)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (et)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (et)", -> ` expect(p.parse("Nutulaulud 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Nl 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("NUTULAULUD 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("NL 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (et)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (et)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ilm 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("ILM 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (et)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (et)", -> ` expect(p.parse("5 Moosese 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5Ms 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("5 MOOSESE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5MS 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book Josh (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (et)", -> ` expect(p.parse("PI:NAME:<NAME>END_PIosua 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jos 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOOSUA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (et)", -> ` expect(p.parse("Kohtumoistjate 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Kohtumōistjate 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Km 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("KOHTUMOISTJATE 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("KOHTUMŌISTJATE 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("KM 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (et)", -> ` expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutt 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTT 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (et)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (et)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (et)", -> ` expect(p.parse("Jesaja 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Js 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("JESAJA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("JS 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (et)", -> ` expect(p.parse("2 Saamueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sm 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("2 SAAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (et)", -> ` expect(p.parse("1 Saamueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sm 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("1 SAAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (et)", -> ` expect(p.parse("2 Kuningate 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kn 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("2 KUNINGATE 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KN 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (et)", -> ` expect(p.parse("1 Kuningate 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kn 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("1 KUNINGATE 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KN 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (et)", -> ` expect(p.parse("2 Ajaraamat 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Aj 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("2 AJARAAMAT 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2AJ 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (et)", -> ` expect(p.parse("1 Ajaraamat 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Aj 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("1 AJARAAMAT 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1AJ 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (et)", -> ` expect(p.parse("Esra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("ESRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (et)", -> ` expect(p.parse("Nehemja 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Ne 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMJA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NE 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (et)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (et)", -> ` expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (et)", -> ` expect(p.parse("Iiob 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ii 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("IIOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("II 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (et)", -> ` expect(p.parse("Laulud 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("LAULUD 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (et)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (et)", -> ` expect(p.parse("Opetussonad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Opetussōnad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Ōpetussonad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Ōpetussōnad 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Op 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Õp 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("OPETUSSONAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OPETUSSŌNAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ŌPETUSSONAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ŌPETUSSŌNAD 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OP 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("ÕP 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (et)", -> ` expect(p.parse("Koguja 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Kg 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("KOGUJA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("KG 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (et)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (et)", -> ` expect(p.parse("Ulemlaul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ülemlaul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ul 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ül 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("ULEMLAUL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("ÜLEMLAUL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("UL 1:1").osis()).toEqual("Song.1.1") expect(p.parse("ÜL 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (et)", -> ` expect(p.parse("Jeremija 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("JEREMIJA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (et)", -> ` expect(p.parse("Hesekiel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Hs 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("HESEKIEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("HS 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book Dan (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Dan (et)", -> ` expect(p.parse("Taaniel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Tn 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("TAANIEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("TN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (et)", -> ` expect(p.parse("Hoosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Ho 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HO 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (et)", -> ` expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (et)", -> ` expect(p.parse("Aamos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AAMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (et)", -> ` expect(p.parse("Obadja 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADJA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jonah (et)", -> ` expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Joona 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jn 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JOONA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JN 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mic (et)", -> ` expect(p.parse("Miika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (et)", -> ` expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (et)", -> ` expect(p.parse("Habakuk 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Ha 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUK 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HA 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (et)", -> ` expect(p.parse("Sefanja 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANJA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (et)", -> ` expect(p.parse("Haggai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hg 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (et)", -> ` expect(p.parse("Sakarja 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sk 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SAKARJA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (et)", -> ` expect(p.parse("Malakia 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Ml 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKIA 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("ML 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book Matt (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (et)", -> ` expect(p.parse("Matteuse 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("MATTEUSE 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (et)", -> ` expect(p.parse("Markuse 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("MARKUSE 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book Luke (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Luke (et)", -> ` expect(p.parse("Luuka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1John (et)", -> ` expect(p.parse("1 Johannese 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1Jh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("1 JOHANNESE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIJohn (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIJohn (et)", -> ` expect(p.parse("2 Johannese 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2Jh 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("2 JOHANNESE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JH 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIJohn (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIJohn (et)", -> ` expect(p.parse("3 Johannese 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3Jh 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("3 JOHANNESE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JH 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (et)", -> ` expect(p.parse("Johannese 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("JOHANNESE 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("JH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (et)", -> ` expect(p.parse("Apostlite Teod 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Ap 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("APOSTLITE TEOD 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("AP 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (et)", -> ` expect(p.parse("Roomlastele 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rm 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("ROOMLASTELE 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (et)", -> ` expect(p.parse("2 Korintlastele 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Kr 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("2 KORINTLASTELE 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2KR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (et)", -> ` expect(p.parse("1 Korintlastele 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Kr 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("1 KORINTLASTELE 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1KR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (et)", -> ` expect(p.parse("Galaatlastele 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gl 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("GALAATLASTELE 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (et)", -> ` expect(p.parse("Efeslastele 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("EFESLASTELE 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phil (et)", -> ` expect(p.parse("Filiplastele 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fl 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FILIPLASTELE 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (et)", -> ` expect(p.parse("Colossians 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kl 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("COLOSSIANS 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (et)", -> ` expect(p.parse("2 Tessalooniklastele 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Ts 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("2 TESSALOONIKLASTELE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2TS 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (et)", -> ` expect(p.parse("1 Tessalooniklastele 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Ts 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("1 TESSALOONIKLASTELE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1TS 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (et)", -> ` expect(p.parse("2 Timoteosele 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tm 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("2 TIMOTEOSELE 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (et)", -> ` expect(p.parse("1 Timoteosele 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tm 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("1 TIMOTEOSELE 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (et)", -> ` expect(p.parse("Tiitusele 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("TIITUSELE 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (et)", -> ` expect(p.parse("Fileemonile 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("FILEEMONILE 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (et)", -> ` expect(p.parse("Heebrealastele 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("HEEBREALASTELE 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (et)", -> ` expect(p.parse("Jaakobuse 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jk 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("JAAKOBUSE 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (et)", -> ` expect(p.parse("2 Peetruse 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pt 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("2 PEETRUSE 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PT 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (et)", -> ` expect(p.parse("1 Peetruse 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pt 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("1 PEETRUSE 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PT 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (et)", -> ` expect(p.parse("Juuda Kiri 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jd 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("JUUDA KIRI 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (et)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (et)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (et)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (et)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (et)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (et)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (et)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (et)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (et)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["et"] it "should handle ranges (et)", -> expect(p.parse("Titus 1:1 et 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1et2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 ET 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (et)", -> expect(p.parse("Titus 1:1, peatükk 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 PEATÜKK 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, peatukk 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 PEATUKK 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (et)", -> expect(p.parse("Exod 1:1 salm 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm SALM 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (et)", -> expect(p.parse("Exod 1:1 ja 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 JA 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (et)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (et)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (et)", -> expect(p.parse("Lev 1 (EEP)").osis_and_translations()).toEqual [["Lev.1", "EEP"]] expect(p.parse("lev 1 eep").osis_and_translations()).toEqual [["Lev.1", "EEP"]] it "should handle boundaries (et)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
[ { "context": "######################\n# Copyright (C) 2015 by Vaughn Iverson\n# SimpleWiki is free software released under ", "end": 119, "score": 0.9998360872268677, "start": 105, "tag": "NAME", "value": "Vaughn Iverson" } ]
SimpleWiki.coffee
vsivsi/SimpleWiki
0
############################################################################ # Copyright (C) 2015 by Vaughn Iverson # SimpleWiki is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ docDb = new Mongo.Collection "docDB" if Meteor.isClient editor = null doc = "Loading..." text = new ReactiveVar doc init = new ReactiveVar false Template.document.helpers textHelp: () -> console.log "Getting text!" text.get() Template.editor.events 'click #commitButton': (e, t) -> console.log "Make Commit" docDb.update "Home", { $set: { text: editor.getValue() }} updateDoc = () -> timeout = null Meteor.call 'pandoc', editor.getValue(), (err, res) -> unless err text.set res else console.warn "Pandoc method failed with #{err}" Template.editor.onRendered () -> AceEditor.instance "edit", { theme: "dawn", mode: "markdown" }, (e) -> editor = e init.set true timeout = null editor.on 'change', (e) -> console.log "Changed!" console.log e unless timeout timeout = Meteor.setTimeout updateDoc, 2500 # Set up an autorun to keep the X-Auth-Token cookie up-to-date and # to update the subscription when the userId changes. Tracker.autorun () -> userId = null # Enable these when accounts support added # userId = Meteor.userId() # $.cookie 'X-Auth-Token', Accounts._storedLoginToken() if init.get() console.log "Setting up subscription" Meteor.subscribe 'allDocs', userId, () -> doc = docDb.findOne "Home" unless doc doc = { _id: "Home", text: "Placeholder..." } docDb.insert doc console.log "Ready!", doc editor.setValue doc.text updateDoc() Meteor.startup () -> # code to run on client at startup ############################################################################## if Meteor.isServer pdc = Async.wrap Meteor.npmRequire('pdc') Meteor.publish 'allDocs', (clientUserId) -> if this.userId is clientUserId return docDb.find {} else return [] docDb.allow insert: (userId, doc) -> true update: (userId, file, fieldNames, modifier) -> true remove: (userId, doc) -> true Meteor.startup () -> # code to run on server at startup Meteor.methods pandoc: (txt) -> check txt, String console.log "Called with: #{txt}" res = pdc txt, "markdown", "html" console.log "Result: #{res}" return res
166463
############################################################################ # Copyright (C) 2015 by <NAME> # SimpleWiki is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ docDb = new Mongo.Collection "docDB" if Meteor.isClient editor = null doc = "Loading..." text = new ReactiveVar doc init = new ReactiveVar false Template.document.helpers textHelp: () -> console.log "Getting text!" text.get() Template.editor.events 'click #commitButton': (e, t) -> console.log "Make Commit" docDb.update "Home", { $set: { text: editor.getValue() }} updateDoc = () -> timeout = null Meteor.call 'pandoc', editor.getValue(), (err, res) -> unless err text.set res else console.warn "Pandoc method failed with #{err}" Template.editor.onRendered () -> AceEditor.instance "edit", { theme: "dawn", mode: "markdown" }, (e) -> editor = e init.set true timeout = null editor.on 'change', (e) -> console.log "Changed!" console.log e unless timeout timeout = Meteor.setTimeout updateDoc, 2500 # Set up an autorun to keep the X-Auth-Token cookie up-to-date and # to update the subscription when the userId changes. Tracker.autorun () -> userId = null # Enable these when accounts support added # userId = Meteor.userId() # $.cookie 'X-Auth-Token', Accounts._storedLoginToken() if init.get() console.log "Setting up subscription" Meteor.subscribe 'allDocs', userId, () -> doc = docDb.findOne "Home" unless doc doc = { _id: "Home", text: "Placeholder..." } docDb.insert doc console.log "Ready!", doc editor.setValue doc.text updateDoc() Meteor.startup () -> # code to run on client at startup ############################################################################## if Meteor.isServer pdc = Async.wrap Meteor.npmRequire('pdc') Meteor.publish 'allDocs', (clientUserId) -> if this.userId is clientUserId return docDb.find {} else return [] docDb.allow insert: (userId, doc) -> true update: (userId, file, fieldNames, modifier) -> true remove: (userId, doc) -> true Meteor.startup () -> # code to run on server at startup Meteor.methods pandoc: (txt) -> check txt, String console.log "Called with: #{txt}" res = pdc txt, "markdown", "html" console.log "Result: #{res}" return res
true
############################################################################ # Copyright (C) 2015 by PI:NAME:<NAME>END_PI # SimpleWiki is free software released under the MIT/X11 license. # See included LICENSE file for details. ############################################################################ docDb = new Mongo.Collection "docDB" if Meteor.isClient editor = null doc = "Loading..." text = new ReactiveVar doc init = new ReactiveVar false Template.document.helpers textHelp: () -> console.log "Getting text!" text.get() Template.editor.events 'click #commitButton': (e, t) -> console.log "Make Commit" docDb.update "Home", { $set: { text: editor.getValue() }} updateDoc = () -> timeout = null Meteor.call 'pandoc', editor.getValue(), (err, res) -> unless err text.set res else console.warn "Pandoc method failed with #{err}" Template.editor.onRendered () -> AceEditor.instance "edit", { theme: "dawn", mode: "markdown" }, (e) -> editor = e init.set true timeout = null editor.on 'change', (e) -> console.log "Changed!" console.log e unless timeout timeout = Meteor.setTimeout updateDoc, 2500 # Set up an autorun to keep the X-Auth-Token cookie up-to-date and # to update the subscription when the userId changes. Tracker.autorun () -> userId = null # Enable these when accounts support added # userId = Meteor.userId() # $.cookie 'X-Auth-Token', Accounts._storedLoginToken() if init.get() console.log "Setting up subscription" Meteor.subscribe 'allDocs', userId, () -> doc = docDb.findOne "Home" unless doc doc = { _id: "Home", text: "Placeholder..." } docDb.insert doc console.log "Ready!", doc editor.setValue doc.text updateDoc() Meteor.startup () -> # code to run on client at startup ############################################################################## if Meteor.isServer pdc = Async.wrap Meteor.npmRequire('pdc') Meteor.publish 'allDocs', (clientUserId) -> if this.userId is clientUserId return docDb.find {} else return [] docDb.allow insert: (userId, doc) -> true update: (userId, file, fieldNames, modifier) -> true remove: (userId, doc) -> true Meteor.startup () -> # code to run on server at startup Meteor.methods pandoc: (txt) -> check txt, String console.log "Called with: #{txt}" res = pdc txt, "markdown", "html" console.log "Result: #{res}" return res
[ { "context": " \"test\"\n source_password: \"abc123\"\n root_route: true\n seconds", "end": 193, "score": 0.9981609582901001, "start": 187, "tag": "PASSWORD", "value": "abc123" }, { "context": " config\n\n info.api_uri = \"http://127.0.0.1:#{info.port}/api\"\n\n cb null, info\n", "end": 1374, "score": 0.9994461536407471, "start": 1365, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
test/helpers/standalone.coffee
VandeurenGlenn/StreamMachine
0
StandaloneMode = $src "modes/standalone" uuid = require "node-uuid" _ = require "underscore" STREAMS = mp3: key: "test" source_password: "abc123" root_route: true seconds: 60*60*4 format: "mp3" module.exports = STREAMS: STREAMS startStandalone: (stream,cb) -> s = STREAMS[stream] if stream && !s cb new Error "Invalid stream spec" return false config = port: 0 source_port: 0 log: stdout: false streams: {} sconfig = null if stream # generate a random stream key streamkey = uuid.v4() sconfig = config.streams[ streamkey ] = _.extend {}, s, key:streamkey new StandaloneMode config, (err,sa) -> throw err if err info = standalone: sa port: sa.handle?.address().port source_port: sa.master.sourcein.server.address().port stream_key: sconfig?.key source_password: sconfig?.source_password slave_uri: "" config: config info.api_uri = "http://127.0.0.1:#{info.port}/api" cb null, info
135602
StandaloneMode = $src "modes/standalone" uuid = require "node-uuid" _ = require "underscore" STREAMS = mp3: key: "test" source_password: "<PASSWORD>" root_route: true seconds: 60*60*4 format: "mp3" module.exports = STREAMS: STREAMS startStandalone: (stream,cb) -> s = STREAMS[stream] if stream && !s cb new Error "Invalid stream spec" return false config = port: 0 source_port: 0 log: stdout: false streams: {} sconfig = null if stream # generate a random stream key streamkey = uuid.v4() sconfig = config.streams[ streamkey ] = _.extend {}, s, key:streamkey new StandaloneMode config, (err,sa) -> throw err if err info = standalone: sa port: sa.handle?.address().port source_port: sa.master.sourcein.server.address().port stream_key: sconfig?.key source_password: sconfig?.source_password slave_uri: "" config: config info.api_uri = "http://127.0.0.1:#{info.port}/api" cb null, info
true
StandaloneMode = $src "modes/standalone" uuid = require "node-uuid" _ = require "underscore" STREAMS = mp3: key: "test" source_password: "PI:PASSWORD:<PASSWORD>END_PI" root_route: true seconds: 60*60*4 format: "mp3" module.exports = STREAMS: STREAMS startStandalone: (stream,cb) -> s = STREAMS[stream] if stream && !s cb new Error "Invalid stream spec" return false config = port: 0 source_port: 0 log: stdout: false streams: {} sconfig = null if stream # generate a random stream key streamkey = uuid.v4() sconfig = config.streams[ streamkey ] = _.extend {}, s, key:streamkey new StandaloneMode config, (err,sa) -> throw err if err info = standalone: sa port: sa.handle?.address().port source_port: sa.master.sourcein.server.address().port stream_key: sconfig?.key source_password: sconfig?.source_password slave_uri: "" config: config info.api_uri = "http://127.0.0.1:#{info.port}/api" cb null, info
[ { "context": " email: $scope.cred.username\n password: $scope.cred.password\n $http.post('/api/verifyUser', creds).success(", "end": 461, "score": 0.9841769933700562, "start": 442, "tag": "PASSWORD", "value": "scope.cred.password" }, { "context": "ngs, (setting) ->\n setting.key is 'facebookAppId'\n )\n if appId?.length > 0\n Faceb", "end": 1649, "score": 0.7358535528182983, "start": 1644, "tag": "KEY", "value": "AppId" } ]
client/controllers/login.coffee
sterob7/gi-security
0
angular.module('gi.security').controller 'loginController' , ['$scope', '$http', '$filter' , 'Auth', 'Facebook', 'Setting' , ( $scope, $http, $filter , Auth, Facebook, Setting) -> #when we're in this controller we should keep testing to see #if the user has managed to login yet. $scope.loginStatus = failed: false $scope.verify = () -> #$scope.tokenMode = true creds = email: $scope.cred.username password: $scope.cred.password $http.post('/api/verifyUser', creds).success( (user) -> if user.valid if user.twoFactorEnabled $scope.tokenMode = true else $scope.login() else $scope.tokenMode = false $scope.loginStatus.failed = true ).error () -> $scope.tokenMode = false $scope.loginStatus.failed = true $scope.login = () -> $http.post('/api/login', $scope.cred).success( () -> Auth.loginConfirmed() ).error () -> $scope.tokenMode = false $scope.loginStatus.failed = true $scope.loginWithFacebook = () -> Facebook.login().then (loggedIn) -> if loggedIn Auth.loginConfirmed() $scope.dismissLoginAlert = () -> $scope.loginStatus.failed = false Setting.all().then (settings) -> allowFacebookLogin = $filter('filter')(settings, (setting) -> setting.key is 'loginWithFacebook' ) if allowFacebookLogin?.length > 0 $scope.allowFacebookLogin = allowFacebookLogin[0].value else $scope.allowFacebookLogin = false if $scope.allowFacebookLogin appId = $filter('filter')(settings, (setting) -> setting.key is 'facebookAppId' ) if appId?.length > 0 Facebook.init appId[0].value else console.log 'error initializing facebook login' ]
3510
angular.module('gi.security').controller 'loginController' , ['$scope', '$http', '$filter' , 'Auth', 'Facebook', 'Setting' , ( $scope, $http, $filter , Auth, Facebook, Setting) -> #when we're in this controller we should keep testing to see #if the user has managed to login yet. $scope.loginStatus = failed: false $scope.verify = () -> #$scope.tokenMode = true creds = email: $scope.cred.username password: $<PASSWORD> $http.post('/api/verifyUser', creds).success( (user) -> if user.valid if user.twoFactorEnabled $scope.tokenMode = true else $scope.login() else $scope.tokenMode = false $scope.loginStatus.failed = true ).error () -> $scope.tokenMode = false $scope.loginStatus.failed = true $scope.login = () -> $http.post('/api/login', $scope.cred).success( () -> Auth.loginConfirmed() ).error () -> $scope.tokenMode = false $scope.loginStatus.failed = true $scope.loginWithFacebook = () -> Facebook.login().then (loggedIn) -> if loggedIn Auth.loginConfirmed() $scope.dismissLoginAlert = () -> $scope.loginStatus.failed = false Setting.all().then (settings) -> allowFacebookLogin = $filter('filter')(settings, (setting) -> setting.key is 'loginWithFacebook' ) if allowFacebookLogin?.length > 0 $scope.allowFacebookLogin = allowFacebookLogin[0].value else $scope.allowFacebookLogin = false if $scope.allowFacebookLogin appId = $filter('filter')(settings, (setting) -> setting.key is 'facebook<KEY>' ) if appId?.length > 0 Facebook.init appId[0].value else console.log 'error initializing facebook login' ]
true
angular.module('gi.security').controller 'loginController' , ['$scope', '$http', '$filter' , 'Auth', 'Facebook', 'Setting' , ( $scope, $http, $filter , Auth, Facebook, Setting) -> #when we're in this controller we should keep testing to see #if the user has managed to login yet. $scope.loginStatus = failed: false $scope.verify = () -> #$scope.tokenMode = true creds = email: $scope.cred.username password: $PI:PASSWORD:<PASSWORD>END_PI $http.post('/api/verifyUser', creds).success( (user) -> if user.valid if user.twoFactorEnabled $scope.tokenMode = true else $scope.login() else $scope.tokenMode = false $scope.loginStatus.failed = true ).error () -> $scope.tokenMode = false $scope.loginStatus.failed = true $scope.login = () -> $http.post('/api/login', $scope.cred).success( () -> Auth.loginConfirmed() ).error () -> $scope.tokenMode = false $scope.loginStatus.failed = true $scope.loginWithFacebook = () -> Facebook.login().then (loggedIn) -> if loggedIn Auth.loginConfirmed() $scope.dismissLoginAlert = () -> $scope.loginStatus.failed = false Setting.all().then (settings) -> allowFacebookLogin = $filter('filter')(settings, (setting) -> setting.key is 'loginWithFacebook' ) if allowFacebookLogin?.length > 0 $scope.allowFacebookLogin = allowFacebookLogin[0].value else $scope.allowFacebookLogin = false if $scope.allowFacebookLogin appId = $filter('filter')(settings, (setting) -> setting.key is 'facebookPI:KEY:<KEY>END_PI' ) if appId?.length > 0 Facebook.init appId[0].value else console.log 'error initializing facebook login' ]
[ { "context": " new Restivus\n useAuth: true\n auth: token: 'apiKey'\n defaultHeaders:\n 'Content-Type': 'text/", "end": 81, "score": 0.9818935394287109, "start": 75, "tag": "KEY", "value": "apiKey" }, { "context": "seAuth, true\n test.equal config.auth.token, 'apiKey'\n test.equal config.defaultHeaders['Content-", "end": 488, "score": 0.9574760794639587, "start": 482, "tag": "KEY", "value": "apiKey" }, { "context": " get: ->\n test.equal @queryParams.key1, '1234'\n test.equal @queryParams.key2, 'abcd'\n ", "end": 8112, "score": 0.9984584450721741, "start": 8108, "tag": "KEY", "value": "1234" }, { "context": ", '1234'\n test.equal @queryParams.key2, 'abcd'\n test.equal @queryParams.key3, 'a1b2'\n ", "end": 8159, "score": 0.9826949238777161, "start": 8155, "tag": "KEY", "value": "abcd" }, { "context": ", 'abcd'\n test.equal @queryParams.key3, 'a1b2'\n true\n\n HTTP.get Meteor.absoluteUr", "end": 8206, "score": 0.997442901134491, "start": 8202, "tag": "KEY", "value": "a1b2" }, { "context": "et Meteor.absoluteUrl('api/mult-query-params?key1=1234&key2=abcd&key3=a1b2'), waitFor (error, result) ->", "end": 8290, "score": 0.9980164766311646, "start": 8286, "tag": "KEY", "value": "1234" }, { "context": "absoluteUrl('api/mult-query-params?key1=1234&key2=abcd&key3=a1b2'), waitFor (error, result) ->\n t", "end": 8300, "score": 0.8806782364845276, "start": 8296, "tag": "KEY", "value": "abcd" }, { "context": "('api/mult-query-params?key1=1234&key2=abcd&key3=a1b2'), waitFor (error, result) ->\n test.isTrue", "end": 8310, "score": 0.8139918446540833, "start": 8307, "tag": "KEY", "value": "1b2" } ]
test/api_tests.coffee
adthrasher/meteor-restivus
613
Meteor.startup -> Api = new Restivus useAuth: true auth: token: 'apiKey' defaultHeaders: 'Content-Type': 'text/json' 'X-Test-Header': 'test header' defaultOptionsEndpoint: -> headers: 'Content-Type': 'text/plain' body: 'options' describe 'An API', -> it 'should allow the default configuration to be overridden', (test) -> config = Api._config test.equal config.useAuth, true test.equal config.auth.token, 'apiKey' test.equal config.defaultHeaders['Content-Type'], 'text/json' test.equal config.defaultHeaders['X-Test-Header'], 'test header' test.equal config.defaultHeaders['Access-Control-Allow-Origin'], '*' it 'should append its version to the base URL path', (test, waitFor) -> AppendVersion = new Restivus version: 'v1' config = AppendVersion._config test.equal config.apiPath, 'api/v1/' # Test with custom base path AppendVersion2 = new Restivus apiPath: 'test' version: 'v1' config = AppendVersion2._config test.equal config.apiPath, 'test/v1/' it 'should support multiple versions of the same endpoint', (test, waitFor) -> ApiV1 = new Restivus version: 'v1' ApiV1.addRoute 'multiple-versions', get: -> 'get something' ApiV2 = new Restivus version: 'v2' ApiV2.addRoute 'multiple-versions', get: -> status: 'success' data: 'get something different' HTTP.get Meteor.absoluteUrl('api/v1/multiple-versions'), waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 200 test.equal response, 'get something' HTTP.get Meteor.absoluteUrl('api/v2/multiple-versions'), waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data, 'get something different' describe 'An API route', -> it 'should use the default OPTIONS endpoint if none is defined for the requested method', (test, waitFor) -> Api.addRoute 'default-endpoints', get: -> 'get' HTTP.call 'OPTIONS', Meteor.absoluteUrl('api/default-endpoints'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'options' describe 'An API collection route', -> it 'should be able to exclude endpoints using just the excludedEndpoints option', (test, waitFor) -> Api.addCollection new Mongo.Collection('excluded-endpoints'), excludedEndpoints: ['get', 'getAll'] HTTP.get Meteor.absoluteUrl('api/excluded-endpoints/10'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' HTTP.get Meteor.absoluteUrl('api/excluded-endpoints/'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' # Make sure it doesn't exclude any endpoints it shouldn't HTTP.post Meteor.absoluteUrl('api/excluded-endpoints/'), {data: test: 'abc'}, waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 201 test.equal response.status, 'success' test.equal response.data.test, 'abc' describe 'with the default autogenerated endpoints', -> Api.addCollection new Mongo.Collection('autogen') testId = null it 'should support a POST on api/collection', (test) -> result = HTTP.post Meteor.absoluteUrl('api/autogen'), data: name: 'test name' description: 'test description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 201 test.equal response.status, 'success' test.equal responseData.name, 'test name' test.equal responseData.description, 'test description' # Persist the new resource id testId = responseData._id it 'should not support a DELETE on api/collection', (test, waitFor) -> HTTP.del Meteor.absoluteUrl('api/autogen'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.isTrue result.headers['allow'].indexOf('POST') != -1 test.isTrue result.headers['allow'].indexOf('GET') != -1 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' it 'should support a PUT on api/collection/:id', (test) -> result = HTTP.put Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'update name' description: 'update description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'update name' test.equal responseData.description, 'update description' result = HTTP.put Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'update name with no description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'update name with no description' test.isUndefined responseData.description it 'should support a PATCH on api/collection/:id', (test) -> result = HTTP.patch Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'new name' description: 'new description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'new name' test.equal responseData.description, 'new description' result = HTTP.patch Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'new name with no description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'new name with no description' test.equal responseData.description, 'new description' describe 'An API endpoint', -> it 'should respond with the default headers when not overridden', (test) -> Api.addRoute 'default-headers', get: -> true result = HTTP.get Meteor.absoluteUrl 'api/default-headers' test.equal result.statusCode, 200 test.equal result.headers['content-type'], 'text/json' test.equal result.headers['x-test-header'], 'test header' test.equal result.headers['access-control-allow-origin'], '*' test.isTrue result.content it 'should allow default headers to be overridden', (test) -> Api.addRoute 'override-default-headers', get: -> headers: 'Content-Type': 'application/json' 'Access-Control-Allow-Origin': 'https://mywebsite.com' body: true result = HTTP.get Meteor.absoluteUrl 'api/override-default-headers' test.equal result.statusCode, 200 test.equal result.headers['content-type'], 'application/json' test.equal result.headers['access-control-allow-origin'], 'https://mywebsite.com' test.isTrue result.content it 'should have access to multiple query params', (test, waitFor) -> Api.addRoute 'mult-query-params', get: -> test.equal @queryParams.key1, '1234' test.equal @queryParams.key2, 'abcd' test.equal @queryParams.key3, 'a1b2' true HTTP.get Meteor.absoluteUrl('api/mult-query-params?key1=1234&key2=abcd&key3=a1b2'), waitFor (error, result) -> test.isTrue result it 'should return a 405 error if that method is not implemented on the route', (test, waitFor) -> Api.addCollection new Mongo.Collection('method-not-implemented'), excludedEndpoints: ['get', 'getAll'] HTTP.get Meteor.absoluteUrl('api/method-not-implemented/'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' HTTP.get Meteor.absoluteUrl('api/method-not-implemented/10'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.isTrue result.headers['allow'].indexOf('PUT') != -1 test.isTrue result.headers['allow'].indexOf('DELETE') != -1 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' it 'should cause an error when it returns null', (test, waitFor) -> Api.addRoute 'null-response', get: -> null HTTP.get Meteor.absoluteUrl('api/null-response'), waitFor (error, result) -> test.isTrue error test.equal result.statusCode, 500 it 'should cause an error when it returns undefined', (test, waitFor) -> Api.addRoute 'undefined-response', get: -> undefined HTTP.get Meteor.absoluteUrl('api/undefined-response'), waitFor (error, result) -> test.isTrue error test.equal result.statusCode, 500 it 'should be able to handle it\'s response manually', (test, waitFor) -> Api.addRoute 'manual-response', get: -> @response.write 'Testing manual response.' @response.end() @done() HTTP.get Meteor.absoluteUrl('api/manual-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'Testing manual response.' it 'should not have to call this.response.end() when handling the response manually', (test, waitFor) -> Api.addRoute 'manual-response-no-end', get: -> @response.write 'Testing this.end()' @done() HTTP.get Meteor.absoluteUrl('api/manual-response-no-end'), waitFor (error, result) -> response = result.content test.isFalse error test.equal result.statusCode, 200 test.equal response, 'Testing this.end()' it 'should be able to send it\'s response in chunks', (test, waitFor) -> Api.addRoute 'chunked-response', get: -> @response.write 'Testing ' @response.write 'chunked response.' @done() HTTP.get Meteor.absoluteUrl('api/chunked-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'Testing chunked response.' # it 'should respond with an error if this.done() isn\'t called after response is handled manually', (test, waitFor) -> # Api.addRoute 'manual-response-without-done', # get: -> # @response.write 'Testing' # # HTTP.get Meteor.absoluteUrl('api/manual-response-without-done'), waitFor (error, result) -> # test.isTrue error # test.equal result.statusCode, 500 it 'should not wrap text with quotes when response Content-Type is text/plain', (test, waitFor) -> Api.addRoute 'plain-text-response', get: -> headers: 'Content-Type': 'text/plain' body: 'foo"bar' HTTP.get Meteor.absoluteUrl('api/plain-text-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'foo"bar' it 'should have its context set', (test) -> Api.addRoute 'context/:test', post: -> test.equal @urlParams.test, '100' test.equal @queryParams.test, 'query' test.equal @bodyParams.test, 'body' test.isNotNull @request test.isNotNull @response test.isTrue _.isFunction @done test.isFalse @authRequired test.isFalse @roleRequired true result = HTTP.post Meteor.absoluteUrl('api/context/100?test=query'), data: test: 'body' test.equal result.statusCode, 200 test.isTrue result.content
165049
Meteor.startup -> Api = new Restivus useAuth: true auth: token: '<KEY>' defaultHeaders: 'Content-Type': 'text/json' 'X-Test-Header': 'test header' defaultOptionsEndpoint: -> headers: 'Content-Type': 'text/plain' body: 'options' describe 'An API', -> it 'should allow the default configuration to be overridden', (test) -> config = Api._config test.equal config.useAuth, true test.equal config.auth.token, '<KEY>' test.equal config.defaultHeaders['Content-Type'], 'text/json' test.equal config.defaultHeaders['X-Test-Header'], 'test header' test.equal config.defaultHeaders['Access-Control-Allow-Origin'], '*' it 'should append its version to the base URL path', (test, waitFor) -> AppendVersion = new Restivus version: 'v1' config = AppendVersion._config test.equal config.apiPath, 'api/v1/' # Test with custom base path AppendVersion2 = new Restivus apiPath: 'test' version: 'v1' config = AppendVersion2._config test.equal config.apiPath, 'test/v1/' it 'should support multiple versions of the same endpoint', (test, waitFor) -> ApiV1 = new Restivus version: 'v1' ApiV1.addRoute 'multiple-versions', get: -> 'get something' ApiV2 = new Restivus version: 'v2' ApiV2.addRoute 'multiple-versions', get: -> status: 'success' data: 'get something different' HTTP.get Meteor.absoluteUrl('api/v1/multiple-versions'), waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 200 test.equal response, 'get something' HTTP.get Meteor.absoluteUrl('api/v2/multiple-versions'), waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data, 'get something different' describe 'An API route', -> it 'should use the default OPTIONS endpoint if none is defined for the requested method', (test, waitFor) -> Api.addRoute 'default-endpoints', get: -> 'get' HTTP.call 'OPTIONS', Meteor.absoluteUrl('api/default-endpoints'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'options' describe 'An API collection route', -> it 'should be able to exclude endpoints using just the excludedEndpoints option', (test, waitFor) -> Api.addCollection new Mongo.Collection('excluded-endpoints'), excludedEndpoints: ['get', 'getAll'] HTTP.get Meteor.absoluteUrl('api/excluded-endpoints/10'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' HTTP.get Meteor.absoluteUrl('api/excluded-endpoints/'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' # Make sure it doesn't exclude any endpoints it shouldn't HTTP.post Meteor.absoluteUrl('api/excluded-endpoints/'), {data: test: 'abc'}, waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 201 test.equal response.status, 'success' test.equal response.data.test, 'abc' describe 'with the default autogenerated endpoints', -> Api.addCollection new Mongo.Collection('autogen') testId = null it 'should support a POST on api/collection', (test) -> result = HTTP.post Meteor.absoluteUrl('api/autogen'), data: name: 'test name' description: 'test description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 201 test.equal response.status, 'success' test.equal responseData.name, 'test name' test.equal responseData.description, 'test description' # Persist the new resource id testId = responseData._id it 'should not support a DELETE on api/collection', (test, waitFor) -> HTTP.del Meteor.absoluteUrl('api/autogen'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.isTrue result.headers['allow'].indexOf('POST') != -1 test.isTrue result.headers['allow'].indexOf('GET') != -1 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' it 'should support a PUT on api/collection/:id', (test) -> result = HTTP.put Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'update name' description: 'update description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'update name' test.equal responseData.description, 'update description' result = HTTP.put Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'update name with no description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'update name with no description' test.isUndefined responseData.description it 'should support a PATCH on api/collection/:id', (test) -> result = HTTP.patch Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'new name' description: 'new description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'new name' test.equal responseData.description, 'new description' result = HTTP.patch Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'new name with no description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'new name with no description' test.equal responseData.description, 'new description' describe 'An API endpoint', -> it 'should respond with the default headers when not overridden', (test) -> Api.addRoute 'default-headers', get: -> true result = HTTP.get Meteor.absoluteUrl 'api/default-headers' test.equal result.statusCode, 200 test.equal result.headers['content-type'], 'text/json' test.equal result.headers['x-test-header'], 'test header' test.equal result.headers['access-control-allow-origin'], '*' test.isTrue result.content it 'should allow default headers to be overridden', (test) -> Api.addRoute 'override-default-headers', get: -> headers: 'Content-Type': 'application/json' 'Access-Control-Allow-Origin': 'https://mywebsite.com' body: true result = HTTP.get Meteor.absoluteUrl 'api/override-default-headers' test.equal result.statusCode, 200 test.equal result.headers['content-type'], 'application/json' test.equal result.headers['access-control-allow-origin'], 'https://mywebsite.com' test.isTrue result.content it 'should have access to multiple query params', (test, waitFor) -> Api.addRoute 'mult-query-params', get: -> test.equal @queryParams.key1, '<KEY>' test.equal @queryParams.key2, '<KEY>' test.equal @queryParams.key3, '<KEY>' true HTTP.get Meteor.absoluteUrl('api/mult-query-params?key1=<KEY>&key2=<KEY>&key3=a<KEY>'), waitFor (error, result) -> test.isTrue result it 'should return a 405 error if that method is not implemented on the route', (test, waitFor) -> Api.addCollection new Mongo.Collection('method-not-implemented'), excludedEndpoints: ['get', 'getAll'] HTTP.get Meteor.absoluteUrl('api/method-not-implemented/'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' HTTP.get Meteor.absoluteUrl('api/method-not-implemented/10'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.isTrue result.headers['allow'].indexOf('PUT') != -1 test.isTrue result.headers['allow'].indexOf('DELETE') != -1 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' it 'should cause an error when it returns null', (test, waitFor) -> Api.addRoute 'null-response', get: -> null HTTP.get Meteor.absoluteUrl('api/null-response'), waitFor (error, result) -> test.isTrue error test.equal result.statusCode, 500 it 'should cause an error when it returns undefined', (test, waitFor) -> Api.addRoute 'undefined-response', get: -> undefined HTTP.get Meteor.absoluteUrl('api/undefined-response'), waitFor (error, result) -> test.isTrue error test.equal result.statusCode, 500 it 'should be able to handle it\'s response manually', (test, waitFor) -> Api.addRoute 'manual-response', get: -> @response.write 'Testing manual response.' @response.end() @done() HTTP.get Meteor.absoluteUrl('api/manual-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'Testing manual response.' it 'should not have to call this.response.end() when handling the response manually', (test, waitFor) -> Api.addRoute 'manual-response-no-end', get: -> @response.write 'Testing this.end()' @done() HTTP.get Meteor.absoluteUrl('api/manual-response-no-end'), waitFor (error, result) -> response = result.content test.isFalse error test.equal result.statusCode, 200 test.equal response, 'Testing this.end()' it 'should be able to send it\'s response in chunks', (test, waitFor) -> Api.addRoute 'chunked-response', get: -> @response.write 'Testing ' @response.write 'chunked response.' @done() HTTP.get Meteor.absoluteUrl('api/chunked-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'Testing chunked response.' # it 'should respond with an error if this.done() isn\'t called after response is handled manually', (test, waitFor) -> # Api.addRoute 'manual-response-without-done', # get: -> # @response.write 'Testing' # # HTTP.get Meteor.absoluteUrl('api/manual-response-without-done'), waitFor (error, result) -> # test.isTrue error # test.equal result.statusCode, 500 it 'should not wrap text with quotes when response Content-Type is text/plain', (test, waitFor) -> Api.addRoute 'plain-text-response', get: -> headers: 'Content-Type': 'text/plain' body: 'foo"bar' HTTP.get Meteor.absoluteUrl('api/plain-text-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'foo"bar' it 'should have its context set', (test) -> Api.addRoute 'context/:test', post: -> test.equal @urlParams.test, '100' test.equal @queryParams.test, 'query' test.equal @bodyParams.test, 'body' test.isNotNull @request test.isNotNull @response test.isTrue _.isFunction @done test.isFalse @authRequired test.isFalse @roleRequired true result = HTTP.post Meteor.absoluteUrl('api/context/100?test=query'), data: test: 'body' test.equal result.statusCode, 200 test.isTrue result.content
true
Meteor.startup -> Api = new Restivus useAuth: true auth: token: 'PI:KEY:<KEY>END_PI' defaultHeaders: 'Content-Type': 'text/json' 'X-Test-Header': 'test header' defaultOptionsEndpoint: -> headers: 'Content-Type': 'text/plain' body: 'options' describe 'An API', -> it 'should allow the default configuration to be overridden', (test) -> config = Api._config test.equal config.useAuth, true test.equal config.auth.token, 'PI:KEY:<KEY>END_PI' test.equal config.defaultHeaders['Content-Type'], 'text/json' test.equal config.defaultHeaders['X-Test-Header'], 'test header' test.equal config.defaultHeaders['Access-Control-Allow-Origin'], '*' it 'should append its version to the base URL path', (test, waitFor) -> AppendVersion = new Restivus version: 'v1' config = AppendVersion._config test.equal config.apiPath, 'api/v1/' # Test with custom base path AppendVersion2 = new Restivus apiPath: 'test' version: 'v1' config = AppendVersion2._config test.equal config.apiPath, 'test/v1/' it 'should support multiple versions of the same endpoint', (test, waitFor) -> ApiV1 = new Restivus version: 'v1' ApiV1.addRoute 'multiple-versions', get: -> 'get something' ApiV2 = new Restivus version: 'v2' ApiV2.addRoute 'multiple-versions', get: -> status: 'success' data: 'get something different' HTTP.get Meteor.absoluteUrl('api/v1/multiple-versions'), waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 200 test.equal response, 'get something' HTTP.get Meteor.absoluteUrl('api/v2/multiple-versions'), waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal response.data, 'get something different' describe 'An API route', -> it 'should use the default OPTIONS endpoint if none is defined for the requested method', (test, waitFor) -> Api.addRoute 'default-endpoints', get: -> 'get' HTTP.call 'OPTIONS', Meteor.absoluteUrl('api/default-endpoints'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'options' describe 'An API collection route', -> it 'should be able to exclude endpoints using just the excludedEndpoints option', (test, waitFor) -> Api.addCollection new Mongo.Collection('excluded-endpoints'), excludedEndpoints: ['get', 'getAll'] HTTP.get Meteor.absoluteUrl('api/excluded-endpoints/10'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' HTTP.get Meteor.absoluteUrl('api/excluded-endpoints/'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' # Make sure it doesn't exclude any endpoints it shouldn't HTTP.post Meteor.absoluteUrl('api/excluded-endpoints/'), {data: test: 'abc'}, waitFor (error, result) -> response = JSON.parse result.content test.equal result.statusCode, 201 test.equal response.status, 'success' test.equal response.data.test, 'abc' describe 'with the default autogenerated endpoints', -> Api.addCollection new Mongo.Collection('autogen') testId = null it 'should support a POST on api/collection', (test) -> result = HTTP.post Meteor.absoluteUrl('api/autogen'), data: name: 'test name' description: 'test description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 201 test.equal response.status, 'success' test.equal responseData.name, 'test name' test.equal responseData.description, 'test description' # Persist the new resource id testId = responseData._id it 'should not support a DELETE on api/collection', (test, waitFor) -> HTTP.del Meteor.absoluteUrl('api/autogen'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.isTrue result.headers['allow'].indexOf('POST') != -1 test.isTrue result.headers['allow'].indexOf('GET') != -1 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' it 'should support a PUT on api/collection/:id', (test) -> result = HTTP.put Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'update name' description: 'update description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'update name' test.equal responseData.description, 'update description' result = HTTP.put Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'update name with no description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'update name with no description' test.isUndefined responseData.description it 'should support a PATCH on api/collection/:id', (test) -> result = HTTP.patch Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'new name' description: 'new description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'new name' test.equal responseData.description, 'new description' result = HTTP.patch Meteor.absoluteUrl("api/autogen/#{testId}"), data: name: 'new name with no description' response = JSON.parse result.content responseData = response.data test.equal result.statusCode, 200 test.equal response.status, 'success' test.equal responseData.name, 'new name with no description' test.equal responseData.description, 'new description' describe 'An API endpoint', -> it 'should respond with the default headers when not overridden', (test) -> Api.addRoute 'default-headers', get: -> true result = HTTP.get Meteor.absoluteUrl 'api/default-headers' test.equal result.statusCode, 200 test.equal result.headers['content-type'], 'text/json' test.equal result.headers['x-test-header'], 'test header' test.equal result.headers['access-control-allow-origin'], '*' test.isTrue result.content it 'should allow default headers to be overridden', (test) -> Api.addRoute 'override-default-headers', get: -> headers: 'Content-Type': 'application/json' 'Access-Control-Allow-Origin': 'https://mywebsite.com' body: true result = HTTP.get Meteor.absoluteUrl 'api/override-default-headers' test.equal result.statusCode, 200 test.equal result.headers['content-type'], 'application/json' test.equal result.headers['access-control-allow-origin'], 'https://mywebsite.com' test.isTrue result.content it 'should have access to multiple query params', (test, waitFor) -> Api.addRoute 'mult-query-params', get: -> test.equal @queryParams.key1, 'PI:KEY:<KEY>END_PI' test.equal @queryParams.key2, 'PI:KEY:<KEY>END_PI' test.equal @queryParams.key3, 'PI:KEY:<KEY>END_PI' true HTTP.get Meteor.absoluteUrl('api/mult-query-params?key1=PI:KEY:<KEY>END_PI&key2=PI:KEY:<KEY>END_PI&key3=aPI:KEY:<KEY>END_PI'), waitFor (error, result) -> test.isTrue result it 'should return a 405 error if that method is not implemented on the route', (test, waitFor) -> Api.addCollection new Mongo.Collection('method-not-implemented'), excludedEndpoints: ['get', 'getAll'] HTTP.get Meteor.absoluteUrl('api/method-not-implemented/'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' HTTP.get Meteor.absoluteUrl('api/method-not-implemented/10'), waitFor (error, result) -> response = JSON.parse result.content test.isTrue error test.equal result.statusCode, 405 test.isTrue result.headers['allow'].indexOf('PUT') != -1 test.isTrue result.headers['allow'].indexOf('DELETE') != -1 test.equal response.status, 'error' test.equal response.message, 'API endpoint does not exist' it 'should cause an error when it returns null', (test, waitFor) -> Api.addRoute 'null-response', get: -> null HTTP.get Meteor.absoluteUrl('api/null-response'), waitFor (error, result) -> test.isTrue error test.equal result.statusCode, 500 it 'should cause an error when it returns undefined', (test, waitFor) -> Api.addRoute 'undefined-response', get: -> undefined HTTP.get Meteor.absoluteUrl('api/undefined-response'), waitFor (error, result) -> test.isTrue error test.equal result.statusCode, 500 it 'should be able to handle it\'s response manually', (test, waitFor) -> Api.addRoute 'manual-response', get: -> @response.write 'Testing manual response.' @response.end() @done() HTTP.get Meteor.absoluteUrl('api/manual-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'Testing manual response.' it 'should not have to call this.response.end() when handling the response manually', (test, waitFor) -> Api.addRoute 'manual-response-no-end', get: -> @response.write 'Testing this.end()' @done() HTTP.get Meteor.absoluteUrl('api/manual-response-no-end'), waitFor (error, result) -> response = result.content test.isFalse error test.equal result.statusCode, 200 test.equal response, 'Testing this.end()' it 'should be able to send it\'s response in chunks', (test, waitFor) -> Api.addRoute 'chunked-response', get: -> @response.write 'Testing ' @response.write 'chunked response.' @done() HTTP.get Meteor.absoluteUrl('api/chunked-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'Testing chunked response.' # it 'should respond with an error if this.done() isn\'t called after response is handled manually', (test, waitFor) -> # Api.addRoute 'manual-response-without-done', # get: -> # @response.write 'Testing' # # HTTP.get Meteor.absoluteUrl('api/manual-response-without-done'), waitFor (error, result) -> # test.isTrue error # test.equal result.statusCode, 500 it 'should not wrap text with quotes when response Content-Type is text/plain', (test, waitFor) -> Api.addRoute 'plain-text-response', get: -> headers: 'Content-Type': 'text/plain' body: 'foo"bar' HTTP.get Meteor.absoluteUrl('api/plain-text-response'), waitFor (error, result) -> response = result.content test.equal result.statusCode, 200 test.equal response, 'foo"bar' it 'should have its context set', (test) -> Api.addRoute 'context/:test', post: -> test.equal @urlParams.test, '100' test.equal @queryParams.test, 'query' test.equal @bodyParams.test, 'body' test.isNotNull @request test.isNotNull @response test.isTrue _.isFunction @done test.isFalse @authRequired test.isFalse @roleRequired true result = HTTP.post Meteor.absoluteUrl('api/context/100?test=query'), data: test: 'body' test.equal result.statusCode, 200 test.isTrue result.content
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998879432678223, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespin", "end": 52, "score": 0.9999309182167053, "start": 40, "tag": "EMAIL", "value": "niwi@niwi.be" }, { "context": " Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David B", "end": 94, "score": 0.9998794198036194, "start": 75, "tag": "NAME", "value": "Jesús Espino Garcia" }, { "context": "iwi.be>\n# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bame", "end": 114, "score": 0.9999343156814575, "start": 96, "tag": "EMAIL", "value": "jespinog@gmail.com" }, { "context": "o Garcia <jespinog@gmail.com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free s", "end": 158, "score": 0.9998791813850403, "start": 137, "tag": "NAME", "value": "David Barragán Merino" }, { "context": ".com>\n# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>\n#\n# This program is free software: you can redis", "end": 180, "score": 0.999934196472168, "start": 160, "tag": "EMAIL", "value": "bameda@dbarragan.com" } ]
public/taiga-front/app/coffee/modules/resources/issues.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/resources/issues.coffee ### taiga = @.taiga generateHash = taiga.generateHash resourceProvider = ($repo, $http, $urls, $storage, $q) -> service = {} hashSuffix = "issues-queryparams" filtersHashSuffix = "issues-filters" myFiltersHashSuffix = "issues-my-filters" service.get = (projectId, issueId) -> params = service.getQueryParams(projectId) params.project = projectId return $repo.queryOne("issues", issueId, params) service.list = (projectId, filters, options) -> params = {project: projectId} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryPaginated("issues", params, options) service.bulkCreate = (projectId, data) -> url = $urls.resolve("bulk-create-issues") params = {project_id: projectId, bulk_issues: data} return $http.post(url, params) service.stats = (projectId) -> return $repo.queryOneRaw("projects", "#{projectId}/issues_stats") service.filtersData = (projectId) -> return $repo.queryOneRaw("projects", "#{projectId}/issue_filters_data") service.listValues = (projectId, type) -> params = {"project": projectId} service.storeQueryParams(projectId, params) return $repo.queryMany(type, params) service.storeQueryParams = (projectId, params) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) $storage.set(hash, params) service.getQueryParams = (projectId) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) return $storage.get(hash) or {} service.storeFilters = (projectSlug, params) -> ns = "#{projectSlug}:#{filtersHashSuffix}" hash = generateHash([projectSlug, ns]) $storage.set(hash, params) service.getFilters = (projectSlug) -> ns = "#{projectSlug}:#{filtersHashSuffix}" hash = generateHash([projectSlug, ns]) return $storage.get(hash) or {} service.storeMyFilters = (projectId, myFilters) -> deferred = $q.defer() url = $urls.resolve("user-storage") ns = "#{projectId}:#{myFiltersHashSuffix}" hash = generateHash([projectId, ns]) if _.isEmpty(myFilters) promise = $http.delete("#{url}/#{hash}", {key: hash, value:myFilters}) promise.then -> deferred.resolve() promise.then null, -> deferred.reject() else promise = $http.put("#{url}/#{hash}", {key: hash, value:myFilters}) promise.then (data) -> deferred.resolve() promise.then null, (data) -> innerPromise = $http.post("#{url}", {key: hash, value:myFilters}) innerPromise.then -> deferred.resolve() innerPromise.then null, -> deferred.reject() return deferred.promise service.getMyFilters = (projectId) -> deferred = $q.defer() url = $urls.resolve("user-storage") ns = "#{projectId}:#{myFiltersHashSuffix}" hash = generateHash([projectId, ns]) promise = $http.get("#{url}/#{hash}") promise.then (data) -> deferred.resolve(data.data.value) promise.then null, (data) -> deferred.resolve({}) return deferred.promise return (instance) -> instance.issues = service module = angular.module("taigaResources") module.factory("$tgIssuesResourcesProvider", ["$tgRepo", "$tgHttp", "$tgUrls", "$tgStorage", "$q", resourceProvider])
3277
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/resources/issues.coffee ### taiga = @.taiga generateHash = taiga.generateHash resourceProvider = ($repo, $http, $urls, $storage, $q) -> service = {} hashSuffix = "issues-queryparams" filtersHashSuffix = "issues-filters" myFiltersHashSuffix = "issues-my-filters" service.get = (projectId, issueId) -> params = service.getQueryParams(projectId) params.project = projectId return $repo.queryOne("issues", issueId, params) service.list = (projectId, filters, options) -> params = {project: projectId} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryPaginated("issues", params, options) service.bulkCreate = (projectId, data) -> url = $urls.resolve("bulk-create-issues") params = {project_id: projectId, bulk_issues: data} return $http.post(url, params) service.stats = (projectId) -> return $repo.queryOneRaw("projects", "#{projectId}/issues_stats") service.filtersData = (projectId) -> return $repo.queryOneRaw("projects", "#{projectId}/issue_filters_data") service.listValues = (projectId, type) -> params = {"project": projectId} service.storeQueryParams(projectId, params) return $repo.queryMany(type, params) service.storeQueryParams = (projectId, params) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) $storage.set(hash, params) service.getQueryParams = (projectId) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) return $storage.get(hash) or {} service.storeFilters = (projectSlug, params) -> ns = "#{projectSlug}:#{filtersHashSuffix}" hash = generateHash([projectSlug, ns]) $storage.set(hash, params) service.getFilters = (projectSlug) -> ns = "#{projectSlug}:#{filtersHashSuffix}" hash = generateHash([projectSlug, ns]) return $storage.get(hash) or {} service.storeMyFilters = (projectId, myFilters) -> deferred = $q.defer() url = $urls.resolve("user-storage") ns = "#{projectId}:#{myFiltersHashSuffix}" hash = generateHash([projectId, ns]) if _.isEmpty(myFilters) promise = $http.delete("#{url}/#{hash}", {key: hash, value:myFilters}) promise.then -> deferred.resolve() promise.then null, -> deferred.reject() else promise = $http.put("#{url}/#{hash}", {key: hash, value:myFilters}) promise.then (data) -> deferred.resolve() promise.then null, (data) -> innerPromise = $http.post("#{url}", {key: hash, value:myFilters}) innerPromise.then -> deferred.resolve() innerPromise.then null, -> deferred.reject() return deferred.promise service.getMyFilters = (projectId) -> deferred = $q.defer() url = $urls.resolve("user-storage") ns = "#{projectId}:#{myFiltersHashSuffix}" hash = generateHash([projectId, ns]) promise = $http.get("#{url}/#{hash}") promise.then (data) -> deferred.resolve(data.data.value) promise.then null, (data) -> deferred.resolve({}) return deferred.promise return (instance) -> instance.issues = service module = angular.module("taigaResources") module.factory("$tgIssuesResourcesProvider", ["$tgRepo", "$tgHttp", "$tgUrls", "$tgStorage", "$q", resourceProvider])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/resources/issues.coffee ### taiga = @.taiga generateHash = taiga.generateHash resourceProvider = ($repo, $http, $urls, $storage, $q) -> service = {} hashSuffix = "issues-queryparams" filtersHashSuffix = "issues-filters" myFiltersHashSuffix = "issues-my-filters" service.get = (projectId, issueId) -> params = service.getQueryParams(projectId) params.project = projectId return $repo.queryOne("issues", issueId, params) service.list = (projectId, filters, options) -> params = {project: projectId} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryPaginated("issues", params, options) service.bulkCreate = (projectId, data) -> url = $urls.resolve("bulk-create-issues") params = {project_id: projectId, bulk_issues: data} return $http.post(url, params) service.stats = (projectId) -> return $repo.queryOneRaw("projects", "#{projectId}/issues_stats") service.filtersData = (projectId) -> return $repo.queryOneRaw("projects", "#{projectId}/issue_filters_data") service.listValues = (projectId, type) -> params = {"project": projectId} service.storeQueryParams(projectId, params) return $repo.queryMany(type, params) service.storeQueryParams = (projectId, params) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) $storage.set(hash, params) service.getQueryParams = (projectId) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) return $storage.get(hash) or {} service.storeFilters = (projectSlug, params) -> ns = "#{projectSlug}:#{filtersHashSuffix}" hash = generateHash([projectSlug, ns]) $storage.set(hash, params) service.getFilters = (projectSlug) -> ns = "#{projectSlug}:#{filtersHashSuffix}" hash = generateHash([projectSlug, ns]) return $storage.get(hash) or {} service.storeMyFilters = (projectId, myFilters) -> deferred = $q.defer() url = $urls.resolve("user-storage") ns = "#{projectId}:#{myFiltersHashSuffix}" hash = generateHash([projectId, ns]) if _.isEmpty(myFilters) promise = $http.delete("#{url}/#{hash}", {key: hash, value:myFilters}) promise.then -> deferred.resolve() promise.then null, -> deferred.reject() else promise = $http.put("#{url}/#{hash}", {key: hash, value:myFilters}) promise.then (data) -> deferred.resolve() promise.then null, (data) -> innerPromise = $http.post("#{url}", {key: hash, value:myFilters}) innerPromise.then -> deferred.resolve() innerPromise.then null, -> deferred.reject() return deferred.promise service.getMyFilters = (projectId) -> deferred = $q.defer() url = $urls.resolve("user-storage") ns = "#{projectId}:#{myFiltersHashSuffix}" hash = generateHash([projectId, ns]) promise = $http.get("#{url}/#{hash}") promise.then (data) -> deferred.resolve(data.data.value) promise.then null, (data) -> deferred.resolve({}) return deferred.promise return (instance) -> instance.issues = service module = angular.module("taigaResources") module.factory("$tgIssuesResourcesProvider", ["$tgRepo", "$tgHttp", "$tgUrls", "$tgStorage", "$q", resourceProvider])
[ { "context": "###\n Pokemon Go (c) MITM node proxy\n by Michael Strassburger <codepoet@cpan.org>\n###\n\nProxy = require 'http-mi", "end": 62, "score": 0.9998676180839539, "start": 42, "tag": "NAME", "value": "Michael Strassburger" }, { "context": "Go (c) MITM node proxy\n by Michael Strassburger <codepoet@cpan.org>\n###\n\nProxy = require 'http-mitm-proxy'\nPOGOProto", "end": 81, "score": 0.999932587146759, "start": 64, "tag": "EMAIL", "value": "codepoet@cpan.org" } ]
lib/pokemon-go-mitm.coffee
noobcakes4603/tinkering
393
### Pokemon Go (c) MITM node proxy by Michael Strassburger <codepoet@cpan.org> ### Proxy = require 'http-mitm-proxy' POGOProtos = require 'pokemongo-protobuf' changeCase = require 'change-case' http = require 'http' https = require 'https' fs = require 'fs' _ = require 'lodash' request = require 'request' rp = require 'request-promise' util = require 'util' Promise = require 'bluebird' DNS = require 'dns' zlib = require 'zlib' forge = require 'node-forge' getRawBody = require 'raw-body' class PokemonGoMITM ports: proxy: 8081 endpoint: 8082 endpoint: api: 'pgorelease.nianticlabs.com' oauth: 'android.clients.google.com' ptc: 'sso.pokemon.com' storage: 'storage.googleapis.com' endpointIPs: {} clientSignature: '321187995bc7cdc2b5fc91b11a96e2baa8602c62' responseEnvelope: 'POGOProtos.Networking.Envelopes.ResponseEnvelope' requestEnvelope: 'POGOProtos.Networking.Envelopes.RequestEnvelope' requestHandlers: {} responseHandlers: {} requestEnvelopeHandlers: [] responseEnvelopeHandlers: [] rawRequestHandlers: {} rawResponseHandlers: {} rawRequestEnvelopeHandlers: [] rawResponseEnvelopeHandlers: [] class Session id: null url: null expiration: 0 lastRequest: null requestInjectQueue: [] data: {} constructor: (id, url) -> @id = id @url = url setRequest: (req, url) -> @lastRequest = req @url = url if req.auth_ticket @expiration = parseInt req.auth_ticket.expire_timestamp_ms Buffer.concat([req.auth_ticket.start, req.auth_ticket.end]).toString() else if req.auth_info and req.auth_info.token req.auth_info.token.contents setResponse: (res) -> if res.auth_ticket @expiration = parseInt res.auth_ticket.expire_timestamp_ms Buffer.concat([res.auth_ticket.start, res.auth_ticket.end]).toString() sessions: {} proxy: null server: null constructor: (options) -> @ports.proxy = options.port or 8081 @ports.endpoint = options.endpoint or 8082 @debug = options.debug or false console.log "[+++] PokemonGo MITM [++++]" @resolveEndpoints() .then => @setupProxy() .then => @setupEndpoint() close: -> console.log "[+] Stopping MITM Proxy..." @proxy.close() @server.close() resolveEndpoints: -> Promise .mapSeries (host for name, host of @endpoint), (endpoint) => new Promise (resolve, reject) => @log "[+] Resolving #{endpoint}" DNS.resolve endpoint, "A", (err, addresses) => return reject err if err @endpointIPs[ip] = endpoint for ip in addresses resolve() .then => @log "[+] Resolving done", @endpointIPs setupProxy: -> @proxy = new Proxy() .use Proxy.gunzip .onConnect @handleProxyConnect .onRequest @handleProxyRequest .onError @handleProxyError .listen port: @ports.proxy, => console.log "[+] Proxy listening on #{@ports.proxy}" console.log "[!] -> PROXY USAGE: install http://<host>:#{@ports.endpoint}/ca.crt as a trusted certificate" @proxy.silent = true setupEndpoint: -> @server = http.createServer (req, res) => @handleEndpointRequest req, res @server.listen @ports.endpoint, => console.log "[+] Virtual endpoint listening on #{@ports.endpoint}" console.log "[!] -> ENDPOINT USAGE: configure 'custom endpoint' in pokemon-go-xposed" handleEndpointRequest: (req, res) -> @log "[+++] #{req.method} request for #{req.url}" switch req.url when '/ca.pem', '/ca.crt', '/ca.der' return @endpointCertHandler req, res getRawBody req .then (buffer) => @handleEndpointConnect req, res, buffer handleEndpointConnect: (req, res, buffer) -> @log "[+] Handling request to virtual endpoint" [buffer, session] = @handleRequest buffer, req.url delete req.headers.host delete req.headers["content-length"] req.headers.connection = "Close" rp url: "https://#{@endpoint.api}#{req.url}" method: req.method body: buffer encoding: null headers: req.headers resolveWithFullResponse: true .then (response) => @log "[+] Forwarding result from real endpoint" send = (buffer) -> response.headers["content-length"] = buffer.length if buffer res.writeHead response.statusCode, response.headers res.end buffer, "binary" unless response.headers["content-encoding"] is "gzip" send @handleResponse response.body, session else zlib.gunzip response.body, (err, decoded) => buffer = @handleResponse decoded, session zlib.gzip buffer, (err, encoded) => send encoded .catch (e) => console.log "[-] #{e}" endpointCertHandler: (req, res) -> path = @proxy.sslCaDir + '/certs' + req.url if toDer = /\.(crt|der)$/.test path path = path.replace /\.(crt|der)$/, '.pem' fs.readFile path, (err, data) -> code = 200 type = "application/x-pem-file" if err code = 404 type = "text/html" data = "<html>\n<title>404</title>\n<body>Not found</body>\n</html>" else if toDer type = "application/x-x509-ca-cert" data = forge.pem.decode(data)[0].body; res.writeHead code, {"Content-Type": type, "Content-Length": data.length} res.end data, 'binary' handleProxyConnect: (req, socket, head, callback) => return callback() unless req.url.match /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:443/ ip = req.url.split(/:/)[0] # Overwrite the request URL if the IP matches on of our intercepted hosts req.url = @endpointIPs[ip]+':443' if @endpointIPs[ip] callback() handleProxyRequest: (ctx, callback) => switch ctx.clientToProxyRequest.headers.host # Intercept all calls to the API when @endpoint.api then @proxyRequestHandler ctx # Intercept calls to the oAuth endpoint to patch the signature when @endpoint.oauth then @proxySignatureHandler ctx callback() proxyRequestHandler: (ctx) -> @log "[+++] Request to #{ctx.clientToProxyRequest.url}" ### Client Reuqest Handling ### requestChunks = [] session = null ctx.onRequestData (ctx, chunk, callback) => requestChunks.push chunk callback null, null ctx.onRequestEnd (ctx, callback) => [buffer, session] = @handleRequest Buffer.concat(requestChunks), ctx.clientToProxyRequest.url ctx.proxyToServerRequest.write buffer @log "[+] Waiting for response..." callback() ### Server Response Handling ### responseChunks = [] ctx.onResponseData (ctx, chunk, callback) => responseChunks.push chunk callback() ctx.onResponseEnd (ctx, callback) => buffer = @handleResponse Buffer.concat(responseChunks), session ctx.proxyToClientResponse.end buffer callback false handleRequest: (buffer, url) -> for handler in @rawRequestEnvelopeHandlers buffer = handler(buffer) or buffer return [buffer] unless data = @parseProtobuf buffer, @requestEnvelope originalData = _.cloneDeep data session = @getSession(data, url) for handler in @requestEnvelopeHandlers data = if handler.length > 1 handler(session.data, data) or data else handler(data) or data for request in data.requests rpcName = changeCase.pascalCase request.request_type proto = "POGOProtos.Networking.Requests.Messages.#{rpcName}Message" # Raw handlers run first handlers = [].concat @rawRequestHandlers[rpcName] or [], @rawRequestHandlers['*'] or [] for handler in handlers request = handler(request, rpcName) or request unless proto in POGOProtos.info() @log "[-] Request handler for #{rpcName} isn't implemented yet!" continue decoded = {} if request.request_message continue unless decoded = @parseProtobuf request.request_message, proto originalRequest = _.cloneDeep decoded afterHandlers = @handleRequestAction session, rpcName, decoded # disabled since signature validation # unless _.isEqual originalRequest, afterHandlers # @log "[!] Overwriting #{rpcName} request # request.request_message = POGOProtos.serialize afterHandlers, proto # disabled since signature validation # for request in @requestInjectQueue # unless data.requests.length < 5 # @log "[-] Delaying inject of #{request.action} because RequestEnvelope is full" # break # @log "[+] Injecting request to #{request.action}" # injected++ # requested.push "POGOProtos.Networking.Responses.#{request.action}Response" # data.requests.push # request_type: changeCase.constantCase request.action # request_message: POGOProtos.serialize request.data, "POGOProtos.Networking.Requests.Messages.#{request.action}Message" # @requestInjectQueue = @requestInjectQueue.slice injected # unless _.isEqual originalData, data # @log "[+] Recoding RequestEnvelope" # buffer = POGOProtos.serialize data, @requestEnvelope session.setRequest data, url [buffer, session] handleResponse: (buffer, session) -> for handler in @rawResponseEnvelopeHandlers buffer = handler(buffer) or buffer return buffer unless session and data = @parseProtobuf buffer, @responseEnvelope originalData = _.cloneDeep data for handler in @responseEnvelopeHandlers data = if handler.length > 1 handler(session.data, data) or data else handler(data) or data for id, response of data.returns when response.length > 0 unless id < session.lastRequest.requests.length @log "[-] Extra response #{id} with no matching request!" continue rpcName = changeCase.pascalCase session.lastRequest.requests[id].request_type proto = "POGOProtos.Networking.Responses.#{rpcName}Response" # Raw handlers run first handlers = [].concat @rawResponseHandlers[rpcName] or [], @rawResponseHandlers['*'] or [] for handler in handlers response = handler(response, rpcName) or response if proto in POGOProtos.info() continue unless decoded = @parseProtobuf response, proto originalResponse = _.cloneDeep decoded afterHandlers = @handleResponseAction session, rpcName, decoded unless _.isEqual afterHandlers, originalResponse @log "[!] Overwriting #{rpcName} response" data.returns[id] = POGOProtos.serialize afterHandlers, proto # disabled since signature validation # if injected and data.returns.length-injected-1 >= id # # Remove a previously injected request to not confuse the client # @log "[!] Removing #{rpcName} from response as it was previously injected" # delete data.returns[id] else @log "[-] Response handler for #{rpcName} isn't implemented yet!" # Update session expiration and auth_ticket from response if id = session.setResponse(data) @refreshSession(session, id) # Overwrite the response in case a hook hit the fan unless _.isEqual originalData, data buffer = POGOProtos.serialize data, @responseEnvelope buffer proxySignatureHandler: (ctx) -> requestChunks = [] ctx.onRequestData (ctx, chunk, callback) => requestChunks.push chunk callback null, null ctx.onRequestEnd (ctx, callback) => buffer = Buffer.concat requestChunks if /Email.*com.nianticlabs.pokemongo/.test buffer.toString() buffer = new Buffer buffer.toString().replace /&client_sig=[^&]*&/, "&client_sig=#{@clientSignature}&" ctx.proxyToServerRequest.write buffer callback() handleProxyError: (ctx, err, errorKind) => url = if ctx and ctx.clientToProxyRequest then ctx.clientToProxyRequest.url else '' @log "[-] #{errorKind} on #{url}:", err getSession: (req, url) -> # use auth_ticket (if logged in) or token as id for this session id = if req.auth_ticket Buffer.concat [req.auth_ticket.start, req.auth_ticket.end] .toString() else if req.auth_info and req.auth_info.token req.auth_info.token.contents unless id and session = @sessions[id] timestamp = Date.now() # check if this is a retried request with different auth token reqId = parseInt req.request_id for i, s of @sessions if s.lastRequest.request_id is reqId session = s # do some housekeeping on old sessions if s.expiration < timestamp delete @sessions[i] # create a new session if not found (id can be undefined) session = new Session id, url unless session # set last request if id = session.setRequest req, url @sessions[id] = session session refreshSession: (session, newId) -> delete @sessions[session.id] if session.id @sessions[newId] = session session.id = newId handleRequestAction: (session, action, data) -> @log "[+] Request for action #{action}:", data handlers = [].concat @requestHandlers[action] or [], @requestHandlers['*'] or [] for handler in handlers data = if handler.length > 2 handler(session.data, data, action) or data else handler(data, action) or data data handleResponseAction: (session, action, data) -> @log "[+] Response for action #{action}:", data handlers = [].concat @responseHandlers[action] or [], @responseHandlers['*'] or [] for handler in handlers data = if handler.length > 2 handler(session.data, data, action) or data else handler(data, action) or data data # disabled since signature validation # injectRequest: (action, data) -> # unless "POGOProtos.Networking.Requests.Messages.#{action}Message" in POGOProtos.info() # @log "[-] Can't inject request #{action} - proto not implemented" # return # @requestInjectQueue.push # action: action # data: data # craftRequest: (action, data, requestEnvelope=@lastRequest, url=undefined) -> # @log "[+] Crafting request for #{action}" # requestEnvelope.request_id ?= 1000000000000000000-Math.floor(Math.random()*1000000000000000000) # requestEnvelope.requests = [ # request_type: changeCase.constantCase action # request_message: POGOProtos.serialize data, "POGOProtos.Networking.Requests.Messages.#{changeCase.pascalCase action}Message" # ] # _.defaults requestEnvelope, @lastRequest # buffer = POGOProtos.serialize requestEnvelope, @requestEnvelope # url ?= 'https://' + @lastCtx.clientToProxyRequest.headers.host + '/' + @lastCtx.clientToProxyRequest.url # return rp( # url: url # method: 'POST' # body: buffer # encoding: null # headers: # 'Content-Type': 'application/x-www-form-urlencoded' # 'Content-Length': Buffer.byteLength buffer # 'Connection': 'Close' # 'User-Agent': @lastCtx?.clientToProxyRequest?.headers['user-agent'] # ).then((buffer) => # try # @log "[+] Response for crafted #{action}" # decoded = POGOProtos.parseWithUnknown buffer, @responseEnvelope # data = POGOProtos.parseWithUnknown decoded.returns[0], "POGOProtos.Networking.Responses.#{changeCase.pascalCase action}Response" # @log data # data # catch e # @log "[-] Parsing of response to crafted #{action} failed: #{e}" # throw e # ).catch (e) => # @log "[-] Crafting a request failed with #{e}" # throw e setRequestHandler: (action, cb) -> @addRequestHandler action, cb this setResponseHandler: (action, cb) -> @addResponseHandler action, cb this addRequestHandler: (action, cb) -> @requestHandlers[action] ?= [] @requestHandlers[action].push cb.bind this this addResponseHandler: (action, cb) -> @responseHandlers[action] ?= [] @responseHandlers[action].push cb.bind this this addRequestEnvelopeHandler: (cb, name=undefined) -> @requestEnvelopeHandlers.push cb.bind this this addResponseEnvelopeHandler: (cb, name=undefined) -> @responseEnvelopeHandlers.push cb.bind this this addRawRequestHandler: (action, cb) -> @rawRequestHandlers[action] ?= [] @rawRequestHandlers[action].push cb.bind this this addRawResponseHandler: (action, cb) -> @rawResponseHandlers[action] ?= [] @rawResponseHandlers[action].push cb.bind this this addRawRequestEnvelopeHandler: (cb, name=undefined) -> @rawRequestEnvelopeHandlers.push cb.bind this this addRawResponseEnvelopeHandler: (cb, name=undefined) -> @rawResponseEnvelopeHandlers.push cb.bind this this parseProtobuf: (buffer, schema) -> try return POGOProtos.parseWithUnknown buffer, schema catch e @log "[-] Parsing protobuf of #{schema} failed: #{e}" log: -> for arg, i in arguments when typeof arg is 'object' arguments[i] = util.inspect arg, { depth: null } console.log.apply null, arguments if @debug module.exports = PokemonGoMITM
158698
### Pokemon Go (c) MITM node proxy by <NAME> <<EMAIL>> ### Proxy = require 'http-mitm-proxy' POGOProtos = require 'pokemongo-protobuf' changeCase = require 'change-case' http = require 'http' https = require 'https' fs = require 'fs' _ = require 'lodash' request = require 'request' rp = require 'request-promise' util = require 'util' Promise = require 'bluebird' DNS = require 'dns' zlib = require 'zlib' forge = require 'node-forge' getRawBody = require 'raw-body' class PokemonGoMITM ports: proxy: 8081 endpoint: 8082 endpoint: api: 'pgorelease.nianticlabs.com' oauth: 'android.clients.google.com' ptc: 'sso.pokemon.com' storage: 'storage.googleapis.com' endpointIPs: {} clientSignature: '321187995bc7cdc2b5fc91b11a96e2baa8602c62' responseEnvelope: 'POGOProtos.Networking.Envelopes.ResponseEnvelope' requestEnvelope: 'POGOProtos.Networking.Envelopes.RequestEnvelope' requestHandlers: {} responseHandlers: {} requestEnvelopeHandlers: [] responseEnvelopeHandlers: [] rawRequestHandlers: {} rawResponseHandlers: {} rawRequestEnvelopeHandlers: [] rawResponseEnvelopeHandlers: [] class Session id: null url: null expiration: 0 lastRequest: null requestInjectQueue: [] data: {} constructor: (id, url) -> @id = id @url = url setRequest: (req, url) -> @lastRequest = req @url = url if req.auth_ticket @expiration = parseInt req.auth_ticket.expire_timestamp_ms Buffer.concat([req.auth_ticket.start, req.auth_ticket.end]).toString() else if req.auth_info and req.auth_info.token req.auth_info.token.contents setResponse: (res) -> if res.auth_ticket @expiration = parseInt res.auth_ticket.expire_timestamp_ms Buffer.concat([res.auth_ticket.start, res.auth_ticket.end]).toString() sessions: {} proxy: null server: null constructor: (options) -> @ports.proxy = options.port or 8081 @ports.endpoint = options.endpoint or 8082 @debug = options.debug or false console.log "[+++] PokemonGo MITM [++++]" @resolveEndpoints() .then => @setupProxy() .then => @setupEndpoint() close: -> console.log "[+] Stopping MITM Proxy..." @proxy.close() @server.close() resolveEndpoints: -> Promise .mapSeries (host for name, host of @endpoint), (endpoint) => new Promise (resolve, reject) => @log "[+] Resolving #{endpoint}" DNS.resolve endpoint, "A", (err, addresses) => return reject err if err @endpointIPs[ip] = endpoint for ip in addresses resolve() .then => @log "[+] Resolving done", @endpointIPs setupProxy: -> @proxy = new Proxy() .use Proxy.gunzip .onConnect @handleProxyConnect .onRequest @handleProxyRequest .onError @handleProxyError .listen port: @ports.proxy, => console.log "[+] Proxy listening on #{@ports.proxy}" console.log "[!] -> PROXY USAGE: install http://<host>:#{@ports.endpoint}/ca.crt as a trusted certificate" @proxy.silent = true setupEndpoint: -> @server = http.createServer (req, res) => @handleEndpointRequest req, res @server.listen @ports.endpoint, => console.log "[+] Virtual endpoint listening on #{@ports.endpoint}" console.log "[!] -> ENDPOINT USAGE: configure 'custom endpoint' in pokemon-go-xposed" handleEndpointRequest: (req, res) -> @log "[+++] #{req.method} request for #{req.url}" switch req.url when '/ca.pem', '/ca.crt', '/ca.der' return @endpointCertHandler req, res getRawBody req .then (buffer) => @handleEndpointConnect req, res, buffer handleEndpointConnect: (req, res, buffer) -> @log "[+] Handling request to virtual endpoint" [buffer, session] = @handleRequest buffer, req.url delete req.headers.host delete req.headers["content-length"] req.headers.connection = "Close" rp url: "https://#{@endpoint.api}#{req.url}" method: req.method body: buffer encoding: null headers: req.headers resolveWithFullResponse: true .then (response) => @log "[+] Forwarding result from real endpoint" send = (buffer) -> response.headers["content-length"] = buffer.length if buffer res.writeHead response.statusCode, response.headers res.end buffer, "binary" unless response.headers["content-encoding"] is "gzip" send @handleResponse response.body, session else zlib.gunzip response.body, (err, decoded) => buffer = @handleResponse decoded, session zlib.gzip buffer, (err, encoded) => send encoded .catch (e) => console.log "[-] #{e}" endpointCertHandler: (req, res) -> path = @proxy.sslCaDir + '/certs' + req.url if toDer = /\.(crt|der)$/.test path path = path.replace /\.(crt|der)$/, '.pem' fs.readFile path, (err, data) -> code = 200 type = "application/x-pem-file" if err code = 404 type = "text/html" data = "<html>\n<title>404</title>\n<body>Not found</body>\n</html>" else if toDer type = "application/x-x509-ca-cert" data = forge.pem.decode(data)[0].body; res.writeHead code, {"Content-Type": type, "Content-Length": data.length} res.end data, 'binary' handleProxyConnect: (req, socket, head, callback) => return callback() unless req.url.match /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:443/ ip = req.url.split(/:/)[0] # Overwrite the request URL if the IP matches on of our intercepted hosts req.url = @endpointIPs[ip]+':443' if @endpointIPs[ip] callback() handleProxyRequest: (ctx, callback) => switch ctx.clientToProxyRequest.headers.host # Intercept all calls to the API when @endpoint.api then @proxyRequestHandler ctx # Intercept calls to the oAuth endpoint to patch the signature when @endpoint.oauth then @proxySignatureHandler ctx callback() proxyRequestHandler: (ctx) -> @log "[+++] Request to #{ctx.clientToProxyRequest.url}" ### Client Reuqest Handling ### requestChunks = [] session = null ctx.onRequestData (ctx, chunk, callback) => requestChunks.push chunk callback null, null ctx.onRequestEnd (ctx, callback) => [buffer, session] = @handleRequest Buffer.concat(requestChunks), ctx.clientToProxyRequest.url ctx.proxyToServerRequest.write buffer @log "[+] Waiting for response..." callback() ### Server Response Handling ### responseChunks = [] ctx.onResponseData (ctx, chunk, callback) => responseChunks.push chunk callback() ctx.onResponseEnd (ctx, callback) => buffer = @handleResponse Buffer.concat(responseChunks), session ctx.proxyToClientResponse.end buffer callback false handleRequest: (buffer, url) -> for handler in @rawRequestEnvelopeHandlers buffer = handler(buffer) or buffer return [buffer] unless data = @parseProtobuf buffer, @requestEnvelope originalData = _.cloneDeep data session = @getSession(data, url) for handler in @requestEnvelopeHandlers data = if handler.length > 1 handler(session.data, data) or data else handler(data) or data for request in data.requests rpcName = changeCase.pascalCase request.request_type proto = "POGOProtos.Networking.Requests.Messages.#{rpcName}Message" # Raw handlers run first handlers = [].concat @rawRequestHandlers[rpcName] or [], @rawRequestHandlers['*'] or [] for handler in handlers request = handler(request, rpcName) or request unless proto in POGOProtos.info() @log "[-] Request handler for #{rpcName} isn't implemented yet!" continue decoded = {} if request.request_message continue unless decoded = @parseProtobuf request.request_message, proto originalRequest = _.cloneDeep decoded afterHandlers = @handleRequestAction session, rpcName, decoded # disabled since signature validation # unless _.isEqual originalRequest, afterHandlers # @log "[!] Overwriting #{rpcName} request # request.request_message = POGOProtos.serialize afterHandlers, proto # disabled since signature validation # for request in @requestInjectQueue # unless data.requests.length < 5 # @log "[-] Delaying inject of #{request.action} because RequestEnvelope is full" # break # @log "[+] Injecting request to #{request.action}" # injected++ # requested.push "POGOProtos.Networking.Responses.#{request.action}Response" # data.requests.push # request_type: changeCase.constantCase request.action # request_message: POGOProtos.serialize request.data, "POGOProtos.Networking.Requests.Messages.#{request.action}Message" # @requestInjectQueue = @requestInjectQueue.slice injected # unless _.isEqual originalData, data # @log "[+] Recoding RequestEnvelope" # buffer = POGOProtos.serialize data, @requestEnvelope session.setRequest data, url [buffer, session] handleResponse: (buffer, session) -> for handler in @rawResponseEnvelopeHandlers buffer = handler(buffer) or buffer return buffer unless session and data = @parseProtobuf buffer, @responseEnvelope originalData = _.cloneDeep data for handler in @responseEnvelopeHandlers data = if handler.length > 1 handler(session.data, data) or data else handler(data) or data for id, response of data.returns when response.length > 0 unless id < session.lastRequest.requests.length @log "[-] Extra response #{id} with no matching request!" continue rpcName = changeCase.pascalCase session.lastRequest.requests[id].request_type proto = "POGOProtos.Networking.Responses.#{rpcName}Response" # Raw handlers run first handlers = [].concat @rawResponseHandlers[rpcName] or [], @rawResponseHandlers['*'] or [] for handler in handlers response = handler(response, rpcName) or response if proto in POGOProtos.info() continue unless decoded = @parseProtobuf response, proto originalResponse = _.cloneDeep decoded afterHandlers = @handleResponseAction session, rpcName, decoded unless _.isEqual afterHandlers, originalResponse @log "[!] Overwriting #{rpcName} response" data.returns[id] = POGOProtos.serialize afterHandlers, proto # disabled since signature validation # if injected and data.returns.length-injected-1 >= id # # Remove a previously injected request to not confuse the client # @log "[!] Removing #{rpcName} from response as it was previously injected" # delete data.returns[id] else @log "[-] Response handler for #{rpcName} isn't implemented yet!" # Update session expiration and auth_ticket from response if id = session.setResponse(data) @refreshSession(session, id) # Overwrite the response in case a hook hit the fan unless _.isEqual originalData, data buffer = POGOProtos.serialize data, @responseEnvelope buffer proxySignatureHandler: (ctx) -> requestChunks = [] ctx.onRequestData (ctx, chunk, callback) => requestChunks.push chunk callback null, null ctx.onRequestEnd (ctx, callback) => buffer = Buffer.concat requestChunks if /Email.*com.nianticlabs.pokemongo/.test buffer.toString() buffer = new Buffer buffer.toString().replace /&client_sig=[^&]*&/, "&client_sig=#{@clientSignature}&" ctx.proxyToServerRequest.write buffer callback() handleProxyError: (ctx, err, errorKind) => url = if ctx and ctx.clientToProxyRequest then ctx.clientToProxyRequest.url else '' @log "[-] #{errorKind} on #{url}:", err getSession: (req, url) -> # use auth_ticket (if logged in) or token as id for this session id = if req.auth_ticket Buffer.concat [req.auth_ticket.start, req.auth_ticket.end] .toString() else if req.auth_info and req.auth_info.token req.auth_info.token.contents unless id and session = @sessions[id] timestamp = Date.now() # check if this is a retried request with different auth token reqId = parseInt req.request_id for i, s of @sessions if s.lastRequest.request_id is reqId session = s # do some housekeeping on old sessions if s.expiration < timestamp delete @sessions[i] # create a new session if not found (id can be undefined) session = new Session id, url unless session # set last request if id = session.setRequest req, url @sessions[id] = session session refreshSession: (session, newId) -> delete @sessions[session.id] if session.id @sessions[newId] = session session.id = newId handleRequestAction: (session, action, data) -> @log "[+] Request for action #{action}:", data handlers = [].concat @requestHandlers[action] or [], @requestHandlers['*'] or [] for handler in handlers data = if handler.length > 2 handler(session.data, data, action) or data else handler(data, action) or data data handleResponseAction: (session, action, data) -> @log "[+] Response for action #{action}:", data handlers = [].concat @responseHandlers[action] or [], @responseHandlers['*'] or [] for handler in handlers data = if handler.length > 2 handler(session.data, data, action) or data else handler(data, action) or data data # disabled since signature validation # injectRequest: (action, data) -> # unless "POGOProtos.Networking.Requests.Messages.#{action}Message" in POGOProtos.info() # @log "[-] Can't inject request #{action} - proto not implemented" # return # @requestInjectQueue.push # action: action # data: data # craftRequest: (action, data, requestEnvelope=@lastRequest, url=undefined) -> # @log "[+] Crafting request for #{action}" # requestEnvelope.request_id ?= 1000000000000000000-Math.floor(Math.random()*1000000000000000000) # requestEnvelope.requests = [ # request_type: changeCase.constantCase action # request_message: POGOProtos.serialize data, "POGOProtos.Networking.Requests.Messages.#{changeCase.pascalCase action}Message" # ] # _.defaults requestEnvelope, @lastRequest # buffer = POGOProtos.serialize requestEnvelope, @requestEnvelope # url ?= 'https://' + @lastCtx.clientToProxyRequest.headers.host + '/' + @lastCtx.clientToProxyRequest.url # return rp( # url: url # method: 'POST' # body: buffer # encoding: null # headers: # 'Content-Type': 'application/x-www-form-urlencoded' # 'Content-Length': Buffer.byteLength buffer # 'Connection': 'Close' # 'User-Agent': @lastCtx?.clientToProxyRequest?.headers['user-agent'] # ).then((buffer) => # try # @log "[+] Response for crafted #{action}" # decoded = POGOProtos.parseWithUnknown buffer, @responseEnvelope # data = POGOProtos.parseWithUnknown decoded.returns[0], "POGOProtos.Networking.Responses.#{changeCase.pascalCase action}Response" # @log data # data # catch e # @log "[-] Parsing of response to crafted #{action} failed: #{e}" # throw e # ).catch (e) => # @log "[-] Crafting a request failed with #{e}" # throw e setRequestHandler: (action, cb) -> @addRequestHandler action, cb this setResponseHandler: (action, cb) -> @addResponseHandler action, cb this addRequestHandler: (action, cb) -> @requestHandlers[action] ?= [] @requestHandlers[action].push cb.bind this this addResponseHandler: (action, cb) -> @responseHandlers[action] ?= [] @responseHandlers[action].push cb.bind this this addRequestEnvelopeHandler: (cb, name=undefined) -> @requestEnvelopeHandlers.push cb.bind this this addResponseEnvelopeHandler: (cb, name=undefined) -> @responseEnvelopeHandlers.push cb.bind this this addRawRequestHandler: (action, cb) -> @rawRequestHandlers[action] ?= [] @rawRequestHandlers[action].push cb.bind this this addRawResponseHandler: (action, cb) -> @rawResponseHandlers[action] ?= [] @rawResponseHandlers[action].push cb.bind this this addRawRequestEnvelopeHandler: (cb, name=undefined) -> @rawRequestEnvelopeHandlers.push cb.bind this this addRawResponseEnvelopeHandler: (cb, name=undefined) -> @rawResponseEnvelopeHandlers.push cb.bind this this parseProtobuf: (buffer, schema) -> try return POGOProtos.parseWithUnknown buffer, schema catch e @log "[-] Parsing protobuf of #{schema} failed: #{e}" log: -> for arg, i in arguments when typeof arg is 'object' arguments[i] = util.inspect arg, { depth: null } console.log.apply null, arguments if @debug module.exports = PokemonGoMITM
true
### Pokemon Go (c) MITM node proxy by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### Proxy = require 'http-mitm-proxy' POGOProtos = require 'pokemongo-protobuf' changeCase = require 'change-case' http = require 'http' https = require 'https' fs = require 'fs' _ = require 'lodash' request = require 'request' rp = require 'request-promise' util = require 'util' Promise = require 'bluebird' DNS = require 'dns' zlib = require 'zlib' forge = require 'node-forge' getRawBody = require 'raw-body' class PokemonGoMITM ports: proxy: 8081 endpoint: 8082 endpoint: api: 'pgorelease.nianticlabs.com' oauth: 'android.clients.google.com' ptc: 'sso.pokemon.com' storage: 'storage.googleapis.com' endpointIPs: {} clientSignature: '321187995bc7cdc2b5fc91b11a96e2baa8602c62' responseEnvelope: 'POGOProtos.Networking.Envelopes.ResponseEnvelope' requestEnvelope: 'POGOProtos.Networking.Envelopes.RequestEnvelope' requestHandlers: {} responseHandlers: {} requestEnvelopeHandlers: [] responseEnvelopeHandlers: [] rawRequestHandlers: {} rawResponseHandlers: {} rawRequestEnvelopeHandlers: [] rawResponseEnvelopeHandlers: [] class Session id: null url: null expiration: 0 lastRequest: null requestInjectQueue: [] data: {} constructor: (id, url) -> @id = id @url = url setRequest: (req, url) -> @lastRequest = req @url = url if req.auth_ticket @expiration = parseInt req.auth_ticket.expire_timestamp_ms Buffer.concat([req.auth_ticket.start, req.auth_ticket.end]).toString() else if req.auth_info and req.auth_info.token req.auth_info.token.contents setResponse: (res) -> if res.auth_ticket @expiration = parseInt res.auth_ticket.expire_timestamp_ms Buffer.concat([res.auth_ticket.start, res.auth_ticket.end]).toString() sessions: {} proxy: null server: null constructor: (options) -> @ports.proxy = options.port or 8081 @ports.endpoint = options.endpoint or 8082 @debug = options.debug or false console.log "[+++] PokemonGo MITM [++++]" @resolveEndpoints() .then => @setupProxy() .then => @setupEndpoint() close: -> console.log "[+] Stopping MITM Proxy..." @proxy.close() @server.close() resolveEndpoints: -> Promise .mapSeries (host for name, host of @endpoint), (endpoint) => new Promise (resolve, reject) => @log "[+] Resolving #{endpoint}" DNS.resolve endpoint, "A", (err, addresses) => return reject err if err @endpointIPs[ip] = endpoint for ip in addresses resolve() .then => @log "[+] Resolving done", @endpointIPs setupProxy: -> @proxy = new Proxy() .use Proxy.gunzip .onConnect @handleProxyConnect .onRequest @handleProxyRequest .onError @handleProxyError .listen port: @ports.proxy, => console.log "[+] Proxy listening on #{@ports.proxy}" console.log "[!] -> PROXY USAGE: install http://<host>:#{@ports.endpoint}/ca.crt as a trusted certificate" @proxy.silent = true setupEndpoint: -> @server = http.createServer (req, res) => @handleEndpointRequest req, res @server.listen @ports.endpoint, => console.log "[+] Virtual endpoint listening on #{@ports.endpoint}" console.log "[!] -> ENDPOINT USAGE: configure 'custom endpoint' in pokemon-go-xposed" handleEndpointRequest: (req, res) -> @log "[+++] #{req.method} request for #{req.url}" switch req.url when '/ca.pem', '/ca.crt', '/ca.der' return @endpointCertHandler req, res getRawBody req .then (buffer) => @handleEndpointConnect req, res, buffer handleEndpointConnect: (req, res, buffer) -> @log "[+] Handling request to virtual endpoint" [buffer, session] = @handleRequest buffer, req.url delete req.headers.host delete req.headers["content-length"] req.headers.connection = "Close" rp url: "https://#{@endpoint.api}#{req.url}" method: req.method body: buffer encoding: null headers: req.headers resolveWithFullResponse: true .then (response) => @log "[+] Forwarding result from real endpoint" send = (buffer) -> response.headers["content-length"] = buffer.length if buffer res.writeHead response.statusCode, response.headers res.end buffer, "binary" unless response.headers["content-encoding"] is "gzip" send @handleResponse response.body, session else zlib.gunzip response.body, (err, decoded) => buffer = @handleResponse decoded, session zlib.gzip buffer, (err, encoded) => send encoded .catch (e) => console.log "[-] #{e}" endpointCertHandler: (req, res) -> path = @proxy.sslCaDir + '/certs' + req.url if toDer = /\.(crt|der)$/.test path path = path.replace /\.(crt|der)$/, '.pem' fs.readFile path, (err, data) -> code = 200 type = "application/x-pem-file" if err code = 404 type = "text/html" data = "<html>\n<title>404</title>\n<body>Not found</body>\n</html>" else if toDer type = "application/x-x509-ca-cert" data = forge.pem.decode(data)[0].body; res.writeHead code, {"Content-Type": type, "Content-Length": data.length} res.end data, 'binary' handleProxyConnect: (req, socket, head, callback) => return callback() unless req.url.match /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:443/ ip = req.url.split(/:/)[0] # Overwrite the request URL if the IP matches on of our intercepted hosts req.url = @endpointIPs[ip]+':443' if @endpointIPs[ip] callback() handleProxyRequest: (ctx, callback) => switch ctx.clientToProxyRequest.headers.host # Intercept all calls to the API when @endpoint.api then @proxyRequestHandler ctx # Intercept calls to the oAuth endpoint to patch the signature when @endpoint.oauth then @proxySignatureHandler ctx callback() proxyRequestHandler: (ctx) -> @log "[+++] Request to #{ctx.clientToProxyRequest.url}" ### Client Reuqest Handling ### requestChunks = [] session = null ctx.onRequestData (ctx, chunk, callback) => requestChunks.push chunk callback null, null ctx.onRequestEnd (ctx, callback) => [buffer, session] = @handleRequest Buffer.concat(requestChunks), ctx.clientToProxyRequest.url ctx.proxyToServerRequest.write buffer @log "[+] Waiting for response..." callback() ### Server Response Handling ### responseChunks = [] ctx.onResponseData (ctx, chunk, callback) => responseChunks.push chunk callback() ctx.onResponseEnd (ctx, callback) => buffer = @handleResponse Buffer.concat(responseChunks), session ctx.proxyToClientResponse.end buffer callback false handleRequest: (buffer, url) -> for handler in @rawRequestEnvelopeHandlers buffer = handler(buffer) or buffer return [buffer] unless data = @parseProtobuf buffer, @requestEnvelope originalData = _.cloneDeep data session = @getSession(data, url) for handler in @requestEnvelopeHandlers data = if handler.length > 1 handler(session.data, data) or data else handler(data) or data for request in data.requests rpcName = changeCase.pascalCase request.request_type proto = "POGOProtos.Networking.Requests.Messages.#{rpcName}Message" # Raw handlers run first handlers = [].concat @rawRequestHandlers[rpcName] or [], @rawRequestHandlers['*'] or [] for handler in handlers request = handler(request, rpcName) or request unless proto in POGOProtos.info() @log "[-] Request handler for #{rpcName} isn't implemented yet!" continue decoded = {} if request.request_message continue unless decoded = @parseProtobuf request.request_message, proto originalRequest = _.cloneDeep decoded afterHandlers = @handleRequestAction session, rpcName, decoded # disabled since signature validation # unless _.isEqual originalRequest, afterHandlers # @log "[!] Overwriting #{rpcName} request # request.request_message = POGOProtos.serialize afterHandlers, proto # disabled since signature validation # for request in @requestInjectQueue # unless data.requests.length < 5 # @log "[-] Delaying inject of #{request.action} because RequestEnvelope is full" # break # @log "[+] Injecting request to #{request.action}" # injected++ # requested.push "POGOProtos.Networking.Responses.#{request.action}Response" # data.requests.push # request_type: changeCase.constantCase request.action # request_message: POGOProtos.serialize request.data, "POGOProtos.Networking.Requests.Messages.#{request.action}Message" # @requestInjectQueue = @requestInjectQueue.slice injected # unless _.isEqual originalData, data # @log "[+] Recoding RequestEnvelope" # buffer = POGOProtos.serialize data, @requestEnvelope session.setRequest data, url [buffer, session] handleResponse: (buffer, session) -> for handler in @rawResponseEnvelopeHandlers buffer = handler(buffer) or buffer return buffer unless session and data = @parseProtobuf buffer, @responseEnvelope originalData = _.cloneDeep data for handler in @responseEnvelopeHandlers data = if handler.length > 1 handler(session.data, data) or data else handler(data) or data for id, response of data.returns when response.length > 0 unless id < session.lastRequest.requests.length @log "[-] Extra response #{id} with no matching request!" continue rpcName = changeCase.pascalCase session.lastRequest.requests[id].request_type proto = "POGOProtos.Networking.Responses.#{rpcName}Response" # Raw handlers run first handlers = [].concat @rawResponseHandlers[rpcName] or [], @rawResponseHandlers['*'] or [] for handler in handlers response = handler(response, rpcName) or response if proto in POGOProtos.info() continue unless decoded = @parseProtobuf response, proto originalResponse = _.cloneDeep decoded afterHandlers = @handleResponseAction session, rpcName, decoded unless _.isEqual afterHandlers, originalResponse @log "[!] Overwriting #{rpcName} response" data.returns[id] = POGOProtos.serialize afterHandlers, proto # disabled since signature validation # if injected and data.returns.length-injected-1 >= id # # Remove a previously injected request to not confuse the client # @log "[!] Removing #{rpcName} from response as it was previously injected" # delete data.returns[id] else @log "[-] Response handler for #{rpcName} isn't implemented yet!" # Update session expiration and auth_ticket from response if id = session.setResponse(data) @refreshSession(session, id) # Overwrite the response in case a hook hit the fan unless _.isEqual originalData, data buffer = POGOProtos.serialize data, @responseEnvelope buffer proxySignatureHandler: (ctx) -> requestChunks = [] ctx.onRequestData (ctx, chunk, callback) => requestChunks.push chunk callback null, null ctx.onRequestEnd (ctx, callback) => buffer = Buffer.concat requestChunks if /Email.*com.nianticlabs.pokemongo/.test buffer.toString() buffer = new Buffer buffer.toString().replace /&client_sig=[^&]*&/, "&client_sig=#{@clientSignature}&" ctx.proxyToServerRequest.write buffer callback() handleProxyError: (ctx, err, errorKind) => url = if ctx and ctx.clientToProxyRequest then ctx.clientToProxyRequest.url else '' @log "[-] #{errorKind} on #{url}:", err getSession: (req, url) -> # use auth_ticket (if logged in) or token as id for this session id = if req.auth_ticket Buffer.concat [req.auth_ticket.start, req.auth_ticket.end] .toString() else if req.auth_info and req.auth_info.token req.auth_info.token.contents unless id and session = @sessions[id] timestamp = Date.now() # check if this is a retried request with different auth token reqId = parseInt req.request_id for i, s of @sessions if s.lastRequest.request_id is reqId session = s # do some housekeeping on old sessions if s.expiration < timestamp delete @sessions[i] # create a new session if not found (id can be undefined) session = new Session id, url unless session # set last request if id = session.setRequest req, url @sessions[id] = session session refreshSession: (session, newId) -> delete @sessions[session.id] if session.id @sessions[newId] = session session.id = newId handleRequestAction: (session, action, data) -> @log "[+] Request for action #{action}:", data handlers = [].concat @requestHandlers[action] or [], @requestHandlers['*'] or [] for handler in handlers data = if handler.length > 2 handler(session.data, data, action) or data else handler(data, action) or data data handleResponseAction: (session, action, data) -> @log "[+] Response for action #{action}:", data handlers = [].concat @responseHandlers[action] or [], @responseHandlers['*'] or [] for handler in handlers data = if handler.length > 2 handler(session.data, data, action) or data else handler(data, action) or data data # disabled since signature validation # injectRequest: (action, data) -> # unless "POGOProtos.Networking.Requests.Messages.#{action}Message" in POGOProtos.info() # @log "[-] Can't inject request #{action} - proto not implemented" # return # @requestInjectQueue.push # action: action # data: data # craftRequest: (action, data, requestEnvelope=@lastRequest, url=undefined) -> # @log "[+] Crafting request for #{action}" # requestEnvelope.request_id ?= 1000000000000000000-Math.floor(Math.random()*1000000000000000000) # requestEnvelope.requests = [ # request_type: changeCase.constantCase action # request_message: POGOProtos.serialize data, "POGOProtos.Networking.Requests.Messages.#{changeCase.pascalCase action}Message" # ] # _.defaults requestEnvelope, @lastRequest # buffer = POGOProtos.serialize requestEnvelope, @requestEnvelope # url ?= 'https://' + @lastCtx.clientToProxyRequest.headers.host + '/' + @lastCtx.clientToProxyRequest.url # return rp( # url: url # method: 'POST' # body: buffer # encoding: null # headers: # 'Content-Type': 'application/x-www-form-urlencoded' # 'Content-Length': Buffer.byteLength buffer # 'Connection': 'Close' # 'User-Agent': @lastCtx?.clientToProxyRequest?.headers['user-agent'] # ).then((buffer) => # try # @log "[+] Response for crafted #{action}" # decoded = POGOProtos.parseWithUnknown buffer, @responseEnvelope # data = POGOProtos.parseWithUnknown decoded.returns[0], "POGOProtos.Networking.Responses.#{changeCase.pascalCase action}Response" # @log data # data # catch e # @log "[-] Parsing of response to crafted #{action} failed: #{e}" # throw e # ).catch (e) => # @log "[-] Crafting a request failed with #{e}" # throw e setRequestHandler: (action, cb) -> @addRequestHandler action, cb this setResponseHandler: (action, cb) -> @addResponseHandler action, cb this addRequestHandler: (action, cb) -> @requestHandlers[action] ?= [] @requestHandlers[action].push cb.bind this this addResponseHandler: (action, cb) -> @responseHandlers[action] ?= [] @responseHandlers[action].push cb.bind this this addRequestEnvelopeHandler: (cb, name=undefined) -> @requestEnvelopeHandlers.push cb.bind this this addResponseEnvelopeHandler: (cb, name=undefined) -> @responseEnvelopeHandlers.push cb.bind this this addRawRequestHandler: (action, cb) -> @rawRequestHandlers[action] ?= [] @rawRequestHandlers[action].push cb.bind this this addRawResponseHandler: (action, cb) -> @rawResponseHandlers[action] ?= [] @rawResponseHandlers[action].push cb.bind this this addRawRequestEnvelopeHandler: (cb, name=undefined) -> @rawRequestEnvelopeHandlers.push cb.bind this this addRawResponseEnvelopeHandler: (cb, name=undefined) -> @rawResponseEnvelopeHandlers.push cb.bind this this parseProtobuf: (buffer, schema) -> try return POGOProtos.parseWithUnknown buffer, schema catch e @log "[-] Parsing protobuf of #{schema} failed: #{e}" log: -> for arg, i in arguments when typeof arg is 'object' arguments[i] = util.inspect arg, { depth: null } console.log.apply null, arguments if @debug module.exports = PokemonGoMITM
[ { "context": "lackListToken', ->\n beforeEach ->\n @redisKey = uuid.v1()\n @sut = new BlackListToken cache: redis.create", "end": 202, "score": 0.9846768379211426, "start": 193, "tag": "KEY", "value": "uuid.v1()" }, { "context": " uuid: 'electric-eels'\n token: 'these-current-events-are-shocking!'\n\n @sut.do request, (error, @response) => d", "end": 622, "score": 0.9991821646690369, "start": 589, "tag": "PASSWORD", "value": "these-current-events-are-shocking" }, { "context": "uuid: 'trapped-in-blizzard'\n token: \"There's snow going back now\"\n\n @sut.do request, (error, @response) => ", "end": 1388, "score": 0.997100293636322, "start": 1361, "tag": "PASSWORD", "value": "There's snow going back now" } ]
test/black-list-token-spec.coffee
octoblu/meshblu-token-black-list
0
BlackListToken = require '../src/black-list-token' crypto = require 'crypto' redis = require 'fakeredis' uuid = require 'uuid' describe 'BlackListToken', -> beforeEach -> @redisKey = uuid.v1() @sut = new BlackListToken cache: redis.createClient(@redisKey), pepper: 'totally-a-secret' @cache = redis.createClient @redisKey describe '->do', -> context 'when given a uuid and token', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' token: 'these-current-events-are-shocking!' @sut.do request, (error, @response) => done error it 'should add a token to the cache', (done) -> @cache.exists "electric-eels:these-current-events-are-shocking!", (error, result) => expect(result).to.deep.equal 1 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a different uuid and token', -> beforeEach (done) -> request = metadata: responseId: 'brrrr' auth: uuid: 'trapped-in-blizzard' token: "There's snow going back now" @sut.do request, (error, @response) => done error it 'should add a hashed token to the cache', (done) -> @cache.exists "trapped-in-blizzard:There's snow going back now", (error, result) => expect(result).to.deep.equal 1 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'brrrr' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse
43316
BlackListToken = require '../src/black-list-token' crypto = require 'crypto' redis = require 'fakeredis' uuid = require 'uuid' describe 'BlackListToken', -> beforeEach -> @redisKey = <KEY> @sut = new BlackListToken cache: redis.createClient(@redisKey), pepper: 'totally-a-secret' @cache = redis.createClient @redisKey describe '->do', -> context 'when given a uuid and token', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' token: '<PASSWORD>!' @sut.do request, (error, @response) => done error it 'should add a token to the cache', (done) -> @cache.exists "electric-eels:these-current-events-are-shocking!", (error, result) => expect(result).to.deep.equal 1 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a different uuid and token', -> beforeEach (done) -> request = metadata: responseId: 'brrrr' auth: uuid: 'trapped-in-blizzard' token: "<PASSWORD>" @sut.do request, (error, @response) => done error it 'should add a hashed token to the cache', (done) -> @cache.exists "trapped-in-blizzard:There's snow going back now", (error, result) => expect(result).to.deep.equal 1 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'brrrr' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse
true
BlackListToken = require '../src/black-list-token' crypto = require 'crypto' redis = require 'fakeredis' uuid = require 'uuid' describe 'BlackListToken', -> beforeEach -> @redisKey = PI:KEY:<KEY>END_PI @sut = new BlackListToken cache: redis.createClient(@redisKey), pepper: 'totally-a-secret' @cache = redis.createClient @redisKey describe '->do', -> context 'when given a uuid and token', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' token: 'PI:PASSWORD:<PASSWORD>END_PI!' @sut.do request, (error, @response) => done error it 'should add a token to the cache', (done) -> @cache.exists "electric-eels:these-current-events-are-shocking!", (error, result) => expect(result).to.deep.equal 1 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a different uuid and token', -> beforeEach (done) -> request = metadata: responseId: 'brrrr' auth: uuid: 'trapped-in-blizzard' token: "PI:PASSWORD:<PASSWORD>END_PI" @sut.do request, (error, @response) => done error it 'should add a hashed token to the cache', (done) -> @cache.exists "trapped-in-blizzard:There's snow going back now", (error, result) => expect(result).to.deep.equal 1 done() it 'should return a 204', -> expectedResponse = metadata: responseId: 'brrrr' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse
[ { "context": ".insert { 'import': @importRecord._id, 'importer': @name, 'type': 'users', 'users': tempUsers }\n\t\t@users =", "end": 2016, "score": 0.9393250942230225, "start": 2011, "tag": "USERNAME", "value": "@name" }, { "context": ".insert { 'import': @importRecord._id, 'importer': @name, 'type': 'channels', 'channels': tempChannels }\n\t", "end": 2299, "score": 0.942838728427887, "start": 2294, "tag": "USERNAME", "value": "@name" }, { "context": ".insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': \"#{channel}/#{date}.", "end": 3096, "score": 0.8655961751937866, "start": 3091, "tag": "USERNAME", "value": "@name" }, { "context": ".insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': \"#{channel}/#{date}\"", "end": 3347, "score": 0.813636064529419, "start": 3342, "tag": "USERNAME", "value": "@name" }, { "context": "g: \"<@#{user.id}|#{user.name}>\"\n\t\t\t\t\t\t\t\trocket: \"@#{existantUser.username}\"\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif user.profile.email\n\t\t\t\t\t\t\t", "end": 5554, "score": 0.886372983455658, "start": 5531, "tag": "USERNAME", "value": "#{existantUser.username" }, { "context": ".createUser { email: user.profile.email, password: Date.now() + user.name + user.profile.email.toUpperCas", "end": 5677, "score": 0.9853776097297668, "start": 5673, "tag": "PASSWORD", "value": "Date" }, { "context": "eUser { email: user.profile.email, password: Date.now() + user.name + user.profile.email.toUpperCase() }\n", "end": 5681, "score": 0.9526983499526978, "start": 5678, "tag": "PASSWORD", "value": "now" }, { "context": " email: user.profile.email, password: Date.now() + user.name + user.profile.email.toUpperCase() }\n\t\t\t\t\t\t\telse\n", "end": 5695, "score": 0.7086592316627502, "start": 5686, "tag": "PASSWORD", "value": "user.name" }, { "context": "word: Date.now() + user.name + user.profile.email.toUpperCase() }\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tuserId = Accounts.createU", "end": 5728, "score": 0.49910134077072144, "start": 5717, "tag": "PASSWORD", "value": "toUpperCase" }, { "context": "e\n\t\t\t\t\t\t\t\tuserId = Accounts.createUser { username: user.name, password: Date.now() + user.name }\n\t\t\t\t\t\t\tMeteor", "end": 5803, "score": 0.9952796101570129, "start": 5794, "tag": "USERNAME", "value": "user.name" }, { "context": "counts.createUser { username: user.name, password: Date.now() + user.name }\n\t\t\t\t\t\t\tMeteor.runAsUser userId, () =>", "end": 5823, "score": 0.8893915414810181, "start": 5815, "tag": "PASSWORD", "value": "Date.now" }, { "context": "User { username: user.name, password: Date.now() + user.name }\n\t\t\t\t\t\t\tMeteor.runAsUser userId, () =>\n\t\t\t\t\t\t\t\tM", "end": 5837, "score": 0.753091037273407, "start": 5828, "tag": "PASSWORD", "value": "user.name" }, { "context": "r userId, () =>\n\t\t\t\t\t\t\t\tMeteor.call 'setUsername', user.name\n\t\t\t\t\t\t\t\tMeteor.call 'joinDefaultChannels', tr", "end": 5917, "score": 0.634171724319458, "start": 5913, "tag": "USERNAME", "value": "user" }, { "context": " \"<@#{user.id}|#{user.name}>\"\n\t\t\t\t\t\t\t\trocket: \"@#{user.name}\"\n\t\t\t\t\t\t@addCountCompleted 1\n\t\t\t@collection.updat", "end": 7036, "score": 0.7977684140205383, "start": 7027, "tag": "USERNAME", "value": "user.name" }, { "context": " member\n\t\t\t\t\t\t\t\tif user?\n\t\t\t\t\t\t\t\t\tusers.push user.username\n\n\t\t\t\t\t\t\tuserId = startedByUserId\n\t\t\t\t\t\t\tfor user ", "end": 7969, "score": 0.9029222130775452, "start": 7961, "tag": "USERNAME", "value": "username" }, { "context": "\t\t\tbotUser = RocketChat.models.Users.findOneById 'rocket.cat', { fields: { username: 1 }}\n\t\t\t\t\t\t\t\t\t\t\t\tbotUsern", "end": 10548, "score": 0.6617298722267151, "start": 10538, "tag": "USERNAME", "value": "rocket.cat" }, { "context": "nts: message.attachments\n\t\t\t\t\t\t\t\t\t\t\t\t\tusername: if botUsername then botUsername else undefined\n\n\t\t\t\t\t\t\t\t\t\t\t\t_.ex", "end": 10903, "score": 0.9923652410507202, "start": 10892, "tag": "USERNAME", "value": "botUsername" }, { "context": "chments\n\t\t\t\t\t\t\t\t\t\t\t\t\tusername: if botUsername then botUsername else undefined\n\n\t\t\t\t\t\t\t\t\t\t\t\t_.extend msgObj, msgD", "end": 10920, "score": 0.9964866638183594, "start": 10909, "tag": "USERNAME", "value": "botUsername" }, { "context": "\t\t\t\tusername: if botUsername then botUsername else undefined\n\n\t\t\t\t\t\t\t\t\t\t\t\t_.extend msgObj, msgDataDefaults\n\n\t\t", "end": 10935, "score": 0.7371937036514282, "start": 10926, "tag": "USERNAME", "value": "undefined" }, { "context": "e] = message\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tuser = @getRocketUser(message.user)\n\t\t\t\t\t\t\t\t\t\t\tif user?\n\t\t\t\t\t\t\t\t\t\t\t\tmsg", "end": 13860, "score": 0.5339858531951904, "start": 13850, "tag": "USERNAME", "value": "RocketUser" }, { "context": "\t\t\t\t\t\t\t\t\t\t\t\t\t_id: user._id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tusername: user.username\n\n\t\t\t\t\t\t\t\t\t\t\t\t_.extend msgObj, msgDataDefaults\n\n\t\t", "end": 14088, "score": 0.9992154240608215, "start": 14075, "tag": "USERNAME", "value": "user.username" }, { "context": "d: editedBy._id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tusername: editedBy.username\n\n\t\t\t\t\t\t\t\t\t\t\t\tRocketChat.sendMessage @getRocketUse", "end": 14450, "score": 0.70989990234375, "start": 14442, "tag": "USERNAME", "value": "username" } ]
packages/rocketchat-importer-slack/server.coffee
claysaad/Rocket.Chat
0
Importer.Slack = class Importer.Slack extends Importer.Base constructor: (name, descriptionI18N, fileTypeRegex) -> super(name, descriptionI18N, fileTypeRegex) @userTags = [] @bots = {} @logger.debug('Constructed a new Slack Importer.') prepare: (dataURI, sentContentType, fileName) => super(dataURI, sentContentType, fileName) {image, contentType} = RocketChatFile.dataURIParse dataURI zip = new @AdmZip(new Buffer(image, 'base64')) zipEntries = zip.getEntries() tempChannels = [] tempUsers = [] tempMessages = {} for entry in zipEntries do (entry) => if entry.entryName.indexOf('__MACOSX') > -1 #ignore all of the files inside of __MACOSX @logger.debug("Ignoring the file: #{entry.entryName}") else if entry.entryName == 'channels.json' @updateProgress Importer.ProgressStep.PREPARING_CHANNELS tempChannels = JSON.parse entry.getData().toString() tempChannels = tempChannels.filter (channel) -> channel.creator? else if entry.entryName == 'users.json' @updateProgress Importer.ProgressStep.PREPARING_USERS tempUsers = JSON.parse entry.getData().toString() for user in tempUsers when user.is_bot @bots[user.profile.bot_id] = user else if not entry.isDirectory and entry.entryName.indexOf('/') > -1 item = entry.entryName.split('/') #random/2015-10-04.json channelName = item[0] #random msgGroupData = item[1].split('.')[0] #2015-10-04 if not tempMessages[channelName] tempMessages[channelName] = {} # Catch files which aren't valid JSON files, ignore them try tempMessages[channelName][msgGroupData] = JSON.parse entry.getData().toString() catch @logger.warn "#{entry.entryName} is not a valid JSON file! Unable to import it." # Insert the users record, eventually this might have to be split into several ones as well # if someone tries to import a several thousands users instance usersId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'users', 'users': tempUsers } @users = @collection.findOne usersId @updateRecord { 'count.users': tempUsers.length } @addCountToTotal tempUsers.length # Insert the channels records. channelsId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'channels', 'channels': tempChannels } @channels = @collection.findOne channelsId @updateRecord { 'count.channels': tempChannels.length } @addCountToTotal tempChannels.length # Insert the messages records @updateProgress Importer.ProgressStep.PREPARING_MESSAGES messagesCount = 0 for channel, messagesObj of tempMessages do (channel, messagesObj) => if not @messages[channel] @messages[channel] = {} for date, msgs of messagesObj messagesCount += msgs.length @updateRecord { 'messagesstatus': "#{channel}/#{date}" } if Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize for splitMsg, i in Importer.Base.getBSONSafeArraysFromAnArray(msgs) messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}.#{i}", 'messages': splitMsg } @messages[channel]["#{date}.#{i}"] = @collection.findOne messagesId else messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}", 'messages': msgs } @messages[channel][date] = @collection.findOne messagesId @updateRecord { 'count.messages': messagesCount, 'messagesstatus': null } @addCountToTotal messagesCount if tempUsers.length is 0 or tempChannels.length is 0 or messagesCount is 0 @logger.warn "The loaded users count #{tempUsers.length}, the loaded channels #{tempChannels.length}, and the loaded messages #{messagesCount}" @updateProgress Importer.ProgressStep.ERROR return @getProgress() selectionUsers = tempUsers.map (user) -> return new Importer.SelectionUser user.id, user.name, user.profile.email, user.deleted, user.is_bot, !user.is_bot selectionChannels = tempChannels.map (channel) -> return new Importer.SelectionChannel channel.id, channel.name, channel.is_archived, true, false @updateProgress Importer.ProgressStep.USER_SELECTION return new Importer.Selection @name, selectionUsers, selectionChannels startImport: (importSelection) => super(importSelection) start = Date.now() for user in importSelection.users for u in @users.users when u.id is user.user_id u.do_import = user.do_import @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} for channel in importSelection.channels for c in @channels.channels when c.id is channel.channel_id c.do_import = channel.do_import @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} startedByUserId = Meteor.userId() Meteor.defer => @updateProgress Importer.ProgressStep.IMPORTING_USERS for user in @users.users when user.do_import do (user) => Meteor.runAsUser startedByUserId, () => existantUser = RocketChat.models.Users.findOneByEmailAddress user.profile.email if not existantUser existantUser = RocketChat.models.Users.findOneByUsername user.name if existantUser user.rocketId = existantUser._id RocketChat.models.Users.update { _id: user.rocketId }, { $addToSet: { importIds: user.id } } @userTags.push slack: "<@#{user.id}>" slackLong: "<@#{user.id}|#{user.name}>" rocket: "@#{existantUser.username}" else if user.profile.email userId = Accounts.createUser { email: user.profile.email, password: Date.now() + user.name + user.profile.email.toUpperCase() } else userId = Accounts.createUser { username: user.name, password: Date.now() + user.name } Meteor.runAsUser userId, () => Meteor.call 'setUsername', user.name Meteor.call 'joinDefaultChannels', true url = null if user.profile.image_original url = user.profile.image_original else if user.profile.image_512 url = user.profile.image_512 try Meteor.call 'setAvatarFromService', url, undefined, 'url' catch error this.logger.warn "Failed to set #{user.name}'s avatar from url #{url}" # Slack's is -18000 which translates to Rocket.Chat's after dividing by 3600 if user.tz_offset Meteor.call 'userSetUtcOffset', user.tz_offset / 3600 RocketChat.models.Users.update { _id: userId }, { $addToSet: { importIds: user.id } } if user.profile.real_name RocketChat.models.Users.setName userId, user.profile.real_name #Deleted users are 'inactive' users in Rocket.Chat if user.deleted Meteor.call 'setUserActiveStatus', userId, false #TODO: Maybe send emails? user.rocketId = userId @userTags.push slack: "<@#{user.id}>" slackLong: "<@#{user.id}|#{user.name}>" rocket: "@#{user.name}" @addCountCompleted 1 @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} @updateProgress Importer.ProgressStep.IMPORTING_CHANNELS for channel in @channels.channels when channel.do_import do (channel) => Meteor.runAsUser startedByUserId, () => existantRoom = RocketChat.models.Rooms.findOneByName channel.name if existantRoom or channel.is_general if channel.is_general and channel.name isnt existantRoom?.name Meteor.call 'saveRoomSettings', 'GENERAL', 'roomName', channel.name channel.rocketId = if channel.is_general then 'GENERAL' else existantRoom._id RocketChat.models.Rooms.update { _id: channel.rocketId }, { $addToSet: { importIds: channel.id } } else users = [] for member in channel.members when member isnt channel.creator user = @getRocketUser member if user? users.push user.username userId = startedByUserId for user in @users.users when user.id is channel.creator and user.do_import userId = user.rocketId Meteor.runAsUser userId, () => returned = Meteor.call 'createChannel', channel.name, users channel.rocketId = returned.rid # @TODO implement model specific function roomUpdate = ts: new Date(channel.created * 1000) if not _.isEmpty channel.topic?.value roomUpdate.topic = channel.topic.value if not _.isEmpty(channel.purpose?.value) roomUpdate.description = channel.purpose.value RocketChat.models.Rooms.update { _id: channel.rocketId }, { $set: roomUpdate, $addToSet: { importIds: channel.id } } @addCountCompleted 1 @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} missedTypes = {} ignoreTypes = { 'bot_add': true, 'file_comment': true, 'file_mention': true } @updateProgress Importer.ProgressStep.IMPORTING_MESSAGES for channel, messagesObj of @messages do (channel, messagesObj) => Meteor.runAsUser startedByUserId, () => slackChannel = @getSlackChannelFromName channel if slackChannel?.do_import room = RocketChat.models.Rooms.findOneById slackChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } } for date, msgs of messagesObj @updateRecord { 'messagesstatus': "#{channel}/#{date}.#{msgs.messages.length}" } for message in msgs.messages msgDataDefaults = _id: "slack-#{slackChannel.id}-#{message.ts.replace(/\./g, '-')}" ts: new Date(parseInt(message.ts.split('.')[0]) * 1000) if message.type is 'message' if message.subtype? if message.subtype is 'channel_join' if @getRocketUser(message.user)? RocketChat.models.Messages.createUserJoinWithRoomIdAndUser room._id, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_leave' if @getRocketUser(message.user)? RocketChat.models.Messages.createUserLeaveWithRoomIdAndUser room._id, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'me_message' msgObj = msg: "_#{@convertSlackMessageToRocketChat(message.text)}_" _.extend msgObj, msgDataDefaults RocketChat.sendMessage @getRocketUser(message.user), msgObj, room, true else if message.subtype is 'bot_message' botUser = RocketChat.models.Users.findOneById 'rocket.cat', { fields: { username: 1 }} botUsername = if @bots[message.bot_id] then @bots[message.bot_id]?.name else message.username msgObj = msg: @convertSlackMessageToRocketChat(message.text) rid: room._id bot: true attachments: message.attachments username: if botUsername then botUsername else undefined _.extend msgObj, msgDataDefaults if message.edited? msgObj.editedAt = new Date(parseInt(message.edited.ts.split('.')[0]) * 1000) editedBy = @getRocketUser(message.edited.user) if editedBy? msgObj.editedBy = _id: editedBy._id username: editedBy.username if message.icons? msgObj.emoji = message.icons.emoji RocketChat.sendMessage botUser, msgObj, room, true else if message.subtype is 'channel_purpose' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser 'room_changed_description', room._id, message.purpose, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_topic' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser 'room_changed_topic', room._id, message.topic, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_name' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomRenamedWithRoomIdRoomNameAndUser room._id, message.name, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'pinned_item' if message.attachments msgObj = attachments: [ "text" : @convertSlackMessageToRocketChat message.attachments[0].text "author_name" : message.attachments[0].author_subname "author_icon" : getAvatarUrlFromUsername(message.attachments[0].author_subname) ] _.extend msgObj, msgDataDefaults RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser 'message_pinned', room._id, '', @getRocketUser(message.user), msgObj else #TODO: make this better @logger.debug('Pinned item with no attachment, needs work.'); #RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser 'message_pinned', room._id, '', @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'file_share' if message.file?.url_private_download isnt undefined details = message_id: "slack-#{message.ts.replace(/\./g, '-')}" name: message.file.name size: message.file.size type: message.file.mimetype rid: room._id @uploadFile details, message.file.url_private_download, @getRocketUser(message.user), room, new Date(parseInt(message.ts.split('.')[0]) * 1000) else if not missedTypes[message.subtype] and not ignoreTypes[message.subtype] missedTypes[message.subtype] = message else user = @getRocketUser(message.user) if user? msgObj = msg: @convertSlackMessageToRocketChat message.text rid: room._id u: _id: user._id username: user.username _.extend msgObj, msgDataDefaults if message.edited? msgObj.editedAt = new Date(parseInt(message.edited.ts.split('.')[0]) * 1000) editedBy = @getRocketUser(message.edited.user) if editedBy? msgObj.editedBy = _id: editedBy._id username: editedBy.username RocketChat.sendMessage @getRocketUser(message.user), msgObj, room, true # Process the reactions if RocketChat.models.Messages.findOneById(msgDataDefaults._id)? and message.reactions?.length > 0 for reaction in message.reactions for u in reaction.users rcUser = @getRocketUser(u) if rcUser? Meteor.runAsUser rcUser._id, () => Meteor.call 'setReaction', ":#{reaction.name}:", msgDataDefaults._id @addCountCompleted 1 console.log 'Missed import types:', missedTypes @updateProgress Importer.ProgressStep.FINISHING for channel in @channels.channels when channel.do_import and channel.is_archived do (channel) => Meteor.runAsUser startedByUserId, () => Meteor.call 'archiveRoom', channel.rocketId @updateProgress Importer.ProgressStep.DONE timeTook = Date.now() - start @logger.log "Import took #{timeTook} milliseconds." return @getProgress() getSlackChannelFromName: (channelName) => for channel in @channels.channels when channel.name is channelName return channel getRocketUser: (slackId) => for user in @users.users when user.id is slackId return RocketChat.models.Users.findOneById user.rocketId, { fields: { username: 1 }} convertSlackMessageToRocketChat: (message) => if message? message = message.replace /<!everyone>/g, '@all' message = message.replace /<!channel>/g, '@all' message = message.replace /<!here>/g, '@here' message = message.replace /&gt;/g, '>' message = message.replace /&lt;/g, '<' message = message.replace /&amp;/g, '&' message = message.replace /:simple_smile:/g, ':smile:' message = message.replace /:memo:/g, ':pencil:' message = message.replace /:piggy:/g, ':pig:' message = message.replace /:uk:/g, ':gb:' message = message.replace /<(http[s]?:[^>]*)>/g, '$1' for userReplace in @userTags message = message.replace userReplace.slack, userReplace.rocket message = message.replace userReplace.slackLong, userReplace.rocket else message = '' return message getSelection: () => selectionUsers = @users.users.map (user) -> return new Importer.SelectionUser user.id, user.name, user.profile.email, user.deleted, user.is_bot, !user.is_bot selectionChannels = @channels.channels.map (channel) -> return new Importer.SelectionChannel channel.id, channel.name, channel.is_archived, true, false return new Importer.Selection @name, selectionUsers, selectionChannels
129860
Importer.Slack = class Importer.Slack extends Importer.Base constructor: (name, descriptionI18N, fileTypeRegex) -> super(name, descriptionI18N, fileTypeRegex) @userTags = [] @bots = {} @logger.debug('Constructed a new Slack Importer.') prepare: (dataURI, sentContentType, fileName) => super(dataURI, sentContentType, fileName) {image, contentType} = RocketChatFile.dataURIParse dataURI zip = new @AdmZip(new Buffer(image, 'base64')) zipEntries = zip.getEntries() tempChannels = [] tempUsers = [] tempMessages = {} for entry in zipEntries do (entry) => if entry.entryName.indexOf('__MACOSX') > -1 #ignore all of the files inside of __MACOSX @logger.debug("Ignoring the file: #{entry.entryName}") else if entry.entryName == 'channels.json' @updateProgress Importer.ProgressStep.PREPARING_CHANNELS tempChannels = JSON.parse entry.getData().toString() tempChannels = tempChannels.filter (channel) -> channel.creator? else if entry.entryName == 'users.json' @updateProgress Importer.ProgressStep.PREPARING_USERS tempUsers = JSON.parse entry.getData().toString() for user in tempUsers when user.is_bot @bots[user.profile.bot_id] = user else if not entry.isDirectory and entry.entryName.indexOf('/') > -1 item = entry.entryName.split('/') #random/2015-10-04.json channelName = item[0] #random msgGroupData = item[1].split('.')[0] #2015-10-04 if not tempMessages[channelName] tempMessages[channelName] = {} # Catch files which aren't valid JSON files, ignore them try tempMessages[channelName][msgGroupData] = JSON.parse entry.getData().toString() catch @logger.warn "#{entry.entryName} is not a valid JSON file! Unable to import it." # Insert the users record, eventually this might have to be split into several ones as well # if someone tries to import a several thousands users instance usersId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'users', 'users': tempUsers } @users = @collection.findOne usersId @updateRecord { 'count.users': tempUsers.length } @addCountToTotal tempUsers.length # Insert the channels records. channelsId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'channels', 'channels': tempChannels } @channels = @collection.findOne channelsId @updateRecord { 'count.channels': tempChannels.length } @addCountToTotal tempChannels.length # Insert the messages records @updateProgress Importer.ProgressStep.PREPARING_MESSAGES messagesCount = 0 for channel, messagesObj of tempMessages do (channel, messagesObj) => if not @messages[channel] @messages[channel] = {} for date, msgs of messagesObj messagesCount += msgs.length @updateRecord { 'messagesstatus': "#{channel}/#{date}" } if Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize for splitMsg, i in Importer.Base.getBSONSafeArraysFromAnArray(msgs) messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}.#{i}", 'messages': splitMsg } @messages[channel]["#{date}.#{i}"] = @collection.findOne messagesId else messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}", 'messages': msgs } @messages[channel][date] = @collection.findOne messagesId @updateRecord { 'count.messages': messagesCount, 'messagesstatus': null } @addCountToTotal messagesCount if tempUsers.length is 0 or tempChannels.length is 0 or messagesCount is 0 @logger.warn "The loaded users count #{tempUsers.length}, the loaded channels #{tempChannels.length}, and the loaded messages #{messagesCount}" @updateProgress Importer.ProgressStep.ERROR return @getProgress() selectionUsers = tempUsers.map (user) -> return new Importer.SelectionUser user.id, user.name, user.profile.email, user.deleted, user.is_bot, !user.is_bot selectionChannels = tempChannels.map (channel) -> return new Importer.SelectionChannel channel.id, channel.name, channel.is_archived, true, false @updateProgress Importer.ProgressStep.USER_SELECTION return new Importer.Selection @name, selectionUsers, selectionChannels startImport: (importSelection) => super(importSelection) start = Date.now() for user in importSelection.users for u in @users.users when u.id is user.user_id u.do_import = user.do_import @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} for channel in importSelection.channels for c in @channels.channels when c.id is channel.channel_id c.do_import = channel.do_import @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} startedByUserId = Meteor.userId() Meteor.defer => @updateProgress Importer.ProgressStep.IMPORTING_USERS for user in @users.users when user.do_import do (user) => Meteor.runAsUser startedByUserId, () => existantUser = RocketChat.models.Users.findOneByEmailAddress user.profile.email if not existantUser existantUser = RocketChat.models.Users.findOneByUsername user.name if existantUser user.rocketId = existantUser._id RocketChat.models.Users.update { _id: user.rocketId }, { $addToSet: { importIds: user.id } } @userTags.push slack: "<@#{user.id}>" slackLong: "<@#{user.id}|#{user.name}>" rocket: "@#{existantUser.username}" else if user.profile.email userId = Accounts.createUser { email: user.profile.email, password: <PASSWORD>.<PASSWORD>() + <PASSWORD> + user.profile.email.<PASSWORD>() } else userId = Accounts.createUser { username: user.name, password: <PASSWORD>() + <PASSWORD> } Meteor.runAsUser userId, () => Meteor.call 'setUsername', user.name Meteor.call 'joinDefaultChannels', true url = null if user.profile.image_original url = user.profile.image_original else if user.profile.image_512 url = user.profile.image_512 try Meteor.call 'setAvatarFromService', url, undefined, 'url' catch error this.logger.warn "Failed to set #{user.name}'s avatar from url #{url}" # Slack's is -18000 which translates to Rocket.Chat's after dividing by 3600 if user.tz_offset Meteor.call 'userSetUtcOffset', user.tz_offset / 3600 RocketChat.models.Users.update { _id: userId }, { $addToSet: { importIds: user.id } } if user.profile.real_name RocketChat.models.Users.setName userId, user.profile.real_name #Deleted users are 'inactive' users in Rocket.Chat if user.deleted Meteor.call 'setUserActiveStatus', userId, false #TODO: Maybe send emails? user.rocketId = userId @userTags.push slack: "<@#{user.id}>" slackLong: "<@#{user.id}|#{user.name}>" rocket: "@#{user.name}" @addCountCompleted 1 @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} @updateProgress Importer.ProgressStep.IMPORTING_CHANNELS for channel in @channels.channels when channel.do_import do (channel) => Meteor.runAsUser startedByUserId, () => existantRoom = RocketChat.models.Rooms.findOneByName channel.name if existantRoom or channel.is_general if channel.is_general and channel.name isnt existantRoom?.name Meteor.call 'saveRoomSettings', 'GENERAL', 'roomName', channel.name channel.rocketId = if channel.is_general then 'GENERAL' else existantRoom._id RocketChat.models.Rooms.update { _id: channel.rocketId }, { $addToSet: { importIds: channel.id } } else users = [] for member in channel.members when member isnt channel.creator user = @getRocketUser member if user? users.push user.username userId = startedByUserId for user in @users.users when user.id is channel.creator and user.do_import userId = user.rocketId Meteor.runAsUser userId, () => returned = Meteor.call 'createChannel', channel.name, users channel.rocketId = returned.rid # @TODO implement model specific function roomUpdate = ts: new Date(channel.created * 1000) if not _.isEmpty channel.topic?.value roomUpdate.topic = channel.topic.value if not _.isEmpty(channel.purpose?.value) roomUpdate.description = channel.purpose.value RocketChat.models.Rooms.update { _id: channel.rocketId }, { $set: roomUpdate, $addToSet: { importIds: channel.id } } @addCountCompleted 1 @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} missedTypes = {} ignoreTypes = { 'bot_add': true, 'file_comment': true, 'file_mention': true } @updateProgress Importer.ProgressStep.IMPORTING_MESSAGES for channel, messagesObj of @messages do (channel, messagesObj) => Meteor.runAsUser startedByUserId, () => slackChannel = @getSlackChannelFromName channel if slackChannel?.do_import room = RocketChat.models.Rooms.findOneById slackChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } } for date, msgs of messagesObj @updateRecord { 'messagesstatus': "#{channel}/#{date}.#{msgs.messages.length}" } for message in msgs.messages msgDataDefaults = _id: "slack-#{slackChannel.id}-#{message.ts.replace(/\./g, '-')}" ts: new Date(parseInt(message.ts.split('.')[0]) * 1000) if message.type is 'message' if message.subtype? if message.subtype is 'channel_join' if @getRocketUser(message.user)? RocketChat.models.Messages.createUserJoinWithRoomIdAndUser room._id, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_leave' if @getRocketUser(message.user)? RocketChat.models.Messages.createUserLeaveWithRoomIdAndUser room._id, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'me_message' msgObj = msg: "_#{@convertSlackMessageToRocketChat(message.text)}_" _.extend msgObj, msgDataDefaults RocketChat.sendMessage @getRocketUser(message.user), msgObj, room, true else if message.subtype is 'bot_message' botUser = RocketChat.models.Users.findOneById 'rocket.cat', { fields: { username: 1 }} botUsername = if @bots[message.bot_id] then @bots[message.bot_id]?.name else message.username msgObj = msg: @convertSlackMessageToRocketChat(message.text) rid: room._id bot: true attachments: message.attachments username: if botUsername then botUsername else undefined _.extend msgObj, msgDataDefaults if message.edited? msgObj.editedAt = new Date(parseInt(message.edited.ts.split('.')[0]) * 1000) editedBy = @getRocketUser(message.edited.user) if editedBy? msgObj.editedBy = _id: editedBy._id username: editedBy.username if message.icons? msgObj.emoji = message.icons.emoji RocketChat.sendMessage botUser, msgObj, room, true else if message.subtype is 'channel_purpose' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser 'room_changed_description', room._id, message.purpose, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_topic' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser 'room_changed_topic', room._id, message.topic, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_name' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomRenamedWithRoomIdRoomNameAndUser room._id, message.name, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'pinned_item' if message.attachments msgObj = attachments: [ "text" : @convertSlackMessageToRocketChat message.attachments[0].text "author_name" : message.attachments[0].author_subname "author_icon" : getAvatarUrlFromUsername(message.attachments[0].author_subname) ] _.extend msgObj, msgDataDefaults RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser 'message_pinned', room._id, '', @getRocketUser(message.user), msgObj else #TODO: make this better @logger.debug('Pinned item with no attachment, needs work.'); #RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser 'message_pinned', room._id, '', @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'file_share' if message.file?.url_private_download isnt undefined details = message_id: "slack-#{message.ts.replace(/\./g, '-')}" name: message.file.name size: message.file.size type: message.file.mimetype rid: room._id @uploadFile details, message.file.url_private_download, @getRocketUser(message.user), room, new Date(parseInt(message.ts.split('.')[0]) * 1000) else if not missedTypes[message.subtype] and not ignoreTypes[message.subtype] missedTypes[message.subtype] = message else user = @getRocketUser(message.user) if user? msgObj = msg: @convertSlackMessageToRocketChat message.text rid: room._id u: _id: user._id username: user.username _.extend msgObj, msgDataDefaults if message.edited? msgObj.editedAt = new Date(parseInt(message.edited.ts.split('.')[0]) * 1000) editedBy = @getRocketUser(message.edited.user) if editedBy? msgObj.editedBy = _id: editedBy._id username: editedBy.username RocketChat.sendMessage @getRocketUser(message.user), msgObj, room, true # Process the reactions if RocketChat.models.Messages.findOneById(msgDataDefaults._id)? and message.reactions?.length > 0 for reaction in message.reactions for u in reaction.users rcUser = @getRocketUser(u) if rcUser? Meteor.runAsUser rcUser._id, () => Meteor.call 'setReaction', ":#{reaction.name}:", msgDataDefaults._id @addCountCompleted 1 console.log 'Missed import types:', missedTypes @updateProgress Importer.ProgressStep.FINISHING for channel in @channels.channels when channel.do_import and channel.is_archived do (channel) => Meteor.runAsUser startedByUserId, () => Meteor.call 'archiveRoom', channel.rocketId @updateProgress Importer.ProgressStep.DONE timeTook = Date.now() - start @logger.log "Import took #{timeTook} milliseconds." return @getProgress() getSlackChannelFromName: (channelName) => for channel in @channels.channels when channel.name is channelName return channel getRocketUser: (slackId) => for user in @users.users when user.id is slackId return RocketChat.models.Users.findOneById user.rocketId, { fields: { username: 1 }} convertSlackMessageToRocketChat: (message) => if message? message = message.replace /<!everyone>/g, '@all' message = message.replace /<!channel>/g, '@all' message = message.replace /<!here>/g, '@here' message = message.replace /&gt;/g, '>' message = message.replace /&lt;/g, '<' message = message.replace /&amp;/g, '&' message = message.replace /:simple_smile:/g, ':smile:' message = message.replace /:memo:/g, ':pencil:' message = message.replace /:piggy:/g, ':pig:' message = message.replace /:uk:/g, ':gb:' message = message.replace /<(http[s]?:[^>]*)>/g, '$1' for userReplace in @userTags message = message.replace userReplace.slack, userReplace.rocket message = message.replace userReplace.slackLong, userReplace.rocket else message = '' return message getSelection: () => selectionUsers = @users.users.map (user) -> return new Importer.SelectionUser user.id, user.name, user.profile.email, user.deleted, user.is_bot, !user.is_bot selectionChannels = @channels.channels.map (channel) -> return new Importer.SelectionChannel channel.id, channel.name, channel.is_archived, true, false return new Importer.Selection @name, selectionUsers, selectionChannels
true
Importer.Slack = class Importer.Slack extends Importer.Base constructor: (name, descriptionI18N, fileTypeRegex) -> super(name, descriptionI18N, fileTypeRegex) @userTags = [] @bots = {} @logger.debug('Constructed a new Slack Importer.') prepare: (dataURI, sentContentType, fileName) => super(dataURI, sentContentType, fileName) {image, contentType} = RocketChatFile.dataURIParse dataURI zip = new @AdmZip(new Buffer(image, 'base64')) zipEntries = zip.getEntries() tempChannels = [] tempUsers = [] tempMessages = {} for entry in zipEntries do (entry) => if entry.entryName.indexOf('__MACOSX') > -1 #ignore all of the files inside of __MACOSX @logger.debug("Ignoring the file: #{entry.entryName}") else if entry.entryName == 'channels.json' @updateProgress Importer.ProgressStep.PREPARING_CHANNELS tempChannels = JSON.parse entry.getData().toString() tempChannels = tempChannels.filter (channel) -> channel.creator? else if entry.entryName == 'users.json' @updateProgress Importer.ProgressStep.PREPARING_USERS tempUsers = JSON.parse entry.getData().toString() for user in tempUsers when user.is_bot @bots[user.profile.bot_id] = user else if not entry.isDirectory and entry.entryName.indexOf('/') > -1 item = entry.entryName.split('/') #random/2015-10-04.json channelName = item[0] #random msgGroupData = item[1].split('.')[0] #2015-10-04 if not tempMessages[channelName] tempMessages[channelName] = {} # Catch files which aren't valid JSON files, ignore them try tempMessages[channelName][msgGroupData] = JSON.parse entry.getData().toString() catch @logger.warn "#{entry.entryName} is not a valid JSON file! Unable to import it." # Insert the users record, eventually this might have to be split into several ones as well # if someone tries to import a several thousands users instance usersId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'users', 'users': tempUsers } @users = @collection.findOne usersId @updateRecord { 'count.users': tempUsers.length } @addCountToTotal tempUsers.length # Insert the channels records. channelsId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'channels', 'channels': tempChannels } @channels = @collection.findOne channelsId @updateRecord { 'count.channels': tempChannels.length } @addCountToTotal tempChannels.length # Insert the messages records @updateProgress Importer.ProgressStep.PREPARING_MESSAGES messagesCount = 0 for channel, messagesObj of tempMessages do (channel, messagesObj) => if not @messages[channel] @messages[channel] = {} for date, msgs of messagesObj messagesCount += msgs.length @updateRecord { 'messagesstatus': "#{channel}/#{date}" } if Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize for splitMsg, i in Importer.Base.getBSONSafeArraysFromAnArray(msgs) messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}.#{i}", 'messages': splitMsg } @messages[channel]["#{date}.#{i}"] = @collection.findOne messagesId else messagesId = @collection.insert { 'import': @importRecord._id, 'importer': @name, 'type': 'messages', 'name': "#{channel}/#{date}", 'messages': msgs } @messages[channel][date] = @collection.findOne messagesId @updateRecord { 'count.messages': messagesCount, 'messagesstatus': null } @addCountToTotal messagesCount if tempUsers.length is 0 or tempChannels.length is 0 or messagesCount is 0 @logger.warn "The loaded users count #{tempUsers.length}, the loaded channels #{tempChannels.length}, and the loaded messages #{messagesCount}" @updateProgress Importer.ProgressStep.ERROR return @getProgress() selectionUsers = tempUsers.map (user) -> return new Importer.SelectionUser user.id, user.name, user.profile.email, user.deleted, user.is_bot, !user.is_bot selectionChannels = tempChannels.map (channel) -> return new Importer.SelectionChannel channel.id, channel.name, channel.is_archived, true, false @updateProgress Importer.ProgressStep.USER_SELECTION return new Importer.Selection @name, selectionUsers, selectionChannels startImport: (importSelection) => super(importSelection) start = Date.now() for user in importSelection.users for u in @users.users when u.id is user.user_id u.do_import = user.do_import @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} for channel in importSelection.channels for c in @channels.channels when c.id is channel.channel_id c.do_import = channel.do_import @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} startedByUserId = Meteor.userId() Meteor.defer => @updateProgress Importer.ProgressStep.IMPORTING_USERS for user in @users.users when user.do_import do (user) => Meteor.runAsUser startedByUserId, () => existantUser = RocketChat.models.Users.findOneByEmailAddress user.profile.email if not existantUser existantUser = RocketChat.models.Users.findOneByUsername user.name if existantUser user.rocketId = existantUser._id RocketChat.models.Users.update { _id: user.rocketId }, { $addToSet: { importIds: user.id } } @userTags.push slack: "<@#{user.id}>" slackLong: "<@#{user.id}|#{user.name}>" rocket: "@#{existantUser.username}" else if user.profile.email userId = Accounts.createUser { email: user.profile.email, password: PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI() + PI:PASSWORD:<PASSWORD>END_PI + user.profile.email.PI:PASSWORD:<PASSWORD>END_PI() } else userId = Accounts.createUser { username: user.name, password: PI:PASSWORD:<PASSWORD>END_PI() + PI:PASSWORD:<PASSWORD>END_PI } Meteor.runAsUser userId, () => Meteor.call 'setUsername', user.name Meteor.call 'joinDefaultChannels', true url = null if user.profile.image_original url = user.profile.image_original else if user.profile.image_512 url = user.profile.image_512 try Meteor.call 'setAvatarFromService', url, undefined, 'url' catch error this.logger.warn "Failed to set #{user.name}'s avatar from url #{url}" # Slack's is -18000 which translates to Rocket.Chat's after dividing by 3600 if user.tz_offset Meteor.call 'userSetUtcOffset', user.tz_offset / 3600 RocketChat.models.Users.update { _id: userId }, { $addToSet: { importIds: user.id } } if user.profile.real_name RocketChat.models.Users.setName userId, user.profile.real_name #Deleted users are 'inactive' users in Rocket.Chat if user.deleted Meteor.call 'setUserActiveStatus', userId, false #TODO: Maybe send emails? user.rocketId = userId @userTags.push slack: "<@#{user.id}>" slackLong: "<@#{user.id}|#{user.name}>" rocket: "@#{user.name}" @addCountCompleted 1 @collection.update { _id: @users._id }, { $set: { 'users': @users.users }} @updateProgress Importer.ProgressStep.IMPORTING_CHANNELS for channel in @channels.channels when channel.do_import do (channel) => Meteor.runAsUser startedByUserId, () => existantRoom = RocketChat.models.Rooms.findOneByName channel.name if existantRoom or channel.is_general if channel.is_general and channel.name isnt existantRoom?.name Meteor.call 'saveRoomSettings', 'GENERAL', 'roomName', channel.name channel.rocketId = if channel.is_general then 'GENERAL' else existantRoom._id RocketChat.models.Rooms.update { _id: channel.rocketId }, { $addToSet: { importIds: channel.id } } else users = [] for member in channel.members when member isnt channel.creator user = @getRocketUser member if user? users.push user.username userId = startedByUserId for user in @users.users when user.id is channel.creator and user.do_import userId = user.rocketId Meteor.runAsUser userId, () => returned = Meteor.call 'createChannel', channel.name, users channel.rocketId = returned.rid # @TODO implement model specific function roomUpdate = ts: new Date(channel.created * 1000) if not _.isEmpty channel.topic?.value roomUpdate.topic = channel.topic.value if not _.isEmpty(channel.purpose?.value) roomUpdate.description = channel.purpose.value RocketChat.models.Rooms.update { _id: channel.rocketId }, { $set: roomUpdate, $addToSet: { importIds: channel.id } } @addCountCompleted 1 @collection.update { _id: @channels._id }, { $set: { 'channels': @channels.channels }} missedTypes = {} ignoreTypes = { 'bot_add': true, 'file_comment': true, 'file_mention': true } @updateProgress Importer.ProgressStep.IMPORTING_MESSAGES for channel, messagesObj of @messages do (channel, messagesObj) => Meteor.runAsUser startedByUserId, () => slackChannel = @getSlackChannelFromName channel if slackChannel?.do_import room = RocketChat.models.Rooms.findOneById slackChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } } for date, msgs of messagesObj @updateRecord { 'messagesstatus': "#{channel}/#{date}.#{msgs.messages.length}" } for message in msgs.messages msgDataDefaults = _id: "slack-#{slackChannel.id}-#{message.ts.replace(/\./g, '-')}" ts: new Date(parseInt(message.ts.split('.')[0]) * 1000) if message.type is 'message' if message.subtype? if message.subtype is 'channel_join' if @getRocketUser(message.user)? RocketChat.models.Messages.createUserJoinWithRoomIdAndUser room._id, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_leave' if @getRocketUser(message.user)? RocketChat.models.Messages.createUserLeaveWithRoomIdAndUser room._id, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'me_message' msgObj = msg: "_#{@convertSlackMessageToRocketChat(message.text)}_" _.extend msgObj, msgDataDefaults RocketChat.sendMessage @getRocketUser(message.user), msgObj, room, true else if message.subtype is 'bot_message' botUser = RocketChat.models.Users.findOneById 'rocket.cat', { fields: { username: 1 }} botUsername = if @bots[message.bot_id] then @bots[message.bot_id]?.name else message.username msgObj = msg: @convertSlackMessageToRocketChat(message.text) rid: room._id bot: true attachments: message.attachments username: if botUsername then botUsername else undefined _.extend msgObj, msgDataDefaults if message.edited? msgObj.editedAt = new Date(parseInt(message.edited.ts.split('.')[0]) * 1000) editedBy = @getRocketUser(message.edited.user) if editedBy? msgObj.editedBy = _id: editedBy._id username: editedBy.username if message.icons? msgObj.emoji = message.icons.emoji RocketChat.sendMessage botUser, msgObj, room, true else if message.subtype is 'channel_purpose' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser 'room_changed_description', room._id, message.purpose, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_topic' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser 'room_changed_topic', room._id, message.topic, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'channel_name' if @getRocketUser(message.user)? RocketChat.models.Messages.createRoomRenamedWithRoomIdRoomNameAndUser room._id, message.name, @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'pinned_item' if message.attachments msgObj = attachments: [ "text" : @convertSlackMessageToRocketChat message.attachments[0].text "author_name" : message.attachments[0].author_subname "author_icon" : getAvatarUrlFromUsername(message.attachments[0].author_subname) ] _.extend msgObj, msgDataDefaults RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser 'message_pinned', room._id, '', @getRocketUser(message.user), msgObj else #TODO: make this better @logger.debug('Pinned item with no attachment, needs work.'); #RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser 'message_pinned', room._id, '', @getRocketUser(message.user), msgDataDefaults else if message.subtype is 'file_share' if message.file?.url_private_download isnt undefined details = message_id: "slack-#{message.ts.replace(/\./g, '-')}" name: message.file.name size: message.file.size type: message.file.mimetype rid: room._id @uploadFile details, message.file.url_private_download, @getRocketUser(message.user), room, new Date(parseInt(message.ts.split('.')[0]) * 1000) else if not missedTypes[message.subtype] and not ignoreTypes[message.subtype] missedTypes[message.subtype] = message else user = @getRocketUser(message.user) if user? msgObj = msg: @convertSlackMessageToRocketChat message.text rid: room._id u: _id: user._id username: user.username _.extend msgObj, msgDataDefaults if message.edited? msgObj.editedAt = new Date(parseInt(message.edited.ts.split('.')[0]) * 1000) editedBy = @getRocketUser(message.edited.user) if editedBy? msgObj.editedBy = _id: editedBy._id username: editedBy.username RocketChat.sendMessage @getRocketUser(message.user), msgObj, room, true # Process the reactions if RocketChat.models.Messages.findOneById(msgDataDefaults._id)? and message.reactions?.length > 0 for reaction in message.reactions for u in reaction.users rcUser = @getRocketUser(u) if rcUser? Meteor.runAsUser rcUser._id, () => Meteor.call 'setReaction', ":#{reaction.name}:", msgDataDefaults._id @addCountCompleted 1 console.log 'Missed import types:', missedTypes @updateProgress Importer.ProgressStep.FINISHING for channel in @channels.channels when channel.do_import and channel.is_archived do (channel) => Meteor.runAsUser startedByUserId, () => Meteor.call 'archiveRoom', channel.rocketId @updateProgress Importer.ProgressStep.DONE timeTook = Date.now() - start @logger.log "Import took #{timeTook} milliseconds." return @getProgress() getSlackChannelFromName: (channelName) => for channel in @channels.channels when channel.name is channelName return channel getRocketUser: (slackId) => for user in @users.users when user.id is slackId return RocketChat.models.Users.findOneById user.rocketId, { fields: { username: 1 }} convertSlackMessageToRocketChat: (message) => if message? message = message.replace /<!everyone>/g, '@all' message = message.replace /<!channel>/g, '@all' message = message.replace /<!here>/g, '@here' message = message.replace /&gt;/g, '>' message = message.replace /&lt;/g, '<' message = message.replace /&amp;/g, '&' message = message.replace /:simple_smile:/g, ':smile:' message = message.replace /:memo:/g, ':pencil:' message = message.replace /:piggy:/g, ':pig:' message = message.replace /:uk:/g, ':gb:' message = message.replace /<(http[s]?:[^>]*)>/g, '$1' for userReplace in @userTags message = message.replace userReplace.slack, userReplace.rocket message = message.replace userReplace.slackLong, userReplace.rocket else message = '' return message getSelection: () => selectionUsers = @users.users.map (user) -> return new Importer.SelectionUser user.id, user.name, user.profile.email, user.deleted, user.is_bot, !user.is_bot selectionChannels = @channels.channels.map (channel) -> return new Importer.SelectionChannel channel.id, channel.name, channel.is_archived, true, false return new Importer.Selection @name, selectionUsers, selectionChannels
[ { "context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'PlLd'\n\n constructor: (layer, length) ->\n super(lay", "end": 178, "score": 0.9480730295181274, "start": 174, "tag": "KEY", "value": "PlLd" } ]
lib/psd/layer_info/placed_layer.coffee
kostark/psd.js
0
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' module.exports = class PlacedLayer extends LayerInfo @shouldParse: (key) -> key is 'PlLd' constructor: (layer, length) -> super(layer, length) @uuid = null @page = 0 @totalPages = 0 @antiAlias = 0 @layerType = 0 @transform = [] @warp = null parse: -> @file.seek 8, true @uuid = @file.readString(@file.readByte()) @page = @file.readInt() @totalPages = @file.readInt() @antiAlias = @file.readInt() @layerType = @file.readInt() @transform.push @file.readDouble() for i in [0...8] @file.seek 8, true @warp = new Descriptor(@file).parse() @parseWarp @warp parseWarp: (warp) -> envelopeWarp = warp.customEnvelopeWarp; meshPoints = null if envelopeWarp meshPoints = [] xs = (envelopeWarp.meshPoints.find (i) => i.type is 'Hrzn')?.values || [] ys = (envelopeWarp.meshPoints.find (i) => i.type is 'Vrtc')?.values || [] for i in [0...xs.length] meshPoints.push({x: xs[i], y: ys[i]}); warp.meshPoints = meshPoints
186101
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' module.exports = class PlacedLayer extends LayerInfo @shouldParse: (key) -> key is '<KEY>' constructor: (layer, length) -> super(layer, length) @uuid = null @page = 0 @totalPages = 0 @antiAlias = 0 @layerType = 0 @transform = [] @warp = null parse: -> @file.seek 8, true @uuid = @file.readString(@file.readByte()) @page = @file.readInt() @totalPages = @file.readInt() @antiAlias = @file.readInt() @layerType = @file.readInt() @transform.push @file.readDouble() for i in [0...8] @file.seek 8, true @warp = new Descriptor(@file).parse() @parseWarp @warp parseWarp: (warp) -> envelopeWarp = warp.customEnvelopeWarp; meshPoints = null if envelopeWarp meshPoints = [] xs = (envelopeWarp.meshPoints.find (i) => i.type is 'Hrzn')?.values || [] ys = (envelopeWarp.meshPoints.find (i) => i.type is 'Vrtc')?.values || [] for i in [0...xs.length] meshPoints.push({x: xs[i], y: ys[i]}); warp.meshPoints = meshPoints
true
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' module.exports = class PlacedLayer extends LayerInfo @shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI' constructor: (layer, length) -> super(layer, length) @uuid = null @page = 0 @totalPages = 0 @antiAlias = 0 @layerType = 0 @transform = [] @warp = null parse: -> @file.seek 8, true @uuid = @file.readString(@file.readByte()) @page = @file.readInt() @totalPages = @file.readInt() @antiAlias = @file.readInt() @layerType = @file.readInt() @transform.push @file.readDouble() for i in [0...8] @file.seek 8, true @warp = new Descriptor(@file).parse() @parseWarp @warp parseWarp: (warp) -> envelopeWarp = warp.customEnvelopeWarp; meshPoints = null if envelopeWarp meshPoints = [] xs = (envelopeWarp.meshPoints.find (i) => i.type is 'Hrzn')?.values || [] ys = (envelopeWarp.meshPoints.find (i) => i.type is 'Vrtc')?.values || [] for i in [0...xs.length] meshPoints.push({x: xs[i], y: ys[i]}); warp.meshPoints = meshPoints
[ { "context": "/PEM--/grunt-phonegapsplash\n#\n# Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>)\n# Licensed under", "end": 120, "score": 0.9998695850372314, "start": 98, "tag": "NAME", "value": "Pierre-Eric Marchandet" }, { "context": "Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>)\n# Licensed under the MIT licence.\n###\n\n'use str", "end": 151, "score": 0.9999237656593323, "start": 129, "tag": "EMAIL", "value": "pemarchandet@gmail.com" } ]
tasks/phonegapsplash.coffee
gruntjs-updater/grunt-phonegapsplash
0
### # grunt-phonegapsplash # https://github.com/PEM--/grunt-phonegapsplash # # Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>) # Licensed under the MIT licence. ### 'use strict' # GraphicsMagick (node-gm) is used for cropping and resizing tasks. gm = require 'gm' # Async is used to transform this task as an asynchronous task. async = require 'async' # Path from NodeJS app is used to merge directory and sub drectories. path = require 'path' # Main splashscreen resolution (a squared PNG) RESOLUTION = 2048 # Special values for layout none (squared layout) OFFSET = 384 NONE_RESOLUTION = 1280 module.exports = (grunt) -> grunt.registerMultiTask 'phonegapsplash', \ 'Create PhoneGap splashscreens from a single PNG file.', -> # Call this function when inner tasks are achieved. done = @async() # Default options are set to produce all splashscreens. # This setting can be surcharged by user. options = @options prjName: 'Test' layouts: [ 'portrait', 'landscape', 'none' ] profiles: [ 'android', 'bada', 'blackberry', 'ios', 'webos', 'windows-phone' ] # Get all profiles as constants PROFILES = (require '../lib/profiles') options # Check existence of source file return done new Error "Only one source file is allowed: #{@files}" \ if @files.length isnt 1 or @files[0].orig.src.length isnt 1 SRC = @files[0].orig.src[0] return done new Error "Source file '#{SRC}' not found: #{@files}" \ if not grunt.file.exists SRC # Get the result's folder DEST = @files[0].dest # Iterate over each selected profile async.each options.profiles, (optProfile, nextProfile) -> grunt.log.debug "Profile: #{optProfile}" # Avoid undefined profile curProfile = PROFILES[optProfile] return nextProfile() if curProfile is undefined # Iterate over each selected layout async.each options.layouts, (optLayout, nextLayout) -> grunt.log.debug "Layout: #{optLayout}" # Avoid undefined layout curLayout = curProfile.layout[optLayout] return nextLayout() if curLayout is undefined # Iterate over each splashcreen async.each curLayout.splashs, (splash, nextSplash) -> targetFile = path.join DEST, curProfile.dir, splash.name grunt.log.debug "Creating #{targetFile}" # Adjust cropping variables depending on layout cropX = cropY = cropWidth = cropHeight = 0 switch optLayout when 'landscape' cropX = 0 cropWidth = RESOLUTION cropHeight = Math.floor splash.height * RESOLUTION / splash.width cropY = Math.floor (RESOLUTION - cropHeight) / 2 when 'portrait' cropY = 0 cropHeight = RESOLUTION cropWidth = Math.floor splash.width * RESOLUTION / splash.height cropX = Math.floor (RESOLUTION - cropWidth) / 2 else cropX = cropY = OFFSET cropWidth = cropHeight = NONE_RESOLUTION # Check if a sub sub path is necessary as Android's splash names # require a specific sub sub directory. grunt.file.mkdir path.dirname targetFile # Create the splashcreen in the appropriate directory. # The source is cropped to fit aspect ratio of target splashcreen # and resized before written. grunt.log.debug "gm convert " + \ "-crop #{cropWidth}x#{cropHeight}+#{cropX}+#{cropY} " + \ "-resize #{splash.width}x#{splash.height}! " + \ "#{SRC} #{targetFile}" gm(SRC) .crop(cropWidth, cropHeight, cropX, cropY) .resize(splash.width, splash.height, '!') .write targetFile, (err) -> grunt.log.ok "Splashcreen #{targetFile} created." return nextSplash err if err nextSplash() , nextLayout , nextProfile , (err) -> if err grunt.log.error err.message done false done()
48546
### # grunt-phonegapsplash # https://github.com/PEM--/grunt-phonegapsplash # # Copyright (c) 2013 <NAME> (PEM-- <<EMAIL>>) # Licensed under the MIT licence. ### 'use strict' # GraphicsMagick (node-gm) is used for cropping and resizing tasks. gm = require 'gm' # Async is used to transform this task as an asynchronous task. async = require 'async' # Path from NodeJS app is used to merge directory and sub drectories. path = require 'path' # Main splashscreen resolution (a squared PNG) RESOLUTION = 2048 # Special values for layout none (squared layout) OFFSET = 384 NONE_RESOLUTION = 1280 module.exports = (grunt) -> grunt.registerMultiTask 'phonegapsplash', \ 'Create PhoneGap splashscreens from a single PNG file.', -> # Call this function when inner tasks are achieved. done = @async() # Default options are set to produce all splashscreens. # This setting can be surcharged by user. options = @options prjName: 'Test' layouts: [ 'portrait', 'landscape', 'none' ] profiles: [ 'android', 'bada', 'blackberry', 'ios', 'webos', 'windows-phone' ] # Get all profiles as constants PROFILES = (require '../lib/profiles') options # Check existence of source file return done new Error "Only one source file is allowed: #{@files}" \ if @files.length isnt 1 or @files[0].orig.src.length isnt 1 SRC = @files[0].orig.src[0] return done new Error "Source file '#{SRC}' not found: #{@files}" \ if not grunt.file.exists SRC # Get the result's folder DEST = @files[0].dest # Iterate over each selected profile async.each options.profiles, (optProfile, nextProfile) -> grunt.log.debug "Profile: #{optProfile}" # Avoid undefined profile curProfile = PROFILES[optProfile] return nextProfile() if curProfile is undefined # Iterate over each selected layout async.each options.layouts, (optLayout, nextLayout) -> grunt.log.debug "Layout: #{optLayout}" # Avoid undefined layout curLayout = curProfile.layout[optLayout] return nextLayout() if curLayout is undefined # Iterate over each splashcreen async.each curLayout.splashs, (splash, nextSplash) -> targetFile = path.join DEST, curProfile.dir, splash.name grunt.log.debug "Creating #{targetFile}" # Adjust cropping variables depending on layout cropX = cropY = cropWidth = cropHeight = 0 switch optLayout when 'landscape' cropX = 0 cropWidth = RESOLUTION cropHeight = Math.floor splash.height * RESOLUTION / splash.width cropY = Math.floor (RESOLUTION - cropHeight) / 2 when 'portrait' cropY = 0 cropHeight = RESOLUTION cropWidth = Math.floor splash.width * RESOLUTION / splash.height cropX = Math.floor (RESOLUTION - cropWidth) / 2 else cropX = cropY = OFFSET cropWidth = cropHeight = NONE_RESOLUTION # Check if a sub sub path is necessary as Android's splash names # require a specific sub sub directory. grunt.file.mkdir path.dirname targetFile # Create the splashcreen in the appropriate directory. # The source is cropped to fit aspect ratio of target splashcreen # and resized before written. grunt.log.debug "gm convert " + \ "-crop #{cropWidth}x#{cropHeight}+#{cropX}+#{cropY} " + \ "-resize #{splash.width}x#{splash.height}! " + \ "#{SRC} #{targetFile}" gm(SRC) .crop(cropWidth, cropHeight, cropX, cropY) .resize(splash.width, splash.height, '!') .write targetFile, (err) -> grunt.log.ok "Splashcreen #{targetFile} created." return nextSplash err if err nextSplash() , nextLayout , nextProfile , (err) -> if err grunt.log.error err.message done false done()
true
### # grunt-phonegapsplash # https://github.com/PEM--/grunt-phonegapsplash # # Copyright (c) 2013 PI:NAME:<NAME>END_PI (PEM-- <PI:EMAIL:<EMAIL>END_PI>) # Licensed under the MIT licence. ### 'use strict' # GraphicsMagick (node-gm) is used for cropping and resizing tasks. gm = require 'gm' # Async is used to transform this task as an asynchronous task. async = require 'async' # Path from NodeJS app is used to merge directory and sub drectories. path = require 'path' # Main splashscreen resolution (a squared PNG) RESOLUTION = 2048 # Special values for layout none (squared layout) OFFSET = 384 NONE_RESOLUTION = 1280 module.exports = (grunt) -> grunt.registerMultiTask 'phonegapsplash', \ 'Create PhoneGap splashscreens from a single PNG file.', -> # Call this function when inner tasks are achieved. done = @async() # Default options are set to produce all splashscreens. # This setting can be surcharged by user. options = @options prjName: 'Test' layouts: [ 'portrait', 'landscape', 'none' ] profiles: [ 'android', 'bada', 'blackberry', 'ios', 'webos', 'windows-phone' ] # Get all profiles as constants PROFILES = (require '../lib/profiles') options # Check existence of source file return done new Error "Only one source file is allowed: #{@files}" \ if @files.length isnt 1 or @files[0].orig.src.length isnt 1 SRC = @files[0].orig.src[0] return done new Error "Source file '#{SRC}' not found: #{@files}" \ if not grunt.file.exists SRC # Get the result's folder DEST = @files[0].dest # Iterate over each selected profile async.each options.profiles, (optProfile, nextProfile) -> grunt.log.debug "Profile: #{optProfile}" # Avoid undefined profile curProfile = PROFILES[optProfile] return nextProfile() if curProfile is undefined # Iterate over each selected layout async.each options.layouts, (optLayout, nextLayout) -> grunt.log.debug "Layout: #{optLayout}" # Avoid undefined layout curLayout = curProfile.layout[optLayout] return nextLayout() if curLayout is undefined # Iterate over each splashcreen async.each curLayout.splashs, (splash, nextSplash) -> targetFile = path.join DEST, curProfile.dir, splash.name grunt.log.debug "Creating #{targetFile}" # Adjust cropping variables depending on layout cropX = cropY = cropWidth = cropHeight = 0 switch optLayout when 'landscape' cropX = 0 cropWidth = RESOLUTION cropHeight = Math.floor splash.height * RESOLUTION / splash.width cropY = Math.floor (RESOLUTION - cropHeight) / 2 when 'portrait' cropY = 0 cropHeight = RESOLUTION cropWidth = Math.floor splash.width * RESOLUTION / splash.height cropX = Math.floor (RESOLUTION - cropWidth) / 2 else cropX = cropY = OFFSET cropWidth = cropHeight = NONE_RESOLUTION # Check if a sub sub path is necessary as Android's splash names # require a specific sub sub directory. grunt.file.mkdir path.dirname targetFile # Create the splashcreen in the appropriate directory. # The source is cropped to fit aspect ratio of target splashcreen # and resized before written. grunt.log.debug "gm convert " + \ "-crop #{cropWidth}x#{cropHeight}+#{cropX}+#{cropY} " + \ "-resize #{splash.width}x#{splash.height}! " + \ "#{SRC} #{targetFile}" gm(SRC) .crop(cropWidth, cropHeight, cropX, cropY) .resize(splash.width, splash.height, '!') .write targetFile, (err) -> grunt.log.ok "Splashcreen #{targetFile} created." return nextSplash err if err nextSplash() , nextLayout , nextProfile , (err) -> if err grunt.log.error err.message done false done()
[ { "context": "verview Tests for jsx-sort-default-props\n# @author Vladimir Kattsov\n###\n'use strict'\n\n# -----------------------------", "end": 80, "score": 0.999868631362915, "start": 64, "tag": "NAME", "value": "Vladimir Kattsov" } ]
src/tests/rules/jsx-sort-default-props.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for jsx-sort-default-props # @author Vladimir Kattsov ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- rule = require '../../rules/jsx-sort-default-props' {RuleTester} = require 'eslint' path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ERROR_MESSAGE = 'Default prop types declarations should be sorted alphabetically' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-sort-default-props', rule, valid: [ code: [ 'First = createReactClass({' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes:' ' A: PropTypes.any' ' Z: PropTypes.string' ' a: PropTypes.any' ' z: PropTypes.string' ' getDefaultProps: ->' ' A: "A"' ' Z: "Z"' ' a: "a"' ' z: "z"' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes: {' ' a: PropTypes.any,' ' A: PropTypes.any,' ' z: PropTypes.string,' ' Z: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' a: "a",' ' A: "A",' ' z: "z",' ' Z: "Z"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' options: [ignoreCase: yes] , code: [ 'First = createReactClass({' ' propTypes: {' ' a: PropTypes.any,' ' z: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' a: "a",' ' z: "z"' ' }' ' render: ->' ' return <div />' '})' 'Second = createReactClass({' ' propTypes: {' ' AA: PropTypes.any,' ' ZZ: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' AA: "AA",' ' ZZ: "ZZ"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'class First extends React.Component' ' render: ->' ' return <div />' 'First.propTypes = {' ' a: PropTypes.string,' ' z: PropTypes.string' '}' 'First.propTypes.justforcheck = PropTypes.string' 'First.defaultProps = {' ' a: a,' ' z: z' '}' 'First.defaultProps.justforcheck = "justforcheck"' ].join '\n' , code: [ 'class First extends React.Component' ' render: ->' ' return <div />' 'First.propTypes = {' ' a: PropTypes.any,' ' A: PropTypes.any,' ' z: PropTypes.string,' ' Z: PropTypes.string' '}' 'First.defaultProps = {' ' a: "a",' ' A: "A",' ' z: "z",' ' Z: "Z"' '}' ].join '\n' options: [ignoreCase: yes] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' b: "b",' ' c: "c"' ' }' ' render: ->' ' return <div />' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "aria-controls": PropTypes.string' '}' 'Hello.defaultProps = {' ' "aria-controls": "aria-controls"' '}' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] , # Invalid code, should not be validated code: [ 'class Component extends React.Component' ' propTypes: {' ' a: PropTypes.any,' ' c: PropTypes.any,' ' b: PropTypes.any' ' }' ' defaultProps: {' ' a: "a",' ' c: "c",' ' b: "b"' ' }' ' render: ->' ' return <div />' ].join '\n' , # parser: 'babel-eslint' code: [ 'Hello = createReactClass({' ' render: ->' ' { a, ...b } = obj' ' c = { ...d }' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes: {' ' barRequired: PropTypes.func.isRequired,' ' onBar: PropTypes.func,' ' z: PropTypes.any' ' },' ' getDefaultProps: ->' ' return {' ' barRequired: "barRequired",' ' onBar: "onBar",' ' z: "z"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' b: PropTypes.string,' ' ...c.propTypes,' ' a: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' ...c.defaultProps,' ' a: "a"' ' }' ].join '\n' , # parser: 'babel-eslint' code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string,' ' d: PropTypes.string,' ' e: PropTypes.string,' ' f: PropTypes.string' ' }' ' @defaultProps = {' ' a: "a",' ' b: "b",' ' ...c.defaultProps,' ' e: "e",' ' f: "f",' ' ...d.defaultProps' ' }' ].join '\n' , # parser: 'babel-eslint' code: [ 'defaults = {' ' b: "b"' '}' 'types = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string' '}' 'StatelessComponentWithSpreadInPropTypes = ({ a, b, c }) ->' ' return <div>{a}{b}{c}</div>' 'StatelessComponentWithSpreadInPropTypes.propTypes = types' 'StatelessComponentWithSpreadInPropTypes.defaultProps = {' ' c: "c",' ' ...defaults,' ' a: "a"' '}' ].join '\n' , # parser: 'babel-eslint' code: [ "propTypes = require('./externalPropTypes')" "defaultProps = require('./externalDefaultProps')" 'TextFieldLabel = (props) =>' ' return <div />' 'TextFieldLabel.propTypes = propTypes' 'TextFieldLabel.defaultProps = defaultProps' ].join '\n' , code: [ 'First = (props) => <div />' 'export propTypes = {' ' a: PropTypes.any,' ' z: PropTypes.string,' '}' 'export defaultProps = {' ' a: "a",' ' z: "z",' '}' 'First.propTypes = propTypes' 'First.defaultProps = defaultProps' ].join '\n' ] invalid: [ code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' c: "c",' ' b: "b"' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 5 type: 'Property' ] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' c: "c",' ' b: "b",' ' a: "a"' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'class Component extends React.Component' ' @propTypes:' ' a: PropTypes.any' ' b: PropTypes.any' ' @defaultProps:' ' Z: "Z"' ' a: "a"' ' render: ->' ' <div />' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] errors: [ message: ERROR_MESSAGE line: 7 column: 5 type: 'Property' ] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' z: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' Z: "Z",' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 8 column: 5 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "b": PropTypes.string' '}' 'Hello.defaultProps = {' ' "b": "b",' ' "a": "a"' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "b": PropTypes.string,' ' "c": PropTypes.string' '}' 'Hello.defaultProps = {' ' "c": "c",' ' "b": "b",' ' "a": "a"' '}' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "B": PropTypes.string,' '}' 'Hello.defaultProps = {' ' "a": "a",' ' "B": "B",' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "B": PropTypes.string,' '}' 'Hello.defaultProps = {' ' "B": "B",' ' "a": "a",' '}' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'First = (props) => <div />' 'propTypes = {' ' z: PropTypes.string,' ' a: PropTypes.any,' '}' 'defaultProps = {' ' z: "z",' ' a: "a",' '}' 'First.propTypes = propTypes' 'First.defaultProps = defaultProps' ].join '\n' errors: [ message: ERROR_MESSAGE line: 8 column: 3 type: 'Property' ] , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' b: PropTypes.string,' ' ...c.propTypes,' ' a: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' a: "a",' ' ...c.defaultProps' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 9 column: 5 type: 'Property' ] , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string,' ' d: PropTypes.string,' ' e: PropTypes.string,' ' f: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' a: "a",' ' ...c.defaultProps,' ' f: "f",' ' e: "e",' ' ...d.defaultProps' ' }' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'defaults = {' ' b: "b"' '}' 'types = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string' '}' 'StatelessComponentWithSpreadInPropTypes = ({ a, b, c }) ->' ' return <div>{a}{b}{c}</div>' 'StatelessComponentWithSpreadInPropTypes.propTypes = types' 'StatelessComponentWithSpreadInPropTypes.defaultProps = {' ' c: "c",' ' a: "a",' ' ...defaults,' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 14 column: 3 type: 'Property' ] ]
117634
###* # @fileoverview Tests for jsx-sort-default-props # @author <NAME> ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- rule = require '../../rules/jsx-sort-default-props' {RuleTester} = require 'eslint' path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ERROR_MESSAGE = 'Default prop types declarations should be sorted alphabetically' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-sort-default-props', rule, valid: [ code: [ 'First = createReactClass({' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes:' ' A: PropTypes.any' ' Z: PropTypes.string' ' a: PropTypes.any' ' z: PropTypes.string' ' getDefaultProps: ->' ' A: "A"' ' Z: "Z"' ' a: "a"' ' z: "z"' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes: {' ' a: PropTypes.any,' ' A: PropTypes.any,' ' z: PropTypes.string,' ' Z: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' a: "a",' ' A: "A",' ' z: "z",' ' Z: "Z"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' options: [ignoreCase: yes] , code: [ 'First = createReactClass({' ' propTypes: {' ' a: PropTypes.any,' ' z: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' a: "a",' ' z: "z"' ' }' ' render: ->' ' return <div />' '})' 'Second = createReactClass({' ' propTypes: {' ' AA: PropTypes.any,' ' ZZ: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' AA: "AA",' ' ZZ: "ZZ"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'class First extends React.Component' ' render: ->' ' return <div />' 'First.propTypes = {' ' a: PropTypes.string,' ' z: PropTypes.string' '}' 'First.propTypes.justforcheck = PropTypes.string' 'First.defaultProps = {' ' a: a,' ' z: z' '}' 'First.defaultProps.justforcheck = "justforcheck"' ].join '\n' , code: [ 'class First extends React.Component' ' render: ->' ' return <div />' 'First.propTypes = {' ' a: PropTypes.any,' ' A: PropTypes.any,' ' z: PropTypes.string,' ' Z: PropTypes.string' '}' 'First.defaultProps = {' ' a: "a",' ' A: "A",' ' z: "z",' ' Z: "Z"' '}' ].join '\n' options: [ignoreCase: yes] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' b: "b",' ' c: "c"' ' }' ' render: ->' ' return <div />' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "aria-controls": PropTypes.string' '}' 'Hello.defaultProps = {' ' "aria-controls": "aria-controls"' '}' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] , # Invalid code, should not be validated code: [ 'class Component extends React.Component' ' propTypes: {' ' a: PropTypes.any,' ' c: PropTypes.any,' ' b: PropTypes.any' ' }' ' defaultProps: {' ' a: "a",' ' c: "c",' ' b: "b"' ' }' ' render: ->' ' return <div />' ].join '\n' , # parser: 'babel-eslint' code: [ 'Hello = createReactClass({' ' render: ->' ' { a, ...b } = obj' ' c = { ...d }' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes: {' ' barRequired: PropTypes.func.isRequired,' ' onBar: PropTypes.func,' ' z: PropTypes.any' ' },' ' getDefaultProps: ->' ' return {' ' barRequired: "barRequired",' ' onBar: "onBar",' ' z: "z"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' b: PropTypes.string,' ' ...c.propTypes,' ' a: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' ...c.defaultProps,' ' a: "a"' ' }' ].join '\n' , # parser: 'babel-eslint' code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string,' ' d: PropTypes.string,' ' e: PropTypes.string,' ' f: PropTypes.string' ' }' ' @defaultProps = {' ' a: "a",' ' b: "b",' ' ...c.defaultProps,' ' e: "e",' ' f: "f",' ' ...d.defaultProps' ' }' ].join '\n' , # parser: 'babel-eslint' code: [ 'defaults = {' ' b: "b"' '}' 'types = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string' '}' 'StatelessComponentWithSpreadInPropTypes = ({ a, b, c }) ->' ' return <div>{a}{b}{c}</div>' 'StatelessComponentWithSpreadInPropTypes.propTypes = types' 'StatelessComponentWithSpreadInPropTypes.defaultProps = {' ' c: "c",' ' ...defaults,' ' a: "a"' '}' ].join '\n' , # parser: 'babel-eslint' code: [ "propTypes = require('./externalPropTypes')" "defaultProps = require('./externalDefaultProps')" 'TextFieldLabel = (props) =>' ' return <div />' 'TextFieldLabel.propTypes = propTypes' 'TextFieldLabel.defaultProps = defaultProps' ].join '\n' , code: [ 'First = (props) => <div />' 'export propTypes = {' ' a: PropTypes.any,' ' z: PropTypes.string,' '}' 'export defaultProps = {' ' a: "a",' ' z: "z",' '}' 'First.propTypes = propTypes' 'First.defaultProps = defaultProps' ].join '\n' ] invalid: [ code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' c: "c",' ' b: "b"' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 5 type: 'Property' ] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' c: "c",' ' b: "b",' ' a: "a"' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'class Component extends React.Component' ' @propTypes:' ' a: PropTypes.any' ' b: PropTypes.any' ' @defaultProps:' ' Z: "Z"' ' a: "a"' ' render: ->' ' <div />' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] errors: [ message: ERROR_MESSAGE line: 7 column: 5 type: 'Property' ] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' z: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' Z: "Z",' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 8 column: 5 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "b": PropTypes.string' '}' 'Hello.defaultProps = {' ' "b": "b",' ' "a": "a"' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "b": PropTypes.string,' ' "c": PropTypes.string' '}' 'Hello.defaultProps = {' ' "c": "c",' ' "b": "b",' ' "a": "a"' '}' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "B": PropTypes.string,' '}' 'Hello.defaultProps = {' ' "a": "a",' ' "B": "B",' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "B": PropTypes.string,' '}' 'Hello.defaultProps = {' ' "B": "B",' ' "a": "a",' '}' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'First = (props) => <div />' 'propTypes = {' ' z: PropTypes.string,' ' a: PropTypes.any,' '}' 'defaultProps = {' ' z: "z",' ' a: "a",' '}' 'First.propTypes = propTypes' 'First.defaultProps = defaultProps' ].join '\n' errors: [ message: ERROR_MESSAGE line: 8 column: 3 type: 'Property' ] , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' b: PropTypes.string,' ' ...c.propTypes,' ' a: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' a: "a",' ' ...c.defaultProps' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 9 column: 5 type: 'Property' ] , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string,' ' d: PropTypes.string,' ' e: PropTypes.string,' ' f: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' a: "a",' ' ...c.defaultProps,' ' f: "f",' ' e: "e",' ' ...d.defaultProps' ' }' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'defaults = {' ' b: "b"' '}' 'types = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string' '}' 'StatelessComponentWithSpreadInPropTypes = ({ a, b, c }) ->' ' return <div>{a}{b}{c}</div>' 'StatelessComponentWithSpreadInPropTypes.propTypes = types' 'StatelessComponentWithSpreadInPropTypes.defaultProps = {' ' c: "c",' ' a: "a",' ' ...defaults,' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 14 column: 3 type: 'Property' ] ]
true
###* # @fileoverview Tests for jsx-sort-default-props # @author PI:NAME:<NAME>END_PI ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- rule = require '../../rules/jsx-sort-default-props' {RuleTester} = require 'eslint' path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ERROR_MESSAGE = 'Default prop types declarations should be sorted alphabetically' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'jsx-sort-default-props', rule, valid: [ code: [ 'First = createReactClass({' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes:' ' A: PropTypes.any' ' Z: PropTypes.string' ' a: PropTypes.any' ' z: PropTypes.string' ' getDefaultProps: ->' ' A: "A"' ' Z: "Z"' ' a: "a"' ' z: "z"' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes: {' ' a: PropTypes.any,' ' A: PropTypes.any,' ' z: PropTypes.string,' ' Z: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' a: "a",' ' A: "A",' ' z: "z",' ' Z: "Z"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' options: [ignoreCase: yes] , code: [ 'First = createReactClass({' ' propTypes: {' ' a: PropTypes.any,' ' z: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' a: "a",' ' z: "z"' ' }' ' render: ->' ' return <div />' '})' 'Second = createReactClass({' ' propTypes: {' ' AA: PropTypes.any,' ' ZZ: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' AA: "AA",' ' ZZ: "ZZ"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'class First extends React.Component' ' render: ->' ' return <div />' 'First.propTypes = {' ' a: PropTypes.string,' ' z: PropTypes.string' '}' 'First.propTypes.justforcheck = PropTypes.string' 'First.defaultProps = {' ' a: a,' ' z: z' '}' 'First.defaultProps.justforcheck = "justforcheck"' ].join '\n' , code: [ 'class First extends React.Component' ' render: ->' ' return <div />' 'First.propTypes = {' ' a: PropTypes.any,' ' A: PropTypes.any,' ' z: PropTypes.string,' ' Z: PropTypes.string' '}' 'First.defaultProps = {' ' a: "a",' ' A: "A",' ' z: "z",' ' Z: "Z"' '}' ].join '\n' options: [ignoreCase: yes] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' b: "b",' ' c: "c"' ' }' ' render: ->' ' return <div />' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "aria-controls": PropTypes.string' '}' 'Hello.defaultProps = {' ' "aria-controls": "aria-controls"' '}' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] , # Invalid code, should not be validated code: [ 'class Component extends React.Component' ' propTypes: {' ' a: PropTypes.any,' ' c: PropTypes.any,' ' b: PropTypes.any' ' }' ' defaultProps: {' ' a: "a",' ' c: "c",' ' b: "b"' ' }' ' render: ->' ' return <div />' ].join '\n' , # parser: 'babel-eslint' code: [ 'Hello = createReactClass({' ' render: ->' ' { a, ...b } = obj' ' c = { ...d }' ' return <div />' '})' ].join '\n' , code: [ 'First = createReactClass({' ' propTypes: {' ' barRequired: PropTypes.func.isRequired,' ' onBar: PropTypes.func,' ' z: PropTypes.any' ' },' ' getDefaultProps: ->' ' return {' ' barRequired: "barRequired",' ' onBar: "onBar",' ' z: "z"' ' }' ' render: ->' ' return <div />' '})' ].join '\n' , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' b: PropTypes.string,' ' ...c.propTypes,' ' a: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' ...c.defaultProps,' ' a: "a"' ' }' ].join '\n' , # parser: 'babel-eslint' code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string,' ' d: PropTypes.string,' ' e: PropTypes.string,' ' f: PropTypes.string' ' }' ' @defaultProps = {' ' a: "a",' ' b: "b",' ' ...c.defaultProps,' ' e: "e",' ' f: "f",' ' ...d.defaultProps' ' }' ].join '\n' , # parser: 'babel-eslint' code: [ 'defaults = {' ' b: "b"' '}' 'types = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string' '}' 'StatelessComponentWithSpreadInPropTypes = ({ a, b, c }) ->' ' return <div>{a}{b}{c}</div>' 'StatelessComponentWithSpreadInPropTypes.propTypes = types' 'StatelessComponentWithSpreadInPropTypes.defaultProps = {' ' c: "c",' ' ...defaults,' ' a: "a"' '}' ].join '\n' , # parser: 'babel-eslint' code: [ "propTypes = require('./externalPropTypes')" "defaultProps = require('./externalDefaultProps')" 'TextFieldLabel = (props) =>' ' return <div />' 'TextFieldLabel.propTypes = propTypes' 'TextFieldLabel.defaultProps = defaultProps' ].join '\n' , code: [ 'First = (props) => <div />' 'export propTypes = {' ' a: PropTypes.any,' ' z: PropTypes.string,' '}' 'export defaultProps = {' ' a: "a",' ' z: "z",' '}' 'First.propTypes = propTypes' 'First.defaultProps = defaultProps' ].join '\n' ] invalid: [ code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' c: "c",' ' b: "b"' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 5 type: 'Property' ] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' b: PropTypes.any,' ' c: PropTypes.any' ' }' ' @defaultProps = {' ' c: "c",' ' b: "b",' ' a: "a"' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'class Component extends React.Component' ' @propTypes:' ' a: PropTypes.any' ' b: PropTypes.any' ' @defaultProps:' ' Z: "Z"' ' a: "a"' ' render: ->' ' <div />' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] errors: [ message: ERROR_MESSAGE line: 7 column: 5 type: 'Property' ] , code: [ 'class Component extends React.Component' ' @propTypes = {' ' a: PropTypes.any,' ' z: PropTypes.any' ' }' ' @defaultProps = {' ' a: "a",' ' Z: "Z",' ' }' ' render: ->' ' return <div />' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 8 column: 5 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "b": PropTypes.string' '}' 'Hello.defaultProps = {' ' "b": "b",' ' "a": "a"' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "b": PropTypes.string,' ' "c": PropTypes.string' '}' 'Hello.defaultProps = {' ' "c": "c",' ' "b": "b",' ' "a": "a"' '}' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "B": PropTypes.string,' '}' 'Hello.defaultProps = {' ' "a": "a",' ' "B": "B",' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "a": PropTypes.string,' ' "B": PropTypes.string,' '}' 'Hello.defaultProps = {' ' "B": "B",' ' "a": "a",' '}' ].join '\n' # parser: 'babel-eslint' options: [ignoreCase: yes] errors: [ message: ERROR_MESSAGE line: 10 column: 3 type: 'Property' ] , code: [ 'First = (props) => <div />' 'propTypes = {' ' z: PropTypes.string,' ' a: PropTypes.any,' '}' 'defaultProps = {' ' z: "z",' ' a: "a",' '}' 'First.propTypes = propTypes' 'First.defaultProps = defaultProps' ].join '\n' errors: [ message: ERROR_MESSAGE line: 8 column: 3 type: 'Property' ] , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' b: PropTypes.string,' ' ...c.propTypes,' ' a: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' a: "a",' ' ...c.defaultProps' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 9 column: 5 type: 'Property' ] , code: [ 'export default class ClassWithSpreadInPropTypes extends BaseClass' ' @propTypes = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string,' ' d: PropTypes.string,' ' e: PropTypes.string,' ' f: PropTypes.string' ' }' ' @defaultProps = {' ' b: "b",' ' a: "a",' ' ...c.defaultProps,' ' f: "f",' ' e: "e",' ' ...d.defaultProps' ' }' ].join '\n' # parser: 'babel-eslint' errors: 2 , code: [ 'defaults = {' ' b: "b"' '}' 'types = {' ' a: PropTypes.string,' ' b: PropTypes.string,' ' c: PropTypes.string' '}' 'StatelessComponentWithSpreadInPropTypes = ({ a, b, c }) ->' ' return <div>{a}{b}{c}</div>' 'StatelessComponentWithSpreadInPropTypes.propTypes = types' 'StatelessComponentWithSpreadInPropTypes.defaultProps = {' ' c: "c",' ' a: "a",' ' ...defaults,' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: ERROR_MESSAGE line: 14 column: 3 type: 'Property' ] ]
[ { "context": "-02-01 下午2.43.25.png\",\n \"fileKey\" : \"110d5ed584332bf5da96fe96b95f8c681dbf\",\n \"imageHeight\" : 437\n ]\n ", "end": 1598, "score": 0.9997535943984985, "start": 1562, "tag": "KEY", "value": "110d5ed584332bf5da96fe96b95f8c681dbf" } ]
talk-api2x/test/controllers/usage.coffee
ikingye/talk-os
3,084
should = require 'should' Promise = require 'bluebird' limbo = require 'limbo' app = require '../app' {prepare, cleanup, requestAsync} = app describe 'Usage#CURD', -> before prepare it 'should read a full list of usages', (done) -> options = method: 'GET' url: '/usages' qs: _sessionUserId: app.user1._id _teamId: app.team1._id requestAsync options .spread (res) -> usages = res.body usages[0].type.should.eql 'userMessage' usages[1].type.should.eql 'inteMessage' usages[2].type.should.eql 'file' usages[3].type.should.eql 'call' usages.forEach (usage) -> usage.should.have.properties 'amount', 'maxAmount', 'team', 'type', 'month' .nodeify done it 'should update the usages when do something', (done) -> # Create a message $message = Promise.resolve().then -> options = method: 'POST' url: '/messages' body: _sessionUserId: app.user1._id _roomId: app.room1._id body: 'ok' requestAsync options $file = Promise.resolve().then -> options = method: 'POST' url: '/messages' body: _sessionUserId: app.user1._id _roomId: app.room1._id attachments: [ category: 'file' data: "fileSize" : 86264, "fileCategory" : "image", "fileType" : "png", "imageWidth" : 1041, "fileName" : "屏幕快照 2016-02-01 下午2.43.25.png", "fileKey" : "110d5ed584332bf5da96fe96b95f8c681dbf", "imageHeight" : 437 ] requestAsync options $usages = Promise.all [$message, $file] .delay(100).then -> options = method: 'GET' url: '/usages' qs: _sessionUserId: app.user1._id _teamId: app.team1._id requestAsync(options).spread (res) -> res.body .then (usages) -> usages[0].amount.should.eql 2 usages[1].amount.should.eql 0 usages[2].amount.should.eql 86264 .nodeify done after cleanup
43542
should = require 'should' Promise = require 'bluebird' limbo = require 'limbo' app = require '../app' {prepare, cleanup, requestAsync} = app describe 'Usage#CURD', -> before prepare it 'should read a full list of usages', (done) -> options = method: 'GET' url: '/usages' qs: _sessionUserId: app.user1._id _teamId: app.team1._id requestAsync options .spread (res) -> usages = res.body usages[0].type.should.eql 'userMessage' usages[1].type.should.eql 'inteMessage' usages[2].type.should.eql 'file' usages[3].type.should.eql 'call' usages.forEach (usage) -> usage.should.have.properties 'amount', 'maxAmount', 'team', 'type', 'month' .nodeify done it 'should update the usages when do something', (done) -> # Create a message $message = Promise.resolve().then -> options = method: 'POST' url: '/messages' body: _sessionUserId: app.user1._id _roomId: app.room1._id body: 'ok' requestAsync options $file = Promise.resolve().then -> options = method: 'POST' url: '/messages' body: _sessionUserId: app.user1._id _roomId: app.room1._id attachments: [ category: 'file' data: "fileSize" : 86264, "fileCategory" : "image", "fileType" : "png", "imageWidth" : 1041, "fileName" : "屏幕快照 2016-02-01 下午2.43.25.png", "fileKey" : "<KEY>", "imageHeight" : 437 ] requestAsync options $usages = Promise.all [$message, $file] .delay(100).then -> options = method: 'GET' url: '/usages' qs: _sessionUserId: app.user1._id _teamId: app.team1._id requestAsync(options).spread (res) -> res.body .then (usages) -> usages[0].amount.should.eql 2 usages[1].amount.should.eql 0 usages[2].amount.should.eql 86264 .nodeify done after cleanup
true
should = require 'should' Promise = require 'bluebird' limbo = require 'limbo' app = require '../app' {prepare, cleanup, requestAsync} = app describe 'Usage#CURD', -> before prepare it 'should read a full list of usages', (done) -> options = method: 'GET' url: '/usages' qs: _sessionUserId: app.user1._id _teamId: app.team1._id requestAsync options .spread (res) -> usages = res.body usages[0].type.should.eql 'userMessage' usages[1].type.should.eql 'inteMessage' usages[2].type.should.eql 'file' usages[3].type.should.eql 'call' usages.forEach (usage) -> usage.should.have.properties 'amount', 'maxAmount', 'team', 'type', 'month' .nodeify done it 'should update the usages when do something', (done) -> # Create a message $message = Promise.resolve().then -> options = method: 'POST' url: '/messages' body: _sessionUserId: app.user1._id _roomId: app.room1._id body: 'ok' requestAsync options $file = Promise.resolve().then -> options = method: 'POST' url: '/messages' body: _sessionUserId: app.user1._id _roomId: app.room1._id attachments: [ category: 'file' data: "fileSize" : 86264, "fileCategory" : "image", "fileType" : "png", "imageWidth" : 1041, "fileName" : "屏幕快照 2016-02-01 下午2.43.25.png", "fileKey" : "PI:KEY:<KEY>END_PI", "imageHeight" : 437 ] requestAsync options $usages = Promise.all [$message, $file] .delay(100).then -> options = method: 'GET' url: '/usages' qs: _sessionUserId: app.user1._id _teamId: app.team1._id requestAsync(options).spread (res) -> res.body .then (usages) -> usages[0].amount.should.eql 2 usages[1].amount.should.eql 0 usages[2].amount.should.eql 86264 .nodeify done after cleanup
[ { "context": "###\nAuthor: Paul B. Hartzog\nYear: 2015\nWWW: http:paulbhartzog.org\nGithub: htt", "end": 27, "score": 0.9998905062675476, "start": 12, "tag": "NAME", "value": "Paul B. Hartzog" }, { "context": ": http:paulbhartzog.org\nGithub: http://github.com/paulbhartzog\n\nRequirements:\nÜbersicht: http://github.com/felix", "end": 104, "score": 0.9842506051063538, "start": 92, "tag": "USERNAME", "value": "paulbhartzog" } ]
uebersicht/rsc/ubersicht-video-widget.widget/ubersicht-video-widget.coffee
HeminWon/.dotfiles
4
### Author: Paul B. Hartzog Year: 2015 WWW: http:paulbhartzog.org Github: http://github.com/paulbhartzog Requirements: Übersicht: http://github.com/felixhageloh/uebersicht/ INSTRUCTIONS - This widget uses the HTML5 "video" tag to place a video into Übersicht - This widget has been tested with .mp4 files. EXAMPLE: <video width="360" loop controls autoplay> <source src="movie.widget/SampleVideo_360x240_1mb.mp4" type="video/mp4"> Your browser does not support the video tag. </video> - For html5 video tutorials see: http://www.w3schools.com/html/html5_video.asp - thanks to Übersicht (http://github.com/felixhageloh/uebersicht/) - thanks to http://www.sample-videos.com/ for the sample video ### # refreshFrequency default is 1000 ms (1 s), so we set it to false on purpose # Reference: https://github.com/felixhageloh/uebersicht/blob/master/README.md refreshFrequency: false render: ->""" <video width="360" loop controls> <source src="video.widget/SampleVideo_360x240_1mb.mp4" type="video/mp4"> Your browser does not support the video tag. </video> """ style: """ top: 10px left: 10px border: 1px solid #fff z-index: 1000 /* kluge to erase space at bottom of video inside container */ video margin-bottom: -4px """
180163
### Author: <NAME> Year: 2015 WWW: http:paulbhartzog.org Github: http://github.com/paulbhartzog Requirements: Übersicht: http://github.com/felixhageloh/uebersicht/ INSTRUCTIONS - This widget uses the HTML5 "video" tag to place a video into Übersicht - This widget has been tested with .mp4 files. EXAMPLE: <video width="360" loop controls autoplay> <source src="movie.widget/SampleVideo_360x240_1mb.mp4" type="video/mp4"> Your browser does not support the video tag. </video> - For html5 video tutorials see: http://www.w3schools.com/html/html5_video.asp - thanks to Übersicht (http://github.com/felixhageloh/uebersicht/) - thanks to http://www.sample-videos.com/ for the sample video ### # refreshFrequency default is 1000 ms (1 s), so we set it to false on purpose # Reference: https://github.com/felixhageloh/uebersicht/blob/master/README.md refreshFrequency: false render: ->""" <video width="360" loop controls> <source src="video.widget/SampleVideo_360x240_1mb.mp4" type="video/mp4"> Your browser does not support the video tag. </video> """ style: """ top: 10px left: 10px border: 1px solid #fff z-index: 1000 /* kluge to erase space at bottom of video inside container */ video margin-bottom: -4px """
true
### Author: PI:NAME:<NAME>END_PI Year: 2015 WWW: http:paulbhartzog.org Github: http://github.com/paulbhartzog Requirements: Übersicht: http://github.com/felixhageloh/uebersicht/ INSTRUCTIONS - This widget uses the HTML5 "video" tag to place a video into Übersicht - This widget has been tested with .mp4 files. EXAMPLE: <video width="360" loop controls autoplay> <source src="movie.widget/SampleVideo_360x240_1mb.mp4" type="video/mp4"> Your browser does not support the video tag. </video> - For html5 video tutorials see: http://www.w3schools.com/html/html5_video.asp - thanks to Übersicht (http://github.com/felixhageloh/uebersicht/) - thanks to http://www.sample-videos.com/ for the sample video ### # refreshFrequency default is 1000 ms (1 s), so we set it to false on purpose # Reference: https://github.com/felixhageloh/uebersicht/blob/master/README.md refreshFrequency: false render: ->""" <video width="360" loop controls> <source src="video.widget/SampleVideo_360x240_1mb.mp4" type="video/mp4"> Your browser does not support the video tag. </video> """ style: """ top: 10px left: 10px border: 1px solid #fff z-index: 1000 /* kluge to erase space at bottom of video inside container */ video margin-bottom: -4px """
[ { "context": "ule')\n data = {\n 'name': @ruleName\n 'type': @ruleType\n ", "end": 2283, "score": 0.9653797745704651, "start": 2283, "tag": "NAME", "value": "" }, { "context": "e')\n data = {\n 'name': @ruleName\n 'type': @ruleType\n ", "end": 2289, "score": 0.8377103805541992, "start": 2285, "tag": "NAME", "value": "rule" }, { "context": " data = {\n 'name': @ruleName\n 'type': @ruleType\n ", "end": 2293, "score": 0.5366363525390625, "start": 2289, "tag": "NAME", "value": "Name" } ]
nosferatu/static/js/directives/rule-selector.coffee
DanCardin/nosferatu
0
angular.module('nosferatuApp').directive('ruleSelector', () -> controller = ['$scope', '$log', '$http', '$timeout', ($scope, $log, $http, $timeout) -> self = this @enableAddRuleBtn = () -> result = ( (not @ruleName) or (not @daysOfWeekSelected.length) or (if @ruleType is 'Schedule' then (if (@scheduleTimeType is 'auto') then (not @scheduleZipCode) else false) else false) or (if @ruleType is 'Event' then (not @foreignNode) else false) ) return result @ruleTypes = ['Schedule', 'Event'] @daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] am_pm = (i) -> if i < 12 return 'AM' else return 'PM' @hoursInDay = {} for i in [0..24] str = "#{((i + 11) % 12) + 1} #{am_pm(i)}" @hoursInDay[str] = i @hoursInDayArr = Object.keys(@hoursInDay) @minutesInDay = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] @ruleType = @ruleTypes[0] @daysOfWeekSelected = [] @daysOfWeekToggle = (day) -> id = @daysOfWeekSelected.indexOf(day) if id > -1 @daysOfWeekSelected.splice(id, 1) else @daysOfWeekSelected.push(day) @scheduleTimeType = 'manual' @scheduleTimeOfDayType = 'sunrise' @hourInDay = @hoursInDayArr[0] @minuteInDay = @minutesInDay[0] @ruleTurnOn = 'unchanged' @ruleMotionTurnOn = 'unchanged' @foreignNode = @foreignNodes[0] @foreignNodeStatus = 'on' @eventNode = (node) -> if node? $log.log(" - node from node name", node) return node.id return null @addRule = () -> $log.log('Adding the rule') data = { 'name': @ruleName 'type': @ruleType 'turn_on': @ruleTurnOn 'turn_motion_on': @ruleMotionTurnOn 'days': @daysOfWeekSelected 'sched_type': @scheduleTimeType # manual 'hour': @hoursInDay[@hourInDay] 'minute': @minuteInDay # auto 'zip_code': @scheduleZipCode or '' 'time_of_day': @scheduleTimeOfDayType 'event_node': self.eventNode(self.foreignNode) 'event_node_status': self.foreignNodeStatus or null } $http.post("/nodes/#{@node.id}/rules", data).then((results) -> $log.log(" - success: ", results.data) self.addedRules.push(results.data) ).catch(errFunc) return ] return { bindToController: { foreignNodes: '=' node: '=' addedRules: '=' ruleName: '=' ruleTypes: '=' ruleType: '=' scheduleTimeType: '=' scheduleZipCode: '=' scheduleTimeOfDayType: '=' scheduleTimeTypeChange: '&' } controller: controller controllerAs: 'rs' restrict: 'E' scope: {} templateUrl: './static/templates/rule-selector.html' } )
163539
angular.module('nosferatuApp').directive('ruleSelector', () -> controller = ['$scope', '$log', '$http', '$timeout', ($scope, $log, $http, $timeout) -> self = this @enableAddRuleBtn = () -> result = ( (not @ruleName) or (not @daysOfWeekSelected.length) or (if @ruleType is 'Schedule' then (if (@scheduleTimeType is 'auto') then (not @scheduleZipCode) else false) else false) or (if @ruleType is 'Event' then (not @foreignNode) else false) ) return result @ruleTypes = ['Schedule', 'Event'] @daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] am_pm = (i) -> if i < 12 return 'AM' else return 'PM' @hoursInDay = {} for i in [0..24] str = "#{((i + 11) % 12) + 1} #{am_pm(i)}" @hoursInDay[str] = i @hoursInDayArr = Object.keys(@hoursInDay) @minutesInDay = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] @ruleType = @ruleTypes[0] @daysOfWeekSelected = [] @daysOfWeekToggle = (day) -> id = @daysOfWeekSelected.indexOf(day) if id > -1 @daysOfWeekSelected.splice(id, 1) else @daysOfWeekSelected.push(day) @scheduleTimeType = 'manual' @scheduleTimeOfDayType = 'sunrise' @hourInDay = @hoursInDayArr[0] @minuteInDay = @minutesInDay[0] @ruleTurnOn = 'unchanged' @ruleMotionTurnOn = 'unchanged' @foreignNode = @foreignNodes[0] @foreignNodeStatus = 'on' @eventNode = (node) -> if node? $log.log(" - node from node name", node) return node.id return null @addRule = () -> $log.log('Adding the rule') data = { 'name':<NAME> @<NAME> <NAME> 'type': @ruleType 'turn_on': @ruleTurnOn 'turn_motion_on': @ruleMotionTurnOn 'days': @daysOfWeekSelected 'sched_type': @scheduleTimeType # manual 'hour': @hoursInDay[@hourInDay] 'minute': @minuteInDay # auto 'zip_code': @scheduleZipCode or '' 'time_of_day': @scheduleTimeOfDayType 'event_node': self.eventNode(self.foreignNode) 'event_node_status': self.foreignNodeStatus or null } $http.post("/nodes/#{@node.id}/rules", data).then((results) -> $log.log(" - success: ", results.data) self.addedRules.push(results.data) ).catch(errFunc) return ] return { bindToController: { foreignNodes: '=' node: '=' addedRules: '=' ruleName: '=' ruleTypes: '=' ruleType: '=' scheduleTimeType: '=' scheduleZipCode: '=' scheduleTimeOfDayType: '=' scheduleTimeTypeChange: '&' } controller: controller controllerAs: 'rs' restrict: 'E' scope: {} templateUrl: './static/templates/rule-selector.html' } )
true
angular.module('nosferatuApp').directive('ruleSelector', () -> controller = ['$scope', '$log', '$http', '$timeout', ($scope, $log, $http, $timeout) -> self = this @enableAddRuleBtn = () -> result = ( (not @ruleName) or (not @daysOfWeekSelected.length) or (if @ruleType is 'Schedule' then (if (@scheduleTimeType is 'auto') then (not @scheduleZipCode) else false) else false) or (if @ruleType is 'Event' then (not @foreignNode) else false) ) return result @ruleTypes = ['Schedule', 'Event'] @daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] am_pm = (i) -> if i < 12 return 'AM' else return 'PM' @hoursInDay = {} for i in [0..24] str = "#{((i + 11) % 12) + 1} #{am_pm(i)}" @hoursInDay[str] = i @hoursInDayArr = Object.keys(@hoursInDay) @minutesInDay = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] @ruleType = @ruleTypes[0] @daysOfWeekSelected = [] @daysOfWeekToggle = (day) -> id = @daysOfWeekSelected.indexOf(day) if id > -1 @daysOfWeekSelected.splice(id, 1) else @daysOfWeekSelected.push(day) @scheduleTimeType = 'manual' @scheduleTimeOfDayType = 'sunrise' @hourInDay = @hoursInDayArr[0] @minuteInDay = @minutesInDay[0] @ruleTurnOn = 'unchanged' @ruleMotionTurnOn = 'unchanged' @foreignNode = @foreignNodes[0] @foreignNodeStatus = 'on' @eventNode = (node) -> if node? $log.log(" - node from node name", node) return node.id return null @addRule = () -> $log.log('Adding the rule') data = { 'name':PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI 'type': @ruleType 'turn_on': @ruleTurnOn 'turn_motion_on': @ruleMotionTurnOn 'days': @daysOfWeekSelected 'sched_type': @scheduleTimeType # manual 'hour': @hoursInDay[@hourInDay] 'minute': @minuteInDay # auto 'zip_code': @scheduleZipCode or '' 'time_of_day': @scheduleTimeOfDayType 'event_node': self.eventNode(self.foreignNode) 'event_node_status': self.foreignNodeStatus or null } $http.post("/nodes/#{@node.id}/rules", data).then((results) -> $log.log(" - success: ", results.data) self.addedRules.push(results.data) ).catch(errFunc) return ] return { bindToController: { foreignNodes: '=' node: '=' addedRules: '=' ruleName: '=' ruleTypes: '=' ruleType: '=' scheduleTimeType: '=' scheduleZipCode: '=' scheduleTimeOfDayType: '=' scheduleTimeTypeChange: '&' } controller: controller controllerAs: 'rs' restrict: 'E' scope: {} templateUrl: './static/templates/rule-selector.html' } )
[ { "context": "Platforms\"\nlocation: \"Leeds\"\nphase: \"alpha\"\nsro: \"Neil Couling\"\nservice_man: \"Tim Carter\"\nfacing: \"internal\"\npha", "end": 229, "score": 0.9998438954353333, "start": 217, "tag": "NAME", "value": "Neil Couling" }, { "context": "\nphase: \"alpha\"\nsro: \"Neil Couling\"\nservice_man: \"Tim Carter\"\nfacing: \"internal\"\nphase_history:\n discovery: [", "end": 255, "score": 0.9998602271080017, "start": 245, "tag": "NAME", "value": "Tim Carter" } ]
app/data/projects/appointment-booking.cson
tsmorgan/dwp-ux-work
0
id: 31 name: "Appointment Booking" description: "Providing the ability for agents to book appointments for users (including self-service appointment booking)" theme: "Platforms" location: "Leeds" phase: "alpha" sro: "Neil Couling" service_man: "Tim Carter" facing: "internal" phase_history: discovery: [ { label: "Completed" date: "February 2016" } ] alpha: [ { label: "Started" date: "March 2016" } ] priority: "Top"
98888
id: 31 name: "Appointment Booking" description: "Providing the ability for agents to book appointments for users (including self-service appointment booking)" theme: "Platforms" location: "Leeds" phase: "alpha" sro: "<NAME>" service_man: "<NAME>" facing: "internal" phase_history: discovery: [ { label: "Completed" date: "February 2016" } ] alpha: [ { label: "Started" date: "March 2016" } ] priority: "Top"
true
id: 31 name: "Appointment Booking" description: "Providing the ability for agents to book appointments for users (including self-service appointment booking)" theme: "Platforms" location: "Leeds" phase: "alpha" sro: "PI:NAME:<NAME>END_PI" service_man: "PI:NAME:<NAME>END_PI" facing: "internal" phase_history: discovery: [ { label: "Completed" date: "February 2016" } ] alpha: [ { label: "Started" date: "March 2016" } ] priority: "Top"
[ { "context": "##\n Translated from JavaScript to Coffeescript by Anton Warnhag, 2015.\n###\n\n'use strict'\n\n# Modifications by Anto", "end": 717, "score": 0.9998910427093506, "start": 704, "tag": "NAME", "value": "Anton Warnhag" }, { "context": "rnhag, 2015.\n###\n\n'use strict'\n\n# Modifications by Anton Warnhag.\n\n# \nrequirejs ['articles'], (articles) -> \n art", "end": 776, "score": 0.9998841881752014, "start": 763, "tag": "NAME", "value": "Anton Warnhag" } ]
app/scripts/main.coffee
awarn/popup-crypt
0
### * * Web Starter Kit * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * ### ### Translated from JavaScript to Coffeescript by Anton Warnhag, 2015. ### 'use strict' # Modifications by Anton Warnhag. # requirejs ['articles'], (articles) -> articles.someMethod('bla2') articles.openArticle() # End of modifications. # Original contents (translated to Coffeescript). querySelector = document.querySelector.bind(document); navdrawerContainer = querySelector '.navdrawer-container' body = document.body appbarElement = querySelector '.app-bar' menuBtn = querySelector '.menu' main = querySelector 'main' closeMenu = -> body.classList.remove 'open' appbarElement.classList.remove 'open' navdrawerContainer.classList.remove 'open' toggleMenu = -> body.classList.toggle 'open' appbarElement.classList.toggle 'open' navdrawerContainer.classList.toggle 'open' navdrawerContainer.classList.add 'opened' main.addEventListener 'click', closeMenu menuBtn.addEventListener 'click', toggleMenu navdrawerContainer.addEventListener 'click', (event) -> if (event.target.nodeName == 'A' || event.target.nodeName == 'LI') closeMenu # End of original contents
62350
### * * Web Starter Kit * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * ### ### Translated from JavaScript to Coffeescript by <NAME>, 2015. ### 'use strict' # Modifications by <NAME>. # requirejs ['articles'], (articles) -> articles.someMethod('bla2') articles.openArticle() # End of modifications. # Original contents (translated to Coffeescript). querySelector = document.querySelector.bind(document); navdrawerContainer = querySelector '.navdrawer-container' body = document.body appbarElement = querySelector '.app-bar' menuBtn = querySelector '.menu' main = querySelector 'main' closeMenu = -> body.classList.remove 'open' appbarElement.classList.remove 'open' navdrawerContainer.classList.remove 'open' toggleMenu = -> body.classList.toggle 'open' appbarElement.classList.toggle 'open' navdrawerContainer.classList.toggle 'open' navdrawerContainer.classList.add 'opened' main.addEventListener 'click', closeMenu menuBtn.addEventListener 'click', toggleMenu navdrawerContainer.addEventListener 'click', (event) -> if (event.target.nodeName == 'A' || event.target.nodeName == 'LI') closeMenu # End of original contents
true
### * * Web Starter Kit * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * ### ### Translated from JavaScript to Coffeescript by PI:NAME:<NAME>END_PI, 2015. ### 'use strict' # Modifications by PI:NAME:<NAME>END_PI. # requirejs ['articles'], (articles) -> articles.someMethod('bla2') articles.openArticle() # End of modifications. # Original contents (translated to Coffeescript). querySelector = document.querySelector.bind(document); navdrawerContainer = querySelector '.navdrawer-container' body = document.body appbarElement = querySelector '.app-bar' menuBtn = querySelector '.menu' main = querySelector 'main' closeMenu = -> body.classList.remove 'open' appbarElement.classList.remove 'open' navdrawerContainer.classList.remove 'open' toggleMenu = -> body.classList.toggle 'open' appbarElement.classList.toggle 'open' navdrawerContainer.classList.toggle 'open' navdrawerContainer.classList.add 'opened' main.addEventListener 'click', closeMenu menuBtn.addEventListener 'click', toggleMenu navdrawerContainer.addEventListener 'click', (event) -> if (event.target.nodeName == 'A' || event.target.nodeName == 'LI') closeMenu # End of original contents
[ { "context": "#\n# Copyright (c) 2012 Konstantin Bender.\n#\n# Permission is hereby granted, free of charge", "end": 40, "score": 0.9998602271080017, "start": 23, "tag": "NAME", "value": "Konstantin Bender" }, { "context": " @setter_name_for = (key) ->\n example_key = \"full_name\"\n is_camel_cased = example_key[4] isnt '_'\n ", "end": 7908, "score": 0.9950903058052063, "start": 7899, "tag": "KEY", "value": "full_name" } ]
source/core.coffee
konstantinbe/milk
0
# # Copyright (c) 2012 Konstantin Bender. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. global = exports ? this # ------------------------------------------------------------------------------ class Module option = (object, key, fallback) -> if object? and Object::hasOwnProperty.call object, key then object[key] else fallback @walk: (path, options = {}) -> create_if_not_exists = option options, 'create_if_not_exists', no secret = option options, 'secret', no object = global for section in path.split "." parent = object object = object[section] object ?= object['$' + section] if secret object ?= parent[section] = new Module() if create_if_not_exists @error "Can't walk module path '#{path}', #{section} doesn't exist" unless object? object export: (object, options = {}) -> as = option options, 'as', null secret = option options, 'secret', no name = as ? object['name'] @error "Can't export #{object}, couldn't determine name" unless name? @error "Can't export #{object} as '#{name}', name already taken" if @[name]? name = '$' + name if secret @[name] = object # ------------------------------------------------------------------------------ Object::module = (path, block) -> module = Module.walk path, create_if_not_exists: yes block?.call module module Object::import = (path, options = {}) -> secret = @option options, 'secret', no Module.walk path, options Object::includes = (mixins...) -> for mixin in mixins @[key] = value for own key, value of mixin @prototype[key] = value for own key, value of mixin.prototype # ------------------------------------------------------------------------------ @module 'Milk', -> class Keywords native_is_array = Array.isArray native_has_own_property = Object::hasOwnProperty native_get_prototype_of = Object.getPrototypeOf native_keys = Object.keys native_to_string = Object::toString option: (object, key, fallback) -> if object? and native_has_own_property.call object, key then object[key] else fallback class_of: (object) -> object?.constructor ? null class_name_of: (object) -> object?.constructor?.name ? null keys_of: (object) -> native_keys object values_of: (object) -> (object[key] for key in native_keys object) prototype_of: (object) -> native_get_prototype_of object copy_of: (object) -> return undefined if object is undefined return null if object is null if @is_dictionary object copy = {} for own key, value of object copy[key] = value return copy @error "Object doesn't support copying" unless @responds_to object, 'copy' native_get_prototype_of(object)['copy'].call object frozen_copy_of: (object) -> return object if @is_frozen object return @freeze @copy_of object description_of: (object) -> return "undefined" if object is undefined return "null" if object is null return "{" + @keys_of(object).join(", ") + "}" if @is_dictionary object return object.to_string() if @responds_to object, 'to_string' native_to_string.call object are_equal: (left, right) -> return yes if left is undefined and right is undefined return no if left is undefined or right is undefined return yes if left is null and right is null return no if left is null or right is null left_is_dictionary = @is_dictionary left right_is_dictionary = @is_dictionary right return no if left_is_dictionary and not right_is_dictionary return no if not left_is_dictionary and right_is_dictionary if left_is_dictionary and right_is_dictionary for key in @keys_of(left).concat @keys_of(right) return no unless @has_own(left, key) and @has_own(right, key) return no unless @are_equal @own(left, key), @own(right, key) return yes return left.equals right if @responds_to left, 'equals' return right.equals left if @responds_to right, 'equals' return left.compare_to(right) is 0 if @responds_to left, 'compare_to' return right.compare_to(left) is 0 if @responds_to right, 'compare_to' @error "Can't check equality, neither left nor right implement equals() or compare_to()" compare: (left, right) -> @error "Can't compare objects, left is undefined" if left is undefined @error "Can't compare objects, right is undefined" if right is undefined @error "Can't compare objects, left is null" if left is null @error "Can't compare objects, right is null" if right is null @error "Can't compare objects, left is a dictionary" if @is_dictionary left @error "Can't compare objects, right is a dictionary" if @is_dictionary right @error "Can't compare, objects don't support comparing" unless @responds_to left, 'compare_to' left.compare_to right has_own: (object, key) -> [object, key] = [@, object] if arguments.length < 2 native_has_own_property.call object, key own: (object, key) -> [object, key] = [@, object] if arguments.length < 2 if native_has_own_property.call object, key then object[key] else undefined mix: (objects...) -> mixed = {} for object in objects mixed[key] = value for own key, value of object when not @has_own mixed, key mixed merge: (objects...) -> merged = {} for object in objects merged[key] = value for own key, value of object merged info: (message) -> console.log "[INFO] " + message warning: (message) -> console.log "[WARNING] " + message error: (message) -> stackTrace = "(can't print stack trace, function printStackTrace() not found)" stackTrace = "\n\n" + printStackTrace()[3..].join "\n" if printStackTrace? throw "[ERROR] " + message + stackTrace debug: (message) -> console.log "[DEBUG] " + message # ---------------------------------------------------------------------------- class FreezingAndSealing native_seal = Object.seal native_freeze = Object.freeze native_is_sealed = Object.isSealed native_is_frozen = Object.isFrozen is_frozen: (object) -> object = @ if arguments.length < 1 native_is_frozen object is_sealed: (object) -> object = @ if arguments.length < 1 native_is_sealed object freeze: (object) -> object = @ if arguments.length < 1 native_freeze? object object seal: (object) -> object = @ if arguments.length < 1 native_seal? object object # ---------------------------------------------------------------------------- class KeyValueCoding @getter_name_for = (key) -> key @setter_name_for = (key) -> example_key = "full_name" is_camel_cased = example_key[4] isnt '_' return "set_" + key unless is_camel_cased "set" + key[0].uppercased() + key.slice 1 value_for: (key, options = {}) -> direct = @option options, 'direct', no unless direct getter_name = Object.getter_name_for key getter_function = @[getter_name] return getter_function.call @ if @is_function getter_function instance_variable_name = '@' + key return @[instance_variable_name] if @[instance_variable_name] isnt undefined @[key] set_value_for: (value, key, options = {}) -> direct = @option options, 'direct', no unless direct setter_name = Object.setter_name_for key setter_function = @[setter_name] return setter_function.call(@, value, options = {}) if @is_function setter_function instance_variable_name = '@' + key if @[instance_variable_name] isnt undefined @[instance_variable_name] = value return @ if @[key] isnt undefined @[key] = value return @ @error "Can't set value for key '" + key + "', property unknown" @ # ---------------------------------------------------------------------------- class TypeChecking native_is_array = Array.isArray is_null: (object) -> object = @ if arguments.length < 1 object is null is_class: (object) -> object = @ if arguments.length < 1 Boolean (typeof object) is 'function' and object.name.match /^[A-Z]/ is_function: (object) -> object = @ if arguments.length < 1 object?.constructor? and object.call? and object.apply? is_boolean: (object) -> object = @ if arguments.length < 1 object is yes or object is no or Object::toString.call(object) is '[object Boolean]' is_number: (object) -> object = @ if arguments.length < 1 object is 0 or (object?.toExponential? and object.toFixed?) is_date: (object) -> object = @ if arguments.length < 1 object? and object.getTimezoneOffset? and object.setUTCFullYear? is_string: (object) -> object = @ if arguments.length < 1 object is "" or (object?.charCodeAt? and object.substr?) is_reg_exp: (object) -> object = @ if arguments.length < 1 object? and object.test? and object.exec? and (object.ignoreCase? or object.ignoreCase == no) is_array: (object) -> object = @ if arguments.length < 1 native_is_array object is_dictionary: (object) -> object = @ if arguments.length < 1 object?.constructor?.name is 'Object' is_kind_of: (object, klass) -> [object, klass] = [@, object] if arguments.length < 2 object instanceof klass is_instance_of: (object, klass) -> [object, klass] = [@, object] if arguments.length < 2 @class_of(object) is klass # ---------------------------------------------------------------------------- class Comparing is_comparable: -> no is_less_than: (value, options = {}) -> @compare_to(value, options) is -1 is_less_than_or_equals: (value, options = {}) -> result = @compare_to value, options result is 0 or result is -1 is_greater_than: (value, options = {}) -> @compare_to(value, options) is 1 is_greater_than_or_equals: (value, options = {}) -> result = @compare_to value, options result is 0 or result is 1 is_between: (bounds, options = {}) -> [lower, upper] = bounds excluding_bounds = options['excluding_bounds'] or no excluding_lower = options['excluding_lower'] or no excluding_upper = options['excluding_upper'] or no include_lower = not (excluding_bounds or excluding_lower) include_upper = not (excluding_bounds or excluding_upper) compared_to_lower = @compare_to lower, options compared_to_upper = @compare_to upper, options meets_lower = compared_to_lower is +1 or include_lower and compared_to_lower is 0 meets_upper = compared_to_upper is -1 or include_upper and compared_to_upper is 0 meets_lower and meets_upper # ---------------------------------------------------------------------------- class Messaging responds_to: (object, command) -> [object, command] = [@, object] if arguments.length < 2 command? and object[command]? and @is_function object[command] # ---------------------------------------------------------------------------- Object.includes Keywords Object.includes FreezingAndSealing Object.includes KeyValueCoding Object.includes TypeChecking Object.includes Comparing Object.includes Messaging @export Module
76809
# # Copyright (c) 2012 <NAME>. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. global = exports ? this # ------------------------------------------------------------------------------ class Module option = (object, key, fallback) -> if object? and Object::hasOwnProperty.call object, key then object[key] else fallback @walk: (path, options = {}) -> create_if_not_exists = option options, 'create_if_not_exists', no secret = option options, 'secret', no object = global for section in path.split "." parent = object object = object[section] object ?= object['$' + section] if secret object ?= parent[section] = new Module() if create_if_not_exists @error "Can't walk module path '#{path}', #{section} doesn't exist" unless object? object export: (object, options = {}) -> as = option options, 'as', null secret = option options, 'secret', no name = as ? object['name'] @error "Can't export #{object}, couldn't determine name" unless name? @error "Can't export #{object} as '#{name}', name already taken" if @[name]? name = '$' + name if secret @[name] = object # ------------------------------------------------------------------------------ Object::module = (path, block) -> module = Module.walk path, create_if_not_exists: yes block?.call module module Object::import = (path, options = {}) -> secret = @option options, 'secret', no Module.walk path, options Object::includes = (mixins...) -> for mixin in mixins @[key] = value for own key, value of mixin @prototype[key] = value for own key, value of mixin.prototype # ------------------------------------------------------------------------------ @module 'Milk', -> class Keywords native_is_array = Array.isArray native_has_own_property = Object::hasOwnProperty native_get_prototype_of = Object.getPrototypeOf native_keys = Object.keys native_to_string = Object::toString option: (object, key, fallback) -> if object? and native_has_own_property.call object, key then object[key] else fallback class_of: (object) -> object?.constructor ? null class_name_of: (object) -> object?.constructor?.name ? null keys_of: (object) -> native_keys object values_of: (object) -> (object[key] for key in native_keys object) prototype_of: (object) -> native_get_prototype_of object copy_of: (object) -> return undefined if object is undefined return null if object is null if @is_dictionary object copy = {} for own key, value of object copy[key] = value return copy @error "Object doesn't support copying" unless @responds_to object, 'copy' native_get_prototype_of(object)['copy'].call object frozen_copy_of: (object) -> return object if @is_frozen object return @freeze @copy_of object description_of: (object) -> return "undefined" if object is undefined return "null" if object is null return "{" + @keys_of(object).join(", ") + "}" if @is_dictionary object return object.to_string() if @responds_to object, 'to_string' native_to_string.call object are_equal: (left, right) -> return yes if left is undefined and right is undefined return no if left is undefined or right is undefined return yes if left is null and right is null return no if left is null or right is null left_is_dictionary = @is_dictionary left right_is_dictionary = @is_dictionary right return no if left_is_dictionary and not right_is_dictionary return no if not left_is_dictionary and right_is_dictionary if left_is_dictionary and right_is_dictionary for key in @keys_of(left).concat @keys_of(right) return no unless @has_own(left, key) and @has_own(right, key) return no unless @are_equal @own(left, key), @own(right, key) return yes return left.equals right if @responds_to left, 'equals' return right.equals left if @responds_to right, 'equals' return left.compare_to(right) is 0 if @responds_to left, 'compare_to' return right.compare_to(left) is 0 if @responds_to right, 'compare_to' @error "Can't check equality, neither left nor right implement equals() or compare_to()" compare: (left, right) -> @error "Can't compare objects, left is undefined" if left is undefined @error "Can't compare objects, right is undefined" if right is undefined @error "Can't compare objects, left is null" if left is null @error "Can't compare objects, right is null" if right is null @error "Can't compare objects, left is a dictionary" if @is_dictionary left @error "Can't compare objects, right is a dictionary" if @is_dictionary right @error "Can't compare, objects don't support comparing" unless @responds_to left, 'compare_to' left.compare_to right has_own: (object, key) -> [object, key] = [@, object] if arguments.length < 2 native_has_own_property.call object, key own: (object, key) -> [object, key] = [@, object] if arguments.length < 2 if native_has_own_property.call object, key then object[key] else undefined mix: (objects...) -> mixed = {} for object in objects mixed[key] = value for own key, value of object when not @has_own mixed, key mixed merge: (objects...) -> merged = {} for object in objects merged[key] = value for own key, value of object merged info: (message) -> console.log "[INFO] " + message warning: (message) -> console.log "[WARNING] " + message error: (message) -> stackTrace = "(can't print stack trace, function printStackTrace() not found)" stackTrace = "\n\n" + printStackTrace()[3..].join "\n" if printStackTrace? throw "[ERROR] " + message + stackTrace debug: (message) -> console.log "[DEBUG] " + message # ---------------------------------------------------------------------------- class FreezingAndSealing native_seal = Object.seal native_freeze = Object.freeze native_is_sealed = Object.isSealed native_is_frozen = Object.isFrozen is_frozen: (object) -> object = @ if arguments.length < 1 native_is_frozen object is_sealed: (object) -> object = @ if arguments.length < 1 native_is_sealed object freeze: (object) -> object = @ if arguments.length < 1 native_freeze? object object seal: (object) -> object = @ if arguments.length < 1 native_seal? object object # ---------------------------------------------------------------------------- class KeyValueCoding @getter_name_for = (key) -> key @setter_name_for = (key) -> example_key = "<KEY>" is_camel_cased = example_key[4] isnt '_' return "set_" + key unless is_camel_cased "set" + key[0].uppercased() + key.slice 1 value_for: (key, options = {}) -> direct = @option options, 'direct', no unless direct getter_name = Object.getter_name_for key getter_function = @[getter_name] return getter_function.call @ if @is_function getter_function instance_variable_name = '@' + key return @[instance_variable_name] if @[instance_variable_name] isnt undefined @[key] set_value_for: (value, key, options = {}) -> direct = @option options, 'direct', no unless direct setter_name = Object.setter_name_for key setter_function = @[setter_name] return setter_function.call(@, value, options = {}) if @is_function setter_function instance_variable_name = '@' + key if @[instance_variable_name] isnt undefined @[instance_variable_name] = value return @ if @[key] isnt undefined @[key] = value return @ @error "Can't set value for key '" + key + "', property unknown" @ # ---------------------------------------------------------------------------- class TypeChecking native_is_array = Array.isArray is_null: (object) -> object = @ if arguments.length < 1 object is null is_class: (object) -> object = @ if arguments.length < 1 Boolean (typeof object) is 'function' and object.name.match /^[A-Z]/ is_function: (object) -> object = @ if arguments.length < 1 object?.constructor? and object.call? and object.apply? is_boolean: (object) -> object = @ if arguments.length < 1 object is yes or object is no or Object::toString.call(object) is '[object Boolean]' is_number: (object) -> object = @ if arguments.length < 1 object is 0 or (object?.toExponential? and object.toFixed?) is_date: (object) -> object = @ if arguments.length < 1 object? and object.getTimezoneOffset? and object.setUTCFullYear? is_string: (object) -> object = @ if arguments.length < 1 object is "" or (object?.charCodeAt? and object.substr?) is_reg_exp: (object) -> object = @ if arguments.length < 1 object? and object.test? and object.exec? and (object.ignoreCase? or object.ignoreCase == no) is_array: (object) -> object = @ if arguments.length < 1 native_is_array object is_dictionary: (object) -> object = @ if arguments.length < 1 object?.constructor?.name is 'Object' is_kind_of: (object, klass) -> [object, klass] = [@, object] if arguments.length < 2 object instanceof klass is_instance_of: (object, klass) -> [object, klass] = [@, object] if arguments.length < 2 @class_of(object) is klass # ---------------------------------------------------------------------------- class Comparing is_comparable: -> no is_less_than: (value, options = {}) -> @compare_to(value, options) is -1 is_less_than_or_equals: (value, options = {}) -> result = @compare_to value, options result is 0 or result is -1 is_greater_than: (value, options = {}) -> @compare_to(value, options) is 1 is_greater_than_or_equals: (value, options = {}) -> result = @compare_to value, options result is 0 or result is 1 is_between: (bounds, options = {}) -> [lower, upper] = bounds excluding_bounds = options['excluding_bounds'] or no excluding_lower = options['excluding_lower'] or no excluding_upper = options['excluding_upper'] or no include_lower = not (excluding_bounds or excluding_lower) include_upper = not (excluding_bounds or excluding_upper) compared_to_lower = @compare_to lower, options compared_to_upper = @compare_to upper, options meets_lower = compared_to_lower is +1 or include_lower and compared_to_lower is 0 meets_upper = compared_to_upper is -1 or include_upper and compared_to_upper is 0 meets_lower and meets_upper # ---------------------------------------------------------------------------- class Messaging responds_to: (object, command) -> [object, command] = [@, object] if arguments.length < 2 command? and object[command]? and @is_function object[command] # ---------------------------------------------------------------------------- Object.includes Keywords Object.includes FreezingAndSealing Object.includes KeyValueCoding Object.includes TypeChecking Object.includes Comparing Object.includes Messaging @export Module
true
# # Copyright (c) 2012 PI:NAME:<NAME>END_PI. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. global = exports ? this # ------------------------------------------------------------------------------ class Module option = (object, key, fallback) -> if object? and Object::hasOwnProperty.call object, key then object[key] else fallback @walk: (path, options = {}) -> create_if_not_exists = option options, 'create_if_not_exists', no secret = option options, 'secret', no object = global for section in path.split "." parent = object object = object[section] object ?= object['$' + section] if secret object ?= parent[section] = new Module() if create_if_not_exists @error "Can't walk module path '#{path}', #{section} doesn't exist" unless object? object export: (object, options = {}) -> as = option options, 'as', null secret = option options, 'secret', no name = as ? object['name'] @error "Can't export #{object}, couldn't determine name" unless name? @error "Can't export #{object} as '#{name}', name already taken" if @[name]? name = '$' + name if secret @[name] = object # ------------------------------------------------------------------------------ Object::module = (path, block) -> module = Module.walk path, create_if_not_exists: yes block?.call module module Object::import = (path, options = {}) -> secret = @option options, 'secret', no Module.walk path, options Object::includes = (mixins...) -> for mixin in mixins @[key] = value for own key, value of mixin @prototype[key] = value for own key, value of mixin.prototype # ------------------------------------------------------------------------------ @module 'Milk', -> class Keywords native_is_array = Array.isArray native_has_own_property = Object::hasOwnProperty native_get_prototype_of = Object.getPrototypeOf native_keys = Object.keys native_to_string = Object::toString option: (object, key, fallback) -> if object? and native_has_own_property.call object, key then object[key] else fallback class_of: (object) -> object?.constructor ? null class_name_of: (object) -> object?.constructor?.name ? null keys_of: (object) -> native_keys object values_of: (object) -> (object[key] for key in native_keys object) prototype_of: (object) -> native_get_prototype_of object copy_of: (object) -> return undefined if object is undefined return null if object is null if @is_dictionary object copy = {} for own key, value of object copy[key] = value return copy @error "Object doesn't support copying" unless @responds_to object, 'copy' native_get_prototype_of(object)['copy'].call object frozen_copy_of: (object) -> return object if @is_frozen object return @freeze @copy_of object description_of: (object) -> return "undefined" if object is undefined return "null" if object is null return "{" + @keys_of(object).join(", ") + "}" if @is_dictionary object return object.to_string() if @responds_to object, 'to_string' native_to_string.call object are_equal: (left, right) -> return yes if left is undefined and right is undefined return no if left is undefined or right is undefined return yes if left is null and right is null return no if left is null or right is null left_is_dictionary = @is_dictionary left right_is_dictionary = @is_dictionary right return no if left_is_dictionary and not right_is_dictionary return no if not left_is_dictionary and right_is_dictionary if left_is_dictionary and right_is_dictionary for key in @keys_of(left).concat @keys_of(right) return no unless @has_own(left, key) and @has_own(right, key) return no unless @are_equal @own(left, key), @own(right, key) return yes return left.equals right if @responds_to left, 'equals' return right.equals left if @responds_to right, 'equals' return left.compare_to(right) is 0 if @responds_to left, 'compare_to' return right.compare_to(left) is 0 if @responds_to right, 'compare_to' @error "Can't check equality, neither left nor right implement equals() or compare_to()" compare: (left, right) -> @error "Can't compare objects, left is undefined" if left is undefined @error "Can't compare objects, right is undefined" if right is undefined @error "Can't compare objects, left is null" if left is null @error "Can't compare objects, right is null" if right is null @error "Can't compare objects, left is a dictionary" if @is_dictionary left @error "Can't compare objects, right is a dictionary" if @is_dictionary right @error "Can't compare, objects don't support comparing" unless @responds_to left, 'compare_to' left.compare_to right has_own: (object, key) -> [object, key] = [@, object] if arguments.length < 2 native_has_own_property.call object, key own: (object, key) -> [object, key] = [@, object] if arguments.length < 2 if native_has_own_property.call object, key then object[key] else undefined mix: (objects...) -> mixed = {} for object in objects mixed[key] = value for own key, value of object when not @has_own mixed, key mixed merge: (objects...) -> merged = {} for object in objects merged[key] = value for own key, value of object merged info: (message) -> console.log "[INFO] " + message warning: (message) -> console.log "[WARNING] " + message error: (message) -> stackTrace = "(can't print stack trace, function printStackTrace() not found)" stackTrace = "\n\n" + printStackTrace()[3..].join "\n" if printStackTrace? throw "[ERROR] " + message + stackTrace debug: (message) -> console.log "[DEBUG] " + message # ---------------------------------------------------------------------------- class FreezingAndSealing native_seal = Object.seal native_freeze = Object.freeze native_is_sealed = Object.isSealed native_is_frozen = Object.isFrozen is_frozen: (object) -> object = @ if arguments.length < 1 native_is_frozen object is_sealed: (object) -> object = @ if arguments.length < 1 native_is_sealed object freeze: (object) -> object = @ if arguments.length < 1 native_freeze? object object seal: (object) -> object = @ if arguments.length < 1 native_seal? object object # ---------------------------------------------------------------------------- class KeyValueCoding @getter_name_for = (key) -> key @setter_name_for = (key) -> example_key = "PI:KEY:<KEY>END_PI" is_camel_cased = example_key[4] isnt '_' return "set_" + key unless is_camel_cased "set" + key[0].uppercased() + key.slice 1 value_for: (key, options = {}) -> direct = @option options, 'direct', no unless direct getter_name = Object.getter_name_for key getter_function = @[getter_name] return getter_function.call @ if @is_function getter_function instance_variable_name = '@' + key return @[instance_variable_name] if @[instance_variable_name] isnt undefined @[key] set_value_for: (value, key, options = {}) -> direct = @option options, 'direct', no unless direct setter_name = Object.setter_name_for key setter_function = @[setter_name] return setter_function.call(@, value, options = {}) if @is_function setter_function instance_variable_name = '@' + key if @[instance_variable_name] isnt undefined @[instance_variable_name] = value return @ if @[key] isnt undefined @[key] = value return @ @error "Can't set value for key '" + key + "', property unknown" @ # ---------------------------------------------------------------------------- class TypeChecking native_is_array = Array.isArray is_null: (object) -> object = @ if arguments.length < 1 object is null is_class: (object) -> object = @ if arguments.length < 1 Boolean (typeof object) is 'function' and object.name.match /^[A-Z]/ is_function: (object) -> object = @ if arguments.length < 1 object?.constructor? and object.call? and object.apply? is_boolean: (object) -> object = @ if arguments.length < 1 object is yes or object is no or Object::toString.call(object) is '[object Boolean]' is_number: (object) -> object = @ if arguments.length < 1 object is 0 or (object?.toExponential? and object.toFixed?) is_date: (object) -> object = @ if arguments.length < 1 object? and object.getTimezoneOffset? and object.setUTCFullYear? is_string: (object) -> object = @ if arguments.length < 1 object is "" or (object?.charCodeAt? and object.substr?) is_reg_exp: (object) -> object = @ if arguments.length < 1 object? and object.test? and object.exec? and (object.ignoreCase? or object.ignoreCase == no) is_array: (object) -> object = @ if arguments.length < 1 native_is_array object is_dictionary: (object) -> object = @ if arguments.length < 1 object?.constructor?.name is 'Object' is_kind_of: (object, klass) -> [object, klass] = [@, object] if arguments.length < 2 object instanceof klass is_instance_of: (object, klass) -> [object, klass] = [@, object] if arguments.length < 2 @class_of(object) is klass # ---------------------------------------------------------------------------- class Comparing is_comparable: -> no is_less_than: (value, options = {}) -> @compare_to(value, options) is -1 is_less_than_or_equals: (value, options = {}) -> result = @compare_to value, options result is 0 or result is -1 is_greater_than: (value, options = {}) -> @compare_to(value, options) is 1 is_greater_than_or_equals: (value, options = {}) -> result = @compare_to value, options result is 0 or result is 1 is_between: (bounds, options = {}) -> [lower, upper] = bounds excluding_bounds = options['excluding_bounds'] or no excluding_lower = options['excluding_lower'] or no excluding_upper = options['excluding_upper'] or no include_lower = not (excluding_bounds or excluding_lower) include_upper = not (excluding_bounds or excluding_upper) compared_to_lower = @compare_to lower, options compared_to_upper = @compare_to upper, options meets_lower = compared_to_lower is +1 or include_lower and compared_to_lower is 0 meets_upper = compared_to_upper is -1 or include_upper and compared_to_upper is 0 meets_lower and meets_upper # ---------------------------------------------------------------------------- class Messaging responds_to: (object, command) -> [object, command] = [@, object] if arguments.length < 2 command? and object[command]? and @is_function object[command] # ---------------------------------------------------------------------------- Object.includes Keywords Object.includes FreezingAndSealing Object.includes KeyValueCoding Object.includes TypeChecking Object.includes Comparing Object.includes Messaging @export Module
[ { "context": "rom Last.fm\nlastFMrequest = () ->\n username = 'paul_r_schaefer'\n API_key = '0f680404e39c821cac34008cc4d803db'", "end": 158, "score": 0.9996594786643982, "start": 143, "tag": "USERNAME", "value": "paul_r_schaefer" }, { "context": ">\n username = 'paul_r_schaefer'\n API_key = '0f680404e39c821cac34008cc4d803db'\n lastFM_URL = 'https://ws.audioscrobbler.com/", "end": 207, "score": 0.9997652173042297, "start": 175, "tag": "KEY", "value": "0f680404e39c821cac34008cc4d803db" } ]
public/js/main.coffee
pschfr/now-playing
3
# Used in development debug = false # Initiate timer variable timer = '' # Load scrobbles from Last.fm lastFMrequest = () -> username = 'paul_r_schaefer' API_key = '0f680404e39c821cac34008cc4d803db' lastFM_URL = 'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=' + username + '&api_key=' + API_key + '&limit=1&format=json' xhr = new XMLHttpRequest() music = document.getElementById('music') image = document.getElementById('album') xhr.open('GET', lastFM_URL, true) xhr.onreadystatechange = () -> if (xhr.readyState == 4 && xhr.status == 200) # Decodes response from Last.fm track = JSON.parse(xhr.responseText).recenttracks.track[0] if debug console.log(track) url = track.url artist = track.artist['\#text'] album = track.album['\#text'] song = track.name # If image exists, use it, otherwise use blank image if track.image[0]['\#text'] # This is an undocumented hack... Somehow this returns a larger image than possible otherwise # https://getmusicbee.com/forum/index.php?topic=22717.msg133539#msg133539 imgURL = track.image[0]['\#text'].replace('34s', '_').replace('.png', '.jpg') else imgURL = "svg/notes.svg" # Add content to HTML image.src = imgURL image.alt = album image.title = album # If image as JPG doesn't load, try PNG version if image.complete = false imgURL = imgURL.replace('.jpg', '.png') image.src = imgURL music.innerHTML = '<a href="' + url + '" target="_blank" class="link underline-hover color-inherit">' + song + '<br><span class="f3 light-silver">' + artist + ' — ' + album + '</span></a>' # Changes page title document.title = song + ' — ' + artist # If the browser doesn't support backdrop-filter, append the image where neccessary for the fallback. if !CSS.supports('backdrop-filter: blur(1px)') # So it doesn't continously append to the CSS, only change the rule if the imgURL is different if document.styleSheets[0].cssRules[0].selectorText == 'html' # Inserts the rule the first time document.styleSheets[0].insertRule('body::before { background-image: url("' + imgURL + '") }') else # Checks if the new image URL is different before replacing if imgURL != document.styleSheets[0].cssRules[0].style.backgroundImage.replace('url("', '').replace('")', '') document.styleSheets[0].cssRules[0].style.backgroundImage = 'url("' + imgURL + '")' # Otherwise, just append it to the body bg else document.body.style.backgroundImage = "url('" + imgURL + "')" xhr.send(null) timer = setTimeout(lastFMrequest, 5000) # refresh every 5 seconds # On load, do this... window.addEventListener 'load', () -> lastFMrequest() # If tab is hidden, clear timer, or start it again document.addEventListener 'visibilitychange', () -> if document.visibilityState == 'hidden' clearTimeout(timer) else if document.visibilityState == 'visible' lastFMrequest()
25571
# Used in development debug = false # Initiate timer variable timer = '' # Load scrobbles from Last.fm lastFMrequest = () -> username = 'paul_r_schaefer' API_key = '<KEY>' lastFM_URL = 'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=' + username + '&api_key=' + API_key + '&limit=1&format=json' xhr = new XMLHttpRequest() music = document.getElementById('music') image = document.getElementById('album') xhr.open('GET', lastFM_URL, true) xhr.onreadystatechange = () -> if (xhr.readyState == 4 && xhr.status == 200) # Decodes response from Last.fm track = JSON.parse(xhr.responseText).recenttracks.track[0] if debug console.log(track) url = track.url artist = track.artist['\#text'] album = track.album['\#text'] song = track.name # If image exists, use it, otherwise use blank image if track.image[0]['\#text'] # This is an undocumented hack... Somehow this returns a larger image than possible otherwise # https://getmusicbee.com/forum/index.php?topic=22717.msg133539#msg133539 imgURL = track.image[0]['\#text'].replace('34s', '_').replace('.png', '.jpg') else imgURL = "svg/notes.svg" # Add content to HTML image.src = imgURL image.alt = album image.title = album # If image as JPG doesn't load, try PNG version if image.complete = false imgURL = imgURL.replace('.jpg', '.png') image.src = imgURL music.innerHTML = '<a href="' + url + '" target="_blank" class="link underline-hover color-inherit">' + song + '<br><span class="f3 light-silver">' + artist + ' — ' + album + '</span></a>' # Changes page title document.title = song + ' — ' + artist # If the browser doesn't support backdrop-filter, append the image where neccessary for the fallback. if !CSS.supports('backdrop-filter: blur(1px)') # So it doesn't continously append to the CSS, only change the rule if the imgURL is different if document.styleSheets[0].cssRules[0].selectorText == 'html' # Inserts the rule the first time document.styleSheets[0].insertRule('body::before { background-image: url("' + imgURL + '") }') else # Checks if the new image URL is different before replacing if imgURL != document.styleSheets[0].cssRules[0].style.backgroundImage.replace('url("', '').replace('")', '') document.styleSheets[0].cssRules[0].style.backgroundImage = 'url("' + imgURL + '")' # Otherwise, just append it to the body bg else document.body.style.backgroundImage = "url('" + imgURL + "')" xhr.send(null) timer = setTimeout(lastFMrequest, 5000) # refresh every 5 seconds # On load, do this... window.addEventListener 'load', () -> lastFMrequest() # If tab is hidden, clear timer, or start it again document.addEventListener 'visibilitychange', () -> if document.visibilityState == 'hidden' clearTimeout(timer) else if document.visibilityState == 'visible' lastFMrequest()
true
# Used in development debug = false # Initiate timer variable timer = '' # Load scrobbles from Last.fm lastFMrequest = () -> username = 'paul_r_schaefer' API_key = 'PI:KEY:<KEY>END_PI' lastFM_URL = 'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=' + username + '&api_key=' + API_key + '&limit=1&format=json' xhr = new XMLHttpRequest() music = document.getElementById('music') image = document.getElementById('album') xhr.open('GET', lastFM_URL, true) xhr.onreadystatechange = () -> if (xhr.readyState == 4 && xhr.status == 200) # Decodes response from Last.fm track = JSON.parse(xhr.responseText).recenttracks.track[0] if debug console.log(track) url = track.url artist = track.artist['\#text'] album = track.album['\#text'] song = track.name # If image exists, use it, otherwise use blank image if track.image[0]['\#text'] # This is an undocumented hack... Somehow this returns a larger image than possible otherwise # https://getmusicbee.com/forum/index.php?topic=22717.msg133539#msg133539 imgURL = track.image[0]['\#text'].replace('34s', '_').replace('.png', '.jpg') else imgURL = "svg/notes.svg" # Add content to HTML image.src = imgURL image.alt = album image.title = album # If image as JPG doesn't load, try PNG version if image.complete = false imgURL = imgURL.replace('.jpg', '.png') image.src = imgURL music.innerHTML = '<a href="' + url + '" target="_blank" class="link underline-hover color-inherit">' + song + '<br><span class="f3 light-silver">' + artist + ' — ' + album + '</span></a>' # Changes page title document.title = song + ' — ' + artist # If the browser doesn't support backdrop-filter, append the image where neccessary for the fallback. if !CSS.supports('backdrop-filter: blur(1px)') # So it doesn't continously append to the CSS, only change the rule if the imgURL is different if document.styleSheets[0].cssRules[0].selectorText == 'html' # Inserts the rule the first time document.styleSheets[0].insertRule('body::before { background-image: url("' + imgURL + '") }') else # Checks if the new image URL is different before replacing if imgURL != document.styleSheets[0].cssRules[0].style.backgroundImage.replace('url("', '').replace('")', '') document.styleSheets[0].cssRules[0].style.backgroundImage = 'url("' + imgURL + '")' # Otherwise, just append it to the body bg else document.body.style.backgroundImage = "url('" + imgURL + "')" xhr.send(null) timer = setTimeout(lastFMrequest, 5000) # refresh every 5 seconds # On load, do this... window.addEventListener 'load', () -> lastFMrequest() # If tab is hidden, clear timer, or start it again document.addEventListener 'visibilitychange', () -> if document.visibilityState == 'hidden' clearTimeout(timer) else if document.visibilityState == 'visible' lastFMrequest()
[ { "context": "titutionUsers', ->\n\t\tbeforeEach ->\n\t\t\t@user1Id = '123abc123abc123abc123abc'\n\t\t\t@user2Id = '456def456def456def456", "end": 1760, "score": 0.850145161151886, "start": 1748, "tag": "PASSWORD", "value": "123abc123abc" }, { "context": "er1Id = '123abc123abc123abc123abc'\n\t\t\t@user2Id = '456def456def456def456def'\n\t\t\t@affiliations = [\n\t\t\t\t{ user_id: @user1Id }\n\t", "end": 1813, "score": 0.9913946390151978, "start": 1789, "tag": "PASSWORD", "value": "456def456def456def456def" }, { "context": "f456def456def'\n\t\t\t@affiliations = [\n\t\t\t\t{ user_id: @user1Id }\n\t\t\t\t{ user_id: @user2Id }\n\t\t\t]\n\t\t\t@user1 =\n\t\t\t\t", "end": 1859, "score": 0.9979115128517151, "start": 1851, "tag": "USERNAME", "value": "@user1Id" }, { "context": "tions = [\n\t\t\t\t{ user_id: @user1Id }\n\t\t\t\t{ user_id: @user2Id }\n\t\t\t]\n\t\t\t@user1 =\n\t\t\t\t_id: @user1Id\n\t\t\t@user2 =\n", "end": 1885, "score": 0.9947889447212219, "start": 1877, "tag": "USERNAME", "value": "@user2Id" }, { "context": "id: @user1Id }\n\t\t\t\t{ user_id: @user2Id }\n\t\t\t]\n\t\t\t@user1 =\n\t\t\t\t_id: @user1Id\n\t\t\t@user2 =\n\t\t\t\t_id: @user2Id", "end": 1902, "score": 0.5865417718887329, "start": 1897, "tag": "USERNAME", "value": "user1" }, { "context": "\t\t\t{ user_id: @user2Id }\n\t\t\t]\n\t\t\t@user1 =\n\t\t\t\t_id: @user1Id\n\t\t\t@user2 =\n\t\t\t\t_id: @user2Id\n\t\t\t@subscription =\n", "end": 1922, "score": 0.982327938079834, "start": 1914, "tag": "USERNAME", "value": "@user1Id" }, { "context": "\t\t\t@user1 =\n\t\t\t\t_id: @user1Id\n\t\t\t@user2 =\n\t\t\t\t_id: @user2Id\n\t\t\t@subscription =\n\t\t\t\tplanCode: 'pro'\n\t\t\t\tgrou", "end": 1950, "score": 0.7508959770202637, "start": 1944, "tag": "USERNAME", "value": "@user2" }, { "context": "\t\tgroupPlan: false\n\t\t\t@UserGetter.getUser.withArgs(@user1Id).callsArgWith(1, null, @user1)\n\t\t\t@UserGetter.get", "end": 2053, "score": 0.9990768432617188, "start": 2045, "tag": "USERNAME", "value": "@user1Id" }, { "context": "ser.withArgs(@user1Id).callsArgWith(1, null, @user1)\n\t\t\t@UserGetter.getUser.withArgs(@user2Id).callsA", "end": 2083, "score": 0.5993180274963379, "start": 2082, "tag": "USERNAME", "value": "1" }, { "context": "h(1, null, @user1)\n\t\t\t@UserGetter.getUser.withArgs(@user2Id).callsArgWith(1, null, @user2)\n\t\t\t@SubscriptionLo", "end": 2125, "score": 0.9920122027397156, "start": 2117, "tag": "USERNAME", "value": "@user2Id" }, { "context": "@SubscriptionLocator.getUsersSubscription.withArgs(@user2).callsArgWith(1, null, @subscription)\n\t\t\t@re", "end": 2210, "score": 0.6284008622169495, "start": 2210, "tag": "USERNAME", "value": "" }, { "context": " null, @subscription)\n\t\t\t@refreshFeatures.withArgs(@user1Id).callsArgWith(2, null, {}, true)\n\t\t\t@getInstituti", "end": 2293, "score": 0.9983295798301697, "start": 2285, "tag": "USERNAME", "value": "@user1Id" }, { "context": "res', (done) ->\n\t\t\taffiliations = [\n\t\t\t\t{ email: 'foo@bar.com' }\n\t\t\t\t{ email: 'baz@boo.edu' }\n\t\t\t]\n\t\t\tstubbedUs", "end": 3483, "score": 0.9999257922172546, "start": 3472, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": "ns = [\n\t\t\t\t{ email: 'foo@bar.com' }\n\t\t\t\t{ email: 'baz@boo.edu' }\n\t\t\t]\n\t\t\tstubbedUsers = [\n\t\t\t\t{\n\t\t\t\t\t_id: '123a", "end": 3512, "score": 0.9999253749847412, "start": 3501, "tag": "EMAIL", "value": "baz@boo.edu" } ]
test/unit/coffee/Institutions/InstitutionsManagerTests.coffee
shyoshyo/web-sharelatex
1
should = require('chai').should() SandboxedModule = require('sandboxed-module') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Institutions/InstitutionsManager" expect = require('chai').expect describe "InstitutionsManager", -> beforeEach -> @institutionId = 123 @logger = log: -> @user = {} @getInstitutionAffiliations = sinon.stub() @refreshFeatures = sinon.stub().yields() @UserGetter = getUsersByAnyConfirmedEmail: sinon.stub().yields() getUser: sinon.stub().callsArgWith(1, null, @user) @creator = create: sinon.stub().callsArg(0) @NotificationsBuilder = featuresUpgradedByAffiliation: sinon.stub().returns(@creator) redundantPersonalSubscription: sinon.stub().returns(@creator) @SubscriptionLocator = getUsersSubscription: sinon.stub().callsArg(1) @institutionWithV1Data = name: 'Wombat University' @institution = fetchV1Data: sinon.stub().callsArgWith(0, null, @institutionWithV1Data) @InstitutionModel = Institution: findOne: sinon.stub().callsArgWith(1, null, @institution) @Mongo = ObjectId: sinon.stub().returnsArg(0) @InstitutionsManager = SandboxedModule.require modulePath, requires: 'logger-sharelatex': @logger './InstitutionsAPI': getInstitutionAffiliations: @getInstitutionAffiliations '../Subscription/FeaturesUpdater': refreshFeatures: @refreshFeatures '../User/UserGetter': @UserGetter '../Notifications/NotificationsBuilder': @NotificationsBuilder '../Subscription/SubscriptionLocator': @SubscriptionLocator '../../models/Institution': @InstitutionModel '../../infrastructure/mongojs': @Mongo describe 'upgradeInstitutionUsers', -> beforeEach -> @user1Id = '123abc123abc123abc123abc' @user2Id = '456def456def456def456def' @affiliations = [ { user_id: @user1Id } { user_id: @user2Id } ] @user1 = _id: @user1Id @user2 = _id: @user2Id @subscription = planCode: 'pro' groupPlan: false @UserGetter.getUser.withArgs(@user1Id).callsArgWith(1, null, @user1) @UserGetter.getUser.withArgs(@user2Id).callsArgWith(1, null, @user2) @SubscriptionLocator.getUsersSubscription.withArgs(@user2).callsArgWith(1, null, @subscription) @refreshFeatures.withArgs(@user1Id).callsArgWith(2, null, {}, true) @getInstitutionAffiliations.yields(null, @affiliations) it 'refresh all users Features', (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledTwice(@refreshFeatures) done() it "notifies users if their features have been upgraded", (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledOnce(@NotificationsBuilder.featuresUpgradedByAffiliation) sinon.assert.calledWith(@NotificationsBuilder.featuresUpgradedByAffiliation, @affiliations[0], @user1) done() it "notifies users if they have a subscription that should be cancelled", (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledOnce(@NotificationsBuilder.redundantPersonalSubscription) sinon.assert.calledWith(@NotificationsBuilder.redundantPersonalSubscription, @affiliations[1], @user2) done() describe 'checkInstitutionUsers', -> it 'check all users Features', (done) -> affiliations = [ { email: 'foo@bar.com' } { email: 'baz@boo.edu' } ] stubbedUsers = [ { _id: '123abc123abc123abc123abc' features: {collaborators: -1, trackChanges: true} } { _id: '456def456def456def456def' features: {collaborators: 10, trackChanges: false} } { _id: '789def789def789def789def' features: {collaborators: -1, trackChanges: false} } ] @getInstitutionAffiliations.yields(null, affiliations) @UserGetter.getUsersByAnyConfirmedEmail.yields(null, stubbedUsers) @InstitutionsManager.checkInstitutionUsers @institutionId, (error, usersSummary) => should.not.exist(error) usersSummary.totalConfirmedUsers.should.equal 3 usersSummary.totalConfirmedProUsers.should.equal 1 usersSummary.totalConfirmedNonProUsers.should.equal 2 expect(usersSummary.confirmedNonProUsers).to.deep.equal ['456def456def456def456def', '789def789def789def789def'] done()
84097
should = require('chai').should() SandboxedModule = require('sandboxed-module') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Institutions/InstitutionsManager" expect = require('chai').expect describe "InstitutionsManager", -> beforeEach -> @institutionId = 123 @logger = log: -> @user = {} @getInstitutionAffiliations = sinon.stub() @refreshFeatures = sinon.stub().yields() @UserGetter = getUsersByAnyConfirmedEmail: sinon.stub().yields() getUser: sinon.stub().callsArgWith(1, null, @user) @creator = create: sinon.stub().callsArg(0) @NotificationsBuilder = featuresUpgradedByAffiliation: sinon.stub().returns(@creator) redundantPersonalSubscription: sinon.stub().returns(@creator) @SubscriptionLocator = getUsersSubscription: sinon.stub().callsArg(1) @institutionWithV1Data = name: 'Wombat University' @institution = fetchV1Data: sinon.stub().callsArgWith(0, null, @institutionWithV1Data) @InstitutionModel = Institution: findOne: sinon.stub().callsArgWith(1, null, @institution) @Mongo = ObjectId: sinon.stub().returnsArg(0) @InstitutionsManager = SandboxedModule.require modulePath, requires: 'logger-sharelatex': @logger './InstitutionsAPI': getInstitutionAffiliations: @getInstitutionAffiliations '../Subscription/FeaturesUpdater': refreshFeatures: @refreshFeatures '../User/UserGetter': @UserGetter '../Notifications/NotificationsBuilder': @NotificationsBuilder '../Subscription/SubscriptionLocator': @SubscriptionLocator '../../models/Institution': @InstitutionModel '../../infrastructure/mongojs': @Mongo describe 'upgradeInstitutionUsers', -> beforeEach -> @user1Id = '<PASSWORD>123abc123abc' @user2Id = '<PASSWORD>' @affiliations = [ { user_id: @user1Id } { user_id: @user2Id } ] @user1 = _id: @user1Id @user2 = _id: @user2Id @subscription = planCode: 'pro' groupPlan: false @UserGetter.getUser.withArgs(@user1Id).callsArgWith(1, null, @user1) @UserGetter.getUser.withArgs(@user2Id).callsArgWith(1, null, @user2) @SubscriptionLocator.getUsersSubscription.withArgs(@user2).callsArgWith(1, null, @subscription) @refreshFeatures.withArgs(@user1Id).callsArgWith(2, null, {}, true) @getInstitutionAffiliations.yields(null, @affiliations) it 'refresh all users Features', (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledTwice(@refreshFeatures) done() it "notifies users if their features have been upgraded", (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledOnce(@NotificationsBuilder.featuresUpgradedByAffiliation) sinon.assert.calledWith(@NotificationsBuilder.featuresUpgradedByAffiliation, @affiliations[0], @user1) done() it "notifies users if they have a subscription that should be cancelled", (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledOnce(@NotificationsBuilder.redundantPersonalSubscription) sinon.assert.calledWith(@NotificationsBuilder.redundantPersonalSubscription, @affiliations[1], @user2) done() describe 'checkInstitutionUsers', -> it 'check all users Features', (done) -> affiliations = [ { email: '<EMAIL>' } { email: '<EMAIL>' } ] stubbedUsers = [ { _id: '123abc123abc123abc123abc' features: {collaborators: -1, trackChanges: true} } { _id: '456def456def456def456def' features: {collaborators: 10, trackChanges: false} } { _id: '789def789def789def789def' features: {collaborators: -1, trackChanges: false} } ] @getInstitutionAffiliations.yields(null, affiliations) @UserGetter.getUsersByAnyConfirmedEmail.yields(null, stubbedUsers) @InstitutionsManager.checkInstitutionUsers @institutionId, (error, usersSummary) => should.not.exist(error) usersSummary.totalConfirmedUsers.should.equal 3 usersSummary.totalConfirmedProUsers.should.equal 1 usersSummary.totalConfirmedNonProUsers.should.equal 2 expect(usersSummary.confirmedNonProUsers).to.deep.equal ['456def456def456def456def', '789def789def789def789def'] done()
true
should = require('chai').should() SandboxedModule = require('sandboxed-module') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Institutions/InstitutionsManager" expect = require('chai').expect describe "InstitutionsManager", -> beforeEach -> @institutionId = 123 @logger = log: -> @user = {} @getInstitutionAffiliations = sinon.stub() @refreshFeatures = sinon.stub().yields() @UserGetter = getUsersByAnyConfirmedEmail: sinon.stub().yields() getUser: sinon.stub().callsArgWith(1, null, @user) @creator = create: sinon.stub().callsArg(0) @NotificationsBuilder = featuresUpgradedByAffiliation: sinon.stub().returns(@creator) redundantPersonalSubscription: sinon.stub().returns(@creator) @SubscriptionLocator = getUsersSubscription: sinon.stub().callsArg(1) @institutionWithV1Data = name: 'Wombat University' @institution = fetchV1Data: sinon.stub().callsArgWith(0, null, @institutionWithV1Data) @InstitutionModel = Institution: findOne: sinon.stub().callsArgWith(1, null, @institution) @Mongo = ObjectId: sinon.stub().returnsArg(0) @InstitutionsManager = SandboxedModule.require modulePath, requires: 'logger-sharelatex': @logger './InstitutionsAPI': getInstitutionAffiliations: @getInstitutionAffiliations '../Subscription/FeaturesUpdater': refreshFeatures: @refreshFeatures '../User/UserGetter': @UserGetter '../Notifications/NotificationsBuilder': @NotificationsBuilder '../Subscription/SubscriptionLocator': @SubscriptionLocator '../../models/Institution': @InstitutionModel '../../infrastructure/mongojs': @Mongo describe 'upgradeInstitutionUsers', -> beforeEach -> @user1Id = 'PI:PASSWORD:<PASSWORD>END_PI123abc123abc' @user2Id = 'PI:PASSWORD:<PASSWORD>END_PI' @affiliations = [ { user_id: @user1Id } { user_id: @user2Id } ] @user1 = _id: @user1Id @user2 = _id: @user2Id @subscription = planCode: 'pro' groupPlan: false @UserGetter.getUser.withArgs(@user1Id).callsArgWith(1, null, @user1) @UserGetter.getUser.withArgs(@user2Id).callsArgWith(1, null, @user2) @SubscriptionLocator.getUsersSubscription.withArgs(@user2).callsArgWith(1, null, @subscription) @refreshFeatures.withArgs(@user1Id).callsArgWith(2, null, {}, true) @getInstitutionAffiliations.yields(null, @affiliations) it 'refresh all users Features', (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledTwice(@refreshFeatures) done() it "notifies users if their features have been upgraded", (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledOnce(@NotificationsBuilder.featuresUpgradedByAffiliation) sinon.assert.calledWith(@NotificationsBuilder.featuresUpgradedByAffiliation, @affiliations[0], @user1) done() it "notifies users if they have a subscription that should be cancelled", (done) -> @InstitutionsManager.upgradeInstitutionUsers @institutionId, (error) => should.not.exist(error) sinon.assert.calledOnce(@NotificationsBuilder.redundantPersonalSubscription) sinon.assert.calledWith(@NotificationsBuilder.redundantPersonalSubscription, @affiliations[1], @user2) done() describe 'checkInstitutionUsers', -> it 'check all users Features', (done) -> affiliations = [ { email: 'PI:EMAIL:<EMAIL>END_PI' } { email: 'PI:EMAIL:<EMAIL>END_PI' } ] stubbedUsers = [ { _id: '123abc123abc123abc123abc' features: {collaborators: -1, trackChanges: true} } { _id: '456def456def456def456def' features: {collaborators: 10, trackChanges: false} } { _id: '789def789def789def789def' features: {collaborators: -1, trackChanges: false} } ] @getInstitutionAffiliations.yields(null, affiliations) @UserGetter.getUsersByAnyConfirmedEmail.yields(null, stubbedUsers) @InstitutionsManager.checkInstitutionUsers @institutionId, (error, usersSummary) => should.not.exist(error) usersSummary.totalConfirmedUsers.should.equal 3 usersSummary.totalConfirmedProUsers.should.equal 1 usersSummary.totalConfirmedNonProUsers.should.equal 2 expect(usersSummary.confirmedNonProUsers).to.deep.equal ['456def456def456def456def', '789def789def789def789def'] done()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992656707763672, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-smalloc.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") os = require("os") # first grab js api's smalloc = require("smalloc") alloc = smalloc.alloc dispose = smalloc.dispose copyOnto = smalloc.copyOnto kMaxLength = smalloc.kMaxLength Types = smalloc.Types # sliceOnto is volatile and cannot be exposed to users. sliceOnto = process.binding("smalloc").sliceOnto # verify allocation b = alloc(5, {}) assert.ok typeof b is "object" i = 0 while i < 5 assert.ok b[i] isnt `undefined` i++ b = {} c = alloc(5, b) assert.equal b, c assert.deepEqual b, c b = alloc(5, {}) c = {} c._data = sliceOnto(b, c, 0, 5) assert.ok typeof c._data is "object" assert.equal b, c._data assert.deepEqual b, c._data # verify writes b = alloc(5, {}) i = 0 while i < 5 b[i] = i i++ i = 0 while i < 5 assert.equal b[i], i i++ b = alloc(1, Types.Uint8) b[0] = 256 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int8) b[0] = 128 assert.equal b[0], -128 assert.equal b[1], `undefined` b = alloc(1, Types.Uint16) b[0] = 65536 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int16) b[0] = 32768 assert.equal b[0], -32768 assert.equal b[1], `undefined` b = alloc(1, Types.Uint32) b[0] = 4294967296 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int32) b[0] = 2147483648 assert.equal b[0], -2147483648 assert.equal b[1], `undefined` b = alloc(1, Types.Float) b[0] = 0.1111111111111111 assert.equal b[0], 0.1111111119389534 assert.equal b[1], `undefined` b = alloc(1, Types.Double) b[0] = 0.1111111111111111 assert.equal b[0], 0.1111111111111111 assert.equal b[1], `undefined` b = alloc(1, Types.Uint8Clamped) b[0] = 300 assert.equal b[0], 255 assert.equal b[1], `undefined` b = alloc(6, {}) c0 = {} c1 = {} c0._data = sliceOnto(b, c0, 0, 3) c1._data = sliceOnto(b, c1, 3, 6) i = 0 while i < 3 c0[i] = i c1[i] = i + 3 i++ i = 0 while i < 3 assert.equal b[i], i i++ i = 3 while i < 6 assert.equal b[i], i i++ a = alloc(6, {}) b = alloc(6, {}) c = alloc(12, {}) i = 0 while i < 6 a[i] = i b[i] = i * 2 i++ copyOnto a, 0, c, 0, 6 copyOnto b, 0, c, 6, 6 i = 0 while i < 6 assert.equal c[i], i assert.equal c[i + 6], i * 2 i++ b = alloc(1, Types.Double) c = alloc(2, Types.Uint32) if os.endianness() is "LE" c[0] = 2576980378 c[1] = 1069128089 else c[0] = 1069128089 c[1] = 2576980378 copyOnto c, 0, b, 0, 2 assert.equal b[0], 0.1 b = alloc(1, Types.Uint16) c = alloc(2, Types.Uint8) c[0] = c[1] = 0xff copyOnto c, 0, b, 0, 2 assert.equal b[0], 0xffff b = alloc(2, Types.Uint8) c = alloc(1, Types.Uint16) c[0] = 0xffff copyOnto c, 0, b, 0, 1 assert.equal b[0], 0xff assert.equal b[1], 0xff # verify checking external if has external memory # check objects b = {} assert.ok not smalloc.hasExternalData(b) alloc 1, b assert.ok smalloc.hasExternalData(b) f = -> alloc 1, f assert.ok smalloc.hasExternalData(f) # and non-objects assert.ok not smalloc.hasExternalData(true) assert.ok not smalloc.hasExternalData(1) assert.ok not smalloc.hasExternalData("string") assert.ok not smalloc.hasExternalData(null) assert.ok not smalloc.hasExternalData() # verify alloc throws properly # arrays are not supported assert.throws (-> alloc 0, [] return ), TypeError # no allocations larger than kMaxLength assert.throws (-> alloc kMaxLength + 1 return ), RangeError # properly convert to uint32 before checking overflow assert.throws (-> alloc -1 return ), RangeError # no allocating on what's been allocated assert.throws (-> alloc 1, alloc(1) return ), TypeError # throw for values passed that are not objects assert.throws (-> alloc 1, "a" return ), TypeError assert.throws (-> alloc 1, true return ), TypeError assert.throws (-> alloc 1, null return ), TypeError # should not throw allocating to most objects alloc 1, -> alloc 1, /abc/ alloc 1, new Date() # range check on external array enumeration assert.throws (-> alloc 1, 0 return ), TypeError assert.throws (-> alloc 1, 10 return ), TypeError # very copyOnto throws properly # source must have data assert.throws (-> copyOnto {}, 0, alloc(1), 0, 0 return ), Error # dest must have data assert.throws (-> copyOnto alloc(1), 0, {}, 0, 0 return ), Error # copyLength <= sourceLength assert.throws (-> copyOnto alloc(1), 0, alloc(3), 0, 2 return ), RangeError # copyLength <= destLength assert.throws (-> copyOnto alloc(3), 0, alloc(1), 0, 2 return ), RangeError # sourceStart <= sourceLength assert.throws (-> copyOnto alloc(1), 3, alloc(1), 0, 1 return ), RangeError # destStart <= destLength assert.throws (-> copyOnto alloc(1), 0, alloc(1), 3, 1 return ), RangeError # sourceStart + copyLength <= sourceLength assert.throws (-> copyOnto alloc(3), 1, alloc(3), 0, 3 return ), RangeError # destStart + copyLength <= destLength assert.throws (-> copyOnto alloc(3), 0, alloc(3), 1, 3 return ), RangeError # copy_length * array_size <= dest_length assert.throws (-> copyOnto alloc(2, Types.Double), 0, alloc(2, Types.Uint32), 0, 2 return ), RangeError # test disposal b = alloc(5, {}) dispose b i = 0 while i < 5 assert.equal b[i], `undefined` i++ # verify dispose throws properly # only allow object to be passed to dispose assert.throws -> smalloc.dispose null return # can't dispose a Buffer assert.throws -> smalloc.dispose new Buffer() return assert.throws -> smalloc.dispose new Uint8Array(new ArrayBuffer(1)) return assert.throws -> smalloc.dispose {} return
71457
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") os = require("os") # first grab js api's smalloc = require("smalloc") alloc = smalloc.alloc dispose = smalloc.dispose copyOnto = smalloc.copyOnto kMaxLength = smalloc.kMaxLength Types = smalloc.Types # sliceOnto is volatile and cannot be exposed to users. sliceOnto = process.binding("smalloc").sliceOnto # verify allocation b = alloc(5, {}) assert.ok typeof b is "object" i = 0 while i < 5 assert.ok b[i] isnt `undefined` i++ b = {} c = alloc(5, b) assert.equal b, c assert.deepEqual b, c b = alloc(5, {}) c = {} c._data = sliceOnto(b, c, 0, 5) assert.ok typeof c._data is "object" assert.equal b, c._data assert.deepEqual b, c._data # verify writes b = alloc(5, {}) i = 0 while i < 5 b[i] = i i++ i = 0 while i < 5 assert.equal b[i], i i++ b = alloc(1, Types.Uint8) b[0] = 256 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int8) b[0] = 128 assert.equal b[0], -128 assert.equal b[1], `undefined` b = alloc(1, Types.Uint16) b[0] = 65536 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int16) b[0] = 32768 assert.equal b[0], -32768 assert.equal b[1], `undefined` b = alloc(1, Types.Uint32) b[0] = 4294967296 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int32) b[0] = 2147483648 assert.equal b[0], -2147483648 assert.equal b[1], `undefined` b = alloc(1, Types.Float) b[0] = 0.1111111111111111 assert.equal b[0], 0.1111111119389534 assert.equal b[1], `undefined` b = alloc(1, Types.Double) b[0] = 0.1111111111111111 assert.equal b[0], 0.1111111111111111 assert.equal b[1], `undefined` b = alloc(1, Types.Uint8Clamped) b[0] = 300 assert.equal b[0], 255 assert.equal b[1], `undefined` b = alloc(6, {}) c0 = {} c1 = {} c0._data = sliceOnto(b, c0, 0, 3) c1._data = sliceOnto(b, c1, 3, 6) i = 0 while i < 3 c0[i] = i c1[i] = i + 3 i++ i = 0 while i < 3 assert.equal b[i], i i++ i = 3 while i < 6 assert.equal b[i], i i++ a = alloc(6, {}) b = alloc(6, {}) c = alloc(12, {}) i = 0 while i < 6 a[i] = i b[i] = i * 2 i++ copyOnto a, 0, c, 0, 6 copyOnto b, 0, c, 6, 6 i = 0 while i < 6 assert.equal c[i], i assert.equal c[i + 6], i * 2 i++ b = alloc(1, Types.Double) c = alloc(2, Types.Uint32) if os.endianness() is "LE" c[0] = 2576980378 c[1] = 1069128089 else c[0] = 1069128089 c[1] = 2576980378 copyOnto c, 0, b, 0, 2 assert.equal b[0], 0.1 b = alloc(1, Types.Uint16) c = alloc(2, Types.Uint8) c[0] = c[1] = 0xff copyOnto c, 0, b, 0, 2 assert.equal b[0], 0xffff b = alloc(2, Types.Uint8) c = alloc(1, Types.Uint16) c[0] = 0xffff copyOnto c, 0, b, 0, 1 assert.equal b[0], 0xff assert.equal b[1], 0xff # verify checking external if has external memory # check objects b = {} assert.ok not smalloc.hasExternalData(b) alloc 1, b assert.ok smalloc.hasExternalData(b) f = -> alloc 1, f assert.ok smalloc.hasExternalData(f) # and non-objects assert.ok not smalloc.hasExternalData(true) assert.ok not smalloc.hasExternalData(1) assert.ok not smalloc.hasExternalData("string") assert.ok not smalloc.hasExternalData(null) assert.ok not smalloc.hasExternalData() # verify alloc throws properly # arrays are not supported assert.throws (-> alloc 0, [] return ), TypeError # no allocations larger than kMaxLength assert.throws (-> alloc kMaxLength + 1 return ), RangeError # properly convert to uint32 before checking overflow assert.throws (-> alloc -1 return ), RangeError # no allocating on what's been allocated assert.throws (-> alloc 1, alloc(1) return ), TypeError # throw for values passed that are not objects assert.throws (-> alloc 1, "a" return ), TypeError assert.throws (-> alloc 1, true return ), TypeError assert.throws (-> alloc 1, null return ), TypeError # should not throw allocating to most objects alloc 1, -> alloc 1, /abc/ alloc 1, new Date() # range check on external array enumeration assert.throws (-> alloc 1, 0 return ), TypeError assert.throws (-> alloc 1, 10 return ), TypeError # very copyOnto throws properly # source must have data assert.throws (-> copyOnto {}, 0, alloc(1), 0, 0 return ), Error # dest must have data assert.throws (-> copyOnto alloc(1), 0, {}, 0, 0 return ), Error # copyLength <= sourceLength assert.throws (-> copyOnto alloc(1), 0, alloc(3), 0, 2 return ), RangeError # copyLength <= destLength assert.throws (-> copyOnto alloc(3), 0, alloc(1), 0, 2 return ), RangeError # sourceStart <= sourceLength assert.throws (-> copyOnto alloc(1), 3, alloc(1), 0, 1 return ), RangeError # destStart <= destLength assert.throws (-> copyOnto alloc(1), 0, alloc(1), 3, 1 return ), RangeError # sourceStart + copyLength <= sourceLength assert.throws (-> copyOnto alloc(3), 1, alloc(3), 0, 3 return ), RangeError # destStart + copyLength <= destLength assert.throws (-> copyOnto alloc(3), 0, alloc(3), 1, 3 return ), RangeError # copy_length * array_size <= dest_length assert.throws (-> copyOnto alloc(2, Types.Double), 0, alloc(2, Types.Uint32), 0, 2 return ), RangeError # test disposal b = alloc(5, {}) dispose b i = 0 while i < 5 assert.equal b[i], `undefined` i++ # verify dispose throws properly # only allow object to be passed to dispose assert.throws -> smalloc.dispose null return # can't dispose a Buffer assert.throws -> smalloc.dispose new Buffer() return assert.throws -> smalloc.dispose new Uint8Array(new ArrayBuffer(1)) return assert.throws -> smalloc.dispose {} return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") os = require("os") # first grab js api's smalloc = require("smalloc") alloc = smalloc.alloc dispose = smalloc.dispose copyOnto = smalloc.copyOnto kMaxLength = smalloc.kMaxLength Types = smalloc.Types # sliceOnto is volatile and cannot be exposed to users. sliceOnto = process.binding("smalloc").sliceOnto # verify allocation b = alloc(5, {}) assert.ok typeof b is "object" i = 0 while i < 5 assert.ok b[i] isnt `undefined` i++ b = {} c = alloc(5, b) assert.equal b, c assert.deepEqual b, c b = alloc(5, {}) c = {} c._data = sliceOnto(b, c, 0, 5) assert.ok typeof c._data is "object" assert.equal b, c._data assert.deepEqual b, c._data # verify writes b = alloc(5, {}) i = 0 while i < 5 b[i] = i i++ i = 0 while i < 5 assert.equal b[i], i i++ b = alloc(1, Types.Uint8) b[0] = 256 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int8) b[0] = 128 assert.equal b[0], -128 assert.equal b[1], `undefined` b = alloc(1, Types.Uint16) b[0] = 65536 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int16) b[0] = 32768 assert.equal b[0], -32768 assert.equal b[1], `undefined` b = alloc(1, Types.Uint32) b[0] = 4294967296 assert.equal b[0], 0 assert.equal b[1], `undefined` b = alloc(1, Types.Int32) b[0] = 2147483648 assert.equal b[0], -2147483648 assert.equal b[1], `undefined` b = alloc(1, Types.Float) b[0] = 0.1111111111111111 assert.equal b[0], 0.1111111119389534 assert.equal b[1], `undefined` b = alloc(1, Types.Double) b[0] = 0.1111111111111111 assert.equal b[0], 0.1111111111111111 assert.equal b[1], `undefined` b = alloc(1, Types.Uint8Clamped) b[0] = 300 assert.equal b[0], 255 assert.equal b[1], `undefined` b = alloc(6, {}) c0 = {} c1 = {} c0._data = sliceOnto(b, c0, 0, 3) c1._data = sliceOnto(b, c1, 3, 6) i = 0 while i < 3 c0[i] = i c1[i] = i + 3 i++ i = 0 while i < 3 assert.equal b[i], i i++ i = 3 while i < 6 assert.equal b[i], i i++ a = alloc(6, {}) b = alloc(6, {}) c = alloc(12, {}) i = 0 while i < 6 a[i] = i b[i] = i * 2 i++ copyOnto a, 0, c, 0, 6 copyOnto b, 0, c, 6, 6 i = 0 while i < 6 assert.equal c[i], i assert.equal c[i + 6], i * 2 i++ b = alloc(1, Types.Double) c = alloc(2, Types.Uint32) if os.endianness() is "LE" c[0] = 2576980378 c[1] = 1069128089 else c[0] = 1069128089 c[1] = 2576980378 copyOnto c, 0, b, 0, 2 assert.equal b[0], 0.1 b = alloc(1, Types.Uint16) c = alloc(2, Types.Uint8) c[0] = c[1] = 0xff copyOnto c, 0, b, 0, 2 assert.equal b[0], 0xffff b = alloc(2, Types.Uint8) c = alloc(1, Types.Uint16) c[0] = 0xffff copyOnto c, 0, b, 0, 1 assert.equal b[0], 0xff assert.equal b[1], 0xff # verify checking external if has external memory # check objects b = {} assert.ok not smalloc.hasExternalData(b) alloc 1, b assert.ok smalloc.hasExternalData(b) f = -> alloc 1, f assert.ok smalloc.hasExternalData(f) # and non-objects assert.ok not smalloc.hasExternalData(true) assert.ok not smalloc.hasExternalData(1) assert.ok not smalloc.hasExternalData("string") assert.ok not smalloc.hasExternalData(null) assert.ok not smalloc.hasExternalData() # verify alloc throws properly # arrays are not supported assert.throws (-> alloc 0, [] return ), TypeError # no allocations larger than kMaxLength assert.throws (-> alloc kMaxLength + 1 return ), RangeError # properly convert to uint32 before checking overflow assert.throws (-> alloc -1 return ), RangeError # no allocating on what's been allocated assert.throws (-> alloc 1, alloc(1) return ), TypeError # throw for values passed that are not objects assert.throws (-> alloc 1, "a" return ), TypeError assert.throws (-> alloc 1, true return ), TypeError assert.throws (-> alloc 1, null return ), TypeError # should not throw allocating to most objects alloc 1, -> alloc 1, /abc/ alloc 1, new Date() # range check on external array enumeration assert.throws (-> alloc 1, 0 return ), TypeError assert.throws (-> alloc 1, 10 return ), TypeError # very copyOnto throws properly # source must have data assert.throws (-> copyOnto {}, 0, alloc(1), 0, 0 return ), Error # dest must have data assert.throws (-> copyOnto alloc(1), 0, {}, 0, 0 return ), Error # copyLength <= sourceLength assert.throws (-> copyOnto alloc(1), 0, alloc(3), 0, 2 return ), RangeError # copyLength <= destLength assert.throws (-> copyOnto alloc(3), 0, alloc(1), 0, 2 return ), RangeError # sourceStart <= sourceLength assert.throws (-> copyOnto alloc(1), 3, alloc(1), 0, 1 return ), RangeError # destStart <= destLength assert.throws (-> copyOnto alloc(1), 0, alloc(1), 3, 1 return ), RangeError # sourceStart + copyLength <= sourceLength assert.throws (-> copyOnto alloc(3), 1, alloc(3), 0, 3 return ), RangeError # destStart + copyLength <= destLength assert.throws (-> copyOnto alloc(3), 0, alloc(3), 1, 3 return ), RangeError # copy_length * array_size <= dest_length assert.throws (-> copyOnto alloc(2, Types.Double), 0, alloc(2, Types.Uint32), 0, 2 return ), RangeError # test disposal b = alloc(5, {}) dispose b i = 0 while i < 5 assert.equal b[i], `undefined` i++ # verify dispose throws properly # only allow object to be passed to dispose assert.throws -> smalloc.dispose null return # can't dispose a Buffer assert.throws -> smalloc.dispose new Buffer() return assert.throws -> smalloc.dispose new Uint8Array(new ArrayBuffer(1)) return assert.throws -> smalloc.dispose {} return
[ { "context": "eady ->\n $submit = $('#submit')\n username = $('#username').val()\n token = $('#token').val()\n $password =", "end": 71, "score": 0.7704900503158569, "start": 63, "tag": "USERNAME", "value": "username" }, { "context": "').val()\n token = $('#token').val()\n $password = $('#password')\n $password2 = $('#password2')\n $('#reset-pass", "end": 134, "score": 0.975525975227356, "start": 122, "tag": "PASSWORD", "value": "$('#password" }, { "context": ")\n $password = $('#password')\n $password2 = $('#password2')\n $('#reset-password').submit ->\n if $passwo", "end": 165, "score": 0.9930719137191772, "start": 156, "tag": "PASSWORD", "value": "password2" }, { "context": " disableButton($submit)\n data =\n username: username\n token: token\n password: $password.val(", "end": 371, "score": 0.9991650581359863, "start": 363, "tag": "USERNAME", "value": "username" } ]
app/assets/javascripts/resetPassword.coffee
ojny/oj_web
2
$(document).ready -> $submit = $('#submit') username = $('#username').val() token = $('#token').val() $password = $('#password') $password2 = $('#password2') $('#reset-password').submit -> if $password.val() != $password2.val() toastr.error "Passwords are different." return false disableButton($submit) data = username: username token: token password: $password.val() $.ajax url: '/account/password/reset' type: 'post' contentType: 'application/json' data: JSON.stringify(data) success: (ret) -> if ret['status'] toastr.error ret['message'] else toastr.success 'Password reset successfully. Please use the new password to login.' setTimeout( -> window.location = '/account/login' , 1000) return false enableButton($submit) return false
159978
$(document).ready -> $submit = $('#submit') username = $('#username').val() token = $('#token').val() $password = <PASSWORD>') $password2 = $('#<PASSWORD>') $('#reset-password').submit -> if $password.val() != $password2.val() toastr.error "Passwords are different." return false disableButton($submit) data = username: username token: token password: $password.val() $.ajax url: '/account/password/reset' type: 'post' contentType: 'application/json' data: JSON.stringify(data) success: (ret) -> if ret['status'] toastr.error ret['message'] else toastr.success 'Password reset successfully. Please use the new password to login.' setTimeout( -> window.location = '/account/login' , 1000) return false enableButton($submit) return false
true
$(document).ready -> $submit = $('#submit') username = $('#username').val() token = $('#token').val() $password = PI:PASSWORD:<PASSWORD>END_PI') $password2 = $('#PI:PASSWORD:<PASSWORD>END_PI') $('#reset-password').submit -> if $password.val() != $password2.val() toastr.error "Passwords are different." return false disableButton($submit) data = username: username token: token password: $password.val() $.ajax url: '/account/password/reset' type: 'post' contentType: 'application/json' data: JSON.stringify(data) success: (ret) -> if ret['status'] toastr.error ret['message'] else toastr.success 'Password reset successfully. Please use the new password to login.' setTimeout( -> window.location = '/account/login' , 1000) return false enableButton($submit) return false
[ { "context": "ase\n username: userCookie\n password: passwordCookie\n .then ->\n Promise.resolve()\n else", "end": 871, "score": 0.9978507161140442, "start": 857, "tag": "PASSWORD", "value": "passwordCookie" } ]
_attachments/app/models/User.coffee
Coconut-Data/coconut-mobile
0
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ global.Cookie = require 'js-cookie' class User extends Backbone.Model url: "/user" username: -> @get("_id").replace(/^user\./,"") district: -> @get("district") isAdmin: -> _(@get("roles")).include "admin" hasRole: (role) -> _(@get("roles")).include role nameOrUsername: -> @get("name") or @username() User.isAuthenticated = -> Coconut.validateDatabase() .catch (error) -> # See if we have cookies that can login userCookie = Cookie.get('current_user') passwordCookie = Cookie.get('current_password') console.log "Trying to login with cookies" if userCookie and userCookie isnt "" and passwordCookie and passwordCookie isnt "" Coconut.openDatabase username: userCookie password: passwordCookie .then -> Promise.resolve() else throw "No saved user, must login" .then => if Coconut.currentUser? Promise.resolve() else throw "No current user" User.login = (options) -> new Promise (resolve) => user = new User _id: "user.#{options.username}" user.fetch success: => console.log "SETTING COOKIES" Coconut.currentUser = user Cookie.set('current_user', user.username()) Cookie.set('current_password', options.password) resolve() error: (error) => throw error User.logout = -> Cookie.set('current_user',"") Cookie.set('current_password',"") Coconut.currentUser = null module.exports = User
160705
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ global.Cookie = require 'js-cookie' class User extends Backbone.Model url: "/user" username: -> @get("_id").replace(/^user\./,"") district: -> @get("district") isAdmin: -> _(@get("roles")).include "admin" hasRole: (role) -> _(@get("roles")).include role nameOrUsername: -> @get("name") or @username() User.isAuthenticated = -> Coconut.validateDatabase() .catch (error) -> # See if we have cookies that can login userCookie = Cookie.get('current_user') passwordCookie = Cookie.get('current_password') console.log "Trying to login with cookies" if userCookie and userCookie isnt "" and passwordCookie and passwordCookie isnt "" Coconut.openDatabase username: userCookie password: <PASSWORD> .then -> Promise.resolve() else throw "No saved user, must login" .then => if Coconut.currentUser? Promise.resolve() else throw "No current user" User.login = (options) -> new Promise (resolve) => user = new User _id: "user.#{options.username}" user.fetch success: => console.log "SETTING COOKIES" Coconut.currentUser = user Cookie.set('current_user', user.username()) Cookie.set('current_password', options.password) resolve() error: (error) => throw error User.logout = -> Cookie.set('current_user',"") Cookie.set('current_password',"") Coconut.currentUser = null module.exports = User
true
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ global.Cookie = require 'js-cookie' class User extends Backbone.Model url: "/user" username: -> @get("_id").replace(/^user\./,"") district: -> @get("district") isAdmin: -> _(@get("roles")).include "admin" hasRole: (role) -> _(@get("roles")).include role nameOrUsername: -> @get("name") or @username() User.isAuthenticated = -> Coconut.validateDatabase() .catch (error) -> # See if we have cookies that can login userCookie = Cookie.get('current_user') passwordCookie = Cookie.get('current_password') console.log "Trying to login with cookies" if userCookie and userCookie isnt "" and passwordCookie and passwordCookie isnt "" Coconut.openDatabase username: userCookie password: PI:PASSWORD:<PASSWORD>END_PI .then -> Promise.resolve() else throw "No saved user, must login" .then => if Coconut.currentUser? Promise.resolve() else throw "No current user" User.login = (options) -> new Promise (resolve) => user = new User _id: "user.#{options.username}" user.fetch success: => console.log "SETTING COOKIES" Coconut.currentUser = user Cookie.set('current_user', user.username()) Cookie.set('current_password', options.password) resolve() error: (error) => throw error User.logout = -> Cookie.set('current_user',"") Cookie.set('current_password',"") Coconut.currentUser = null module.exports = User
[ { "context": "art of butterfly\n#\n# butterfly Copyright (C) 2014 Florian Mounier\n# This program is free software: you can redistri", "end": 106, "score": 0.9998512268066406, "start": 91, "tag": "NAME", "value": "Florian Mounier" } ]
butterfly/coffees/main.coffee
binRick/thc.digital
0
# *-* coding: utf-8 *-* # This file is part of butterfly # # butterfly Copyright (C) 2014 Florian Mounier # 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 <http://www.gnu.org/licenses/>. cols = rows = null quit = false openTs = (new Date()).getTime() $ = document.querySelectorAll.bind(document) document.addEventListener 'DOMContentLoaded', -> send = (data) -> ws.send 'S' + data ctl = (type, args...) -> params = args.join(',') if type == 'Resize' ws.send 'R' + params if location.protocol == 'https:' wsUrl = 'wss://' else wsUrl = 'ws://' wsUrl += document.location.host + '/ws' + location.pathname ws = new WebSocket wsUrl ws.addEventListener 'open', -> console.log "WebSocket open", arguments ws.send 'R' + term.cols + ',' + term.rows openTs = (new Date()).getTime() ws.addEventListener 'error', -> console.log "WebSocket error", arguments lastData = '' t_queue = null queue = '' ws.addEventListener 'message', (e) -> clearTimeout t_queue if t_queue queue += e.data if term.stop queue = queue.slice -10 * 1024 if queue.length > term.buffSize treat() else t_queue = setTimeout treat, 1 treat = -> term.write queue if term.stop term.stop = false term.body.classList.remove 'stopped' queue = '' ws.addEventListener 'close', -> console.log "WebSocket closed", arguments setTimeout -> term.write 'Closed' # Allow quick reload term.skipNextKey = true term.body.classList.add('dead') , 1 quit = true # Don't autoclose if websocket didn't last 1 minute if (new Date()).getTime() - openTs > 60 * 1000 open('','_self').close() term = new Terminal document.body, send, ctl addEventListener 'beforeunload', -> if not quit 'This will exit the terminal session' term.ws = ws window.butterfly = term window.bench = (n=100000000) -> rnd = '' while rnd.length < n rnd += Math.random().toString(36).substring(2) console.time('bench') console.profile('bench') term.write rnd console.profileEnd() console.timeEnd('bench') window.cbench = (n=100000000) -> rnd = '' while rnd.length < n rnd += "\x1b[#{30 + parseInt(Math.random() * 20)}m" rnd += Math.random().toString(36).substring(2) console.time('cbench') console.profile('cbench') term.write rnd console.profileEnd() console.timeEnd('cbench')
128673
# *-* coding: utf-8 *-* # This file is part of butterfly # # butterfly Copyright (C) 2014 <NAME> # 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 <http://www.gnu.org/licenses/>. cols = rows = null quit = false openTs = (new Date()).getTime() $ = document.querySelectorAll.bind(document) document.addEventListener 'DOMContentLoaded', -> send = (data) -> ws.send 'S' + data ctl = (type, args...) -> params = args.join(',') if type == 'Resize' ws.send 'R' + params if location.protocol == 'https:' wsUrl = 'wss://' else wsUrl = 'ws://' wsUrl += document.location.host + '/ws' + location.pathname ws = new WebSocket wsUrl ws.addEventListener 'open', -> console.log "WebSocket open", arguments ws.send 'R' + term.cols + ',' + term.rows openTs = (new Date()).getTime() ws.addEventListener 'error', -> console.log "WebSocket error", arguments lastData = '' t_queue = null queue = '' ws.addEventListener 'message', (e) -> clearTimeout t_queue if t_queue queue += e.data if term.stop queue = queue.slice -10 * 1024 if queue.length > term.buffSize treat() else t_queue = setTimeout treat, 1 treat = -> term.write queue if term.stop term.stop = false term.body.classList.remove 'stopped' queue = '' ws.addEventListener 'close', -> console.log "WebSocket closed", arguments setTimeout -> term.write 'Closed' # Allow quick reload term.skipNextKey = true term.body.classList.add('dead') , 1 quit = true # Don't autoclose if websocket didn't last 1 minute if (new Date()).getTime() - openTs > 60 * 1000 open('','_self').close() term = new Terminal document.body, send, ctl addEventListener 'beforeunload', -> if not quit 'This will exit the terminal session' term.ws = ws window.butterfly = term window.bench = (n=100000000) -> rnd = '' while rnd.length < n rnd += Math.random().toString(36).substring(2) console.time('bench') console.profile('bench') term.write rnd console.profileEnd() console.timeEnd('bench') window.cbench = (n=100000000) -> rnd = '' while rnd.length < n rnd += "\x1b[#{30 + parseInt(Math.random() * 20)}m" rnd += Math.random().toString(36).substring(2) console.time('cbench') console.profile('cbench') term.write rnd console.profileEnd() console.timeEnd('cbench')
true
# *-* coding: utf-8 *-* # This file is part of butterfly # # butterfly Copyright (C) 2014 PI:NAME:<NAME>END_PI # 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 <http://www.gnu.org/licenses/>. cols = rows = null quit = false openTs = (new Date()).getTime() $ = document.querySelectorAll.bind(document) document.addEventListener 'DOMContentLoaded', -> send = (data) -> ws.send 'S' + data ctl = (type, args...) -> params = args.join(',') if type == 'Resize' ws.send 'R' + params if location.protocol == 'https:' wsUrl = 'wss://' else wsUrl = 'ws://' wsUrl += document.location.host + '/ws' + location.pathname ws = new WebSocket wsUrl ws.addEventListener 'open', -> console.log "WebSocket open", arguments ws.send 'R' + term.cols + ',' + term.rows openTs = (new Date()).getTime() ws.addEventListener 'error', -> console.log "WebSocket error", arguments lastData = '' t_queue = null queue = '' ws.addEventListener 'message', (e) -> clearTimeout t_queue if t_queue queue += e.data if term.stop queue = queue.slice -10 * 1024 if queue.length > term.buffSize treat() else t_queue = setTimeout treat, 1 treat = -> term.write queue if term.stop term.stop = false term.body.classList.remove 'stopped' queue = '' ws.addEventListener 'close', -> console.log "WebSocket closed", arguments setTimeout -> term.write 'Closed' # Allow quick reload term.skipNextKey = true term.body.classList.add('dead') , 1 quit = true # Don't autoclose if websocket didn't last 1 minute if (new Date()).getTime() - openTs > 60 * 1000 open('','_self').close() term = new Terminal document.body, send, ctl addEventListener 'beforeunload', -> if not quit 'This will exit the terminal session' term.ws = ws window.butterfly = term window.bench = (n=100000000) -> rnd = '' while rnd.length < n rnd += Math.random().toString(36).substring(2) console.time('bench') console.profile('bench') term.write rnd console.profileEnd() console.timeEnd('bench') window.cbench = (n=100000000) -> rnd = '' while rnd.length < n rnd += "\x1b[#{30 + parseInt(Math.random() * 20)}m" rnd += Math.random().toString(36).substring(2) console.time('cbench') console.profile('cbench') term.write rnd console.profileEnd() console.timeEnd('cbench')
[ { "context": " (Darwin)\nComment: GPGTools - http://gpgtools.org\n\nowEBRAK7/ZANAwACAS/gHEVDSNo5AcsbYgBTBq2LR28gcmV0cm8gbGlrZSBXb3hp\nZHUKiQIVAwUAUwatiy/gHEVDSNo5AQIjZA/+M9tnFjf0EOVOwUHYS6AYfk6rpgoP\nSJcGNxpflU6nMA92AiMexlp7iyBPe7ZklkDclMNAaxelR6e9jLIEckm9qq6qw0vP\ni5XhbwJnqVh0cYn+AG/PKrlxZk6ULpmFw2MRfcnftW6f3H5W1b59SvBGaUtZ1dx7\nWzbGYvyPeyWHCEPoQgcv+mi5GRx4V76PLE5GdLdQdB0giCF9OqlVTcT0UFqfhJ3/\nsc5u/Olyokk7RAFjC9qoEMsGTJcF1A5Rk5PVfaS9O/UbFkxsU/uqRx6Lb3hyjNf5\n7c2hl7qGVOuZk6RSC3/jEZbbHhiSAd01LOS5TgQRaToZa4+NX8oXwWBc8Oa4iva4\ngHbgusStDjsUCXl8IWS8xogryQbxxnhC9cNdmdnBWZwQJufZXlK7BgQyRiBSTlap\nyBKxX1oP1iMIlLuVT8KsbSAHBjREPv9weHGjzJEjIhLT+RcW56vWaL5qTwOWOOXi\nFDtyU0zLcBIxDIGxYb1eAMBWavpWp6mwqNOkFrSggOgsH/Myg", "end": 944, "score": 0.9990478157997131, "start": 360, "tag": "KEY", "value": "owEBRAK7/ZANAwACAS/gHEVDSNo5AcsbYgBTBq2LR28gcmV0cm8gbGlrZSBXb3hp\nZHUKiQIVAwUAUwatiy/gHEVDSNo5AQIjZA/+M9tnFjf0EOVOwUHYS6AYfk6rpgoP\nSJcGNxpflU6nMA92AiMexlp7iyBPe7ZklkDclMNAaxelR6e9jLIEckm9qq6qw0vP\ni5XhbwJnqVh0cYn+AG/PKrlxZk6ULpmFw2MRfcnftW6f3H5W1b59SvBGaUtZ1dx7\nWzbGYvyPeyWHCEPoQgcv+mi5GRx4V76PLE5GdLdQdB0giCF9OqlVTcT0UFqfhJ3/\nsc5u/Olyokk7RAFjC9qoEMsGTJcF1A5Rk5PVfaS9O/UbFkxsU/uqRx6Lb3hyjNf5\n7c2hl7qGVOuZk6RSC3/jEZbbHhiSAd01LOS5TgQRaToZa4+NX8oXwWBc8Oa4iva4\ngHbgusStDjsUCXl8IWS8xogryQbxxnhC9cNdmdnBWZwQJufZXlK7BgQyRiBSTlap\nyBKxX1oP1iMIlLuVT8KsbSAHBjREPv9weHGjzJEjIhLT+RcW56vWaL5qTwOWOOXi" }, { "context": "VT8KsbSAHBjREPv9weHGjzJEjIhLT+RcW56vWaL5qTwOWOOXi\nFDtyU0zLcBIxDIGxYb1eAMBWavpWp6mwqNOkFrSggOgsH/MygLQ5lshgCrYBu36q\ne4ED3iMdzAI6fV5jaDvYRQRLjBSdzl+JCAbIf/pLLP8H8Pl3/CVgS96M6ztq7Gsc\nm2FCDrioktpkjzM4VBw6UVipPmvAYHQ5BxQIFZ6gFdE9JkIF45o50QnmNd3BTizT\noAn9gpIRZacCPbs=\n=63G5\n-----END PGP MESSAGE-----\n\"\"\",\n key : \"\"\"\n----", "end": 1162, "score": 0.9986677169799805, "start": 945, "tag": "KEY", "value": "FDtyU0zLcBIxDIGxYb1eAMBWavpWp6mwqNOkFrSggOgsH/MygLQ5lshgCrYBu36q\ne4ED3iMdzAI6fV5jaDvYRQRLjBSdzl+JCAbIf/pLLP8H8Pl3/CVgS96M6ztq7Gsc\nm2FCDrioktpkjzM4VBw6UVipPmvAYHQ5BxQIFZ6gFdE9JkIF45o50QnmNd3BTizT\noAn9gpIRZacCPbs=\n=63G5" }, { "context": " (Darwin)\nComment: GPGTools - http://gpgtools.org\n\nmQINBFJPT88BEADJWa60OpECivzsrEXx9Bx+X7h9HKdTjFS/QTdndv/CPuTjGeuk\n5vlme5ePqXzRnB1hag7BDmvZjiVhzSWBlbzJKfSWGySe/to+mA4AjldZkzCnKeBt\nGWsxJvu9+HWsfJp2/fNKyTMyL2VWThyhqJERrLtH/WK/CSA6ohV2f4/ZW/JN+mVp\nukUDIuNgHVcFV2c6AXNQLnHBB/xcAMdxRofbaw2anjDE+TM1C2aoIJY1aBtGPlZ1\nwdcaIbrvzIW5xKA3Wv2ERPRYnJutZLb6fPLnrXJrOyvPocOwRNhcZs/s2g46y00B\n1yPVvdntuvNuhIMSmEbd3NCxXykA+KgtZw7SXbYTwC68L9nfjR2CGYJDyyTQMHwq\ndWEQcmETLqjtV2CDnuEspEg8pWZPHe/ImHhLP72unES6/oN/8xDlejd4tCJCAVE4\nuY5UraTu4e4TN3B69x9j13hioFdfb7Jv9BNujB9axcZ7n63mkDQ2bBE7Y6KUtpr0\nclTit8lxDqKAOJXgFxG+U/Y/xllxqNrY8+IJpVgzuFpU+O4Y6p1jaZMY5pweGLv4\nggE8MD//FDsQNwcxDLRQKCxqYUYGQCKl2U33W1+KR85S0v84Emc1PlfdjGO7aMft\nvNladhBMjXRrUjL19NgMsLaFVNHKEP6lE+vQFejyqsXIXf4S1lHPfJT2dwARAQAB\ntCBNYXh3ZWxsIEtyb2huIDx0aGVtYXhAZ21haWwuY29tPokCQQQTAQIAKwIbLwUJ\nB4YfgAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AFAlKrwa0CGQEACgkQY4R7S4OT\nDwxFIhAAsvZyxDEmqkQPUW5s41PMbCM/QLJhCAzeVtz6sZN0sfj7JQAQfP0PEzsG\n0vm9tqpGt1xhjQxThcduFrSutHDYLeY56ptpKpvkOHmXhLrGoGjwOFHL/SBdkV/O\nWqMN5FgABw+LDmrPMA1zJ8/fbk4AoTopM7Ch4aKJ9WRdJliWUcteXXkuPX9lbzbE\na9uMUYtcMtnZ0tcHQ1SSSafO7AGS2wrOLIG+jzHx4Lfs8G6hAe3EB0Gq0lhpeJEz\n15fNjsOFNLf1fjqsnYer+k2hHdZ1q+tKmyVylBYdpu1q8XXSSEx3agBhVbl5iBTO\n+d36+4MAyYafehE41Fu/bdVt0QjjUuhwTd+VwP39YnNvnPjWnF5D18RLQR0l8Cd9\nKflptsxJ0W28TfyUSyZ1QCoIpA8hUwmydliZWoDK+YIm07mJkLvk9goofpRZyRFD\n0Xq4nP3CggL3t6DvHNqdvlsSc1gSM1cgPTVrYSmvyu23KWHXvEYfn/DKz1Yr0cj4\n2pNyl0UGCCoa25xjo5c+JTaALGCPQ0UwlSBX1Q3F1l7E/ayBZyVAroZ/y0lgKdh3\nIZtYRE9LBqDWVAZ6z2t4Eup7B+yGjXZQbjXmQ6BqJ4Lm0h2wm8kj1P8bC9Dw5OKG\nFFCuDmcyX5bEc7IEkF7y3pOT3RwCTE7k+puDul37BJw3rQ2SUMm0HE1heCBLcm9o\nbiA8dGhlbWF4QGdtYWlsLmNvbT6JAj4EEwECACgFAlJPT88CGy8FCQeGH4AGCwkI\nBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEGOEe0uDkw8MRXoQAMZ0zCx55D2J77ON\nHH0XzIAz28woxBcDfpOpvUJ2BPfmFV8Y3G63Yjzs7QKQQJtDzGWOJxS3YaYYgM7+\nHDXbjIzqy6LYUfyvGKJYdV8oQir+sXeZlPMomGzYG///4kV9YAS8CZZ92Fk+m0e5\nGg3jtV8rrQo/j0HBsXBNXdA52h7314Wa4Mm9bkpOVcST4hv25liKlAvVHvOWHWK+\nM/5vv9aSm0TVp1vPIL83eCFyBlQPmVZiHuQ2JvHnMDTWA4wsFJe6a0g6gjiSx/pv\n4zQ6zgAN7I74GIZsRs9+m6KCsVC8oiFSPuVjB7kGXAvDEhqDxYsP42Vyi3nHsS6W\niduMXk/MsqYL2ZbanVCex5I9LethOZiSkHMhDG9wGB+pxu4wSFGQUK4wxLV6wBFE\nuEpwZ70ZbDO0xgBUlQW0W7B71OHjeC8rrqVuuRoiHWB9GcVbm/Gs2NjTN10zf1YV\nSjtYJ8SvdthtkChIwRtrLPVINm7aegxGwRNVqJVxySfDUU1EtfHSf4dUBvulapwc\n6Ch2uvADeS4IDxB2AxgXVokCDOYQfirw22CBpFA2p8OwZwNOhjACMbHOtBEn/Egh\ny3c9JqYFN+INVsWJjbLQtLQlzZSPSm09++VZFrEzoIfDG3utzKJk/NbVyP37Pp4L\nemaUmg2jEvHmOPdXVnFi8i8Du1npuQINBFJPT88BEADT34Gl3bjm93joOH5DCujj\nd/7cpBuOxkYm5ZsxKa7wlMB489yUm1TpsXFuNvPWFqFckhJFW7vgUg3mCurK1fv9\nEjpZu1JD29V+1ZnbHNOEr5FLP+fDG/gbMykRRYBfscnpuqSiCQ7uDiVX0fivyUXb\nVOlzHkV8pgkgllyLHUBzosxkq5EmhPzWObTnuJZrxZD8JYPED1jZf8J4QCyMFDHC\nvn1PY1HnUM2lKuL04WNfjiukIhx0EcTNY4M8PIO3J+nyn5QxTC9J3SKFonkRH2Ft\ntTkWb6fQYlKBw0PejJ94o6GWyvfbLFh9B9WFB2WrfSH+cCqyj1CzLLz8BjnWysN8\ncZzo1cVxzwLsz36+NaeM6Wv6Ja9oFaw0KE+NdYuZ4Qp69yqzVuukyaeTCGqEJP4H\nrPqEQB9diMVotWKGq2tpGKQgBlR9QlJSZqW+a1ikQcBwAZ/sLSszppD0/CQU1upO\nV4Lk7FhYbaGs0I9aANj8zX83GcHrj5dN1uT7eFMCGBjr5C+SQWoxD1F5FzC/+32L\nEeDaaPI9mYE5IKN0rbcEqpShP0LualBDyJszlfELWs5LrdBW7Ay28VqjST2ai+w1\n2pxSFf6ii49jF+I2W5lXoYtY/8OhuoRh2bA4I5ONaSJs16Dwl87z1LUZlO0+ziRU\nSFk84TyioykwPKLmLUPf5QARAQABiQREBBgBAgAPBQJST0/PAhsuBQkHhh+AAikJ\nEGOEe0uDkw8MwV0gBBkBAgAGBQJST0/PAAoJEC/gHEVDSNo5OYwQAKnwVn7t/sLS\nSe9WvHY7W7Y3BixRRygTtdkhVkaC+WoWZJ8RgwXlM8d620x61aHAxCiwho5FTc/7\nmoB6WFPyUMfPWWEVNfwvYkwL+I/DC1jDdwpQlMeR7xdK7DOU2q6ypN9xzz9Cfj1N\nITKa2X609yKooMNKdE+dSA0iII3hYRy9OCXHjQsdDTQK4OPRFqgo02ZVO6kLwwa3\nNY9dvtm1GUFgEIomgFnN8qjOaKZcIcKp11HDvqDqsBJw96w0n", "end": 4705, "score": 0.9995616674423218, "start": 1326, "tag": "KEY", "value": "mQINBFJPT88BEADJWa60OpECivzsrEXx9Bx+X7h9HKdTjFS/QTdndv/CPuTjGeuk\n5vlme5ePqXzRnB1hag7BDmvZjiVhzSWBlbzJKfSWGySe/to+mA4AjldZkzCnKeBt\nGWsxJvu9+HWsfJp2/fNKyTMyL2VWThyhqJERrLtH/WK/CSA6ohV2f4/ZW/JN+mVp\nukUDIuNgHVcFV2c6AXNQLnHBB/xcAMdxRofbaw2anjDE+TM1C2aoIJY1aBtGPlZ1\nwdcaIbrvzIW5xKA3Wv2ERPRYnJutZLb6fPLnrXJrOyvPocOwRNhcZs/s2g46y00B\n1yPVvdntuvNuhIMSmEbd3NCxXykA+KgtZw7SXbYTwC68L9nfjR2CGYJDyyTQMHwq\ndWEQcmETLqjtV2CDnuEspEg8pWZPHe/ImHhLP72unES6/oN/8xDlejd4tCJCAVE4\nuY5UraTu4e4TN3B69x9j13hioFdfb7Jv9BNujB9axcZ7n63mkDQ2bBE7Y6KUtpr0\nclTit8lxDqKAOJXgFxG+U/Y/xllxqNrY8+IJpVgzuFpU+O4Y6p1jaZMY5pweGLv4\nggE8MD//FDsQNwcxDLRQKCxqYUYGQCKl2U33W1+KR85S0v84Emc1PlfdjGO7aMft\nvNladhBMjXRrUjL19NgMsLaFVNHKEP6lE+vQFejyqsXIXf4S1lHPfJT2dwARAQAB\ntCBNYXh3ZWxsIEtyb2huIDx0aGVtYXhAZ21haWwuY29tPokCQQQTAQIAKwIbLwUJ\nB4YfgAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AFAlKrwa0CGQEACgkQY4R7S4OT\nDwxFIhAAsvZyxDEmqkQPUW5s41PMbCM/QLJhCAzeVtz6sZN0sfj7JQAQfP0PEzsG\n0vm9tqpGt1xhjQxThcduFrSutHDYLeY56ptpKpvkOHmXhLrGoGjwOFHL/SBdkV/O\nWqMN5FgABw+LDmrPMA1zJ8/fbk4AoTopM7Ch4aKJ9WRdJliWUcteXXkuPX9lbzbE\na9uMUYtcMtnZ0tcHQ1SSSafO7AGS2wrOLIG+jzHx4Lfs8G6hAe3EB0Gq0lhpeJEz\n15fNjsOFNLf1fjqsnYer+k2hHdZ1q+tKmyVylBYdpu1q8XXSSEx3agBhVbl5iBTO\n+d36+4MAyYafehE41Fu/bdVt0QjjUuhwTd+VwP39YnNvnPjWnF5D18RLQR0l8Cd9\nKflptsxJ0W28TfyUSyZ1QCoIpA8hUwmydliZWoDK+YIm07mJkLvk9goofpRZyRFD\n0Xq4nP3CggL3t6DvHNqdvlsSc1gSM1cgPTVrYSmvyu23KWHXvEYfn/DKz1Yr0cj4\n2pNyl0UGCCoa25xjo5c+JTaALGCPQ0UwlSBX1Q3F1l7E/ayBZyVAroZ/y0lgKdh3\nIZtYRE9LBqDWVAZ6z2t4Eup7B+yGjXZQbjXmQ6BqJ4Lm0h2wm8kj1P8bC9Dw5OKG\nFFCuDmcyX5bEc7IEkF7y3pOT3RwCTE7k+puDul37BJw3rQ2SUMm0HE1heCBLcm9o\nbiA8dGhlbWF4QGdtYWlsLmNvbT6JAj4EEwECACgFAlJPT88CGy8FCQeGH4AGCwkI\nBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEGOEe0uDkw8MRXoQAMZ0zCx55D2J77ON\nHH0XzIAz28woxBcDfpOpvUJ2BPfmFV8Y3G63Yjzs7QKQQJtDzGWOJxS3YaYYgM7+\nHDXbjIzqy6LYUfyvGKJYdV8oQir+sXeZlPMomGzYG///4kV9YAS8CZZ92Fk+m0e5\nGg3jtV8rrQo/j0HBsXBNXdA52h7314Wa4Mm9bkpOVcST4hv25liKlAvVHvOWHWK+\nM/5vv9aSm0TVp1vPIL83eCFyBlQPmVZiHuQ2JvHnMDTWA4wsFJe6a0g6gjiSx/pv\n4zQ6zgAN7I74GIZsRs9+m6KCsVC8oiFSPuVjB7kGXAvDEhqDxYsP42Vyi3nHsS6W\niduMXk/MsqYL2ZbanVCex5I9LethOZiSkHMhDG9wGB+pxu4wSFGQUK4wxLV6wBFE\nuEpwZ70ZbDO0xgBUlQW0W7B71OHjeC8rrqVuuRoiHWB9GcVbm/Gs2NjTN10zf1YV\nSjtYJ8SvdthtkChIwRtrLPVINm7aegxGwRNVqJVxySfDUU1EtfHSf4dUBvulapwc\n6Ch2uvADeS4IDxB2AxgXVokCDOYQfirw22CBpFA2p8OwZwNOhjACMbHOtBEn/Egh\ny3c9JqYFN+INVsWJjbLQtLQlzZSPSm09++VZFrEzoIfDG3utzKJk/NbVyP37Pp4L\nemaUmg2jEvHmOPdXVnFi8i8Du1npuQINBFJPT88BEADT34Gl3bjm93joOH5DCujj\nd/7cpBuOxkYm5ZsxKa7wlMB489yUm1TpsXFuNvPWFqFckhJFW7vgUg3mCurK1fv9\nEjpZu1JD29V+1ZnbHNOEr5FLP+fDG/gbMykRRYBfscnpuqSiCQ7uDiVX0fivyUXb\nVOlzHkV8pgkgllyLHUBzosxkq5EmhPzWObTnuJZrxZD8JYPED1jZf8J4QCyMFDHC\nvn1PY1HnUM2lKuL04WNfjiukIhx0EcTNY4M8PIO3J+nyn5QxTC9J3SKFonkRH2Ft\ntTkWb6fQYlKBw0PejJ94o6GWyvfbLFh9B9WFB2WrfSH+cCqyj1CzLLz8BjnWysN8\ncZzo1cVxzwLsz36+NaeM6Wv6Ja9oFaw0KE+NdYuZ4Qp69yqzVuukyaeTCGqEJP4H\nrPqEQB9diMVotWKGq2tpGKQgBlR9QlJSZqW+a1ikQcBwAZ/sLSszppD0/CQU1upO\nV4Lk7FhYbaGs0I9aANj8zX83GcHrj5dN1uT7eFMCGBjr5C+SQWoxD1F5FzC/+32L\nEeDaaPI9mYE5IKN0rbcEqpShP0LualBDyJszlfELWs5LrdBW7Ay28VqjST2ai+w1\n2pxSFf6ii49jF+I2W5lXoYtY/8OhuoRh2bA4I5ONaSJs16Dwl87z1LUZlO0+ziRU\nSFk84TyioykwPKLmLUPf5QARAQABiQREBBgBAgAPBQJST0/PAhsuBQkHhh+AAikJ\nEGOEe0uDkw8MwV0gBBkBAgAGBQJST0/PAAoJEC/gHEVDSNo5OYwQAKnwVn7t/sLS\nSe9WvHY7W7Y3BixRRygTtdkhVkaC+WoWZJ8RgwXlM8d620x61aHAxCiwho5FTc/7\nmoB6WFPyUMfPWWEVNfwvYkwL+I/DC1jDdwpQlMeR7xdK7DOU2q6ypN9xzz9Cfj1N\nITKa2X609yKooMNKdE+dSA0iII3hYRy9OCXHjQsdDTQK4OPRFqgo02ZVO6kLwwa3" }, { "context": "KdE+dSA0iII3hYRy9OCXHjQsdDTQK4OPRFqgo02ZVO6kLwwa3\nNY9dvtm1GUFgEIomgFnN8qjOaKZcIcKp11HDvqDqsBJw96w0nESG817/dkzeEva9\ngjSzrMjLyfaGoj1CfjfXaom6xJ/pXogzCSyz+/yxOx4aKAyYfZHWFf9qzRk7xLbL\nvwXLU4r1tnYbmZMojWi8qLttrTG252XlxujOkMzwY/C2QIBDVxrL8XJTAEfcJ8BN\nJ1Jt3H+edmBInKmVT7EwSX+CUxFjmJO+csfX6hmck3jSXG+ZUpk4d7c8OwHQQIE1\nr2Qdj8tEZucwA7ApQ8oEa7jZiIx4ACxVs1KAFv6yZCPWqrXzXdwHcU763i7uS4Ny\nvRoz6B53l3wiIBtGsc/yBB26J0I57v8dGW5boUhlWz1NXG/jUVgcWPlzv/gPrMBg\n5nvs9zy5P4eVfBktytcc6rW6IFqVTkIQrSghjGA/8gWK0ll0N0tO4p3auw24meet\nOfqonLDQUh/xzEKFMJMoU8K16sKaGneOjzgQALzuYHCzsYwAj0YX1724FVOnsrmW\nySME2r69kxHR2lcF8ttyLt1yGqTmM+/14KFHk75Wxbz8Ipjk48mpgGOGqfGvd3rn\nLCc0izqPxPLU/RQIK2OibqWeyKkn4E+h7WfIzIWQMInFGKITSeX+q9DeCar+ROWR\nt3XXZ16c3QzfFF5SvK+YfV8fxCpMjrLYGUxEgl8NZKERRSpXcniNqHlZHyYiAa/Z\nQQG8rg4mu0eQjMSAqQtgkWKOIdLUmdzhLppceWIoRpg9de1TU6YHNbFhJuRMO1n3\nwqhaz47M19Pj6C7jAdsf3y085SWr+vIRt4V42/7b2eBEjH0U1DFBjhOJgPTS8XaJ\n8LAL8VVZDTJvKK59qCjWHSGe927nHqnDeHzXVxYW49xs3UzSimkZqO+61XY8ShfH\ns0geyDwX7755XCqYspzDcQnDoAU0HOzuUUWIDPNX88ahFFb8P9zRCpOK1y4UnrrH\nO54iZmn6gp+OY7WASw2DXk/iJCOlYIWal2LcXOrg2wgOPOkExaqY26rhbQd5WUrp\nFe/whzJIT6wUIKyq0MSFIFjrxp6lsLCUXPaS4C+v6Nu5PQFMoDnKHgnz1nAYDzsI\nVps55e2p7JL3Pu7HnEoBO/VtegT0a4blfk+x02vcDCvVEC590secx3y9hmMPHuuj\n7lu5/Zw+Z6JiUl0p\n=TUk8\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n },\n {\n sig", "end": 5904, "score": 0.998394787311554, "start": 4706, "tag": "KEY", "value": "NY9dvtm1GUFgEIomgFnN8qjOaKZcIcKp11HDvqDqsBJw96w0nESG817/dkzeEva9\ngjSzrMjLyfaGoj1CfjfXaom6xJ/pXogzCSyz+/yxOx4aKAyYfZHWFf9qzRk7xLbL\nvwXLU4r1tnYbmZMojWi8qLttrTG252XlxujOkMzwY/C2QIBDVxrL8XJTAEfcJ8BN\nJ1Jt3H+edmBInKmVT7EwSX+CUxFjmJO+csfX6hmck3jSXG+ZUpk4d7c8OwHQQIE1\nr2Qdj8tEZucwA7ApQ8oEa7jZiIx4ACxVs1KAFv6yZCPWqrXzXdwHcU763i7uS4Ny\nvRoz6B53l3wiIBtGsc/yBB26J0I57v8dGW5boUhlWz1NXG/jUVgcWPlzv/gPrMBg\n5nvs9zy5P4eVfBktytcc6rW6IFqVTkIQrSghjGA/8gWK0ll0N0tO4p3auw24meet\nOfqonLDQUh/xzEKFMJMoU8K16sKaGneOjzgQALzuYHCzsYwAj0YX1724FVOnsrmW\nySME2r69kxHR2lcF8ttyLt1yGqTmM+/14KFHk75Wxbz8Ipjk48mpgGOGqfGvd3rn\nLCc0izqPxPLU/RQIK2OibqWeyKkn4E+h7WfIzIWQMInFGKITSeX+q9DeCar+ROWR\nt3XXZ16c3QzfFF5SvK+YfV8fxCpMjrLYGUxEgl8NZKERRSpXcniNqHlZHyYiAa/Z\nQQG8rg4mu0eQjMSAqQtgkWKOIdLUmdzhLppceWIoRpg9de1TU6YHNbFhJuRMO1n3\nwqhaz47M19Pj6C7jAdsf3y085SWr+vIRt4V42/7b2eBEjH0U1DFBjhOJgPTS8XaJ\n8LAL8VVZDTJvKK59qCjWHSGe927nHqnDeHzXVxYW49xs3UzSimkZqO+61XY8ShfH\ns0geyDwX7755XCqYspzDcQnDoAU0HOzuUUWIDPNX88ahFFb8P9zRCpOK1y4UnrrH\nO54iZmn6gp+OY7WASw2DXk/iJCOlYIWal2LcXOrg2wgOPOkExaqY26rhbQd5WUrp\nFe/whzJIT6wUIKyq0MSFIFjrxp6lsLCUXPaS4C+v6Nu5PQFMoDnKHgnz1nAYDzsI\nVps55e2p7JL3Pu7HnEoBO/VtegT0a4blfk+x02vcDCvVEC590secx3y9hmMPHuuj\n7lu5/Zw+Z6JiUl0p\n=TUk8\n-----" }, { "context": "(Darwin)\nComment: GPGTools - http://gpgtools.org\n\nowGbwMvMwCRo/tx/CuOhxzMYT0snMQSzrVByz1coSi0pylfIycxOVQjPr8hMKeXq\nsGdmBcvClAsyyagyzFNVDN3Ut0R7yV7Wkj0bkl4z7VzcdJhhvqea9W6B3F2ltuFG\n+yZ9s1R9rHazFgA=\n=HIJN\n-----END PGP MESSAGE-----\n\"\"\",\n\n key : \"", "end": 6216, "score": 0.9662269949913025, "start": 6070, "tag": "KEY", "value": "owGbwMvMwCRo/tx/CuOhxzMYT0snMQSzrVByz1coSi0pylfIycxOVQjPr8hMKeXq\nsGdmBcvClAsyyagyzFNVDN3Ut0R7yV7Wkj0bkl4z7VzcdJhhvqea9W6B3F2ltuFG\n+yZ9s1R9rHazFgA=" }, { "context": " (Darwin)\nComment: GPGTools - http://gpgtools.org\n\nmQGiBFMFX/YRBACKwOOj7dkyHb8J3qDOvS0ZEcgiZnFCaLCh07GWV/S/HEelVaDF\nBIVdn2Ho/j80HWkRMJAFqNBoEfqqz1n6MFxZNgUlWOOSdUIkOq2qcZhqQqcvwqJU\nFxKKO7gKI037HBYlgmgD2/LGAWGZQDHDciDqcy+SEwvFB+y/x9bSSCornwCgnVzp\nC77KgeXIS26JtbMeNd7x+xkD/3NjzK0jF3v7fASE2Eik+VlGiXkk8IuV32LYAtkd\nQyjw+Xqx6T3gtOEPOJWd0MlOdb75J/EMJYN+10yMCIFgMTUexL4uVRKMRBy3JBwW\nkHApO+LG/2g5ZHupaqBixfcpya5N1T+sNNlPQ1pvCTANakp1ELR2BAb6g5PGuQab\nscboA/9LsjYMdTqXQVCj9ck0+kSFxeBygobDqQIwd4BW2fMRzRg7kFZdICtzYSSi\n2z9iHmzC+OiokPKHnVSYRKSZ5cHe/ke2SunptKzpFhWxKO5FYRODX3txvEMUUst+\nFE1f/+dnLQyxY5BB1fRcpUlUtRZ453lObMm0aY652bgyW/6CSLQ3R2VvcmdlcyBC\nZW5qYW1pbiBDbGVtZW5jZWF1IChwdyBpcyAnYWJjZCcpIDxnYmNAZ292LmZyPoho\nBBMRAgAoBQJTBV/2AhsDBQkSzAMABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAK\nCRA350+UAcLjmJWYAKCYHsrgY+k3bQ7ov2XHf9SjX7qUtwCfebPu3y0/Ll7OdCw5\nfcXuzbCUbjY=\n=FQCZ\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n }\n]\n\n#==", "end": 7187, "score": 0.9939741492271423, "start": 6389, "tag": "KEY", "value": "mQGiBFMFX/YRBACKwOOj7dkyHb8J3qDOvS0ZEcgiZnFCaLCh07GWV/S/HEelVaDF\nBIVdn2Ho/j80HWkRMJAFqNBoEfqqz1n6MFxZNgUlWOOSdUIkOq2qcZhqQqcvwqJU\nFxKKO7gKI037HBYlgmgD2/LGAWGZQDHDciDqcy+SEwvFB+y/x9bSSCornwCgnVzp\nC77KgeXIS26JtbMeNd7x+xkD/3NjzK0jF3v7fASE2Eik+VlGiXkk8IuV32LYAtkd\nQyjw+Xqx6T3gtOEPOJWd0MlOdb75J/EMJYN+10yMCIFgMTUexL4uVRKMRBy3JBwW\nkHApO+LG/2g5ZHupaqBixfcpya5N1T+sNNlPQ1pvCTANakp1ELR2BAb6g5PGuQab\nscboA/9LsjYMdTqXQVCj9ck0+kSFxeBygobDqQIwd4BW2fMRzRg7kFZdICtzYSSi\n2z9iHmzC+OiokPKHnVSYRKSZ5cHe/ke2SunptKzpFhWxKO5FYRODX3txvEMUUst+\nFE1f/+dnLQyxY5BB1fRcpUlUtRZ453lObMm0aY652bgyW/6CSLQ3R2VvcmdlcyBC\nZW5qYW1pbiBDbGVtZW5jZWF1IChwdyBpcyAnYWJjZCcpIDxnYmNAZ292LmZyPoho\nBBMRAgAoBQJTBV/2AhsDBQkSzAMABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAK\nCRA350+UAcLjmJWYAKCYHsrgY+k3bQ7ov2XHf9SjX7qUtwCfebPu3y0/Ll7OdCw5\nfcXuzbCUbjY=\n=FQCZ" } ]
test/files/sig_v3.iced
johnnyRose/kbpgp
1
testing_unixtime = Math.floor(new Date(2014, 2, 20)/1000) {KeyManager} = require '../../' {do_message,Processor} = require '../../lib/openpgp/processor' #================================================================== sigs = [ { sig : """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org owEBRAK7/ZANAwACAS/gHEVDSNo5AcsbYgBTBq2LR28gcmV0cm8gbGlrZSBXb3hp ZHUKiQIVAwUAUwatiy/gHEVDSNo5AQIjZA/+M9tnFjf0EOVOwUHYS6AYfk6rpgoP SJcGNxpflU6nMA92AiMexlp7iyBPe7ZklkDclMNAaxelR6e9jLIEckm9qq6qw0vP i5XhbwJnqVh0cYn+AG/PKrlxZk6ULpmFw2MRfcnftW6f3H5W1b59SvBGaUtZ1dx7 WzbGYvyPeyWHCEPoQgcv+mi5GRx4V76PLE5GdLdQdB0giCF9OqlVTcT0UFqfhJ3/ sc5u/Olyokk7RAFjC9qoEMsGTJcF1A5Rk5PVfaS9O/UbFkxsU/uqRx6Lb3hyjNf5 7c2hl7qGVOuZk6RSC3/jEZbbHhiSAd01LOS5TgQRaToZa4+NX8oXwWBc8Oa4iva4 gHbgusStDjsUCXl8IWS8xogryQbxxnhC9cNdmdnBWZwQJufZXlK7BgQyRiBSTlap yBKxX1oP1iMIlLuVT8KsbSAHBjREPv9weHGjzJEjIhLT+RcW56vWaL5qTwOWOOXi FDtyU0zLcBIxDIGxYb1eAMBWavpWp6mwqNOkFrSggOgsH/MygLQ5lshgCrYBu36q e4ED3iMdzAI6fV5jaDvYRQRLjBSdzl+JCAbIf/pLLP8H8Pl3/CVgS96M6ztq7Gsc m2FCDrioktpkjzM4VBw6UVipPmvAYHQ5BxQIFZ6gFdE9JkIF45o50QnmNd3BTizT oAn9gpIRZacCPbs= =63G5 -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org mQINBFJPT88BEADJWa60OpECivzsrEXx9Bx+X7h9HKdTjFS/QTdndv/CPuTjGeuk 5vlme5ePqXzRnB1hag7BDmvZjiVhzSWBlbzJKfSWGySe/to+mA4AjldZkzCnKeBt GWsxJvu9+HWsfJp2/fNKyTMyL2VWThyhqJERrLtH/WK/CSA6ohV2f4/ZW/JN+mVp ukUDIuNgHVcFV2c6AXNQLnHBB/xcAMdxRofbaw2anjDE+TM1C2aoIJY1aBtGPlZ1 wdcaIbrvzIW5xKA3Wv2ERPRYnJutZLb6fPLnrXJrOyvPocOwRNhcZs/s2g46y00B 1yPVvdntuvNuhIMSmEbd3NCxXykA+KgtZw7SXbYTwC68L9nfjR2CGYJDyyTQMHwq dWEQcmETLqjtV2CDnuEspEg8pWZPHe/ImHhLP72unES6/oN/8xDlejd4tCJCAVE4 uY5UraTu4e4TN3B69x9j13hioFdfb7Jv9BNujB9axcZ7n63mkDQ2bBE7Y6KUtpr0 clTit8lxDqKAOJXgFxG+U/Y/xllxqNrY8+IJpVgzuFpU+O4Y6p1jaZMY5pweGLv4 ggE8MD//FDsQNwcxDLRQKCxqYUYGQCKl2U33W1+KR85S0v84Emc1PlfdjGO7aMft vNladhBMjXRrUjL19NgMsLaFVNHKEP6lE+vQFejyqsXIXf4S1lHPfJT2dwARAQAB tCBNYXh3ZWxsIEtyb2huIDx0aGVtYXhAZ21haWwuY29tPokCQQQTAQIAKwIbLwUJ B4YfgAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AFAlKrwa0CGQEACgkQY4R7S4OT DwxFIhAAsvZyxDEmqkQPUW5s41PMbCM/QLJhCAzeVtz6sZN0sfj7JQAQfP0PEzsG 0vm9tqpGt1xhjQxThcduFrSutHDYLeY56ptpKpvkOHmXhLrGoGjwOFHL/SBdkV/O WqMN5FgABw+LDmrPMA1zJ8/fbk4AoTopM7Ch4aKJ9WRdJliWUcteXXkuPX9lbzbE a9uMUYtcMtnZ0tcHQ1SSSafO7AGS2wrOLIG+jzHx4Lfs8G6hAe3EB0Gq0lhpeJEz 15fNjsOFNLf1fjqsnYer+k2hHdZ1q+tKmyVylBYdpu1q8XXSSEx3agBhVbl5iBTO +d36+4MAyYafehE41Fu/bdVt0QjjUuhwTd+VwP39YnNvnPjWnF5D18RLQR0l8Cd9 KflptsxJ0W28TfyUSyZ1QCoIpA8hUwmydliZWoDK+YIm07mJkLvk9goofpRZyRFD 0Xq4nP3CggL3t6DvHNqdvlsSc1gSM1cgPTVrYSmvyu23KWHXvEYfn/DKz1Yr0cj4 2pNyl0UGCCoa25xjo5c+JTaALGCPQ0UwlSBX1Q3F1l7E/ayBZyVAroZ/y0lgKdh3 IZtYRE9LBqDWVAZ6z2t4Eup7B+yGjXZQbjXmQ6BqJ4Lm0h2wm8kj1P8bC9Dw5OKG FFCuDmcyX5bEc7IEkF7y3pOT3RwCTE7k+puDul37BJw3rQ2SUMm0HE1heCBLcm9o biA8dGhlbWF4QGdtYWlsLmNvbT6JAj4EEwECACgFAlJPT88CGy8FCQeGH4AGCwkI BwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEGOEe0uDkw8MRXoQAMZ0zCx55D2J77ON HH0XzIAz28woxBcDfpOpvUJ2BPfmFV8Y3G63Yjzs7QKQQJtDzGWOJxS3YaYYgM7+ HDXbjIzqy6LYUfyvGKJYdV8oQir+sXeZlPMomGzYG///4kV9YAS8CZZ92Fk+m0e5 Gg3jtV8rrQo/j0HBsXBNXdA52h7314Wa4Mm9bkpOVcST4hv25liKlAvVHvOWHWK+ M/5vv9aSm0TVp1vPIL83eCFyBlQPmVZiHuQ2JvHnMDTWA4wsFJe6a0g6gjiSx/pv 4zQ6zgAN7I74GIZsRs9+m6KCsVC8oiFSPuVjB7kGXAvDEhqDxYsP42Vyi3nHsS6W iduMXk/MsqYL2ZbanVCex5I9LethOZiSkHMhDG9wGB+pxu4wSFGQUK4wxLV6wBFE uEpwZ70ZbDO0xgBUlQW0W7B71OHjeC8rrqVuuRoiHWB9GcVbm/Gs2NjTN10zf1YV SjtYJ8SvdthtkChIwRtrLPVINm7aegxGwRNVqJVxySfDUU1EtfHSf4dUBvulapwc 6Ch2uvADeS4IDxB2AxgXVokCDOYQfirw22CBpFA2p8OwZwNOhjACMbHOtBEn/Egh y3c9JqYFN+INVsWJjbLQtLQlzZSPSm09++VZFrEzoIfDG3utzKJk/NbVyP37Pp4L emaUmg2jEvHmOPdXVnFi8i8Du1npuQINBFJPT88BEADT34Gl3bjm93joOH5DCujj d/7cpBuOxkYm5ZsxKa7wlMB489yUm1TpsXFuNvPWFqFckhJFW7vgUg3mCurK1fv9 EjpZu1JD29V+1ZnbHNOEr5FLP+fDG/gbMykRRYBfscnpuqSiCQ7uDiVX0fivyUXb VOlzHkV8pgkgllyLHUBzosxkq5EmhPzWObTnuJZrxZD8JYPED1jZf8J4QCyMFDHC vn1PY1HnUM2lKuL04WNfjiukIhx0EcTNY4M8PIO3J+nyn5QxTC9J3SKFonkRH2Ft tTkWb6fQYlKBw0PejJ94o6GWyvfbLFh9B9WFB2WrfSH+cCqyj1CzLLz8BjnWysN8 cZzo1cVxzwLsz36+NaeM6Wv6Ja9oFaw0KE+NdYuZ4Qp69yqzVuukyaeTCGqEJP4H rPqEQB9diMVotWKGq2tpGKQgBlR9QlJSZqW+a1ikQcBwAZ/sLSszppD0/CQU1upO V4Lk7FhYbaGs0I9aANj8zX83GcHrj5dN1uT7eFMCGBjr5C+SQWoxD1F5FzC/+32L EeDaaPI9mYE5IKN0rbcEqpShP0LualBDyJszlfELWs5LrdBW7Ay28VqjST2ai+w1 2pxSFf6ii49jF+I2W5lXoYtY/8OhuoRh2bA4I5ONaSJs16Dwl87z1LUZlO0+ziRU SFk84TyioykwPKLmLUPf5QARAQABiQREBBgBAgAPBQJST0/PAhsuBQkHhh+AAikJ EGOEe0uDkw8MwV0gBBkBAgAGBQJST0/PAAoJEC/gHEVDSNo5OYwQAKnwVn7t/sLS Se9WvHY7W7Y3BixRRygTtdkhVkaC+WoWZJ8RgwXlM8d620x61aHAxCiwho5FTc/7 moB6WFPyUMfPWWEVNfwvYkwL+I/DC1jDdwpQlMeR7xdK7DOU2q6ypN9xzz9Cfj1N ITKa2X609yKooMNKdE+dSA0iII3hYRy9OCXHjQsdDTQK4OPRFqgo02ZVO6kLwwa3 NY9dvtm1GUFgEIomgFnN8qjOaKZcIcKp11HDvqDqsBJw96w0nESG817/dkzeEva9 gjSzrMjLyfaGoj1CfjfXaom6xJ/pXogzCSyz+/yxOx4aKAyYfZHWFf9qzRk7xLbL vwXLU4r1tnYbmZMojWi8qLttrTG252XlxujOkMzwY/C2QIBDVxrL8XJTAEfcJ8BN J1Jt3H+edmBInKmVT7EwSX+CUxFjmJO+csfX6hmck3jSXG+ZUpk4d7c8OwHQQIE1 r2Qdj8tEZucwA7ApQ8oEa7jZiIx4ACxVs1KAFv6yZCPWqrXzXdwHcU763i7uS4Ny vRoz6B53l3wiIBtGsc/yBB26J0I57v8dGW5boUhlWz1NXG/jUVgcWPlzv/gPrMBg 5nvs9zy5P4eVfBktytcc6rW6IFqVTkIQrSghjGA/8gWK0ll0N0tO4p3auw24meet OfqonLDQUh/xzEKFMJMoU8K16sKaGneOjzgQALzuYHCzsYwAj0YX1724FVOnsrmW ySME2r69kxHR2lcF8ttyLt1yGqTmM+/14KFHk75Wxbz8Ipjk48mpgGOGqfGvd3rn LCc0izqPxPLU/RQIK2OibqWeyKkn4E+h7WfIzIWQMInFGKITSeX+q9DeCar+ROWR t3XXZ16c3QzfFF5SvK+YfV8fxCpMjrLYGUxEgl8NZKERRSpXcniNqHlZHyYiAa/Z QQG8rg4mu0eQjMSAqQtgkWKOIdLUmdzhLppceWIoRpg9de1TU6YHNbFhJuRMO1n3 wqhaz47M19Pj6C7jAdsf3y085SWr+vIRt4V42/7b2eBEjH0U1DFBjhOJgPTS8XaJ 8LAL8VVZDTJvKK59qCjWHSGe927nHqnDeHzXVxYW49xs3UzSimkZqO+61XY8ShfH s0geyDwX7755XCqYspzDcQnDoAU0HOzuUUWIDPNX88ahFFb8P9zRCpOK1y4UnrrH O54iZmn6gp+OY7WASw2DXk/iJCOlYIWal2LcXOrg2wgOPOkExaqY26rhbQd5WUrp Fe/whzJIT6wUIKyq0MSFIFjrxp6lsLCUXPaS4C+v6Nu5PQFMoDnKHgnz1nAYDzsI Vps55e2p7JL3Pu7HnEoBO/VtegT0a4blfk+x02vcDCvVEC590secx3y9hmMPHuuj 7lu5/Zw+Z6JiUl0p =TUk8 -----END PGP PUBLIC KEY BLOCK----- """ }, { sig : """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org owGbwMvMwCRo/tx/CuOhxzMYT0snMQSzrVByz1coSi0pylfIycxOVQjPr8hMKeXq sGdmBcvClAsyyagyzFNVDN3Ut0R7yV7Wkj0bkl4z7VzcdJhhvqea9W6B3F2ltuFG +yZ9s1R9rHazFgA= =HIJN -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org mQGiBFMFX/YRBACKwOOj7dkyHb8J3qDOvS0ZEcgiZnFCaLCh07GWV/S/HEelVaDF BIVdn2Ho/j80HWkRMJAFqNBoEfqqz1n6MFxZNgUlWOOSdUIkOq2qcZhqQqcvwqJU FxKKO7gKI037HBYlgmgD2/LGAWGZQDHDciDqcy+SEwvFB+y/x9bSSCornwCgnVzp C77KgeXIS26JtbMeNd7x+xkD/3NjzK0jF3v7fASE2Eik+VlGiXkk8IuV32LYAtkd Qyjw+Xqx6T3gtOEPOJWd0MlOdb75J/EMJYN+10yMCIFgMTUexL4uVRKMRBy3JBwW kHApO+LG/2g5ZHupaqBixfcpya5N1T+sNNlPQ1pvCTANakp1ELR2BAb6g5PGuQab scboA/9LsjYMdTqXQVCj9ck0+kSFxeBygobDqQIwd4BW2fMRzRg7kFZdICtzYSSi 2z9iHmzC+OiokPKHnVSYRKSZ5cHe/ke2SunptKzpFhWxKO5FYRODX3txvEMUUst+ FE1f/+dnLQyxY5BB1fRcpUlUtRZ453lObMm0aY652bgyW/6CSLQ3R2VvcmdlcyBC ZW5qYW1pbiBDbGVtZW5jZWF1IChwdyBpcyAnYWJjZCcpIDxnYmNAZ292LmZyPoho BBMRAgAoBQJTBV/2AhsDBQkSzAMABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAK CRA350+UAcLjmJWYAKCYHsrgY+k3bQ7ov2XHf9SjX7qUtwCfebPu3y0/Ll7OdCw5 fcXuzbCUbjY= =FQCZ -----END PGP PUBLIC KEY BLOCK----- """ } ] #================================================================== verify = ({sig,key}, T,cb) -> opts = now : testing_unixtime await KeyManager.import_from_armored_pgp { raw : key, opts }, defer err, km T.no_error err await do_message { armored : sig , keyfetch : km, now : testing_unixtime }, defer err T.no_error err cb() #-------------------------------- exports.verify = (T,cb) -> for sig in sigs await verify sig, T, defer() cb() #==================================================================
107241
testing_unixtime = Math.floor(new Date(2014, 2, 20)/1000) {KeyManager} = require '../../' {do_message,Processor} = require '../../lib/openpgp/processor' #================================================================== sigs = [ { sig : """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org <KEY> <KEY> -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org <KEY> <KEY>END PGP PUBLIC KEY BLOCK----- """ }, { sig : """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org <KEY> =HIJN -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org <KEY> -----END PGP PUBLIC KEY BLOCK----- """ } ] #================================================================== verify = ({sig,key}, T,cb) -> opts = now : testing_unixtime await KeyManager.import_from_armored_pgp { raw : key, opts }, defer err, km T.no_error err await do_message { armored : sig , keyfetch : km, now : testing_unixtime }, defer err T.no_error err cb() #-------------------------------- exports.verify = (T,cb) -> for sig in sigs await verify sig, T, defer() cb() #==================================================================
true
testing_unixtime = Math.floor(new Date(2014, 2, 20)/1000) {KeyManager} = require '../../' {do_message,Processor} = require '../../lib/openpgp/processor' #================================================================== sigs = [ { sig : """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PIEND PGP PUBLIC KEY BLOCK----- """ }, { sig : """ -----BEGIN PGP MESSAGE----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org PI:KEY:<KEY>END_PI =HIJN -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - http://gpgtools.org PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK----- """ } ] #================================================================== verify = ({sig,key}, T,cb) -> opts = now : testing_unixtime await KeyManager.import_from_armored_pgp { raw : key, opts }, defer err, km T.no_error err await do_message { armored : sig , keyfetch : km, now : testing_unixtime }, defer err T.no_error err cb() #-------------------------------- exports.verify = (T,cb) -> for sig in sigs await verify sig, T, defer() cb() #==================================================================
[ { "context": "pingFactor = 0.3;\n controls.keys = [65, 83, 68];\n controls.addEventListener('change'", "end": 9170, "score": 0.9166293740272522, "start": 9158, "tag": "KEY", "value": "65, 83, 68];" } ]
packages/custom/transparency/coffee/public/directives/austrianMapDirective.coffee
AnotherCodeArtist/medien-transparenz.at
3
'use strict' app = angular.module 'mean.transparency' app.directive 'austrianMap', ($rootScope, TPAService) -> restrict: 'EA' scope: data: '=' link: ($scope,element,attrs) -> $rootScope.showTooltip = true; initialized = false transferSums = {} json = {} mouse = new THREE.Vector2(); objects = []; onDocumentMouseDown = (e) -> debugMode = false; if debugMode console.log e event = e.originalEvent if debugMode console.log event event.preventDefault(); mouse3D = new THREE.Vector3(event.offsetX / event.target.clientWidth * 2 - 1, -(event.offsetY ) / event.target.clientHeight * 2 + 1, 1.0 ); mouse3D.unproject(camera); mouse3D.sub(camera.position); mouse3D.normalize(); raycaster = new THREE.Raycaster(camera.position, mouse3D ); if debugMode console.log 'camera' console.log camera.position console.log 'mouse' console.log mouse3D geometry = new THREE.Geometry(); geometry.vertices.push(raycaster.ray.origin); newV = new THREE.Vector3(raycaster.ray.direction.x, raycaster.ray.direction.y, raycaster.ray.direction.z); newV = newV.multiplyScalar(10000); newV = newV.add(raycaster.ray.origin); geometry.vertices.push(newV); line = new THREE.Line(geometry, materials.phong (new THREE.Color("rgb(241, 176, 0)"))); scene.add line intersects = raycaster.intersectObjects(objects); if ( intersects.length > 0 ) $rootScope.$broadcast 'federalStateClicked', intersects[0].object.userData.bundesland onDocumentMouseOver = (event) -> debugMode = false mouse3D = new THREE.Vector3(event.offsetX / event.target.clientWidth * 2 - 1, -(event.offsetY ) / event.target.clientHeight * 2 + 1, 1.0 ); mouse3D.unproject(camera); mouse3D.sub(camera.position); mouse3D.normalize(); raycaster = new THREE.Raycaster(camera.position, mouse3D ); if debugMode console.log 'camera' console.log camera.position console.log 'mouse' console.log mouse3D geometry = new THREE.Geometry(); geometry.vertices.push(raycaster.ray.origin); newV = new THREE.Vector3(raycaster.ray.direction.x, raycaster.ray.direction.y, raycaster.ray.direction.z); newV = newV.multiplyScalar(10000); newV = newV.add(raycaster.ray.origin); geometry.vertices.push(newV); line = new THREE.Line(geometry, materials.phongNotTransparent (new THREE.Color("rgb(241, 176, 0)"))); scene.add line intersects = raycaster.intersectObjects(objects); toolTipDiv = document.getElementById 'toolTip' if ( intersects.length > 0 ) ### for object in objects if object.userData.bundesland isnt intersects[0].object.userData.bundesland object.material = materials.phong(defaults.color({iso: object.userData.bundesland})); else object.material = materials.phongNotTransparent(defaults.color({iso: object.userData.bundesland})) render()### $rootScope.$broadcast 'isoChanged', transferSums[intersects[0].object.userData.bundesland] toolTipDiv.style.display = 'block'; left = event.clientX + "px"; top = event.clientY + "px"; toolTipDiv.style.left = left; toolTipDiv.style.top = top; if debugMode console.log intersects[0].object.userData.bundesland else toolTipDiv.style.display = 'none'; element.bind 'click', onDocumentMouseDown element[0].addEventListener 'mousemove', onDocumentMouseOver, false element.on('mouseleave', () -> document.getElementById 'toolTip' .style.display = 'none'; ###for object in objects object.material = materials.phong(defaults.color({iso: object.userData.bundesland})); render() ### ) #Store downloaded JSON in variable defaults = { color: (d) -> switch (d.iso) when "AT-1" then new THREE.Color(0,0,0) when "AT-2" then new THREE.Color(1,1,0) when "AT-3" then new THREE.Color(1,0,1) when "AT-4" then new THREE.Color(1,0,0) when "AT-5" then new THREE.Color(0,1,1) when "AT-6" then new THREE.Color(0,1,0) when "AT-7" then new THREE.Color(0,0,1) when "AT-8" then new THREE.Color(0,0,0) when "AT-9" then new THREE.Color(0,0,1) height: (d) -> transferSums[d.iso].height*250 } latest = { url: null color: null height: null } materials = { phong: (color) -> new THREE.MeshPhongMaterial({ color: color, side: THREE.DoubleSide, opacity: 0.5, transparent: true #phong : new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x000000, shininess: 60, shading: THREE.SmoothShading, transparent:true }), }) phongNotTransparent: (color) -> new THREE.MeshPhongMaterial({ color: color, side: THREE.DoubleSide }) meshLambert: (color) -> new THREE.MeshLambertMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, transparent:true }) meshWireFrame: (color) -> new THREE.MeshBasicMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, wireframe:true, transparent:true }) meshBasic: (color) -> new THREE.MeshBasicMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, transparent: true }); } if (!Detector.webgl) Detector.addGetWebGLMessage() container = {} camera = {} controls = {} scene = {} renderer = {} light = {} spotLight = {} ambientLight = {} cross = {} onWindowResize = () -> camera.aspect = container.clientWidth / container.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(container.clientWidth, container.clientHeight); controls.handleResize(); render() animate = () -> requestAnimationFrame(animate) controls.update() render = () -> renderer.render(scene, camera) init = () -> container = document.getElementById('webgl'); camera = new THREE.PerspectiveCamera( 80, container.clientWidth / container.clientHeight, 0.1, 10000); camera.position.set(0,-370,380) #camera.position.z = Math.min(container.clientWidth, container.clientHeight); camera.zoom = 0.7; controls = new THREE.TrackballControls(camera, container); controls.rotateSpeed = 1.0; controls.zoomSpeed = 1.2; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.keys = [65, 83, 68]; controls.addEventListener('change', render); #World scene = new THREE.Scene(); #Lights light = new THREE.DirectionalLight(0xffffff); light.position.set(1, 1, 1); scene.add(light); spotLight = new THREE.SpotLight(0xffffff); spotLight.position.set(-1000, -1000, 1000); spotLight.castShadow = true; scene.add(spotLight); ambientLight = new THREE.AmbientLight(0x333333); scene.add(ambientLight); #Renderer renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(container.clientWidth, container.clientHeight); container.appendChild(renderer.domElement); #Shadows renderer.shadowMap.enabled = true; renderer.shadowMapSoft = true; renderer.shadowCameraNear = 1; renderer.shadowCameraFar = camera.far; renderer.shadowCameraFov = 60; renderer.shadowMapBias = 0.0025; renderer.shadowMapDarkness = 0.5; renderer.shadowMapWidth = 1024; renderer.shadowMapHeight = 1024; renderer.setClearColor(0xffffff, 1); window.addEventListener('resize', onWindowResize, false); onWindowResize(); render(); update(); animate(); clearGroups = () -> if (json) if json.type is 'FeatureCollection' json.features.forEach (feature) -> scene.remove(scene.getObjectByName(feature.properties.iso)) else if (json.type is 'Topology') Object.keys(json.objects).forEach (key) -> json.objects[key].geometries.forEach (object) -> scene.remove(object._group) render() update = () -> width = container.clientWidth; height = container.clientHeight; #Read url from url textarea url = "/transparency/assets/data/oesterreich.json" d3.json(url, (data) -> json = data; clearGroups(); functions = {}; functions.color = defaults.color functions.height = defaults.height if (json.type is 'FeatureCollection') projection = getProjection(json, width, height) json.features.forEach (feature) -> group = addFeature(feature, projection, functions) feature._group = group render() else if (json.type is 'Topology') geojson = topojson.merge(json, json.objects[Object.keys(json.objects)[0]].geometries) projection = getProjection(geojson, width, height) Object.keys(json.objects).forEach (key) -> json.objects[key].geometries.forEach (object) -> feature = topojson.feature(json, object) group = addFeature(feature, projection, functions) object._group = group render() else console.log('This tutorial only renders TopoJSON and GeoJSON FeatureCollections')) addShape = (group, shape, extrudeSettings, material, color, x, y, z, rx, ry, rz, s, iso) -> geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings); mesh = new THREE.Mesh(geometry, materials[material](color)); #Add shadows mesh.castShadow = true; mesh.receiveShadow = true; mesh.position.set(x, y, z); mesh.rotation.set(rx, ry, rz); mesh.scale.set(s, s, s); mesh.userData.bundesland = iso objects.push mesh group.add(mesh); addFeature = (feature, projection, functions) -> group = new THREE.Group(); group.name = feature.properties.iso scene.add(group); color; amount; try color = functions.color(feature.properties); catch err console.log(err) try amount = functions.height(feature.properties); catch err console.log(err) extrudeSettings = { amount: amount, bevelEnabled: false }; material = 'phongNotTransparent'; iso = feature.properties.iso if (feature.geometry.type is 'Polygon') shape = createPolygonShape(feature.geometry.coordinates, projection) addShape(group, shape, extrudeSettings, material, color, 0, 0, amount, Math.PI, 0, 0, 1, iso) else if (feature.geometry.type is 'MultiPolygon') feature.geometry.coordinates.forEach (polygon) -> shape = createPolygonShape(polygon, projection) addShape(group, shape, extrudeSettings, material, color, 0, 0, amount, Math.PI, 0, 0, 1, iso) else console.log('This tutorial only renders Polygons and MultiPolygons') group dataUpdated = () -> if $scope.data and Object.keys($scope.data).length isnt 0 #transferSums = $scope.data maximum = Number.NEGATIVE_INFINITY sum = 0 for k,v of $scope.data if v.federalState != 'Unknown' sum += v.amount if v.amount > maximum maximum = v.amount for k,v of $scope.data if v.federalState != 'Unknown' transferSums[v.federalState] = {} transferSums[v.federalState].height = v.amount/parseFloat(maximum) transferSums[v.federalState].sum = v.amount transferSums[v.federalState].percent = (v.amount/sum)*100 transferSums[v.federalState].iso = v.federalState if !initialized init() render() initialized = true if initialized update() $scope.$watch 'data', dataUpdated
129926
'use strict' app = angular.module 'mean.transparency' app.directive 'austrianMap', ($rootScope, TPAService) -> restrict: 'EA' scope: data: '=' link: ($scope,element,attrs) -> $rootScope.showTooltip = true; initialized = false transferSums = {} json = {} mouse = new THREE.Vector2(); objects = []; onDocumentMouseDown = (e) -> debugMode = false; if debugMode console.log e event = e.originalEvent if debugMode console.log event event.preventDefault(); mouse3D = new THREE.Vector3(event.offsetX / event.target.clientWidth * 2 - 1, -(event.offsetY ) / event.target.clientHeight * 2 + 1, 1.0 ); mouse3D.unproject(camera); mouse3D.sub(camera.position); mouse3D.normalize(); raycaster = new THREE.Raycaster(camera.position, mouse3D ); if debugMode console.log 'camera' console.log camera.position console.log 'mouse' console.log mouse3D geometry = new THREE.Geometry(); geometry.vertices.push(raycaster.ray.origin); newV = new THREE.Vector3(raycaster.ray.direction.x, raycaster.ray.direction.y, raycaster.ray.direction.z); newV = newV.multiplyScalar(10000); newV = newV.add(raycaster.ray.origin); geometry.vertices.push(newV); line = new THREE.Line(geometry, materials.phong (new THREE.Color("rgb(241, 176, 0)"))); scene.add line intersects = raycaster.intersectObjects(objects); if ( intersects.length > 0 ) $rootScope.$broadcast 'federalStateClicked', intersects[0].object.userData.bundesland onDocumentMouseOver = (event) -> debugMode = false mouse3D = new THREE.Vector3(event.offsetX / event.target.clientWidth * 2 - 1, -(event.offsetY ) / event.target.clientHeight * 2 + 1, 1.0 ); mouse3D.unproject(camera); mouse3D.sub(camera.position); mouse3D.normalize(); raycaster = new THREE.Raycaster(camera.position, mouse3D ); if debugMode console.log 'camera' console.log camera.position console.log 'mouse' console.log mouse3D geometry = new THREE.Geometry(); geometry.vertices.push(raycaster.ray.origin); newV = new THREE.Vector3(raycaster.ray.direction.x, raycaster.ray.direction.y, raycaster.ray.direction.z); newV = newV.multiplyScalar(10000); newV = newV.add(raycaster.ray.origin); geometry.vertices.push(newV); line = new THREE.Line(geometry, materials.phongNotTransparent (new THREE.Color("rgb(241, 176, 0)"))); scene.add line intersects = raycaster.intersectObjects(objects); toolTipDiv = document.getElementById 'toolTip' if ( intersects.length > 0 ) ### for object in objects if object.userData.bundesland isnt intersects[0].object.userData.bundesland object.material = materials.phong(defaults.color({iso: object.userData.bundesland})); else object.material = materials.phongNotTransparent(defaults.color({iso: object.userData.bundesland})) render()### $rootScope.$broadcast 'isoChanged', transferSums[intersects[0].object.userData.bundesland] toolTipDiv.style.display = 'block'; left = event.clientX + "px"; top = event.clientY + "px"; toolTipDiv.style.left = left; toolTipDiv.style.top = top; if debugMode console.log intersects[0].object.userData.bundesland else toolTipDiv.style.display = 'none'; element.bind 'click', onDocumentMouseDown element[0].addEventListener 'mousemove', onDocumentMouseOver, false element.on('mouseleave', () -> document.getElementById 'toolTip' .style.display = 'none'; ###for object in objects object.material = materials.phong(defaults.color({iso: object.userData.bundesland})); render() ### ) #Store downloaded JSON in variable defaults = { color: (d) -> switch (d.iso) when "AT-1" then new THREE.Color(0,0,0) when "AT-2" then new THREE.Color(1,1,0) when "AT-3" then new THREE.Color(1,0,1) when "AT-4" then new THREE.Color(1,0,0) when "AT-5" then new THREE.Color(0,1,1) when "AT-6" then new THREE.Color(0,1,0) when "AT-7" then new THREE.Color(0,0,1) when "AT-8" then new THREE.Color(0,0,0) when "AT-9" then new THREE.Color(0,0,1) height: (d) -> transferSums[d.iso].height*250 } latest = { url: null color: null height: null } materials = { phong: (color) -> new THREE.MeshPhongMaterial({ color: color, side: THREE.DoubleSide, opacity: 0.5, transparent: true #phong : new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x000000, shininess: 60, shading: THREE.SmoothShading, transparent:true }), }) phongNotTransparent: (color) -> new THREE.MeshPhongMaterial({ color: color, side: THREE.DoubleSide }) meshLambert: (color) -> new THREE.MeshLambertMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, transparent:true }) meshWireFrame: (color) -> new THREE.MeshBasicMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, wireframe:true, transparent:true }) meshBasic: (color) -> new THREE.MeshBasicMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, transparent: true }); } if (!Detector.webgl) Detector.addGetWebGLMessage() container = {} camera = {} controls = {} scene = {} renderer = {} light = {} spotLight = {} ambientLight = {} cross = {} onWindowResize = () -> camera.aspect = container.clientWidth / container.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(container.clientWidth, container.clientHeight); controls.handleResize(); render() animate = () -> requestAnimationFrame(animate) controls.update() render = () -> renderer.render(scene, camera) init = () -> container = document.getElementById('webgl'); camera = new THREE.PerspectiveCamera( 80, container.clientWidth / container.clientHeight, 0.1, 10000); camera.position.set(0,-370,380) #camera.position.z = Math.min(container.clientWidth, container.clientHeight); camera.zoom = 0.7; controls = new THREE.TrackballControls(camera, container); controls.rotateSpeed = 1.0; controls.zoomSpeed = 1.2; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.keys = [<KEY> controls.addEventListener('change', render); #World scene = new THREE.Scene(); #Lights light = new THREE.DirectionalLight(0xffffff); light.position.set(1, 1, 1); scene.add(light); spotLight = new THREE.SpotLight(0xffffff); spotLight.position.set(-1000, -1000, 1000); spotLight.castShadow = true; scene.add(spotLight); ambientLight = new THREE.AmbientLight(0x333333); scene.add(ambientLight); #Renderer renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(container.clientWidth, container.clientHeight); container.appendChild(renderer.domElement); #Shadows renderer.shadowMap.enabled = true; renderer.shadowMapSoft = true; renderer.shadowCameraNear = 1; renderer.shadowCameraFar = camera.far; renderer.shadowCameraFov = 60; renderer.shadowMapBias = 0.0025; renderer.shadowMapDarkness = 0.5; renderer.shadowMapWidth = 1024; renderer.shadowMapHeight = 1024; renderer.setClearColor(0xffffff, 1); window.addEventListener('resize', onWindowResize, false); onWindowResize(); render(); update(); animate(); clearGroups = () -> if (json) if json.type is 'FeatureCollection' json.features.forEach (feature) -> scene.remove(scene.getObjectByName(feature.properties.iso)) else if (json.type is 'Topology') Object.keys(json.objects).forEach (key) -> json.objects[key].geometries.forEach (object) -> scene.remove(object._group) render() update = () -> width = container.clientWidth; height = container.clientHeight; #Read url from url textarea url = "/transparency/assets/data/oesterreich.json" d3.json(url, (data) -> json = data; clearGroups(); functions = {}; functions.color = defaults.color functions.height = defaults.height if (json.type is 'FeatureCollection') projection = getProjection(json, width, height) json.features.forEach (feature) -> group = addFeature(feature, projection, functions) feature._group = group render() else if (json.type is 'Topology') geojson = topojson.merge(json, json.objects[Object.keys(json.objects)[0]].geometries) projection = getProjection(geojson, width, height) Object.keys(json.objects).forEach (key) -> json.objects[key].geometries.forEach (object) -> feature = topojson.feature(json, object) group = addFeature(feature, projection, functions) object._group = group render() else console.log('This tutorial only renders TopoJSON and GeoJSON FeatureCollections')) addShape = (group, shape, extrudeSettings, material, color, x, y, z, rx, ry, rz, s, iso) -> geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings); mesh = new THREE.Mesh(geometry, materials[material](color)); #Add shadows mesh.castShadow = true; mesh.receiveShadow = true; mesh.position.set(x, y, z); mesh.rotation.set(rx, ry, rz); mesh.scale.set(s, s, s); mesh.userData.bundesland = iso objects.push mesh group.add(mesh); addFeature = (feature, projection, functions) -> group = new THREE.Group(); group.name = feature.properties.iso scene.add(group); color; amount; try color = functions.color(feature.properties); catch err console.log(err) try amount = functions.height(feature.properties); catch err console.log(err) extrudeSettings = { amount: amount, bevelEnabled: false }; material = 'phongNotTransparent'; iso = feature.properties.iso if (feature.geometry.type is 'Polygon') shape = createPolygonShape(feature.geometry.coordinates, projection) addShape(group, shape, extrudeSettings, material, color, 0, 0, amount, Math.PI, 0, 0, 1, iso) else if (feature.geometry.type is 'MultiPolygon') feature.geometry.coordinates.forEach (polygon) -> shape = createPolygonShape(polygon, projection) addShape(group, shape, extrudeSettings, material, color, 0, 0, amount, Math.PI, 0, 0, 1, iso) else console.log('This tutorial only renders Polygons and MultiPolygons') group dataUpdated = () -> if $scope.data and Object.keys($scope.data).length isnt 0 #transferSums = $scope.data maximum = Number.NEGATIVE_INFINITY sum = 0 for k,v of $scope.data if v.federalState != 'Unknown' sum += v.amount if v.amount > maximum maximum = v.amount for k,v of $scope.data if v.federalState != 'Unknown' transferSums[v.federalState] = {} transferSums[v.federalState].height = v.amount/parseFloat(maximum) transferSums[v.federalState].sum = v.amount transferSums[v.federalState].percent = (v.amount/sum)*100 transferSums[v.federalState].iso = v.federalState if !initialized init() render() initialized = true if initialized update() $scope.$watch 'data', dataUpdated
true
'use strict' app = angular.module 'mean.transparency' app.directive 'austrianMap', ($rootScope, TPAService) -> restrict: 'EA' scope: data: '=' link: ($scope,element,attrs) -> $rootScope.showTooltip = true; initialized = false transferSums = {} json = {} mouse = new THREE.Vector2(); objects = []; onDocumentMouseDown = (e) -> debugMode = false; if debugMode console.log e event = e.originalEvent if debugMode console.log event event.preventDefault(); mouse3D = new THREE.Vector3(event.offsetX / event.target.clientWidth * 2 - 1, -(event.offsetY ) / event.target.clientHeight * 2 + 1, 1.0 ); mouse3D.unproject(camera); mouse3D.sub(camera.position); mouse3D.normalize(); raycaster = new THREE.Raycaster(camera.position, mouse3D ); if debugMode console.log 'camera' console.log camera.position console.log 'mouse' console.log mouse3D geometry = new THREE.Geometry(); geometry.vertices.push(raycaster.ray.origin); newV = new THREE.Vector3(raycaster.ray.direction.x, raycaster.ray.direction.y, raycaster.ray.direction.z); newV = newV.multiplyScalar(10000); newV = newV.add(raycaster.ray.origin); geometry.vertices.push(newV); line = new THREE.Line(geometry, materials.phong (new THREE.Color("rgb(241, 176, 0)"))); scene.add line intersects = raycaster.intersectObjects(objects); if ( intersects.length > 0 ) $rootScope.$broadcast 'federalStateClicked', intersects[0].object.userData.bundesland onDocumentMouseOver = (event) -> debugMode = false mouse3D = new THREE.Vector3(event.offsetX / event.target.clientWidth * 2 - 1, -(event.offsetY ) / event.target.clientHeight * 2 + 1, 1.0 ); mouse3D.unproject(camera); mouse3D.sub(camera.position); mouse3D.normalize(); raycaster = new THREE.Raycaster(camera.position, mouse3D ); if debugMode console.log 'camera' console.log camera.position console.log 'mouse' console.log mouse3D geometry = new THREE.Geometry(); geometry.vertices.push(raycaster.ray.origin); newV = new THREE.Vector3(raycaster.ray.direction.x, raycaster.ray.direction.y, raycaster.ray.direction.z); newV = newV.multiplyScalar(10000); newV = newV.add(raycaster.ray.origin); geometry.vertices.push(newV); line = new THREE.Line(geometry, materials.phongNotTransparent (new THREE.Color("rgb(241, 176, 0)"))); scene.add line intersects = raycaster.intersectObjects(objects); toolTipDiv = document.getElementById 'toolTip' if ( intersects.length > 0 ) ### for object in objects if object.userData.bundesland isnt intersects[0].object.userData.bundesland object.material = materials.phong(defaults.color({iso: object.userData.bundesland})); else object.material = materials.phongNotTransparent(defaults.color({iso: object.userData.bundesland})) render()### $rootScope.$broadcast 'isoChanged', transferSums[intersects[0].object.userData.bundesland] toolTipDiv.style.display = 'block'; left = event.clientX + "px"; top = event.clientY + "px"; toolTipDiv.style.left = left; toolTipDiv.style.top = top; if debugMode console.log intersects[0].object.userData.bundesland else toolTipDiv.style.display = 'none'; element.bind 'click', onDocumentMouseDown element[0].addEventListener 'mousemove', onDocumentMouseOver, false element.on('mouseleave', () -> document.getElementById 'toolTip' .style.display = 'none'; ###for object in objects object.material = materials.phong(defaults.color({iso: object.userData.bundesland})); render() ### ) #Store downloaded JSON in variable defaults = { color: (d) -> switch (d.iso) when "AT-1" then new THREE.Color(0,0,0) when "AT-2" then new THREE.Color(1,1,0) when "AT-3" then new THREE.Color(1,0,1) when "AT-4" then new THREE.Color(1,0,0) when "AT-5" then new THREE.Color(0,1,1) when "AT-6" then new THREE.Color(0,1,0) when "AT-7" then new THREE.Color(0,0,1) when "AT-8" then new THREE.Color(0,0,0) when "AT-9" then new THREE.Color(0,0,1) height: (d) -> transferSums[d.iso].height*250 } latest = { url: null color: null height: null } materials = { phong: (color) -> new THREE.MeshPhongMaterial({ color: color, side: THREE.DoubleSide, opacity: 0.5, transparent: true #phong : new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x000000, shininess: 60, shading: THREE.SmoothShading, transparent:true }), }) phongNotTransparent: (color) -> new THREE.MeshPhongMaterial({ color: color, side: THREE.DoubleSide }) meshLambert: (color) -> new THREE.MeshLambertMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, transparent:true }) meshWireFrame: (color) -> new THREE.MeshBasicMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, wireframe:true, transparent:true }) meshBasic: (color) -> new THREE.MeshBasicMaterial({ color: color, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, transparent: true }); } if (!Detector.webgl) Detector.addGetWebGLMessage() container = {} camera = {} controls = {} scene = {} renderer = {} light = {} spotLight = {} ambientLight = {} cross = {} onWindowResize = () -> camera.aspect = container.clientWidth / container.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(container.clientWidth, container.clientHeight); controls.handleResize(); render() animate = () -> requestAnimationFrame(animate) controls.update() render = () -> renderer.render(scene, camera) init = () -> container = document.getElementById('webgl'); camera = new THREE.PerspectiveCamera( 80, container.clientWidth / container.clientHeight, 0.1, 10000); camera.position.set(0,-370,380) #camera.position.z = Math.min(container.clientWidth, container.clientHeight); camera.zoom = 0.7; controls = new THREE.TrackballControls(camera, container); controls.rotateSpeed = 1.0; controls.zoomSpeed = 1.2; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.keys = [PI:KEY:<KEY>END_PI controls.addEventListener('change', render); #World scene = new THREE.Scene(); #Lights light = new THREE.DirectionalLight(0xffffff); light.position.set(1, 1, 1); scene.add(light); spotLight = new THREE.SpotLight(0xffffff); spotLight.position.set(-1000, -1000, 1000); spotLight.castShadow = true; scene.add(spotLight); ambientLight = new THREE.AmbientLight(0x333333); scene.add(ambientLight); #Renderer renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(container.clientWidth, container.clientHeight); container.appendChild(renderer.domElement); #Shadows renderer.shadowMap.enabled = true; renderer.shadowMapSoft = true; renderer.shadowCameraNear = 1; renderer.shadowCameraFar = camera.far; renderer.shadowCameraFov = 60; renderer.shadowMapBias = 0.0025; renderer.shadowMapDarkness = 0.5; renderer.shadowMapWidth = 1024; renderer.shadowMapHeight = 1024; renderer.setClearColor(0xffffff, 1); window.addEventListener('resize', onWindowResize, false); onWindowResize(); render(); update(); animate(); clearGroups = () -> if (json) if json.type is 'FeatureCollection' json.features.forEach (feature) -> scene.remove(scene.getObjectByName(feature.properties.iso)) else if (json.type is 'Topology') Object.keys(json.objects).forEach (key) -> json.objects[key].geometries.forEach (object) -> scene.remove(object._group) render() update = () -> width = container.clientWidth; height = container.clientHeight; #Read url from url textarea url = "/transparency/assets/data/oesterreich.json" d3.json(url, (data) -> json = data; clearGroups(); functions = {}; functions.color = defaults.color functions.height = defaults.height if (json.type is 'FeatureCollection') projection = getProjection(json, width, height) json.features.forEach (feature) -> group = addFeature(feature, projection, functions) feature._group = group render() else if (json.type is 'Topology') geojson = topojson.merge(json, json.objects[Object.keys(json.objects)[0]].geometries) projection = getProjection(geojson, width, height) Object.keys(json.objects).forEach (key) -> json.objects[key].geometries.forEach (object) -> feature = topojson.feature(json, object) group = addFeature(feature, projection, functions) object._group = group render() else console.log('This tutorial only renders TopoJSON and GeoJSON FeatureCollections')) addShape = (group, shape, extrudeSettings, material, color, x, y, z, rx, ry, rz, s, iso) -> geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings); mesh = new THREE.Mesh(geometry, materials[material](color)); #Add shadows mesh.castShadow = true; mesh.receiveShadow = true; mesh.position.set(x, y, z); mesh.rotation.set(rx, ry, rz); mesh.scale.set(s, s, s); mesh.userData.bundesland = iso objects.push mesh group.add(mesh); addFeature = (feature, projection, functions) -> group = new THREE.Group(); group.name = feature.properties.iso scene.add(group); color; amount; try color = functions.color(feature.properties); catch err console.log(err) try amount = functions.height(feature.properties); catch err console.log(err) extrudeSettings = { amount: amount, bevelEnabled: false }; material = 'phongNotTransparent'; iso = feature.properties.iso if (feature.geometry.type is 'Polygon') shape = createPolygonShape(feature.geometry.coordinates, projection) addShape(group, shape, extrudeSettings, material, color, 0, 0, amount, Math.PI, 0, 0, 1, iso) else if (feature.geometry.type is 'MultiPolygon') feature.geometry.coordinates.forEach (polygon) -> shape = createPolygonShape(polygon, projection) addShape(group, shape, extrudeSettings, material, color, 0, 0, amount, Math.PI, 0, 0, 1, iso) else console.log('This tutorial only renders Polygons and MultiPolygons') group dataUpdated = () -> if $scope.data and Object.keys($scope.data).length isnt 0 #transferSums = $scope.data maximum = Number.NEGATIVE_INFINITY sum = 0 for k,v of $scope.data if v.federalState != 'Unknown' sum += v.amount if v.amount > maximum maximum = v.amount for k,v of $scope.data if v.federalState != 'Unknown' transferSums[v.federalState] = {} transferSums[v.federalState].height = v.amount/parseFloat(maximum) transferSums[v.federalState].sum = v.amount transferSums[v.federalState].percent = (v.amount/sum)*100 transferSums[v.federalState].iso = v.federalState if !initialized init() render() initialized = true if initialized update() $scope.$watch 'data', dataUpdated
[ { "context": "ingGambitDamageNearbyForAttack\"\n\n\t@modifierName: \"Opening Gambit\"\n\t@description: \"ALL nearby minions deal damage t", "end": 406, "score": 0.9196373820304871, "start": 392, "tag": "NAME", "value": "Opening Gambit" } ]
app/sdk/modifiers/modifierOpeningGambitDamageNearbyForAttack.coffee
willroberts/duelyst
5
ModifierOpeningGambit = require './modifierOpeningGambit' DamageAction = require 'app/sdk/actions/damageAction' CardType = require 'app/sdk/cards/cardType' Modifier = require './modifier' class ModifierOpeningGambitDamageNearbyForAttack extends ModifierOpeningGambit type: "ModifierOpeningGambitDamageNearbyForAttack" @type: "ModifierOpeningGambitDamageNearbyForAttack" @modifierName: "Opening Gambit" @description: "ALL nearby minions deal damage to themselves equal to their Attack" targetType: CardType.Unit fxResource: ["FX.Modifiers.ModifierOpeningGambit", "FX.Modifiers.ModifierGenericDamageNearby"] onOpeningGambit: () -> for entity in @getGameSession().getBoard().getEntitiesAroundEntity(@getCard(), CardType.Unit, 1) if !entity.getIsGeneral() # this ability only damages minions, not Generals damageAction = new DamageAction(@getGameSession()) damageAction.setOwnerId(@getCard().getOwnerId()) # source and target are same because minion deals damage to itself damageAction.setSource(entity) damageAction.setTarget(entity) damageAction.setDamageAmount(entity.getATK()) @getGameSession().executeAction(damageAction) module.exports = ModifierOpeningGambitDamageNearbyForAttack
91513
ModifierOpeningGambit = require './modifierOpeningGambit' DamageAction = require 'app/sdk/actions/damageAction' CardType = require 'app/sdk/cards/cardType' Modifier = require './modifier' class ModifierOpeningGambitDamageNearbyForAttack extends ModifierOpeningGambit type: "ModifierOpeningGambitDamageNearbyForAttack" @type: "ModifierOpeningGambitDamageNearbyForAttack" @modifierName: "<NAME>" @description: "ALL nearby minions deal damage to themselves equal to their Attack" targetType: CardType.Unit fxResource: ["FX.Modifiers.ModifierOpeningGambit", "FX.Modifiers.ModifierGenericDamageNearby"] onOpeningGambit: () -> for entity in @getGameSession().getBoard().getEntitiesAroundEntity(@getCard(), CardType.Unit, 1) if !entity.getIsGeneral() # this ability only damages minions, not Generals damageAction = new DamageAction(@getGameSession()) damageAction.setOwnerId(@getCard().getOwnerId()) # source and target are same because minion deals damage to itself damageAction.setSource(entity) damageAction.setTarget(entity) damageAction.setDamageAmount(entity.getATK()) @getGameSession().executeAction(damageAction) module.exports = ModifierOpeningGambitDamageNearbyForAttack
true
ModifierOpeningGambit = require './modifierOpeningGambit' DamageAction = require 'app/sdk/actions/damageAction' CardType = require 'app/sdk/cards/cardType' Modifier = require './modifier' class ModifierOpeningGambitDamageNearbyForAttack extends ModifierOpeningGambit type: "ModifierOpeningGambitDamageNearbyForAttack" @type: "ModifierOpeningGambitDamageNearbyForAttack" @modifierName: "PI:NAME:<NAME>END_PI" @description: "ALL nearby minions deal damage to themselves equal to their Attack" targetType: CardType.Unit fxResource: ["FX.Modifiers.ModifierOpeningGambit", "FX.Modifiers.ModifierGenericDamageNearby"] onOpeningGambit: () -> for entity in @getGameSession().getBoard().getEntitiesAroundEntity(@getCard(), CardType.Unit, 1) if !entity.getIsGeneral() # this ability only damages minions, not Generals damageAction = new DamageAction(@getGameSession()) damageAction.setOwnerId(@getCard().getOwnerId()) # source and target are same because minion deals damage to itself damageAction.setSource(entity) damageAction.setTarget(entity) damageAction.setDamageAmount(entity.getATK()) @getGameSession().executeAction(damageAction) module.exports = ModifierOpeningGambitDamageNearbyForAttack
[ { "context": "ey: 'I7GcKlS4hnVloq9vLyvfQ'\n consumer_secret: 'N0eoeNkSufsKsnpywjKZsZeK6DrqA7Jhr7kW6I'\n scope: 'https://api.twitter.com/1.1/'\n ap", "end": 1099, "score": 0.999661386013031, "start": 1061, "tag": "KEY", "value": "N0eoeNkSufsKsnpywjKZsZeK6DrqA7Jhr7kW6I" }, { "context": "pe: 'https://api.twitter.com/1.1/'\n app_name: 'vimmers_folow_status'\n\n # TODO onfailure\n @sendSignedRequest: (url, ", "end": 1178, "score": 0.772077739238739, "start": 1158, "tag": "USERNAME", "value": "vimmers_folow_status" } ]
src/coffee/eventPage.coffee
yonchu/vimmers-follow-status
3
class Background constructor: (@commands) -> @addEventListeners() addEventListeners: -> chrome.runtime.onMessage.addListener (request, sender, sendResponse) => if sender.tab console.log "from a content script: #{sender.tab.url}" else console.log "from the extension" target = @commands[request.target] unless target throw Error "Invalid target #{request.target}", @commands args = request.args args.push sendResponse res = target[request.action].apply target, args if res sendResponse res: res return true return class TwitterCommands constructor: -> sendSignedRequest: (url, request, sendResponse) -> Twitter.sendSignedRequest url, sendResponse, request return class Twitter @OAUTH_PARAM: request_url: 'https://api.twitter.com/oauth/request_token' authorize_url: 'https://api.twitter.com/oauth/authorize' access_url: 'https://api.twitter.com/oauth/access_token' consumer_key: 'I7GcKlS4hnVloq9vLyvfQ' consumer_secret: 'N0eoeNkSufsKsnpywjKZsZeK6DrqA7Jhr7kW6I' scope: 'https://api.twitter.com/1.1/' app_name: 'vimmers_folow_status' # TODO onfailure @sendSignedRequest: (url, onsuccess, request) -> new Twitter().sendSignedRequest url, onsuccess, request constructor: -> authorize: (onAuthorised) -> console.log 'Run authorizing.' oauth = ChromeExOAuth.initBackgroundPage Twitter.OAUTH_PARAM oauth.authorize -> console.log 'Authorized successfully.' onAuthorised oauth return sendSignedRequest: (url, onsuccess, request) -> @authorize (oauth) => # Note Function.bind supported only from ES5. oauth.sendSignedRequest( url, @_onSendSignedRequest.bind(@, onsuccess), request ) return return _onSendSignedRequest: (onsuccess, response, xhr) -> resJson = JSON.parse response console.log 'Signed request response', resJson if resJson.errors?[0].code is 89 @removeOauthToken() onsuccess res: resJson return removeOauthToken: -> console.log 'Remove oath access token.', localStorage localStorage.removeItem 'oauth_tokenhttps://api.twitter.com/1.1/' localStorage.removeItem 'oauth_token_secrethttps://api.twitter.com/1.1/' console.log localStorage return ## Main exports = exports ? window ? @ exports.bg = new Background( twitter: new TwitterCommands )
66655
class Background constructor: (@commands) -> @addEventListeners() addEventListeners: -> chrome.runtime.onMessage.addListener (request, sender, sendResponse) => if sender.tab console.log "from a content script: #{sender.tab.url}" else console.log "from the extension" target = @commands[request.target] unless target throw Error "Invalid target #{request.target}", @commands args = request.args args.push sendResponse res = target[request.action].apply target, args if res sendResponse res: res return true return class TwitterCommands constructor: -> sendSignedRequest: (url, request, sendResponse) -> Twitter.sendSignedRequest url, sendResponse, request return class Twitter @OAUTH_PARAM: request_url: 'https://api.twitter.com/oauth/request_token' authorize_url: 'https://api.twitter.com/oauth/authorize' access_url: 'https://api.twitter.com/oauth/access_token' consumer_key: 'I7GcKlS4hnVloq9vLyvfQ' consumer_secret: '<KEY>' scope: 'https://api.twitter.com/1.1/' app_name: 'vimmers_folow_status' # TODO onfailure @sendSignedRequest: (url, onsuccess, request) -> new Twitter().sendSignedRequest url, onsuccess, request constructor: -> authorize: (onAuthorised) -> console.log 'Run authorizing.' oauth = ChromeExOAuth.initBackgroundPage Twitter.OAUTH_PARAM oauth.authorize -> console.log 'Authorized successfully.' onAuthorised oauth return sendSignedRequest: (url, onsuccess, request) -> @authorize (oauth) => # Note Function.bind supported only from ES5. oauth.sendSignedRequest( url, @_onSendSignedRequest.bind(@, onsuccess), request ) return return _onSendSignedRequest: (onsuccess, response, xhr) -> resJson = JSON.parse response console.log 'Signed request response', resJson if resJson.errors?[0].code is 89 @removeOauthToken() onsuccess res: resJson return removeOauthToken: -> console.log 'Remove oath access token.', localStorage localStorage.removeItem 'oauth_tokenhttps://api.twitter.com/1.1/' localStorage.removeItem 'oauth_token_secrethttps://api.twitter.com/1.1/' console.log localStorage return ## Main exports = exports ? window ? @ exports.bg = new Background( twitter: new TwitterCommands )
true
class Background constructor: (@commands) -> @addEventListeners() addEventListeners: -> chrome.runtime.onMessage.addListener (request, sender, sendResponse) => if sender.tab console.log "from a content script: #{sender.tab.url}" else console.log "from the extension" target = @commands[request.target] unless target throw Error "Invalid target #{request.target}", @commands args = request.args args.push sendResponse res = target[request.action].apply target, args if res sendResponse res: res return true return class TwitterCommands constructor: -> sendSignedRequest: (url, request, sendResponse) -> Twitter.sendSignedRequest url, sendResponse, request return class Twitter @OAUTH_PARAM: request_url: 'https://api.twitter.com/oauth/request_token' authorize_url: 'https://api.twitter.com/oauth/authorize' access_url: 'https://api.twitter.com/oauth/access_token' consumer_key: 'I7GcKlS4hnVloq9vLyvfQ' consumer_secret: 'PI:KEY:<KEY>END_PI' scope: 'https://api.twitter.com/1.1/' app_name: 'vimmers_folow_status' # TODO onfailure @sendSignedRequest: (url, onsuccess, request) -> new Twitter().sendSignedRequest url, onsuccess, request constructor: -> authorize: (onAuthorised) -> console.log 'Run authorizing.' oauth = ChromeExOAuth.initBackgroundPage Twitter.OAUTH_PARAM oauth.authorize -> console.log 'Authorized successfully.' onAuthorised oauth return sendSignedRequest: (url, onsuccess, request) -> @authorize (oauth) => # Note Function.bind supported only from ES5. oauth.sendSignedRequest( url, @_onSendSignedRequest.bind(@, onsuccess), request ) return return _onSendSignedRequest: (onsuccess, response, xhr) -> resJson = JSON.parse response console.log 'Signed request response', resJson if resJson.errors?[0].code is 89 @removeOauthToken() onsuccess res: resJson return removeOauthToken: -> console.log 'Remove oath access token.', localStorage localStorage.removeItem 'oauth_tokenhttps://api.twitter.com/1.1/' localStorage.removeItem 'oauth_token_secrethttps://api.twitter.com/1.1/' console.log localStorage return ## Main exports = exports ? window ? @ exports.bg = new Background( twitter: new TwitterCommands )
[ { "context": "key}\"\n\n initialize: (options) ->\n @key = 'popular'\n @query = options.query\n @id = options", "end": 348, "score": 0.9924149513244629, "start": 341, "tag": "KEY", "value": "popular" } ]
app/assets/javascripts/backbone/models/searchresult.js.coffee
vacaybug/vacaybug
0
jQuery -> Vacaybug = window.Vacaybug ? {} class SearchResultCollection extends window.Vacaybug.GenericCollection model: window.Vacaybug.GuideModel restURL: -> "/rest/search/search" queryParams: -> "#{super()}&query=#{encodeURIComponent(@query)}&id=#{@id}&key=#{@key}" initialize: (options) -> @key = 'popular' @query = options.query @id = options.id super(options) Vacaybug.SearchResultCollection = SearchResultCollection class FamousGuideCollection extends window.Vacaybug.GenericCollection restURL: -> "/rest/search/famous" parse: (resp, options) -> @most_commented = _.map resp.most_commented, (model) -> new Vacaybug.GuideModel(model) @most_liked = _.map resp.most_liked, (model) -> new Vacaybug.GuideModel(model) super(resp, options) Vacaybug.FamousGuideCollection = FamousGuideCollection
144916
jQuery -> Vacaybug = window.Vacaybug ? {} class SearchResultCollection extends window.Vacaybug.GenericCollection model: window.Vacaybug.GuideModel restURL: -> "/rest/search/search" queryParams: -> "#{super()}&query=#{encodeURIComponent(@query)}&id=#{@id}&key=#{@key}" initialize: (options) -> @key = '<KEY>' @query = options.query @id = options.id super(options) Vacaybug.SearchResultCollection = SearchResultCollection class FamousGuideCollection extends window.Vacaybug.GenericCollection restURL: -> "/rest/search/famous" parse: (resp, options) -> @most_commented = _.map resp.most_commented, (model) -> new Vacaybug.GuideModel(model) @most_liked = _.map resp.most_liked, (model) -> new Vacaybug.GuideModel(model) super(resp, options) Vacaybug.FamousGuideCollection = FamousGuideCollection
true
jQuery -> Vacaybug = window.Vacaybug ? {} class SearchResultCollection extends window.Vacaybug.GenericCollection model: window.Vacaybug.GuideModel restURL: -> "/rest/search/search" queryParams: -> "#{super()}&query=#{encodeURIComponent(@query)}&id=#{@id}&key=#{@key}" initialize: (options) -> @key = 'PI:KEY:<KEY>END_PI' @query = options.query @id = options.id super(options) Vacaybug.SearchResultCollection = SearchResultCollection class FamousGuideCollection extends window.Vacaybug.GenericCollection restURL: -> "/rest/search/famous" parse: (resp, options) -> @most_commented = _.map resp.most_commented, (model) -> new Vacaybug.GuideModel(model) @most_liked = _.map resp.most_liked, (model) -> new Vacaybug.GuideModel(model) super(resp, options) Vacaybug.FamousGuideCollection = FamousGuideCollection
[ { "context": ", 'app', 'files'], coffeeLintConfig\n\n\t\tif key is 'spaJade'\n\t\t\tcopyDevConfig.src = path.join(dirname, \"#{bas", "end": 14597, "score": 0.8514201641082764, "start": 14590, "tag": "KEY", "value": "spaJade" }, { "context": "dirname, \"#{basename}.{jade,html}\")\n\n\t\tif key is 'jade'\n\t\t\tcopyDevConfig.src = path.join(dirname, \"#{bas", "end": 14686, "score": 0.7713514566421509, "start": 14682, "tag": "KEY", "value": "jade" } ]
Gruntfile.coffee
jceverritt/AngularFun-master
0
path = require 'path' # Build configurations module.exports = (grunt) -> require('load-grunt-tasks')(grunt) require('time-grunt')(grunt) pkg = require './package.json' grunt.initConfig settings: distDirectory: 'dist' srcDirectory: 'src' tempDirectory: '.temp' # Gets dependent components from bower # see bower.json file bower: install: options: cleanTargetDir: true copy: true layout: (type, component) -> path.join type targetDir: '.components/' uninstall: options: cleanBowerDir: true copy: false install: false # Creates changelog changelog: options: repository: pkg.repository.url version: pkg.version # Deletes dist and .temp directories # The .temp directory is used during the build process # The dist directory contains the artifacts of the build # These directories should be deleted before subsequent builds # These directories are not committed to source control clean: working: [ '<%= settings.tempDirectory %>' '<%= settings.distDirectory %>' ] # Used for those that desire plain old JavaScript jslove: [ '**/*.coffee' '!**/.components/**' '!**/.temp/**' '!**/bower_components/**' '!**/node_modules/**' ] # Compiles CoffeeScript (.coffee) files to JavaScript (.js) coffee: app: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.coffee' dest: '<%= settings.tempDirectory %>' expand: true ext: '.js' ] options: sourceMap: true # Used for those that desire plain old JavaScript jslove: files: [ cwd: '' src: '<%= clean.jslove %>' dest: '' expand: true ext: '.js' ] # Lints CoffeeScript files coffeelint: app: files: [ cwd: '' src: [ 'src/**/*.coffee' '!src/scripts/libs/**' ] ] options: indentation: value: 1 max_line_length: level: 'ignore' no_tabs: level: 'ignore' # Sets up a web server connect: app: options: base: '<%= settings.distDirectory %>' hostname: 'localhost' livereload: true middleware: (connect, options, middlewares) -> express = require 'express' routes = require './routes' app = express() app.use express.static String(options.base) routes app, options middlewares.unshift app middlewares open: true port: 0 # Copies directories and files from one location to another copy: app: files: [ cwd: '<%= settings.srcDirectory %>' src: '**' dest: '<%= settings.tempDirectory %>' expand: true , cwd: '.components/' src: '**' dest: '<%= settings.tempDirectory %>' expand: true ] dev: cwd: '<%= settings.tempDirectory %>' src: '**' dest: '<%= settings.distDirectory %>' expand: true prod: files: [ cwd: '<%= settings.tempDirectory %>' src: [ '**/*.{eot,svg,ttf,woff}' '**/*.{gif,jpeg,jpg,png,svg,webp}' 'index.html' 'scripts/ie.min.*.js' 'scripts/scripts.min.*.js' 'styles/styles.min.*.css' ] dest: '<%= settings.distDirectory %>' expand: true ] # Renames files based on their hashed content # When the files contents change, the hash value changes # Used as a cache buster, ensuring browsers load the correct static resources # # glyphicons-halflings.png -> glyphicons-halflings.6c8829cc6f.png # scripts.min.js -> scripts.min.6c355e03ee.js hash: images: '.temp/**/*.{gif,jpeg,jpg,png,svg,webp}' scripts: cwd: '.temp/scripts' src: [ 'ie.min.js' 'scripts.min.js' ] expand: true styles: '.temp/styles/styles.min.css' # Compresses png files imagemin: images: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.{gif,jpeg,jpg,png}' dest: '<%= settings.tempDirectory %>' expand: true ] options: optimizationLevel: 7 # Compiles jade templates jade: views: cwd: '<%= settings.tempDirectory %>' src: '**/*.jade' dest: '<%= settings.tempDirectory %>' expand: true ext: '.html' options: pretty: true spa: cwd: '<%= settings.tempDirectory %>' src: 'index.jade' dest: '<%= settings.tempDirectory %>' expand: true ext: '.html' options: pretty: true # Runs unit tests using karma karma: unit: options: browsers: [ 'PhantomJS' ] captureTimeout: 5000 colors: true files: [ 'dist/scripts/libs/angular.min.js' 'dist/scripts/libs/angular-animate.min.js' 'dist/scripts/libs/angular-route.min.js' '.components/scripts/libs/angular-mocks.js' 'dist/**/*.js' 'test/**/*.{coffee,js}' ] frameworks: [ 'jasmine' ] junitReporter: outputFile: 'test-results.xml' keepalive: false logLevel: 'INFO' port: 9876 preprocessors: '**/*.coffee': 'coffee' reporters: [ 'spec' ] runnerPort: 9100 singleRun: true # Compile LESS (.less) files to CSS (.css) less: app: files: '.temp/styles/styles.css': '.temp/styles/styles.less' # Minifies index.html # Extra white space and comments will be removed # Content within <pre /> tags will be left unchanged # IE conditional comments will be left unchanged # Reduces file size by over 14% minifyHtml: prod: src: '.temp/index.html' ext: '.html' expand: true # Convert CoffeeScript classes to AngularJS modules ngClassify: app: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.coffee' dest: '<%= settings.tempDirectory %>' expand: true ] # Creates a file to push views directly into the $templateCache # This will produce a file with the following content # # angular.module('app').run(['$templateCache', function ($templateCache) { # $templateCache.put('/views/directives/tab.html', '<div class="tab-pane" ng-class="{active: selected}" ng-transclude></div>'); # $templateCache.put('/views/directives/tabs.html', '<div class="tabbable"> <ul class="nav nav-tabs"> <li ng-repeat="tab in tabs" ng-class="{active:tab.selected}"> <a href="http://localhost:3005/scripts/views.js" ng-click="select(tab)">{{tab.caption}}</a> </li> </ul> <div class="tab-content" ng-transclude></div> </div>'); # $templateCache.put('/views/people.html', '<ul ng-hide="!people.length"> <li class="row" ng-repeat="person in people | orderBy:\'name\'"> <a ng-href="#/people/{{person.id}}" ng-bind="person.name"></a> </li> </ul>'); # $templateCache.put('/views/repos.html', '<ul ng-hide="!repos.length"> <li ng-repeat="repo in repos | orderBy:\'pushed_at\':true"> <a ng-href="{{repo.url}}" ng-bind="repo.name" target="_blank"></a> <div ng-bind="repo.description"></div> </li> </ul>'); # $templateCache.put('/views/tweets.html', '<ul ng-hide="!tweets.length"> <li class="row" ng-repeat="tweet in tweets"> <div class="span1 thumbnail"> <img ng-src="{{tweet.profile_image_url}}"/> </div> <div class="span6"> <div> <b ng-bind="tweet.from_user_name"></b> <a ng-href="https://twitter.com/{{tweet.from_user}}" ng-bind="tweet.from_user | twitterfy" target="_blank"></a> </div> <div ng-bind="tweet.text"></div> </div> </li> </ul>'); # }]); # # This file is then included in the output automatically # AngularJS will use it instead of going to the file system for the views, saving requests # Notice that the view content is actually minified. :) ngTemplateCache: views: files: '.temp/scripts/views.js': '.temp/**/*.html' options: trim: '<%= settings.tempDirectory %>' prompt: jslove: options: questions: [ { config: 'coffee.jslove.compile' type: 'input' message: 'Are you sure you wish to convert all CoffeeScript (.coffee) files to JavaScript (.js)?' + '\n' + 'This cannot be undone.'.red + ': (y/N)' default: false filter: (input) -> confirmed = /^y(es)?/i.test input if not confirmed grunt.fatal 'exiting jslove' return confirmed } ] # RequireJS optimizer configuration for both scripts and styles # This configuration is only used in the 'prod' build # The optimizer will scan the main file, walk the dependency tree, and write the output in dependent sequence to a single file # Since RequireJS is not being used outside of the main file or for dependency resolution (this is handled by AngularJS), RequireJS is not needed for final output and is excluded # RequireJS is still used for the 'dev' build # The main file is used only to establish the proper loading sequence requirejs: scripts: options: baseUrl: '.temp/scripts' findNestedDependencies: true logLevel: 0 mainConfigFile: '.temp/scripts/main.js' name: 'main' # Exclude main from the final output to avoid the dependency on RequireJS at runtime onBuildWrite: (moduleName, path, contents) -> modulesToExclude = ['main'] shouldExcludeModule = modulesToExclude.indexOf(moduleName) >= 0 return '' if shouldExcludeModule contents optimize: 'uglify2' out: '.temp/scripts/scripts.min.js' preserveLicenseComments: false skipModuleInsertion: true uglify: # Let uglifier replace variables to further reduce file size no_mangle: false useStrict: true wrap: start: '(function(){\'use strict\';' end: '}).call(this);' styles: options: baseUrl: '.temp/styles/' cssIn: '.temp/styles/styles.css' logLevel: 0 optimizeCss: 'standard' out: '.temp/styles/styles.min.css' # Creates main file for RequireJS shimmer: dev: cwd: '.temp/scripts' src: [ '**/*.{coffee,js}' '!libs/angular.{coffee,js}' '!libs/angular-animate.{coffee,js}' '!libs/angular-route.{coffee,js}' '!libs/html5shiv-printshiv.{coffee,js}' '!libs/json3.min.{coffee,js}' '!libs/require.{coffee,js}' ] order: [ 'libs/angular.min.js' 'NGAPP': 'ngAnimate': 'libs/angular-animate.min.js' 'ngMockE2E': 'libs/angular-mocks.js' 'ngRoute': 'libs/angular-route.min.js' ] require: 'NGBOOTSTRAP' prod: cwd: '<%= shimmer.dev.cwd %>' src: [ '**/*.{coffee,js}' '!libs/angular.{coffee,js}' '!libs/angular-animate.{coffee,js}' '!libs/angular-mocks.{coffee,js}' '!libs/angular-route.{coffee,js}' '!libs/html5shiv-printshiv.{coffee,js}' '!libs/json3.min.{coffee,js}' '!libs/require.{coffee,js}' '!backend/**/*.*' ] order: [ 'libs/angular.min.js' 'NGAPP': 'ngAnimate': 'libs/angular-animate.min.js' 'ngRoute': 'libs/angular-route.min.js' ] require: '<%= shimmer.dev.require %>' # Compiles underscore expressions # # The example below demonstrates the use of the environment configuration setting # In 'prod' build the hashed file of the concatenated and minified scripts is referened # In environments other than 'prod' the individual files are used and loaded with RequireJS # # <% if (config.environment === 'prod') { %> # <script src="<%= config.getHashedFile('.temp/scripts/scripts.min.js', {trim: '.temp'}) %>"></script> # <% } else { %> # <script data-main="/scripts/main.js" src="/scripts/libs/require.js"></script> # <% } %> template: indexDev: files: '.temp/index.html': '.temp/index.html' '.temp/index.jade': '.temp/index.jade' index: files: '<%= template.indexDev.files %>' environment: 'prod' # Concatenates and minifies JavaScript files uglify: scripts: files: '.temp/scripts/ie.min.js': [ '.temp/scripts/libs/json3.js' '.temp/scripts/libs/html5shiv-printshiv.js' ] # Run tasks when monitored files change watch: basic: files: [ 'src/fonts/**' 'src/images/**' 'src/scripts/**/*.js' 'src/styles/**/*.css' 'src/**/*.html' ] tasks: [ 'copy:app' 'copy:dev' 'karma' ] options: livereload: true nospawn: true coffee: files: 'src/scripts/**/*.coffee' tasks: [ 'clean:working' 'coffeelint' 'copy:app' 'shimmer:dev' 'ngClassify:app' 'coffee:app' 'copy:dev' 'karma' ] options: livereload: true nospawn: true jade: files: 'src/views/**/*.jade' tasks: [ 'copy:app' 'jade:views' 'copy:dev' 'karma' ] options: livereload: true nospawn: true less: files: 'src/styles/**/*.less' tasks: [ 'copy:app' 'less' 'copy:dev' ] options: livereload: true nospawn: true spaHtml: files: 'src/index.html' tasks: [ 'copy:app' 'template:indexDev' 'copy:dev' 'karma' ] options: livereload: true nospawn: true spaJade: files: 'src/index.jade' tasks: [ 'copy:app' 'template:indexDev' 'jade:spa' 'copy:dev' 'karma' ] options: livereload: true nospawn: true test: files: 'test/**/*.*' tasks: [ 'karma' ] # Used to keep the web server alive none: files: 'none' options: livereload: true # ensure only tasks are executed for the changed file # without this, the tasks for all files matching the original pattern are executed grunt.event.on 'watch', (action, filepath, key) -> file = filepath.substr(4) # trim "src/" from the beginning. I don't like what I'm doing here, need a better way of handling paths. dirname = path.dirname file ext = path.extname file basename = path.basename file, ext grunt.config ['copy', 'app'], cwd: 'src/' src: file dest: '.temp/' expand: true copyDevConfig = grunt.config ['copy', 'dev'] copyDevConfig.src = file if key is 'coffee' # delete associated temp file prior to performing remaining tasks # without doing so, shimmer may fail grunt.config ['clean', 'working'], [ path.join('.temp', dirname, "#{basename}.{coffee,js,js.map}") ] copyDevConfig.src = [ path.join(dirname, "#{basename}.{coffee,js,js.map}") 'scripts/main.{coffee,js,js.map}' ] coffeeConfig = grunt.config ['coffee', 'app', 'files'] coffeeConfig.src = file coffeeLintConfig = grunt.config ['coffeelint', 'app', 'files'] coffeeLintConfig = filepath grunt.config ['coffee', 'app', 'files'], coffeeConfig grunt.config ['coffeelint', 'app', 'files'], coffeeLintConfig if key is 'spaJade' copyDevConfig.src = path.join(dirname, "#{basename}.{jade,html}") if key is 'jade' copyDevConfig.src = path.join(dirname, "#{basename}.{jade,html}") jadeConfig = grunt.config ['jade', 'views'] jadeConfig.src = file grunt.config ['jade', 'views'], jadeConfig if key is 'less' copyDevConfig.src = [ path.join(dirname, "#{basename}.{less,css}") path.join(dirname, 'styles.css') ] grunt.config ['copy', 'dev'], copyDevConfig # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Enter the following command at the command line to execute this build task: # grunt build grunt.registerTask 'build', [ 'clean:working' 'bower:install' 'coffeelint' 'copy:app' 'jade' 'shimmer:dev' 'ngClassify' 'coffee:app' 'less' 'template:indexDev' 'copy:dev' ] # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Opens the app in the default browser # Watches for file changes, and compiles and reloads the web browser upon change # Enter the following command at the command line to execute this build task: # grunt or grunt default grunt.registerTask 'default', [ 'build' 'connect' 'watch' ] # Identical to the default build task # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Opens the app in the default browser # Watches for file changes, and compiles and reloads the web browser upon change # Enter the following command at the command line to execute this build task: # grunt dev grunt.registerTask 'dev', [ 'default' ] # Compiles the app with optimized build settings # Places the build artifacts in the dist directory # Enter the following command at the command line to execute this build task: # grunt prod grunt.registerTask 'prod', [ 'clean:working' 'bower:install' 'coffeelint' 'copy:app' 'jade:views' 'ngTemplateCache' 'shimmer:prod' 'ngClassify' 'coffee:app' 'imagemin' 'hash:images' 'less' 'requirejs' 'uglify' 'hash:scripts' 'hash:styles' 'template:index' 'jade:spa' 'minifyHtml' 'copy:prod' ] # Opens the app in the default browser # Build artifacts must be in the dist directory via a prior grunt build, grunt, grunt dev, or grunt prod # Enter the following command at the command line to execute this build task: # grunt server grunt.registerTask 'server', [ 'connect' 'watch:none' ] # Looks like the prevailing winds are pointing to use 'serve' instead of 'server' # Why not both? :) # grunt serve grunt.registerTask 'serve', [ 'server' ] # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Runs unit tests via karma # Enter the following command at the command line to execute this build task: # grunt test grunt.registerTask 'test', [ 'build' 'karma' ] # Compiles all CoffeeScript files in the project to JavaScript then deletes all CoffeeScript files # Used for those that desire plain old JavaScript # Enter the following command at the command line to execute this build task: # grunt jslove grunt.registerTask 'jslove', [ 'prompt:jslove' 'coffee:jslove' 'clean:jslove' ]
58052
path = require 'path' # Build configurations module.exports = (grunt) -> require('load-grunt-tasks')(grunt) require('time-grunt')(grunt) pkg = require './package.json' grunt.initConfig settings: distDirectory: 'dist' srcDirectory: 'src' tempDirectory: '.temp' # Gets dependent components from bower # see bower.json file bower: install: options: cleanTargetDir: true copy: true layout: (type, component) -> path.join type targetDir: '.components/' uninstall: options: cleanBowerDir: true copy: false install: false # Creates changelog changelog: options: repository: pkg.repository.url version: pkg.version # Deletes dist and .temp directories # The .temp directory is used during the build process # The dist directory contains the artifacts of the build # These directories should be deleted before subsequent builds # These directories are not committed to source control clean: working: [ '<%= settings.tempDirectory %>' '<%= settings.distDirectory %>' ] # Used for those that desire plain old JavaScript jslove: [ '**/*.coffee' '!**/.components/**' '!**/.temp/**' '!**/bower_components/**' '!**/node_modules/**' ] # Compiles CoffeeScript (.coffee) files to JavaScript (.js) coffee: app: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.coffee' dest: '<%= settings.tempDirectory %>' expand: true ext: '.js' ] options: sourceMap: true # Used for those that desire plain old JavaScript jslove: files: [ cwd: '' src: '<%= clean.jslove %>' dest: '' expand: true ext: '.js' ] # Lints CoffeeScript files coffeelint: app: files: [ cwd: '' src: [ 'src/**/*.coffee' '!src/scripts/libs/**' ] ] options: indentation: value: 1 max_line_length: level: 'ignore' no_tabs: level: 'ignore' # Sets up a web server connect: app: options: base: '<%= settings.distDirectory %>' hostname: 'localhost' livereload: true middleware: (connect, options, middlewares) -> express = require 'express' routes = require './routes' app = express() app.use express.static String(options.base) routes app, options middlewares.unshift app middlewares open: true port: 0 # Copies directories and files from one location to another copy: app: files: [ cwd: '<%= settings.srcDirectory %>' src: '**' dest: '<%= settings.tempDirectory %>' expand: true , cwd: '.components/' src: '**' dest: '<%= settings.tempDirectory %>' expand: true ] dev: cwd: '<%= settings.tempDirectory %>' src: '**' dest: '<%= settings.distDirectory %>' expand: true prod: files: [ cwd: '<%= settings.tempDirectory %>' src: [ '**/*.{eot,svg,ttf,woff}' '**/*.{gif,jpeg,jpg,png,svg,webp}' 'index.html' 'scripts/ie.min.*.js' 'scripts/scripts.min.*.js' 'styles/styles.min.*.css' ] dest: '<%= settings.distDirectory %>' expand: true ] # Renames files based on their hashed content # When the files contents change, the hash value changes # Used as a cache buster, ensuring browsers load the correct static resources # # glyphicons-halflings.png -> glyphicons-halflings.6c8829cc6f.png # scripts.min.js -> scripts.min.6c355e03ee.js hash: images: '.temp/**/*.{gif,jpeg,jpg,png,svg,webp}' scripts: cwd: '.temp/scripts' src: [ 'ie.min.js' 'scripts.min.js' ] expand: true styles: '.temp/styles/styles.min.css' # Compresses png files imagemin: images: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.{gif,jpeg,jpg,png}' dest: '<%= settings.tempDirectory %>' expand: true ] options: optimizationLevel: 7 # Compiles jade templates jade: views: cwd: '<%= settings.tempDirectory %>' src: '**/*.jade' dest: '<%= settings.tempDirectory %>' expand: true ext: '.html' options: pretty: true spa: cwd: '<%= settings.tempDirectory %>' src: 'index.jade' dest: '<%= settings.tempDirectory %>' expand: true ext: '.html' options: pretty: true # Runs unit tests using karma karma: unit: options: browsers: [ 'PhantomJS' ] captureTimeout: 5000 colors: true files: [ 'dist/scripts/libs/angular.min.js' 'dist/scripts/libs/angular-animate.min.js' 'dist/scripts/libs/angular-route.min.js' '.components/scripts/libs/angular-mocks.js' 'dist/**/*.js' 'test/**/*.{coffee,js}' ] frameworks: [ 'jasmine' ] junitReporter: outputFile: 'test-results.xml' keepalive: false logLevel: 'INFO' port: 9876 preprocessors: '**/*.coffee': 'coffee' reporters: [ 'spec' ] runnerPort: 9100 singleRun: true # Compile LESS (.less) files to CSS (.css) less: app: files: '.temp/styles/styles.css': '.temp/styles/styles.less' # Minifies index.html # Extra white space and comments will be removed # Content within <pre /> tags will be left unchanged # IE conditional comments will be left unchanged # Reduces file size by over 14% minifyHtml: prod: src: '.temp/index.html' ext: '.html' expand: true # Convert CoffeeScript classes to AngularJS modules ngClassify: app: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.coffee' dest: '<%= settings.tempDirectory %>' expand: true ] # Creates a file to push views directly into the $templateCache # This will produce a file with the following content # # angular.module('app').run(['$templateCache', function ($templateCache) { # $templateCache.put('/views/directives/tab.html', '<div class="tab-pane" ng-class="{active: selected}" ng-transclude></div>'); # $templateCache.put('/views/directives/tabs.html', '<div class="tabbable"> <ul class="nav nav-tabs"> <li ng-repeat="tab in tabs" ng-class="{active:tab.selected}"> <a href="http://localhost:3005/scripts/views.js" ng-click="select(tab)">{{tab.caption}}</a> </li> </ul> <div class="tab-content" ng-transclude></div> </div>'); # $templateCache.put('/views/people.html', '<ul ng-hide="!people.length"> <li class="row" ng-repeat="person in people | orderBy:\'name\'"> <a ng-href="#/people/{{person.id}}" ng-bind="person.name"></a> </li> </ul>'); # $templateCache.put('/views/repos.html', '<ul ng-hide="!repos.length"> <li ng-repeat="repo in repos | orderBy:\'pushed_at\':true"> <a ng-href="{{repo.url}}" ng-bind="repo.name" target="_blank"></a> <div ng-bind="repo.description"></div> </li> </ul>'); # $templateCache.put('/views/tweets.html', '<ul ng-hide="!tweets.length"> <li class="row" ng-repeat="tweet in tweets"> <div class="span1 thumbnail"> <img ng-src="{{tweet.profile_image_url}}"/> </div> <div class="span6"> <div> <b ng-bind="tweet.from_user_name"></b> <a ng-href="https://twitter.com/{{tweet.from_user}}" ng-bind="tweet.from_user | twitterfy" target="_blank"></a> </div> <div ng-bind="tweet.text"></div> </div> </li> </ul>'); # }]); # # This file is then included in the output automatically # AngularJS will use it instead of going to the file system for the views, saving requests # Notice that the view content is actually minified. :) ngTemplateCache: views: files: '.temp/scripts/views.js': '.temp/**/*.html' options: trim: '<%= settings.tempDirectory %>' prompt: jslove: options: questions: [ { config: 'coffee.jslove.compile' type: 'input' message: 'Are you sure you wish to convert all CoffeeScript (.coffee) files to JavaScript (.js)?' + '\n' + 'This cannot be undone.'.red + ': (y/N)' default: false filter: (input) -> confirmed = /^y(es)?/i.test input if not confirmed grunt.fatal 'exiting jslove' return confirmed } ] # RequireJS optimizer configuration for both scripts and styles # This configuration is only used in the 'prod' build # The optimizer will scan the main file, walk the dependency tree, and write the output in dependent sequence to a single file # Since RequireJS is not being used outside of the main file or for dependency resolution (this is handled by AngularJS), RequireJS is not needed for final output and is excluded # RequireJS is still used for the 'dev' build # The main file is used only to establish the proper loading sequence requirejs: scripts: options: baseUrl: '.temp/scripts' findNestedDependencies: true logLevel: 0 mainConfigFile: '.temp/scripts/main.js' name: 'main' # Exclude main from the final output to avoid the dependency on RequireJS at runtime onBuildWrite: (moduleName, path, contents) -> modulesToExclude = ['main'] shouldExcludeModule = modulesToExclude.indexOf(moduleName) >= 0 return '' if shouldExcludeModule contents optimize: 'uglify2' out: '.temp/scripts/scripts.min.js' preserveLicenseComments: false skipModuleInsertion: true uglify: # Let uglifier replace variables to further reduce file size no_mangle: false useStrict: true wrap: start: '(function(){\'use strict\';' end: '}).call(this);' styles: options: baseUrl: '.temp/styles/' cssIn: '.temp/styles/styles.css' logLevel: 0 optimizeCss: 'standard' out: '.temp/styles/styles.min.css' # Creates main file for RequireJS shimmer: dev: cwd: '.temp/scripts' src: [ '**/*.{coffee,js}' '!libs/angular.{coffee,js}' '!libs/angular-animate.{coffee,js}' '!libs/angular-route.{coffee,js}' '!libs/html5shiv-printshiv.{coffee,js}' '!libs/json3.min.{coffee,js}' '!libs/require.{coffee,js}' ] order: [ 'libs/angular.min.js' 'NGAPP': 'ngAnimate': 'libs/angular-animate.min.js' 'ngMockE2E': 'libs/angular-mocks.js' 'ngRoute': 'libs/angular-route.min.js' ] require: 'NGBOOTSTRAP' prod: cwd: '<%= shimmer.dev.cwd %>' src: [ '**/*.{coffee,js}' '!libs/angular.{coffee,js}' '!libs/angular-animate.{coffee,js}' '!libs/angular-mocks.{coffee,js}' '!libs/angular-route.{coffee,js}' '!libs/html5shiv-printshiv.{coffee,js}' '!libs/json3.min.{coffee,js}' '!libs/require.{coffee,js}' '!backend/**/*.*' ] order: [ 'libs/angular.min.js' 'NGAPP': 'ngAnimate': 'libs/angular-animate.min.js' 'ngRoute': 'libs/angular-route.min.js' ] require: '<%= shimmer.dev.require %>' # Compiles underscore expressions # # The example below demonstrates the use of the environment configuration setting # In 'prod' build the hashed file of the concatenated and minified scripts is referened # In environments other than 'prod' the individual files are used and loaded with RequireJS # # <% if (config.environment === 'prod') { %> # <script src="<%= config.getHashedFile('.temp/scripts/scripts.min.js', {trim: '.temp'}) %>"></script> # <% } else { %> # <script data-main="/scripts/main.js" src="/scripts/libs/require.js"></script> # <% } %> template: indexDev: files: '.temp/index.html': '.temp/index.html' '.temp/index.jade': '.temp/index.jade' index: files: '<%= template.indexDev.files %>' environment: 'prod' # Concatenates and minifies JavaScript files uglify: scripts: files: '.temp/scripts/ie.min.js': [ '.temp/scripts/libs/json3.js' '.temp/scripts/libs/html5shiv-printshiv.js' ] # Run tasks when monitored files change watch: basic: files: [ 'src/fonts/**' 'src/images/**' 'src/scripts/**/*.js' 'src/styles/**/*.css' 'src/**/*.html' ] tasks: [ 'copy:app' 'copy:dev' 'karma' ] options: livereload: true nospawn: true coffee: files: 'src/scripts/**/*.coffee' tasks: [ 'clean:working' 'coffeelint' 'copy:app' 'shimmer:dev' 'ngClassify:app' 'coffee:app' 'copy:dev' 'karma' ] options: livereload: true nospawn: true jade: files: 'src/views/**/*.jade' tasks: [ 'copy:app' 'jade:views' 'copy:dev' 'karma' ] options: livereload: true nospawn: true less: files: 'src/styles/**/*.less' tasks: [ 'copy:app' 'less' 'copy:dev' ] options: livereload: true nospawn: true spaHtml: files: 'src/index.html' tasks: [ 'copy:app' 'template:indexDev' 'copy:dev' 'karma' ] options: livereload: true nospawn: true spaJade: files: 'src/index.jade' tasks: [ 'copy:app' 'template:indexDev' 'jade:spa' 'copy:dev' 'karma' ] options: livereload: true nospawn: true test: files: 'test/**/*.*' tasks: [ 'karma' ] # Used to keep the web server alive none: files: 'none' options: livereload: true # ensure only tasks are executed for the changed file # without this, the tasks for all files matching the original pattern are executed grunt.event.on 'watch', (action, filepath, key) -> file = filepath.substr(4) # trim "src/" from the beginning. I don't like what I'm doing here, need a better way of handling paths. dirname = path.dirname file ext = path.extname file basename = path.basename file, ext grunt.config ['copy', 'app'], cwd: 'src/' src: file dest: '.temp/' expand: true copyDevConfig = grunt.config ['copy', 'dev'] copyDevConfig.src = file if key is 'coffee' # delete associated temp file prior to performing remaining tasks # without doing so, shimmer may fail grunt.config ['clean', 'working'], [ path.join('.temp', dirname, "#{basename}.{coffee,js,js.map}") ] copyDevConfig.src = [ path.join(dirname, "#{basename}.{coffee,js,js.map}") 'scripts/main.{coffee,js,js.map}' ] coffeeConfig = grunt.config ['coffee', 'app', 'files'] coffeeConfig.src = file coffeeLintConfig = grunt.config ['coffeelint', 'app', 'files'] coffeeLintConfig = filepath grunt.config ['coffee', 'app', 'files'], coffeeConfig grunt.config ['coffeelint', 'app', 'files'], coffeeLintConfig if key is '<KEY>' copyDevConfig.src = path.join(dirname, "#{basename}.{jade,html}") if key is '<KEY>' copyDevConfig.src = path.join(dirname, "#{basename}.{jade,html}") jadeConfig = grunt.config ['jade', 'views'] jadeConfig.src = file grunt.config ['jade', 'views'], jadeConfig if key is 'less' copyDevConfig.src = [ path.join(dirname, "#{basename}.{less,css}") path.join(dirname, 'styles.css') ] grunt.config ['copy', 'dev'], copyDevConfig # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Enter the following command at the command line to execute this build task: # grunt build grunt.registerTask 'build', [ 'clean:working' 'bower:install' 'coffeelint' 'copy:app' 'jade' 'shimmer:dev' 'ngClassify' 'coffee:app' 'less' 'template:indexDev' 'copy:dev' ] # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Opens the app in the default browser # Watches for file changes, and compiles and reloads the web browser upon change # Enter the following command at the command line to execute this build task: # grunt or grunt default grunt.registerTask 'default', [ 'build' 'connect' 'watch' ] # Identical to the default build task # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Opens the app in the default browser # Watches for file changes, and compiles and reloads the web browser upon change # Enter the following command at the command line to execute this build task: # grunt dev grunt.registerTask 'dev', [ 'default' ] # Compiles the app with optimized build settings # Places the build artifacts in the dist directory # Enter the following command at the command line to execute this build task: # grunt prod grunt.registerTask 'prod', [ 'clean:working' 'bower:install' 'coffeelint' 'copy:app' 'jade:views' 'ngTemplateCache' 'shimmer:prod' 'ngClassify' 'coffee:app' 'imagemin' 'hash:images' 'less' 'requirejs' 'uglify' 'hash:scripts' 'hash:styles' 'template:index' 'jade:spa' 'minifyHtml' 'copy:prod' ] # Opens the app in the default browser # Build artifacts must be in the dist directory via a prior grunt build, grunt, grunt dev, or grunt prod # Enter the following command at the command line to execute this build task: # grunt server grunt.registerTask 'server', [ 'connect' 'watch:none' ] # Looks like the prevailing winds are pointing to use 'serve' instead of 'server' # Why not both? :) # grunt serve grunt.registerTask 'serve', [ 'server' ] # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Runs unit tests via karma # Enter the following command at the command line to execute this build task: # grunt test grunt.registerTask 'test', [ 'build' 'karma' ] # Compiles all CoffeeScript files in the project to JavaScript then deletes all CoffeeScript files # Used for those that desire plain old JavaScript # Enter the following command at the command line to execute this build task: # grunt jslove grunt.registerTask 'jslove', [ 'prompt:jslove' 'coffee:jslove' 'clean:jslove' ]
true
path = require 'path' # Build configurations module.exports = (grunt) -> require('load-grunt-tasks')(grunt) require('time-grunt')(grunt) pkg = require './package.json' grunt.initConfig settings: distDirectory: 'dist' srcDirectory: 'src' tempDirectory: '.temp' # Gets dependent components from bower # see bower.json file bower: install: options: cleanTargetDir: true copy: true layout: (type, component) -> path.join type targetDir: '.components/' uninstall: options: cleanBowerDir: true copy: false install: false # Creates changelog changelog: options: repository: pkg.repository.url version: pkg.version # Deletes dist and .temp directories # The .temp directory is used during the build process # The dist directory contains the artifacts of the build # These directories should be deleted before subsequent builds # These directories are not committed to source control clean: working: [ '<%= settings.tempDirectory %>' '<%= settings.distDirectory %>' ] # Used for those that desire plain old JavaScript jslove: [ '**/*.coffee' '!**/.components/**' '!**/.temp/**' '!**/bower_components/**' '!**/node_modules/**' ] # Compiles CoffeeScript (.coffee) files to JavaScript (.js) coffee: app: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.coffee' dest: '<%= settings.tempDirectory %>' expand: true ext: '.js' ] options: sourceMap: true # Used for those that desire plain old JavaScript jslove: files: [ cwd: '' src: '<%= clean.jslove %>' dest: '' expand: true ext: '.js' ] # Lints CoffeeScript files coffeelint: app: files: [ cwd: '' src: [ 'src/**/*.coffee' '!src/scripts/libs/**' ] ] options: indentation: value: 1 max_line_length: level: 'ignore' no_tabs: level: 'ignore' # Sets up a web server connect: app: options: base: '<%= settings.distDirectory %>' hostname: 'localhost' livereload: true middleware: (connect, options, middlewares) -> express = require 'express' routes = require './routes' app = express() app.use express.static String(options.base) routes app, options middlewares.unshift app middlewares open: true port: 0 # Copies directories and files from one location to another copy: app: files: [ cwd: '<%= settings.srcDirectory %>' src: '**' dest: '<%= settings.tempDirectory %>' expand: true , cwd: '.components/' src: '**' dest: '<%= settings.tempDirectory %>' expand: true ] dev: cwd: '<%= settings.tempDirectory %>' src: '**' dest: '<%= settings.distDirectory %>' expand: true prod: files: [ cwd: '<%= settings.tempDirectory %>' src: [ '**/*.{eot,svg,ttf,woff}' '**/*.{gif,jpeg,jpg,png,svg,webp}' 'index.html' 'scripts/ie.min.*.js' 'scripts/scripts.min.*.js' 'styles/styles.min.*.css' ] dest: '<%= settings.distDirectory %>' expand: true ] # Renames files based on their hashed content # When the files contents change, the hash value changes # Used as a cache buster, ensuring browsers load the correct static resources # # glyphicons-halflings.png -> glyphicons-halflings.6c8829cc6f.png # scripts.min.js -> scripts.min.6c355e03ee.js hash: images: '.temp/**/*.{gif,jpeg,jpg,png,svg,webp}' scripts: cwd: '.temp/scripts' src: [ 'ie.min.js' 'scripts.min.js' ] expand: true styles: '.temp/styles/styles.min.css' # Compresses png files imagemin: images: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.{gif,jpeg,jpg,png}' dest: '<%= settings.tempDirectory %>' expand: true ] options: optimizationLevel: 7 # Compiles jade templates jade: views: cwd: '<%= settings.tempDirectory %>' src: '**/*.jade' dest: '<%= settings.tempDirectory %>' expand: true ext: '.html' options: pretty: true spa: cwd: '<%= settings.tempDirectory %>' src: 'index.jade' dest: '<%= settings.tempDirectory %>' expand: true ext: '.html' options: pretty: true # Runs unit tests using karma karma: unit: options: browsers: [ 'PhantomJS' ] captureTimeout: 5000 colors: true files: [ 'dist/scripts/libs/angular.min.js' 'dist/scripts/libs/angular-animate.min.js' 'dist/scripts/libs/angular-route.min.js' '.components/scripts/libs/angular-mocks.js' 'dist/**/*.js' 'test/**/*.{coffee,js}' ] frameworks: [ 'jasmine' ] junitReporter: outputFile: 'test-results.xml' keepalive: false logLevel: 'INFO' port: 9876 preprocessors: '**/*.coffee': 'coffee' reporters: [ 'spec' ] runnerPort: 9100 singleRun: true # Compile LESS (.less) files to CSS (.css) less: app: files: '.temp/styles/styles.css': '.temp/styles/styles.less' # Minifies index.html # Extra white space and comments will be removed # Content within <pre /> tags will be left unchanged # IE conditional comments will be left unchanged # Reduces file size by over 14% minifyHtml: prod: src: '.temp/index.html' ext: '.html' expand: true # Convert CoffeeScript classes to AngularJS modules ngClassify: app: files: [ cwd: '<%= settings.tempDirectory %>' src: '**/*.coffee' dest: '<%= settings.tempDirectory %>' expand: true ] # Creates a file to push views directly into the $templateCache # This will produce a file with the following content # # angular.module('app').run(['$templateCache', function ($templateCache) { # $templateCache.put('/views/directives/tab.html', '<div class="tab-pane" ng-class="{active: selected}" ng-transclude></div>'); # $templateCache.put('/views/directives/tabs.html', '<div class="tabbable"> <ul class="nav nav-tabs"> <li ng-repeat="tab in tabs" ng-class="{active:tab.selected}"> <a href="http://localhost:3005/scripts/views.js" ng-click="select(tab)">{{tab.caption}}</a> </li> </ul> <div class="tab-content" ng-transclude></div> </div>'); # $templateCache.put('/views/people.html', '<ul ng-hide="!people.length"> <li class="row" ng-repeat="person in people | orderBy:\'name\'"> <a ng-href="#/people/{{person.id}}" ng-bind="person.name"></a> </li> </ul>'); # $templateCache.put('/views/repos.html', '<ul ng-hide="!repos.length"> <li ng-repeat="repo in repos | orderBy:\'pushed_at\':true"> <a ng-href="{{repo.url}}" ng-bind="repo.name" target="_blank"></a> <div ng-bind="repo.description"></div> </li> </ul>'); # $templateCache.put('/views/tweets.html', '<ul ng-hide="!tweets.length"> <li class="row" ng-repeat="tweet in tweets"> <div class="span1 thumbnail"> <img ng-src="{{tweet.profile_image_url}}"/> </div> <div class="span6"> <div> <b ng-bind="tweet.from_user_name"></b> <a ng-href="https://twitter.com/{{tweet.from_user}}" ng-bind="tweet.from_user | twitterfy" target="_blank"></a> </div> <div ng-bind="tweet.text"></div> </div> </li> </ul>'); # }]); # # This file is then included in the output automatically # AngularJS will use it instead of going to the file system for the views, saving requests # Notice that the view content is actually minified. :) ngTemplateCache: views: files: '.temp/scripts/views.js': '.temp/**/*.html' options: trim: '<%= settings.tempDirectory %>' prompt: jslove: options: questions: [ { config: 'coffee.jslove.compile' type: 'input' message: 'Are you sure you wish to convert all CoffeeScript (.coffee) files to JavaScript (.js)?' + '\n' + 'This cannot be undone.'.red + ': (y/N)' default: false filter: (input) -> confirmed = /^y(es)?/i.test input if not confirmed grunt.fatal 'exiting jslove' return confirmed } ] # RequireJS optimizer configuration for both scripts and styles # This configuration is only used in the 'prod' build # The optimizer will scan the main file, walk the dependency tree, and write the output in dependent sequence to a single file # Since RequireJS is not being used outside of the main file or for dependency resolution (this is handled by AngularJS), RequireJS is not needed for final output and is excluded # RequireJS is still used for the 'dev' build # The main file is used only to establish the proper loading sequence requirejs: scripts: options: baseUrl: '.temp/scripts' findNestedDependencies: true logLevel: 0 mainConfigFile: '.temp/scripts/main.js' name: 'main' # Exclude main from the final output to avoid the dependency on RequireJS at runtime onBuildWrite: (moduleName, path, contents) -> modulesToExclude = ['main'] shouldExcludeModule = modulesToExclude.indexOf(moduleName) >= 0 return '' if shouldExcludeModule contents optimize: 'uglify2' out: '.temp/scripts/scripts.min.js' preserveLicenseComments: false skipModuleInsertion: true uglify: # Let uglifier replace variables to further reduce file size no_mangle: false useStrict: true wrap: start: '(function(){\'use strict\';' end: '}).call(this);' styles: options: baseUrl: '.temp/styles/' cssIn: '.temp/styles/styles.css' logLevel: 0 optimizeCss: 'standard' out: '.temp/styles/styles.min.css' # Creates main file for RequireJS shimmer: dev: cwd: '.temp/scripts' src: [ '**/*.{coffee,js}' '!libs/angular.{coffee,js}' '!libs/angular-animate.{coffee,js}' '!libs/angular-route.{coffee,js}' '!libs/html5shiv-printshiv.{coffee,js}' '!libs/json3.min.{coffee,js}' '!libs/require.{coffee,js}' ] order: [ 'libs/angular.min.js' 'NGAPP': 'ngAnimate': 'libs/angular-animate.min.js' 'ngMockE2E': 'libs/angular-mocks.js' 'ngRoute': 'libs/angular-route.min.js' ] require: 'NGBOOTSTRAP' prod: cwd: '<%= shimmer.dev.cwd %>' src: [ '**/*.{coffee,js}' '!libs/angular.{coffee,js}' '!libs/angular-animate.{coffee,js}' '!libs/angular-mocks.{coffee,js}' '!libs/angular-route.{coffee,js}' '!libs/html5shiv-printshiv.{coffee,js}' '!libs/json3.min.{coffee,js}' '!libs/require.{coffee,js}' '!backend/**/*.*' ] order: [ 'libs/angular.min.js' 'NGAPP': 'ngAnimate': 'libs/angular-animate.min.js' 'ngRoute': 'libs/angular-route.min.js' ] require: '<%= shimmer.dev.require %>' # Compiles underscore expressions # # The example below demonstrates the use of the environment configuration setting # In 'prod' build the hashed file of the concatenated and minified scripts is referened # In environments other than 'prod' the individual files are used and loaded with RequireJS # # <% if (config.environment === 'prod') { %> # <script src="<%= config.getHashedFile('.temp/scripts/scripts.min.js', {trim: '.temp'}) %>"></script> # <% } else { %> # <script data-main="/scripts/main.js" src="/scripts/libs/require.js"></script> # <% } %> template: indexDev: files: '.temp/index.html': '.temp/index.html' '.temp/index.jade': '.temp/index.jade' index: files: '<%= template.indexDev.files %>' environment: 'prod' # Concatenates and minifies JavaScript files uglify: scripts: files: '.temp/scripts/ie.min.js': [ '.temp/scripts/libs/json3.js' '.temp/scripts/libs/html5shiv-printshiv.js' ] # Run tasks when monitored files change watch: basic: files: [ 'src/fonts/**' 'src/images/**' 'src/scripts/**/*.js' 'src/styles/**/*.css' 'src/**/*.html' ] tasks: [ 'copy:app' 'copy:dev' 'karma' ] options: livereload: true nospawn: true coffee: files: 'src/scripts/**/*.coffee' tasks: [ 'clean:working' 'coffeelint' 'copy:app' 'shimmer:dev' 'ngClassify:app' 'coffee:app' 'copy:dev' 'karma' ] options: livereload: true nospawn: true jade: files: 'src/views/**/*.jade' tasks: [ 'copy:app' 'jade:views' 'copy:dev' 'karma' ] options: livereload: true nospawn: true less: files: 'src/styles/**/*.less' tasks: [ 'copy:app' 'less' 'copy:dev' ] options: livereload: true nospawn: true spaHtml: files: 'src/index.html' tasks: [ 'copy:app' 'template:indexDev' 'copy:dev' 'karma' ] options: livereload: true nospawn: true spaJade: files: 'src/index.jade' tasks: [ 'copy:app' 'template:indexDev' 'jade:spa' 'copy:dev' 'karma' ] options: livereload: true nospawn: true test: files: 'test/**/*.*' tasks: [ 'karma' ] # Used to keep the web server alive none: files: 'none' options: livereload: true # ensure only tasks are executed for the changed file # without this, the tasks for all files matching the original pattern are executed grunt.event.on 'watch', (action, filepath, key) -> file = filepath.substr(4) # trim "src/" from the beginning. I don't like what I'm doing here, need a better way of handling paths. dirname = path.dirname file ext = path.extname file basename = path.basename file, ext grunt.config ['copy', 'app'], cwd: 'src/' src: file dest: '.temp/' expand: true copyDevConfig = grunt.config ['copy', 'dev'] copyDevConfig.src = file if key is 'coffee' # delete associated temp file prior to performing remaining tasks # without doing so, shimmer may fail grunt.config ['clean', 'working'], [ path.join('.temp', dirname, "#{basename}.{coffee,js,js.map}") ] copyDevConfig.src = [ path.join(dirname, "#{basename}.{coffee,js,js.map}") 'scripts/main.{coffee,js,js.map}' ] coffeeConfig = grunt.config ['coffee', 'app', 'files'] coffeeConfig.src = file coffeeLintConfig = grunt.config ['coffeelint', 'app', 'files'] coffeeLintConfig = filepath grunt.config ['coffee', 'app', 'files'], coffeeConfig grunt.config ['coffeelint', 'app', 'files'], coffeeLintConfig if key is 'PI:KEY:<KEY>END_PI' copyDevConfig.src = path.join(dirname, "#{basename}.{jade,html}") if key is 'PI:KEY:<KEY>END_PI' copyDevConfig.src = path.join(dirname, "#{basename}.{jade,html}") jadeConfig = grunt.config ['jade', 'views'] jadeConfig.src = file grunt.config ['jade', 'views'], jadeConfig if key is 'less' copyDevConfig.src = [ path.join(dirname, "#{basename}.{less,css}") path.join(dirname, 'styles.css') ] grunt.config ['copy', 'dev'], copyDevConfig # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Enter the following command at the command line to execute this build task: # grunt build grunt.registerTask 'build', [ 'clean:working' 'bower:install' 'coffeelint' 'copy:app' 'jade' 'shimmer:dev' 'ngClassify' 'coffee:app' 'less' 'template:indexDev' 'copy:dev' ] # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Opens the app in the default browser # Watches for file changes, and compiles and reloads the web browser upon change # Enter the following command at the command line to execute this build task: # grunt or grunt default grunt.registerTask 'default', [ 'build' 'connect' 'watch' ] # Identical to the default build task # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Opens the app in the default browser # Watches for file changes, and compiles and reloads the web browser upon change # Enter the following command at the command line to execute this build task: # grunt dev grunt.registerTask 'dev', [ 'default' ] # Compiles the app with optimized build settings # Places the build artifacts in the dist directory # Enter the following command at the command line to execute this build task: # grunt prod grunt.registerTask 'prod', [ 'clean:working' 'bower:install' 'coffeelint' 'copy:app' 'jade:views' 'ngTemplateCache' 'shimmer:prod' 'ngClassify' 'coffee:app' 'imagemin' 'hash:images' 'less' 'requirejs' 'uglify' 'hash:scripts' 'hash:styles' 'template:index' 'jade:spa' 'minifyHtml' 'copy:prod' ] # Opens the app in the default browser # Build artifacts must be in the dist directory via a prior grunt build, grunt, grunt dev, or grunt prod # Enter the following command at the command line to execute this build task: # grunt server grunt.registerTask 'server', [ 'connect' 'watch:none' ] # Looks like the prevailing winds are pointing to use 'serve' instead of 'server' # Why not both? :) # grunt serve grunt.registerTask 'serve', [ 'server' ] # Compiles the app with non-optimized build settings # Places the build artifacts in the dist directory # Runs unit tests via karma # Enter the following command at the command line to execute this build task: # grunt test grunt.registerTask 'test', [ 'build' 'karma' ] # Compiles all CoffeeScript files in the project to JavaScript then deletes all CoffeeScript files # Used for those that desire plain old JavaScript # Enter the following command at the command line to execute this build task: # grunt jslove grunt.registerTask 'jslove', [ 'prompt:jslove' 'coffee:jslove' 'clean:jslove' ]
[ { "context": "ileoverview Tests for dot-notation rule.\n# @author Josh Perez\n###\n\n'use strict'\n\n#-----------------------------", "end": 70, "score": 0.9998437166213989, "start": 60, "tag": "NAME", "value": "Josh Perez" } ]
src/tests/rules/dot-notation.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for dot-notation rule. # @author Josh Perez ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/dot-notation' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ###* # Quote a string in "double quotes" because it’s painful # with a double-quoted string literal # @param {string} str The string to quote # @returns {string} `"${str}"` ### q = (str) -> "\"#{str}\"" ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'dot-notation', rule, valid: [ 'a.b' 'a.b.c' "a['12']" 'a[b]' 'a[0]' , code: 'a.b.c', options: [allowKeywords: no] , code: 'a.arguments', options: [allowKeywords: no] , code: 'a.let', options: [allowKeywords: no] , code: 'a.yield', options: [allowKeywords: no] , code: 'a.eval', options: [allowKeywords: no] , code: 'a[0]', options: [allowKeywords: no] , code: "a['while']", options: [allowKeywords: no] , code: "a['true']", options: [allowKeywords: no] , code: "a['null']", options: [allowKeywords: no] , code: 'a[true]', options: [allowKeywords: no] , code: 'a[null]', options: [allowKeywords: no] , code: 'a.true', options: [allowKeywords: yes] , code: 'a.null', options: [allowKeywords: yes] , code: "a['snake_case']", options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] , code: "a['lots_of_snake_case']" options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] , 'a["time#{range}"]' , code: 'a["""while"""]' options: [allowKeywords: no] , 'a["time range"]' 'a.true' 'a.null' 'a[undefined]' 'a[b()]' ] invalid: [ code: 'a.true' output: 'a["true"]' options: [allowKeywords: no] errors: [messageId: 'useBrackets', data: key: 'true'] , code: "a['true']" output: 'a.true' errors: [messageId: 'useDot', data: key: q 'true'] , code: 'a["time"]' output: 'a.time' errors: [messageId: 'useDot', data: key: '"time"'] , code: 'a[null]' output: 'a.null' errors: [messageId: 'useDot', data: key: 'null'] , code: "a['b']" output: 'a.b' errors: [messageId: 'useDot', data: key: q 'b'] , code: "a.b['c']" output: 'a.b.c' errors: [messageId: 'useDot', data: key: q 'c'] , code: "a['_dangle']" output: 'a._dangle' options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] errors: [messageId: 'useDot', data: key: q '_dangle'] , code: "a['SHOUT_CASE']" output: 'a.SHOUT_CASE' options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] errors: [messageId: 'useDot', data: key: q 'SHOUT_CASE'] , code: ''' getResource() .then(->)["catch"](->) .then(->)["catch"](->) ''' output: ''' getResource() .then(->).catch(->) .then(->).catch(->) ''' errors: [ messageId: 'useDot' data: key: q 'catch' line: 2 column: 15 , messageId: 'useDot' data: key: q 'catch' line: 3 column: 15 ] , # , # code: # 'foo\n' + ' .while' # output: # 'foo\n' + ' ["while"]' # options: [allowKeywords: no] # errors: [messageId: 'useBrackets', data: key: 'while'] code: "foo[ ### comment ### 'bar' ]" output: null # Not fixed due to comment errors: [messageId: 'useDot', data: key: q 'bar'] , code: "foo[ 'bar' ### comment ### ]" output: null # Not fixed due to comment errors: [messageId: 'useDot', data: key: q 'bar'] , code: "foo[ 'bar' ]" output: 'foo.bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: 'foo. ### comment ### while' output: null # Not fixed due to comment options: [allowKeywords: no] errors: [messageId: 'useBrackets', data: key: 'while'] , code: "foo[('bar')]" output: 'foo.bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: 'foo[(null)]' output: 'foo.null' errors: [messageId: 'useDot', data: key: 'null'] , code: "(foo)['bar']" output: '(foo).bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: "1['toString']" output: '1 .toString' errors: [messageId: 'useDot', data: key: q 'toString'] , code: "foo['bar']instanceof baz" output: 'foo.bar instanceof baz' errors: [messageId: 'useDot', data: key: q 'bar'] ]
30252
###* # @fileoverview Tests for dot-notation rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/dot-notation' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ###* # Quote a string in "double quotes" because it’s painful # with a double-quoted string literal # @param {string} str The string to quote # @returns {string} `"${str}"` ### q = (str) -> "\"#{str}\"" ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'dot-notation', rule, valid: [ 'a.b' 'a.b.c' "a['12']" 'a[b]' 'a[0]' , code: 'a.b.c', options: [allowKeywords: no] , code: 'a.arguments', options: [allowKeywords: no] , code: 'a.let', options: [allowKeywords: no] , code: 'a.yield', options: [allowKeywords: no] , code: 'a.eval', options: [allowKeywords: no] , code: 'a[0]', options: [allowKeywords: no] , code: "a['while']", options: [allowKeywords: no] , code: "a['true']", options: [allowKeywords: no] , code: "a['null']", options: [allowKeywords: no] , code: 'a[true]', options: [allowKeywords: no] , code: 'a[null]', options: [allowKeywords: no] , code: 'a.true', options: [allowKeywords: yes] , code: 'a.null', options: [allowKeywords: yes] , code: "a['snake_case']", options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] , code: "a['lots_of_snake_case']" options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] , 'a["time#{range}"]' , code: 'a["""while"""]' options: [allowKeywords: no] , 'a["time range"]' 'a.true' 'a.null' 'a[undefined]' 'a[b()]' ] invalid: [ code: 'a.true' output: 'a["true"]' options: [allowKeywords: no] errors: [messageId: 'useBrackets', data: key: 'true'] , code: "a['true']" output: 'a.true' errors: [messageId: 'useDot', data: key: q 'true'] , code: 'a["time"]' output: 'a.time' errors: [messageId: 'useDot', data: key: '"time"'] , code: 'a[null]' output: 'a.null' errors: [messageId: 'useDot', data: key: 'null'] , code: "a['b']" output: 'a.b' errors: [messageId: 'useDot', data: key: q 'b'] , code: "a.b['c']" output: 'a.b.c' errors: [messageId: 'useDot', data: key: q 'c'] , code: "a['_dangle']" output: 'a._dangle' options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] errors: [messageId: 'useDot', data: key: q '_dangle'] , code: "a['SHOUT_CASE']" output: 'a.SHOUT_CASE' options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] errors: [messageId: 'useDot', data: key: q 'SHOUT_CASE'] , code: ''' getResource() .then(->)["catch"](->) .then(->)["catch"](->) ''' output: ''' getResource() .then(->).catch(->) .then(->).catch(->) ''' errors: [ messageId: 'useDot' data: key: q 'catch' line: 2 column: 15 , messageId: 'useDot' data: key: q 'catch' line: 3 column: 15 ] , # , # code: # 'foo\n' + ' .while' # output: # 'foo\n' + ' ["while"]' # options: [allowKeywords: no] # errors: [messageId: 'useBrackets', data: key: 'while'] code: "foo[ ### comment ### 'bar' ]" output: null # Not fixed due to comment errors: [messageId: 'useDot', data: key: q 'bar'] , code: "foo[ 'bar' ### comment ### ]" output: null # Not fixed due to comment errors: [messageId: 'useDot', data: key: q 'bar'] , code: "foo[ 'bar' ]" output: 'foo.bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: 'foo. ### comment ### while' output: null # Not fixed due to comment options: [allowKeywords: no] errors: [messageId: 'useBrackets', data: key: 'while'] , code: "foo[('bar')]" output: 'foo.bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: 'foo[(null)]' output: 'foo.null' errors: [messageId: 'useDot', data: key: 'null'] , code: "(foo)['bar']" output: '(foo).bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: "1['toString']" output: '1 .toString' errors: [messageId: 'useDot', data: key: q 'toString'] , code: "foo['bar']instanceof baz" output: 'foo.bar instanceof baz' errors: [messageId: 'useDot', data: key: q 'bar'] ]
true
###* # @fileoverview Tests for dot-notation rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/dot-notation' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ###* # Quote a string in "double quotes" because it’s painful # with a double-quoted string literal # @param {string} str The string to quote # @returns {string} `"${str}"` ### q = (str) -> "\"#{str}\"" ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'dot-notation', rule, valid: [ 'a.b' 'a.b.c' "a['12']" 'a[b]' 'a[0]' , code: 'a.b.c', options: [allowKeywords: no] , code: 'a.arguments', options: [allowKeywords: no] , code: 'a.let', options: [allowKeywords: no] , code: 'a.yield', options: [allowKeywords: no] , code: 'a.eval', options: [allowKeywords: no] , code: 'a[0]', options: [allowKeywords: no] , code: "a['while']", options: [allowKeywords: no] , code: "a['true']", options: [allowKeywords: no] , code: "a['null']", options: [allowKeywords: no] , code: 'a[true]', options: [allowKeywords: no] , code: 'a[null]', options: [allowKeywords: no] , code: 'a.true', options: [allowKeywords: yes] , code: 'a.null', options: [allowKeywords: yes] , code: "a['snake_case']", options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] , code: "a['lots_of_snake_case']" options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] , 'a["time#{range}"]' , code: 'a["""while"""]' options: [allowKeywords: no] , 'a["time range"]' 'a.true' 'a.null' 'a[undefined]' 'a[b()]' ] invalid: [ code: 'a.true' output: 'a["true"]' options: [allowKeywords: no] errors: [messageId: 'useBrackets', data: key: 'true'] , code: "a['true']" output: 'a.true' errors: [messageId: 'useDot', data: key: q 'true'] , code: 'a["time"]' output: 'a.time' errors: [messageId: 'useDot', data: key: '"time"'] , code: 'a[null]' output: 'a.null' errors: [messageId: 'useDot', data: key: 'null'] , code: "a['b']" output: 'a.b' errors: [messageId: 'useDot', data: key: q 'b'] , code: "a.b['c']" output: 'a.b.c' errors: [messageId: 'useDot', data: key: q 'c'] , code: "a['_dangle']" output: 'a._dangle' options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] errors: [messageId: 'useDot', data: key: q '_dangle'] , code: "a['SHOUT_CASE']" output: 'a.SHOUT_CASE' options: [allowPattern: '^[a-z]+(_[a-z]+)+$'] errors: [messageId: 'useDot', data: key: q 'SHOUT_CASE'] , code: ''' getResource() .then(->)["catch"](->) .then(->)["catch"](->) ''' output: ''' getResource() .then(->).catch(->) .then(->).catch(->) ''' errors: [ messageId: 'useDot' data: key: q 'catch' line: 2 column: 15 , messageId: 'useDot' data: key: q 'catch' line: 3 column: 15 ] , # , # code: # 'foo\n' + ' .while' # output: # 'foo\n' + ' ["while"]' # options: [allowKeywords: no] # errors: [messageId: 'useBrackets', data: key: 'while'] code: "foo[ ### comment ### 'bar' ]" output: null # Not fixed due to comment errors: [messageId: 'useDot', data: key: q 'bar'] , code: "foo[ 'bar' ### comment ### ]" output: null # Not fixed due to comment errors: [messageId: 'useDot', data: key: q 'bar'] , code: "foo[ 'bar' ]" output: 'foo.bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: 'foo. ### comment ### while' output: null # Not fixed due to comment options: [allowKeywords: no] errors: [messageId: 'useBrackets', data: key: 'while'] , code: "foo[('bar')]" output: 'foo.bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: 'foo[(null)]' output: 'foo.null' errors: [messageId: 'useDot', data: key: 'null'] , code: "(foo)['bar']" output: '(foo).bar' errors: [messageId: 'useDot', data: key: q 'bar'] , code: "1['toString']" output: '1 .toString' errors: [messageId: 'useDot', data: key: q 'toString'] , code: "foo['bar']instanceof baz" output: 'foo.bar instanceof baz' errors: [messageId: 'useDot', data: key: q 'bar'] ]
[ { "context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ", "end": 33, "score": 0.9998614192008972, "start": 21, "tag": "NAME", "value": "John Judnich" } ]
source/ContentCache.coffee
anandprabhakar0507/Kosmos
46
# Copyright (C) 2013 John Judnich # Released under The MIT License - see "LICENSE" file for details. root = exports ? this # This object lets you manage a number of content objects which are uniquely identifiable with some # string or integer identifier in such a way that you can simply query them frequently and loading/unloading # will be managed automatically (with old content unloaded when the cache "spills" with too many items) # # Moreover, this allows progressive loading that may take multiple calls to the load function to "fully" load # an item. This is handled by your loader function returning a pair of [finished, object], so only when # finished==true does the cache consider the object loaded and return it to the original requester. class root.ContentCache # maxItems sets the maximum number of content items that may be loaded at any given time. # loaderCallback should accept two parameters (contentId, partialContent) and return a pair # [finished, object], where finished is a boolean true/false representing whether the returned # "object" is fully loaded. This allows you to implement progressive loading where several load steps # should be spaced out across several frames. The first call to loaderCallback will provide the # partialContent parameter as null. If your callback returns "finished == false", then the loader # will be called again in the future. In each successive call to your callback, "partialContent" # provides the "object" value returned from the last call to your callback. Only when # "finished == true" will the "object" be considered valid, and returned to the requester via # non-null return value of contentCache.getContent(). constructor: (maxItems, loaderCallback) -> @loadedItems = {} # { contentId: [content, timestamp] } @loadedCount = 0 @queuedItems = [] # list of [contentId, partialContent] pending load @queuedIdSet = {} # set of contentIds pending load (to prevent duplicate insertion) @maxItems = maxItems # the maximum number of items to cache before deleting old items @loaderCallback = loaderCallback # Call this as frequently as desired to get the loaded content object corresponding to contentId. # The object this returns should be identical in content to if you called loaderCallback(contentId), # with the performance difference that this manages a cache of already loaded content. getContent: (contentId) -> if @loadedItems[contentId] != undefined item = @loadedItems[contentId] item[1] = (new Date()).getTime() return item[0] if not @queuedIdSet.hasOwnProperty(contentId) @queuedItems.push({contentId: contentId, partialContent: null}) @queuedIdSet[contentId] = true return null # returns true if there is nothing more to load isUpToDate: -> return (@queuedItems.length == 0) # The "getContent" method does not actually load or unload anything. It queues these jobs, so when # you call update() all the pending loads and unloads are performed. The parameter allows you to adjust # how many pending items at most may be loaded by this function call. update: (maxItemsToLoad = 1) -> @_evictOldItems() len = Math.min(@queuedItems.length, maxItemsToLoad) if len <= 0 then return for i in [0 .. len-1] loadTask = @queuedItems.pop() if loadTask != undefined and @loadedItems[loadTask] == undefined [finished, loadedObject] = @loaderCallback(loadTask.contentId, loadTask.partialContent) if finished == true # loading has finished - add to the loaded item map @loadedItems[loadTask.contentId] = [loadedObject, (new Date()).getTime()] @loadedCount++ delete @queuedIdSet[loadTask.contentId] else # loading hasn't finished - push the task back in the queue with the updated object loadTask.partialContent = loadedObject @queuedItems.push(loadTask) _evictOldItems: -> if @loadedCount > @maxItems keys = Object.keys(@loadedItems) while @loadedCount > @maxItems lastUsedSeed = null lastUsed = null # find loaded item with min time for contentId in keys thisLastUsed = @loadedItems[contentId][1] if lastUsedSeed == null or thisLastUsed < lastUsed lastUsed = thisLastUsed lastUsedSeed = contentId #delete it console.log("Evicting content: " + lastUsedSeed) delete @loadedItems[lastUsedSeed] @loadedCount--
4080
# Copyright (C) 2013 <NAME> # Released under The MIT License - see "LICENSE" file for details. root = exports ? this # This object lets you manage a number of content objects which are uniquely identifiable with some # string or integer identifier in such a way that you can simply query them frequently and loading/unloading # will be managed automatically (with old content unloaded when the cache "spills" with too many items) # # Moreover, this allows progressive loading that may take multiple calls to the load function to "fully" load # an item. This is handled by your loader function returning a pair of [finished, object], so only when # finished==true does the cache consider the object loaded and return it to the original requester. class root.ContentCache # maxItems sets the maximum number of content items that may be loaded at any given time. # loaderCallback should accept two parameters (contentId, partialContent) and return a pair # [finished, object], where finished is a boolean true/false representing whether the returned # "object" is fully loaded. This allows you to implement progressive loading where several load steps # should be spaced out across several frames. The first call to loaderCallback will provide the # partialContent parameter as null. If your callback returns "finished == false", then the loader # will be called again in the future. In each successive call to your callback, "partialContent" # provides the "object" value returned from the last call to your callback. Only when # "finished == true" will the "object" be considered valid, and returned to the requester via # non-null return value of contentCache.getContent(). constructor: (maxItems, loaderCallback) -> @loadedItems = {} # { contentId: [content, timestamp] } @loadedCount = 0 @queuedItems = [] # list of [contentId, partialContent] pending load @queuedIdSet = {} # set of contentIds pending load (to prevent duplicate insertion) @maxItems = maxItems # the maximum number of items to cache before deleting old items @loaderCallback = loaderCallback # Call this as frequently as desired to get the loaded content object corresponding to contentId. # The object this returns should be identical in content to if you called loaderCallback(contentId), # with the performance difference that this manages a cache of already loaded content. getContent: (contentId) -> if @loadedItems[contentId] != undefined item = @loadedItems[contentId] item[1] = (new Date()).getTime() return item[0] if not @queuedIdSet.hasOwnProperty(contentId) @queuedItems.push({contentId: contentId, partialContent: null}) @queuedIdSet[contentId] = true return null # returns true if there is nothing more to load isUpToDate: -> return (@queuedItems.length == 0) # The "getContent" method does not actually load or unload anything. It queues these jobs, so when # you call update() all the pending loads and unloads are performed. The parameter allows you to adjust # how many pending items at most may be loaded by this function call. update: (maxItemsToLoad = 1) -> @_evictOldItems() len = Math.min(@queuedItems.length, maxItemsToLoad) if len <= 0 then return for i in [0 .. len-1] loadTask = @queuedItems.pop() if loadTask != undefined and @loadedItems[loadTask] == undefined [finished, loadedObject] = @loaderCallback(loadTask.contentId, loadTask.partialContent) if finished == true # loading has finished - add to the loaded item map @loadedItems[loadTask.contentId] = [loadedObject, (new Date()).getTime()] @loadedCount++ delete @queuedIdSet[loadTask.contentId] else # loading hasn't finished - push the task back in the queue with the updated object loadTask.partialContent = loadedObject @queuedItems.push(loadTask) _evictOldItems: -> if @loadedCount > @maxItems keys = Object.keys(@loadedItems) while @loadedCount > @maxItems lastUsedSeed = null lastUsed = null # find loaded item with min time for contentId in keys thisLastUsed = @loadedItems[contentId][1] if lastUsedSeed == null or thisLastUsed < lastUsed lastUsed = thisLastUsed lastUsedSeed = contentId #delete it console.log("Evicting content: " + lastUsedSeed) delete @loadedItems[lastUsedSeed] @loadedCount--
true
# Copyright (C) 2013 PI:NAME:<NAME>END_PI # Released under The MIT License - see "LICENSE" file for details. root = exports ? this # This object lets you manage a number of content objects which are uniquely identifiable with some # string or integer identifier in such a way that you can simply query them frequently and loading/unloading # will be managed automatically (with old content unloaded when the cache "spills" with too many items) # # Moreover, this allows progressive loading that may take multiple calls to the load function to "fully" load # an item. This is handled by your loader function returning a pair of [finished, object], so only when # finished==true does the cache consider the object loaded and return it to the original requester. class root.ContentCache # maxItems sets the maximum number of content items that may be loaded at any given time. # loaderCallback should accept two parameters (contentId, partialContent) and return a pair # [finished, object], where finished is a boolean true/false representing whether the returned # "object" is fully loaded. This allows you to implement progressive loading where several load steps # should be spaced out across several frames. The first call to loaderCallback will provide the # partialContent parameter as null. If your callback returns "finished == false", then the loader # will be called again in the future. In each successive call to your callback, "partialContent" # provides the "object" value returned from the last call to your callback. Only when # "finished == true" will the "object" be considered valid, and returned to the requester via # non-null return value of contentCache.getContent(). constructor: (maxItems, loaderCallback) -> @loadedItems = {} # { contentId: [content, timestamp] } @loadedCount = 0 @queuedItems = [] # list of [contentId, partialContent] pending load @queuedIdSet = {} # set of contentIds pending load (to prevent duplicate insertion) @maxItems = maxItems # the maximum number of items to cache before deleting old items @loaderCallback = loaderCallback # Call this as frequently as desired to get the loaded content object corresponding to contentId. # The object this returns should be identical in content to if you called loaderCallback(contentId), # with the performance difference that this manages a cache of already loaded content. getContent: (contentId) -> if @loadedItems[contentId] != undefined item = @loadedItems[contentId] item[1] = (new Date()).getTime() return item[0] if not @queuedIdSet.hasOwnProperty(contentId) @queuedItems.push({contentId: contentId, partialContent: null}) @queuedIdSet[contentId] = true return null # returns true if there is nothing more to load isUpToDate: -> return (@queuedItems.length == 0) # The "getContent" method does not actually load or unload anything. It queues these jobs, so when # you call update() all the pending loads and unloads are performed. The parameter allows you to adjust # how many pending items at most may be loaded by this function call. update: (maxItemsToLoad = 1) -> @_evictOldItems() len = Math.min(@queuedItems.length, maxItemsToLoad) if len <= 0 then return for i in [0 .. len-1] loadTask = @queuedItems.pop() if loadTask != undefined and @loadedItems[loadTask] == undefined [finished, loadedObject] = @loaderCallback(loadTask.contentId, loadTask.partialContent) if finished == true # loading has finished - add to the loaded item map @loadedItems[loadTask.contentId] = [loadedObject, (new Date()).getTime()] @loadedCount++ delete @queuedIdSet[loadTask.contentId] else # loading hasn't finished - push the task back in the queue with the updated object loadTask.partialContent = loadedObject @queuedItems.push(loadTask) _evictOldItems: -> if @loadedCount > @maxItems keys = Object.keys(@loadedItems) while @loadedCount > @maxItems lastUsedSeed = null lastUsed = null # find loaded item with min time for contentId in keys thisLastUsed = @loadedItems[contentId][1] if lastUsedSeed == null or thisLastUsed < lastUsed lastUsed = thisLastUsed lastUsedSeed = contentId #delete it console.log("Evicting content: " + lastUsedSeed) delete @loadedItems[lastUsedSeed] @loadedCount--
[ { "context": "y to rock!'\n return\n # See https://github.com/Polymer/polymer/issues/1381\n window.addEventListener 'We", "end": 1515, "score": 0.9993410110473633, "start": 1508, "tag": "USERNAME", "value": "Polymer" }, { "context": "er()\n return\n\n app.myListItems = [\n name: 'nina'\n gender: 'female'\n ,\n name: 'hannibal'\n ", "end": 3348, "score": 0.9985722899436951, "start": 3344, "tag": "NAME", "value": "nina" }, { "context": " name: 'nina'\n gender: 'female'\n ,\n name: 'hannibal'\n gender: 'male'\n ]\n return\n", "end": 3394, "score": 0.9997492432594299, "start": 3386, "tag": "NAME", "value": "hannibal" } ]
public/javascripts/app.coffee
mafiuss/sandcat
1
### Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt ### do (document) -> 'use strict' # Grab a reference to our auto-binding template # and give it some initial binding values # Learn more about auto-binding templates at http://goo.gl/Dx1u2g app = document.querySelector('#app') # Sets app default base URL app.baseUrl = '/' if window.location.port == '' # if production # Uncomment app.baseURL below and # set app.baseURL to '/your-pathname/' if running from folder in production app.baseUrl = '/mountpath/'; app.displayInstalledToast = -> # Check to make sure caching is actually enabled—it won't be in the dev environment. if !Polymer.dom(document).querySelector('platinum-sw-cache').disabled Polymer.dom(document).querySelector('#caching-complete').show() return # Listen for template bound event to know when bindings # have resolved and content has been stamped to the page app.addEventListener 'dom-change', -> console.log 'Our app is ready to rock!' return # See https://github.com/Polymer/polymer/issues/1381 window.addEventListener 'WebComponentsReady', -> # imports are loaded and elements have been registered return # Main area's paper-scroll-header-panel custom condensing transformation of # the appName in the middle-container and the bottom title in the bottom-container. # The appName is moved to top and shrunk on condensing. The bottom sub title # is shrunk to nothing on condensing. window.addEventListener 'paper-header-transform', (e) -> appName = Polymer.dom(document).querySelector('#mainToolbar .app-name') middleContainer = Polymer.dom(document).querySelector('#mainToolbar .middle-container') bottomContainer = Polymer.dom(document).querySelector('#mainToolbar .bottom-container') detail = e.detail heightDiff = detail.height - (detail.condensedHeight) yRatio = Math.min(1, detail.y / heightDiff) # appName max size when condensed. The smaller the number the smaller the condensed size. maxMiddleScale = 0.50 auxHeight = heightDiff - (detail.y) auxScale = heightDiff / (1 - maxMiddleScale) scaleMiddle = Math.max(maxMiddleScale, auxHeight / auxScale + maxMiddleScale) scaleBottom = 1 - yRatio # Move/translate middleContainer Polymer.Base.transform 'translate3d(0,' + yRatio * 100 + '%,0)', middleContainer # Scale bottomContainer and bottom sub title to nothing and back Polymer.Base.transform 'scale(' + scaleBottom + ') translateZ(0)', bottomContainer # Scale middleContainer appName Polymer.Base.transform 'scale(' + scaleMiddle + ') translateZ(0)', appName return # Scroll page to top and expand header app.scrollPageToTop = -> app.$.headerPanelMain.scrollToTop true return app.closeDrawer = -> app.$.paperDrawerPanel.closeDrawer() return app.myListItems = [ name: 'nina' gender: 'female' , name: 'hannibal' gender: 'male' ] return
66120
### Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt ### do (document) -> 'use strict' # Grab a reference to our auto-binding template # and give it some initial binding values # Learn more about auto-binding templates at http://goo.gl/Dx1u2g app = document.querySelector('#app') # Sets app default base URL app.baseUrl = '/' if window.location.port == '' # if production # Uncomment app.baseURL below and # set app.baseURL to '/your-pathname/' if running from folder in production app.baseUrl = '/mountpath/'; app.displayInstalledToast = -> # Check to make sure caching is actually enabled—it won't be in the dev environment. if !Polymer.dom(document).querySelector('platinum-sw-cache').disabled Polymer.dom(document).querySelector('#caching-complete').show() return # Listen for template bound event to know when bindings # have resolved and content has been stamped to the page app.addEventListener 'dom-change', -> console.log 'Our app is ready to rock!' return # See https://github.com/Polymer/polymer/issues/1381 window.addEventListener 'WebComponentsReady', -> # imports are loaded and elements have been registered return # Main area's paper-scroll-header-panel custom condensing transformation of # the appName in the middle-container and the bottom title in the bottom-container. # The appName is moved to top and shrunk on condensing. The bottom sub title # is shrunk to nothing on condensing. window.addEventListener 'paper-header-transform', (e) -> appName = Polymer.dom(document).querySelector('#mainToolbar .app-name') middleContainer = Polymer.dom(document).querySelector('#mainToolbar .middle-container') bottomContainer = Polymer.dom(document).querySelector('#mainToolbar .bottom-container') detail = e.detail heightDiff = detail.height - (detail.condensedHeight) yRatio = Math.min(1, detail.y / heightDiff) # appName max size when condensed. The smaller the number the smaller the condensed size. maxMiddleScale = 0.50 auxHeight = heightDiff - (detail.y) auxScale = heightDiff / (1 - maxMiddleScale) scaleMiddle = Math.max(maxMiddleScale, auxHeight / auxScale + maxMiddleScale) scaleBottom = 1 - yRatio # Move/translate middleContainer Polymer.Base.transform 'translate3d(0,' + yRatio * 100 + '%,0)', middleContainer # Scale bottomContainer and bottom sub title to nothing and back Polymer.Base.transform 'scale(' + scaleBottom + ') translateZ(0)', bottomContainer # Scale middleContainer appName Polymer.Base.transform 'scale(' + scaleMiddle + ') translateZ(0)', appName return # Scroll page to top and expand header app.scrollPageToTop = -> app.$.headerPanelMain.scrollToTop true return app.closeDrawer = -> app.$.paperDrawerPanel.closeDrawer() return app.myListItems = [ name: '<NAME>' gender: 'female' , name: '<NAME>' gender: 'male' ] return
true
### Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt ### do (document) -> 'use strict' # Grab a reference to our auto-binding template # and give it some initial binding values # Learn more about auto-binding templates at http://goo.gl/Dx1u2g app = document.querySelector('#app') # Sets app default base URL app.baseUrl = '/' if window.location.port == '' # if production # Uncomment app.baseURL below and # set app.baseURL to '/your-pathname/' if running from folder in production app.baseUrl = '/mountpath/'; app.displayInstalledToast = -> # Check to make sure caching is actually enabled—it won't be in the dev environment. if !Polymer.dom(document).querySelector('platinum-sw-cache').disabled Polymer.dom(document).querySelector('#caching-complete').show() return # Listen for template bound event to know when bindings # have resolved and content has been stamped to the page app.addEventListener 'dom-change', -> console.log 'Our app is ready to rock!' return # See https://github.com/Polymer/polymer/issues/1381 window.addEventListener 'WebComponentsReady', -> # imports are loaded and elements have been registered return # Main area's paper-scroll-header-panel custom condensing transformation of # the appName in the middle-container and the bottom title in the bottom-container. # The appName is moved to top and shrunk on condensing. The bottom sub title # is shrunk to nothing on condensing. window.addEventListener 'paper-header-transform', (e) -> appName = Polymer.dom(document).querySelector('#mainToolbar .app-name') middleContainer = Polymer.dom(document).querySelector('#mainToolbar .middle-container') bottomContainer = Polymer.dom(document).querySelector('#mainToolbar .bottom-container') detail = e.detail heightDiff = detail.height - (detail.condensedHeight) yRatio = Math.min(1, detail.y / heightDiff) # appName max size when condensed. The smaller the number the smaller the condensed size. maxMiddleScale = 0.50 auxHeight = heightDiff - (detail.y) auxScale = heightDiff / (1 - maxMiddleScale) scaleMiddle = Math.max(maxMiddleScale, auxHeight / auxScale + maxMiddleScale) scaleBottom = 1 - yRatio # Move/translate middleContainer Polymer.Base.transform 'translate3d(0,' + yRatio * 100 + '%,0)', middleContainer # Scale bottomContainer and bottom sub title to nothing and back Polymer.Base.transform 'scale(' + scaleBottom + ') translateZ(0)', bottomContainer # Scale middleContainer appName Polymer.Base.transform 'scale(' + scaleMiddle + ') translateZ(0)', appName return # Scroll page to top and expand header app.scrollPageToTop = -> app.$.headerPanelMain.scrollToTop true return app.closeDrawer = -> app.$.paperDrawerPanel.closeDrawer() return app.myListItems = [ name: 'PI:NAME:<NAME>END_PI' gender: 'female' , name: 'PI:NAME:<NAME>END_PI' gender: 'male' ] return
[ { "context": "ts: =>\n @props.tokens.map (item) =>\n key = @props.tokenKey(item)\n valid = true\n if @props.tokenIsV", "end": 10658, "score": 0.6704034209251404, "start": 10643, "tag": "KEY", "value": "@props.tokenKey" } ]
app/src/components/tokenizing-text-field.cjsx
immershy/nodemail
0
React = require 'react' ReactDOM = require 'react-dom' classNames = require 'classnames' _ = require 'underscore' {CompositeDisposable} = require 'event-kit' {Utils, Contact, RegExpUtils} = require 'nylas-exports' RetinaImg = require './retina-img' class SizeToFitInput extends React.Component constructor: (@props) -> @state = {} componentDidMount: => @_sizeToFit() componentDidUpdate: => @_sizeToFit() _sizeToFit: => # Measure the width of the text in the input and # resize the input field to fit. input = ReactDOM.findDOMNode(@refs.input) measure = ReactDOM.findDOMNode(@refs.measure) measure.innerText = input.value measure.style.top = input.offsetTop + "px" measure.style.left = input.offsetLeft + "px" # The 10px comes from the 7.5px left padding and 2.5px more of # breathing room. input.style.width = "#{measure.offsetWidth+10}px" render: => <span> <span ref="measure" style={visibility:'hidden', position: 'absolute'}></span> <input ref="input" type="text" {...@props}/> </span> select: => ReactDOM.findDOMNode(@refs.input).select() focus: => ReactDOM.findDOMNode(@refs.input).focus() class Token extends React.Component @displayName: "Token" @propTypes: className: React.PropTypes.string, selected: React.PropTypes.bool, valid: React.PropTypes.bool, item: React.PropTypes.object, onSelected: React.PropTypes.func.isRequired, onEdited: React.PropTypes.func, onAction: React.PropTypes.func @defaultProps: className: '' constructor: (@props) -> @state = editing: false editingValue: @props.item.toString() render: => if @state.editing @_renderEditing() else @_renderViewing() componentDidUpdate: (prevProps, prevState) => if @state.editing && !prevState.editing @refs.input.select() componentWillReceiveProps: (props) => # never override the text the user is editing if they're looking at it return if @state.editing @setState(editingValue: @props.item.toString()) _renderEditing: => <SizeToFitInput ref="input" className="token-editing-input" spellCheck="false" value={@state.editingValue} onKeyDown={@_onEditKeydown} onBlur={@_onEditFinished} onChange={ (event) => @setState(editingValue: event.target.value)}/> _renderViewing: => classes = classNames "token": true "dragging": @state.dragging "invalid": !@props.valid "selected": @props.selected <div className={"#{classes} #{@props.className}"} onDragStart={@_onDragStart} onDragEnd={@_onDragEnd} draggable="true" onDoubleClick={@_onDoubleClick} onClick={@_onSelect}> {if @props.onAction <button className="action" onClick={@_onAction} tabIndex={-1}> <RetinaImg mode={RetinaImg.Mode.ContentIsMask} name="composer-caret.png" /> </button> } {@props.children} </div> _onDragStart: (event) => json = JSON.stringify(@props.item, Utils.registeredObjectReplacer) event.dataTransfer.setData('nylas-token-item', json) event.dataTransfer.setData('text/plain', @props.item.toString()) event.dataTransfer.dropEffect = "move" event.dataTransfer.effectAllowed = "move" @setState(dragging: true) _onDragEnd: (event) => @setState(dragging: false) _onSelect: (event) => @props.onSelected(@props.item) _onDoubleClick: (event) => if @props.onEdited @setState(editing: true) _onEditKeydown: (event) => if event.key in ['Escape', 'Enter'] @_onEditFinished() _onEditFinished: (event) => @props.onEdited?(@props.item, @state.editingValue) @setState(editing: false) _onAction: (event) => @props.onAction(@props.item) event.preventDefault() ### The TokenizingTextField component displays a list of options as you type and converts them into stylable tokens. It wraps the Menu component, which takes care of the typing and keyboard interactions. See documentation on the propTypes for usage info. Section: Component Kit ### class TokenizingTextField extends React.Component @displayName: "TokenizingTextField" @containerRequired: false # Exposed for tests @Token: Token @propTypes: className: React.PropTypes.string # An array of current tokens. # # A token is usually an object type like a `Contact`. The set of # tokens is stored as a prop instead of `state`. This means that when # the set of tokens needs to be changed, it is the parent's # responsibility to make that change. tokens: React.PropTypes.arrayOf(React.PropTypes.object) # The maximum number of tokens allowed. When null (the default) and # unlimited number of tokens may be given maxTokens: React.PropTypes.number # A function that, given an object used for tokens, returns a unique # id (key) for that object. # # This is necessary for React to assign each of the subitems and # unique key. tokenKey: React.PropTypes.func.isRequired # A function that, given a token, returns true if the token is valid # and false if the token is invalid. Useful if your implementation of # onAdd allows invalid tokens to be added to the field (ie malformed # email addresses.) Optional. # tokenIsValid: React.PropTypes.func # What each token looks like # # A function that is passed an object and should return React elements # to display that individual token. tokenRenderer: React.PropTypes.func.isRequired tokenClassNames: React.PropTypes.func # The function responsible for providing a list of possible options # given the current input. # # It takes the current input as a value and should return an array of # candidate objects. These objects must be the same type as are passed # to the `tokens` prop. # # The function may either directly return tokens, or may return a # Promise, that resolves with the requested tokens onRequestCompletions: React.PropTypes.func.isRequired # What each suggestion looks like. # # This is passed through to the Menu component's `itemContent` prop. # See components/menu.cjsx for more info. completionNode: React.PropTypes.func.isRequired # Gets called when we we're ready to add whatever it is we're # completing # # It's either passed an array of objects (the same ones used to # render tokens) # # OR # # It's passed the string currently in the input field. The string case # happens on paste and blur. # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onAdd: React.PropTypes.func.isRequired # Gets called when we remove a token # # It's passed an array of objects (the same ones used to render # tokens) # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onRemove: React.PropTypes.func.isRequired # Gets called when an existing token is double-clicked and edited. # Do not provide this method if you want to disable editing. # # It's passed a token index, and the new text typed in that location. # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onEdit: React.PropTypes.func # Called when we remove and there's nothing left to remove onEmptied: React.PropTypes.func # Called when the secondary action of the token gets invoked. onTokenAction: React.PropTypes.oneOfType([ React.PropTypes.func, React.PropTypes.bool, ]) # Called when the input is focused onFocus: React.PropTypes.func # A Prompt used in the head of the menu menuPrompt: React.PropTypes.string # A classSet hash applied to the Menu item menuClassSet: React.PropTypes.object @defaultProps: className: '' tokenClassNames: -> '' constructor: (@props) -> @state = inputValue: "" completions: [] selectedTokenKey: null componentDidMount: -> @_mounted = true componentWillUnmount: -> @_mounted = false render: => {Menu} = require 'nylas-component-kit' classSet = {} classSet[@props.className] = true classes = classNames _.extend {}, classSet, (@props.menuClassSet ? {}), "tokenizing-field": true "focused": @state.focus "empty": (@state.inputValue ? "").trim().length is 0 <Menu className={classes} ref="completions" items={@state.completions} itemKey={ (item) -> item.id } itemContent={@props.completionNode} headerComponents={[@_fieldComponent()]} onFocus={@_onInputFocused} onBlur={@_onInputBlurred} onSelect={@_addToken} /> _fieldComponent: => <div key="field-component" ref="field-drop-target" onClick={@_onClick} onDrop={@_onDrop}> {@_renderPrompt()} <div className="tokenizing-field-input"> {@_placeholder()} {@_fieldComponents()} {@_inputEl()} </div> </div> _inputEl: => props = onCopy: @_onCopy onCut: @_onCut onPaste: @_onPaste onKeyDown: @_onInputKeydown onBlur: @_onInputBlurred onFocus: @_onInputFocused onChange: @_onInputChanged disabled: @props.disabled tabIndex: 0 value: @state.inputValue # If we can't accept additional tokens, override the events that would # enable additional items to be inserted if @_atMaxTokens() props.className = "noop-input" props.onFocus = => @_onInputFocused(noCompletions: true) props.onPaste = => 'noop-input' props.onChange = => 'noop' props.value = '' <SizeToFitInput ref="input" spellCheck="false" {...props} /> _placeholder: => if not @state.focus and @props.placeholder? return <div className="placeholder">{@props.placeholder}</div> else return <span></span> _atMaxTokens: => if @props.maxTokens @props.tokens.length >= @props.maxTokens else return false _renderPrompt: => if @props.menuPrompt <div className="tokenizing-field-label">{"#{@props.menuPrompt}:"}</div> else <div></div> _fieldComponents: => @props.tokens.map (item) => key = @props.tokenKey(item) valid = true if @props.tokenIsValid valid = @props.tokenIsValid(item) TokenRenderer = @props.tokenRenderer onAction = if @props.onTokenAction is false null else @props.onTokenAction || @_showDefaultTokenMenu <Token className={@props.tokenClassNames(item)} item={item} key={key} valid={valid} selected={@state.selectedTokenKey is key} onSelected={@_selectToken} onEdited={@props.onEdit} onAction={onAction}> <TokenRenderer token={item} /> </Token> # Maintaining Input State _onClick: (event) => # Don't focus if the focus is already on an input within our field, # like an editable token's input if event.target.tagName is 'INPUT' and ReactDOM.findDOMNode(@).contains(event.target) return @focus() _onDrop: (event) => return unless 'nylas-token-item' in event.dataTransfer.types try data = event.dataTransfer.getData('nylas-token-item') item = JSON.parse(data, Utils.registeredObjectReviver) catch err console.error(err) item = null if item @_addToken(item) _onInputFocused: ({noCompletions}={}) => @setState(focus: true) @props.onFocus?() @_refreshCompletions() unless noCompletions _onInputKeydown: (event) => if event.key in ["Backspace", "Delete"] @_removeToken() else if event.key in ["Escape"] @_refreshCompletions("", clear: true) else if event.key in ["Tab", "Enter"] @_onInputTrySubmit(event) else if event.keyCode is 188 # comma event.preventDefault() # never allow commas in the field @_onInputTrySubmit(event) _onInputTrySubmit: (event) => return if (@state.inputValue ? "").trim().length is 0 event.preventDefault() event.stopPropagation() if @state.completions.length > 0 @_addToken(@refs.completions.getSelectedItem() || @state.completions[0]) else @_addInputValue() _onInputChanged: (event) => val = event.target.value.trimLeft() @setState selectedTokenKey: null inputValue: val # If it looks like an email, and the last character entered was a # space, then let's add the input value. # TODO WHY IS THIS EMAIL RELATED? if RegExpUtils.emailRegex().test(val) and _.last(val) is " " @_addInputValue(val[0...-1], skipNameLookup: true) else @_refreshCompletions(val) _onInputBlurred: (event) => # Not having a relatedTarget can happen when the whole app blurs. When # this happens we want to leave the field as-is return unless event.relatedTarget if event.relatedTarget is ReactDOM.findDOMNode(@) return @_addInputValue() @_refreshCompletions("", clear: true) @setState selectedTokenKey: null focus: false _clearInput: => @setState(inputValue: "") @_refreshCompletions("", clear: true) focus: => @refs.input.focus() # Managing Tokens _addInputValue: (input, options={}) => return if @_atMaxTokens() input ?= @state.inputValue @props.onAdd(input, options) @_clearInput() _selectToken: (token) => @setState selectedTokenKey: @props.tokenKey(token) _selectedToken: => _.find @props.tokens, (t) => @props.tokenKey(t) is @state.selectedTokenKey _addToken: (token) => return unless token @props.onAdd([token]) @_clearInput() @focus() _removeToken: (token = null) => if @state.inputValue.trim().length is 0 and @props.tokens.length is 0 and @props.onEmptied? @props.onEmptied() if token tokenToDelete = token else if @state.selectedTokenKey tokenToDelete = @_selectedToken() else if @props.tokens.length > 0 @_selectToken(@props.tokens[@props.tokens.length - 1]) if tokenToDelete @props.onRemove([tokenToDelete]) if @props.tokenKey(tokenToDelete) is @state.selectedTokenKey @setState selectedTokenKey: null _showDefaultTokenMenu: (token) => {remote} = require('electron') Menu = remote.require('menu') MenuItem = remote.require('menu-item') menu = new Menu() menu.append(new MenuItem( label: 'Remove', click: => @_removeToken(token) )) menu.popup(remote.getCurrentWindow()) # Copy and Paste _onCut: (event) => if @state.selectedTokenKey event.clipboardData?.setData('text/plain', @props.tokenKey(@_selectedToken())) event.preventDefault() @_removeToken(@_selectedToken()) _onCopy: (event) => if @state.selectedTokenKey event.clipboardData.setData('text/plain', @props.tokenKey(@_selectedToken())) event.preventDefault() _onPaste: (event) => data = event.clipboardData.getData('text/plain') @_addInputValue(data) event.preventDefault() # Managing Suggestions # Asks `@props.onRequestCompletions` for new completions given the # current inputValue. Since `onRequestCompletions` can be asynchronous, # this function will handle calling `setState` on `completions` when # `onRequestCompletions` returns. _refreshCompletions: (val = @state.inputValue, {clear}={}) => existingKeys = _.map(@props.tokens, @props.tokenKey) filterTokens = (tokens) => _.reject tokens, (t) => @props.tokenKey(t) in existingKeys tokensOrPromise = @props.onRequestCompletions(val, {clear}) if _.isArray(tokensOrPromise) @setState completions: filterTokens(tokensOrPromise) else if tokensOrPromise instanceof Promise tokensOrPromise.then (tokens) => return unless @_mounted @setState completions: filterTokens(tokens) else console.warn "onRequestCompletions returned an invalid type. It must return an Array of tokens or a Promise that resolves to an array of tokens" @setState completions: [] module.exports = TokenizingTextField
95842
React = require 'react' ReactDOM = require 'react-dom' classNames = require 'classnames' _ = require 'underscore' {CompositeDisposable} = require 'event-kit' {Utils, Contact, RegExpUtils} = require 'nylas-exports' RetinaImg = require './retina-img' class SizeToFitInput extends React.Component constructor: (@props) -> @state = {} componentDidMount: => @_sizeToFit() componentDidUpdate: => @_sizeToFit() _sizeToFit: => # Measure the width of the text in the input and # resize the input field to fit. input = ReactDOM.findDOMNode(@refs.input) measure = ReactDOM.findDOMNode(@refs.measure) measure.innerText = input.value measure.style.top = input.offsetTop + "px" measure.style.left = input.offsetLeft + "px" # The 10px comes from the 7.5px left padding and 2.5px more of # breathing room. input.style.width = "#{measure.offsetWidth+10}px" render: => <span> <span ref="measure" style={visibility:'hidden', position: 'absolute'}></span> <input ref="input" type="text" {...@props}/> </span> select: => ReactDOM.findDOMNode(@refs.input).select() focus: => ReactDOM.findDOMNode(@refs.input).focus() class Token extends React.Component @displayName: "Token" @propTypes: className: React.PropTypes.string, selected: React.PropTypes.bool, valid: React.PropTypes.bool, item: React.PropTypes.object, onSelected: React.PropTypes.func.isRequired, onEdited: React.PropTypes.func, onAction: React.PropTypes.func @defaultProps: className: '' constructor: (@props) -> @state = editing: false editingValue: @props.item.toString() render: => if @state.editing @_renderEditing() else @_renderViewing() componentDidUpdate: (prevProps, prevState) => if @state.editing && !prevState.editing @refs.input.select() componentWillReceiveProps: (props) => # never override the text the user is editing if they're looking at it return if @state.editing @setState(editingValue: @props.item.toString()) _renderEditing: => <SizeToFitInput ref="input" className="token-editing-input" spellCheck="false" value={@state.editingValue} onKeyDown={@_onEditKeydown} onBlur={@_onEditFinished} onChange={ (event) => @setState(editingValue: event.target.value)}/> _renderViewing: => classes = classNames "token": true "dragging": @state.dragging "invalid": !@props.valid "selected": @props.selected <div className={"#{classes} #{@props.className}"} onDragStart={@_onDragStart} onDragEnd={@_onDragEnd} draggable="true" onDoubleClick={@_onDoubleClick} onClick={@_onSelect}> {if @props.onAction <button className="action" onClick={@_onAction} tabIndex={-1}> <RetinaImg mode={RetinaImg.Mode.ContentIsMask} name="composer-caret.png" /> </button> } {@props.children} </div> _onDragStart: (event) => json = JSON.stringify(@props.item, Utils.registeredObjectReplacer) event.dataTransfer.setData('nylas-token-item', json) event.dataTransfer.setData('text/plain', @props.item.toString()) event.dataTransfer.dropEffect = "move" event.dataTransfer.effectAllowed = "move" @setState(dragging: true) _onDragEnd: (event) => @setState(dragging: false) _onSelect: (event) => @props.onSelected(@props.item) _onDoubleClick: (event) => if @props.onEdited @setState(editing: true) _onEditKeydown: (event) => if event.key in ['Escape', 'Enter'] @_onEditFinished() _onEditFinished: (event) => @props.onEdited?(@props.item, @state.editingValue) @setState(editing: false) _onAction: (event) => @props.onAction(@props.item) event.preventDefault() ### The TokenizingTextField component displays a list of options as you type and converts them into stylable tokens. It wraps the Menu component, which takes care of the typing and keyboard interactions. See documentation on the propTypes for usage info. Section: Component Kit ### class TokenizingTextField extends React.Component @displayName: "TokenizingTextField" @containerRequired: false # Exposed for tests @Token: Token @propTypes: className: React.PropTypes.string # An array of current tokens. # # A token is usually an object type like a `Contact`. The set of # tokens is stored as a prop instead of `state`. This means that when # the set of tokens needs to be changed, it is the parent's # responsibility to make that change. tokens: React.PropTypes.arrayOf(React.PropTypes.object) # The maximum number of tokens allowed. When null (the default) and # unlimited number of tokens may be given maxTokens: React.PropTypes.number # A function that, given an object used for tokens, returns a unique # id (key) for that object. # # This is necessary for React to assign each of the subitems and # unique key. tokenKey: React.PropTypes.func.isRequired # A function that, given a token, returns true if the token is valid # and false if the token is invalid. Useful if your implementation of # onAdd allows invalid tokens to be added to the field (ie malformed # email addresses.) Optional. # tokenIsValid: React.PropTypes.func # What each token looks like # # A function that is passed an object and should return React elements # to display that individual token. tokenRenderer: React.PropTypes.func.isRequired tokenClassNames: React.PropTypes.func # The function responsible for providing a list of possible options # given the current input. # # It takes the current input as a value and should return an array of # candidate objects. These objects must be the same type as are passed # to the `tokens` prop. # # The function may either directly return tokens, or may return a # Promise, that resolves with the requested tokens onRequestCompletions: React.PropTypes.func.isRequired # What each suggestion looks like. # # This is passed through to the Menu component's `itemContent` prop. # See components/menu.cjsx for more info. completionNode: React.PropTypes.func.isRequired # Gets called when we we're ready to add whatever it is we're # completing # # It's either passed an array of objects (the same ones used to # render tokens) # # OR # # It's passed the string currently in the input field. The string case # happens on paste and blur. # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onAdd: React.PropTypes.func.isRequired # Gets called when we remove a token # # It's passed an array of objects (the same ones used to render # tokens) # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onRemove: React.PropTypes.func.isRequired # Gets called when an existing token is double-clicked and edited. # Do not provide this method if you want to disable editing. # # It's passed a token index, and the new text typed in that location. # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onEdit: React.PropTypes.func # Called when we remove and there's nothing left to remove onEmptied: React.PropTypes.func # Called when the secondary action of the token gets invoked. onTokenAction: React.PropTypes.oneOfType([ React.PropTypes.func, React.PropTypes.bool, ]) # Called when the input is focused onFocus: React.PropTypes.func # A Prompt used in the head of the menu menuPrompt: React.PropTypes.string # A classSet hash applied to the Menu item menuClassSet: React.PropTypes.object @defaultProps: className: '' tokenClassNames: -> '' constructor: (@props) -> @state = inputValue: "" completions: [] selectedTokenKey: null componentDidMount: -> @_mounted = true componentWillUnmount: -> @_mounted = false render: => {Menu} = require 'nylas-component-kit' classSet = {} classSet[@props.className] = true classes = classNames _.extend {}, classSet, (@props.menuClassSet ? {}), "tokenizing-field": true "focused": @state.focus "empty": (@state.inputValue ? "").trim().length is 0 <Menu className={classes} ref="completions" items={@state.completions} itemKey={ (item) -> item.id } itemContent={@props.completionNode} headerComponents={[@_fieldComponent()]} onFocus={@_onInputFocused} onBlur={@_onInputBlurred} onSelect={@_addToken} /> _fieldComponent: => <div key="field-component" ref="field-drop-target" onClick={@_onClick} onDrop={@_onDrop}> {@_renderPrompt()} <div className="tokenizing-field-input"> {@_placeholder()} {@_fieldComponents()} {@_inputEl()} </div> </div> _inputEl: => props = onCopy: @_onCopy onCut: @_onCut onPaste: @_onPaste onKeyDown: @_onInputKeydown onBlur: @_onInputBlurred onFocus: @_onInputFocused onChange: @_onInputChanged disabled: @props.disabled tabIndex: 0 value: @state.inputValue # If we can't accept additional tokens, override the events that would # enable additional items to be inserted if @_atMaxTokens() props.className = "noop-input" props.onFocus = => @_onInputFocused(noCompletions: true) props.onPaste = => 'noop-input' props.onChange = => 'noop' props.value = '' <SizeToFitInput ref="input" spellCheck="false" {...props} /> _placeholder: => if not @state.focus and @props.placeholder? return <div className="placeholder">{@props.placeholder}</div> else return <span></span> _atMaxTokens: => if @props.maxTokens @props.tokens.length >= @props.maxTokens else return false _renderPrompt: => if @props.menuPrompt <div className="tokenizing-field-label">{"#{@props.menuPrompt}:"}</div> else <div></div> _fieldComponents: => @props.tokens.map (item) => key = <KEY>(item) valid = true if @props.tokenIsValid valid = @props.tokenIsValid(item) TokenRenderer = @props.tokenRenderer onAction = if @props.onTokenAction is false null else @props.onTokenAction || @_showDefaultTokenMenu <Token className={@props.tokenClassNames(item)} item={item} key={key} valid={valid} selected={@state.selectedTokenKey is key} onSelected={@_selectToken} onEdited={@props.onEdit} onAction={onAction}> <TokenRenderer token={item} /> </Token> # Maintaining Input State _onClick: (event) => # Don't focus if the focus is already on an input within our field, # like an editable token's input if event.target.tagName is 'INPUT' and ReactDOM.findDOMNode(@).contains(event.target) return @focus() _onDrop: (event) => return unless 'nylas-token-item' in event.dataTransfer.types try data = event.dataTransfer.getData('nylas-token-item') item = JSON.parse(data, Utils.registeredObjectReviver) catch err console.error(err) item = null if item @_addToken(item) _onInputFocused: ({noCompletions}={}) => @setState(focus: true) @props.onFocus?() @_refreshCompletions() unless noCompletions _onInputKeydown: (event) => if event.key in ["Backspace", "Delete"] @_removeToken() else if event.key in ["Escape"] @_refreshCompletions("", clear: true) else if event.key in ["Tab", "Enter"] @_onInputTrySubmit(event) else if event.keyCode is 188 # comma event.preventDefault() # never allow commas in the field @_onInputTrySubmit(event) _onInputTrySubmit: (event) => return if (@state.inputValue ? "").trim().length is 0 event.preventDefault() event.stopPropagation() if @state.completions.length > 0 @_addToken(@refs.completions.getSelectedItem() || @state.completions[0]) else @_addInputValue() _onInputChanged: (event) => val = event.target.value.trimLeft() @setState selectedTokenKey: null inputValue: val # If it looks like an email, and the last character entered was a # space, then let's add the input value. # TODO WHY IS THIS EMAIL RELATED? if RegExpUtils.emailRegex().test(val) and _.last(val) is " " @_addInputValue(val[0...-1], skipNameLookup: true) else @_refreshCompletions(val) _onInputBlurred: (event) => # Not having a relatedTarget can happen when the whole app blurs. When # this happens we want to leave the field as-is return unless event.relatedTarget if event.relatedTarget is ReactDOM.findDOMNode(@) return @_addInputValue() @_refreshCompletions("", clear: true) @setState selectedTokenKey: null focus: false _clearInput: => @setState(inputValue: "") @_refreshCompletions("", clear: true) focus: => @refs.input.focus() # Managing Tokens _addInputValue: (input, options={}) => return if @_atMaxTokens() input ?= @state.inputValue @props.onAdd(input, options) @_clearInput() _selectToken: (token) => @setState selectedTokenKey: @props.tokenKey(token) _selectedToken: => _.find @props.tokens, (t) => @props.tokenKey(t) is @state.selectedTokenKey _addToken: (token) => return unless token @props.onAdd([token]) @_clearInput() @focus() _removeToken: (token = null) => if @state.inputValue.trim().length is 0 and @props.tokens.length is 0 and @props.onEmptied? @props.onEmptied() if token tokenToDelete = token else if @state.selectedTokenKey tokenToDelete = @_selectedToken() else if @props.tokens.length > 0 @_selectToken(@props.tokens[@props.tokens.length - 1]) if tokenToDelete @props.onRemove([tokenToDelete]) if @props.tokenKey(tokenToDelete) is @state.selectedTokenKey @setState selectedTokenKey: null _showDefaultTokenMenu: (token) => {remote} = require('electron') Menu = remote.require('menu') MenuItem = remote.require('menu-item') menu = new Menu() menu.append(new MenuItem( label: 'Remove', click: => @_removeToken(token) )) menu.popup(remote.getCurrentWindow()) # Copy and Paste _onCut: (event) => if @state.selectedTokenKey event.clipboardData?.setData('text/plain', @props.tokenKey(@_selectedToken())) event.preventDefault() @_removeToken(@_selectedToken()) _onCopy: (event) => if @state.selectedTokenKey event.clipboardData.setData('text/plain', @props.tokenKey(@_selectedToken())) event.preventDefault() _onPaste: (event) => data = event.clipboardData.getData('text/plain') @_addInputValue(data) event.preventDefault() # Managing Suggestions # Asks `@props.onRequestCompletions` for new completions given the # current inputValue. Since `onRequestCompletions` can be asynchronous, # this function will handle calling `setState` on `completions` when # `onRequestCompletions` returns. _refreshCompletions: (val = @state.inputValue, {clear}={}) => existingKeys = _.map(@props.tokens, @props.tokenKey) filterTokens = (tokens) => _.reject tokens, (t) => @props.tokenKey(t) in existingKeys tokensOrPromise = @props.onRequestCompletions(val, {clear}) if _.isArray(tokensOrPromise) @setState completions: filterTokens(tokensOrPromise) else if tokensOrPromise instanceof Promise tokensOrPromise.then (tokens) => return unless @_mounted @setState completions: filterTokens(tokens) else console.warn "onRequestCompletions returned an invalid type. It must return an Array of tokens or a Promise that resolves to an array of tokens" @setState completions: [] module.exports = TokenizingTextField
true
React = require 'react' ReactDOM = require 'react-dom' classNames = require 'classnames' _ = require 'underscore' {CompositeDisposable} = require 'event-kit' {Utils, Contact, RegExpUtils} = require 'nylas-exports' RetinaImg = require './retina-img' class SizeToFitInput extends React.Component constructor: (@props) -> @state = {} componentDidMount: => @_sizeToFit() componentDidUpdate: => @_sizeToFit() _sizeToFit: => # Measure the width of the text in the input and # resize the input field to fit. input = ReactDOM.findDOMNode(@refs.input) measure = ReactDOM.findDOMNode(@refs.measure) measure.innerText = input.value measure.style.top = input.offsetTop + "px" measure.style.left = input.offsetLeft + "px" # The 10px comes from the 7.5px left padding and 2.5px more of # breathing room. input.style.width = "#{measure.offsetWidth+10}px" render: => <span> <span ref="measure" style={visibility:'hidden', position: 'absolute'}></span> <input ref="input" type="text" {...@props}/> </span> select: => ReactDOM.findDOMNode(@refs.input).select() focus: => ReactDOM.findDOMNode(@refs.input).focus() class Token extends React.Component @displayName: "Token" @propTypes: className: React.PropTypes.string, selected: React.PropTypes.bool, valid: React.PropTypes.bool, item: React.PropTypes.object, onSelected: React.PropTypes.func.isRequired, onEdited: React.PropTypes.func, onAction: React.PropTypes.func @defaultProps: className: '' constructor: (@props) -> @state = editing: false editingValue: @props.item.toString() render: => if @state.editing @_renderEditing() else @_renderViewing() componentDidUpdate: (prevProps, prevState) => if @state.editing && !prevState.editing @refs.input.select() componentWillReceiveProps: (props) => # never override the text the user is editing if they're looking at it return if @state.editing @setState(editingValue: @props.item.toString()) _renderEditing: => <SizeToFitInput ref="input" className="token-editing-input" spellCheck="false" value={@state.editingValue} onKeyDown={@_onEditKeydown} onBlur={@_onEditFinished} onChange={ (event) => @setState(editingValue: event.target.value)}/> _renderViewing: => classes = classNames "token": true "dragging": @state.dragging "invalid": !@props.valid "selected": @props.selected <div className={"#{classes} #{@props.className}"} onDragStart={@_onDragStart} onDragEnd={@_onDragEnd} draggable="true" onDoubleClick={@_onDoubleClick} onClick={@_onSelect}> {if @props.onAction <button className="action" onClick={@_onAction} tabIndex={-1}> <RetinaImg mode={RetinaImg.Mode.ContentIsMask} name="composer-caret.png" /> </button> } {@props.children} </div> _onDragStart: (event) => json = JSON.stringify(@props.item, Utils.registeredObjectReplacer) event.dataTransfer.setData('nylas-token-item', json) event.dataTransfer.setData('text/plain', @props.item.toString()) event.dataTransfer.dropEffect = "move" event.dataTransfer.effectAllowed = "move" @setState(dragging: true) _onDragEnd: (event) => @setState(dragging: false) _onSelect: (event) => @props.onSelected(@props.item) _onDoubleClick: (event) => if @props.onEdited @setState(editing: true) _onEditKeydown: (event) => if event.key in ['Escape', 'Enter'] @_onEditFinished() _onEditFinished: (event) => @props.onEdited?(@props.item, @state.editingValue) @setState(editing: false) _onAction: (event) => @props.onAction(@props.item) event.preventDefault() ### The TokenizingTextField component displays a list of options as you type and converts them into stylable tokens. It wraps the Menu component, which takes care of the typing and keyboard interactions. See documentation on the propTypes for usage info. Section: Component Kit ### class TokenizingTextField extends React.Component @displayName: "TokenizingTextField" @containerRequired: false # Exposed for tests @Token: Token @propTypes: className: React.PropTypes.string # An array of current tokens. # # A token is usually an object type like a `Contact`. The set of # tokens is stored as a prop instead of `state`. This means that when # the set of tokens needs to be changed, it is the parent's # responsibility to make that change. tokens: React.PropTypes.arrayOf(React.PropTypes.object) # The maximum number of tokens allowed. When null (the default) and # unlimited number of tokens may be given maxTokens: React.PropTypes.number # A function that, given an object used for tokens, returns a unique # id (key) for that object. # # This is necessary for React to assign each of the subitems and # unique key. tokenKey: React.PropTypes.func.isRequired # A function that, given a token, returns true if the token is valid # and false if the token is invalid. Useful if your implementation of # onAdd allows invalid tokens to be added to the field (ie malformed # email addresses.) Optional. # tokenIsValid: React.PropTypes.func # What each token looks like # # A function that is passed an object and should return React elements # to display that individual token. tokenRenderer: React.PropTypes.func.isRequired tokenClassNames: React.PropTypes.func # The function responsible for providing a list of possible options # given the current input. # # It takes the current input as a value and should return an array of # candidate objects. These objects must be the same type as are passed # to the `tokens` prop. # # The function may either directly return tokens, or may return a # Promise, that resolves with the requested tokens onRequestCompletions: React.PropTypes.func.isRequired # What each suggestion looks like. # # This is passed through to the Menu component's `itemContent` prop. # See components/menu.cjsx for more info. completionNode: React.PropTypes.func.isRequired # Gets called when we we're ready to add whatever it is we're # completing # # It's either passed an array of objects (the same ones used to # render tokens) # # OR # # It's passed the string currently in the input field. The string case # happens on paste and blur. # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onAdd: React.PropTypes.func.isRequired # Gets called when we remove a token # # It's passed an array of objects (the same ones used to render # tokens) # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onRemove: React.PropTypes.func.isRequired # Gets called when an existing token is double-clicked and edited. # Do not provide this method if you want to disable editing. # # It's passed a token index, and the new text typed in that location. # # The function doesn't need to return anything, but it is generally # responible for mutating the parent's state in a way that eventually # updates this component's `tokens` prop. onEdit: React.PropTypes.func # Called when we remove and there's nothing left to remove onEmptied: React.PropTypes.func # Called when the secondary action of the token gets invoked. onTokenAction: React.PropTypes.oneOfType([ React.PropTypes.func, React.PropTypes.bool, ]) # Called when the input is focused onFocus: React.PropTypes.func # A Prompt used in the head of the menu menuPrompt: React.PropTypes.string # A classSet hash applied to the Menu item menuClassSet: React.PropTypes.object @defaultProps: className: '' tokenClassNames: -> '' constructor: (@props) -> @state = inputValue: "" completions: [] selectedTokenKey: null componentDidMount: -> @_mounted = true componentWillUnmount: -> @_mounted = false render: => {Menu} = require 'nylas-component-kit' classSet = {} classSet[@props.className] = true classes = classNames _.extend {}, classSet, (@props.menuClassSet ? {}), "tokenizing-field": true "focused": @state.focus "empty": (@state.inputValue ? "").trim().length is 0 <Menu className={classes} ref="completions" items={@state.completions} itemKey={ (item) -> item.id } itemContent={@props.completionNode} headerComponents={[@_fieldComponent()]} onFocus={@_onInputFocused} onBlur={@_onInputBlurred} onSelect={@_addToken} /> _fieldComponent: => <div key="field-component" ref="field-drop-target" onClick={@_onClick} onDrop={@_onDrop}> {@_renderPrompt()} <div className="tokenizing-field-input"> {@_placeholder()} {@_fieldComponents()} {@_inputEl()} </div> </div> _inputEl: => props = onCopy: @_onCopy onCut: @_onCut onPaste: @_onPaste onKeyDown: @_onInputKeydown onBlur: @_onInputBlurred onFocus: @_onInputFocused onChange: @_onInputChanged disabled: @props.disabled tabIndex: 0 value: @state.inputValue # If we can't accept additional tokens, override the events that would # enable additional items to be inserted if @_atMaxTokens() props.className = "noop-input" props.onFocus = => @_onInputFocused(noCompletions: true) props.onPaste = => 'noop-input' props.onChange = => 'noop' props.value = '' <SizeToFitInput ref="input" spellCheck="false" {...props} /> _placeholder: => if not @state.focus and @props.placeholder? return <div className="placeholder">{@props.placeholder}</div> else return <span></span> _atMaxTokens: => if @props.maxTokens @props.tokens.length >= @props.maxTokens else return false _renderPrompt: => if @props.menuPrompt <div className="tokenizing-field-label">{"#{@props.menuPrompt}:"}</div> else <div></div> _fieldComponents: => @props.tokens.map (item) => key = PI:KEY:<KEY>END_PI(item) valid = true if @props.tokenIsValid valid = @props.tokenIsValid(item) TokenRenderer = @props.tokenRenderer onAction = if @props.onTokenAction is false null else @props.onTokenAction || @_showDefaultTokenMenu <Token className={@props.tokenClassNames(item)} item={item} key={key} valid={valid} selected={@state.selectedTokenKey is key} onSelected={@_selectToken} onEdited={@props.onEdit} onAction={onAction}> <TokenRenderer token={item} /> </Token> # Maintaining Input State _onClick: (event) => # Don't focus if the focus is already on an input within our field, # like an editable token's input if event.target.tagName is 'INPUT' and ReactDOM.findDOMNode(@).contains(event.target) return @focus() _onDrop: (event) => return unless 'nylas-token-item' in event.dataTransfer.types try data = event.dataTransfer.getData('nylas-token-item') item = JSON.parse(data, Utils.registeredObjectReviver) catch err console.error(err) item = null if item @_addToken(item) _onInputFocused: ({noCompletions}={}) => @setState(focus: true) @props.onFocus?() @_refreshCompletions() unless noCompletions _onInputKeydown: (event) => if event.key in ["Backspace", "Delete"] @_removeToken() else if event.key in ["Escape"] @_refreshCompletions("", clear: true) else if event.key in ["Tab", "Enter"] @_onInputTrySubmit(event) else if event.keyCode is 188 # comma event.preventDefault() # never allow commas in the field @_onInputTrySubmit(event) _onInputTrySubmit: (event) => return if (@state.inputValue ? "").trim().length is 0 event.preventDefault() event.stopPropagation() if @state.completions.length > 0 @_addToken(@refs.completions.getSelectedItem() || @state.completions[0]) else @_addInputValue() _onInputChanged: (event) => val = event.target.value.trimLeft() @setState selectedTokenKey: null inputValue: val # If it looks like an email, and the last character entered was a # space, then let's add the input value. # TODO WHY IS THIS EMAIL RELATED? if RegExpUtils.emailRegex().test(val) and _.last(val) is " " @_addInputValue(val[0...-1], skipNameLookup: true) else @_refreshCompletions(val) _onInputBlurred: (event) => # Not having a relatedTarget can happen when the whole app blurs. When # this happens we want to leave the field as-is return unless event.relatedTarget if event.relatedTarget is ReactDOM.findDOMNode(@) return @_addInputValue() @_refreshCompletions("", clear: true) @setState selectedTokenKey: null focus: false _clearInput: => @setState(inputValue: "") @_refreshCompletions("", clear: true) focus: => @refs.input.focus() # Managing Tokens _addInputValue: (input, options={}) => return if @_atMaxTokens() input ?= @state.inputValue @props.onAdd(input, options) @_clearInput() _selectToken: (token) => @setState selectedTokenKey: @props.tokenKey(token) _selectedToken: => _.find @props.tokens, (t) => @props.tokenKey(t) is @state.selectedTokenKey _addToken: (token) => return unless token @props.onAdd([token]) @_clearInput() @focus() _removeToken: (token = null) => if @state.inputValue.trim().length is 0 and @props.tokens.length is 0 and @props.onEmptied? @props.onEmptied() if token tokenToDelete = token else if @state.selectedTokenKey tokenToDelete = @_selectedToken() else if @props.tokens.length > 0 @_selectToken(@props.tokens[@props.tokens.length - 1]) if tokenToDelete @props.onRemove([tokenToDelete]) if @props.tokenKey(tokenToDelete) is @state.selectedTokenKey @setState selectedTokenKey: null _showDefaultTokenMenu: (token) => {remote} = require('electron') Menu = remote.require('menu') MenuItem = remote.require('menu-item') menu = new Menu() menu.append(new MenuItem( label: 'Remove', click: => @_removeToken(token) )) menu.popup(remote.getCurrentWindow()) # Copy and Paste _onCut: (event) => if @state.selectedTokenKey event.clipboardData?.setData('text/plain', @props.tokenKey(@_selectedToken())) event.preventDefault() @_removeToken(@_selectedToken()) _onCopy: (event) => if @state.selectedTokenKey event.clipboardData.setData('text/plain', @props.tokenKey(@_selectedToken())) event.preventDefault() _onPaste: (event) => data = event.clipboardData.getData('text/plain') @_addInputValue(data) event.preventDefault() # Managing Suggestions # Asks `@props.onRequestCompletions` for new completions given the # current inputValue. Since `onRequestCompletions` can be asynchronous, # this function will handle calling `setState` on `completions` when # `onRequestCompletions` returns. _refreshCompletions: (val = @state.inputValue, {clear}={}) => existingKeys = _.map(@props.tokens, @props.tokenKey) filterTokens = (tokens) => _.reject tokens, (t) => @props.tokenKey(t) in existingKeys tokensOrPromise = @props.onRequestCompletions(val, {clear}) if _.isArray(tokensOrPromise) @setState completions: filterTokens(tokensOrPromise) else if tokensOrPromise instanceof Promise tokensOrPromise.then (tokens) => return unless @_mounted @setState completions: filterTokens(tokens) else console.warn "onRequestCompletions returned an invalid type. It must return an Array of tokens or a Promise that resolves to an array of tokens" @setState completions: [] module.exports = TokenizingTextField
[ { "context": "--------------------\n\n // created by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} )\n // creation ", "end": 232, "score": 0.9998783469200134, "start": 215, "tag": "NAME", "value": "Alessandro Muraro" }, { "context": " // created by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} )\n // creation data: ${4: 00 Month 2016}", "end": 258, "score": 0.9998189210891724, "start": 240, "tag": "EMAIL", "value": "akmuraro@gmail.com" }, { "context": " ${4: 00 Month 2016}\n\n // upadate by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} )\n // update da", "end": 355, "score": 0.9998738169670105, "start": 338, "tag": "NAME", "value": "Alessandro Muraro" }, { "context": " // upadate by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} )\n // update data: ${4: 00 Month 2016}\n\n", "end": 381, "score": 0.9998001456260681, "start": 363, "tag": "EMAIL", "value": "akmuraro@gmail.com" }, { "context": "-------------------\n\n //- created by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} )\n //- creation", "end": 1051, "score": 0.9998833537101746, "start": 1034, "tag": "NAME", "value": "Alessandro Muraro" }, { "context": " //- created by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} )\n //- creation data: ${4: 00 Month 2016", "end": 1077, "score": 0.9997035264968872, "start": 1059, "tag": "EMAIL", "value": "akmuraro@gmail.com" }, { "context": "${4: 00 Month 2016}\n\n //- upadate by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} )\n //- update d", "end": 1176, "score": 0.999869167804718, "start": 1159, "tag": "NAME", "value": "Alessandro Muraro" }, { "context": " //- upadate by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} )\n //- update data: ${4: 00 Month 2016}\n", "end": 1202, "score": 0.9998947978019714, "start": 1184, "tag": "EMAIL", "value": "akmuraro@gmail.com" } ]
snippets/comment.cson
akmur/atom-sass-style-comments
0
'.source.scss, .source.sass, .source.js': 'Comment Section Title': 'prefix': 'c-t' 'body': ''' // --------------------------- ${1:Title} ------------------------------ // created by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} ) // creation data: ${4: 00 Month 2016} // upadate by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} ) // update data: ${4: 00 Month 2016} // ${5:1. Your text} // ${6:2. Your text} // --------------------------------------------------------------------- ''' 'Comment Block': 'prefix': 'c-b' 'body': ''' // --------------------------------------------------------------------- // ${1:Note} // --------------------------------------------------------------------- ''' '.source.jade, .source.pug': 'Comment Section Title': 'prefix': 'c-t' 'body': ''' //---------------------------- ${1:Title} ------------------------------ //- created by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} ) //- creation data: ${4: 00 Month 2016} //- upadate by: ${2:Alessandro Muraro} ( ${3:akmuraro@gmail.com} ) //- update data: ${4: 00 Month 2016} //- ${5:1. Your text} //- ${6:2. Your text} //---------------------------------------------------------------------- ''' 'Comment Block': 'prefix': 'c-b' 'body': ''' //---------------------------------------------------------------------- //- ${1:Note} //---------------------------------------------------------------------- '''
119473
'.source.scss, .source.sass, .source.js': 'Comment Section Title': 'prefix': 'c-t' 'body': ''' // --------------------------- ${1:Title} ------------------------------ // created by: ${2:<NAME>} ( ${3:<EMAIL>} ) // creation data: ${4: 00 Month 2016} // upadate by: ${2:<NAME>} ( ${3:<EMAIL>} ) // update data: ${4: 00 Month 2016} // ${5:1. Your text} // ${6:2. Your text} // --------------------------------------------------------------------- ''' 'Comment Block': 'prefix': 'c-b' 'body': ''' // --------------------------------------------------------------------- // ${1:Note} // --------------------------------------------------------------------- ''' '.source.jade, .source.pug': 'Comment Section Title': 'prefix': 'c-t' 'body': ''' //---------------------------- ${1:Title} ------------------------------ //- created by: ${2:<NAME>} ( ${3:<EMAIL>} ) //- creation data: ${4: 00 Month 2016} //- upadate by: ${2:<NAME>} ( ${3:<EMAIL>} ) //- update data: ${4: 00 Month 2016} //- ${5:1. Your text} //- ${6:2. Your text} //---------------------------------------------------------------------- ''' 'Comment Block': 'prefix': 'c-b' 'body': ''' //---------------------------------------------------------------------- //- ${1:Note} //---------------------------------------------------------------------- '''
true
'.source.scss, .source.sass, .source.js': 'Comment Section Title': 'prefix': 'c-t' 'body': ''' // --------------------------- ${1:Title} ------------------------------ // created by: ${2:PI:NAME:<NAME>END_PI} ( ${3:PI:EMAIL:<EMAIL>END_PI} ) // creation data: ${4: 00 Month 2016} // upadate by: ${2:PI:NAME:<NAME>END_PI} ( ${3:PI:EMAIL:<EMAIL>END_PI} ) // update data: ${4: 00 Month 2016} // ${5:1. Your text} // ${6:2. Your text} // --------------------------------------------------------------------- ''' 'Comment Block': 'prefix': 'c-b' 'body': ''' // --------------------------------------------------------------------- // ${1:Note} // --------------------------------------------------------------------- ''' '.source.jade, .source.pug': 'Comment Section Title': 'prefix': 'c-t' 'body': ''' //---------------------------- ${1:Title} ------------------------------ //- created by: ${2:PI:NAME:<NAME>END_PI} ( ${3:PI:EMAIL:<EMAIL>END_PI} ) //- creation data: ${4: 00 Month 2016} //- upadate by: ${2:PI:NAME:<NAME>END_PI} ( ${3:PI:EMAIL:<EMAIL>END_PI} ) //- update data: ${4: 00 Month 2016} //- ${5:1. Your text} //- ${6:2. Your text} //---------------------------------------------------------------------- ''' 'Comment Block': 'prefix': 'c-b' 'body': ''' //---------------------------------------------------------------------- //- ${1:Note} //---------------------------------------------------------------------- '''
[ { "context": "#\t> File Name: discuss.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: S", "end": 44, "score": 0.9992979764938354, "start": 42, "tag": "USERNAME", "value": "LY" }, { "context": "File Name: discuss.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: Saturday, December 06, 2014 PM0", "end": 74, "score": 0.9999294281005859, "start": 55, "tag": "EMAIL", "value": "ly.franky@gmail.com" } ]
server/views/src/coffee/discuss.coffee
Booker-Z/MIAC-website
0
# > File Name: discuss.coffee # > Author: LY # > Mail: ly.franky@gmail.com # > Created Time: Saturday, December 06, 2014 PM03:36:38 CST $('.up').click -> discussionId = $(@).attr('discussion-id') $.post '/Discuss/up', { discussionId: discussionId }, (data)-> alert data.result + '\n' + (data.msg if data.msg) if data.result is 'success' window.location.reload() $('.down').click -> discussionId = $(@).attr('discussion-id') $.post '/Discuss/down', { discussionId: discussionId }, (data)-> alert data.result + '\n' + (data.msg if data.msg) if data.result is 'success' window.location.reload()
191515
# > File Name: discuss.coffee # > Author: LY # > Mail: <EMAIL> # > Created Time: Saturday, December 06, 2014 PM03:36:38 CST $('.up').click -> discussionId = $(@).attr('discussion-id') $.post '/Discuss/up', { discussionId: discussionId }, (data)-> alert data.result + '\n' + (data.msg if data.msg) if data.result is 'success' window.location.reload() $('.down').click -> discussionId = $(@).attr('discussion-id') $.post '/Discuss/down', { discussionId: discussionId }, (data)-> alert data.result + '\n' + (data.msg if data.msg) if data.result is 'success' window.location.reload()
true
# > File Name: discuss.coffee # > Author: LY # > Mail: PI:EMAIL:<EMAIL>END_PI # > Created Time: Saturday, December 06, 2014 PM03:36:38 CST $('.up').click -> discussionId = $(@).attr('discussion-id') $.post '/Discuss/up', { discussionId: discussionId }, (data)-> alert data.result + '\n' + (data.msg if data.msg) if data.result is 'success' window.location.reload() $('.down').click -> discussionId = $(@).attr('discussion-id') $.post '/Discuss/down', { discussionId: discussionId }, (data)-> alert data.result + '\n' + (data.msg if data.msg) if data.result is 'success' window.location.reload()
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 197, "score": 0.9998777508735657, "start": 180, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.com\n\nThis softwa", "end": 213, "score": 0.9999294281005859, "start": 200, "tag": "EMAIL", "value": "ben@pxljs.com" } ]
examples/simple.coffee
OniDaito/pxljs
1
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> white = new PXL.Colour.RGBA.WHITE() v0 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(-1,-1,0) c : white v1 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(0,1,0) c : white v2 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(1,-1,0) c : white t = new PXL.Geometry.Triangle(v0,v1,v2) vertexMaterial = new PXL.Material.VertexColourMaterial() @node = new PXL.Node t camera = new PXL.Camera.PerspCamera() @node.add camera @node.add vertexMaterial @node.add new PXL.GL.UberShader(@node) draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @node.draw() params = canvas : 'webgl-canvas' context : @ init : init draw : draw cgl = new PXL.App params
194100
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> white = new PXL.Colour.RGBA.WHITE() v0 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(-1,-1,0) c : white v1 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(0,1,0) c : white v2 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(1,-1,0) c : white t = new PXL.Geometry.Triangle(v0,v1,v2) vertexMaterial = new PXL.Material.VertexColourMaterial() @node = new PXL.Node t camera = new PXL.Camera.PerspCamera() @node.add camera @node.add vertexMaterial @node.add new PXL.GL.UberShader(@node) draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @node.draw() params = canvas : 'webgl-canvas' context : @ init : init draw : draw cgl = new PXL.App params
true
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details ### init = () -> white = new PXL.Colour.RGBA.WHITE() v0 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(-1,-1,0) c : white v1 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(0,1,0) c : white v2 = new PXL.Geometry.Vertex p : new PXL.Math.Vec3(1,-1,0) c : white t = new PXL.Geometry.Triangle(v0,v1,v2) vertexMaterial = new PXL.Material.VertexColourMaterial() @node = new PXL.Node t camera = new PXL.Camera.PerspCamera() @node.add camera @node.add vertexMaterial @node.add new PXL.GL.UberShader(@node) draw = () -> GL.clearColor(0.15, 0.15, 0.15, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @node.draw() params = canvas : 'webgl-canvas' context : @ init : init draw : draw cgl = new PXL.App params
[ { "context": "lintIdentifier: (token, tokenApi) ->\n key = token[1]\n\n # Class names might not be in a scope\n ", "end": 927, "score": 0.9957132339477539, "start": 919, "tag": "KEY", "value": "token[1]" }, { "context": "d \"something\" are not the same thing\n key = \"@#{key}\" if previousToken[0] is '@'\n\n # Added ", "end": 1371, "score": 0.768857479095459, "start": 1367, "tag": "KEY", "value": "\"@#{" }, { "context": "re with things like \"constructor\".\n key = \"identifier-#{key}\"\n if @currentScope[key]\n return ", "end": 1512, "score": 0.8323149681091309, "start": 1494, "tag": "KEY", "value": "identifier-#{key}\"" } ]
src/rules/duplicate_key.coffee
AsaAyers/coffeelint
0
module.exports = class DuplicateKey rule: # I don't know of any legitimate reason to define duplicate keys in an # object. It seems to always be a mistake, it's also a syntax error in # strict mode. # See http://jslinterrors.com/duplicate-key-a/ name: 'duplicate_key' level: 'error' message: 'Duplicate key defined in object or class' description: ''' Prevents defining duplicate keys in object literals and classes ''' tokens: [ 'IDENTIFIER', '{', '}' ] constructor: -> @braceScopes = [] # A stack tracking keys defined in nexted scopes. lintToken: ([type], tokenApi) -> if type in [ '{', '}' ] @lintBrace arguments... return undefined if type is 'IDENTIFIER' @lintIdentifier arguments... lintIdentifier: (token, tokenApi) -> key = token[1] # Class names might not be in a scope return null if not @currentScope? nextToken = tokenApi.peek(1) # Exit if this identifier isn't being assigned. A and B # are identifiers, but only A should be examined: # A = B return null if nextToken[1] isnt ':' previousToken = tokenApi.peek(-1) # Assigning "@something" and "something" are not the same thing key = "@#{key}" if previousToken[0] is '@' # Added a prefix to not interfere with things like "constructor". key = "identifier-#{key}" if @currentScope[key] return true else @currentScope[key] = token null lintBrace: (token) -> if token[0] is '{' @braceScopes.push @currentScope if @currentScope? @currentScope = {} else @currentScope = @braceScopes.pop() return null
32899
module.exports = class DuplicateKey rule: # I don't know of any legitimate reason to define duplicate keys in an # object. It seems to always be a mistake, it's also a syntax error in # strict mode. # See http://jslinterrors.com/duplicate-key-a/ name: 'duplicate_key' level: 'error' message: 'Duplicate key defined in object or class' description: ''' Prevents defining duplicate keys in object literals and classes ''' tokens: [ 'IDENTIFIER', '{', '}' ] constructor: -> @braceScopes = [] # A stack tracking keys defined in nexted scopes. lintToken: ([type], tokenApi) -> if type in [ '{', '}' ] @lintBrace arguments... return undefined if type is 'IDENTIFIER' @lintIdentifier arguments... lintIdentifier: (token, tokenApi) -> key = <KEY> # Class names might not be in a scope return null if not @currentScope? nextToken = tokenApi.peek(1) # Exit if this identifier isn't being assigned. A and B # are identifiers, but only A should be examined: # A = B return null if nextToken[1] isnt ':' previousToken = tokenApi.peek(-1) # Assigning "@something" and "something" are not the same thing key = <KEY>key}" if previousToken[0] is '@' # Added a prefix to not interfere with things like "constructor". key = "<KEY> if @currentScope[key] return true else @currentScope[key] = token null lintBrace: (token) -> if token[0] is '{' @braceScopes.push @currentScope if @currentScope? @currentScope = {} else @currentScope = @braceScopes.pop() return null
true
module.exports = class DuplicateKey rule: # I don't know of any legitimate reason to define duplicate keys in an # object. It seems to always be a mistake, it's also a syntax error in # strict mode. # See http://jslinterrors.com/duplicate-key-a/ name: 'duplicate_key' level: 'error' message: 'Duplicate key defined in object or class' description: ''' Prevents defining duplicate keys in object literals and classes ''' tokens: [ 'IDENTIFIER', '{', '}' ] constructor: -> @braceScopes = [] # A stack tracking keys defined in nexted scopes. lintToken: ([type], tokenApi) -> if type in [ '{', '}' ] @lintBrace arguments... return undefined if type is 'IDENTIFIER' @lintIdentifier arguments... lintIdentifier: (token, tokenApi) -> key = PI:KEY:<KEY>END_PI # Class names might not be in a scope return null if not @currentScope? nextToken = tokenApi.peek(1) # Exit if this identifier isn't being assigned. A and B # are identifiers, but only A should be examined: # A = B return null if nextToken[1] isnt ':' previousToken = tokenApi.peek(-1) # Assigning "@something" and "something" are not the same thing key = PI:KEY:<KEY>END_PIkey}" if previousToken[0] is '@' # Added a prefix to not interfere with things like "constructor". key = "PI:KEY:<KEY>END_PI if @currentScope[key] return true else @currentScope[key] = token null lintBrace: (token) -> if token[0] is '{' @braceScopes.push @currentScope if @currentScope? @currentScope = {} else @currentScope = @braceScopes.pop() return null
[ { "context": "s to get different\n# result.\n\nkeyAndIdsPackets = 'c652045b6f142613082a8648ce3d030107020304a54bdb6b6f7c145f584c3cf33ba9894b16708b3707310df27625546d2b10310a4ac4b23c516c8ceb4f38aa96a21e02c8717480c831095a2a287317d8e03e3c22cd264d69636861c582205067702054657374203c6e6f742d7a617075406b6579626173652e696f3ec2640413130a001605025b6f14260910433b1545547b718c021b03021901000034cf00ff68b1c1c4abded838df365ce8bec751ff2de8b58cf474b39cef708ac9790db30d0100a8702072316854172daff68dc0167c9e66b2159bca936087a30a8f7054ef20a8'\nsubkeyPacket = 'ce6d045b6f1426010300b97dfbd29467", "end": 771, "score": 0.9997849464416504, "start": 319, "tag": "KEY", "value": "c652045b6f142613082a8648ce3d030107020304a54bdb6b6f7c145f584c3cf33ba9894b16708b3707310df27625546d2b10310a4ac4b23c516c8ceb4f38aa96a21e02c8717480c831095a2a287317d8e03e3c22cd264d69636861c582205067702054657374203c6e6f742d7a617075406b6579626173652e696f3ec2640413130a001605025b6f14260910433b1545547b718c021b03021901000034cf00ff68b1c1c4abded838df365ce8bec751ff2de8b58cf474b39cef708ac9790db30d0100a8702072316854172daff68dc0167c9e66b2159bca936087a30a8f7054ef20a8" }, { "context": "66b2159bca936087a30a8f7054ef20a8'\nsubkeyPacket = 'ce6d045b6f1426010300b97dfbd29467121a7f621d2eff9c78ad8f90017f2074c94f1999ae9956b7e2169af0bcf9d3021421b88e9166d11a2e3153d8ccd9c85d59525af654e4e4c63166273dc365a04ac40d8abce2397aa3058433ce76afba7c7362d130cd395e4e1f0d0011010001'\n\n# Signature with Flags=Sign, valid cross-signat", "end": 1011, "score": 0.9995059370994568, "start": 789, "tag": "KEY", "value": "ce6d045b6f1426010300b97dfbd29467121a7f621d2eff9c78ad8f90017f2074c94f1999ae9956b7e2169af0bcf9d3021421b88e9166d11a2e3153d8ccd9c85d59525af654e4e4c63166273dc365a04ac40d8abce2397aa3058433ce76afba7c7362d130cd395e4e1f0d0011010001" }, { "context": "and expiring 4 years from\n# now.\nsignSigPacket = 'c2c01b0418130a001905025b6f14260910433b1545547b718c021b0205090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8cda9306037c58715454f92d4c39004cf7adffdfc25ea79b85d65840a13bb8eb1d8db455a2f72207195aeed8f6a37e6dfcd35ef5985de539f3bf17358841ad7581fc2cb5844dbb0b2d206e6ae6e99447fcb7f9306517a6100fe396ab483e28ccc6f55e9129c9c209e92eca03560c4baf3156e454347a8c4d27f00fe216749fa6aadb5018c00699b71040f3404572c257772b71751de234f361edaf7'\n\n# Signature with Flags=Encrypt, no cross-signat", "end": 1560, "score": 0.9153440594673157, "start": 1116, "tag": "KEY", "value": "c2c01b0418130a001905025b6f14260910433b1545547b718c021b0205090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8cda9306037c58715454f92d4c39004cf7adffdfc25ea79b85d65840a13bb8eb1d8db455a2f72207195aeed8f6a37e6dfcd35ef5985de539f3bf17358841ad7581fc2cb5844dbb0b2d206e6ae6e99447fcb7f9306517a6100fe396ab483e28ccc6f55e9129c9c209e92eca03560c4baf3156e454347a8c4d27f00fe216749fa6aadb5018c00699b71040f3404572c257772b71751de234f361edaf7" }, { "context": "will\n# become encryption key.\nencryptSigPacket = 'c2610418130a001305025b6f14260910433b1545547b718c021b0c000013aa0100b42663de14cbf358a84d96c997450fc7911426b4eff49aa36bcc532b352618e800ff5953423ce1f82b35ed8b421c3d9a3b3f4f02d0aa05bfa8f99c5b8711b1f290b4'\n\n# Signature with Flags=Encrypt, cross-certified", "end": 1957, "score": 0.9221556782722473, "start": 1759, "tag": "KEY", "value": "c2610418130a001305025b6f14260910433b1545547b718c021b0c000013aa0100b42663de14cbf358a84d96c997450fc7911426b4eff49aa36bcc532b352618e800ff5953423ce1f82b35ed8b421c3d9a3b3f4f02d0aa05bfa8f99c5b8711b1f290b4" }, { "context": " = 'c2c01b0418130a001905025b6f14260910433b1545547b718c021b0c05090784ce00007473200419010a000605025b6f142", "end": 2198, "score": 0.6242483258247375, "start": 2195, "tag": "KEY", "value": "718" }, { "context": "2c01b0418130a001905025b6f14260910433b1545547b718c021b0c05090784ce00007473200419010a000605025b6f142600", "end": 2201, "score": 0.5151286125183105, "start": 2200, "tag": "KEY", "value": "2" }, { "context": "0418130a001905025b6f14260910433b1545547b718c021b0c05090784ce00007473200419010a000605025b6f142600008638", "end": 2207, "score": 0.6702092885971069, "start": 2205, "tag": "KEY", "value": "05" }, { "context": "8130a001905025b6f14260910433b1545547b718c021b0c05090784ce00007473200419010a000605025b6f14260000863803", "end": 2209, "score": 0.5845670104026794, "start": 2208, "tag": "KEY", "value": "9" }, { "context": "30a001905025b6f14260910433b1545547b718c021b0c05090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8", "end": 2233, "score": 0.6386921405792236, "start": 2210, "tag": "KEY", "value": "784ce00007473200419010a" }, { "context": "33b1545547b718c021b0c05090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8cd", "end": 2235, "score": 0.5152228474617004, "start": 2234, "tag": "KEY", "value": "0" }, { "context": "b1545547b718c021b0c05090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8cda930603", "end": 2242, "score": 0.6181912422180176, "start": 2236, "tag": "KEY", "value": "605025" }, { "context": "b718c021b0c05090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8cda9306037c587", "end": 2247, "score": 0.6399858593940735, "start": 2244, "tag": "KEY", "value": "f14" }, { "context": "1b0c05090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8cda9306037c58715454f92d4c39004cf7adffdfc25ea79b85d65840a13bb8eb1d8db455a2f72207195aeed8f6a37e6dfcd35ef5985de539f3bf17358841ad7581fc2cb5844dbb0b2d206e6ae6e99447fcb7f930651f00200ff785d955a6c2a10bded5f7033ba6fa9b38b58dcbf17039bf593fd060a4735e3ef00fd12376c99eb14665d8620c90debc5993be492dbb163e9bc364d52b2b8acc11c68'\n\n# Signature with Flags=Sign, not cross-certifie", "end": 2593, "score": 0.9482434391975403, "start": 2251, "tag": "KEY", "value": "00863803006e73fb2763cb717761b4c8cda9306037c58715454f92d4c39004cf7adffdfc25ea79b85d65840a13bb8eb1d8db455a2f72207195aeed8f6a37e6dfcd35ef5985de539f3bf17358841ad7581fc2cb5844dbb0b2d206e6ae6e99447fcb7f930651f00200ff785d955a6c2a10bded5f7033ba6fa9b38b58dcbf17039bf593fd060a4735e3ef00fd12376c99eb14665d8620c90debc5993be492dbb163e9bc364d52b2b8acc11c68" }, { "context": "t = 'c2610418130a001305025b6f14260910433b1545547b718c021b020000ca2f00ff7c5d366c584ca03ea27cd0dad841f8", "end": 2795, "score": 0.5070713758468628, "start": 2794, "tag": "KEY", "value": "1" }, { "context": "= 'c2610418130a001305025b6f14260910433b1545547b718c021b020000ca2f00ff7c5d366c584ca03ea27cd0dad841f8ad", "end": 2797, "score": 0.5303801894187927, "start": 2796, "tag": "KEY", "value": "c" }, { "context": "10418130a001305025b6f14260910433b1545547b718c021b020000ca2f00ff7c5d366c584ca03ea27cd0dad841f8adda24fc7efa212550ec773effc418136300fe32160c17b36a3a13be3ca6058d35dc7da89bfbb857753e6db45994183e58ed6d'\n\narmoredMessage = \"", "end": 2918, "score": 0.6412771344184875, "start": 2802, "tag": "KEY", "value": "20000ca2f00ff7c5d366c584ca03ea27cd0dad841f8adda24fc7efa212550ec773effc418136300fe32160c17b36a3a13be3ca6058d35dc7da89" }, { "context": "418136300fe32160c17b36a3a13be3ca6058d35dc7da89bfbb857753e6db45994183e58ed6d'\n\narmoredMessage = \"\"\"\n-----BEGI", "end": 2930, "score": 0.6209701299667358, "start": 2922, "tag": "KEY", "value": "857753e6" }, { "context": "e32160c17b36a3a13be3ca6058d35dc7da89bfbb857753e6db45994183e58ed6d'\n\narmoredMessage = \"\"\"\n-----BEGIN PGP MESSAGE--", "end": 2945, "score": 0.585573136806488, "start": 2932, "tag": "KEY", "value": "45994183e58ed" }, { "context": "\narmoredMessage = \"\"\"\n-----BEGIN PGP MESSAGE-----\n\nxA0DAAoBRFStQ5saN6IBy+F0AOIAAAAA5GhlbGxvIGNyb3NzIHNpZ27jZWQgd29y\nbGQAwnwEAAEKABAFAluX8qYJEERUrUObGjeiAADPOgMAaAUjgKY0r+vsO4bxXr5d\nF99ostfQWReex/tkPGqvQRrwEVMKgymQ8zerQdu+30nl+UibIXu9LSvxPbQkPcWN\nxC/ywM5zfa/WOMD1zrOjoCpUktnyMZN8H4P4bF8Az4aj\n=7UNF\n-----END PGP MESSAGE-----\n\n\"\"\"\n\nmake_key_from_par", "end": 3245, "score": 0.9577798843383789, "start": 3000, "tag": "KEY", "value": "xA0DAAoBRFStQ5saN6IBy+F0AOIAAAAA5GhlbGxvIGNyb3NzIHNpZ27jZWQgd29y\nbGQAwnwEAAEKABAFAluX8qYJEERUrUObGjeiAADPOgMAaAUjgKY0r+vsO4bxXr5d\nF99ostfQWReex/tkPGqvQRrwEVMKgymQ8zerQdu+30nl+UibIXu9LSvxPbQkPcWN\nxC/ywM5zfa/WOMD1zrOjoCpUktnyMZN8H4P4bF8Az4aj\n=7UNF" } ]
test/files/subkey_multiple_sigs.iced
samkenxstream/kbpgp
464
C = require('../../lib/const').openpgp {KeyManager} = require '../../lib/main' {do_message} = require '../../lib/openpgp/processor' {Message} = require '../../lib/openpgp/armor' {make_esc} = require 'iced-error' # Keep key in parts that we concatenate in different ways to get different # result. keyAndIdsPackets = 'c652045b6f142613082a8648ce3d030107020304a54bdb6b6f7c145f584c3cf33ba9894b16708b3707310df27625546d2b10310a4ac4b23c516c8ceb4f38aa96a21e02c8717480c831095a2a287317d8e03e3c22cd264d69636861c582205067702054657374203c6e6f742d7a617075406b6579626173652e696f3ec2640413130a001605025b6f14260910433b1545547b718c021b03021901000034cf00ff68b1c1c4abded838df365ce8bec751ff2de8b58cf474b39cef708ac9790db30d0100a8702072316854172daff68dc0167c9e66b2159bca936087a30a8f7054ef20a8' subkeyPacket = 'ce6d045b6f1426010300b97dfbd29467121a7f621d2eff9c78ad8f90017f2074c94f1999ae9956b7e2169af0bcf9d3021421b88e9166d11a2e3153d8ccd9c85d59525af654e4e4c63166273dc365a04ac40d8abce2397aa3058433ce76afba7c7362d130cd395e4e1f0d0011010001' # Signature with Flags=Sign, valid cross-signature, and expiring 4 years from # now. signSigPacket = 'c2c01b0418130a001905025b6f14260910433b1545547b718c021b0205090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8cda9306037c58715454f92d4c39004cf7adffdfc25ea79b85d65840a13bb8eb1d8db455a2f72207195aeed8f6a37e6dfcd35ef5985de539f3bf17358841ad7581fc2cb5844dbb0b2d206e6ae6e99447fcb7f9306517a6100fe396ab483e28ccc6f55e9129c9c209e92eca03560c4baf3156e454347a8c4d27f00fe216749fa6aadb5018c00699b71040f3404572c257772b71751de234f361edaf7' # Signature with Flags=Encrypt, no cross-signature (not needed), and never # expiring. When both are present in bundle, this one will win and key will # become encryption key. encryptSigPacket = 'c2610418130a001305025b6f14260910433b1545547b718c021b0c000013aa0100b42663de14cbf358a84d96c997450fc7911426b4eff49aa36bcc532b352618e800ff5953423ce1f82b35ed8b421c3d9a3b3f4f02d0aa05bfa8f99c5b8711b1f290b4' # Signature with Flags=Encrypt, cross-certified. This binding makes key expire # after 4 years, so if it's combined with binding with no-expiration, it should # lose. encryptXSignPacket = 'c2c01b0418130a001905025b6f14260910433b1545547b718c021b0c05090784ce00007473200419010a000605025b6f14260000863803006e73fb2763cb717761b4c8cda9306037c58715454f92d4c39004cf7adffdfc25ea79b85d65840a13bb8eb1d8db455a2f72207195aeed8f6a37e6dfcd35ef5985de539f3bf17358841ad7581fc2cb5844dbb0b2d206e6ae6e99447fcb7f930651f00200ff785d955a6c2a10bded5f7033ba6fa9b38b58dcbf17039bf593fd060a4735e3ef00fd12376c99eb14665d8620c90debc5993be492dbb163e9bc364d52b2b8acc11c68' # Signature with Flags=Sign, not cross-certified. Provides no-expiration for the, # so it would win against encryptXSignPacket. signSigNoXSignPacket = 'c2610418130a001305025b6f14260910433b1545547b718c021b020000ca2f00ff7c5d366c584ca03ea27cd0dad841f8adda24fc7efa212550ec773effc418136300fe32160c17b36a3a13be3ca6058d35dc7da89bfbb857753e6db45994183e58ed6d' armoredMessage = """ -----BEGIN PGP MESSAGE----- xA0DAAoBRFStQ5saN6IBy+F0AOIAAAAA5GhlbGxvIGNyb3NzIHNpZ27jZWQgd29y bGQAwnwEAAEKABAFAluX8qYJEERUrUObGjeiAADPOgMAaAUjgKY0r+vsO4bxXr5d F99ostfQWReex/tkPGqvQRrwEVMKgymQ8zerQdu+30nl+UibIXu9LSvxPbQkPcWN xC/ywM5zfa/WOMD1zrOjoCpUktnyMZN8H4P4bF8Az4aj =7UNF -----END PGP MESSAGE----- """ make_key_from_parts = (parts, cb) -> keyBuf = Buffer.from(parts.join(''), 'hex') msg = new Message { body : keyBuf, type : C.message_types.public_key } KeyManager.import_from_pgp_message { msg }, cb exports.load_multi_binding_key_and_verify = (T, cb) -> esc = make_esc cb, "load_multi_binding_key_and_verify" await make_key_from_parts [keyAndIdsPackets, subkeyPacket, signSigPacket, encryptSigPacket], esc defer km await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert err?, "have error" T.assert err?.toString().indexOf("We don't have a key for the requested PGP ops") isnt -1, "have right message" T.assert not(msg?), "should not return msg" cb null exports.load_with_only_right_sig_then_verify = (T, cb) -> esc = make_esc cb, "load_with_only_right_sig_then_verify" # Only concat flagSignSig - if we don't add encryptSig, it won't # "win over" signSig, so this key will actually function as a # signing subkey. await make_key_from_parts [keyAndIdsPackets, subkeyPacket, signSigPacket], esc defer km await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert not(err?), "no error" T.assert (msg?[0]?.get_data_signer()?), "was signed!" T.equal msg?[0]?.data.toString(), "hello cross signed world", "right message cae back" cb null exports.do_not_merge_crosscertify = (T, cb) -> esc = make_esc cb, "do_not_merge_crosscertify" # Pass two bindings: one x-certified with flags=encrypt, and another one # *not x-certified* with flags=sign. Subkey should become cross-certified # signing subkey. await make_key_from_parts [keyAndIdsPackets, subkeyPacket, encryptXSignPacket, signSigNoXSignPacket], esc defer km, w # Right now, KBPGP will throw that subkey completely. This happens because # the second binding "wins" (because it provides indefinite key lifetime), # but then in _check_subkeys it is found out that the binding provides no # cross cerfitication, so subkey is deemed invalid. T.assert w.warnings().length is 1, "expecting a warning" T.assert w.warnings()[0]?.indexOf("Subkey 0 was invalid") isnt -1, "found the right warning" await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert err?, "expecting an error" T.assert not(msg?), "do not return message" cb null
55636
C = require('../../lib/const').openpgp {KeyManager} = require '../../lib/main' {do_message} = require '../../lib/openpgp/processor' {Message} = require '../../lib/openpgp/armor' {make_esc} = require 'iced-error' # Keep key in parts that we concatenate in different ways to get different # result. keyAndIdsPackets = '<KEY>' subkeyPacket = '<KEY>' # Signature with Flags=Sign, valid cross-signature, and expiring 4 years from # now. signSigPacket = '<KEY>' # Signature with Flags=Encrypt, no cross-signature (not needed), and never # expiring. When both are present in bundle, this one will win and key will # become encryption key. encryptSigPacket = '<KEY>' # Signature with Flags=Encrypt, cross-certified. This binding makes key expire # after 4 years, so if it's combined with binding with no-expiration, it should # lose. encryptXSignPacket = 'c2c01b0418130a001905025b6f14260910433b1545547b<KEY>c0<KEY>1b0c<KEY>0<KEY>0<KEY>0<KEY>0<KEY>b6<KEY>2600<KEY>' # Signature with Flags=Sign, not cross-certified. Provides no-expiration for the, # so it would win against encryptXSignPacket. signSigNoXSignPacket = 'c2610418130a001305025b6f14260910433b1545547b7<KEY>8<KEY>021b0<KEY>bfbb<KEY>db<KEY>6d' armoredMessage = """ -----BEGIN PGP MESSAGE----- <KEY> -----END PGP MESSAGE----- """ make_key_from_parts = (parts, cb) -> keyBuf = Buffer.from(parts.join(''), 'hex') msg = new Message { body : keyBuf, type : C.message_types.public_key } KeyManager.import_from_pgp_message { msg }, cb exports.load_multi_binding_key_and_verify = (T, cb) -> esc = make_esc cb, "load_multi_binding_key_and_verify" await make_key_from_parts [keyAndIdsPackets, subkeyPacket, signSigPacket, encryptSigPacket], esc defer km await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert err?, "have error" T.assert err?.toString().indexOf("We don't have a key for the requested PGP ops") isnt -1, "have right message" T.assert not(msg?), "should not return msg" cb null exports.load_with_only_right_sig_then_verify = (T, cb) -> esc = make_esc cb, "load_with_only_right_sig_then_verify" # Only concat flagSignSig - if we don't add encryptSig, it won't # "win over" signSig, so this key will actually function as a # signing subkey. await make_key_from_parts [keyAndIdsPackets, subkeyPacket, signSigPacket], esc defer km await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert not(err?), "no error" T.assert (msg?[0]?.get_data_signer()?), "was signed!" T.equal msg?[0]?.data.toString(), "hello cross signed world", "right message cae back" cb null exports.do_not_merge_crosscertify = (T, cb) -> esc = make_esc cb, "do_not_merge_crosscertify" # Pass two bindings: one x-certified with flags=encrypt, and another one # *not x-certified* with flags=sign. Subkey should become cross-certified # signing subkey. await make_key_from_parts [keyAndIdsPackets, subkeyPacket, encryptXSignPacket, signSigNoXSignPacket], esc defer km, w # Right now, KBPGP will throw that subkey completely. This happens because # the second binding "wins" (because it provides indefinite key lifetime), # but then in _check_subkeys it is found out that the binding provides no # cross cerfitication, so subkey is deemed invalid. T.assert w.warnings().length is 1, "expecting a warning" T.assert w.warnings()[0]?.indexOf("Subkey 0 was invalid") isnt -1, "found the right warning" await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert err?, "expecting an error" T.assert not(msg?), "do not return message" cb null
true
C = require('../../lib/const').openpgp {KeyManager} = require '../../lib/main' {do_message} = require '../../lib/openpgp/processor' {Message} = require '../../lib/openpgp/armor' {make_esc} = require 'iced-error' # Keep key in parts that we concatenate in different ways to get different # result. keyAndIdsPackets = 'PI:KEY:<KEY>END_PI' subkeyPacket = 'PI:KEY:<KEY>END_PI' # Signature with Flags=Sign, valid cross-signature, and expiring 4 years from # now. signSigPacket = 'PI:KEY:<KEY>END_PI' # Signature with Flags=Encrypt, no cross-signature (not needed), and never # expiring. When both are present in bundle, this one will win and key will # become encryption key. encryptSigPacket = 'PI:KEY:<KEY>END_PI' # Signature with Flags=Encrypt, cross-certified. This binding makes key expire # after 4 years, so if it's combined with binding with no-expiration, it should # lose. encryptXSignPacket = 'c2c01b0418130a001905025b6f14260910433b1545547bPI:KEY:<KEY>END_PIc0PI:KEY:<KEY>END_PI1b0cPI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PIb6PI:KEY:<KEY>END_PI2600PI:KEY:<KEY>END_PI' # Signature with Flags=Sign, not cross-certified. Provides no-expiration for the, # so it would win against encryptXSignPacket. signSigNoXSignPacket = 'c2610418130a001305025b6f14260910433b1545547b7PI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI021b0PI:KEY:<KEY>END_PIbfbbPI:KEY:<KEY>END_PIdbPI:KEY:<KEY>END_PI6d' armoredMessage = """ -----BEGIN PGP MESSAGE----- PI:KEY:<KEY>END_PI -----END PGP MESSAGE----- """ make_key_from_parts = (parts, cb) -> keyBuf = Buffer.from(parts.join(''), 'hex') msg = new Message { body : keyBuf, type : C.message_types.public_key } KeyManager.import_from_pgp_message { msg }, cb exports.load_multi_binding_key_and_verify = (T, cb) -> esc = make_esc cb, "load_multi_binding_key_and_verify" await make_key_from_parts [keyAndIdsPackets, subkeyPacket, signSigPacket, encryptSigPacket], esc defer km await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert err?, "have error" T.assert err?.toString().indexOf("We don't have a key for the requested PGP ops") isnt -1, "have right message" T.assert not(msg?), "should not return msg" cb null exports.load_with_only_right_sig_then_verify = (T, cb) -> esc = make_esc cb, "load_with_only_right_sig_then_verify" # Only concat flagSignSig - if we don't add encryptSig, it won't # "win over" signSig, so this key will actually function as a # signing subkey. await make_key_from_parts [keyAndIdsPackets, subkeyPacket, signSigPacket], esc defer km await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert not(err?), "no error" T.assert (msg?[0]?.get_data_signer()?), "was signed!" T.equal msg?[0]?.data.toString(), "hello cross signed world", "right message cae back" cb null exports.do_not_merge_crosscertify = (T, cb) -> esc = make_esc cb, "do_not_merge_crosscertify" # Pass two bindings: one x-certified with flags=encrypt, and another one # *not x-certified* with flags=sign. Subkey should become cross-certified # signing subkey. await make_key_from_parts [keyAndIdsPackets, subkeyPacket, encryptXSignPacket, signSigNoXSignPacket], esc defer km, w # Right now, KBPGP will throw that subkey completely. This happens because # the second binding "wins" (because it provides indefinite key lifetime), # but then in _check_subkeys it is found out that the binding provides no # cross cerfitication, so subkey is deemed invalid. T.assert w.warnings().length is 1, "expecting a warning" T.assert w.warnings()[0]?.indexOf("Subkey 0 was invalid") isnt -1, "found the right warning" await do_message { armored : armoredMessage, keyfetch : km }, defer err, msg T.assert err?, "expecting an error" T.assert not(msg?), "do not return message" cb null
[ { "context": "home controller shows the start view.\n\n @author Sebastian Sachtleben\n###\nclass HomeController extends BaseController\n\n", "end": 138, "score": 0.9998869895935059, "start": 118, "tag": "NAME", "value": "Sebastian Sachtleben" } ]
app/assets/javascripts/site/controllers/home.coffee
ssachtleben/herowar
1
BaseController = require 'controllers/baseController' ### The home controller shows the start view. @author Sebastian Sachtleben ### class HomeController extends BaseController views: 'views/header' : '' 'views/home' : '' return HomeController
149681
BaseController = require 'controllers/baseController' ### The home controller shows the start view. @author <NAME> ### class HomeController extends BaseController views: 'views/header' : '' 'views/home' : '' return HomeController
true
BaseController = require 'controllers/baseController' ### The home controller shows the start view. @author PI:NAME:<NAME>END_PI ### class HomeController extends BaseController views: 'views/header' : '' 'views/home' : '' return HomeController
[ { "context": " ### a=b ###\n\n key = keyval.split('=', 1)[0]\n\n ### If the key is blank, eg. \"#path?a=b&=", "end": 2943, "score": 0.60211580991745, "start": 2942, "tag": "KEY", "value": "0" }, { "context": "lit('=', 1)[0]\n\n ### If the key is blank, eg. \"#path?a=b&=d\", then ignore the value. It'll overwrite\n #", "end": 2994, "score": 0.8968082070350647, "start": 2981, "tag": "KEY", "value": "\"#path?a=b&=d" }, { "context": "+= path\n params = []\n hash.each (k) ->\n key = k[0]\n value = k[1]\n if key == ''\n return\n ", "end": 3750, "score": 0.703100860118866, "start": 3747, "tag": "KEY", "value": "k[0" }, { "context": " return\n if !value?\n return\n key = window.encodeURIComponent(key)\n value = window.encodeURIComponent(value)\n ", "end": 3866, "score": 0.9235284924507141, "start": 3837, "tag": "KEY", "value": "window.encodeURIComponent(key" } ]
app/javascript/src/legacy/browser-url-hash.coffee
AstroAntics/moebooru
0
window.UrlHashHandler = -> @observers = new Hash @normalize = (h) -> @denormalize = (h) -> @deferred_sets = [] @deferred_replace = false @current_hash = @parse(@get_raw_hash()) @normalize @current_hash ### The last value received by the hashchange event: ### @last_hashchange = @current_hash.clone() @hashchange_event = @hashchange_event.bindAsEventListener(this) Element.observe window, 'hashchange', @hashchange_event return UrlHashHandler::fire_observers = (old_hash, new_hash) -> all_keys = old_hash.keys() all_keys = all_keys.concat(new_hash.keys()) all_keys = all_keys.uniq() changed_hash_keys = [] all_keys.each ((key) -> old_value = old_hash.get(key) new_value = new_hash.get(key) if old_value != new_value changed_hash_keys.push key return ).bind(this) observers_to_call = [] changed_hash_keys.each ((key) -> observers = @observers.get(key) if !observers? return observers_to_call = observers_to_call.concat(observers) return ).bind(this) universal_observers = @observers.get(null) if universal_observers? observers_to_call = observers_to_call.concat(universal_observers) observers_to_call.each (observer) -> observer changed_hash_keys, old_hash, new_hash return return ### # Set handlers to normalize and denormalize the URL hash. # # Denormalizing a URL hash can convert the URL hash to something clearer for URLs. Normalizing # it reverses any denormalization, giving names to parameters. # # For example, if a normalized URL is # # http://www.example.com/app#show?id=1 # # where the hash is {"": "show", id: "1"}, a denormalized URL may be # # http://www.example.com/app#show/1 # # The denormalize callback will only be called with normalized input. The normalize callback # may receive any combination of normalized or denormalized input. ### UrlHashHandler::set_normalize = (norm, denorm) -> @normalize = norm @denormalize = denorm @normalize @current_hash @set_all @current_hash.clone() return UrlHashHandler::hashchange_event = (event) -> old_hash = @last_hashchange.clone() @normalize old_hash raw = @get_raw_hash() new_hash = @parse(raw) @normalize new_hash @current_hash = new_hash.clone() @last_hashchange = new_hash.clone() @fire_observers old_hash, new_hash return ### # Parse a hash, returning a Hash. # # #a/b?c=d&e=f -> {"": 'a/b', c: 'd', e: 'f'} ### UrlHashHandler::parse = (hash) -> if !hash? hash = '' if hash.substr(0, 1) == '#' hash = hash.substr(1) hash_path = hash.split('?', 1)[0] hash_query = hash.substr(hash_path.length + 1) hash_path = window.decodeURIComponent(hash_path) query_params = new Hash query_params.set '', hash_path if hash_query != '' hash_query_values = hash_query.split('&') i = 0 while i < hash_query_values.length keyval = hash_query_values[i] ### a=b ### key = keyval.split('=', 1)[0] ### If the key is blank, eg. "#path?a=b&=d", then ignore the value. It'll overwrite # the path, which is confusing and never what's wanted. ### if key == '' ++i continue value = keyval.substr(key.length + 1) key = window.decodeURIComponent(key) value = window.decodeURIComponent(value) query_params.set key, value ++i query_params UrlHashHandler::construct = (hash) -> s = '#' path = hash.get('') if path? ### For the path portion, we only need to escape the params separator ? and the escape # character % itself. Don't use encodeURIComponent; it'll encode far more than necessary. ### path = path.replace(/%/g, '%25').replace(/\?/g, '%3f') s += path params = [] hash.each (k) -> key = k[0] value = k[1] if key == '' return if !value? return key = window.encodeURIComponent(key) value = window.encodeURIComponent(value) params.push key + '=' + value return if params.length != 0 s += '?' + params.join('&') s UrlHashHandler::get_raw_hash = -> ### # Firefox doesn't handle window.location.hash correctly; it decodes the contents, # where all other browsers give us the correct data. http://stackoverflow.com/questions/1703552 ### pre_hash_part = window.location.href.split('#', 1)[0] window.location.href.substr pre_hash_part.length UrlHashHandler::set_raw_hash = (hash) -> query_params = @parse(hash) @set_all query_params return UrlHashHandler::get = (key) -> @current_hash.get key ### # Set keys in the URL hash. # # UrlHash.set({id: 50}); # # If replace is true and the History API is available, replace the state instead # of pushing it. ### UrlHashHandler::set = (hash, replace) -> new_hash = @current_hash.merge(hash) @normalize new_hash @set_all new_hash, replace return ### # Each call to UrlHash.set() will immediately set the new hash, which will create a new # browser history slot. This isn't always wanted. When several changes are being made # in response to a single action, all changes should be made simultaeously, so only a # single history slot is created. Making only a single call to set() is difficult when # these changes are made by unrelated parts of code. # # Defer changes to the URL hash. If several calls are made in quick succession, buffer # the changes. When a short timer expires, make all changes at once. This will never # happen before the current Javascript call completes, because timers will never interrupt # running code. # # UrlHash.set() doesn't do this, because set() guarantees that the hashchange event will # be fired and complete before the function returns. # # If replace is true and the History API is available, replace the state instead of pushing # it. If any set_deferred call consolidated into a single update has replace = false, the # new state will be pushed. ### UrlHashHandler::set_deferred = (hash, replace) -> @deferred_sets.push hash if replace @deferred_replace = true set = (-> @deferred_set_timer = null new_hash = @current_hash @deferred_sets.each (m) -> new_hash = new_hash.merge(m) return @normalize new_hash @set_all new_hash, @deferred_replace @deferred_sets = [] @hashchange_event null @deferred_replace = false return ).bind(this) if !@deferred_set_timer? @deferred_set_timer = set.defer() return UrlHashHandler::set_all = (query_params, replace) -> query_params = query_params.clone() @normalize query_params @current_hash = query_params.clone() @denormalize query_params new_hash = @construct(query_params) if window.location.hash != new_hash ### If the History API is available, use it to support URL replacement. FF4.0's pushState # is broken; don't use it. ### if window.history and window.history.replaceState and window.history.pushState and !navigator.userAgent.match('Firefox/[45].') url = window.location.protocol + '//' + window.location.host + window.location.pathname + new_hash if replace window.history.replaceState {}, window.title, url else window.history.pushState {}, window.title, url else window.location.hash = new_hash ### Explicitly fire the hashchange event, so it's handled quickly even if the browser # doesn't support the event. It's harmless if we get this event multiple times due # to the browser delivering it normally due to our change. ### @hashchange_event null return ### Observe changes to the specified key. If key is null, watch for all changes. ### UrlHashHandler::observe = (key, func) -> observers = @observers.get(key) if !observers? observers = [] @observers.set key, observers if observers.indexOf(func) != -1 return observers.push func return UrlHashHandler::stopObserving = (key, func) -> observers = @observers.get(key) if !observers? return observers = observers.without(func) @observers.set key, observers return window.UrlHash = new UrlHashHandler
108664
window.UrlHashHandler = -> @observers = new Hash @normalize = (h) -> @denormalize = (h) -> @deferred_sets = [] @deferred_replace = false @current_hash = @parse(@get_raw_hash()) @normalize @current_hash ### The last value received by the hashchange event: ### @last_hashchange = @current_hash.clone() @hashchange_event = @hashchange_event.bindAsEventListener(this) Element.observe window, 'hashchange', @hashchange_event return UrlHashHandler::fire_observers = (old_hash, new_hash) -> all_keys = old_hash.keys() all_keys = all_keys.concat(new_hash.keys()) all_keys = all_keys.uniq() changed_hash_keys = [] all_keys.each ((key) -> old_value = old_hash.get(key) new_value = new_hash.get(key) if old_value != new_value changed_hash_keys.push key return ).bind(this) observers_to_call = [] changed_hash_keys.each ((key) -> observers = @observers.get(key) if !observers? return observers_to_call = observers_to_call.concat(observers) return ).bind(this) universal_observers = @observers.get(null) if universal_observers? observers_to_call = observers_to_call.concat(universal_observers) observers_to_call.each (observer) -> observer changed_hash_keys, old_hash, new_hash return return ### # Set handlers to normalize and denormalize the URL hash. # # Denormalizing a URL hash can convert the URL hash to something clearer for URLs. Normalizing # it reverses any denormalization, giving names to parameters. # # For example, if a normalized URL is # # http://www.example.com/app#show?id=1 # # where the hash is {"": "show", id: "1"}, a denormalized URL may be # # http://www.example.com/app#show/1 # # The denormalize callback will only be called with normalized input. The normalize callback # may receive any combination of normalized or denormalized input. ### UrlHashHandler::set_normalize = (norm, denorm) -> @normalize = norm @denormalize = denorm @normalize @current_hash @set_all @current_hash.clone() return UrlHashHandler::hashchange_event = (event) -> old_hash = @last_hashchange.clone() @normalize old_hash raw = @get_raw_hash() new_hash = @parse(raw) @normalize new_hash @current_hash = new_hash.clone() @last_hashchange = new_hash.clone() @fire_observers old_hash, new_hash return ### # Parse a hash, returning a Hash. # # #a/b?c=d&e=f -> {"": 'a/b', c: 'd', e: 'f'} ### UrlHashHandler::parse = (hash) -> if !hash? hash = '' if hash.substr(0, 1) == '#' hash = hash.substr(1) hash_path = hash.split('?', 1)[0] hash_query = hash.substr(hash_path.length + 1) hash_path = window.decodeURIComponent(hash_path) query_params = new Hash query_params.set '', hash_path if hash_query != '' hash_query_values = hash_query.split('&') i = 0 while i < hash_query_values.length keyval = hash_query_values[i] ### a=b ### key = keyval.split('=', 1)[<KEY>] ### If the key is blank, eg. <KEY>", then ignore the value. It'll overwrite # the path, which is confusing and never what's wanted. ### if key == '' ++i continue value = keyval.substr(key.length + 1) key = window.decodeURIComponent(key) value = window.decodeURIComponent(value) query_params.set key, value ++i query_params UrlHashHandler::construct = (hash) -> s = '#' path = hash.get('') if path? ### For the path portion, we only need to escape the params separator ? and the escape # character % itself. Don't use encodeURIComponent; it'll encode far more than necessary. ### path = path.replace(/%/g, '%25').replace(/\?/g, '%3f') s += path params = [] hash.each (k) -> key = <KEY>] value = k[1] if key == '' return if !value? return key = <KEY>) value = window.encodeURIComponent(value) params.push key + '=' + value return if params.length != 0 s += '?' + params.join('&') s UrlHashHandler::get_raw_hash = -> ### # Firefox doesn't handle window.location.hash correctly; it decodes the contents, # where all other browsers give us the correct data. http://stackoverflow.com/questions/1703552 ### pre_hash_part = window.location.href.split('#', 1)[0] window.location.href.substr pre_hash_part.length UrlHashHandler::set_raw_hash = (hash) -> query_params = @parse(hash) @set_all query_params return UrlHashHandler::get = (key) -> @current_hash.get key ### # Set keys in the URL hash. # # UrlHash.set({id: 50}); # # If replace is true and the History API is available, replace the state instead # of pushing it. ### UrlHashHandler::set = (hash, replace) -> new_hash = @current_hash.merge(hash) @normalize new_hash @set_all new_hash, replace return ### # Each call to UrlHash.set() will immediately set the new hash, which will create a new # browser history slot. This isn't always wanted. When several changes are being made # in response to a single action, all changes should be made simultaeously, so only a # single history slot is created. Making only a single call to set() is difficult when # these changes are made by unrelated parts of code. # # Defer changes to the URL hash. If several calls are made in quick succession, buffer # the changes. When a short timer expires, make all changes at once. This will never # happen before the current Javascript call completes, because timers will never interrupt # running code. # # UrlHash.set() doesn't do this, because set() guarantees that the hashchange event will # be fired and complete before the function returns. # # If replace is true and the History API is available, replace the state instead of pushing # it. If any set_deferred call consolidated into a single update has replace = false, the # new state will be pushed. ### UrlHashHandler::set_deferred = (hash, replace) -> @deferred_sets.push hash if replace @deferred_replace = true set = (-> @deferred_set_timer = null new_hash = @current_hash @deferred_sets.each (m) -> new_hash = new_hash.merge(m) return @normalize new_hash @set_all new_hash, @deferred_replace @deferred_sets = [] @hashchange_event null @deferred_replace = false return ).bind(this) if !@deferred_set_timer? @deferred_set_timer = set.defer() return UrlHashHandler::set_all = (query_params, replace) -> query_params = query_params.clone() @normalize query_params @current_hash = query_params.clone() @denormalize query_params new_hash = @construct(query_params) if window.location.hash != new_hash ### If the History API is available, use it to support URL replacement. FF4.0's pushState # is broken; don't use it. ### if window.history and window.history.replaceState and window.history.pushState and !navigator.userAgent.match('Firefox/[45].') url = window.location.protocol + '//' + window.location.host + window.location.pathname + new_hash if replace window.history.replaceState {}, window.title, url else window.history.pushState {}, window.title, url else window.location.hash = new_hash ### Explicitly fire the hashchange event, so it's handled quickly even if the browser # doesn't support the event. It's harmless if we get this event multiple times due # to the browser delivering it normally due to our change. ### @hashchange_event null return ### Observe changes to the specified key. If key is null, watch for all changes. ### UrlHashHandler::observe = (key, func) -> observers = @observers.get(key) if !observers? observers = [] @observers.set key, observers if observers.indexOf(func) != -1 return observers.push func return UrlHashHandler::stopObserving = (key, func) -> observers = @observers.get(key) if !observers? return observers = observers.without(func) @observers.set key, observers return window.UrlHash = new UrlHashHandler
true
window.UrlHashHandler = -> @observers = new Hash @normalize = (h) -> @denormalize = (h) -> @deferred_sets = [] @deferred_replace = false @current_hash = @parse(@get_raw_hash()) @normalize @current_hash ### The last value received by the hashchange event: ### @last_hashchange = @current_hash.clone() @hashchange_event = @hashchange_event.bindAsEventListener(this) Element.observe window, 'hashchange', @hashchange_event return UrlHashHandler::fire_observers = (old_hash, new_hash) -> all_keys = old_hash.keys() all_keys = all_keys.concat(new_hash.keys()) all_keys = all_keys.uniq() changed_hash_keys = [] all_keys.each ((key) -> old_value = old_hash.get(key) new_value = new_hash.get(key) if old_value != new_value changed_hash_keys.push key return ).bind(this) observers_to_call = [] changed_hash_keys.each ((key) -> observers = @observers.get(key) if !observers? return observers_to_call = observers_to_call.concat(observers) return ).bind(this) universal_observers = @observers.get(null) if universal_observers? observers_to_call = observers_to_call.concat(universal_observers) observers_to_call.each (observer) -> observer changed_hash_keys, old_hash, new_hash return return ### # Set handlers to normalize and denormalize the URL hash. # # Denormalizing a URL hash can convert the URL hash to something clearer for URLs. Normalizing # it reverses any denormalization, giving names to parameters. # # For example, if a normalized URL is # # http://www.example.com/app#show?id=1 # # where the hash is {"": "show", id: "1"}, a denormalized URL may be # # http://www.example.com/app#show/1 # # The denormalize callback will only be called with normalized input. The normalize callback # may receive any combination of normalized or denormalized input. ### UrlHashHandler::set_normalize = (norm, denorm) -> @normalize = norm @denormalize = denorm @normalize @current_hash @set_all @current_hash.clone() return UrlHashHandler::hashchange_event = (event) -> old_hash = @last_hashchange.clone() @normalize old_hash raw = @get_raw_hash() new_hash = @parse(raw) @normalize new_hash @current_hash = new_hash.clone() @last_hashchange = new_hash.clone() @fire_observers old_hash, new_hash return ### # Parse a hash, returning a Hash. # # #a/b?c=d&e=f -> {"": 'a/b', c: 'd', e: 'f'} ### UrlHashHandler::parse = (hash) -> if !hash? hash = '' if hash.substr(0, 1) == '#' hash = hash.substr(1) hash_path = hash.split('?', 1)[0] hash_query = hash.substr(hash_path.length + 1) hash_path = window.decodeURIComponent(hash_path) query_params = new Hash query_params.set '', hash_path if hash_query != '' hash_query_values = hash_query.split('&') i = 0 while i < hash_query_values.length keyval = hash_query_values[i] ### a=b ### key = keyval.split('=', 1)[PI:KEY:<KEY>END_PI] ### If the key is blank, eg. PI:KEY:<KEY>END_PI", then ignore the value. It'll overwrite # the path, which is confusing and never what's wanted. ### if key == '' ++i continue value = keyval.substr(key.length + 1) key = window.decodeURIComponent(key) value = window.decodeURIComponent(value) query_params.set key, value ++i query_params UrlHashHandler::construct = (hash) -> s = '#' path = hash.get('') if path? ### For the path portion, we only need to escape the params separator ? and the escape # character % itself. Don't use encodeURIComponent; it'll encode far more than necessary. ### path = path.replace(/%/g, '%25').replace(/\?/g, '%3f') s += path params = [] hash.each (k) -> key = PI:KEY:<KEY>END_PI] value = k[1] if key == '' return if !value? return key = PI:KEY:<KEY>END_PI) value = window.encodeURIComponent(value) params.push key + '=' + value return if params.length != 0 s += '?' + params.join('&') s UrlHashHandler::get_raw_hash = -> ### # Firefox doesn't handle window.location.hash correctly; it decodes the contents, # where all other browsers give us the correct data. http://stackoverflow.com/questions/1703552 ### pre_hash_part = window.location.href.split('#', 1)[0] window.location.href.substr pre_hash_part.length UrlHashHandler::set_raw_hash = (hash) -> query_params = @parse(hash) @set_all query_params return UrlHashHandler::get = (key) -> @current_hash.get key ### # Set keys in the URL hash. # # UrlHash.set({id: 50}); # # If replace is true and the History API is available, replace the state instead # of pushing it. ### UrlHashHandler::set = (hash, replace) -> new_hash = @current_hash.merge(hash) @normalize new_hash @set_all new_hash, replace return ### # Each call to UrlHash.set() will immediately set the new hash, which will create a new # browser history slot. This isn't always wanted. When several changes are being made # in response to a single action, all changes should be made simultaeously, so only a # single history slot is created. Making only a single call to set() is difficult when # these changes are made by unrelated parts of code. # # Defer changes to the URL hash. If several calls are made in quick succession, buffer # the changes. When a short timer expires, make all changes at once. This will never # happen before the current Javascript call completes, because timers will never interrupt # running code. # # UrlHash.set() doesn't do this, because set() guarantees that the hashchange event will # be fired and complete before the function returns. # # If replace is true and the History API is available, replace the state instead of pushing # it. If any set_deferred call consolidated into a single update has replace = false, the # new state will be pushed. ### UrlHashHandler::set_deferred = (hash, replace) -> @deferred_sets.push hash if replace @deferred_replace = true set = (-> @deferred_set_timer = null new_hash = @current_hash @deferred_sets.each (m) -> new_hash = new_hash.merge(m) return @normalize new_hash @set_all new_hash, @deferred_replace @deferred_sets = [] @hashchange_event null @deferred_replace = false return ).bind(this) if !@deferred_set_timer? @deferred_set_timer = set.defer() return UrlHashHandler::set_all = (query_params, replace) -> query_params = query_params.clone() @normalize query_params @current_hash = query_params.clone() @denormalize query_params new_hash = @construct(query_params) if window.location.hash != new_hash ### If the History API is available, use it to support URL replacement. FF4.0's pushState # is broken; don't use it. ### if window.history and window.history.replaceState and window.history.pushState and !navigator.userAgent.match('Firefox/[45].') url = window.location.protocol + '//' + window.location.host + window.location.pathname + new_hash if replace window.history.replaceState {}, window.title, url else window.history.pushState {}, window.title, url else window.location.hash = new_hash ### Explicitly fire the hashchange event, so it's handled quickly even if the browser # doesn't support the event. It's harmless if we get this event multiple times due # to the browser delivering it normally due to our change. ### @hashchange_event null return ### Observe changes to the specified key. If key is null, watch for all changes. ### UrlHashHandler::observe = (key, func) -> observers = @observers.get(key) if !observers? observers = [] @observers.set key, observers if observers.indexOf(func) != -1 return observers.push func return UrlHashHandler::stopObserving = (key, func) -> observers = @observers.get(key) if !observers? return observers = observers.without(func) @observers.set key, observers return window.UrlHash = new UrlHashHandler
[ { "context": "e CMS helpers\n#\n# Nodize CMS\n# https://github.com/hypee/nodize\n#\n# Copyright 2013, Hypee\n# http://hypee.c", "end": 98, "score": 0.9994433522224426, "start": 93, "tag": "USERNAME", "value": "hypee" }, { "context": "ttps://github.com/hypee/nodize\n#\n# Copyright 2013, Hypee\n# http://hypee.com\n#\n# Licensed under the MIT lic", "end": 131, "score": 0.9978995323181152, "start": 126, "tag": "NAME", "value": "Hypee" } ]
modules/ionize/libs/jade_helpers_filters.coffee
nodize/nodizecms
32
# Monkey patching Jade to allow using Nodize CMS helpers # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2013, Hypee # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # jade = require "jade" # # Adding helpers compatibility to Jade templates, # Creating a new filter for each existing helpers # createFilters = (helpers) -> for helper_name,helper_function of helpers do (helper_name,helper_function) -> jade.filters[ helper_name ] = (block, options) -> try # Calling the regular helper @template_engine = "jade" helper_function.call( @, options, block ) catch error console.log "Template error [#{helper_name}]: ", error console.log "jade_helpers_filters | stack", error.stack init = -> filters = require "jade/lib/filters" utils = require "jade/lib/utils" # # Modification to send the context (locals) to the Jade template executed inside the filter # jade.Compiler::visitFilter = (filter) -> fn = filters[filter.name] #console.log "Filter is ", filter # unknown filter throw new Error("unknown filter \":" + filter.name + "\"") unless fn text = filter.block.nodes.map((node) -> node.val ).join("\n") # console.log "text is ", text filter.attrs = filter.attrs or {} filter.attrs.filename = @options.filename # Original Javascript code, modified to send the context : # this.buffer(utils.text(fn(text, filter.attrs))); try @buffer utils.text(fn.call(@options, text, filter.attrs)) catch err console.log "visitFilter error : ", err init() module.exports.createFilters = createFilters #module.exports = sequelize #exports.config = config
91254
# Monkey patching Jade to allow using Nodize CMS helpers # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2013, <NAME> # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # jade = require "jade" # # Adding helpers compatibility to Jade templates, # Creating a new filter for each existing helpers # createFilters = (helpers) -> for helper_name,helper_function of helpers do (helper_name,helper_function) -> jade.filters[ helper_name ] = (block, options) -> try # Calling the regular helper @template_engine = "jade" helper_function.call( @, options, block ) catch error console.log "Template error [#{helper_name}]: ", error console.log "jade_helpers_filters | stack", error.stack init = -> filters = require "jade/lib/filters" utils = require "jade/lib/utils" # # Modification to send the context (locals) to the Jade template executed inside the filter # jade.Compiler::visitFilter = (filter) -> fn = filters[filter.name] #console.log "Filter is ", filter # unknown filter throw new Error("unknown filter \":" + filter.name + "\"") unless fn text = filter.block.nodes.map((node) -> node.val ).join("\n") # console.log "text is ", text filter.attrs = filter.attrs or {} filter.attrs.filename = @options.filename # Original Javascript code, modified to send the context : # this.buffer(utils.text(fn(text, filter.attrs))); try @buffer utils.text(fn.call(@options, text, filter.attrs)) catch err console.log "visitFilter error : ", err init() module.exports.createFilters = createFilters #module.exports = sequelize #exports.config = config
true
# Monkey patching Jade to allow using Nodize CMS helpers # # Nodize CMS # https://github.com/hypee/nodize # # Copyright 2013, PI:NAME:<NAME>END_PI # http://hypee.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # jade = require "jade" # # Adding helpers compatibility to Jade templates, # Creating a new filter for each existing helpers # createFilters = (helpers) -> for helper_name,helper_function of helpers do (helper_name,helper_function) -> jade.filters[ helper_name ] = (block, options) -> try # Calling the regular helper @template_engine = "jade" helper_function.call( @, options, block ) catch error console.log "Template error [#{helper_name}]: ", error console.log "jade_helpers_filters | stack", error.stack init = -> filters = require "jade/lib/filters" utils = require "jade/lib/utils" # # Modification to send the context (locals) to the Jade template executed inside the filter # jade.Compiler::visitFilter = (filter) -> fn = filters[filter.name] #console.log "Filter is ", filter # unknown filter throw new Error("unknown filter \":" + filter.name + "\"") unless fn text = filter.block.nodes.map((node) -> node.val ).join("\n") # console.log "text is ", text filter.attrs = filter.attrs or {} filter.attrs.filename = @options.filename # Original Javascript code, modified to send the context : # this.buffer(utils.text(fn(text, filter.attrs))); try @buffer utils.text(fn.call(@options, text, filter.attrs)) catch err console.log "visitFilter error : ", err init() module.exports.createFilters = createFilters #module.exports = sequelize #exports.config = config
[ { "context": "ail address to signup'\n u :\n aliases : [ 'username' ]\n help : 'the username to signup as'\n\n #-", "end": 814, "score": 0.9281525015830994, "start": 806, "tag": "USERNAME", "value": "username" }, { "context": "\n pwh : @pwh.toString('hex')\n username : @data.username\n email : @data.email\n invitation_id : @", "end": 2451, "score": 0.9973835945129395, "start": 2437, "tag": "USERNAME", "value": "@data.username" }, { "context": "P_USERNAME_TAKEN'\n log.error \"Username '#{@data.username}' already registered\"\n retry = true\n ", "end": 2985, "score": 0.9943908452987671, "start": 2971, "tag": "USERNAME", "value": "@data.username" }, { "context": "fields.username\n log.error \"Username '#{@data.username}' was rejected by the server\"\n retry =", "end": 3198, "score": 0.9894747138023376, "start": 3184, "tag": "USERNAME", "value": "@data.username" }, { "context": " ->\n seq =\n full_name :\n prompt : \"Your name\"\n notes :\n prompt : \"Any comments for", "end": 5053, "score": 0.6878453493118286, "start": 5044, "tag": "NAME", "value": "Your name" } ]
src/command/join.iced
AngelKey/Angelkey.nodeclient
151
{Base} = require './base' log = require '../log' {ArgumentParser} = require 'argparse' {add_option_dict} = require './argparse' {PackageJson} = require '../package' {E} = require '../err' {prompt_yn,Prompter} = require '../prompter' {checkers} = require '../checkers' {make_esc} = require 'iced-error' triplesec = require 'triplesec' {rng} = require 'crypto' {constants} = require '../constants' SC = constants.security req = require '../req' {env} = require '../env' read = require 'read' session = require '../session' {dict_union} = require '../util' ##======================================================================= exports.Command = class Command extends Base #---------- OPTS : e : aliases : [ 'email' ] help : 'the email address to signup' u : aliases : [ 'username' ] help : 'the username to signup as' #---------- use_session : () -> true #---------- add_subcommand_parser : (scp) -> opts = aliases : [ "signup" ] help : "establish a new account on keybase.io" name = "join" sub = scp.addParser name, opts opts.aliases.concat [ name ] #---------- prompt : (cb) -> seq = email : prompt : "Your email" checker : checkers.email invite: prompt : "Invitation code (leave blank if you don't have one)" thrower : (k,s) -> if (s.match /^\s*$/)? then (new E.CleanCancelError(k)) else null username : prompt : "Your desired username" checker : checkers.username passphrase: prompt: "Your login passphrase" passphrase: true checker: checkers.passphrase confirm : prompt: "Repeat to confirm" if not @prompter if (u = env().get_username())? then seq.username.defval = u if (p = env().get_passphrase())? then seq.passphrase.defval = p if (e = env().get_email())? then seq.email.defval = e @prompter = new Prompter seq await @prompter.run defer err @data = @prompter.data() unless err? cb err #---------- gen_pwh : (cb) -> passphrase = @data.passphrase if not(@pp_last) or (@pp_last isnt passphrase) await session.gen_pwh { passphrase }, defer err, @pwh, @salt, @pwh_version @pp_last = passphrase if not err? cb err #---------- post : (cb) -> args = salt : @salt.toString('hex') pwh : @pwh.toString('hex') username : @data.username email : @data.email invitation_id : @data.invite pwh_version : @pwh_version await req.post { endpoint : "signup", args }, defer err, body retry = false if err? and (err instanceof E.KeybaseError) switch body.status.name when 'BAD_SIGNUP_EMAIL_TAKEN' log.error "Email address '#{@data.email}' already registered" retry = true @prompter.clear 'email' err = null when 'BAD_SIGNUP_USERNAME_TAKEN' log.error "Username '#{@data.username}' already registered" retry = true @prompter.clear 'username' err = null when 'INPUT_ERROR' if err.fields.username log.error "Username '#{@data.username}' was rejected by the server" retry = true @prompter.clear 'username' err = null when 'BAD_INVITATION_CODE' log.error "Bad invitation code '#{@data.invite}' given" retry = true @prompter.clear 'invite' err = null if not err? @uid = body.uid session.set_id body.session session.set_csrf body.csrf_token else if not retry then log.error "Unexpected error: #{err}" cb err, retry #---------- write_out : (cb) -> esc = make_esc cb, "Join::write_out" await @write_config esc defer() await session.write esc defer() cb null #---------- write_config : (cb) -> c = env().config c.set "user.email", @data.email c.set "user.salt", @salt.toString('hex') c.set "user.name", @data.username c.set "user.id" , @uid await c.write defer err cb err #---------- check_registered : (cb) -> err = null if (env().config.get "user.id")? opts = prompt : "Already registered; do you want to reregister?" defval : false await prompt_yn opts, defer err, rereg if not err? and not rereg err = new E.CancelError "registration canceled" cb err #---------- request_invite : (cb) -> esc = make_esc cb, "request_invite" await @ri_prompt_for_ok esc defer() await @ri_prompt_for_data esc defer d2 await @ri_post_request d2, esc defer() cb null #---------- ri_prompt_for_ok : (cb) -> opts = prompt : "Would you like to be added to the invite list?" defval : true await prompt_yn opts, defer err, go if not err? and not go err = new E.CancelError "invitation request canceled" cb err #---------- ri_prompt_for_data : (cb) -> seq = full_name : prompt : "Your name" notes : prompt : "Any comments for the team" prompter = new Prompter seq await prompter.run defer err ret = null ret = prompter.data() unless err? cb err, ret #---------- ri_post_request : (d2, cb) -> args = dict_union d2, @prompter.data() await req.post {endpoint : "invitation_request", args }, defer err unless err? log.info "Success! You're on our list. Thanks for your interest!" cb err #---------- run : (cb) -> await @run2 defer err if err? and (err instanceof E.CleanCancelError) await @request_invite defer err cb err #---------- run2 : (cb) -> esc = make_esc cb, "Join::run" retry = true await @check_registered esc defer() while retry await @prompt esc defer() await @gen_pwh esc defer() await @post esc defer retry await @write_out esc defer() log.info "Success! You are now signed up." log.console.log """ Welcome to keybase.io! You now need to associate a public key with your account. If you have a key already then: keybase push <key-id> # if you know the ID of the key --- OR --- keybase push # to select from a menu If you need a public key, we'll happily generate one for you: keybase gen --push # Generate a new key and push public part to server Enjoy! """ cb null ##=======================================================================
6952
{Base} = require './base' log = require '../log' {ArgumentParser} = require 'argparse' {add_option_dict} = require './argparse' {PackageJson} = require '../package' {E} = require '../err' {prompt_yn,Prompter} = require '../prompter' {checkers} = require '../checkers' {make_esc} = require 'iced-error' triplesec = require 'triplesec' {rng} = require 'crypto' {constants} = require '../constants' SC = constants.security req = require '../req' {env} = require '../env' read = require 'read' session = require '../session' {dict_union} = require '../util' ##======================================================================= exports.Command = class Command extends Base #---------- OPTS : e : aliases : [ 'email' ] help : 'the email address to signup' u : aliases : [ 'username' ] help : 'the username to signup as' #---------- use_session : () -> true #---------- add_subcommand_parser : (scp) -> opts = aliases : [ "signup" ] help : "establish a new account on keybase.io" name = "join" sub = scp.addParser name, opts opts.aliases.concat [ name ] #---------- prompt : (cb) -> seq = email : prompt : "Your email" checker : checkers.email invite: prompt : "Invitation code (leave blank if you don't have one)" thrower : (k,s) -> if (s.match /^\s*$/)? then (new E.CleanCancelError(k)) else null username : prompt : "Your desired username" checker : checkers.username passphrase: prompt: "Your login passphrase" passphrase: true checker: checkers.passphrase confirm : prompt: "Repeat to confirm" if not @prompter if (u = env().get_username())? then seq.username.defval = u if (p = env().get_passphrase())? then seq.passphrase.defval = p if (e = env().get_email())? then seq.email.defval = e @prompter = new Prompter seq await @prompter.run defer err @data = @prompter.data() unless err? cb err #---------- gen_pwh : (cb) -> passphrase = @data.passphrase if not(@pp_last) or (@pp_last isnt passphrase) await session.gen_pwh { passphrase }, defer err, @pwh, @salt, @pwh_version @pp_last = passphrase if not err? cb err #---------- post : (cb) -> args = salt : @salt.toString('hex') pwh : @pwh.toString('hex') username : @data.username email : @data.email invitation_id : @data.invite pwh_version : @pwh_version await req.post { endpoint : "signup", args }, defer err, body retry = false if err? and (err instanceof E.KeybaseError) switch body.status.name when 'BAD_SIGNUP_EMAIL_TAKEN' log.error "Email address '#{@data.email}' already registered" retry = true @prompter.clear 'email' err = null when 'BAD_SIGNUP_USERNAME_TAKEN' log.error "Username '#{@data.username}' already registered" retry = true @prompter.clear 'username' err = null when 'INPUT_ERROR' if err.fields.username log.error "Username '#{@data.username}' was rejected by the server" retry = true @prompter.clear 'username' err = null when 'BAD_INVITATION_CODE' log.error "Bad invitation code '#{@data.invite}' given" retry = true @prompter.clear 'invite' err = null if not err? @uid = body.uid session.set_id body.session session.set_csrf body.csrf_token else if not retry then log.error "Unexpected error: #{err}" cb err, retry #---------- write_out : (cb) -> esc = make_esc cb, "Join::write_out" await @write_config esc defer() await session.write esc defer() cb null #---------- write_config : (cb) -> c = env().config c.set "user.email", @data.email c.set "user.salt", @salt.toString('hex') c.set "user.name", @data.username c.set "user.id" , @uid await c.write defer err cb err #---------- check_registered : (cb) -> err = null if (env().config.get "user.id")? opts = prompt : "Already registered; do you want to reregister?" defval : false await prompt_yn opts, defer err, rereg if not err? and not rereg err = new E.CancelError "registration canceled" cb err #---------- request_invite : (cb) -> esc = make_esc cb, "request_invite" await @ri_prompt_for_ok esc defer() await @ri_prompt_for_data esc defer d2 await @ri_post_request d2, esc defer() cb null #---------- ri_prompt_for_ok : (cb) -> opts = prompt : "Would you like to be added to the invite list?" defval : true await prompt_yn opts, defer err, go if not err? and not go err = new E.CancelError "invitation request canceled" cb err #---------- ri_prompt_for_data : (cb) -> seq = full_name : prompt : "<NAME>" notes : prompt : "Any comments for the team" prompter = new Prompter seq await prompter.run defer err ret = null ret = prompter.data() unless err? cb err, ret #---------- ri_post_request : (d2, cb) -> args = dict_union d2, @prompter.data() await req.post {endpoint : "invitation_request", args }, defer err unless err? log.info "Success! You're on our list. Thanks for your interest!" cb err #---------- run : (cb) -> await @run2 defer err if err? and (err instanceof E.CleanCancelError) await @request_invite defer err cb err #---------- run2 : (cb) -> esc = make_esc cb, "Join::run" retry = true await @check_registered esc defer() while retry await @prompt esc defer() await @gen_pwh esc defer() await @post esc defer retry await @write_out esc defer() log.info "Success! You are now signed up." log.console.log """ Welcome to keybase.io! You now need to associate a public key with your account. If you have a key already then: keybase push <key-id> # if you know the ID of the key --- OR --- keybase push # to select from a menu If you need a public key, we'll happily generate one for you: keybase gen --push # Generate a new key and push public part to server Enjoy! """ cb null ##=======================================================================
true
{Base} = require './base' log = require '../log' {ArgumentParser} = require 'argparse' {add_option_dict} = require './argparse' {PackageJson} = require '../package' {E} = require '../err' {prompt_yn,Prompter} = require '../prompter' {checkers} = require '../checkers' {make_esc} = require 'iced-error' triplesec = require 'triplesec' {rng} = require 'crypto' {constants} = require '../constants' SC = constants.security req = require '../req' {env} = require '../env' read = require 'read' session = require '../session' {dict_union} = require '../util' ##======================================================================= exports.Command = class Command extends Base #---------- OPTS : e : aliases : [ 'email' ] help : 'the email address to signup' u : aliases : [ 'username' ] help : 'the username to signup as' #---------- use_session : () -> true #---------- add_subcommand_parser : (scp) -> opts = aliases : [ "signup" ] help : "establish a new account on keybase.io" name = "join" sub = scp.addParser name, opts opts.aliases.concat [ name ] #---------- prompt : (cb) -> seq = email : prompt : "Your email" checker : checkers.email invite: prompt : "Invitation code (leave blank if you don't have one)" thrower : (k,s) -> if (s.match /^\s*$/)? then (new E.CleanCancelError(k)) else null username : prompt : "Your desired username" checker : checkers.username passphrase: prompt: "Your login passphrase" passphrase: true checker: checkers.passphrase confirm : prompt: "Repeat to confirm" if not @prompter if (u = env().get_username())? then seq.username.defval = u if (p = env().get_passphrase())? then seq.passphrase.defval = p if (e = env().get_email())? then seq.email.defval = e @prompter = new Prompter seq await @prompter.run defer err @data = @prompter.data() unless err? cb err #---------- gen_pwh : (cb) -> passphrase = @data.passphrase if not(@pp_last) or (@pp_last isnt passphrase) await session.gen_pwh { passphrase }, defer err, @pwh, @salt, @pwh_version @pp_last = passphrase if not err? cb err #---------- post : (cb) -> args = salt : @salt.toString('hex') pwh : @pwh.toString('hex') username : @data.username email : @data.email invitation_id : @data.invite pwh_version : @pwh_version await req.post { endpoint : "signup", args }, defer err, body retry = false if err? and (err instanceof E.KeybaseError) switch body.status.name when 'BAD_SIGNUP_EMAIL_TAKEN' log.error "Email address '#{@data.email}' already registered" retry = true @prompter.clear 'email' err = null when 'BAD_SIGNUP_USERNAME_TAKEN' log.error "Username '#{@data.username}' already registered" retry = true @prompter.clear 'username' err = null when 'INPUT_ERROR' if err.fields.username log.error "Username '#{@data.username}' was rejected by the server" retry = true @prompter.clear 'username' err = null when 'BAD_INVITATION_CODE' log.error "Bad invitation code '#{@data.invite}' given" retry = true @prompter.clear 'invite' err = null if not err? @uid = body.uid session.set_id body.session session.set_csrf body.csrf_token else if not retry then log.error "Unexpected error: #{err}" cb err, retry #---------- write_out : (cb) -> esc = make_esc cb, "Join::write_out" await @write_config esc defer() await session.write esc defer() cb null #---------- write_config : (cb) -> c = env().config c.set "user.email", @data.email c.set "user.salt", @salt.toString('hex') c.set "user.name", @data.username c.set "user.id" , @uid await c.write defer err cb err #---------- check_registered : (cb) -> err = null if (env().config.get "user.id")? opts = prompt : "Already registered; do you want to reregister?" defval : false await prompt_yn opts, defer err, rereg if not err? and not rereg err = new E.CancelError "registration canceled" cb err #---------- request_invite : (cb) -> esc = make_esc cb, "request_invite" await @ri_prompt_for_ok esc defer() await @ri_prompt_for_data esc defer d2 await @ri_post_request d2, esc defer() cb null #---------- ri_prompt_for_ok : (cb) -> opts = prompt : "Would you like to be added to the invite list?" defval : true await prompt_yn opts, defer err, go if not err? and not go err = new E.CancelError "invitation request canceled" cb err #---------- ri_prompt_for_data : (cb) -> seq = full_name : prompt : "PI:NAME:<NAME>END_PI" notes : prompt : "Any comments for the team" prompter = new Prompter seq await prompter.run defer err ret = null ret = prompter.data() unless err? cb err, ret #---------- ri_post_request : (d2, cb) -> args = dict_union d2, @prompter.data() await req.post {endpoint : "invitation_request", args }, defer err unless err? log.info "Success! You're on our list. Thanks for your interest!" cb err #---------- run : (cb) -> await @run2 defer err if err? and (err instanceof E.CleanCancelError) await @request_invite defer err cb err #---------- run2 : (cb) -> esc = make_esc cb, "Join::run" retry = true await @check_registered esc defer() while retry await @prompt esc defer() await @gen_pwh esc defer() await @post esc defer retry await @write_out esc defer() log.info "Success! You are now signed up." log.console.log """ Welcome to keybase.io! You now need to associate a public key with your account. If you have a key already then: keybase push <key-id> # if you know the ID of the key --- OR --- keybase push # to select from a menu If you need a public key, we'll happily generate one for you: keybase gen --push # Generate a new key and push public part to server Enjoy! """ cb null ##=======================================================================
[ { "context": " getNode = (name,nodeType) ->\n key = \"#{name}-#{nodeType}\"\n if not nodes[key]\n nod", "end": 23330, "score": 0.9604167342185974, "start": 23309, "tag": "KEY", "value": "\"#{name}-#{nodeType}\"" } ]
packages/custom/transparency/coffee/public/controllers/flowController.coffee
AnotherCodeArtist/medien-transparenz.at
3
'use strict' app = angular.module 'mean.transparency' app.filter('searchFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "searchFilter"+item.name html = """<span class="label #{if item.groupType is 'public' then 'label-danger' else 'label-primary'}"> #{gettextCatalog.getString(item.groupType)}</span>#{item.name} <span class="close select-search-list-item_selection-remove">&times;</span>""" $sce.trustAsHtml(html) ]) app.filter('dropdownFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "dropdownFilter"+item.name html = """<span class="label #{if item.groupType is 'public' then 'label-danger' else 'label-primary'}"> #{gettextCatalog.getString(item.groupType)}</span>&nbsp;#{item.name}<span class="close select-search-list-item_selection-remove">&times;</span>""" ### if not item.region? html = '<span class="label label-primary">' + gettextCatalog.getString('custom') + '</span> ' + label else html = '<span class="label label-danger">' + gettextCatalog.getString('public') + '</span> ' + item.name ### $sce.trustAsHtml(html) ]) app.filter('groupFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "groupFilter"+item.name if typeof item.group is "undefined" or item.group is "" html = label + '<span class="close select-search-list-item_selection-remove">&times;</span>' else labelClass = "label-danger" if item.groupType is "custom" labelClass = "label-primary" html = '<span class="label ' + labelClass + '">' + item.group + '</span> ' + label + '<span class="close select-search-list-item_selection-remove">&times;</span>' $sce.trustAsHtml(html) ]) app.controller 'FlowCtrl',['$scope','TPAService','$q','$interval','$state','gettextCatalog', '$filter','DTOptionsBuilder','DTColumnBuilder', '$rootScope', '$timeout','$uibModal' ($scope,TPAService,$q,$interval,$state,gettextCatalog, $filter,DTOptionsBuilder,DTColumnBuilder,$rootScope, $timeout,$uibModal) -> #console.log "initialize dataPromise" dataPromise = $q.defer() forcedChange = false $scope.flowTab = true $scope.activeTab = 0 gettextCatalog.getString("custom") gettextCatalog.getString("public") stateName = "flowState" fieldsToStore = ['slider','periods','typesText', 'allOrganisations', 'allMedia', 'selectedOrganisationGroups', 'selectedMediaGroups', 'selectedOrganisations','selectedMedia', 'allOrganisationGroups','allMediaGroups','events','tags','regions'] $scope.init = 'init' typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]' $scope.mediaLabel = gettextCatalog.getString('Media') $scope.organisationLabel = gettextCatalog.getString('Organisation') $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') clearFields = -> $scope.selectedOrganisations = [] $scope.selectedMedia = [] $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] clearFields() $scope.selectedItemsWithoutGroups = (selected,groups) -> orgsInGroups = groups.reduce ((acc,val)->acc.concat(val.members)),[] selected.filter ((org)-> org.name not in orgsInGroups) $scope.selectedMediaWithoutGroups = -> mediaInGroups = $scope.selectedMediaGroups.reduce ((acc,val)->acc.concat(val.members)),[] $scope.selectedMedia.filter ((org)-> org.name not in mediaInGroups) $scope.groupMembersToHTML = (group) -> (group.members.reduce ((acc,val)->acc+"<li>"+val+"</li>"),"<ul>")+"</ul>" $scope.showTable = false # Method for setting the intro-options (e.g. after translations) setIntroOptions = -> $scope.IntroOptions = steps: [ { element: document.querySelector('#flowSettings') intro: gettextCatalog.getString 'It is possible to customize the pie chart. To do so, use the settings.' }, { element: document.querySelector('#flowSlider') intro: gettextCatalog.getString 'Move the sliders to define a range.' }, { element: document.querySelector('#fixSliderRange') intro: gettextCatalog.getString 'Fix slider range. With that it is possible to keep the range constant.' }, { element: document.querySelector('#paymentTypes') intro: gettextCatalog.getString 'Transfers are divided in different payment types. Select the types to display.' }, { element: document.querySelector('#multiselectOrg') intro: gettextCatalog.getString 'You can add organisations to the flow. Go into detail by clicking on the rectangular box.' }, { element: document.querySelector('#multiselectMedia') intro: gettextCatalog.getString 'You can add media to the flow too. Click on the rectangular box for details.' }, { element: document.querySelector('#multiselectOrgGroup') intro: gettextCatalog.getString 'It is possible to select predefined groups for organisations. The entries of the group will be loaded and displayed automatically.' }, { element: document.querySelector('#multiselectMediaGroup') intro: gettextCatalog.getString 'It is possible to select predefined groups for media. The entries of the group will be loaded and displayed automatically.' }, { element: document.querySelector('#customGroups') intro: gettextCatalog.getString 'Based on your selection, you can create custom groups for all non-grouped organisations or media.' }, { element: document.querySelector('#sankeyRow') intro: gettextCatalog.getString 'Per default the top spender based on your chosen payment types and period is selected.' }, { element: document.querySelector('#sankeyRow') intro: gettextCatalog.getString 'To discover the flow in detail just click on the flow between an organisation and a media entry.' } ] showStepNumbers: false exitOnOverlayClick: true exitOnEsc: true nextLabel: gettextCatalog.getString 'Next info' prevLabel: gettextCatalog.getString 'Previous info' skipLabel: gettextCatalog.getString 'Skip info' doneLabel: gettextCatalog.getString 'End tour' $scope.timelineOpened = -> $scope.flowTab = false $timeout((-> $rootScope.$broadcast "updateTimeline"), 100) $scope.flowOpened = -> $scope.flowTab = true $timeout((-> $rootScope.$broadcast "updateFlow"), 100) if $scope.slider current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 90 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 95 startLoading = -> try $interval.cancel timer if timer isnt null catch error $scope.loading = true $scope.progress = 20 stopLoading = -> $scope.loading = false $scope.transferTypeLabel = gettextCatalog.getString('Payment Type') $scope.amountLabel = gettextCatalog.getString('Amount') $scope.maxNodes = 800 $scope.maxExceeded = 0 $scope.data = {} $scope.filter ='' $scope.loading = true $scope.progress = 20 $scope.showSettings = false $scope.selectionSettings = false #$scope.org = null $scope.isDetails = false window.scrollTo 0, 0 $scope.clearDetails = -> #$scope.org = null update() timer = null makeProgress = -> $scope.progress = ($scope.progress + 10) % 101 console.log "Progress: " + $scope.progress flowData = [] nodeMap = {} initSlider = -> if not $scope.slider? then $scope.slider = {} $scope.slider.options = ceil: ($scope.periods.length - 1)*5 step:5 floor:0 onEnd: -> change(1,2) translate: (value) -> $scope.periods.map((p) -> "#{p.year}/Q#{p.quarter}")[value/5] draggableRangeOnly: false $scope.slider.from = ($scope.periods.length - 1)*5 if (not $scope.slider.from?) or isNaN($scope.slider.from) $scope.slider.to = ($scope.periods.length - 1)*5 if not $scope.slider.to? if not $scope.fixedRange? then $scope.fixedRange = false #Load all available periods loadPeriods = () => deferred = $q.defer() TPAService.periods() .then (res) -> $scope.periods = res.data.reverse() initSlider() deferred.resolve() deferred.promise #(Pre-)load all organisation and media names loadAllNames = () -> deferred = $q.defer(); TPAService.search({name: ' '}) .then (res) -> $scope.mediaLabel = gettextCatalog.getString('Media') $scope.organisationLabel = gettextCatalog.getString('Organisation') $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') if typeof $scope.allOrganisations is 'undefined' or $scope.allOrganisations.length is 0 $scope.allOrganisations = res.data.org.map (o) -> { name: o.name, } if typeof $scope.allMedia is 'undefined' or $scope.allMedia.length is 0 $scope.allMedia = res.data.media.map (m) -> { name: m.name, } deferred.resolve() deferred.promise loadEvents = () -> deferred = $q.defer(); TPAService.getEvents().then (res)-> $scope.events = res.data.map((event) -> event.selected=true;event) $scope.regions = [] addedregions = [] for event in $scope.events #event.selected = true; if addedregions.indexOf(event.region) is -1 $scope.regions.push { name: event.region selected: true } addedregions.push event.region deferred.resolve(res) deferred loadEventTags = () -> deferred = $q.defer(); TPAService.getEventTags().then (res) -> $scope.tags = res.data.map((tag)-> {name: tag, selected:true} ) deferred.resolve(res) deferred $scope.updateEvents = () -> $scope.$broadcast 'updateEvents' types = [2,4,31] $scope.typesText = (type:type,text: gettextCatalog.getString(TPAService.decodeType(type)),checked:false for type in types) $scope.typesText[0].checked = true $scope.flows = nodes: [] links: [] $scope.mediaLabel = gettextCatalog.getString 'Media' $scope.organisationsLabel = gettextCatalog.getString 'Organisations' $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') parameters = -> params = {} params.maxLength = $scope.maxNodes params.from = $scope.periods[$scope.slider.from/5].period (params.to = $scope.periods[$scope.slider.to/5].period) if $scope.periods types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 (params.filter = $scope.filter) if $scope.filter.length >= 3 if $scope.selectedMedia and $scope.selectedMedia.length > 0 params.media = $scope.selectedMedia.map (media) -> media.name if $scope.selectedOrganisations and $scope.selectedOrganisations.length > 0 params.organisations = $scope.selectedOrganisations.map (org) -> org.name params parametersTimeline = -> params = {} params.source = $scope.selectedOrganisations.map (org) -> org.name params.target = $scope.selectedMedia.map (media) -> media.name types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 params # init the introOptions and call the method $scope.IntroOptions = null; setIntroOptions() toArray = (value) -> if typeof value is 'string' value.split ',' else value compareWith = (param) -> (value) -> if typeIsArray param then normalizeGrpName(value) in param else normalizeGrpName(value) is param #check for parameters in the URL so that this view can be bookmarked checkForStateParams = -> $scope.slider.from = $scope.periods.map((p) -> p.period).indexOf(parseInt $state.params.from)*5 if $state.params.from $scope.slider.to = $scope.periods.map((p) -> p.period).indexOf(parseInt $state.params.to)*5 if $state.params.to $scope.flowTab = ($state.params.flow || "true") is "true" $scope.activeTab = if $scope.flowTab then 0 else 1 if $state.params.media? $scope.selectedMedia = $scope.allMedia.filter(compareWith($state.params.media)) if $state.params.organisations? $scope.selectedOrganisations = $scope.allOrganisations.filter(compareWith($state.params.organisations)) if $state.params.orgGrp? $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter(compareWith($state.params.orgGrp)) members = $scope.selectedOrganisationGroups.map((g)->g.members.map((m)->{name:m,group:g.name,groupType:if g.serverside then 'public' else 'custom'})).reduce(((a,b)->a.concat(b)),[]) memberNames = members.map((o)->o.name) $scope.selectedOrganisations = $scope.selectedOrganisations.filter((o)->o.name not in memberNames) .concat(members) if $state.params.mediaGrp? $scope.selectedMediaGroups = $scope.allMediaGroups.filter(compareWith($state.params.mediaGrp)) members = $scope.selectedMediaGroups.map((g)->g.members.map((m)->{name:m,group:g.name,groupType:if g.serverside then 'public' else 'custom'})).reduce(((a,b)->a.concat(b)),[]) memberNames = members.map((o)->o.name) $scope.selectedMedia = $scope.selectedMedia.filter((o)->o.name not in memberNames) .concat(members) if $state.params.pTypes? pTypes = toArray($state.params.pTypes).map (v) -> parseInt v t.checked = t.type in pTypes for t in $scope.typesText #$scope.org = {} if $state.params.name or $state.params.orgType if $state.params.name if $state.params.orgType is 'org' $scope.selectedOrganisations = [{name: $state.params.name}] else if $state.params.orgType is 'media' $scope.selectedMedia = [{name: $state.params.name}] # Load grouping else if $state.params.grouping # Load grouping by name mediaGroup = $scope.allMediaGroups.filter((g)->g.name is $state.params.grouping) orgGroup = $scope.allOrganisationGroups.filter((g)->g.name is $state.params.grouping) if mediaGroup.length > 0 $scope.selectedMediaGroup = mediaGroup[0] $scope.selectedMedia = mediaGroup.members.map((m) -> m.name) else if orgGroup.length > 0 $scope.selectedOrganisations = orgGroup.members.map((m) -> m.name) $scope.selectedOrganionsationGroups = orgGroup[0] translate = -> $scope.typesText.forEach (t) -> t.text = gettextCatalog.getString TPAService.decodeType t.type $scope.mediaLabel = gettextCatalog.getString 'Media' $scope.organisationsLabel = gettextCatalog.getString 'Organisations' $scope.organisationGroupLabel = gettextCatalog.getString 'Organisation Group' $scope.mediaGroupLabel = gettextCatalog.getString 'Media Group' setIntroOptions() $scope.$on 'gettextLanguageChanged', translate #Updates the browser's address bar without causing the controller to be reloaded #this allows to bookmark the page in every state updateURL = (reload = false)-> $state.transitionTo('showflow',{ from: $scope.periods[$scope.slider.from/5].period to: $scope.periods[$scope.slider.to/5].period media: $scope.selectedMedia.map((m)->m.name) organisations: $scope.selectedOrganisations.map((o)->o.name) mediaGrp: $scope.selectedMediaGroups.map(normalizeGrpName) orgGrp: $scope.selectedOrganisationGroups.map(normalizeGrpName) pTypes: (v.type for v in $scope.typesText when v.checked) flow: $scope.flowTab },{notify:reload, reload: reload}) $scope.showDetails = (node) -> selectionTypes = o: 'org' m: 'media' mg: 'mediaGrp' og: 'orgGrp' $scope.isDetails = true; $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] $scope.selectedMedia = [] $scope.selectedOrganisations = [] switch node.type when 'o' $scope.selectedOrganisations = [{name: node.name}] when 'm' $scope.selectedMedia = [{name: node.name}] when 'og' $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter((g)->g.name is node.name) $scope.selectedOrganisations = $scope.selectedOrganisationGroups .map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) when 'mg' $scope.selectedMediaGroups = $scope.allMediaGroups.filter((g)->g.name is node.name) $scope.selectedMedia = $scope.selectedMediaGroups .map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) updateURL(true) window.scrollTo 0,0 $scope.flowTab = true $scope.showFlowDetails = (link) -> $scope.isDetails = true; $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] $scope.selectedMedia = [] $scope.selectedOrganisations = [] switch link.source.type when 'o' $scope.selectedOrganisations = [name: link.source.name] when 'og' $scope.selectedOrganisations = link.source.targetLinks.map (l)->{name: l.source.name} $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter((g)->g.name is link.source.name) switch link.target.type when 'mg' $scope.selectedMedia = link.target.sourceLinks.map (l)->{name: l.target.name} $scope.selectedMediaGroups = $scope.allMediaGroups.filter((g)->g.name is link.target.name) when 'm' $scope.selectedMedia = [name: link.target.name] $scope.flowTab = false updateURL(true) window.scrollTo 0,0 filterData = (data) -> if $scope.filter.trim().length > 2 r = new RegExp ".*#{$scope.filter}.*","i" data.filter (d) -> r.test(d.organisation) or r.test(d.media) else data $scope.editLocalGroups = () -> $state.go('groupingLocal') $rootScope.$on('groupsChanged', -> loadGroups()) loadFlowData = -> TPAService.filteredflows(parameters()) .then (res) -> stopLoading() #console.log "Got result from Server: " + Date.now() $scope.error = null flowData = res.data for flowDatum in flowData if flowDatum.organisation is 'Other organisations' flowDatum.organisation = gettextCatalog.getString flowDatum.organisation flowDatum.otherOrgs = "oo" if flowDatum.media is 'Other media' flowDatum.media = gettextCatalog.getString flowDatum.media flowDatum.otherMedia = "om" $scope.flowData = flowData if dataPromise.promise.$$state.status == 1 dataPromise = $q.defer() if $scope.dtInstance.reloadData $scope.dtInstance.reloadData() dataPromise.resolve() $scope.flows = buildNodes filterData flowData #checkMaxLength(data) .catch (res) -> stopLoading() $scope.flowData = [] $scope.flows = nodes:[],links:[] $scope.error = res.data #console.log "resolve dataPromise after exception" dataPromise.resolve() loadTimeLineDataAbsolute = -> deferred = $q.defer() TPAService.flowdetail(parametersTimeline()) .then (res) -> $scope.data = res.data loadTimeLineDataRelative = -> TPAService.annualcomparison parametersTimeline() .then (res) -> $scope.annualComparisonData = res.data update = -> if (!$scope.selectedOrganisations or $scope.selectedOrganisations.length is 0) and (!$scope.selectedMedia or $scope.selectedMedia.length is 0) and !$state.params.grouping and $scope.init is 'init' $scope.init = 'preselected' TPAService.top parameters() .then (res) -> $scope.selectedOrganisations = [{name: res.data.top[0].organisation}] return #console.log "Starting update: " + Date.now() startLoading() if ($scope.selectedOrganisations and $scope.selectedOrganisations.length > 0) or ($scope.selectedMedia and $scope.selectedMedia.length > 0) $q.all([loadFlowData(),loadTimeLineDataAbsolute(),loadTimeLineDataRelative()]) .then stopLoading else stopLoading() $scope.error = "nothing selected" checkMaxLength = (data) -> ###if data.nodes.length > $scope.maxNodes $scope.maxExceeded = data.nodes.length $scope.flows = {} else ### $scope.maxExceeded = 0 $scope.flows = data createLink = (source, target, value, type) -> { source: source target: target value: value type: type } buildNodes = (data) -> nodes = {} links = [] sum = 0 getNode = (name,nodeType) -> key = "#{name}-#{nodeType}" if not nodes[key] nodes[key] = {name: name, type: nodeType, index: Object.keys(nodes).length} nodes[key] addLink = (source,target,transfer) -> link = links.filter( (l)-> l.source is source.index and l.target is target.index) if link.length > 0 link[0].value+= transfer.amount link[0].details[transfer.transferType]+=transfer.amount else newLink = source: source.index target: target.index value: transfer.amount, details: 2:0 4:0 31:0 if source.type in ["oo","om"] or target.type in ["oo","om"] newLink.linkType = "others" newLink.details[transfer.transferType]+=transfer.amount links.push(newLink) data.forEach (entry) -> sum+=entry.amount org = getNode(entry.organisation, entry.otherOrgs or "o") media = getNode(entry.media, entry.otherMedia or "m") orgGroups = $scope.selectedOrganisationGroups.filter((v)->org.name in v.members) mediaGroups = $scope.selectedMediaGroups.filter((v)->media.name in v.members) orgGroup = if orgGroups.length > 0 then getNode(orgGroups[0].name,"og") mediaGroup = if mediaGroups.length > 0 then getNode(mediaGroups[0].name,"mg") if orgGroup then addLink(org,orgGroup,entry) if mediaGroup then addLink(mediaGroup,media,entry) if orgGroup and mediaGroup then addLink(orgGroup,mediaGroup,entry) else if orgGroup then addLink(orgGroup,media,entry) else if mediaGroup then addLink(org,mediaGroup,entry) else addLink(org,media,entry) nodes = Object.keys(nodes).map((k)->nodes[k]) links.forEach (l) -> l.type = Object.keys(l.details).filter((k)->l.details[k]>0).reduce(((a,b)->a+b),"") {nodes: nodes,links: links, sum: sum} $scope.dtOptions = {} $scope.dtOptions = DTOptionsBuilder.fromFnPromise( -> defer = $q.defer() dataPromise.promise.then (result) -> defer.resolve($scope.flowData); defer.promise ) .withPaginationType('full_numbers') .withButtons(['copy','csv','excel']) .withBootstrap() angular.extend $scope.dtOptions, language: paginate: previous: gettextCatalog.getString('previous') next: gettextCatalog.getString('next') first: gettextCatalog.getString('first') last: gettextCatalog.getString('last') search: gettextCatalog.getString('search') info: gettextCatalog.getString('Showing page _PAGE_ of _PAGES_') lengthMenu: gettextCatalog.getString "Display _MENU_ records" getExplanation = (paymentType) -> switch paymentType when 2 then gettextCatalog.getString('§2 MedKF-TG (Media Cooperations)') when 4 then gettextCatalog.getString('§4 MedKF-TG (Funding)') when 31 then gettextCatalog.getString('§31 ORF-G (Charges)') $scope.dtColumns = [ DTColumnBuilder.newColumn('organisation').withTitle(gettextCatalog.getString('Payer')) DTColumnBuilder.newColumn('media').withTitle(gettextCatalog.getString('Recipient')), DTColumnBuilder.newColumn('transferType').withTitle(gettextCatalog.getString('Type')) .renderWith((paragraph,type)-> if type is 'display' getExplanation(paragraph) else paragraph ) DTColumnBuilder.newColumn('amount').withTitle(gettextCatalog.getString('Amount')) .renderWith((amount,type) -> if type is 'display' amount.toLocaleString($rootScope.language,{currency: "EUR", maximumFractionDigits:2,minimumFractionDigits:2}) else amount) .withClass('text-right') ] $scope.dtInstance = {} change = (oldValue,newValue) -> #console.log "Change: " + Date.now() if (oldValue isnt newValue) if $scope.dtInstance.reloadData dataPromise = $q.defer() $scope.dtInstance.reloadData() updateURL() update() $rootScope.$on '$stateChangeStart', (event, toState)-> if toState.name isnt 'home' TPAService.saveState stateName,fieldsToStore, $scope loadGroups = () -> orgGroupsPromise = TPAService.getGroupings {type: 'org'} orgGroupsPromise.then (res, err) -> if (err) console.error err return $scope.allOrganisationGroups = res.data.map((g)->g.groupType='public';g) .concat(TPAService.getLocalGroups("org").map((g)->g.groupType='custom';g)) mediaGroupsPromise = TPAService.getGroupings {type: 'media'} mediaGroupsPromise.then (res, err) -> if (err) console.error err return $scope.allMediaGroups = res.data.map((g)->g.groupType='public';g) .concat(TPAService.getLocalGroups("media").map((g)->g.groupType='custom';g)) $q.all([orgGroupsPromise,mediaGroupsPromise]) #start initialization savedState = sessionStorage.getItem stateName stateParamsExist = () -> if $state.params for k,v of $state.params if typeof v isnt 'undefined' return true return false #Lazy loading of media for multi selection box mediaList = [] $scope.loadMedia = (name) -> if name.length >= 3 if mediaList.length == 0 mediaList = $scope.allMedia.filter((m)-> m.name.toLowerCase().indexOf(name.toLowerCase()) > -1) else mediaList = [] mediaList organisationList = [] #Lazy loading of organisation for multi selection box $scope.loadOrganisations = (name) -> if name.length >= 3 if organisationList.length == 0 organisationList = $scope.allOrganisations.filter((m)-> m.name.toLowerCase().indexOf(name.toLowerCase()) > -1) else organisationList = [] organisationList #Initialize form data either by loading a saved state or by fetching data from the server initialize = -> deferred = $q.defer() if savedState TPAService.restoreState stateName, fieldsToStore, $scope $scope.allOrganisations.forEach((o)->o.group="";o.groupType="") $scope.allMedia.forEach((o)->o.group="";o.groupType="") initSlider() stopLoading() deferred.resolve() else startLoading() $q.all([loadPeriods(),loadAllNames(),loadGroups(),loadEvents(),loadEventTags()]) .then () -> stopLoading() if not stateParamsExist() #no defined state so start loading default data update() deferred.resolve() deferred.promise $scope.toggleRegion = (region) -> for event in $scope.events if event.region is region.name event.selected = region.selected $scope.updateEvents() $scope.toggleTag = (tag) -> for event in $scope.events if event.tags.indexOf(tag.name) isnt -1 event.selected = tag.selected $scope.selectedTypes = -> $scope.typesText.filter((t) -> t.checked).map (t) -> t.type $scope.getFrom = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.from/5].quarter}/#{$scope.periods[$scope.slider.from/5].year}" else "" $scope.getTo = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.to/5].quarter}/#{$scope.periods[$scope.slider.to/5].year}" else "" initialize() .then -> if stateParamsExist() clearFields() checkForStateParams() update() $scope.showSelectPayers = -> showSelectDialog(properties.org) $scope.showSelectBeneficiaries = -> showSelectDialog(properties.media) showSelectDialog = (config) -> parent = $scope $uibModal.open( #template: selectOrgText templateUrl: 'transparency/views/selectItemsDialog.html' scope: $scope controller: ($scope, $uibModalInstance) -> $scope.close = -> config.setSelectedGroups $scope.selectedGroupsLocal $uibModalInstance.close() updateItems = (newvalue,oldvalue) -> return if oldvalue is newvalue if newvalue.length > oldvalue.length selected = config.selected() selected.push(newvalue[newvalue.length-1]) config.setSelected(selected) else newNames = newvalue.map (v)->v.name removedItems = oldvalue.filter((v)-> v.name not in newNames).map((v)->v.name) config.setSelected(config.selected().filter ((v)-> v.name not in removedItems)) $scope.createGroup = -> group = config.createLocalGroup()($scope.localGroupName) if group $scope.selectedGroupsLocal.push(group) $uibModalInstance.close() $scope.localGroups = config.allGroups().filter (v)->v.groupType is 'custom' $scope.allGroups = config.allGroups() $scope.items = config.items() $scope.labels = config.labels $scope.selectedGroupsLocal = config.selectedGroups() $scope.selectedLocal = parent.selectedItemsWithoutGroups(config.selected(),config.selectedGroups()) $scope.$watch 'selectedLocal', updateItems, true $scope.addGroup = true size: 'lg' ) $scope.showSettingsDialog = -> parent = $scope $uibModal.open( templateUrl: 'transparency/views/flowSettingsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 100 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 120 ) $scope.showEventSelectionDialog = -> $uibModal.open( templateUrl: 'transparency/views/selectEventsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ) showDialog = (text) -> $uibModal.open( { template: """ <div class="source-list-modal"> <div class="modal-header"> <h3 class="modal-title"> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;Info </h3> </div> <div class="modal-body"> <p>#{text}</p> </div> <div class="modal-footer"> <div class="controls"> <button class="btn btn-primary" type="button" ng-click="close()">OK</button> </div> </div> </div> """ controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() size: 'sm' }) selectionChanged = (config) -> (newValue, oldValue) -> return if newValue is oldValue if newValue.length < oldValue.length removedElement = oldValue.filter((o) -> o.name not in newValue.map((v)->v.name))[0] if removedElement.name in config.selectedGroups().map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) config.setSelected(oldValue) showDialog config.removeMsg return if not $scope.isDetails updateURL() update() $scope.isDetails = false; #Since it is possible to have local and public groups with the same name #we need to be able to distinguish them normalizeGrpName = (v)->"#{if v.serverside then "S:" else ""}#{v.name}" handleRemovingGroup = (config) -> (newValue,oldValue) -> return if newValue is oldValue remainingGroupNames = newValue.map(normalizeGrpName) removedGroup = oldValue.filter((v)->normalizeGrpName(v) not in remainingGroupNames)[0] config.selected().filter((v)->v.name in removedGroup.members) .forEach((v)->v.group="";v.groupType="") config.setSelected(config.selected().filter((v)-> v.name not in removedGroup.members )) #TODO remove if refactored everywhere $scope.organisationsInSelectedGroups = $scope.selectedOrganisationGroups.map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) #config access to properties properties = org: labels: item: "Please select your Payers" title: "Select Payers" all: ()->$scope.allOrganisations allGroups: ()->$scope.allOrganisationGroups selected: ()->$scope.selectedOrganisations selectedGroups: ()->$scope.selectedOrganisationGroups setSelected: (s) -> $scope.selectedOrganisations = s setSelectedGroups: (s) -> $scope.selectedOrganisationGroups = s localGroupName: () -> $scope.localOrgGroupName setLocalGroupName: (s)->$scope.localOrgGroupName=s type:'org' createLocalGroup: -> $scope.createLocalOrgGroup items: -> $scope.loadOrganisations removeMsg: gettextCatalog.getString "You cannot remove this Organisation since it belongs to a selected group. Remove the group instead." media: labels: item: "Please select your Beneficiaries" title: "Select Beneficiaries" all: ()->$scope.allMedia allGroups: ()->$scope.allMediaGroups selected: ()->$scope.selectedMedia selectedGroups: ()->$scope.selectedMediaGroups setSelected: (s) -> $scope.selectedMedia = s setSelectedGroups: (s) -> $scope.selectedMediaGroups = s localGroupName: ()-> $scope.localMediaGroupName setLocalGroupName: (s)->$scope.localMediaGroupName=s type:'media' createLocalGroup: -> $scope.createLocalMediaGroup items: -> $scope.loadMedia removeMsg: gettextCatalog.getString "You cannot remove this Media since it belongs to a selected group. Remove the group instead" handleAddingGroup = (config) -> (newValue, oldValue) -> selectedMembers = oldValue.map((v)->v.members).reduce(((a,b)->a.concat(b)),[]) oldGroupNames = oldValue.map(normalizeGrpName) newGroup = newValue.filter((v)->normalizeGrpName(v) not in oldGroupNames)[0] if newGroup.members.filter((v)->v in selectedMembers).length > 0 showDialog gettextCatalog.getString """ You cannot add this group, since some of its members are also members of already selected groups. This is not allowed. So please remove the other group first """ config.setSelectedGroups(oldValue) forcedChange = true return membersToAdd = newGroup.members .map((m)->{name:m,group:newGroup.name,groupType:if newGroup.serverside then 'public' else 'custom'}) membersOutsideNewGroup = config.selected().filter((v)->v.name not in newGroup.members) config.setSelected(membersOutsideNewGroup.concat(membersToAdd)) selectedGroupsChanged = (config) -> (newValue, oldValue) -> return if newValue is oldValue if forcedChange forcedChange = false return newLength = if (typeof newValue isnt 'undefined') then newValue.length else 0 oldLength = if (typeof oldValue isnt 'undefined') then oldValue.length else 0 if newLength < oldLength handleRemovingGroup(config)(newValue, oldValue) else handleAddingGroup(config)(newValue, oldValue) createLocalGroup = (config) -> (name) -> localGroupName = name || config.localGroupName if localGroupName in TPAService.getLocalGroups(config.type).map((g)->g.name) showDialog gettextCatalog.getString "Custom group could not be created since an local group with an equal name already exists" return null groupedOrganisations = config.selectedGroups().map((g)->g.members).reduce(((a,b)->a.concat(b)),[]) newMembers = config.selected().filter((o)->o.name not in groupedOrganisations) if newMembers.length is 0 showDialog gettextCatalog.getString "Custom group could not be created because there are no ungrouped entries." return null group = { type: config.type members: newMembers.map((m)->m.name) name: localGroupName region: 'AT' } TPAService.saveLocalGroup group group.groupType = 'custom' config.allGroups().push group config.setSelectedGroups(config.selectedGroups().concat [group]) newMembers.forEach((m)->m.group=group.name;m.groupType='custom') TPAService.saveState stateName,fieldsToStore, $scope config.setLocalGroupName("") group $scope.barClicked = (src) -> quarter = $scope.periods.map((v)->"#{v.year}/Q#{v.quarter}").indexOf(src.label) $scope.slider.to = quarter*5 $scope.slider.from = quarter*5 $scope.flowTab = true updateURL(true) $scope.createLocalOrgGroup = createLocalGroup(properties.org) $scope.createLocalMediaGroup = createLocalGroup(properties.media) $scope.organisationsInSelectedGroups = [] $scope.mediaInSelectedGroups = [] $scope.$watch 'selectedOrganisationGroups', selectedGroupsChanged(properties.org), true $scope.$watch 'selectedMediaGroups', selectedGroupsChanged(properties.media), true $scope.$watch 'selectedMedia', selectionChanged(properties.media), true $scope.$watch 'selectedOrganisations', selectionChanged(properties.org), true $scope.$watch('typesText',change,true) ]
74975
'use strict' app = angular.module 'mean.transparency' app.filter('searchFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "searchFilter"+item.name html = """<span class="label #{if item.groupType is 'public' then 'label-danger' else 'label-primary'}"> #{gettextCatalog.getString(item.groupType)}</span>#{item.name} <span class="close select-search-list-item_selection-remove">&times;</span>""" $sce.trustAsHtml(html) ]) app.filter('dropdownFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "dropdownFilter"+item.name html = """<span class="label #{if item.groupType is 'public' then 'label-danger' else 'label-primary'}"> #{gettextCatalog.getString(item.groupType)}</span>&nbsp;#{item.name}<span class="close select-search-list-item_selection-remove">&times;</span>""" ### if not item.region? html = '<span class="label label-primary">' + gettextCatalog.getString('custom') + '</span> ' + label else html = '<span class="label label-danger">' + gettextCatalog.getString('public') + '</span> ' + item.name ### $sce.trustAsHtml(html) ]) app.filter('groupFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "groupFilter"+item.name if typeof item.group is "undefined" or item.group is "" html = label + '<span class="close select-search-list-item_selection-remove">&times;</span>' else labelClass = "label-danger" if item.groupType is "custom" labelClass = "label-primary" html = '<span class="label ' + labelClass + '">' + item.group + '</span> ' + label + '<span class="close select-search-list-item_selection-remove">&times;</span>' $sce.trustAsHtml(html) ]) app.controller 'FlowCtrl',['$scope','TPAService','$q','$interval','$state','gettextCatalog', '$filter','DTOptionsBuilder','DTColumnBuilder', '$rootScope', '$timeout','$uibModal' ($scope,TPAService,$q,$interval,$state,gettextCatalog, $filter,DTOptionsBuilder,DTColumnBuilder,$rootScope, $timeout,$uibModal) -> #console.log "initialize dataPromise" dataPromise = $q.defer() forcedChange = false $scope.flowTab = true $scope.activeTab = 0 gettextCatalog.getString("custom") gettextCatalog.getString("public") stateName = "flowState" fieldsToStore = ['slider','periods','typesText', 'allOrganisations', 'allMedia', 'selectedOrganisationGroups', 'selectedMediaGroups', 'selectedOrganisations','selectedMedia', 'allOrganisationGroups','allMediaGroups','events','tags','regions'] $scope.init = 'init' typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]' $scope.mediaLabel = gettextCatalog.getString('Media') $scope.organisationLabel = gettextCatalog.getString('Organisation') $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') clearFields = -> $scope.selectedOrganisations = [] $scope.selectedMedia = [] $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] clearFields() $scope.selectedItemsWithoutGroups = (selected,groups) -> orgsInGroups = groups.reduce ((acc,val)->acc.concat(val.members)),[] selected.filter ((org)-> org.name not in orgsInGroups) $scope.selectedMediaWithoutGroups = -> mediaInGroups = $scope.selectedMediaGroups.reduce ((acc,val)->acc.concat(val.members)),[] $scope.selectedMedia.filter ((org)-> org.name not in mediaInGroups) $scope.groupMembersToHTML = (group) -> (group.members.reduce ((acc,val)->acc+"<li>"+val+"</li>"),"<ul>")+"</ul>" $scope.showTable = false # Method for setting the intro-options (e.g. after translations) setIntroOptions = -> $scope.IntroOptions = steps: [ { element: document.querySelector('#flowSettings') intro: gettextCatalog.getString 'It is possible to customize the pie chart. To do so, use the settings.' }, { element: document.querySelector('#flowSlider') intro: gettextCatalog.getString 'Move the sliders to define a range.' }, { element: document.querySelector('#fixSliderRange') intro: gettextCatalog.getString 'Fix slider range. With that it is possible to keep the range constant.' }, { element: document.querySelector('#paymentTypes') intro: gettextCatalog.getString 'Transfers are divided in different payment types. Select the types to display.' }, { element: document.querySelector('#multiselectOrg') intro: gettextCatalog.getString 'You can add organisations to the flow. Go into detail by clicking on the rectangular box.' }, { element: document.querySelector('#multiselectMedia') intro: gettextCatalog.getString 'You can add media to the flow too. Click on the rectangular box for details.' }, { element: document.querySelector('#multiselectOrgGroup') intro: gettextCatalog.getString 'It is possible to select predefined groups for organisations. The entries of the group will be loaded and displayed automatically.' }, { element: document.querySelector('#multiselectMediaGroup') intro: gettextCatalog.getString 'It is possible to select predefined groups for media. The entries of the group will be loaded and displayed automatically.' }, { element: document.querySelector('#customGroups') intro: gettextCatalog.getString 'Based on your selection, you can create custom groups for all non-grouped organisations or media.' }, { element: document.querySelector('#sankeyRow') intro: gettextCatalog.getString 'Per default the top spender based on your chosen payment types and period is selected.' }, { element: document.querySelector('#sankeyRow') intro: gettextCatalog.getString 'To discover the flow in detail just click on the flow between an organisation and a media entry.' } ] showStepNumbers: false exitOnOverlayClick: true exitOnEsc: true nextLabel: gettextCatalog.getString 'Next info' prevLabel: gettextCatalog.getString 'Previous info' skipLabel: gettextCatalog.getString 'Skip info' doneLabel: gettextCatalog.getString 'End tour' $scope.timelineOpened = -> $scope.flowTab = false $timeout((-> $rootScope.$broadcast "updateTimeline"), 100) $scope.flowOpened = -> $scope.flowTab = true $timeout((-> $rootScope.$broadcast "updateFlow"), 100) if $scope.slider current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 90 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 95 startLoading = -> try $interval.cancel timer if timer isnt null catch error $scope.loading = true $scope.progress = 20 stopLoading = -> $scope.loading = false $scope.transferTypeLabel = gettextCatalog.getString('Payment Type') $scope.amountLabel = gettextCatalog.getString('Amount') $scope.maxNodes = 800 $scope.maxExceeded = 0 $scope.data = {} $scope.filter ='' $scope.loading = true $scope.progress = 20 $scope.showSettings = false $scope.selectionSettings = false #$scope.org = null $scope.isDetails = false window.scrollTo 0, 0 $scope.clearDetails = -> #$scope.org = null update() timer = null makeProgress = -> $scope.progress = ($scope.progress + 10) % 101 console.log "Progress: " + $scope.progress flowData = [] nodeMap = {} initSlider = -> if not $scope.slider? then $scope.slider = {} $scope.slider.options = ceil: ($scope.periods.length - 1)*5 step:5 floor:0 onEnd: -> change(1,2) translate: (value) -> $scope.periods.map((p) -> "#{p.year}/Q#{p.quarter}")[value/5] draggableRangeOnly: false $scope.slider.from = ($scope.periods.length - 1)*5 if (not $scope.slider.from?) or isNaN($scope.slider.from) $scope.slider.to = ($scope.periods.length - 1)*5 if not $scope.slider.to? if not $scope.fixedRange? then $scope.fixedRange = false #Load all available periods loadPeriods = () => deferred = $q.defer() TPAService.periods() .then (res) -> $scope.periods = res.data.reverse() initSlider() deferred.resolve() deferred.promise #(Pre-)load all organisation and media names loadAllNames = () -> deferred = $q.defer(); TPAService.search({name: ' '}) .then (res) -> $scope.mediaLabel = gettextCatalog.getString('Media') $scope.organisationLabel = gettextCatalog.getString('Organisation') $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') if typeof $scope.allOrganisations is 'undefined' or $scope.allOrganisations.length is 0 $scope.allOrganisations = res.data.org.map (o) -> { name: o.name, } if typeof $scope.allMedia is 'undefined' or $scope.allMedia.length is 0 $scope.allMedia = res.data.media.map (m) -> { name: m.name, } deferred.resolve() deferred.promise loadEvents = () -> deferred = $q.defer(); TPAService.getEvents().then (res)-> $scope.events = res.data.map((event) -> event.selected=true;event) $scope.regions = [] addedregions = [] for event in $scope.events #event.selected = true; if addedregions.indexOf(event.region) is -1 $scope.regions.push { name: event.region selected: true } addedregions.push event.region deferred.resolve(res) deferred loadEventTags = () -> deferred = $q.defer(); TPAService.getEventTags().then (res) -> $scope.tags = res.data.map((tag)-> {name: tag, selected:true} ) deferred.resolve(res) deferred $scope.updateEvents = () -> $scope.$broadcast 'updateEvents' types = [2,4,31] $scope.typesText = (type:type,text: gettextCatalog.getString(TPAService.decodeType(type)),checked:false for type in types) $scope.typesText[0].checked = true $scope.flows = nodes: [] links: [] $scope.mediaLabel = gettextCatalog.getString 'Media' $scope.organisationsLabel = gettextCatalog.getString 'Organisations' $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') parameters = -> params = {} params.maxLength = $scope.maxNodes params.from = $scope.periods[$scope.slider.from/5].period (params.to = $scope.periods[$scope.slider.to/5].period) if $scope.periods types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 (params.filter = $scope.filter) if $scope.filter.length >= 3 if $scope.selectedMedia and $scope.selectedMedia.length > 0 params.media = $scope.selectedMedia.map (media) -> media.name if $scope.selectedOrganisations and $scope.selectedOrganisations.length > 0 params.organisations = $scope.selectedOrganisations.map (org) -> org.name params parametersTimeline = -> params = {} params.source = $scope.selectedOrganisations.map (org) -> org.name params.target = $scope.selectedMedia.map (media) -> media.name types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 params # init the introOptions and call the method $scope.IntroOptions = null; setIntroOptions() toArray = (value) -> if typeof value is 'string' value.split ',' else value compareWith = (param) -> (value) -> if typeIsArray param then normalizeGrpName(value) in param else normalizeGrpName(value) is param #check for parameters in the URL so that this view can be bookmarked checkForStateParams = -> $scope.slider.from = $scope.periods.map((p) -> p.period).indexOf(parseInt $state.params.from)*5 if $state.params.from $scope.slider.to = $scope.periods.map((p) -> p.period).indexOf(parseInt $state.params.to)*5 if $state.params.to $scope.flowTab = ($state.params.flow || "true") is "true" $scope.activeTab = if $scope.flowTab then 0 else 1 if $state.params.media? $scope.selectedMedia = $scope.allMedia.filter(compareWith($state.params.media)) if $state.params.organisations? $scope.selectedOrganisations = $scope.allOrganisations.filter(compareWith($state.params.organisations)) if $state.params.orgGrp? $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter(compareWith($state.params.orgGrp)) members = $scope.selectedOrganisationGroups.map((g)->g.members.map((m)->{name:m,group:g.name,groupType:if g.serverside then 'public' else 'custom'})).reduce(((a,b)->a.concat(b)),[]) memberNames = members.map((o)->o.name) $scope.selectedOrganisations = $scope.selectedOrganisations.filter((o)->o.name not in memberNames) .concat(members) if $state.params.mediaGrp? $scope.selectedMediaGroups = $scope.allMediaGroups.filter(compareWith($state.params.mediaGrp)) members = $scope.selectedMediaGroups.map((g)->g.members.map((m)->{name:m,group:g.name,groupType:if g.serverside then 'public' else 'custom'})).reduce(((a,b)->a.concat(b)),[]) memberNames = members.map((o)->o.name) $scope.selectedMedia = $scope.selectedMedia.filter((o)->o.name not in memberNames) .concat(members) if $state.params.pTypes? pTypes = toArray($state.params.pTypes).map (v) -> parseInt v t.checked = t.type in pTypes for t in $scope.typesText #$scope.org = {} if $state.params.name or $state.params.orgType if $state.params.name if $state.params.orgType is 'org' $scope.selectedOrganisations = [{name: $state.params.name}] else if $state.params.orgType is 'media' $scope.selectedMedia = [{name: $state.params.name}] # Load grouping else if $state.params.grouping # Load grouping by name mediaGroup = $scope.allMediaGroups.filter((g)->g.name is $state.params.grouping) orgGroup = $scope.allOrganisationGroups.filter((g)->g.name is $state.params.grouping) if mediaGroup.length > 0 $scope.selectedMediaGroup = mediaGroup[0] $scope.selectedMedia = mediaGroup.members.map((m) -> m.name) else if orgGroup.length > 0 $scope.selectedOrganisations = orgGroup.members.map((m) -> m.name) $scope.selectedOrganionsationGroups = orgGroup[0] translate = -> $scope.typesText.forEach (t) -> t.text = gettextCatalog.getString TPAService.decodeType t.type $scope.mediaLabel = gettextCatalog.getString 'Media' $scope.organisationsLabel = gettextCatalog.getString 'Organisations' $scope.organisationGroupLabel = gettextCatalog.getString 'Organisation Group' $scope.mediaGroupLabel = gettextCatalog.getString 'Media Group' setIntroOptions() $scope.$on 'gettextLanguageChanged', translate #Updates the browser's address bar without causing the controller to be reloaded #this allows to bookmark the page in every state updateURL = (reload = false)-> $state.transitionTo('showflow',{ from: $scope.periods[$scope.slider.from/5].period to: $scope.periods[$scope.slider.to/5].period media: $scope.selectedMedia.map((m)->m.name) organisations: $scope.selectedOrganisations.map((o)->o.name) mediaGrp: $scope.selectedMediaGroups.map(normalizeGrpName) orgGrp: $scope.selectedOrganisationGroups.map(normalizeGrpName) pTypes: (v.type for v in $scope.typesText when v.checked) flow: $scope.flowTab },{notify:reload, reload: reload}) $scope.showDetails = (node) -> selectionTypes = o: 'org' m: 'media' mg: 'mediaGrp' og: 'orgGrp' $scope.isDetails = true; $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] $scope.selectedMedia = [] $scope.selectedOrganisations = [] switch node.type when 'o' $scope.selectedOrganisations = [{name: node.name}] when 'm' $scope.selectedMedia = [{name: node.name}] when 'og' $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter((g)->g.name is node.name) $scope.selectedOrganisations = $scope.selectedOrganisationGroups .map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) when 'mg' $scope.selectedMediaGroups = $scope.allMediaGroups.filter((g)->g.name is node.name) $scope.selectedMedia = $scope.selectedMediaGroups .map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) updateURL(true) window.scrollTo 0,0 $scope.flowTab = true $scope.showFlowDetails = (link) -> $scope.isDetails = true; $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] $scope.selectedMedia = [] $scope.selectedOrganisations = [] switch link.source.type when 'o' $scope.selectedOrganisations = [name: link.source.name] when 'og' $scope.selectedOrganisations = link.source.targetLinks.map (l)->{name: l.source.name} $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter((g)->g.name is link.source.name) switch link.target.type when 'mg' $scope.selectedMedia = link.target.sourceLinks.map (l)->{name: l.target.name} $scope.selectedMediaGroups = $scope.allMediaGroups.filter((g)->g.name is link.target.name) when 'm' $scope.selectedMedia = [name: link.target.name] $scope.flowTab = false updateURL(true) window.scrollTo 0,0 filterData = (data) -> if $scope.filter.trim().length > 2 r = new RegExp ".*#{$scope.filter}.*","i" data.filter (d) -> r.test(d.organisation) or r.test(d.media) else data $scope.editLocalGroups = () -> $state.go('groupingLocal') $rootScope.$on('groupsChanged', -> loadGroups()) loadFlowData = -> TPAService.filteredflows(parameters()) .then (res) -> stopLoading() #console.log "Got result from Server: " + Date.now() $scope.error = null flowData = res.data for flowDatum in flowData if flowDatum.organisation is 'Other organisations' flowDatum.organisation = gettextCatalog.getString flowDatum.organisation flowDatum.otherOrgs = "oo" if flowDatum.media is 'Other media' flowDatum.media = gettextCatalog.getString flowDatum.media flowDatum.otherMedia = "om" $scope.flowData = flowData if dataPromise.promise.$$state.status == 1 dataPromise = $q.defer() if $scope.dtInstance.reloadData $scope.dtInstance.reloadData() dataPromise.resolve() $scope.flows = buildNodes filterData flowData #checkMaxLength(data) .catch (res) -> stopLoading() $scope.flowData = [] $scope.flows = nodes:[],links:[] $scope.error = res.data #console.log "resolve dataPromise after exception" dataPromise.resolve() loadTimeLineDataAbsolute = -> deferred = $q.defer() TPAService.flowdetail(parametersTimeline()) .then (res) -> $scope.data = res.data loadTimeLineDataRelative = -> TPAService.annualcomparison parametersTimeline() .then (res) -> $scope.annualComparisonData = res.data update = -> if (!$scope.selectedOrganisations or $scope.selectedOrganisations.length is 0) and (!$scope.selectedMedia or $scope.selectedMedia.length is 0) and !$state.params.grouping and $scope.init is 'init' $scope.init = 'preselected' TPAService.top parameters() .then (res) -> $scope.selectedOrganisations = [{name: res.data.top[0].organisation}] return #console.log "Starting update: " + Date.now() startLoading() if ($scope.selectedOrganisations and $scope.selectedOrganisations.length > 0) or ($scope.selectedMedia and $scope.selectedMedia.length > 0) $q.all([loadFlowData(),loadTimeLineDataAbsolute(),loadTimeLineDataRelative()]) .then stopLoading else stopLoading() $scope.error = "nothing selected" checkMaxLength = (data) -> ###if data.nodes.length > $scope.maxNodes $scope.maxExceeded = data.nodes.length $scope.flows = {} else ### $scope.maxExceeded = 0 $scope.flows = data createLink = (source, target, value, type) -> { source: source target: target value: value type: type } buildNodes = (data) -> nodes = {} links = [] sum = 0 getNode = (name,nodeType) -> key = <KEY> if not nodes[key] nodes[key] = {name: name, type: nodeType, index: Object.keys(nodes).length} nodes[key] addLink = (source,target,transfer) -> link = links.filter( (l)-> l.source is source.index and l.target is target.index) if link.length > 0 link[0].value+= transfer.amount link[0].details[transfer.transferType]+=transfer.amount else newLink = source: source.index target: target.index value: transfer.amount, details: 2:0 4:0 31:0 if source.type in ["oo","om"] or target.type in ["oo","om"] newLink.linkType = "others" newLink.details[transfer.transferType]+=transfer.amount links.push(newLink) data.forEach (entry) -> sum+=entry.amount org = getNode(entry.organisation, entry.otherOrgs or "o") media = getNode(entry.media, entry.otherMedia or "m") orgGroups = $scope.selectedOrganisationGroups.filter((v)->org.name in v.members) mediaGroups = $scope.selectedMediaGroups.filter((v)->media.name in v.members) orgGroup = if orgGroups.length > 0 then getNode(orgGroups[0].name,"og") mediaGroup = if mediaGroups.length > 0 then getNode(mediaGroups[0].name,"mg") if orgGroup then addLink(org,orgGroup,entry) if mediaGroup then addLink(mediaGroup,media,entry) if orgGroup and mediaGroup then addLink(orgGroup,mediaGroup,entry) else if orgGroup then addLink(orgGroup,media,entry) else if mediaGroup then addLink(org,mediaGroup,entry) else addLink(org,media,entry) nodes = Object.keys(nodes).map((k)->nodes[k]) links.forEach (l) -> l.type = Object.keys(l.details).filter((k)->l.details[k]>0).reduce(((a,b)->a+b),"") {nodes: nodes,links: links, sum: sum} $scope.dtOptions = {} $scope.dtOptions = DTOptionsBuilder.fromFnPromise( -> defer = $q.defer() dataPromise.promise.then (result) -> defer.resolve($scope.flowData); defer.promise ) .withPaginationType('full_numbers') .withButtons(['copy','csv','excel']) .withBootstrap() angular.extend $scope.dtOptions, language: paginate: previous: gettextCatalog.getString('previous') next: gettextCatalog.getString('next') first: gettextCatalog.getString('first') last: gettextCatalog.getString('last') search: gettextCatalog.getString('search') info: gettextCatalog.getString('Showing page _PAGE_ of _PAGES_') lengthMenu: gettextCatalog.getString "Display _MENU_ records" getExplanation = (paymentType) -> switch paymentType when 2 then gettextCatalog.getString('§2 MedKF-TG (Media Cooperations)') when 4 then gettextCatalog.getString('§4 MedKF-TG (Funding)') when 31 then gettextCatalog.getString('§31 ORF-G (Charges)') $scope.dtColumns = [ DTColumnBuilder.newColumn('organisation').withTitle(gettextCatalog.getString('Payer')) DTColumnBuilder.newColumn('media').withTitle(gettextCatalog.getString('Recipient')), DTColumnBuilder.newColumn('transferType').withTitle(gettextCatalog.getString('Type')) .renderWith((paragraph,type)-> if type is 'display' getExplanation(paragraph) else paragraph ) DTColumnBuilder.newColumn('amount').withTitle(gettextCatalog.getString('Amount')) .renderWith((amount,type) -> if type is 'display' amount.toLocaleString($rootScope.language,{currency: "EUR", maximumFractionDigits:2,minimumFractionDigits:2}) else amount) .withClass('text-right') ] $scope.dtInstance = {} change = (oldValue,newValue) -> #console.log "Change: " + Date.now() if (oldValue isnt newValue) if $scope.dtInstance.reloadData dataPromise = $q.defer() $scope.dtInstance.reloadData() updateURL() update() $rootScope.$on '$stateChangeStart', (event, toState)-> if toState.name isnt 'home' TPAService.saveState stateName,fieldsToStore, $scope loadGroups = () -> orgGroupsPromise = TPAService.getGroupings {type: 'org'} orgGroupsPromise.then (res, err) -> if (err) console.error err return $scope.allOrganisationGroups = res.data.map((g)->g.groupType='public';g) .concat(TPAService.getLocalGroups("org").map((g)->g.groupType='custom';g)) mediaGroupsPromise = TPAService.getGroupings {type: 'media'} mediaGroupsPromise.then (res, err) -> if (err) console.error err return $scope.allMediaGroups = res.data.map((g)->g.groupType='public';g) .concat(TPAService.getLocalGroups("media").map((g)->g.groupType='custom';g)) $q.all([orgGroupsPromise,mediaGroupsPromise]) #start initialization savedState = sessionStorage.getItem stateName stateParamsExist = () -> if $state.params for k,v of $state.params if typeof v isnt 'undefined' return true return false #Lazy loading of media for multi selection box mediaList = [] $scope.loadMedia = (name) -> if name.length >= 3 if mediaList.length == 0 mediaList = $scope.allMedia.filter((m)-> m.name.toLowerCase().indexOf(name.toLowerCase()) > -1) else mediaList = [] mediaList organisationList = [] #Lazy loading of organisation for multi selection box $scope.loadOrganisations = (name) -> if name.length >= 3 if organisationList.length == 0 organisationList = $scope.allOrganisations.filter((m)-> m.name.toLowerCase().indexOf(name.toLowerCase()) > -1) else organisationList = [] organisationList #Initialize form data either by loading a saved state or by fetching data from the server initialize = -> deferred = $q.defer() if savedState TPAService.restoreState stateName, fieldsToStore, $scope $scope.allOrganisations.forEach((o)->o.group="";o.groupType="") $scope.allMedia.forEach((o)->o.group="";o.groupType="") initSlider() stopLoading() deferred.resolve() else startLoading() $q.all([loadPeriods(),loadAllNames(),loadGroups(),loadEvents(),loadEventTags()]) .then () -> stopLoading() if not stateParamsExist() #no defined state so start loading default data update() deferred.resolve() deferred.promise $scope.toggleRegion = (region) -> for event in $scope.events if event.region is region.name event.selected = region.selected $scope.updateEvents() $scope.toggleTag = (tag) -> for event in $scope.events if event.tags.indexOf(tag.name) isnt -1 event.selected = tag.selected $scope.selectedTypes = -> $scope.typesText.filter((t) -> t.checked).map (t) -> t.type $scope.getFrom = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.from/5].quarter}/#{$scope.periods[$scope.slider.from/5].year}" else "" $scope.getTo = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.to/5].quarter}/#{$scope.periods[$scope.slider.to/5].year}" else "" initialize() .then -> if stateParamsExist() clearFields() checkForStateParams() update() $scope.showSelectPayers = -> showSelectDialog(properties.org) $scope.showSelectBeneficiaries = -> showSelectDialog(properties.media) showSelectDialog = (config) -> parent = $scope $uibModal.open( #template: selectOrgText templateUrl: 'transparency/views/selectItemsDialog.html' scope: $scope controller: ($scope, $uibModalInstance) -> $scope.close = -> config.setSelectedGroups $scope.selectedGroupsLocal $uibModalInstance.close() updateItems = (newvalue,oldvalue) -> return if oldvalue is newvalue if newvalue.length > oldvalue.length selected = config.selected() selected.push(newvalue[newvalue.length-1]) config.setSelected(selected) else newNames = newvalue.map (v)->v.name removedItems = oldvalue.filter((v)-> v.name not in newNames).map((v)->v.name) config.setSelected(config.selected().filter ((v)-> v.name not in removedItems)) $scope.createGroup = -> group = config.createLocalGroup()($scope.localGroupName) if group $scope.selectedGroupsLocal.push(group) $uibModalInstance.close() $scope.localGroups = config.allGroups().filter (v)->v.groupType is 'custom' $scope.allGroups = config.allGroups() $scope.items = config.items() $scope.labels = config.labels $scope.selectedGroupsLocal = config.selectedGroups() $scope.selectedLocal = parent.selectedItemsWithoutGroups(config.selected(),config.selectedGroups()) $scope.$watch 'selectedLocal', updateItems, true $scope.addGroup = true size: 'lg' ) $scope.showSettingsDialog = -> parent = $scope $uibModal.open( templateUrl: 'transparency/views/flowSettingsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 100 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 120 ) $scope.showEventSelectionDialog = -> $uibModal.open( templateUrl: 'transparency/views/selectEventsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ) showDialog = (text) -> $uibModal.open( { template: """ <div class="source-list-modal"> <div class="modal-header"> <h3 class="modal-title"> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;Info </h3> </div> <div class="modal-body"> <p>#{text}</p> </div> <div class="modal-footer"> <div class="controls"> <button class="btn btn-primary" type="button" ng-click="close()">OK</button> </div> </div> </div> """ controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() size: 'sm' }) selectionChanged = (config) -> (newValue, oldValue) -> return if newValue is oldValue if newValue.length < oldValue.length removedElement = oldValue.filter((o) -> o.name not in newValue.map((v)->v.name))[0] if removedElement.name in config.selectedGroups().map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) config.setSelected(oldValue) showDialog config.removeMsg return if not $scope.isDetails updateURL() update() $scope.isDetails = false; #Since it is possible to have local and public groups with the same name #we need to be able to distinguish them normalizeGrpName = (v)->"#{if v.serverside then "S:" else ""}#{v.name}" handleRemovingGroup = (config) -> (newValue,oldValue) -> return if newValue is oldValue remainingGroupNames = newValue.map(normalizeGrpName) removedGroup = oldValue.filter((v)->normalizeGrpName(v) not in remainingGroupNames)[0] config.selected().filter((v)->v.name in removedGroup.members) .forEach((v)->v.group="";v.groupType="") config.setSelected(config.selected().filter((v)-> v.name not in removedGroup.members )) #TODO remove if refactored everywhere $scope.organisationsInSelectedGroups = $scope.selectedOrganisationGroups.map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) #config access to properties properties = org: labels: item: "Please select your Payers" title: "Select Payers" all: ()->$scope.allOrganisations allGroups: ()->$scope.allOrganisationGroups selected: ()->$scope.selectedOrganisations selectedGroups: ()->$scope.selectedOrganisationGroups setSelected: (s) -> $scope.selectedOrganisations = s setSelectedGroups: (s) -> $scope.selectedOrganisationGroups = s localGroupName: () -> $scope.localOrgGroupName setLocalGroupName: (s)->$scope.localOrgGroupName=s type:'org' createLocalGroup: -> $scope.createLocalOrgGroup items: -> $scope.loadOrganisations removeMsg: gettextCatalog.getString "You cannot remove this Organisation since it belongs to a selected group. Remove the group instead." media: labels: item: "Please select your Beneficiaries" title: "Select Beneficiaries" all: ()->$scope.allMedia allGroups: ()->$scope.allMediaGroups selected: ()->$scope.selectedMedia selectedGroups: ()->$scope.selectedMediaGroups setSelected: (s) -> $scope.selectedMedia = s setSelectedGroups: (s) -> $scope.selectedMediaGroups = s localGroupName: ()-> $scope.localMediaGroupName setLocalGroupName: (s)->$scope.localMediaGroupName=s type:'media' createLocalGroup: -> $scope.createLocalMediaGroup items: -> $scope.loadMedia removeMsg: gettextCatalog.getString "You cannot remove this Media since it belongs to a selected group. Remove the group instead" handleAddingGroup = (config) -> (newValue, oldValue) -> selectedMembers = oldValue.map((v)->v.members).reduce(((a,b)->a.concat(b)),[]) oldGroupNames = oldValue.map(normalizeGrpName) newGroup = newValue.filter((v)->normalizeGrpName(v) not in oldGroupNames)[0] if newGroup.members.filter((v)->v in selectedMembers).length > 0 showDialog gettextCatalog.getString """ You cannot add this group, since some of its members are also members of already selected groups. This is not allowed. So please remove the other group first """ config.setSelectedGroups(oldValue) forcedChange = true return membersToAdd = newGroup.members .map((m)->{name:m,group:newGroup.name,groupType:if newGroup.serverside then 'public' else 'custom'}) membersOutsideNewGroup = config.selected().filter((v)->v.name not in newGroup.members) config.setSelected(membersOutsideNewGroup.concat(membersToAdd)) selectedGroupsChanged = (config) -> (newValue, oldValue) -> return if newValue is oldValue if forcedChange forcedChange = false return newLength = if (typeof newValue isnt 'undefined') then newValue.length else 0 oldLength = if (typeof oldValue isnt 'undefined') then oldValue.length else 0 if newLength < oldLength handleRemovingGroup(config)(newValue, oldValue) else handleAddingGroup(config)(newValue, oldValue) createLocalGroup = (config) -> (name) -> localGroupName = name || config.localGroupName if localGroupName in TPAService.getLocalGroups(config.type).map((g)->g.name) showDialog gettextCatalog.getString "Custom group could not be created since an local group with an equal name already exists" return null groupedOrganisations = config.selectedGroups().map((g)->g.members).reduce(((a,b)->a.concat(b)),[]) newMembers = config.selected().filter((o)->o.name not in groupedOrganisations) if newMembers.length is 0 showDialog gettextCatalog.getString "Custom group could not be created because there are no ungrouped entries." return null group = { type: config.type members: newMembers.map((m)->m.name) name: localGroupName region: 'AT' } TPAService.saveLocalGroup group group.groupType = 'custom' config.allGroups().push group config.setSelectedGroups(config.selectedGroups().concat [group]) newMembers.forEach((m)->m.group=group.name;m.groupType='custom') TPAService.saveState stateName,fieldsToStore, $scope config.setLocalGroupName("") group $scope.barClicked = (src) -> quarter = $scope.periods.map((v)->"#{v.year}/Q#{v.quarter}").indexOf(src.label) $scope.slider.to = quarter*5 $scope.slider.from = quarter*5 $scope.flowTab = true updateURL(true) $scope.createLocalOrgGroup = createLocalGroup(properties.org) $scope.createLocalMediaGroup = createLocalGroup(properties.media) $scope.organisationsInSelectedGroups = [] $scope.mediaInSelectedGroups = [] $scope.$watch 'selectedOrganisationGroups', selectedGroupsChanged(properties.org), true $scope.$watch 'selectedMediaGroups', selectedGroupsChanged(properties.media), true $scope.$watch 'selectedMedia', selectionChanged(properties.media), true $scope.$watch 'selectedOrganisations', selectionChanged(properties.org), true $scope.$watch('typesText',change,true) ]
true
'use strict' app = angular.module 'mean.transparency' app.filter('searchFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "searchFilter"+item.name html = """<span class="label #{if item.groupType is 'public' then 'label-danger' else 'label-primary'}"> #{gettextCatalog.getString(item.groupType)}</span>#{item.name} <span class="close select-search-list-item_selection-remove">&times;</span>""" $sce.trustAsHtml(html) ]) app.filter('dropdownFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "dropdownFilter"+item.name html = """<span class="label #{if item.groupType is 'public' then 'label-danger' else 'label-primary'}"> #{gettextCatalog.getString(item.groupType)}</span>&nbsp;#{item.name}<span class="close select-search-list-item_selection-remove">&times;</span>""" ### if not item.region? html = '<span class="label label-primary">' + gettextCatalog.getString('custom') + '</span> ' + label else html = '<span class="label label-danger">' + gettextCatalog.getString('public') + '</span> ' + item.name ### $sce.trustAsHtml(html) ]) app.filter('groupFilter', ['$sce', 'gettextCatalog', ($sce, gettextCatalog) -> (label, query, item, options, element) -> #console.log "groupFilter"+item.name if typeof item.group is "undefined" or item.group is "" html = label + '<span class="close select-search-list-item_selection-remove">&times;</span>' else labelClass = "label-danger" if item.groupType is "custom" labelClass = "label-primary" html = '<span class="label ' + labelClass + '">' + item.group + '</span> ' + label + '<span class="close select-search-list-item_selection-remove">&times;</span>' $sce.trustAsHtml(html) ]) app.controller 'FlowCtrl',['$scope','TPAService','$q','$interval','$state','gettextCatalog', '$filter','DTOptionsBuilder','DTColumnBuilder', '$rootScope', '$timeout','$uibModal' ($scope,TPAService,$q,$interval,$state,gettextCatalog, $filter,DTOptionsBuilder,DTColumnBuilder,$rootScope, $timeout,$uibModal) -> #console.log "initialize dataPromise" dataPromise = $q.defer() forcedChange = false $scope.flowTab = true $scope.activeTab = 0 gettextCatalog.getString("custom") gettextCatalog.getString("public") stateName = "flowState" fieldsToStore = ['slider','periods','typesText', 'allOrganisations', 'allMedia', 'selectedOrganisationGroups', 'selectedMediaGroups', 'selectedOrganisations','selectedMedia', 'allOrganisationGroups','allMediaGroups','events','tags','regions'] $scope.init = 'init' typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]' $scope.mediaLabel = gettextCatalog.getString('Media') $scope.organisationLabel = gettextCatalog.getString('Organisation') $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') clearFields = -> $scope.selectedOrganisations = [] $scope.selectedMedia = [] $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] clearFields() $scope.selectedItemsWithoutGroups = (selected,groups) -> orgsInGroups = groups.reduce ((acc,val)->acc.concat(val.members)),[] selected.filter ((org)-> org.name not in orgsInGroups) $scope.selectedMediaWithoutGroups = -> mediaInGroups = $scope.selectedMediaGroups.reduce ((acc,val)->acc.concat(val.members)),[] $scope.selectedMedia.filter ((org)-> org.name not in mediaInGroups) $scope.groupMembersToHTML = (group) -> (group.members.reduce ((acc,val)->acc+"<li>"+val+"</li>"),"<ul>")+"</ul>" $scope.showTable = false # Method for setting the intro-options (e.g. after translations) setIntroOptions = -> $scope.IntroOptions = steps: [ { element: document.querySelector('#flowSettings') intro: gettextCatalog.getString 'It is possible to customize the pie chart. To do so, use the settings.' }, { element: document.querySelector('#flowSlider') intro: gettextCatalog.getString 'Move the sliders to define a range.' }, { element: document.querySelector('#fixSliderRange') intro: gettextCatalog.getString 'Fix slider range. With that it is possible to keep the range constant.' }, { element: document.querySelector('#paymentTypes') intro: gettextCatalog.getString 'Transfers are divided in different payment types. Select the types to display.' }, { element: document.querySelector('#multiselectOrg') intro: gettextCatalog.getString 'You can add organisations to the flow. Go into detail by clicking on the rectangular box.' }, { element: document.querySelector('#multiselectMedia') intro: gettextCatalog.getString 'You can add media to the flow too. Click on the rectangular box for details.' }, { element: document.querySelector('#multiselectOrgGroup') intro: gettextCatalog.getString 'It is possible to select predefined groups for organisations. The entries of the group will be loaded and displayed automatically.' }, { element: document.querySelector('#multiselectMediaGroup') intro: gettextCatalog.getString 'It is possible to select predefined groups for media. The entries of the group will be loaded and displayed automatically.' }, { element: document.querySelector('#customGroups') intro: gettextCatalog.getString 'Based on your selection, you can create custom groups for all non-grouped organisations or media.' }, { element: document.querySelector('#sankeyRow') intro: gettextCatalog.getString 'Per default the top spender based on your chosen payment types and period is selected.' }, { element: document.querySelector('#sankeyRow') intro: gettextCatalog.getString 'To discover the flow in detail just click on the flow between an organisation and a media entry.' } ] showStepNumbers: false exitOnOverlayClick: true exitOnEsc: true nextLabel: gettextCatalog.getString 'Next info' prevLabel: gettextCatalog.getString 'Previous info' skipLabel: gettextCatalog.getString 'Skip info' doneLabel: gettextCatalog.getString 'End tour' $scope.timelineOpened = -> $scope.flowTab = false $timeout((-> $rootScope.$broadcast "updateTimeline"), 100) $scope.flowOpened = -> $scope.flowTab = true $timeout((-> $rootScope.$broadcast "updateFlow"), 100) if $scope.slider current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 90 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 95 startLoading = -> try $interval.cancel timer if timer isnt null catch error $scope.loading = true $scope.progress = 20 stopLoading = -> $scope.loading = false $scope.transferTypeLabel = gettextCatalog.getString('Payment Type') $scope.amountLabel = gettextCatalog.getString('Amount') $scope.maxNodes = 800 $scope.maxExceeded = 0 $scope.data = {} $scope.filter ='' $scope.loading = true $scope.progress = 20 $scope.showSettings = false $scope.selectionSettings = false #$scope.org = null $scope.isDetails = false window.scrollTo 0, 0 $scope.clearDetails = -> #$scope.org = null update() timer = null makeProgress = -> $scope.progress = ($scope.progress + 10) % 101 console.log "Progress: " + $scope.progress flowData = [] nodeMap = {} initSlider = -> if not $scope.slider? then $scope.slider = {} $scope.slider.options = ceil: ($scope.periods.length - 1)*5 step:5 floor:0 onEnd: -> change(1,2) translate: (value) -> $scope.periods.map((p) -> "#{p.year}/Q#{p.quarter}")[value/5] draggableRangeOnly: false $scope.slider.from = ($scope.periods.length - 1)*5 if (not $scope.slider.from?) or isNaN($scope.slider.from) $scope.slider.to = ($scope.periods.length - 1)*5 if not $scope.slider.to? if not $scope.fixedRange? then $scope.fixedRange = false #Load all available periods loadPeriods = () => deferred = $q.defer() TPAService.periods() .then (res) -> $scope.periods = res.data.reverse() initSlider() deferred.resolve() deferred.promise #(Pre-)load all organisation and media names loadAllNames = () -> deferred = $q.defer(); TPAService.search({name: ' '}) .then (res) -> $scope.mediaLabel = gettextCatalog.getString('Media') $scope.organisationLabel = gettextCatalog.getString('Organisation') $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') if typeof $scope.allOrganisations is 'undefined' or $scope.allOrganisations.length is 0 $scope.allOrganisations = res.data.org.map (o) -> { name: o.name, } if typeof $scope.allMedia is 'undefined' or $scope.allMedia.length is 0 $scope.allMedia = res.data.media.map (m) -> { name: m.name, } deferred.resolve() deferred.promise loadEvents = () -> deferred = $q.defer(); TPAService.getEvents().then (res)-> $scope.events = res.data.map((event) -> event.selected=true;event) $scope.regions = [] addedregions = [] for event in $scope.events #event.selected = true; if addedregions.indexOf(event.region) is -1 $scope.regions.push { name: event.region selected: true } addedregions.push event.region deferred.resolve(res) deferred loadEventTags = () -> deferred = $q.defer(); TPAService.getEventTags().then (res) -> $scope.tags = res.data.map((tag)-> {name: tag, selected:true} ) deferred.resolve(res) deferred $scope.updateEvents = () -> $scope.$broadcast 'updateEvents' types = [2,4,31] $scope.typesText = (type:type,text: gettextCatalog.getString(TPAService.decodeType(type)),checked:false for type in types) $scope.typesText[0].checked = true $scope.flows = nodes: [] links: [] $scope.mediaLabel = gettextCatalog.getString 'Media' $scope.organisationsLabel = gettextCatalog.getString 'Organisations' $scope.organisationGroupLabel = gettextCatalog.getString('Organisation Group') $scope.mediaGroupLabel = gettextCatalog.getString('Media Group') parameters = -> params = {} params.maxLength = $scope.maxNodes params.from = $scope.periods[$scope.slider.from/5].period (params.to = $scope.periods[$scope.slider.to/5].period) if $scope.periods types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 (params.filter = $scope.filter) if $scope.filter.length >= 3 if $scope.selectedMedia and $scope.selectedMedia.length > 0 params.media = $scope.selectedMedia.map (media) -> media.name if $scope.selectedOrganisations and $scope.selectedOrganisations.length > 0 params.organisations = $scope.selectedOrganisations.map (org) -> org.name params parametersTimeline = -> params = {} params.source = $scope.selectedOrganisations.map (org) -> org.name params.target = $scope.selectedMedia.map (media) -> media.name types = (v.type for v in $scope.typesText when v.checked) (params.pType = types) if types.length > 0 params # init the introOptions and call the method $scope.IntroOptions = null; setIntroOptions() toArray = (value) -> if typeof value is 'string' value.split ',' else value compareWith = (param) -> (value) -> if typeIsArray param then normalizeGrpName(value) in param else normalizeGrpName(value) is param #check for parameters in the URL so that this view can be bookmarked checkForStateParams = -> $scope.slider.from = $scope.periods.map((p) -> p.period).indexOf(parseInt $state.params.from)*5 if $state.params.from $scope.slider.to = $scope.periods.map((p) -> p.period).indexOf(parseInt $state.params.to)*5 if $state.params.to $scope.flowTab = ($state.params.flow || "true") is "true" $scope.activeTab = if $scope.flowTab then 0 else 1 if $state.params.media? $scope.selectedMedia = $scope.allMedia.filter(compareWith($state.params.media)) if $state.params.organisations? $scope.selectedOrganisations = $scope.allOrganisations.filter(compareWith($state.params.organisations)) if $state.params.orgGrp? $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter(compareWith($state.params.orgGrp)) members = $scope.selectedOrganisationGroups.map((g)->g.members.map((m)->{name:m,group:g.name,groupType:if g.serverside then 'public' else 'custom'})).reduce(((a,b)->a.concat(b)),[]) memberNames = members.map((o)->o.name) $scope.selectedOrganisations = $scope.selectedOrganisations.filter((o)->o.name not in memberNames) .concat(members) if $state.params.mediaGrp? $scope.selectedMediaGroups = $scope.allMediaGroups.filter(compareWith($state.params.mediaGrp)) members = $scope.selectedMediaGroups.map((g)->g.members.map((m)->{name:m,group:g.name,groupType:if g.serverside then 'public' else 'custom'})).reduce(((a,b)->a.concat(b)),[]) memberNames = members.map((o)->o.name) $scope.selectedMedia = $scope.selectedMedia.filter((o)->o.name not in memberNames) .concat(members) if $state.params.pTypes? pTypes = toArray($state.params.pTypes).map (v) -> parseInt v t.checked = t.type in pTypes for t in $scope.typesText #$scope.org = {} if $state.params.name or $state.params.orgType if $state.params.name if $state.params.orgType is 'org' $scope.selectedOrganisations = [{name: $state.params.name}] else if $state.params.orgType is 'media' $scope.selectedMedia = [{name: $state.params.name}] # Load grouping else if $state.params.grouping # Load grouping by name mediaGroup = $scope.allMediaGroups.filter((g)->g.name is $state.params.grouping) orgGroup = $scope.allOrganisationGroups.filter((g)->g.name is $state.params.grouping) if mediaGroup.length > 0 $scope.selectedMediaGroup = mediaGroup[0] $scope.selectedMedia = mediaGroup.members.map((m) -> m.name) else if orgGroup.length > 0 $scope.selectedOrganisations = orgGroup.members.map((m) -> m.name) $scope.selectedOrganionsationGroups = orgGroup[0] translate = -> $scope.typesText.forEach (t) -> t.text = gettextCatalog.getString TPAService.decodeType t.type $scope.mediaLabel = gettextCatalog.getString 'Media' $scope.organisationsLabel = gettextCatalog.getString 'Organisations' $scope.organisationGroupLabel = gettextCatalog.getString 'Organisation Group' $scope.mediaGroupLabel = gettextCatalog.getString 'Media Group' setIntroOptions() $scope.$on 'gettextLanguageChanged', translate #Updates the browser's address bar without causing the controller to be reloaded #this allows to bookmark the page in every state updateURL = (reload = false)-> $state.transitionTo('showflow',{ from: $scope.periods[$scope.slider.from/5].period to: $scope.periods[$scope.slider.to/5].period media: $scope.selectedMedia.map((m)->m.name) organisations: $scope.selectedOrganisations.map((o)->o.name) mediaGrp: $scope.selectedMediaGroups.map(normalizeGrpName) orgGrp: $scope.selectedOrganisationGroups.map(normalizeGrpName) pTypes: (v.type for v in $scope.typesText when v.checked) flow: $scope.flowTab },{notify:reload, reload: reload}) $scope.showDetails = (node) -> selectionTypes = o: 'org' m: 'media' mg: 'mediaGrp' og: 'orgGrp' $scope.isDetails = true; $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] $scope.selectedMedia = [] $scope.selectedOrganisations = [] switch node.type when 'o' $scope.selectedOrganisations = [{name: node.name}] when 'm' $scope.selectedMedia = [{name: node.name}] when 'og' $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter((g)->g.name is node.name) $scope.selectedOrganisations = $scope.selectedOrganisationGroups .map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) when 'mg' $scope.selectedMediaGroups = $scope.allMediaGroups.filter((g)->g.name is node.name) $scope.selectedMedia = $scope.selectedMediaGroups .map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) updateURL(true) window.scrollTo 0,0 $scope.flowTab = true $scope.showFlowDetails = (link) -> $scope.isDetails = true; $scope.selectedMediaGroups = [] $scope.selectedOrganisationGroups = [] $scope.selectedMedia = [] $scope.selectedOrganisations = [] switch link.source.type when 'o' $scope.selectedOrganisations = [name: link.source.name] when 'og' $scope.selectedOrganisations = link.source.targetLinks.map (l)->{name: l.source.name} $scope.selectedOrganisationGroups = $scope.allOrganisationGroups.filter((g)->g.name is link.source.name) switch link.target.type when 'mg' $scope.selectedMedia = link.target.sourceLinks.map (l)->{name: l.target.name} $scope.selectedMediaGroups = $scope.allMediaGroups.filter((g)->g.name is link.target.name) when 'm' $scope.selectedMedia = [name: link.target.name] $scope.flowTab = false updateURL(true) window.scrollTo 0,0 filterData = (data) -> if $scope.filter.trim().length > 2 r = new RegExp ".*#{$scope.filter}.*","i" data.filter (d) -> r.test(d.organisation) or r.test(d.media) else data $scope.editLocalGroups = () -> $state.go('groupingLocal') $rootScope.$on('groupsChanged', -> loadGroups()) loadFlowData = -> TPAService.filteredflows(parameters()) .then (res) -> stopLoading() #console.log "Got result from Server: " + Date.now() $scope.error = null flowData = res.data for flowDatum in flowData if flowDatum.organisation is 'Other organisations' flowDatum.organisation = gettextCatalog.getString flowDatum.organisation flowDatum.otherOrgs = "oo" if flowDatum.media is 'Other media' flowDatum.media = gettextCatalog.getString flowDatum.media flowDatum.otherMedia = "om" $scope.flowData = flowData if dataPromise.promise.$$state.status == 1 dataPromise = $q.defer() if $scope.dtInstance.reloadData $scope.dtInstance.reloadData() dataPromise.resolve() $scope.flows = buildNodes filterData flowData #checkMaxLength(data) .catch (res) -> stopLoading() $scope.flowData = [] $scope.flows = nodes:[],links:[] $scope.error = res.data #console.log "resolve dataPromise after exception" dataPromise.resolve() loadTimeLineDataAbsolute = -> deferred = $q.defer() TPAService.flowdetail(parametersTimeline()) .then (res) -> $scope.data = res.data loadTimeLineDataRelative = -> TPAService.annualcomparison parametersTimeline() .then (res) -> $scope.annualComparisonData = res.data update = -> if (!$scope.selectedOrganisations or $scope.selectedOrganisations.length is 0) and (!$scope.selectedMedia or $scope.selectedMedia.length is 0) and !$state.params.grouping and $scope.init is 'init' $scope.init = 'preselected' TPAService.top parameters() .then (res) -> $scope.selectedOrganisations = [{name: res.data.top[0].organisation}] return #console.log "Starting update: " + Date.now() startLoading() if ($scope.selectedOrganisations and $scope.selectedOrganisations.length > 0) or ($scope.selectedMedia and $scope.selectedMedia.length > 0) $q.all([loadFlowData(),loadTimeLineDataAbsolute(),loadTimeLineDataRelative()]) .then stopLoading else stopLoading() $scope.error = "nothing selected" checkMaxLength = (data) -> ###if data.nodes.length > $scope.maxNodes $scope.maxExceeded = data.nodes.length $scope.flows = {} else ### $scope.maxExceeded = 0 $scope.flows = data createLink = (source, target, value, type) -> { source: source target: target value: value type: type } buildNodes = (data) -> nodes = {} links = [] sum = 0 getNode = (name,nodeType) -> key = PI:KEY:<KEY>END_PI if not nodes[key] nodes[key] = {name: name, type: nodeType, index: Object.keys(nodes).length} nodes[key] addLink = (source,target,transfer) -> link = links.filter( (l)-> l.source is source.index and l.target is target.index) if link.length > 0 link[0].value+= transfer.amount link[0].details[transfer.transferType]+=transfer.amount else newLink = source: source.index target: target.index value: transfer.amount, details: 2:0 4:0 31:0 if source.type in ["oo","om"] or target.type in ["oo","om"] newLink.linkType = "others" newLink.details[transfer.transferType]+=transfer.amount links.push(newLink) data.forEach (entry) -> sum+=entry.amount org = getNode(entry.organisation, entry.otherOrgs or "o") media = getNode(entry.media, entry.otherMedia or "m") orgGroups = $scope.selectedOrganisationGroups.filter((v)->org.name in v.members) mediaGroups = $scope.selectedMediaGroups.filter((v)->media.name in v.members) orgGroup = if orgGroups.length > 0 then getNode(orgGroups[0].name,"og") mediaGroup = if mediaGroups.length > 0 then getNode(mediaGroups[0].name,"mg") if orgGroup then addLink(org,orgGroup,entry) if mediaGroup then addLink(mediaGroup,media,entry) if orgGroup and mediaGroup then addLink(orgGroup,mediaGroup,entry) else if orgGroup then addLink(orgGroup,media,entry) else if mediaGroup then addLink(org,mediaGroup,entry) else addLink(org,media,entry) nodes = Object.keys(nodes).map((k)->nodes[k]) links.forEach (l) -> l.type = Object.keys(l.details).filter((k)->l.details[k]>0).reduce(((a,b)->a+b),"") {nodes: nodes,links: links, sum: sum} $scope.dtOptions = {} $scope.dtOptions = DTOptionsBuilder.fromFnPromise( -> defer = $q.defer() dataPromise.promise.then (result) -> defer.resolve($scope.flowData); defer.promise ) .withPaginationType('full_numbers') .withButtons(['copy','csv','excel']) .withBootstrap() angular.extend $scope.dtOptions, language: paginate: previous: gettextCatalog.getString('previous') next: gettextCatalog.getString('next') first: gettextCatalog.getString('first') last: gettextCatalog.getString('last') search: gettextCatalog.getString('search') info: gettextCatalog.getString('Showing page _PAGE_ of _PAGES_') lengthMenu: gettextCatalog.getString "Display _MENU_ records" getExplanation = (paymentType) -> switch paymentType when 2 then gettextCatalog.getString('§2 MedKF-TG (Media Cooperations)') when 4 then gettextCatalog.getString('§4 MedKF-TG (Funding)') when 31 then gettextCatalog.getString('§31 ORF-G (Charges)') $scope.dtColumns = [ DTColumnBuilder.newColumn('organisation').withTitle(gettextCatalog.getString('Payer')) DTColumnBuilder.newColumn('media').withTitle(gettextCatalog.getString('Recipient')), DTColumnBuilder.newColumn('transferType').withTitle(gettextCatalog.getString('Type')) .renderWith((paragraph,type)-> if type is 'display' getExplanation(paragraph) else paragraph ) DTColumnBuilder.newColumn('amount').withTitle(gettextCatalog.getString('Amount')) .renderWith((amount,type) -> if type is 'display' amount.toLocaleString($rootScope.language,{currency: "EUR", maximumFractionDigits:2,minimumFractionDigits:2}) else amount) .withClass('text-right') ] $scope.dtInstance = {} change = (oldValue,newValue) -> #console.log "Change: " + Date.now() if (oldValue isnt newValue) if $scope.dtInstance.reloadData dataPromise = $q.defer() $scope.dtInstance.reloadData() updateURL() update() $rootScope.$on '$stateChangeStart', (event, toState)-> if toState.name isnt 'home' TPAService.saveState stateName,fieldsToStore, $scope loadGroups = () -> orgGroupsPromise = TPAService.getGroupings {type: 'org'} orgGroupsPromise.then (res, err) -> if (err) console.error err return $scope.allOrganisationGroups = res.data.map((g)->g.groupType='public';g) .concat(TPAService.getLocalGroups("org").map((g)->g.groupType='custom';g)) mediaGroupsPromise = TPAService.getGroupings {type: 'media'} mediaGroupsPromise.then (res, err) -> if (err) console.error err return $scope.allMediaGroups = res.data.map((g)->g.groupType='public';g) .concat(TPAService.getLocalGroups("media").map((g)->g.groupType='custom';g)) $q.all([orgGroupsPromise,mediaGroupsPromise]) #start initialization savedState = sessionStorage.getItem stateName stateParamsExist = () -> if $state.params for k,v of $state.params if typeof v isnt 'undefined' return true return false #Lazy loading of media for multi selection box mediaList = [] $scope.loadMedia = (name) -> if name.length >= 3 if mediaList.length == 0 mediaList = $scope.allMedia.filter((m)-> m.name.toLowerCase().indexOf(name.toLowerCase()) > -1) else mediaList = [] mediaList organisationList = [] #Lazy loading of organisation for multi selection box $scope.loadOrganisations = (name) -> if name.length >= 3 if organisationList.length == 0 organisationList = $scope.allOrganisations.filter((m)-> m.name.toLowerCase().indexOf(name.toLowerCase()) > -1) else organisationList = [] organisationList #Initialize form data either by loading a saved state or by fetching data from the server initialize = -> deferred = $q.defer() if savedState TPAService.restoreState stateName, fieldsToStore, $scope $scope.allOrganisations.forEach((o)->o.group="";o.groupType="") $scope.allMedia.forEach((o)->o.group="";o.groupType="") initSlider() stopLoading() deferred.resolve() else startLoading() $q.all([loadPeriods(),loadAllNames(),loadGroups(),loadEvents(),loadEventTags()]) .then () -> stopLoading() if not stateParamsExist() #no defined state so start loading default data update() deferred.resolve() deferred.promise $scope.toggleRegion = (region) -> for event in $scope.events if event.region is region.name event.selected = region.selected $scope.updateEvents() $scope.toggleTag = (tag) -> for event in $scope.events if event.tags.indexOf(tag.name) isnt -1 event.selected = tag.selected $scope.selectedTypes = -> $scope.typesText.filter((t) -> t.checked).map (t) -> t.type $scope.getFrom = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.from/5].quarter}/#{$scope.periods[$scope.slider.from/5].year}" else "" $scope.getTo = -> if $scope.periods && $scope.periods.length > 0 "Q#{$scope.periods[$scope.slider.to/5].quarter}/#{$scope.periods[$scope.slider.to/5].year}" else "" initialize() .then -> if stateParamsExist() clearFields() checkForStateParams() update() $scope.showSelectPayers = -> showSelectDialog(properties.org) $scope.showSelectBeneficiaries = -> showSelectDialog(properties.media) showSelectDialog = (config) -> parent = $scope $uibModal.open( #template: selectOrgText templateUrl: 'transparency/views/selectItemsDialog.html' scope: $scope controller: ($scope, $uibModalInstance) -> $scope.close = -> config.setSelectedGroups $scope.selectedGroupsLocal $uibModalInstance.close() updateItems = (newvalue,oldvalue) -> return if oldvalue is newvalue if newvalue.length > oldvalue.length selected = config.selected() selected.push(newvalue[newvalue.length-1]) config.setSelected(selected) else newNames = newvalue.map (v)->v.name removedItems = oldvalue.filter((v)-> v.name not in newNames).map((v)->v.name) config.setSelected(config.selected().filter ((v)-> v.name not in removedItems)) $scope.createGroup = -> group = config.createLocalGroup()($scope.localGroupName) if group $scope.selectedGroupsLocal.push(group) $uibModalInstance.close() $scope.localGroups = config.allGroups().filter (v)->v.groupType is 'custom' $scope.allGroups = config.allGroups() $scope.items = config.items() $scope.labels = config.labels $scope.selectedGroupsLocal = config.selectedGroups() $scope.selectedLocal = parent.selectedItemsWithoutGroups(config.selected(),config.selectedGroups()) $scope.$watch 'selectedLocal', updateItems, true $scope.addGroup = true size: 'lg' ) $scope.showSettingsDialog = -> parent = $scope $uibModal.open( templateUrl: 'transparency/views/flowSettingsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() current = $scope.slider.options.draggableRangeOnly $timeout (-> $scope.slider.options.draggableRangeOnly = !current), 100 $timeout (-> $scope.slider.options.draggableRangeOnly = current), 120 ) $scope.showEventSelectionDialog = -> $uibModal.open( templateUrl: 'transparency/views/selectEventsDialog.html' scope: $scope size: 'lg' controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() ) showDialog = (text) -> $uibModal.open( { template: """ <div class="source-list-modal"> <div class="modal-header"> <h3 class="modal-title"> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;Info </h3> </div> <div class="modal-body"> <p>#{text}</p> </div> <div class="modal-footer"> <div class="controls"> <button class="btn btn-primary" type="button" ng-click="close()">OK</button> </div> </div> </div> """ controller: ($scope, $uibModalInstance) -> $scope.close = -> $uibModalInstance.close() size: 'sm' }) selectionChanged = (config) -> (newValue, oldValue) -> return if newValue is oldValue if newValue.length < oldValue.length removedElement = oldValue.filter((o) -> o.name not in newValue.map((v)->v.name))[0] if removedElement.name in config.selectedGroups().map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) config.setSelected(oldValue) showDialog config.removeMsg return if not $scope.isDetails updateURL() update() $scope.isDetails = false; #Since it is possible to have local and public groups with the same name #we need to be able to distinguish them normalizeGrpName = (v)->"#{if v.serverside then "S:" else ""}#{v.name}" handleRemovingGroup = (config) -> (newValue,oldValue) -> return if newValue is oldValue remainingGroupNames = newValue.map(normalizeGrpName) removedGroup = oldValue.filter((v)->normalizeGrpName(v) not in remainingGroupNames)[0] config.selected().filter((v)->v.name in removedGroup.members) .forEach((v)->v.group="";v.groupType="") config.setSelected(config.selected().filter((v)-> v.name not in removedGroup.members )) #TODO remove if refactored everywhere $scope.organisationsInSelectedGroups = $scope.selectedOrganisationGroups.map((g)->g.members).reduce(((a,b) -> a.concat(b)),[]) #config access to properties properties = org: labels: item: "Please select your Payers" title: "Select Payers" all: ()->$scope.allOrganisations allGroups: ()->$scope.allOrganisationGroups selected: ()->$scope.selectedOrganisations selectedGroups: ()->$scope.selectedOrganisationGroups setSelected: (s) -> $scope.selectedOrganisations = s setSelectedGroups: (s) -> $scope.selectedOrganisationGroups = s localGroupName: () -> $scope.localOrgGroupName setLocalGroupName: (s)->$scope.localOrgGroupName=s type:'org' createLocalGroup: -> $scope.createLocalOrgGroup items: -> $scope.loadOrganisations removeMsg: gettextCatalog.getString "You cannot remove this Organisation since it belongs to a selected group. Remove the group instead." media: labels: item: "Please select your Beneficiaries" title: "Select Beneficiaries" all: ()->$scope.allMedia allGroups: ()->$scope.allMediaGroups selected: ()->$scope.selectedMedia selectedGroups: ()->$scope.selectedMediaGroups setSelected: (s) -> $scope.selectedMedia = s setSelectedGroups: (s) -> $scope.selectedMediaGroups = s localGroupName: ()-> $scope.localMediaGroupName setLocalGroupName: (s)->$scope.localMediaGroupName=s type:'media' createLocalGroup: -> $scope.createLocalMediaGroup items: -> $scope.loadMedia removeMsg: gettextCatalog.getString "You cannot remove this Media since it belongs to a selected group. Remove the group instead" handleAddingGroup = (config) -> (newValue, oldValue) -> selectedMembers = oldValue.map((v)->v.members).reduce(((a,b)->a.concat(b)),[]) oldGroupNames = oldValue.map(normalizeGrpName) newGroup = newValue.filter((v)->normalizeGrpName(v) not in oldGroupNames)[0] if newGroup.members.filter((v)->v in selectedMembers).length > 0 showDialog gettextCatalog.getString """ You cannot add this group, since some of its members are also members of already selected groups. This is not allowed. So please remove the other group first """ config.setSelectedGroups(oldValue) forcedChange = true return membersToAdd = newGroup.members .map((m)->{name:m,group:newGroup.name,groupType:if newGroup.serverside then 'public' else 'custom'}) membersOutsideNewGroup = config.selected().filter((v)->v.name not in newGroup.members) config.setSelected(membersOutsideNewGroup.concat(membersToAdd)) selectedGroupsChanged = (config) -> (newValue, oldValue) -> return if newValue is oldValue if forcedChange forcedChange = false return newLength = if (typeof newValue isnt 'undefined') then newValue.length else 0 oldLength = if (typeof oldValue isnt 'undefined') then oldValue.length else 0 if newLength < oldLength handleRemovingGroup(config)(newValue, oldValue) else handleAddingGroup(config)(newValue, oldValue) createLocalGroup = (config) -> (name) -> localGroupName = name || config.localGroupName if localGroupName in TPAService.getLocalGroups(config.type).map((g)->g.name) showDialog gettextCatalog.getString "Custom group could not be created since an local group with an equal name already exists" return null groupedOrganisations = config.selectedGroups().map((g)->g.members).reduce(((a,b)->a.concat(b)),[]) newMembers = config.selected().filter((o)->o.name not in groupedOrganisations) if newMembers.length is 0 showDialog gettextCatalog.getString "Custom group could not be created because there are no ungrouped entries." return null group = { type: config.type members: newMembers.map((m)->m.name) name: localGroupName region: 'AT' } TPAService.saveLocalGroup group group.groupType = 'custom' config.allGroups().push group config.setSelectedGroups(config.selectedGroups().concat [group]) newMembers.forEach((m)->m.group=group.name;m.groupType='custom') TPAService.saveState stateName,fieldsToStore, $scope config.setLocalGroupName("") group $scope.barClicked = (src) -> quarter = $scope.periods.map((v)->"#{v.year}/Q#{v.quarter}").indexOf(src.label) $scope.slider.to = quarter*5 $scope.slider.from = quarter*5 $scope.flowTab = true updateURL(true) $scope.createLocalOrgGroup = createLocalGroup(properties.org) $scope.createLocalMediaGroup = createLocalGroup(properties.media) $scope.organisationsInSelectedGroups = [] $scope.mediaInSelectedGroups = [] $scope.$watch 'selectedOrganisationGroups', selectedGroupsChanged(properties.org), true $scope.$watch 'selectedMediaGroups', selectedGroupsChanged(properties.media), true $scope.$watch 'selectedMedia', selectionChanged(properties.media), true $scope.$watch 'selectedOrganisations', selectionChanged(properties.org), true $scope.$watch('typesText',change,true) ]
[ { "context": "\n# @fileoverview Tests for max-len rule.\n# @author Matt DuVall <http://www.mattduvall.com>\n###\n\n'use strict'\n\n#-", "end": 66, "score": 0.9998372793197632, "start": 55, "tag": "NAME", "value": "Matt DuVall" }, { "context": "check indented comment lines - https://github.com/eslint/eslint/issues/6322\n code:\n '->\\n' + '# th", "end": 4410, "score": 0.996450662612915, "start": 4404, "tag": "USERNAME", "value": "eslint" }, { "context": "check indented comment lines - https://github.com/eslint/eslint/issues/6322\n code:\n '->\\n' + '# th", "end": 8960, "score": 0.999411940574646, "start": 8954, "tag": "USERNAME", "value": "eslint" }, { "context": " same length as non-comments - https://github.com/eslint/eslint/issues/6564\n code:\n '# This comme", "end": 11269, "score": 0.9994317889213562, "start": 11263, "tag": "USERNAME", "value": "eslint" } ]
src/tests/rules/max-len.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for max-len rule. # @author Matt DuVall <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/max-len' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable no-useless-concat ### ruleTester.run 'max-len', rule, valid: [ 'x = 5\nx = 2' , code: 'x = 5\nx = 2' options: [80, 4] , code: '\t\t\ti = 1\n\t\t\tj = 1' options: [15, 1] , code: 'one\t\t= 1\nthree\t= 3' options: [16, 4] , code: '\tone\t\t= 1\n\tthree\t= 3' options: [20, 4] , code: 'i = 1\r\ni = 1\n' options: [10, 4] , code: '\n# Blank line on top\nfoo = module.exports = {}\n' options: [80, 4] , '\n# Blank line on top\nfoo = module.exports = {}\n' , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreComments: yes}] , code: 'foo() \t# strips entire comment *and* trailing whitespace' options: [6, 4, {ignoreComments: yes}] , code: '# really long comment on its own line sitting here' options: [40, 4, {ignoreComments: yes}] , '###inline-comment### i = 1' , code: '###inline-comment### i = 1 # with really long trailing comment' options: [40, 4, {ignoreComments: yes}] , code: "foo('http://example.com/this/is/?a=longish&url=in#here')" options: [40, 4, {ignoreUrls: yes}] , code: "foo(bar(bazz('this is a long'), 'line of'), 'stuff')" options: [40, 4, {ignorePattern: 'foo.+bazz\\('}] , code: '### hey there! this is a multiline\n' + ' comment with longish lines in various places\n' + ' but\n' + ' with a short line-length ###' options: [10, 4, {ignoreComments: yes}] , code: '# I like short comments\n' + 'butLongSourceLines = -> weird(eh())' options: [80, {tabWidth: 4, comments: 30}] , code: '# I like longer comments and shorter code\n' + 'see = -> odd(eh())' options: [30, {tabWidth: 4, comments: 80}] , code: '# Full line comment\n' + 'someCode() # With a long trailing comment.' options: [code: 30, tabWidth: 4, comments: 20, ignoreTrailingComments: yes] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreTrailingComments: yes}] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreComments: yes, ignoreTrailingComments: no}] , # ignoreStrings, ignoreTemplateLiterals and ignoreRegExpLiterals options code: "foo = veryLongIdentifier\nbar = 'this is a very long string'" options: [29, 4, {ignoreStrings: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string"' options: [29, 4, {ignoreStrings: yes}] , code: 'str = "this is a very long string\\\nwith continuation"' options: [29, 4, {ignoreStrings: yes}] , code: 'str = "this is a very long string\\\nwith continuation\\\nand with another very very long continuation\\\nand ending"' options: [29, 4, {ignoreStrings: yes}] , code: 'foo = <div className="this is a very long string"></div>' options: [29, 4, {ignoreStrings: yes}] , ### eslint-disable coffee/no-template-curly-in-string ### code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string"' options: [29, 4, {ignoreTemplateLiterals: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string\nand #{this} is another line that is very long"' options: [29, 4, {ignoreTemplateLiterals: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string\nand this is another line that is very long\nand #{here} is another\n and another!"' options: [29, 4, {ignoreTemplateLiterals: yes}] , ### eslint-enable coffee/no-template-curly-in-string ### code: 'foo = /this is a very long pattern/' options: [29, 4, {ignoreRegExpLiterals: yes}] , # check indented comment lines - https://github.com/eslint/eslint/issues/6322 code: '->\n' + '# this line has 29 characters\n' options: [40, 4, {comments: 29}] , code: '->\n' + ' # this line has 33 characters\n' options: [40, 4, {comments: 33}] , code: '->\n' + '###this line has29 characters\n' + 'and this one has21###\n' options: [40, 4, {comments: 29}] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has25###\n' options: [40, 4, {comments: 33}] , code: '->\n' + ' a ###this line has40 characters\n' + ' and this one has36 characters###\n' options: [40, 4, {comments: 36}] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has43 characters### a\n' options: [43, 4, {comments: 33}] , # blank line '' , # Multi-code-point unicode glyphs code: "'🙂😀😆😎😊😜😉👍'" options: [10] ] invalid: [ code: '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti = 1' errors: [ message: 'Line 1 exceeds the maximum line length of 80.' type: 'Program' line: 1 column: 1 ] , code: 'x = 5; y = 2; z = 5' options: [10, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] , code: '\t\t\ti = 1' options: [15, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 15.' type: 'Program' line: 1 column: 1 ] , code: '\t\t\ti = 1\n\t\t\tj = 1' options: [15, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 15.' type: 'Program' line: 1 column: 1 , message: 'Line 2 exceeds the maximum line length of 15.' type: 'Program' line: 2 column: 1 ] , code: '###this is a long non-removed inline comment### i = 1' options: [20, 4, {ignoreComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: "foobar = 'this line isn\\'t matched by the regexp'\n" + "fizzbuzz = 'but this one is matched by the regexp'\n" options: [20, 4, {ignorePattern: 'fizzbuzz'}] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: "longLine = 'will trigger' # even with a comment" options: [10, 4, {ignoreComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4] # ignoreComments is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: "foo('http://example.com/this/is/?a=longish&url=in#here')" options: [40, 4] # ignoreUrls is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: "foo(bar(bazz('this is a long'), 'line of'), 'stuff')" options: [40, 4] # ignorePattern is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length.' options: [80, 4, {comments: 20}] errors: [ message: 'Line 1 exceeds the maximum comment line length of 20.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length and the max code length, but will fail for being too long of a comment' options: [40, 4, {comments: 80}] errors: [ message: 'Line 1 exceeds the maximum comment line length of 80.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length.' options: [code: 20] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: '#This is very long comment with more than 40 characters which is invalid' options: [40, 4, {ignoreTrailingComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , # check indented comment lines - https://github.com/eslint/eslint/issues/6322 code: '->\n' + '# this line has 29 characters\n' options: [40, 4, {comments: 28}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 28.' type: 'Program' line: 2 column: 1 ] , code: '->\n' + ' # this line has 33 characters\n' options: [40, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 ] , code: '->\n' + '###this line has29 characters\n' + 'and this one has32 characters###\n' options: [40, 4, {comments: 28}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 28.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 28.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has36 characters###\n' options: [40, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 32.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' a ###this line has40 characters \n' + ' and this one has36 characters###\n' options: [39, 4, {comments: 35}] errors: [ message: 'Line 2 exceeds the maximum line length of 39.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 35.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has43 characters### a\n' options: [42, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum line length of 42.' type: 'Program' line: 3 column: 1 ] , # check comments with the same length as non-comments - https://github.com/eslint/eslint/issues/6564 code: '# This commented line has precisely 51 characters.\n' + "x = 'This line also has exactly 51 characters'" options: [20, {ignoreComments: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 20.' type: 'Program' line: 2 column: 1 ] , # ignoreStrings and ignoreTemplateLiterals options code: "foo = veryLongIdentifier\nbar = 'this is a very long string'" options: [29, {ignoreStrings: no, ignoreTemplateLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = /this is a very very long pattern/' options: [29, {ignoreStrings: no, ignoreRegExpLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: "foo = veryLongIdentifier\nbar = new RegExp('this is a very very long pattern')" options: [29, {ignoreStrings: no, ignoreRegExpLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , ### eslint-disable coffee/no-template-curly-in-string ### code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string\nand this is another line that is very long"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum line length of 29.' type: 'Program' line: 3 column: 1 ] , code: 'foo = <div>this is a very very very long string</div>' options: [29, 4, {ignoreStrings: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 29.' type: 'Program' line: 1 column: 1 ] , ### eslint-enable coffee/no-template-curly-in-string ### # Multi-code-point unicode glyphs code: "'🙁😁😟☹️😣😖😩😱👎'" options: [10] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] ]
21863
###* # @fileoverview Tests for max-len rule. # @author <NAME> <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/max-len' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable no-useless-concat ### ruleTester.run 'max-len', rule, valid: [ 'x = 5\nx = 2' , code: 'x = 5\nx = 2' options: [80, 4] , code: '\t\t\ti = 1\n\t\t\tj = 1' options: [15, 1] , code: 'one\t\t= 1\nthree\t= 3' options: [16, 4] , code: '\tone\t\t= 1\n\tthree\t= 3' options: [20, 4] , code: 'i = 1\r\ni = 1\n' options: [10, 4] , code: '\n# Blank line on top\nfoo = module.exports = {}\n' options: [80, 4] , '\n# Blank line on top\nfoo = module.exports = {}\n' , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreComments: yes}] , code: 'foo() \t# strips entire comment *and* trailing whitespace' options: [6, 4, {ignoreComments: yes}] , code: '# really long comment on its own line sitting here' options: [40, 4, {ignoreComments: yes}] , '###inline-comment### i = 1' , code: '###inline-comment### i = 1 # with really long trailing comment' options: [40, 4, {ignoreComments: yes}] , code: "foo('http://example.com/this/is/?a=longish&url=in#here')" options: [40, 4, {ignoreUrls: yes}] , code: "foo(bar(bazz('this is a long'), 'line of'), 'stuff')" options: [40, 4, {ignorePattern: 'foo.+bazz\\('}] , code: '### hey there! this is a multiline\n' + ' comment with longish lines in various places\n' + ' but\n' + ' with a short line-length ###' options: [10, 4, {ignoreComments: yes}] , code: '# I like short comments\n' + 'butLongSourceLines = -> weird(eh())' options: [80, {tabWidth: 4, comments: 30}] , code: '# I like longer comments and shorter code\n' + 'see = -> odd(eh())' options: [30, {tabWidth: 4, comments: 80}] , code: '# Full line comment\n' + 'someCode() # With a long trailing comment.' options: [code: 30, tabWidth: 4, comments: 20, ignoreTrailingComments: yes] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreTrailingComments: yes}] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreComments: yes, ignoreTrailingComments: no}] , # ignoreStrings, ignoreTemplateLiterals and ignoreRegExpLiterals options code: "foo = veryLongIdentifier\nbar = 'this is a very long string'" options: [29, 4, {ignoreStrings: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string"' options: [29, 4, {ignoreStrings: yes}] , code: 'str = "this is a very long string\\\nwith continuation"' options: [29, 4, {ignoreStrings: yes}] , code: 'str = "this is a very long string\\\nwith continuation\\\nand with another very very long continuation\\\nand ending"' options: [29, 4, {ignoreStrings: yes}] , code: 'foo = <div className="this is a very long string"></div>' options: [29, 4, {ignoreStrings: yes}] , ### eslint-disable coffee/no-template-curly-in-string ### code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string"' options: [29, 4, {ignoreTemplateLiterals: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string\nand #{this} is another line that is very long"' options: [29, 4, {ignoreTemplateLiterals: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string\nand this is another line that is very long\nand #{here} is another\n and another!"' options: [29, 4, {ignoreTemplateLiterals: yes}] , ### eslint-enable coffee/no-template-curly-in-string ### code: 'foo = /this is a very long pattern/' options: [29, 4, {ignoreRegExpLiterals: yes}] , # check indented comment lines - https://github.com/eslint/eslint/issues/6322 code: '->\n' + '# this line has 29 characters\n' options: [40, 4, {comments: 29}] , code: '->\n' + ' # this line has 33 characters\n' options: [40, 4, {comments: 33}] , code: '->\n' + '###this line has29 characters\n' + 'and this one has21###\n' options: [40, 4, {comments: 29}] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has25###\n' options: [40, 4, {comments: 33}] , code: '->\n' + ' a ###this line has40 characters\n' + ' and this one has36 characters###\n' options: [40, 4, {comments: 36}] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has43 characters### a\n' options: [43, 4, {comments: 33}] , # blank line '' , # Multi-code-point unicode glyphs code: "'🙂😀😆😎😊😜😉👍'" options: [10] ] invalid: [ code: '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti = 1' errors: [ message: 'Line 1 exceeds the maximum line length of 80.' type: 'Program' line: 1 column: 1 ] , code: 'x = 5; y = 2; z = 5' options: [10, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] , code: '\t\t\ti = 1' options: [15, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 15.' type: 'Program' line: 1 column: 1 ] , code: '\t\t\ti = 1\n\t\t\tj = 1' options: [15, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 15.' type: 'Program' line: 1 column: 1 , message: 'Line 2 exceeds the maximum line length of 15.' type: 'Program' line: 2 column: 1 ] , code: '###this is a long non-removed inline comment### i = 1' options: [20, 4, {ignoreComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: "foobar = 'this line isn\\'t matched by the regexp'\n" + "fizzbuzz = 'but this one is matched by the regexp'\n" options: [20, 4, {ignorePattern: 'fizzbuzz'}] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: "longLine = 'will trigger' # even with a comment" options: [10, 4, {ignoreComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4] # ignoreComments is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: "foo('http://example.com/this/is/?a=longish&url=in#here')" options: [40, 4] # ignoreUrls is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: "foo(bar(bazz('this is a long'), 'line of'), 'stuff')" options: [40, 4] # ignorePattern is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length.' options: [80, 4, {comments: 20}] errors: [ message: 'Line 1 exceeds the maximum comment line length of 20.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length and the max code length, but will fail for being too long of a comment' options: [40, 4, {comments: 80}] errors: [ message: 'Line 1 exceeds the maximum comment line length of 80.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length.' options: [code: 20] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: '#This is very long comment with more than 40 characters which is invalid' options: [40, 4, {ignoreTrailingComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , # check indented comment lines - https://github.com/eslint/eslint/issues/6322 code: '->\n' + '# this line has 29 characters\n' options: [40, 4, {comments: 28}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 28.' type: 'Program' line: 2 column: 1 ] , code: '->\n' + ' # this line has 33 characters\n' options: [40, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 ] , code: '->\n' + '###this line has29 characters\n' + 'and this one has32 characters###\n' options: [40, 4, {comments: 28}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 28.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 28.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has36 characters###\n' options: [40, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 32.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' a ###this line has40 characters \n' + ' and this one has36 characters###\n' options: [39, 4, {comments: 35}] errors: [ message: 'Line 2 exceeds the maximum line length of 39.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 35.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has43 characters### a\n' options: [42, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum line length of 42.' type: 'Program' line: 3 column: 1 ] , # check comments with the same length as non-comments - https://github.com/eslint/eslint/issues/6564 code: '# This commented line has precisely 51 characters.\n' + "x = 'This line also has exactly 51 characters'" options: [20, {ignoreComments: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 20.' type: 'Program' line: 2 column: 1 ] , # ignoreStrings and ignoreTemplateLiterals options code: "foo = veryLongIdentifier\nbar = 'this is a very long string'" options: [29, {ignoreStrings: no, ignoreTemplateLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = /this is a very very long pattern/' options: [29, {ignoreStrings: no, ignoreRegExpLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: "foo = veryLongIdentifier\nbar = new RegExp('this is a very very long pattern')" options: [29, {ignoreStrings: no, ignoreRegExpLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , ### eslint-disable coffee/no-template-curly-in-string ### code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string\nand this is another line that is very long"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum line length of 29.' type: 'Program' line: 3 column: 1 ] , code: 'foo = <div>this is a very very very long string</div>' options: [29, 4, {ignoreStrings: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 29.' type: 'Program' line: 1 column: 1 ] , ### eslint-enable coffee/no-template-curly-in-string ### # Multi-code-point unicode glyphs code: "'🙁😁😟☹️😣😖😩😱👎'" options: [10] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] ]
true
###* # @fileoverview Tests for max-len rule. # @author PI:NAME:<NAME>END_PI <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/max-len' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable no-useless-concat ### ruleTester.run 'max-len', rule, valid: [ 'x = 5\nx = 2' , code: 'x = 5\nx = 2' options: [80, 4] , code: '\t\t\ti = 1\n\t\t\tj = 1' options: [15, 1] , code: 'one\t\t= 1\nthree\t= 3' options: [16, 4] , code: '\tone\t\t= 1\n\tthree\t= 3' options: [20, 4] , code: 'i = 1\r\ni = 1\n' options: [10, 4] , code: '\n# Blank line on top\nfoo = module.exports = {}\n' options: [80, 4] , '\n# Blank line on top\nfoo = module.exports = {}\n' , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreComments: yes}] , code: 'foo() \t# strips entire comment *and* trailing whitespace' options: [6, 4, {ignoreComments: yes}] , code: '# really long comment on its own line sitting here' options: [40, 4, {ignoreComments: yes}] , '###inline-comment### i = 1' , code: '###inline-comment### i = 1 # with really long trailing comment' options: [40, 4, {ignoreComments: yes}] , code: "foo('http://example.com/this/is/?a=longish&url=in#here')" options: [40, 4, {ignoreUrls: yes}] , code: "foo(bar(bazz('this is a long'), 'line of'), 'stuff')" options: [40, 4, {ignorePattern: 'foo.+bazz\\('}] , code: '### hey there! this is a multiline\n' + ' comment with longish lines in various places\n' + ' but\n' + ' with a short line-length ###' options: [10, 4, {ignoreComments: yes}] , code: '# I like short comments\n' + 'butLongSourceLines = -> weird(eh())' options: [80, {tabWidth: 4, comments: 30}] , code: '# I like longer comments and shorter code\n' + 'see = -> odd(eh())' options: [30, {tabWidth: 4, comments: 80}] , code: '# Full line comment\n' + 'someCode() # With a long trailing comment.' options: [code: 30, tabWidth: 4, comments: 20, ignoreTrailingComments: yes] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreTrailingComments: yes}] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4, {ignoreComments: yes, ignoreTrailingComments: no}] , # ignoreStrings, ignoreTemplateLiterals and ignoreRegExpLiterals options code: "foo = veryLongIdentifier\nbar = 'this is a very long string'" options: [29, 4, {ignoreStrings: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string"' options: [29, 4, {ignoreStrings: yes}] , code: 'str = "this is a very long string\\\nwith continuation"' options: [29, 4, {ignoreStrings: yes}] , code: 'str = "this is a very long string\\\nwith continuation\\\nand with another very very long continuation\\\nand ending"' options: [29, 4, {ignoreStrings: yes}] , code: 'foo = <div className="this is a very long string"></div>' options: [29, 4, {ignoreStrings: yes}] , ### eslint-disable coffee/no-template-curly-in-string ### code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string"' options: [29, 4, {ignoreTemplateLiterals: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string\nand #{this} is another line that is very long"' options: [29, 4, {ignoreTemplateLiterals: yes}] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string\nand this is another line that is very long\nand #{here} is another\n and another!"' options: [29, 4, {ignoreTemplateLiterals: yes}] , ### eslint-enable coffee/no-template-curly-in-string ### code: 'foo = /this is a very long pattern/' options: [29, 4, {ignoreRegExpLiterals: yes}] , # check indented comment lines - https://github.com/eslint/eslint/issues/6322 code: '->\n' + '# this line has 29 characters\n' options: [40, 4, {comments: 29}] , code: '->\n' + ' # this line has 33 characters\n' options: [40, 4, {comments: 33}] , code: '->\n' + '###this line has29 characters\n' + 'and this one has21###\n' options: [40, 4, {comments: 29}] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has25###\n' options: [40, 4, {comments: 33}] , code: '->\n' + ' a ###this line has40 characters\n' + ' and this one has36 characters###\n' options: [40, 4, {comments: 36}] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has43 characters### a\n' options: [43, 4, {comments: 33}] , # blank line '' , # Multi-code-point unicode glyphs code: "'🙂😀😆😎😊😜😉👍'" options: [10] ] invalid: [ code: '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti = 1' errors: [ message: 'Line 1 exceeds the maximum line length of 80.' type: 'Program' line: 1 column: 1 ] , code: 'x = 5; y = 2; z = 5' options: [10, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] , code: '\t\t\ti = 1' options: [15, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 15.' type: 'Program' line: 1 column: 1 ] , code: '\t\t\ti = 1\n\t\t\tj = 1' options: [15, 4] errors: [ message: 'Line 1 exceeds the maximum line length of 15.' type: 'Program' line: 1 column: 1 , message: 'Line 2 exceeds the maximum line length of 15.' type: 'Program' line: 2 column: 1 ] , code: '###this is a long non-removed inline comment### i = 1' options: [20, 4, {ignoreComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: "foobar = 'this line isn\\'t matched by the regexp'\n" + "fizzbuzz = 'but this one is matched by the regexp'\n" options: [20, 4, {ignorePattern: 'fizzbuzz'}] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: "longLine = 'will trigger' # even with a comment" options: [10, 4, {ignoreComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] , code: 'foo = module.exports = {} # really long trailing comment' options: [40, 4] # ignoreComments is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: "foo('http://example.com/this/is/?a=longish&url=in#here')" options: [40, 4] # ignoreUrls is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: "foo(bar(bazz('this is a long'), 'line of'), 'stuff')" options: [40, 4] # ignorePattern is disabled errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length.' options: [80, 4, {comments: 20}] errors: [ message: 'Line 1 exceeds the maximum comment line length of 20.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length and the max code length, but will fail for being too long of a comment' options: [40, 4, {comments: 80}] errors: [ message: 'Line 1 exceeds the maximum comment line length of 80.' type: 'Program' line: 1 column: 1 ] , code: '# A comment that exceeds the max comment length.' options: [code: 20] errors: [ message: 'Line 1 exceeds the maximum line length of 20.' type: 'Program' line: 1 column: 1 ] , code: '#This is very long comment with more than 40 characters which is invalid' options: [40, 4, {ignoreTrailingComments: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 40.' type: 'Program' line: 1 column: 1 ] , # check indented comment lines - https://github.com/eslint/eslint/issues/6322 code: '->\n' + '# this line has 29 characters\n' options: [40, 4, {comments: 28}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 28.' type: 'Program' line: 2 column: 1 ] , code: '->\n' + ' # this line has 33 characters\n' options: [40, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 ] , code: '->\n' + '###this line has29 characters\n' + 'and this one has32 characters###\n' options: [40, 4, {comments: 28}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 28.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 28.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has36 characters###\n' options: [40, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 32.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' a ###this line has40 characters \n' + ' and this one has36 characters###\n' options: [39, 4, {comments: 35}] errors: [ message: 'Line 2 exceeds the maximum line length of 39.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum comment line length of 35.' type: 'Program' line: 3 column: 1 ] , code: '->\n' + ' ###this line has33 characters\n' + ' and this one has43 characters### a\n' options: [42, 4, {comments: 32}] errors: [ message: 'Line 2 exceeds the maximum comment line length of 32.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum line length of 42.' type: 'Program' line: 3 column: 1 ] , # check comments with the same length as non-comments - https://github.com/eslint/eslint/issues/6564 code: '# This commented line has precisely 51 characters.\n' + "x = 'This line also has exactly 51 characters'" options: [20, {ignoreComments: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 20.' type: 'Program' line: 2 column: 1 ] , # ignoreStrings and ignoreTemplateLiterals options code: "foo = veryLongIdentifier\nbar = 'this is a very long string'" options: [29, {ignoreStrings: no, ignoreTemplateLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = /this is a very very long pattern/' options: [29, {ignoreStrings: no, ignoreRegExpLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: "foo = veryLongIdentifier\nbar = new RegExp('this is a very very long pattern')" options: [29, {ignoreStrings: no, ignoreRegExpLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = "this is a very long string"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: yes}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , ### eslint-disable coffee/no-template-curly-in-string ### code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 ] , code: 'foo = veryLongIdentifier\nbar = "this is a #{very} long string\nand this is another line that is very long"' options: [29, {ignoreStrings: no, ignoreTemplateLiterals: no}] errors: [ message: 'Line 2 exceeds the maximum line length of 29.' type: 'Program' line: 2 column: 1 , message: 'Line 3 exceeds the maximum line length of 29.' type: 'Program' line: 3 column: 1 ] , code: 'foo = <div>this is a very very very long string</div>' options: [29, 4, {ignoreStrings: yes}] errors: [ message: 'Line 1 exceeds the maximum line length of 29.' type: 'Program' line: 1 column: 1 ] , ### eslint-enable coffee/no-template-curly-in-string ### # Multi-code-point unicode glyphs code: "'🙁😁😟☹️😣😖😩😱👎'" options: [10] errors: [ message: 'Line 1 exceeds the maximum line length of 10.' type: 'Program' line: 1 column: 1 ] ]
[ { "context": "onstructor: -> \n @username = ko.observable 'max'\n @password = ko.observable 'abc'\n\n @mayLog", "end": 149, "score": 0.9993133544921875, "start": 146, "tag": "USERNAME", "value": "max" }, { "context": "o.observable 'max'\n @password = ko.observable 'abc'\n\n @mayLogin = ko.computed => @username() isn", "end": 185, "score": 0.9987930655479431, "start": 182, "tag": "PASSWORD", "value": "abc" } ]
app/scripts/pages/login/login.coffee
Welfenlab/tutor-corrector
0
ko = require 'knockout' app = require '../../app' api = require '../../api' class ViewModel constructor: -> @username = ko.observable 'max' @password = ko.observable 'abc' @mayLogin = ko.computed => @username() isnt '' and @password() isnt '' @isLoggingIn = ko.observable no @error = ko.observable null @hasError = ko.computed => @error() isnt null login: -> @isLoggingIn yes api.post.login @username(), @password() .then -> api.get.me() .then (data) => @isLoggingIn no app.user ko.mapping.fromJS data app.goto 'overview' .catch (e) => @isLoggingIn no $('.login').transition('shake') fs = require 'fs' module.exports = -> ko.components.register __filename.substr(__dirname.length, __filename.length - 7), template: fs.readFileSync __filename.substr(0, __filename.length - 7) + '.html', 'utf8' viewModel: ViewModel return __filename.substr(__dirname.length, __filename.length - 7)
69290
ko = require 'knockout' app = require '../../app' api = require '../../api' class ViewModel constructor: -> @username = ko.observable 'max' @password = ko.observable '<PASSWORD>' @mayLogin = ko.computed => @username() isnt '' and @password() isnt '' @isLoggingIn = ko.observable no @error = ko.observable null @hasError = ko.computed => @error() isnt null login: -> @isLoggingIn yes api.post.login @username(), @password() .then -> api.get.me() .then (data) => @isLoggingIn no app.user ko.mapping.fromJS data app.goto 'overview' .catch (e) => @isLoggingIn no $('.login').transition('shake') fs = require 'fs' module.exports = -> ko.components.register __filename.substr(__dirname.length, __filename.length - 7), template: fs.readFileSync __filename.substr(0, __filename.length - 7) + '.html', 'utf8' viewModel: ViewModel return __filename.substr(__dirname.length, __filename.length - 7)
true
ko = require 'knockout' app = require '../../app' api = require '../../api' class ViewModel constructor: -> @username = ko.observable 'max' @password = ko.observable 'PI:PASSWORD:<PASSWORD>END_PI' @mayLogin = ko.computed => @username() isnt '' and @password() isnt '' @isLoggingIn = ko.observable no @error = ko.observable null @hasError = ko.computed => @error() isnt null login: -> @isLoggingIn yes api.post.login @username(), @password() .then -> api.get.me() .then (data) => @isLoggingIn no app.user ko.mapping.fromJS data app.goto 'overview' .catch (e) => @isLoggingIn no $('.login').transition('shake') fs = require 'fs' module.exports = -> ko.components.register __filename.substr(__dirname.length, __filename.length - 7), template: fs.readFileSync __filename.substr(0, __filename.length - 7) + '.html', 'utf8' viewModel: ViewModel return __filename.substr(__dirname.length, __filename.length - 7)
[ { "context": " nock('https://api.github.com')\n .get('/users/pgilad')\n .reply 200, pgilad: 'true' # JSON response\n", "end": 461, "score": 0.9996204376220703, "start": 455, "tag": "USERNAME", "value": "pgilad" }, { "context": "ser = robot.brain.userForId '1', {\n name: 'mocha'\n room: '#mocha'\n }\n adapter = r", "end": 969, "score": 0.7413936257362366, "start": 964, "tag": "NAME", "value": "mocha" } ]
test/evaluate.coffee
pgilad/hubot-evaluate
0
expect = require("chai").expect path = require("path") chai = require("chai") sinon = require("sinon") chai.use require("sinon-chai") nock = require('nock') Robot = require("hubot/src/robot") TextMessage = require("hubot/src/message").TextMessage process.env.HUBOT_LOG_LEVEL = 'debug' describe 'evaluate', -> robot = null user = null adapter = null beforeEach (done)-> nock('https://api.github.com') .get('/users/pgilad') .reply 200, pgilad: 'true' # JSON response robot = new Robot(null, "mock-adapter", false, "hubot") robot.adapter.on "connected", -> process.env.HUBOT_AUTH_ADMIN = "1" # robot.loadFile(path.resolve(path.join("node_modules/hubot/src/scripts")), "auth.coffee") require('../index')(robot) # load help scripts to test help messages hubotScripts = path.resolve 'node_modules', 'hubot', 'src', 'scripts' user = robot.brain.userForId '1', { name: 'mocha' room: '#mocha' } adapter = robot.adapter setTimeout(done, 250) do robot.run afterEach -> do robot.shutdown nock.cleanAll() describe 'respond evaluate', -> it 'replies evaluate', (done)-> adapter.on "send", (envelope, strings)-> try expect(strings).to.have.length(1) data = JSON.parse strings[0] expect(data).to.equal( pgilad: true ) do done catch e done e adapter.receive new TextMessage(user, "#{robot.name} evaluate pgilad")
43756
expect = require("chai").expect path = require("path") chai = require("chai") sinon = require("sinon") chai.use require("sinon-chai") nock = require('nock') Robot = require("hubot/src/robot") TextMessage = require("hubot/src/message").TextMessage process.env.HUBOT_LOG_LEVEL = 'debug' describe 'evaluate', -> robot = null user = null adapter = null beforeEach (done)-> nock('https://api.github.com') .get('/users/pgilad') .reply 200, pgilad: 'true' # JSON response robot = new Robot(null, "mock-adapter", false, "hubot") robot.adapter.on "connected", -> process.env.HUBOT_AUTH_ADMIN = "1" # robot.loadFile(path.resolve(path.join("node_modules/hubot/src/scripts")), "auth.coffee") require('../index')(robot) # load help scripts to test help messages hubotScripts = path.resolve 'node_modules', 'hubot', 'src', 'scripts' user = robot.brain.userForId '1', { name: '<NAME>' room: '#mocha' } adapter = robot.adapter setTimeout(done, 250) do robot.run afterEach -> do robot.shutdown nock.cleanAll() describe 'respond evaluate', -> it 'replies evaluate', (done)-> adapter.on "send", (envelope, strings)-> try expect(strings).to.have.length(1) data = JSON.parse strings[0] expect(data).to.equal( pgilad: true ) do done catch e done e adapter.receive new TextMessage(user, "#{robot.name} evaluate pgilad")
true
expect = require("chai").expect path = require("path") chai = require("chai") sinon = require("sinon") chai.use require("sinon-chai") nock = require('nock') Robot = require("hubot/src/robot") TextMessage = require("hubot/src/message").TextMessage process.env.HUBOT_LOG_LEVEL = 'debug' describe 'evaluate', -> robot = null user = null adapter = null beforeEach (done)-> nock('https://api.github.com') .get('/users/pgilad') .reply 200, pgilad: 'true' # JSON response robot = new Robot(null, "mock-adapter", false, "hubot") robot.adapter.on "connected", -> process.env.HUBOT_AUTH_ADMIN = "1" # robot.loadFile(path.resolve(path.join("node_modules/hubot/src/scripts")), "auth.coffee") require('../index')(robot) # load help scripts to test help messages hubotScripts = path.resolve 'node_modules', 'hubot', 'src', 'scripts' user = robot.brain.userForId '1', { name: 'PI:NAME:<NAME>END_PI' room: '#mocha' } adapter = robot.adapter setTimeout(done, 250) do robot.run afterEach -> do robot.shutdown nock.cleanAll() describe 'respond evaluate', -> it 'replies evaluate', (done)-> adapter.on "send", (envelope, strings)-> try expect(strings).to.have.length(1) data = JSON.parse strings[0] expect(data).to.equal( pgilad: true ) do done catch e done e adapter.receive new TextMessage(user, "#{robot.name} evaluate pgilad")
[ { "context": "# Company: Homes Store\n# Author: Douglas Cockerham\n# email: douglas.cockerham@homes-store.com\n# ", "end": 56, "score": 0.9998976588249207, "start": 39, "tag": "NAME", "value": "Douglas Cockerham" }, { "context": "s Store\n# Author: Douglas Cockerham\n# email: douglas.cockerham@homes-store.com\n# date: 01-OCT-2014\n$('.flash-modal').modal()\n", "end": 102, "score": 0.999936580657959, "start": 69, "tag": "EMAIL", "value": "douglas.cockerham@homes-store.com" } ]
assets/coffeescript/main.coffee
DouglasCockerham/HomesStore
0
# Company: Homes Store # Author: Douglas Cockerham # email: douglas.cockerham@homes-store.com # date: 01-OCT-2014 $('.flash-modal').modal() $("[data-toggle='tooltip']").tooltip({ animation: true }) $(".bottom").fadeIn(300).delay(2500).fadeOut(300)
115784
# Company: Homes Store # Author: <NAME> # email: <EMAIL> # date: 01-OCT-2014 $('.flash-modal').modal() $("[data-toggle='tooltip']").tooltip({ animation: true }) $(".bottom").fadeIn(300).delay(2500).fadeOut(300)
true
# Company: Homes Store # Author: PI:NAME:<NAME>END_PI # email: PI:EMAIL:<EMAIL>END_PI # date: 01-OCT-2014 $('.flash-modal').modal() $("[data-toggle='tooltip']").tooltip({ animation: true }) $(".bottom").fadeIn(300).delay(2500).fadeOut(300)
[ { "context": "\trequest.setRequestHeader 'X-Auth-Token', Accounts._storedLoginToken()\n\t\t\trequest.setRequestHeader 'X-Space-Id', Steed", "end": 598, "score": 0.5242280960083008, "start": 582, "tag": "KEY", "value": "storedLoginToken" } ]
creator/packages/steedos-creator-autoform-modals/lib/client/object-modal.coffee
baozhoutao/steedos-platform
10
oDataOperation = (type, url, data, object_name, operation, other)-> self = this beforeHook = FormManager.runHook(object_name, operation, 'before', {_id: other._id, formId: other.formId, doc: data}) if !beforeHook return false; previousDoc = FormManager.getPreviousDoc(object_name, other._id, operation) $.ajax type: type url: url data: JSON.stringify(data) dataType: 'json' contentType: "application/json" processData: false beforeSend: (request) -> request.setRequestHeader 'X-User-Id', Meteor.userId() request.setRequestHeader 'X-Auth-Token', Accounts._storedLoginToken() request.setRequestHeader 'X-Space-Id', Steedos.spaceId() success: (data) -> if operation == "insert" value = data.value[0] else if operation == "update" value = data result = {_id: value._id} result.type = type result.object_name = object_name result.value = value FormManager.runHook(object_name, operation, 'after', {previousDoc: previousDoc, dbDoc: result?.value[0]}) self.done(null, result) error: (jqXHR, textStatus, errorThrown) -> FormManager.runHook(object_name, operation, 'error', {_id: other._id, doc: data, error: jqXHR.responseJSON.error}) self.done(jqXHR.responseJSON.error) getObjectName = (collectionName)-> return collectionName.replace(/Creator.Collections./, "") getSimpleSchema = (collectionName)-> if collectionName object_name = getObjectName collectionName object_fields = Creator.getObject(object_name).fields _fields = Creator.getFields(object_name) schema = Creator.getRecordSafeObjectSchema({}, object_name) final_schema = schema if true #新增_ids虚拟字段,以实现条记录同时更新 final_schema._ids = type: String optional: true autoform: type: "hidden" #新增_object_name虚拟字段,以让后台method知道更新哪个表 final_schema._object_name = type: String optional: true autoform: type: "hidden" defaultValue: -> return object_name return new SimpleSchema(final_schema) Template.CreatorObjectModal.onCreated ()-> if !@data.formId throw new Meteor.Error("500", "缺少参数formId") if !@data.collection throw new Meteor.Error("500", "缺少参数collection") if !@data.object_name throw new Meteor.Error("500", "缺少参数object_name") if !@data.operation throw new Meteor.Error("500", "缺少参数operation") collection = Template.instance().data.collection this.__schema = new ReactiveVar(getSimpleSchema(collection)) this.__record = new ReactiveVar(this.doc || {}); FormManager.runHook(@data.object_name, 'edit', 'before', {schema: this.__schema, record: this.__record}); Template.CreatorObjectModal.onRendered ()-> template = @ formId = @data.formId collection = @data.collection object_name = @data.object_name operation = @data.operation || "insert" onSuccess = @data.onSuccess onError = @data.onError #清理hooks,否则会多次执行 delete AutoForm._hooks[formId] onEscKey = (e) -> if e.keyCode == 27 $('#creatorObjectModal').modal 'hide' $('#creatorObjectModal').on 'shown.bs.modal', -> $(window).bind 'keyup', onEscKey $('#creatorObjectModal').on 'hidden.bs.modal', -> $(window).unbind 'keyup', onEscKey #添加当前form的hooks AutoForm.addHooks formId, before: method: (doc)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "before.insert" trigger.todo.apply({object_name: object_name},[userId, doc]) else if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "before.update" trigger.todo.apply({object_name: object_name},[userId, doc]) return doc after: method: (error, result)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "after.insert" trigger.todo.apply({object_name: object_name},[userId, result]) else if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "after.update" trigger.todo.apply({object_name: object_name},[userId, result]) return result onSubmit: (insertDoc, updateDoc, currentDoc)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers self = this urls = [] if operation == "insert" data = insertDoc type = "post" urls.push {url: Steedos.absoluteUrl("/api/v4/#{object_name}"), formId: formId} delete data._object_name if operation == "update" if Session.get("cmMeteorMethod") if updateDoc["$set"] _id = updateDoc["$set"]._ids || Session.get("cmDoc")._id else _id = Session.get("cmDoc")._id else _id = Session.get("cmDoc")._id if updateDoc["$set"] delete updateDoc["$set"]._ids delete updateDoc["$set"]._object_name if updateDoc["$unset"] delete updateDoc["$unset"]._ids delete updateDoc["$unset"]._object_name # insertDoc里面的值是最全最精确的 updateDoc["$set"] = insertDoc _ids = _id.split(",") _.each _ids, (id)-> urls.push {url: Steedos.absoluteUrl("/api/v4/#{object_name}/#{id}"), _id: id, formId: formId} data = updateDoc type = "put" if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and (trigger.when == "before.insert" or trigger.when == "after.insert") trigger.todo.apply({object_name: object_name},[userId, data]) if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and (trigger.when == "before.update" or trigger.when == "after.update") trigger.todo.apply({object_name: object_name},[userId, data]) _.each urls, (item)-> oDataOperation.call(self, type, item.url, data, object_name, operation, {_id: item._id, formId: item.formId}) return false onSuccess: (operation,result)-> if _.isFunction(onSuccess) onSuccess(operation, result) # $('#creatorObjectModal').modal 'hide' Modal.hide(template) onError: (operation,error) -> if _.isFunction(onError) onError(operation,error) console.error error if error.reason toastr?.error?(TAPi18n.__(error.reason)) else if error.message toastr?.error?(TAPi18n.__(error.message)) else toastr?.error?(error) Template.CreatorObjectModal.helpers doc: ()-> return Template.instance().__record.get(); schema: ()-> return Template.instance().__schema.get() title: ()-> data_title = Template.instance().data.title if data_title return data_title else object_label = Creator.getObject(Template.instance().data.object_name)?.label if Template.instance().data.operation == "update" title = "#{t('Edit')} #{object_label}" else if Template.instance().data.operation == "insert" title = "#{t('New')} #{object_label}" else if Template.instance().data.operation == "remove" title = "#{t('Delete')} #{object_label}" return title fields: ()-> object_name = Template.instance().data.object_name return Creator.getObject(object_name).fields objectSchema: ()-> cmCollection = Template.instance().data.collection cmOperation = Template.instance().data.operation object_name = Template.instance().data.object_name keys = [] if cmCollection schemaInstance = Template.instance().__schema.get() schema = schemaInstance._schema firstLevelKeys = schemaInstance._firstLevelSchemaKeys _permission_fields = _.clone(Creator.getRecordSafeFields({}, object_name)) permission_fields = [] _.each _permission_fields, (_sf, k)-> if !_sf.disabled permission_fields.push(k) unless permission_fields permission_fields = [] if true permission_fields.push "_ids" permission_fields.push "_object_name" if cmOperation == "insert" # 新建记录时,把autonumber、formula、summary类型字段视为omit字段 # 修改记录时不用处理,由schema中设定的readonly属性控制 fields = Creator.getObject(object_name).fields firstLevelKeys = _.filter firstLevelKeys, (firstLevelKey)-> return ["autonumber", "formula", "summary"].indexOf(fields[firstLevelKey]?.type) < 0 _.each schema, (value, key) -> if (_.indexOf firstLevelKeys, key) > -1 if !value.autoform?.omit keys.push key if keys.length == 1 finalFields = grouplessFields: [keys] return finalFields hiddenFields = Creator.getHiddenFields(schema) disabledFields = Creator.getDisabledFields(schema) fieldGroups = [] fieldsForGroup = [] isSingle = false grouplessFields = [] grouplessFields = Creator.getFieldsWithNoGroup(schema) grouplessFields = Creator.getFieldsInFirstLevel(firstLevelKeys, grouplessFields) if permission_fields grouplessFields = _.intersection(permission_fields, grouplessFields) grouplessFields = Creator.getFieldsWithoutOmit(schema, grouplessFields) grouplessFields = Creator.getFieldsForReorder(schema, grouplessFields, isSingle) fieldGroupNames = Creator.getSortedFieldGroupNames(schema) _.each fieldGroupNames, (fieldGroupName) -> fieldsForGroup = Creator.getFieldsForGroup(schema, fieldGroupName) fieldsForGroup = Creator.getFieldsInFirstLevel(firstLevelKeys, fieldsForGroup) if permission_fields fieldsForGroup = _.intersection(permission_fields, fieldsForGroup) fieldsForGroup = Creator.getFieldsWithoutOmit(schema, fieldsForGroup) fieldsForGroup = Creator.getFieldsForReorder(schema, fieldsForGroup, isSingle) fieldGroups.push name: fieldGroupName fields: fieldsForGroup finalFields = grouplessFields: grouplessFields groupFields: fieldGroups hiddenFields: hiddenFields disabledFields: disabledFields return finalFields Template.CreatorObjectModal.events 'click .group-section-control': (event, template) -> event.preventDefault() event.stopPropagation() $(event.currentTarget).closest('.group-section').toggleClass('slds-is-open') 'click button.btn-insert': (event,template) -> $("#"+template.data.formId, "#creatorObjectModal").submit() 'change form': (event, template)-> object_name = template.data.object_name formId = template.data.formId validate = FormManager.validate(object_name, formId); if(!validate) event.preventDefault() event.stopPropagation() else _doc = AutoForm.getFormValues(formId)?.insertDoc FormManager.runHook(object_name, 'edit', 'after', {schema: template.__schema, record: template.__record, doc: _doc}); Template.CreatorObjectFields.helpers isDisabled :(key)-> fields = Template.instance().data.fields return fields[key].disabled getLabel: (key)-> return AutoForm.getLabelForField(key) disabledFieldsValue: (key)-> cmCollection = Template.instance().data.collection object_name = Template.instance().data.object_name if cmCollection fields = Creator.getObject(object_name).fields defaultValue = fields[key].defaultValue if _.isFunction(defaultValue) defaultValue = defaultValue() return defaultValue
207015
oDataOperation = (type, url, data, object_name, operation, other)-> self = this beforeHook = FormManager.runHook(object_name, operation, 'before', {_id: other._id, formId: other.formId, doc: data}) if !beforeHook return false; previousDoc = FormManager.getPreviousDoc(object_name, other._id, operation) $.ajax type: type url: url data: JSON.stringify(data) dataType: 'json' contentType: "application/json" processData: false beforeSend: (request) -> request.setRequestHeader 'X-User-Id', Meteor.userId() request.setRequestHeader 'X-Auth-Token', Accounts._<KEY>() request.setRequestHeader 'X-Space-Id', Steedos.spaceId() success: (data) -> if operation == "insert" value = data.value[0] else if operation == "update" value = data result = {_id: value._id} result.type = type result.object_name = object_name result.value = value FormManager.runHook(object_name, operation, 'after', {previousDoc: previousDoc, dbDoc: result?.value[0]}) self.done(null, result) error: (jqXHR, textStatus, errorThrown) -> FormManager.runHook(object_name, operation, 'error', {_id: other._id, doc: data, error: jqXHR.responseJSON.error}) self.done(jqXHR.responseJSON.error) getObjectName = (collectionName)-> return collectionName.replace(/Creator.Collections./, "") getSimpleSchema = (collectionName)-> if collectionName object_name = getObjectName collectionName object_fields = Creator.getObject(object_name).fields _fields = Creator.getFields(object_name) schema = Creator.getRecordSafeObjectSchema({}, object_name) final_schema = schema if true #新增_ids虚拟字段,以实现条记录同时更新 final_schema._ids = type: String optional: true autoform: type: "hidden" #新增_object_name虚拟字段,以让后台method知道更新哪个表 final_schema._object_name = type: String optional: true autoform: type: "hidden" defaultValue: -> return object_name return new SimpleSchema(final_schema) Template.CreatorObjectModal.onCreated ()-> if !@data.formId throw new Meteor.Error("500", "缺少参数formId") if !@data.collection throw new Meteor.Error("500", "缺少参数collection") if !@data.object_name throw new Meteor.Error("500", "缺少参数object_name") if !@data.operation throw new Meteor.Error("500", "缺少参数operation") collection = Template.instance().data.collection this.__schema = new ReactiveVar(getSimpleSchema(collection)) this.__record = new ReactiveVar(this.doc || {}); FormManager.runHook(@data.object_name, 'edit', 'before', {schema: this.__schema, record: this.__record}); Template.CreatorObjectModal.onRendered ()-> template = @ formId = @data.formId collection = @data.collection object_name = @data.object_name operation = @data.operation || "insert" onSuccess = @data.onSuccess onError = @data.onError #清理hooks,否则会多次执行 delete AutoForm._hooks[formId] onEscKey = (e) -> if e.keyCode == 27 $('#creatorObjectModal').modal 'hide' $('#creatorObjectModal').on 'shown.bs.modal', -> $(window).bind 'keyup', onEscKey $('#creatorObjectModal').on 'hidden.bs.modal', -> $(window).unbind 'keyup', onEscKey #添加当前form的hooks AutoForm.addHooks formId, before: method: (doc)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "before.insert" trigger.todo.apply({object_name: object_name},[userId, doc]) else if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "before.update" trigger.todo.apply({object_name: object_name},[userId, doc]) return doc after: method: (error, result)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "after.insert" trigger.todo.apply({object_name: object_name},[userId, result]) else if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "after.update" trigger.todo.apply({object_name: object_name},[userId, result]) return result onSubmit: (insertDoc, updateDoc, currentDoc)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers self = this urls = [] if operation == "insert" data = insertDoc type = "post" urls.push {url: Steedos.absoluteUrl("/api/v4/#{object_name}"), formId: formId} delete data._object_name if operation == "update" if Session.get("cmMeteorMethod") if updateDoc["$set"] _id = updateDoc["$set"]._ids || Session.get("cmDoc")._id else _id = Session.get("cmDoc")._id else _id = Session.get("cmDoc")._id if updateDoc["$set"] delete updateDoc["$set"]._ids delete updateDoc["$set"]._object_name if updateDoc["$unset"] delete updateDoc["$unset"]._ids delete updateDoc["$unset"]._object_name # insertDoc里面的值是最全最精确的 updateDoc["$set"] = insertDoc _ids = _id.split(",") _.each _ids, (id)-> urls.push {url: Steedos.absoluteUrl("/api/v4/#{object_name}/#{id}"), _id: id, formId: formId} data = updateDoc type = "put" if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and (trigger.when == "before.insert" or trigger.when == "after.insert") trigger.todo.apply({object_name: object_name},[userId, data]) if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and (trigger.when == "before.update" or trigger.when == "after.update") trigger.todo.apply({object_name: object_name},[userId, data]) _.each urls, (item)-> oDataOperation.call(self, type, item.url, data, object_name, operation, {_id: item._id, formId: item.formId}) return false onSuccess: (operation,result)-> if _.isFunction(onSuccess) onSuccess(operation, result) # $('#creatorObjectModal').modal 'hide' Modal.hide(template) onError: (operation,error) -> if _.isFunction(onError) onError(operation,error) console.error error if error.reason toastr?.error?(TAPi18n.__(error.reason)) else if error.message toastr?.error?(TAPi18n.__(error.message)) else toastr?.error?(error) Template.CreatorObjectModal.helpers doc: ()-> return Template.instance().__record.get(); schema: ()-> return Template.instance().__schema.get() title: ()-> data_title = Template.instance().data.title if data_title return data_title else object_label = Creator.getObject(Template.instance().data.object_name)?.label if Template.instance().data.operation == "update" title = "#{t('Edit')} #{object_label}" else if Template.instance().data.operation == "insert" title = "#{t('New')} #{object_label}" else if Template.instance().data.operation == "remove" title = "#{t('Delete')} #{object_label}" return title fields: ()-> object_name = Template.instance().data.object_name return Creator.getObject(object_name).fields objectSchema: ()-> cmCollection = Template.instance().data.collection cmOperation = Template.instance().data.operation object_name = Template.instance().data.object_name keys = [] if cmCollection schemaInstance = Template.instance().__schema.get() schema = schemaInstance._schema firstLevelKeys = schemaInstance._firstLevelSchemaKeys _permission_fields = _.clone(Creator.getRecordSafeFields({}, object_name)) permission_fields = [] _.each _permission_fields, (_sf, k)-> if !_sf.disabled permission_fields.push(k) unless permission_fields permission_fields = [] if true permission_fields.push "_ids" permission_fields.push "_object_name" if cmOperation == "insert" # 新建记录时,把autonumber、formula、summary类型字段视为omit字段 # 修改记录时不用处理,由schema中设定的readonly属性控制 fields = Creator.getObject(object_name).fields firstLevelKeys = _.filter firstLevelKeys, (firstLevelKey)-> return ["autonumber", "formula", "summary"].indexOf(fields[firstLevelKey]?.type) < 0 _.each schema, (value, key) -> if (_.indexOf firstLevelKeys, key) > -1 if !value.autoform?.omit keys.push key if keys.length == 1 finalFields = grouplessFields: [keys] return finalFields hiddenFields = Creator.getHiddenFields(schema) disabledFields = Creator.getDisabledFields(schema) fieldGroups = [] fieldsForGroup = [] isSingle = false grouplessFields = [] grouplessFields = Creator.getFieldsWithNoGroup(schema) grouplessFields = Creator.getFieldsInFirstLevel(firstLevelKeys, grouplessFields) if permission_fields grouplessFields = _.intersection(permission_fields, grouplessFields) grouplessFields = Creator.getFieldsWithoutOmit(schema, grouplessFields) grouplessFields = Creator.getFieldsForReorder(schema, grouplessFields, isSingle) fieldGroupNames = Creator.getSortedFieldGroupNames(schema) _.each fieldGroupNames, (fieldGroupName) -> fieldsForGroup = Creator.getFieldsForGroup(schema, fieldGroupName) fieldsForGroup = Creator.getFieldsInFirstLevel(firstLevelKeys, fieldsForGroup) if permission_fields fieldsForGroup = _.intersection(permission_fields, fieldsForGroup) fieldsForGroup = Creator.getFieldsWithoutOmit(schema, fieldsForGroup) fieldsForGroup = Creator.getFieldsForReorder(schema, fieldsForGroup, isSingle) fieldGroups.push name: fieldGroupName fields: fieldsForGroup finalFields = grouplessFields: grouplessFields groupFields: fieldGroups hiddenFields: hiddenFields disabledFields: disabledFields return finalFields Template.CreatorObjectModal.events 'click .group-section-control': (event, template) -> event.preventDefault() event.stopPropagation() $(event.currentTarget).closest('.group-section').toggleClass('slds-is-open') 'click button.btn-insert': (event,template) -> $("#"+template.data.formId, "#creatorObjectModal").submit() 'change form': (event, template)-> object_name = template.data.object_name formId = template.data.formId validate = FormManager.validate(object_name, formId); if(!validate) event.preventDefault() event.stopPropagation() else _doc = AutoForm.getFormValues(formId)?.insertDoc FormManager.runHook(object_name, 'edit', 'after', {schema: template.__schema, record: template.__record, doc: _doc}); Template.CreatorObjectFields.helpers isDisabled :(key)-> fields = Template.instance().data.fields return fields[key].disabled getLabel: (key)-> return AutoForm.getLabelForField(key) disabledFieldsValue: (key)-> cmCollection = Template.instance().data.collection object_name = Template.instance().data.object_name if cmCollection fields = Creator.getObject(object_name).fields defaultValue = fields[key].defaultValue if _.isFunction(defaultValue) defaultValue = defaultValue() return defaultValue
true
oDataOperation = (type, url, data, object_name, operation, other)-> self = this beforeHook = FormManager.runHook(object_name, operation, 'before', {_id: other._id, formId: other.formId, doc: data}) if !beforeHook return false; previousDoc = FormManager.getPreviousDoc(object_name, other._id, operation) $.ajax type: type url: url data: JSON.stringify(data) dataType: 'json' contentType: "application/json" processData: false beforeSend: (request) -> request.setRequestHeader 'X-User-Id', Meteor.userId() request.setRequestHeader 'X-Auth-Token', Accounts._PI:KEY:<KEY>END_PI() request.setRequestHeader 'X-Space-Id', Steedos.spaceId() success: (data) -> if operation == "insert" value = data.value[0] else if operation == "update" value = data result = {_id: value._id} result.type = type result.object_name = object_name result.value = value FormManager.runHook(object_name, operation, 'after', {previousDoc: previousDoc, dbDoc: result?.value[0]}) self.done(null, result) error: (jqXHR, textStatus, errorThrown) -> FormManager.runHook(object_name, operation, 'error', {_id: other._id, doc: data, error: jqXHR.responseJSON.error}) self.done(jqXHR.responseJSON.error) getObjectName = (collectionName)-> return collectionName.replace(/Creator.Collections./, "") getSimpleSchema = (collectionName)-> if collectionName object_name = getObjectName collectionName object_fields = Creator.getObject(object_name).fields _fields = Creator.getFields(object_name) schema = Creator.getRecordSafeObjectSchema({}, object_name) final_schema = schema if true #新增_ids虚拟字段,以实现条记录同时更新 final_schema._ids = type: String optional: true autoform: type: "hidden" #新增_object_name虚拟字段,以让后台method知道更新哪个表 final_schema._object_name = type: String optional: true autoform: type: "hidden" defaultValue: -> return object_name return new SimpleSchema(final_schema) Template.CreatorObjectModal.onCreated ()-> if !@data.formId throw new Meteor.Error("500", "缺少参数formId") if !@data.collection throw new Meteor.Error("500", "缺少参数collection") if !@data.object_name throw new Meteor.Error("500", "缺少参数object_name") if !@data.operation throw new Meteor.Error("500", "缺少参数operation") collection = Template.instance().data.collection this.__schema = new ReactiveVar(getSimpleSchema(collection)) this.__record = new ReactiveVar(this.doc || {}); FormManager.runHook(@data.object_name, 'edit', 'before', {schema: this.__schema, record: this.__record}); Template.CreatorObjectModal.onRendered ()-> template = @ formId = @data.formId collection = @data.collection object_name = @data.object_name operation = @data.operation || "insert" onSuccess = @data.onSuccess onError = @data.onError #清理hooks,否则会多次执行 delete AutoForm._hooks[formId] onEscKey = (e) -> if e.keyCode == 27 $('#creatorObjectModal').modal 'hide' $('#creatorObjectModal').on 'shown.bs.modal', -> $(window).bind 'keyup', onEscKey $('#creatorObjectModal').on 'hidden.bs.modal', -> $(window).unbind 'keyup', onEscKey #添加当前form的hooks AutoForm.addHooks formId, before: method: (doc)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "before.insert" trigger.todo.apply({object_name: object_name},[userId, doc]) else if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "before.update" trigger.todo.apply({object_name: object_name},[userId, doc]) return doc after: method: (error, result)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "after.insert" trigger.todo.apply({object_name: object_name},[userId, result]) else if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and trigger.when == "after.update" trigger.todo.apply({object_name: object_name},[userId, result]) return result onSubmit: (insertDoc, updateDoc, currentDoc)-> userId = Meteor.userId() triggers = Creator.getObject(object_name).triggers self = this urls = [] if operation == "insert" data = insertDoc type = "post" urls.push {url: Steedos.absoluteUrl("/api/v4/#{object_name}"), formId: formId} delete data._object_name if operation == "update" if Session.get("cmMeteorMethod") if updateDoc["$set"] _id = updateDoc["$set"]._ids || Session.get("cmDoc")._id else _id = Session.get("cmDoc")._id else _id = Session.get("cmDoc")._id if updateDoc["$set"] delete updateDoc["$set"]._ids delete updateDoc["$set"]._object_name if updateDoc["$unset"] delete updateDoc["$unset"]._ids delete updateDoc["$unset"]._object_name # insertDoc里面的值是最全最精确的 updateDoc["$set"] = insertDoc _ids = _id.split(",") _.each _ids, (id)-> urls.push {url: Steedos.absoluteUrl("/api/v4/#{object_name}/#{id}"), _id: id, formId: formId} data = updateDoc type = "put" if triggers if operation == "insert" _.each triggers, (trigger, key)-> if trigger.on == "client" and (trigger.when == "before.insert" or trigger.when == "after.insert") trigger.todo.apply({object_name: object_name},[userId, data]) if operation == "update" _.each triggers, (trigger, key)-> if trigger.on == "client" and (trigger.when == "before.update" or trigger.when == "after.update") trigger.todo.apply({object_name: object_name},[userId, data]) _.each urls, (item)-> oDataOperation.call(self, type, item.url, data, object_name, operation, {_id: item._id, formId: item.formId}) return false onSuccess: (operation,result)-> if _.isFunction(onSuccess) onSuccess(operation, result) # $('#creatorObjectModal').modal 'hide' Modal.hide(template) onError: (operation,error) -> if _.isFunction(onError) onError(operation,error) console.error error if error.reason toastr?.error?(TAPi18n.__(error.reason)) else if error.message toastr?.error?(TAPi18n.__(error.message)) else toastr?.error?(error) Template.CreatorObjectModal.helpers doc: ()-> return Template.instance().__record.get(); schema: ()-> return Template.instance().__schema.get() title: ()-> data_title = Template.instance().data.title if data_title return data_title else object_label = Creator.getObject(Template.instance().data.object_name)?.label if Template.instance().data.operation == "update" title = "#{t('Edit')} #{object_label}" else if Template.instance().data.operation == "insert" title = "#{t('New')} #{object_label}" else if Template.instance().data.operation == "remove" title = "#{t('Delete')} #{object_label}" return title fields: ()-> object_name = Template.instance().data.object_name return Creator.getObject(object_name).fields objectSchema: ()-> cmCollection = Template.instance().data.collection cmOperation = Template.instance().data.operation object_name = Template.instance().data.object_name keys = [] if cmCollection schemaInstance = Template.instance().__schema.get() schema = schemaInstance._schema firstLevelKeys = schemaInstance._firstLevelSchemaKeys _permission_fields = _.clone(Creator.getRecordSafeFields({}, object_name)) permission_fields = [] _.each _permission_fields, (_sf, k)-> if !_sf.disabled permission_fields.push(k) unless permission_fields permission_fields = [] if true permission_fields.push "_ids" permission_fields.push "_object_name" if cmOperation == "insert" # 新建记录时,把autonumber、formula、summary类型字段视为omit字段 # 修改记录时不用处理,由schema中设定的readonly属性控制 fields = Creator.getObject(object_name).fields firstLevelKeys = _.filter firstLevelKeys, (firstLevelKey)-> return ["autonumber", "formula", "summary"].indexOf(fields[firstLevelKey]?.type) < 0 _.each schema, (value, key) -> if (_.indexOf firstLevelKeys, key) > -1 if !value.autoform?.omit keys.push key if keys.length == 1 finalFields = grouplessFields: [keys] return finalFields hiddenFields = Creator.getHiddenFields(schema) disabledFields = Creator.getDisabledFields(schema) fieldGroups = [] fieldsForGroup = [] isSingle = false grouplessFields = [] grouplessFields = Creator.getFieldsWithNoGroup(schema) grouplessFields = Creator.getFieldsInFirstLevel(firstLevelKeys, grouplessFields) if permission_fields grouplessFields = _.intersection(permission_fields, grouplessFields) grouplessFields = Creator.getFieldsWithoutOmit(schema, grouplessFields) grouplessFields = Creator.getFieldsForReorder(schema, grouplessFields, isSingle) fieldGroupNames = Creator.getSortedFieldGroupNames(schema) _.each fieldGroupNames, (fieldGroupName) -> fieldsForGroup = Creator.getFieldsForGroup(schema, fieldGroupName) fieldsForGroup = Creator.getFieldsInFirstLevel(firstLevelKeys, fieldsForGroup) if permission_fields fieldsForGroup = _.intersection(permission_fields, fieldsForGroup) fieldsForGroup = Creator.getFieldsWithoutOmit(schema, fieldsForGroup) fieldsForGroup = Creator.getFieldsForReorder(schema, fieldsForGroup, isSingle) fieldGroups.push name: fieldGroupName fields: fieldsForGroup finalFields = grouplessFields: grouplessFields groupFields: fieldGroups hiddenFields: hiddenFields disabledFields: disabledFields return finalFields Template.CreatorObjectModal.events 'click .group-section-control': (event, template) -> event.preventDefault() event.stopPropagation() $(event.currentTarget).closest('.group-section').toggleClass('slds-is-open') 'click button.btn-insert': (event,template) -> $("#"+template.data.formId, "#creatorObjectModal").submit() 'change form': (event, template)-> object_name = template.data.object_name formId = template.data.formId validate = FormManager.validate(object_name, formId); if(!validate) event.preventDefault() event.stopPropagation() else _doc = AutoForm.getFormValues(formId)?.insertDoc FormManager.runHook(object_name, 'edit', 'after', {schema: template.__schema, record: template.__record, doc: _doc}); Template.CreatorObjectFields.helpers isDisabled :(key)-> fields = Template.instance().data.fields return fields[key].disabled getLabel: (key)-> return AutoForm.getLabelForField(key) disabledFieldsValue: (key)-> cmCollection = Template.instance().data.collection object_name = Template.instance().data.object_name if cmCollection fields = Creator.getObject(object_name).fields defaultValue = fields[key].defaultValue if _.isFunction(defaultValue) defaultValue = defaultValue() return defaultValue
[ { "context": " v: API_VERSION\n oauth_token: token\n venueId: venueid\n success: (", "end": 3187, "score": 0.4187012314796448, "start": 3182, "tag": "PASSWORD", "value": "token" } ]
app/assets/javascripts/search/VenueActionPopovers/ExportAction.js.coffee
Gavin-X/4sweep
12
#= require search/VenueActionPopovers/VenueActionPopover class ExportAction extends VenueActionPopover requireSelectedCount: 1 template: "explore/massflags/export" userCreatedLists: (options = {}) -> return options.success?(@createdListCache) if @createdListCache $.ajax url: "https://api.foursquare.com/v2/users/self/lists" data: oauth_token: token v: API_VERSION m: 'swarm' group: 'created' limit: 200 offset: 0 success: (data) => @createdListCache = data.response.lists.items options.success?(@createdListCache) error: options.error? title: () -> "Export <span class='selectedcount'>#{@selectedcount}</span> place(s):" tooltipTitle: () -> "Export Selected Items" openGeneratedLink: (options = {}) -> link = document.createElement "a" link.download = options.download if options.download link.href = options.href link.target = options.target if options.target # Firefox needs it attached to the doc popover = @trigger.data('popover')?.tip() popover.find(".linkdump").append(link) link.click() popover.find(".linkdump").html("") contentExtras: () -> for own id, element of @explorer.selected querytext = element.venueresult.venuedata.name break dupquery: querytext showPopover: (e) -> super(e) popover = @trigger.data('popover')?.tip() self = this @userCreatedLists success: (lists) -> popover.find(".list-chooser").select2 data: lists.map (list) -> {id: list.id, text: list.name, list: list} placeholder: "Choose a list" popover.find(".loadinglists").hide() popover.find(".list-chooser").on "change", () => popover.find(".addaction").removeClass('disabled') error: () -> popover.find(".error").removeClass("hide").text("Could not load your lists") popover.find(".addaction").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.addSelectedToList(popover.find('.list-chooser').select2('data')) popover.find(".exportvenueids").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.exportVenueIds() self.deselectAndHide() popover.find(".exportvenuecsv").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.exportCSV() self.deselectAndHide() popover.find(".searchfordups").click (e) -> e.preventDefault() self.searchForDuplicates() self.deselectAndHide() popover.find(".elioupload").click (e) -> e.preventDefault() self.openInElio() self.deselectAndHide() deselectAndHide: () -> for id, venueelement of @explorer.selected venueelement.toggleSelection(false) @trigger.popover("hide") addSelectedToList: (list) -> for own venueid, venueelement of @explorer.selected do (venueid, venueelement) => $.ajax type: "POST" url: "https://api.foursquare.com/v2/lists/#{list.id}/additem" data: m: 'swarm' v: API_VERSION oauth_token: token venueId: venueid success: (data) => @trigger.popover('hide') venueelement.toggleSelection(false) @notifyWithTimeout(data.response.item, list.list, true) error: (xhr, textStatus, errorThrown) => @notifyWithTimeout({venue: venueelement.venueresult.venuedata}, list.list, false) venueelement.toggleSelection(false) @trigger.popover('hide') notifyWithTimeout: (listItem, listObj, success) -> # FIXME: add timeout and grouping? $.pnotify text: HandlebarsTemplates['explore/massflags/addlist_confirm']({venue: listItem.venue, list: listObj, success: success}).replace(/[\n\r]/,"") type: if success then "success" else "error" stack: STACK_BOTTOMRIGHT addclass: "stack-bottomright" icon: false width: "450px" searchForDuplicates: () -> locations = for own id, element of @explorer.selected venuedata = element.venueresult.venuedata parseFloat(venuedata.location.lat).toFixed(6) + "," + parseFloat(venuedata.location.lng).toFixed(6) popover = @trigger.data('popover')?.tip() query = popover.find('.dupquery').val() @openGeneratedLink target: "_blank" href: "#s=dupsearch&q=#{encodeURIComponent(query)}&locations=#{locations.join(';')}" exportVenueIds: () -> data = (id for own id, element of @explorer.selected) @openGeneratedLink download: "4sweep_export.txt" href: "data:text/plain;charset=utf-8," + encodeURIComponent(data.join("\n")) openInElio: () -> data = (id for own id, element of @explorer.selected) chunkedData = (data.splice(0, 250) while data.length) for d, i in chunkedData @openGeneratedLink target: "_blank" href: "http://4sq.eliotools.site/load.php?venues=" + d.join(",") exportCSV: () -> header = [ 'venue', 'name', 'address', 'crossStreet', 'city', 'state', 'zip', 'twitter', 'phone', 'url', 'description', 'venuell', 'categoryId', 'facebook' ] data = for own id, element of @explorer.selected venuedata = element.venueresult.venuedata [ venuedata.id, venuedata.name, venuedata.location.address, venuedata.location.crossStreet, venuedata.location.city, venuedata.location.state, venuedata.location.postalCode, venuedata.contact.twitter, venuedata.contact.phone, venuedata.url, venuedata.description, venuedata.location.lat + "," + venuedata.location.lng, venuedata.categories[0]?.id, venuedata.contact.facebookUsername || venuedata.contact.facebook ] csv = header.join(";") + "\n" csv += data.map (row) -> row.map (field) -> field = (field || "").replace(/\\/g, '\\\\') field = field.replace(/"/g,'\\"') "\"#{field}\"" .join(";") .join("\n") @openGeneratedLink download: "4sweep_export.csv" href: "data:text/csv;charset=UTF-8," + window.encodeURIComponent(csv) window.ExportAction = ExportAction
34119
#= require search/VenueActionPopovers/VenueActionPopover class ExportAction extends VenueActionPopover requireSelectedCount: 1 template: "explore/massflags/export" userCreatedLists: (options = {}) -> return options.success?(@createdListCache) if @createdListCache $.ajax url: "https://api.foursquare.com/v2/users/self/lists" data: oauth_token: token v: API_VERSION m: 'swarm' group: 'created' limit: 200 offset: 0 success: (data) => @createdListCache = data.response.lists.items options.success?(@createdListCache) error: options.error? title: () -> "Export <span class='selectedcount'>#{@selectedcount}</span> place(s):" tooltipTitle: () -> "Export Selected Items" openGeneratedLink: (options = {}) -> link = document.createElement "a" link.download = options.download if options.download link.href = options.href link.target = options.target if options.target # Firefox needs it attached to the doc popover = @trigger.data('popover')?.tip() popover.find(".linkdump").append(link) link.click() popover.find(".linkdump").html("") contentExtras: () -> for own id, element of @explorer.selected querytext = element.venueresult.venuedata.name break dupquery: querytext showPopover: (e) -> super(e) popover = @trigger.data('popover')?.tip() self = this @userCreatedLists success: (lists) -> popover.find(".list-chooser").select2 data: lists.map (list) -> {id: list.id, text: list.name, list: list} placeholder: "Choose a list" popover.find(".loadinglists").hide() popover.find(".list-chooser").on "change", () => popover.find(".addaction").removeClass('disabled') error: () -> popover.find(".error").removeClass("hide").text("Could not load your lists") popover.find(".addaction").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.addSelectedToList(popover.find('.list-chooser').select2('data')) popover.find(".exportvenueids").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.exportVenueIds() self.deselectAndHide() popover.find(".exportvenuecsv").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.exportCSV() self.deselectAndHide() popover.find(".searchfordups").click (e) -> e.preventDefault() self.searchForDuplicates() self.deselectAndHide() popover.find(".elioupload").click (e) -> e.preventDefault() self.openInElio() self.deselectAndHide() deselectAndHide: () -> for id, venueelement of @explorer.selected venueelement.toggleSelection(false) @trigger.popover("hide") addSelectedToList: (list) -> for own venueid, venueelement of @explorer.selected do (venueid, venueelement) => $.ajax type: "POST" url: "https://api.foursquare.com/v2/lists/#{list.id}/additem" data: m: 'swarm' v: API_VERSION oauth_token: <PASSWORD> venueId: venueid success: (data) => @trigger.popover('hide') venueelement.toggleSelection(false) @notifyWithTimeout(data.response.item, list.list, true) error: (xhr, textStatus, errorThrown) => @notifyWithTimeout({venue: venueelement.venueresult.venuedata}, list.list, false) venueelement.toggleSelection(false) @trigger.popover('hide') notifyWithTimeout: (listItem, listObj, success) -> # FIXME: add timeout and grouping? $.pnotify text: HandlebarsTemplates['explore/massflags/addlist_confirm']({venue: listItem.venue, list: listObj, success: success}).replace(/[\n\r]/,"") type: if success then "success" else "error" stack: STACK_BOTTOMRIGHT addclass: "stack-bottomright" icon: false width: "450px" searchForDuplicates: () -> locations = for own id, element of @explorer.selected venuedata = element.venueresult.venuedata parseFloat(venuedata.location.lat).toFixed(6) + "," + parseFloat(venuedata.location.lng).toFixed(6) popover = @trigger.data('popover')?.tip() query = popover.find('.dupquery').val() @openGeneratedLink target: "_blank" href: "#s=dupsearch&q=#{encodeURIComponent(query)}&locations=#{locations.join(';')}" exportVenueIds: () -> data = (id for own id, element of @explorer.selected) @openGeneratedLink download: "4sweep_export.txt" href: "data:text/plain;charset=utf-8," + encodeURIComponent(data.join("\n")) openInElio: () -> data = (id for own id, element of @explorer.selected) chunkedData = (data.splice(0, 250) while data.length) for d, i in chunkedData @openGeneratedLink target: "_blank" href: "http://4sq.eliotools.site/load.php?venues=" + d.join(",") exportCSV: () -> header = [ 'venue', 'name', 'address', 'crossStreet', 'city', 'state', 'zip', 'twitter', 'phone', 'url', 'description', 'venuell', 'categoryId', 'facebook' ] data = for own id, element of @explorer.selected venuedata = element.venueresult.venuedata [ venuedata.id, venuedata.name, venuedata.location.address, venuedata.location.crossStreet, venuedata.location.city, venuedata.location.state, venuedata.location.postalCode, venuedata.contact.twitter, venuedata.contact.phone, venuedata.url, venuedata.description, venuedata.location.lat + "," + venuedata.location.lng, venuedata.categories[0]?.id, venuedata.contact.facebookUsername || venuedata.contact.facebook ] csv = header.join(";") + "\n" csv += data.map (row) -> row.map (field) -> field = (field || "").replace(/\\/g, '\\\\') field = field.replace(/"/g,'\\"') "\"#{field}\"" .join(";") .join("\n") @openGeneratedLink download: "4sweep_export.csv" href: "data:text/csv;charset=UTF-8," + window.encodeURIComponent(csv) window.ExportAction = ExportAction
true
#= require search/VenueActionPopovers/VenueActionPopover class ExportAction extends VenueActionPopover requireSelectedCount: 1 template: "explore/massflags/export" userCreatedLists: (options = {}) -> return options.success?(@createdListCache) if @createdListCache $.ajax url: "https://api.foursquare.com/v2/users/self/lists" data: oauth_token: token v: API_VERSION m: 'swarm' group: 'created' limit: 200 offset: 0 success: (data) => @createdListCache = data.response.lists.items options.success?(@createdListCache) error: options.error? title: () -> "Export <span class='selectedcount'>#{@selectedcount}</span> place(s):" tooltipTitle: () -> "Export Selected Items" openGeneratedLink: (options = {}) -> link = document.createElement "a" link.download = options.download if options.download link.href = options.href link.target = options.target if options.target # Firefox needs it attached to the doc popover = @trigger.data('popover')?.tip() popover.find(".linkdump").append(link) link.click() popover.find(".linkdump").html("") contentExtras: () -> for own id, element of @explorer.selected querytext = element.venueresult.venuedata.name break dupquery: querytext showPopover: (e) -> super(e) popover = @trigger.data('popover')?.tip() self = this @userCreatedLists success: (lists) -> popover.find(".list-chooser").select2 data: lists.map (list) -> {id: list.id, text: list.name, list: list} placeholder: "Choose a list" popover.find(".loadinglists").hide() popover.find(".list-chooser").on "change", () => popover.find(".addaction").removeClass('disabled') error: () -> popover.find(".error").removeClass("hide").text("Could not load your lists") popover.find(".addaction").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.addSelectedToList(popover.find('.list-chooser').select2('data')) popover.find(".exportvenueids").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.exportVenueIds() self.deselectAndHide() popover.find(".exportvenuecsv").click (e) -> e.preventDefault() return if $(this).hasClass("disabled") self.exportCSV() self.deselectAndHide() popover.find(".searchfordups").click (e) -> e.preventDefault() self.searchForDuplicates() self.deselectAndHide() popover.find(".elioupload").click (e) -> e.preventDefault() self.openInElio() self.deselectAndHide() deselectAndHide: () -> for id, venueelement of @explorer.selected venueelement.toggleSelection(false) @trigger.popover("hide") addSelectedToList: (list) -> for own venueid, venueelement of @explorer.selected do (venueid, venueelement) => $.ajax type: "POST" url: "https://api.foursquare.com/v2/lists/#{list.id}/additem" data: m: 'swarm' v: API_VERSION oauth_token: PI:PASSWORD:<PASSWORD>END_PI venueId: venueid success: (data) => @trigger.popover('hide') venueelement.toggleSelection(false) @notifyWithTimeout(data.response.item, list.list, true) error: (xhr, textStatus, errorThrown) => @notifyWithTimeout({venue: venueelement.venueresult.venuedata}, list.list, false) venueelement.toggleSelection(false) @trigger.popover('hide') notifyWithTimeout: (listItem, listObj, success) -> # FIXME: add timeout and grouping? $.pnotify text: HandlebarsTemplates['explore/massflags/addlist_confirm']({venue: listItem.venue, list: listObj, success: success}).replace(/[\n\r]/,"") type: if success then "success" else "error" stack: STACK_BOTTOMRIGHT addclass: "stack-bottomright" icon: false width: "450px" searchForDuplicates: () -> locations = for own id, element of @explorer.selected venuedata = element.venueresult.venuedata parseFloat(venuedata.location.lat).toFixed(6) + "," + parseFloat(venuedata.location.lng).toFixed(6) popover = @trigger.data('popover')?.tip() query = popover.find('.dupquery').val() @openGeneratedLink target: "_blank" href: "#s=dupsearch&q=#{encodeURIComponent(query)}&locations=#{locations.join(';')}" exportVenueIds: () -> data = (id for own id, element of @explorer.selected) @openGeneratedLink download: "4sweep_export.txt" href: "data:text/plain;charset=utf-8," + encodeURIComponent(data.join("\n")) openInElio: () -> data = (id for own id, element of @explorer.selected) chunkedData = (data.splice(0, 250) while data.length) for d, i in chunkedData @openGeneratedLink target: "_blank" href: "http://4sq.eliotools.site/load.php?venues=" + d.join(",") exportCSV: () -> header = [ 'venue', 'name', 'address', 'crossStreet', 'city', 'state', 'zip', 'twitter', 'phone', 'url', 'description', 'venuell', 'categoryId', 'facebook' ] data = for own id, element of @explorer.selected venuedata = element.venueresult.venuedata [ venuedata.id, venuedata.name, venuedata.location.address, venuedata.location.crossStreet, venuedata.location.city, venuedata.location.state, venuedata.location.postalCode, venuedata.contact.twitter, venuedata.contact.phone, venuedata.url, venuedata.description, venuedata.location.lat + "," + venuedata.location.lng, venuedata.categories[0]?.id, venuedata.contact.facebookUsername || venuedata.contact.facebook ] csv = header.join(";") + "\n" csv += data.map (row) -> row.map (field) -> field = (field || "").replace(/\\/g, '\\\\') field = field.replace(/"/g,'\\"') "\"#{field}\"" .join(";") .join("\n") @openGeneratedLink download: "4sweep_export.csv" href: "data:text/csv;charset=UTF-8," + window.encodeURIComponent(csv) window.ExportAction = ExportAction
[ { "context": "G.host,\n user: DBCONFIG.user,\n password: DBCONFIG.password,\n database: DBCONFIG.name,\n port: DBCON", "end": 435, "score": 0.9994201064109802, "start": 418, "tag": "PASSWORD", "value": "DBCONFIG.password" } ]
node_modules/konsserto/lib/src/Konsserto/Component/EntityManager/Adapter/MysqlAdapter.coffee
konsserto/konsserto
2
MySql = use('mysql') DBCONFIG = use('/app/config/config').database cc = use('cli-color') Q = use('q') class MysqlAdapter @INSTANCE = undefined @CONNECTION = undefined @getInstance: ()-> if !@INSTANCE @INSTANCE = new @ @connect() return @INSTANCE @connect: ()-> MysqlAdapter.CONNECTION = MySql.createConnection({ host: DBCONFIG.host, user: DBCONFIG.user, password: DBCONFIG.password, database: DBCONFIG.name, port: DBCONFIG.port }) MysqlAdapter.CONNECTION.connect((err)-> if err console.log cc.red('[ERROR MYSQL] An error occured with MySQL, maybe due to : ') console.log cc.red(' - MYSQL is not started') console.log cc.red(' - Bad host configuration in /app/config/config, database part') console.log cc.red(' - Bad port configuration in /app/config/config, database part') console.log cc.red(' - Bad name configuration in /app/config/config, database part') console.log cc.red(' - Bad user or bad password configuration in /app/config/config, database part') else MysqlAdapter.showConfigurations() ) @showConfigurations: ()-> console.log '' console.log '------------------------------------------------------------------' console.log cc.magentaBright('[DATABASE] MYSQL started and ready') console.log cc.magentaBright(' Host : ' + DBCONFIG.host) console.log cc.magentaBright(' Port : ' + DBCONFIG.port) console.log cc.magentaBright(' Database : ' + DBCONFIG.name) console.log cc.magentaBright(' User : ' + DBCONFIG.user) console.log cc.magentaBright(' Password : ' + DBCONFIG.password) console.log '------------------------------------------------------------------' console.log '' getAll: (collectionName)-> sql = MySql.format('SELECT * FROM ??', [collectionName]) deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise getById: (collectionName, id)-> sql = MySql.format('SELECT * FROM ?? WHERE ?? = ?', [collectionName, 'id', id]) deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else if rows.length == 1 deferred.resolve(rows[0]) else if rows.length == 0 deferred.resolve({}) ) return deferred.promise ## Has to bo modified because of Mysql.format ## getByCriteria: (collectionName, criteria)-> sql = MySql.format('SELECT * FROM ?? WHERE ', [collectionName]) sql += @objectToValues criteria deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise objectToValues: (array)-> values = [] for k,v of array values.push MySql.escapeId(k) + ' = ' + MySql.escape(v, true, new Date().getTime()) return values.join(' AND ') add: (object)-> return @ remove: (object)-> return @ removeById: (id)-> return @ modify: (objectSource, newObject)-> return @ modifyById: (id, newObject)-> return @ query: (criteria)-> sql = MySql.format('SELECT * FROM ?? WHERE ', [collectionName]) sql += @objectToValues criteria deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise module.exports = MysqlAdapter
126726
MySql = use('mysql') DBCONFIG = use('/app/config/config').database cc = use('cli-color') Q = use('q') class MysqlAdapter @INSTANCE = undefined @CONNECTION = undefined @getInstance: ()-> if !@INSTANCE @INSTANCE = new @ @connect() return @INSTANCE @connect: ()-> MysqlAdapter.CONNECTION = MySql.createConnection({ host: DBCONFIG.host, user: DBCONFIG.user, password: <PASSWORD>, database: DBCONFIG.name, port: DBCONFIG.port }) MysqlAdapter.CONNECTION.connect((err)-> if err console.log cc.red('[ERROR MYSQL] An error occured with MySQL, maybe due to : ') console.log cc.red(' - MYSQL is not started') console.log cc.red(' - Bad host configuration in /app/config/config, database part') console.log cc.red(' - Bad port configuration in /app/config/config, database part') console.log cc.red(' - Bad name configuration in /app/config/config, database part') console.log cc.red(' - Bad user or bad password configuration in /app/config/config, database part') else MysqlAdapter.showConfigurations() ) @showConfigurations: ()-> console.log '' console.log '------------------------------------------------------------------' console.log cc.magentaBright('[DATABASE] MYSQL started and ready') console.log cc.magentaBright(' Host : ' + DBCONFIG.host) console.log cc.magentaBright(' Port : ' + DBCONFIG.port) console.log cc.magentaBright(' Database : ' + DBCONFIG.name) console.log cc.magentaBright(' User : ' + DBCONFIG.user) console.log cc.magentaBright(' Password : ' + DBCONFIG.password) console.log '------------------------------------------------------------------' console.log '' getAll: (collectionName)-> sql = MySql.format('SELECT * FROM ??', [collectionName]) deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise getById: (collectionName, id)-> sql = MySql.format('SELECT * FROM ?? WHERE ?? = ?', [collectionName, 'id', id]) deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else if rows.length == 1 deferred.resolve(rows[0]) else if rows.length == 0 deferred.resolve({}) ) return deferred.promise ## Has to bo modified because of Mysql.format ## getByCriteria: (collectionName, criteria)-> sql = MySql.format('SELECT * FROM ?? WHERE ', [collectionName]) sql += @objectToValues criteria deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise objectToValues: (array)-> values = [] for k,v of array values.push MySql.escapeId(k) + ' = ' + MySql.escape(v, true, new Date().getTime()) return values.join(' AND ') add: (object)-> return @ remove: (object)-> return @ removeById: (id)-> return @ modify: (objectSource, newObject)-> return @ modifyById: (id, newObject)-> return @ query: (criteria)-> sql = MySql.format('SELECT * FROM ?? WHERE ', [collectionName]) sql += @objectToValues criteria deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise module.exports = MysqlAdapter
true
MySql = use('mysql') DBCONFIG = use('/app/config/config').database cc = use('cli-color') Q = use('q') class MysqlAdapter @INSTANCE = undefined @CONNECTION = undefined @getInstance: ()-> if !@INSTANCE @INSTANCE = new @ @connect() return @INSTANCE @connect: ()-> MysqlAdapter.CONNECTION = MySql.createConnection({ host: DBCONFIG.host, user: DBCONFIG.user, password: PI:PASSWORD:<PASSWORD>END_PI, database: DBCONFIG.name, port: DBCONFIG.port }) MysqlAdapter.CONNECTION.connect((err)-> if err console.log cc.red('[ERROR MYSQL] An error occured with MySQL, maybe due to : ') console.log cc.red(' - MYSQL is not started') console.log cc.red(' - Bad host configuration in /app/config/config, database part') console.log cc.red(' - Bad port configuration in /app/config/config, database part') console.log cc.red(' - Bad name configuration in /app/config/config, database part') console.log cc.red(' - Bad user or bad password configuration in /app/config/config, database part') else MysqlAdapter.showConfigurations() ) @showConfigurations: ()-> console.log '' console.log '------------------------------------------------------------------' console.log cc.magentaBright('[DATABASE] MYSQL started and ready') console.log cc.magentaBright(' Host : ' + DBCONFIG.host) console.log cc.magentaBright(' Port : ' + DBCONFIG.port) console.log cc.magentaBright(' Database : ' + DBCONFIG.name) console.log cc.magentaBright(' User : ' + DBCONFIG.user) console.log cc.magentaBright(' Password : ' + DBCONFIG.password) console.log '------------------------------------------------------------------' console.log '' getAll: (collectionName)-> sql = MySql.format('SELECT * FROM ??', [collectionName]) deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise getById: (collectionName, id)-> sql = MySql.format('SELECT * FROM ?? WHERE ?? = ?', [collectionName, 'id', id]) deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else if rows.length == 1 deferred.resolve(rows[0]) else if rows.length == 0 deferred.resolve({}) ) return deferred.promise ## Has to bo modified because of Mysql.format ## getByCriteria: (collectionName, criteria)-> sql = MySql.format('SELECT * FROM ?? WHERE ', [collectionName]) sql += @objectToValues criteria deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise objectToValues: (array)-> values = [] for k,v of array values.push MySql.escapeId(k) + ' = ' + MySql.escape(v, true, new Date().getTime()) return values.join(' AND ') add: (object)-> return @ remove: (object)-> return @ removeById: (id)-> return @ modify: (objectSource, newObject)-> return @ modifyById: (id, newObject)-> return @ query: (criteria)-> sql = MySql.format('SELECT * FROM ?? WHERE ', [collectionName]) sql += @objectToValues criteria deferred = Q.defer() MysqlAdapter.CONNECTION.query(sql, (err, rows, fields)-> if err deferred.reject(new Error(err)) else deferred.resolve(rows) ) return deferred.promise module.exports = MysqlAdapter
[ { "context": "alse\n\n model: () ->\n [\n {\n name: 'Sven Fuchs'\n title: 'The Original Builder'\n ha", "end": 178, "score": 0.9998896718025208, "start": 168, "tag": "NAME", "value": "Sven Fuchs" }, { "context": " title: 'The Original Builder'\n handle: 'svenfuchs'\n nationality: 'germany'\n country: ", "end": 244, "score": 0.9989155530929565, "start": 235, "tag": "USERNAME", "value": "svenfuchs" }, { "context": " image: 'sven'\n },\n {\n name: 'Josh Kalderimis'\n title: 'Chief Post-It Officer'\n h", "end": 373, "score": 0.9998876452445984, "start": 358, "tag": "NAME", "value": "Josh Kalderimis" }, { "context": " title: 'Chief Post-It Officer'\n handle: 'j2h'\n nationality: 'newzealand'\n countr", "end": 434, "score": 0.9980111718177795, "start": 431, "tag": "USERNAME", "value": "j2h" }, { "context": " image: 'josh'\n },\n {\n name: 'Fritz Thielemann'\n title: 'Admin Adventures'\n handle", "end": 567, "score": 0.9998906254768372, "start": 551, "tag": "NAME", "value": "Fritz Thielemann" }, { "context": " title: 'Admin Adventures'\n handle: 'fritzek'\n nationality: 'germany'\n country: ", "end": 627, "score": 0.9988947510719299, "start": 620, "tag": "USERNAME", "value": "fritzek" }, { "context": " image: 'fritz'\n },\n {\n name: 'Konstantin Haase'\n title: 'Haase of Pain'\n handle: '", "end": 758, "score": 0.9998846054077148, "start": 742, "tag": "NAME", "value": "Konstantin Haase" }, { "context": "'\n title: 'Haase of Pain'\n handle: 'konstantinhaase'\n nationality: 'germany'\n country: ", "end": 823, "score": 0.9978485703468323, "start": 808, "tag": "USERNAME", "value": "konstantinhaase" }, { "context": "age: 'konstantin'\n },\n {\n name: 'Mathias Meyer'\n title: 'Director of Bacon Relations'\n ", "end": 956, "score": 0.9998831748962402, "start": 943, "tag": "NAME", "value": "Mathias Meyer" }, { "context": "e: 'Director of Bacon Relations'\n handle: 'roidrage'\n nationality: 'germany'\n country: ", "end": 1028, "score": 0.9976035952568054, "start": 1020, "tag": "USERNAME", "value": "roidrage" }, { "context": " image: 'mathias'\n },\n {\n name: 'Piotr Sarnacki'\n title: 'Code Monkey'\n handle: 'dr", "end": 1159, "score": 0.9998903274536133, "start": 1145, "tag": "NAME", "value": "Piotr Sarnacki" }, { "context": "ki'\n title: 'Code Monkey'\n handle: 'drogus'\n nationality: 'poland'\n country: '", "end": 1213, "score": 0.9985033869743347, "start": 1207, "tag": "USERNAME", "value": "drogus" }, { "context": " image: 'piotr'\n },\n {\n name: 'Anika Lindtner'\n title: 'Head Catwoman'\n handle: '", "end": 1341, "score": 0.9998860955238342, "start": 1327, "tag": "NAME", "value": "Anika Lindtner" }, { "context": "'\n title: 'Head Catwoman'\n handle: 'langziehohr'\n nationality: 'germany'\n country: ", "end": 1402, "score": 0.9980582594871521, "start": 1391, "tag": "USERNAME", "value": "langziehohr" }, { "context": " image: 'anika'\n },\n {\n name: 'Henrik Hodne'\n title: 'Timezone Experimentalist'\n ", "end": 1529, "score": 0.9998899102210999, "start": 1517, "tag": "NAME", "value": "Henrik Hodne" }, { "context": "itle: 'Timezone Experimentalist'\n handle: 'henrikhodne'\n nationality: 'norway'\n country: '", "end": 1601, "score": 0.998430073261261, "start": 1590, "tag": "USERNAME", "value": "henrikhodne" }, { "context": " image: 'henrik'\n },\n {\n name: 'Justine Arreche'\n title: 'Lead Clipart Strategist'\n ", "end": 1730, "score": 0.9998854398727417, "start": 1715, "tag": "NAME", "value": "Justine Arreche" }, { "context": "title: 'Lead Clipart Strategist'\n handle: 'saltinejustine'\n nationality: 'usa'\n country: 'usa", "end": 1804, "score": 0.9389451742172241, "start": 1790, "tag": "USERNAME", "value": "saltinejustine" }, { "context": " image: 'justine'\n },\n {\n name: 'Hiro Asari'\n title: 'International Man of IPAs'\n ", "end": 1923, "score": 0.9998983144760132, "start": 1913, "tag": "NAME", "value": "Hiro Asari" }, { "context": "tle: 'International Man of IPAs'\n handle: 'hiro_asari'\n nationality: 'japan'\n country: 'u", "end": 1995, "score": 0.9800437092781067, "start": 1985, "tag": "USERNAME", "value": "hiro_asari" }, { "context": " image: 'hiro'\n },\n {\n name: 'Dan Buch'\n title: 'That\\'s Numberwang'\n hand", "end": 2111, "score": 0.9998918175697327, "start": 2103, "tag": "NAME", "value": "Dan Buch" }, { "context": " title: 'That\\'s Numberwang'\n handle: 'meatballhat'\n nationality: 'usa'\n country: 'usa", "end": 2177, "score": 0.9424044489860535, "start": 2166, "tag": "USERNAME", "value": "meatballhat" }, { "context": " image: 'dan'\n },\n {\n name: 'Lisa Passing'\n title: 'Queen of !important'\n nat", "end": 2294, "score": 0.9998877644538879, "start": 2282, "tag": "NAME", "value": "Lisa Passing" }, { "context": " image: 'lisa'\n },\n {\n name: 'Carla Drago'\n title: 'inchworm'\n handle: 'carla", "end": 2456, "score": 0.9998838901519775, "start": 2445, "tag": "NAME", "value": "Carla Drago" }, { "context": "Drago'\n title: 'inchworm'\n handle: 'carlad'\n nationality: 'italy'\n country: 'g", "end": 2507, "score": 0.9952462911605835, "start": 2501, "tag": "USERNAME", "value": "carlad" }, { "context": " image: 'carla'\n },\n {\n name: 'Anja Reichmann'\n title: 'Tyranjasaurus Specs'\n han", "end": 2634, "score": 0.9998719096183777, "start": 2620, "tag": "NAME", "value": "Anja Reichmann" }, { "context": " title: 'Tyranjasaurus Specs'\n handle: '_tyranja_'\n nationality: 'germany'\n country:", "end": 2698, "score": 0.8668926358222961, "start": 2691, "tag": "USERNAME", "value": "tyranja" }, { "context": " image: 'anja'\n },\n {\n name: 'Aly Fulton'\n title: 'Resident Linguist'\n handl", "end": 2823, "score": 0.9998852610588074, "start": 2813, "tag": "NAME", "value": "Aly Fulton" }, { "context": " title: 'Resident Linguist'\n handle: 'sinthetix'\n nationality: 'usa'\n country: 'usa", "end": 2886, "score": 0.991313636302948, "start": 2877, "tag": "USERNAME", "value": "sinthetix" }, { "context": " image: 'aly'\n },\n {\n name: 'Amanda Quaranto'\n title: 'Crafting Extremist'\n hand", "end": 3006, "score": 0.9998871684074402, "start": 2991, "tag": "NAME", "value": "Amanda Quaranto" }, { "context": " title: 'Crafting Extremist'\n handle: 'aquaranto'\n nationality: 'usa'\n country: 'usa", "end": 3070, "score": 0.9870154857635498, "start": 3061, "tag": "USERNAME", "value": "aquaranto" }, { "context": " image: 'amanda'\n },\n {\n name: 'Jen Duke'\n title: 'Gastrognome'\n handle: 'du", "end": 3186, "score": 0.9998857975006104, "start": 3178, "tag": "NAME", "value": "Jen Duke" }, { "context": "ke'\n title: 'Gastrognome'\n handle: 'dukeofberlin'\n nationality: 'usa'\n country: 'ger", "end": 3246, "score": 0.988256573677063, "start": 3234, "tag": "USERNAME", "value": "dukeofberlin" }, { "context": " image: 'jen'\n },\n {\n name: 'Brandon Burton'\n title: 'Infrastructure Conductor'\n ", "end": 3369, "score": 0.9998770952224731, "start": 3355, "tag": "NAME", "value": "Brandon Burton" }, { "context": "itle: 'Infrastructure Conductor'\n handle: 'solarce'\n nationality: 'usa'\n country: 'usa", "end": 3437, "score": 0.7265132665634155, "start": 3430, "tag": "USERNAME", "value": "solarce" }, { "context": " image: 'brandon'\n },\n {\n name: 'Emma Trimble'\n title: 'Lead Pungineer'\n handle: ", "end": 3558, "score": 0.9998806118965149, "start": 3546, "tag": "NAME", "value": "Emma Trimble" }, { "context": "\n title: 'Lead Pungineer'\n handle: 'emdantrim'\n nationality: 'usa'\n country: 'usa", "end": 3618, "score": 0.963418185710907, "start": 3609, "tag": "USERNAME", "value": "emdantrim" }, { "context": " image: 'emma'\n },\n {\n name: 'María de Antón'\n title: 'Sous Chef at The Bloge'\n ", "end": 3738, "score": 0.9998646974563599, "start": 3724, "tag": "NAME", "value": "María de Antón" }, { "context": " title: 'Sous Chef at The Bloge'\n handle: 'amalulla'\n nationality: 'spain'\n country: 's", "end": 3805, "score": 0.9991385340690613, "start": 3797, "tag": "USERNAME", "value": "amalulla" }, { "context": " image: 'maria'\n },\n {\n name: 'Danish Khan'\n title: 'Red Shirt'\n handle: 'dani", "end": 3927, "score": 0.9998568296432495, "start": 3916, "tag": "NAME", "value": "Danish Khan" }, { "context": "Khan'\n title: 'Red Shirt'\n handle: 'danishkhan'\n nationality: 'usa'\n country: 'usa", "end": 3983, "score": 0.9995027184486389, "start": 3973, "tag": "USERNAME", "value": "danishkhan" }, { "context": " image: 'danish'\n },\n {\n name: 'Dominic Jodoin'\n title: 'Humble Tab Hoarder'\n hand", "end": 4105, "score": 0.9998534321784973, "start": 4091, "tag": "NAME", "value": "Dominic Jodoin" }, { "context": " title: 'Humble Tab Hoarder'\n handle: 'cotsog'\n nationality: 'canada'\n country: '", "end": 4166, "score": 0.9989243149757385, "start": 4160, "tag": "USERNAME", "value": "cotsog" }, { "context": " image: 'dominic'\n },\n {\n name: 'Liza Brisker'\n title: 'Brainy Trainee'\n national", "end": 4293, "score": 0.9998592138290405, "start": 4281, "tag": "NAME", "value": "Liza Brisker" } ]
app/routes/team.coffee
2947721120/travis-web
0
`import Ember from 'ember'` `import TravisRoute from 'travis/routes/basic'` Route = TravisRoute.extend needsAuth: false model: () -> [ { name: 'Sven Fuchs' title: 'The Original Builder' handle: 'svenfuchs' nationality: 'germany' country: 'germany' image: 'sven' }, { name: 'Josh Kalderimis' title: 'Chief Post-It Officer' handle: 'j2h' nationality: 'newzealand' country: 'germany' image: 'josh' }, { name: 'Fritz Thielemann' title: 'Admin Adventures' handle: 'fritzek' nationality: 'germany' country: 'germany' image: 'fritz' }, { name: 'Konstantin Haase' title: 'Haase of Pain' handle: 'konstantinhaase' nationality: 'germany' country: 'germany' image: 'konstantin' }, { name: 'Mathias Meyer' title: 'Director of Bacon Relations' handle: 'roidrage' nationality: 'germany' country: 'germany' image: 'mathias' }, { name: 'Piotr Sarnacki' title: 'Code Monkey' handle: 'drogus' nationality: 'poland' country: 'germany' image: 'piotr' }, { name: 'Anika Lindtner' title: 'Head Catwoman' handle: 'langziehohr' nationality: 'germany' country: 'germany' image: 'anika' }, { name: 'Henrik Hodne' title: 'Timezone Experimentalist' handle: 'henrikhodne' nationality: 'norway' country: 'norway' image: 'henrik' }, { name: 'Justine Arreche' title: 'Lead Clipart Strategist' handle: 'saltinejustine' nationality: 'usa' country: 'usa' image: 'justine' }, { name: 'Hiro Asari' title: 'International Man of IPAs' handle: 'hiro_asari' nationality: 'japan' country: 'usa' image: 'hiro' }, { name: 'Dan Buch' title: 'That\'s Numberwang' handle: 'meatballhat' nationality: 'usa' country: 'usa' image: 'dan' }, { name: 'Lisa Passing' title: 'Queen of !important' nationality: 'germany' country: 'germany' image: 'lisa' }, { name: 'Carla Drago' title: 'inchworm' handle: 'carlad' nationality: 'italy' country: 'germany' image: 'carla' }, { name: 'Anja Reichmann' title: 'Tyranjasaurus Specs' handle: '_tyranja_' nationality: 'germany' country: 'germany' image: 'anja' }, { name: 'Aly Fulton' title: 'Resident Linguist' handle: 'sinthetix' nationality: 'usa' country: 'usa' image: 'aly' }, { name: 'Amanda Quaranto' title: 'Crafting Extremist' handle: 'aquaranto' nationality: 'usa' country: 'usa' image: 'amanda' }, { name: 'Jen Duke' title: 'Gastrognome' handle: 'dukeofberlin' nationality: 'usa' country: 'germany' image: 'jen' }, { name: 'Brandon Burton' title: 'Infrastructure Conductor' handle: 'solarce' nationality: 'usa' country: 'usa' image: 'brandon' }, { name: 'Emma Trimble' title: 'Lead Pungineer' handle: 'emdantrim' nationality: 'usa' country: 'usa' image: 'emma' }, { name: 'María de Antón' title: 'Sous Chef at The Bloge' handle: 'amalulla' nationality: 'spain' country: 'spain' image: 'maria' }, { name: 'Danish Khan' title: 'Red Shirt' handle: 'danishkhan' nationality: 'usa' country: 'usa' image: 'danish' }, { name: 'Dominic Jodoin' title: 'Humble Tab Hoarder' handle: 'cotsog' nationality: 'canada' country: 'canada' image: 'dominic' }, { name: 'Liza Brisker' title: 'Brainy Trainee' nationality: 'russia' country: 'germany' image: 'liz' } ] `export default Route`
93004
`import Ember from 'ember'` `import TravisRoute from 'travis/routes/basic'` Route = TravisRoute.extend needsAuth: false model: () -> [ { name: '<NAME>' title: 'The Original Builder' handle: 'svenfuchs' nationality: 'germany' country: 'germany' image: 'sven' }, { name: '<NAME>' title: 'Chief Post-It Officer' handle: 'j2h' nationality: 'newzealand' country: 'germany' image: 'josh' }, { name: '<NAME>' title: 'Admin Adventures' handle: 'fritzek' nationality: 'germany' country: 'germany' image: 'fritz' }, { name: '<NAME>' title: 'Haase of Pain' handle: 'konstantinhaase' nationality: 'germany' country: 'germany' image: 'konstantin' }, { name: '<NAME>' title: 'Director of Bacon Relations' handle: 'roidrage' nationality: 'germany' country: 'germany' image: 'mathias' }, { name: '<NAME>' title: 'Code Monkey' handle: 'drogus' nationality: 'poland' country: 'germany' image: 'piotr' }, { name: '<NAME>' title: 'Head Catwoman' handle: 'langziehohr' nationality: 'germany' country: 'germany' image: 'anika' }, { name: '<NAME>' title: 'Timezone Experimentalist' handle: 'henrikhodne' nationality: 'norway' country: 'norway' image: 'henrik' }, { name: '<NAME>' title: 'Lead Clipart Strategist' handle: 'saltinejustine' nationality: 'usa' country: 'usa' image: 'justine' }, { name: '<NAME>' title: 'International Man of IPAs' handle: 'hiro_asari' nationality: 'japan' country: 'usa' image: 'hiro' }, { name: '<NAME>' title: 'That\'s Numberwang' handle: 'meatballhat' nationality: 'usa' country: 'usa' image: 'dan' }, { name: '<NAME>' title: 'Queen of !important' nationality: 'germany' country: 'germany' image: 'lisa' }, { name: '<NAME>' title: 'inchworm' handle: 'carlad' nationality: 'italy' country: 'germany' image: 'carla' }, { name: '<NAME>' title: 'Tyranjasaurus Specs' handle: '_tyranja_' nationality: 'germany' country: 'germany' image: 'anja' }, { name: '<NAME>' title: 'Resident Linguist' handle: 'sinthetix' nationality: 'usa' country: 'usa' image: 'aly' }, { name: '<NAME>' title: 'Crafting Extremist' handle: 'aquaranto' nationality: 'usa' country: 'usa' image: 'amanda' }, { name: '<NAME>' title: 'Gastrognome' handle: 'dukeofberlin' nationality: 'usa' country: 'germany' image: 'jen' }, { name: '<NAME>' title: 'Infrastructure Conductor' handle: 'solarce' nationality: 'usa' country: 'usa' image: 'brandon' }, { name: '<NAME>' title: 'Lead Pungineer' handle: 'emdantrim' nationality: 'usa' country: 'usa' image: 'emma' }, { name: '<NAME>' title: 'Sous Chef at The Bloge' handle: 'amalulla' nationality: 'spain' country: 'spain' image: 'maria' }, { name: '<NAME>' title: 'Red Shirt' handle: 'danishkhan' nationality: 'usa' country: 'usa' image: 'danish' }, { name: '<NAME>' title: 'Humble Tab Hoarder' handle: 'cotsog' nationality: 'canada' country: 'canada' image: 'dominic' }, { name: '<NAME>' title: 'Brainy Trainee' nationality: 'russia' country: 'germany' image: 'liz' } ] `export default Route`
true
`import Ember from 'ember'` `import TravisRoute from 'travis/routes/basic'` Route = TravisRoute.extend needsAuth: false model: () -> [ { name: 'PI:NAME:<NAME>END_PI' title: 'The Original Builder' handle: 'svenfuchs' nationality: 'germany' country: 'germany' image: 'sven' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Chief Post-It Officer' handle: 'j2h' nationality: 'newzealand' country: 'germany' image: 'josh' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Admin Adventures' handle: 'fritzek' nationality: 'germany' country: 'germany' image: 'fritz' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Haase of Pain' handle: 'konstantinhaase' nationality: 'germany' country: 'germany' image: 'konstantin' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Director of Bacon Relations' handle: 'roidrage' nationality: 'germany' country: 'germany' image: 'mathias' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Code Monkey' handle: 'drogus' nationality: 'poland' country: 'germany' image: 'piotr' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Head Catwoman' handle: 'langziehohr' nationality: 'germany' country: 'germany' image: 'anika' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Timezone Experimentalist' handle: 'henrikhodne' nationality: 'norway' country: 'norway' image: 'henrik' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Lead Clipart Strategist' handle: 'saltinejustine' nationality: 'usa' country: 'usa' image: 'justine' }, { name: 'PI:NAME:<NAME>END_PI' title: 'International Man of IPAs' handle: 'hiro_asari' nationality: 'japan' country: 'usa' image: 'hiro' }, { name: 'PI:NAME:<NAME>END_PI' title: 'That\'s Numberwang' handle: 'meatballhat' nationality: 'usa' country: 'usa' image: 'dan' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Queen of !important' nationality: 'germany' country: 'germany' image: 'lisa' }, { name: 'PI:NAME:<NAME>END_PI' title: 'inchworm' handle: 'carlad' nationality: 'italy' country: 'germany' image: 'carla' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Tyranjasaurus Specs' handle: '_tyranja_' nationality: 'germany' country: 'germany' image: 'anja' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Resident Linguist' handle: 'sinthetix' nationality: 'usa' country: 'usa' image: 'aly' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Crafting Extremist' handle: 'aquaranto' nationality: 'usa' country: 'usa' image: 'amanda' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Gastrognome' handle: 'dukeofberlin' nationality: 'usa' country: 'germany' image: 'jen' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Infrastructure Conductor' handle: 'solarce' nationality: 'usa' country: 'usa' image: 'brandon' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Lead Pungineer' handle: 'emdantrim' nationality: 'usa' country: 'usa' image: 'emma' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Sous Chef at The Bloge' handle: 'amalulla' nationality: 'spain' country: 'spain' image: 'maria' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Red Shirt' handle: 'danishkhan' nationality: 'usa' country: 'usa' image: 'danish' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Humble Tab Hoarder' handle: 'cotsog' nationality: 'canada' country: 'canada' image: 'dominic' }, { name: 'PI:NAME:<NAME>END_PI' title: 'Brainy Trainee' nationality: 'russia' country: 'germany' image: 'liz' } ] `export default Route`
[ { "context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio", "end": 30, "score": 0.999874472618103, "start": 17, "tag": "NAME", "value": "Joshua Carver" } ]
src/coffeescript/charts/grid.coffee
jcarver989/raphy-charts
5
# Copyright 2012 Joshua Carver # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Grid constructor: (@r, @width, @height, @points, @options) -> draw: -> grid_lines = Math.round(@points.length / @options.step_size) height = @height - @options.y_padding width = @width - @options.x_padding x_step_size = Math.round(width / grid_lines) y_step_size = Math.round(height / grid_lines) y = @options.y_padding paths = @r.set() for point, i in @points when i % @options.step_size == 0 x = @points[i].x paths.push @r.path("M #{x}, #{@options.y_padding} L #{x}, #{height} Z") for i in [0..grid_lines] paths.push @r.path("M #{@options.x_padding}, #{y} L #{width}, #{y} Z") if y <= height y += y_step_size paths.attr({ stroke: "#ccc" "stroke-width": 1 }).toBack()
207607
# Copyright 2012 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Grid constructor: (@r, @width, @height, @points, @options) -> draw: -> grid_lines = Math.round(@points.length / @options.step_size) height = @height - @options.y_padding width = @width - @options.x_padding x_step_size = Math.round(width / grid_lines) y_step_size = Math.round(height / grid_lines) y = @options.y_padding paths = @r.set() for point, i in @points when i % @options.step_size == 0 x = @points[i].x paths.push @r.path("M #{x}, #{@options.y_padding} L #{x}, #{height} Z") for i in [0..grid_lines] paths.push @r.path("M #{@options.x_padding}, #{y} L #{width}, #{y} Z") if y <= height y += y_step_size paths.attr({ stroke: "#ccc" "stroke-width": 1 }).toBack()
true
# Copyright 2012 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Grid constructor: (@r, @width, @height, @points, @options) -> draw: -> grid_lines = Math.round(@points.length / @options.step_size) height = @height - @options.y_padding width = @width - @options.x_padding x_step_size = Math.round(width / grid_lines) y_step_size = Math.round(height / grid_lines) y = @options.y_padding paths = @r.set() for point, i in @points when i % @options.step_size == 0 x = @points[i].x paths.push @r.path("M #{x}, #{@options.y_padding} L #{x}, #{height} Z") for i in [0..grid_lines] paths.push @r.path("M #{@options.x_padding}, #{y} L #{width}, #{y} Z") if y <= height y += y_step_size paths.attr({ stroke: "#ccc" "stroke-width": 1 }).toBack()
[ { "context": "s!\n# Entry for the GitHub Game Off 2013\n# Author : Paul Joannon for H-Bomb\n# <paul.joannon@gmail.com>\n##\n#####\n\nc", "end": 85, "score": 0.9998572468757629, "start": 73, "tag": "NAME", "value": "Paul Joannon" }, { "context": "e GitHub Game Off 2013\n# Author : Paul Joannon for H-Bomb\n# <paul.joannon@gmail.com>\n##\n#####\n\nclass DrawBa", "end": 96, "score": 0.8980622291564941, "start": 90, "tag": "NAME", "value": "H-Bomb" }, { "context": "me Off 2013\n# Author : Paul Joannon for H-Bomb\n# <paul.joannon@gmail.com>\n##\n#####\n\nclass DrawBatch\n constructor : ->\n ", "end": 122, "score": 0.9999246597290039, "start": 100, "tag": "EMAIL", "value": "paul.joannon@gmail.com" } ]
assets/js/coffee/game.coffee
MySweetWhomp/demcreepers
1
##### ## # Dem Creepers! # Entry for the GitHub Game Off 2013 # Author : Paul Joannon for H-Bomb # <paul.joannon@gmail.com> ## ##### class DrawBatch constructor : -> @_toDraw = [] add : (elem) => if jaws.isArray elem _.map elem, (e) => @_toDraw.push e else @_toDraw.push elem draw : (viewport) => @_toDraw = _.sortBy @_toDraw, (a) => if a._feets? (do a._feets.rect).bottom else if a._box? then (do a._box.rect).bottom else a.y _.map @_toDraw, (item) => do item.draw @_toDraw = [] class Game constructor : -> if jaws? jaws.preventDefaultKeys ['up', 'right', 'down', 'left', 'w', 'a', 's', 'd', 'space', 'left_mouse_button'] jaws.assets.add ['img/Barbarian.gif', 'img/Gob.gif', 'img/GobCorpse.gif', 'img/Axe.gif', 'img/HUD.gif', 'img/HUD---TEXT.gif', 'img/HUD-NUMBERSLETTERS.gif', 'audio/HIT.ogg', 'img/HUD-ANIMATED.gif', 'audio/WOOSH.ogg', 'img/GOLEM.gif', 'img/BG---Tiles.gif' 'img/Block.gif', 'audio/START.ogg', 'audio/GOLEMMORT.ogg', 'audio/GAME_LOOP.ogg', 'audio/MORT02.ogg', 'audio/GAMEOVER.ogg', 'audio/MORT01.ogg', 'img/HUD---PICTURES---V1.gif', 'audio/MENU.ogg'] else throw "Not Implemented" start : => jaws.start window.DemCreepers.MainGame class Utils pointDirection : do -> _RADTODEGRATIO = 57.29577951308232 (x1, y1, x2, y2) -> _RADTODEGRATIO * (Math.atan2 (y1 - y2), (x2 - x1)) pointOrientation : do -> _ORFROMDIR = [ 'E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE', 'E' ] (x1, y1, x2, y2) -> _ORFROMDIR[(Math.round ((@pointDirection x1, y1, x2, y2) / 45)) + 4] pointDistance : (aX, aY, bX, bY) -> x = if aX > bX then aX - bX else bX - aX y = if aY > bY then aY - bY else bY - aY parseInt Math.abs Math.sqrt (x * x) + (y * y) getTileId : (x) -> n = parseInt x if isNaN n 10 + (do (do x.toLowerCase).charCodeAt) - 97 # 97 is 'a' ASCII code else n getRandomSpawn : -> n = _.random 0, 7 if n is 0 [600, -200] else if n is 1 [1400, -200] else if n is 2 [1400, 450] else if n is 3 [1400, 1100] else if n is 4 [600, 1100] else if n is 5 [-200, 1100] else if n is 6 [-200, 450] else if n is 7 [-200, -200] getNextOr : (_or) -> if _or is 'N' ['NE','NW','E','W','SE','SW','S','N'] else if _or is 'NE' ['E','N','SE','NW','S','W','SW','NE'] else if _or is 'E' ['SE','NE','S','N','SW','SE','W','E'] else if _or is 'SE' ['S','E','SW','NE','W','N','NW','SE'] else if _or is 'S' ['SW','SE','W','E','NW','NE','N','S'] else if _or is 'SW' ['W','S','NW','SE','N','E','NE','SW'] else if _or is 'W' ['NW','SW','N','S','NE','SE','E','W'] else if _or is 'NW' ['N','W','NE','SW','S','E','SE','NW'] window.DemCreepers = Game : Game Utils : new Utils DrawBatch : new DrawBatch Config : ActiveControls : 1 TileSize : [50, 50] Volumes : FX : 0.1 Music : 0.4 Controls : [ { 'up' : 'w' 'right' : 'd' 'down' : 's' 'left' : 'a' } { 'up' : 'up' 'right' : 'right' 'down' : 'down' 'left' : 'left' } { 'up' : 'z' 'right' : 'd' 'down' : 's' 'left' : 'q' } ]
32438
##### ## # Dem Creepers! # Entry for the GitHub Game Off 2013 # Author : <NAME> for <NAME> # <<EMAIL>> ## ##### class DrawBatch constructor : -> @_toDraw = [] add : (elem) => if jaws.isArray elem _.map elem, (e) => @_toDraw.push e else @_toDraw.push elem draw : (viewport) => @_toDraw = _.sortBy @_toDraw, (a) => if a._feets? (do a._feets.rect).bottom else if a._box? then (do a._box.rect).bottom else a.y _.map @_toDraw, (item) => do item.draw @_toDraw = [] class Game constructor : -> if jaws? jaws.preventDefaultKeys ['up', 'right', 'down', 'left', 'w', 'a', 's', 'd', 'space', 'left_mouse_button'] jaws.assets.add ['img/Barbarian.gif', 'img/Gob.gif', 'img/GobCorpse.gif', 'img/Axe.gif', 'img/HUD.gif', 'img/HUD---TEXT.gif', 'img/HUD-NUMBERSLETTERS.gif', 'audio/HIT.ogg', 'img/HUD-ANIMATED.gif', 'audio/WOOSH.ogg', 'img/GOLEM.gif', 'img/BG---Tiles.gif' 'img/Block.gif', 'audio/START.ogg', 'audio/GOLEMMORT.ogg', 'audio/GAME_LOOP.ogg', 'audio/MORT02.ogg', 'audio/GAMEOVER.ogg', 'audio/MORT01.ogg', 'img/HUD---PICTURES---V1.gif', 'audio/MENU.ogg'] else throw "Not Implemented" start : => jaws.start window.DemCreepers.MainGame class Utils pointDirection : do -> _RADTODEGRATIO = 57.29577951308232 (x1, y1, x2, y2) -> _RADTODEGRATIO * (Math.atan2 (y1 - y2), (x2 - x1)) pointOrientation : do -> _ORFROMDIR = [ 'E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE', 'E' ] (x1, y1, x2, y2) -> _ORFROMDIR[(Math.round ((@pointDirection x1, y1, x2, y2) / 45)) + 4] pointDistance : (aX, aY, bX, bY) -> x = if aX > bX then aX - bX else bX - aX y = if aY > bY then aY - bY else bY - aY parseInt Math.abs Math.sqrt (x * x) + (y * y) getTileId : (x) -> n = parseInt x if isNaN n 10 + (do (do x.toLowerCase).charCodeAt) - 97 # 97 is 'a' ASCII code else n getRandomSpawn : -> n = _.random 0, 7 if n is 0 [600, -200] else if n is 1 [1400, -200] else if n is 2 [1400, 450] else if n is 3 [1400, 1100] else if n is 4 [600, 1100] else if n is 5 [-200, 1100] else if n is 6 [-200, 450] else if n is 7 [-200, -200] getNextOr : (_or) -> if _or is 'N' ['NE','NW','E','W','SE','SW','S','N'] else if _or is 'NE' ['E','N','SE','NW','S','W','SW','NE'] else if _or is 'E' ['SE','NE','S','N','SW','SE','W','E'] else if _or is 'SE' ['S','E','SW','NE','W','N','NW','SE'] else if _or is 'S' ['SW','SE','W','E','NW','NE','N','S'] else if _or is 'SW' ['W','S','NW','SE','N','E','NE','SW'] else if _or is 'W' ['NW','SW','N','S','NE','SE','E','W'] else if _or is 'NW' ['N','W','NE','SW','S','E','SE','NW'] window.DemCreepers = Game : Game Utils : new Utils DrawBatch : new DrawBatch Config : ActiveControls : 1 TileSize : [50, 50] Volumes : FX : 0.1 Music : 0.4 Controls : [ { 'up' : 'w' 'right' : 'd' 'down' : 's' 'left' : 'a' } { 'up' : 'up' 'right' : 'right' 'down' : 'down' 'left' : 'left' } { 'up' : 'z' 'right' : 'd' 'down' : 's' 'left' : 'q' } ]
true
##### ## # Dem Creepers! # Entry for the GitHub Game Off 2013 # Author : PI:NAME:<NAME>END_PI for PI:NAME:<NAME>END_PI # <PI:EMAIL:<EMAIL>END_PI> ## ##### class DrawBatch constructor : -> @_toDraw = [] add : (elem) => if jaws.isArray elem _.map elem, (e) => @_toDraw.push e else @_toDraw.push elem draw : (viewport) => @_toDraw = _.sortBy @_toDraw, (a) => if a._feets? (do a._feets.rect).bottom else if a._box? then (do a._box.rect).bottom else a.y _.map @_toDraw, (item) => do item.draw @_toDraw = [] class Game constructor : -> if jaws? jaws.preventDefaultKeys ['up', 'right', 'down', 'left', 'w', 'a', 's', 'd', 'space', 'left_mouse_button'] jaws.assets.add ['img/Barbarian.gif', 'img/Gob.gif', 'img/GobCorpse.gif', 'img/Axe.gif', 'img/HUD.gif', 'img/HUD---TEXT.gif', 'img/HUD-NUMBERSLETTERS.gif', 'audio/HIT.ogg', 'img/HUD-ANIMATED.gif', 'audio/WOOSH.ogg', 'img/GOLEM.gif', 'img/BG---Tiles.gif' 'img/Block.gif', 'audio/START.ogg', 'audio/GOLEMMORT.ogg', 'audio/GAME_LOOP.ogg', 'audio/MORT02.ogg', 'audio/GAMEOVER.ogg', 'audio/MORT01.ogg', 'img/HUD---PICTURES---V1.gif', 'audio/MENU.ogg'] else throw "Not Implemented" start : => jaws.start window.DemCreepers.MainGame class Utils pointDirection : do -> _RADTODEGRATIO = 57.29577951308232 (x1, y1, x2, y2) -> _RADTODEGRATIO * (Math.atan2 (y1 - y2), (x2 - x1)) pointOrientation : do -> _ORFROMDIR = [ 'E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE', 'E' ] (x1, y1, x2, y2) -> _ORFROMDIR[(Math.round ((@pointDirection x1, y1, x2, y2) / 45)) + 4] pointDistance : (aX, aY, bX, bY) -> x = if aX > bX then aX - bX else bX - aX y = if aY > bY then aY - bY else bY - aY parseInt Math.abs Math.sqrt (x * x) + (y * y) getTileId : (x) -> n = parseInt x if isNaN n 10 + (do (do x.toLowerCase).charCodeAt) - 97 # 97 is 'a' ASCII code else n getRandomSpawn : -> n = _.random 0, 7 if n is 0 [600, -200] else if n is 1 [1400, -200] else if n is 2 [1400, 450] else if n is 3 [1400, 1100] else if n is 4 [600, 1100] else if n is 5 [-200, 1100] else if n is 6 [-200, 450] else if n is 7 [-200, -200] getNextOr : (_or) -> if _or is 'N' ['NE','NW','E','W','SE','SW','S','N'] else if _or is 'NE' ['E','N','SE','NW','S','W','SW','NE'] else if _or is 'E' ['SE','NE','S','N','SW','SE','W','E'] else if _or is 'SE' ['S','E','SW','NE','W','N','NW','SE'] else if _or is 'S' ['SW','SE','W','E','NW','NE','N','S'] else if _or is 'SW' ['W','S','NW','SE','N','E','NE','SW'] else if _or is 'W' ['NW','SW','N','S','NE','SE','E','W'] else if _or is 'NW' ['N','W','NE','SW','S','E','SE','NW'] window.DemCreepers = Game : Game Utils : new Utils DrawBatch : new DrawBatch Config : ActiveControls : 1 TileSize : [50, 50] Volumes : FX : 0.1 Music : 0.4 Controls : [ { 'up' : 'w' 'right' : 'd' 'down' : 's' 'left' : 'a' } { 'up' : 'up' 'right' : 'right' 'down' : 'down' 'left' : 'left' } { 'up' : 'z' 'right' : 'd' 'down' : 's' 'left' : 'q' } ]
[ { "context": "m popular definition for the term.\n#\n# Author:\n# Kevin Qiu\n#\n# FIXME merge with urban.coffee\n\njsdom = requir", "end": 246, "score": 0.9998505711555481, "start": 237, "tag": "NAME", "value": "Kevin Qiu" } ]
src/scripts/whatis.coffee
contolini/hubot-scripts
1,450
# Description: # None # # Dependencies: # "jsdom": "0.2.14" # # Configuration: # None # # Commands: # hubot whatis <term> - search the term on urbandictionary.com and get a random popular definition for the term. # # Author: # Kevin Qiu # # FIXME merge with urban.coffee jsdom = require('jsdom').jsdom module.exports = (robot) -> robot.respond /whatis (.+)$/i, (msg) -> msg .http('http://www.urbandictionary.com/define.php?term=' + (encodeURIComponent msg.match[1])) .get() (err, res, body) -> window = (jsdom body, null, features : FetchExternalResources : false ProcessExternalResources : false MutationEvents : false QuerySelector : false ).createWindow() $ = require('jquery').create(window) definitions = [] $(".meaning").each (idx, item) -> definitions.push $(item).text() msgText = if definitions.length==0 then "No definition found." else (msg.random definitions) msg.send msgText
113403
# Description: # None # # Dependencies: # "jsdom": "0.2.14" # # Configuration: # None # # Commands: # hubot whatis <term> - search the term on urbandictionary.com and get a random popular definition for the term. # # Author: # <NAME> # # FIXME merge with urban.coffee jsdom = require('jsdom').jsdom module.exports = (robot) -> robot.respond /whatis (.+)$/i, (msg) -> msg .http('http://www.urbandictionary.com/define.php?term=' + (encodeURIComponent msg.match[1])) .get() (err, res, body) -> window = (jsdom body, null, features : FetchExternalResources : false ProcessExternalResources : false MutationEvents : false QuerySelector : false ).createWindow() $ = require('jquery').create(window) definitions = [] $(".meaning").each (idx, item) -> definitions.push $(item).text() msgText = if definitions.length==0 then "No definition found." else (msg.random definitions) msg.send msgText
true
# Description: # None # # Dependencies: # "jsdom": "0.2.14" # # Configuration: # None # # Commands: # hubot whatis <term> - search the term on urbandictionary.com and get a random popular definition for the term. # # Author: # PI:NAME:<NAME>END_PI # # FIXME merge with urban.coffee jsdom = require('jsdom').jsdom module.exports = (robot) -> robot.respond /whatis (.+)$/i, (msg) -> msg .http('http://www.urbandictionary.com/define.php?term=' + (encodeURIComponent msg.match[1])) .get() (err, res, body) -> window = (jsdom body, null, features : FetchExternalResources : false ProcessExternalResources : false MutationEvents : false QuerySelector : false ).createWindow() $ = require('jquery').create(window) definitions = [] $(".meaning").each (idx, item) -> definitions.push $(item).text() msgText = if definitions.length==0 then "No definition found." else (msg.random definitions) msg.send msgText
[ { "context": " requestAnimFrame shim\n copy the one from paul irish\n###\nwindow.requestAnimFrame = do ->\n window.requ", "end": 93, "score": 0.5058414936065674, "start": 90, "tag": "NAME", "value": "ish" } ]
src/waveform.coffee
samcrosoft/waveformjs
6
Observant = require('observant') ### requestAnimFrame shim copy the one from paul irish ### window.requestAnimFrame = do -> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (callback) -> window.setTimeout callback, 1000 / 30 return # start of waveform class class Waveform extends Observant # opacity settings Waveform.DEFAULT_MAX_OPACITY = 1 Waveform.DEFAULT_MIN_OPACITY = 0.2 ### create color constants ### Waveform.WAVE_FOCUS = 'wave-focus' Waveform.WAVE = 'wave' Waveform.WAVE_ACTIVE = 'wave-active' Waveform.WAVE_SELECTED = 'wave-selected' Waveform.GUTTER = 'gutter' Waveform.GUTTER_ACTIVE = 'gutter-active' Waveform.GUTTER_SELECTED = 'gutter-selected' Waveform.REFLECTION = 'reflection' Waveform.REFLECTION_ACTIVE = 'reflection-active' ### create events constants ### Waveform.EVENT_READY = "ready" Waveform.EVENT_CLICK = "click" Waveform.EVENT_HOVER = "hover" Waveform.EVENT_RESIZED = "hover" constructor: (options) -> # initiate observable super() @container = options.container @canvas = options.canvas @data = options.data or [] @wavesCollection = @data @outerColor = options.outerColor or 'transparent' @reflection = options.reflection or 0 @interpolate = options.interpolate or true @bindResize = options.bindResize or false @fadeOpacity = options.fadeOpacity or Waveform.DEFAULT_MAX_OPACITY if(isNaN(@fadeOpacity)) throw new Error 'Fade Opacity Can Only Be A Number' else if @fadeOpacity < Waveform.DEFAULT_MIN_OPACITY or @fadeOpacity > Waveform.DEFAULT_MAX_OPACITY throw new Error "Fade Opacity Can Only Be A Number Between #{Waveform.DEFAULT_MIN_OPACITY} and #{Waveform.DEFAULT_MAX_OPACITY}" ### Cater for data interpolation right here ### if options.interpolate == false @interpolate = false if not @canvas if @container @canvas = @createCanvas(@container, options.width or @container.clientWidth, options.height or @container.clientHeight) else throw new Error 'Either canvas or container option must be passed' # add this for real in production to support IE # @patchCanvasForIE @canvas @context = @canvas.getContext('2d') @width = parseInt(@context.canvas.width, 10) @height = parseInt(@context.canvas.height, 10) #custom Talk @waveWidth = 2 @iGutterWidth = 1 @colors = {} # holds events @events = {} #active = highlighted section of track @active = -1 #slected = dimmer highlighted selections @selected = -1 #mouse dragging @isDragging = false #is playing @isPlaying = false @hasStartedPlaying = null #is in focus @isFocus = false # kick-start the process @initialize() return # initialize the whole process initialize: () -> # update height @updateHeight() # set the colors @setColors() # bind the event handler @bindEventHandlers() # Cache the waveform data @cache() # draw the waveform @redraw() # bind event for container redraw if @bindResize is on then @bindContainerResize() @fireEvent(Waveform.EVENT_READY) return ### this will make sure the container is bound to resize event ### bindContainerResize: () -> window.addEventListener("resize", ()=> iContWidth = @container.clientWidth @update(width: iContWidth) @redraw() @notify(Waveform.EVENT_RESIZED, iContWidth) ) return ### this method will set the colors to the main colors ### setColors: () -> @setColor(Waveform.WAVE_FOCUS, '#333333') @setGradient(Waveform.WAVE, ['#666666', 0, '#868686', 1]) @setGradient(Waveform.WAVE_ACTIVE, ['#FF3300', 0, '#FF5100', 1]) @setGradient(Waveform.WAVE_SELECTED, ['#993016', 0, '#973C15', 1]) @setGradient(Waveform.GUTTER, ['#6B6B6B', 0, '#c9c9c9', 1]) @setGradient(Waveform.GUTTER_ACTIVE, ['#FF3704', 0, '#FF8F63', 1]) @setGradient(Waveform.GUTTER_SELECTED, ['#9A371E', 0, '#CE9E8A', 1]) @setColor(Waveform.REFLECTION, '#999999') @setColor(Waveform.REFLECTION_ACTIVE, '#FFC0A0') return setColor: (name, color) -> @colors[name] = color setGradient: (name, colors) -> gradient = @context.createLinearGradient(0, @waveOffset, 0, 0) i = 0 while i < colors.length gradient.addColorStop colors[i + 1], colors[i] i += 2 @colors[name] = gradient return ### This will draw the waveform ### redraw: () -> requestAnimationFrame (@render) return # this will draw the waveform really render: () => i = 0 ref = @wavesCollection t = @width / @data.length # this should be reconsidered xPos = 0 # start from farthest left yPos = @waveOffset # clear the entire canvas for redraw @clear() j = 0 len = ref.length while j < len d = ref[j] dNext = ref[j + 1] ### Draw the wave here ### if @selected > 0 and (@selected <= j and j < @active) or (@selected > j and j >= @active) @context.fillStyle = @colors[Waveform.WAVE_SELECTED] else if @active > j @context.fillStyle = @colors[Waveform.WAVE_ACTIVE] else @context.fillStyle = @colors[Waveform.WAVE_FOCUS] @context.fillRect xPos, yPos, @waveWidth, d ### draw the gutter ### # if is hovered if @selected > 0 and (@selected <= j and j < @active) or (@selected > j and j >= @active) @context.fillStyle = @colors[Waveform.GUTTER_SELECTED] else if @active > j @context.fillStyle = @colors[Waveform.GUTTER_ACTIVE] else @context.fillStyle = @colors[Waveform.GUTTER] # smallest wave between butter is gutters height # note: Math.max because wave values are negative gutterX = Math.max d, dNext @context.fillRect(xPos + @waveWidth, yPos, @iGutterWidth, gutterX) ### draw the reflection ### # reflection wave if @reflection > 0 reflectionHeight = Math.abs(d) / (1 - (@reflection)) * @reflection if @active > i @context.fillStyle = @colors[Waveform.REFLECTION_ACTIVE] else @context.fillStyle = @colors[Waveform.REFLECTION] # draw reflection @context.fillRect xPos, yPos, @waveWidth, reflectionHeight #increment the x-axis position xPos += @waveWidth + @iGutterWidth j++ clear: () -> @context.fillStyle = @outerColor @context.clearRect(0, 0, @width, @height) @context.fillRect(0, 0, @width, @height) ### Data related codes ### setData: (data) -> @data = data getData: () -> @data setDataInterpolated: (data) -> @setData @interpolateArray(data, @width) setDataCropped: (data) -> @setData @expandArray(data, @width) linearInterpolate: (before, after, atPoint) -> before + (after - before) * atPoint; expandArray: (data, limit, defaultValue) -> i = undefined j = undefined newData = undefined ref = undefined if defaultValue == null defaultValue = 0.0 newData = [] if data.length > limit newData = data.slice(data.length - limit, data.length) else i = j = 0 ref = limit - 1 while (if 0 <= ref then j <= ref else j >= ref) newData[i] = data[i] or defaultValue i = (if 0 <= ref then ++j else --j) newData interpolateArray: (data, fitCount) -> after = undefined atPoint = undefined before = undefined i = undefined newData = undefined springFactor = undefined tmp = undefined newData = [] springFactor = new Number((data.length - 1) / (fitCount - 1)) newData[0] = data[0] i = 1 while i < fitCount - 1 tmp = i * springFactor before = new Number(Math.floor(tmp)).toFixed() after = new Number(Math.ceil(tmp)).toFixed() atPoint = tmp - before newData[i] = @linearInterpolate(data[before], data[after], atPoint) i++ newData[fitCount - 1] = data[data.length - 1] newData putDataIntoWaveBlock: () -> iWaveBlock = @waveWidth + @iGutterWidth data = @getData() newDataBlocks = [] iWaveCount = Math.ceil data.length / iWaveBlock i = 0 while i < iWaveCount sum = 0 j = 0 while j < iWaveBlock key = (i * iWaveBlock) + j sum += data[key] j++ fAverage = (sum / iWaveBlock ) fAbsValue = fAverage * @waveHeight # push it into the new block fWavePoint = Math.floor(-Math.abs(fAbsValue)) newDataBlocks.push fWavePoint # newDataBlocks.push Math.abs fAverage i++ # ... newDataBlocks cache: () -> if @interpolate == false @setDataCropped @data else @setDataInterpolated @data # split the data into waves collection @wavesCollection = @putDataIntoWaveBlock @data return ### Data update details here ### update: (options) -> if options if options.gutterWidth @gutterWidth = options.gutterWidth if options.waveWidth @waveWidth = options.waveWidth if options.width @width = options.width @canvas.width = @width if options.height @height = options.height @canvas.height = @height if options.reflection == 0 or options.reflection @reflection = options.reflection if options.interpolate @interpolate = @options.interpolate ### Re-calculate the wave block formations once one of the following is altered ### if options.gutterWidth or options.waveWidth or options.width or options.height or options.reflection or options.interpolate or options.reflection == 0 @cache() if options.height or options.reflection or options.reflection == 0 @updateHeight() #redraw the waveform @redraw() return updateHeight: () -> @waveOffset = Math.round(@height - (@height * @reflection)) @reflectionHeight = Math.round(@height - @waveOffset) @waveHeight = @height - @reflectionHeight return # patchCanvasForIE = (canvas) -> # oldGetContext = undefined # if typeof window.G_vmlCanvasManager != 'undefined' # canvas = window.G_vmlCanvasManager.initElement(canvas) # oldGetContext = canvas.getContext # return # canvas.getContext = (a) -> # ctx = undefined # ctx = oldGetContext.apply(canvas, arguments) # canvas.getContext = oldGetContext # ctx # return createCanvas: (container, width, height) -> canvas = document.createElement "canvas" container.appendChild canvas canvas.width = width canvas.height = height return canvas ### Events related ### getMouseClickPosition: (evt)-> canvas = @canvas rect = canvas.getBoundingClientRect() # { # x: evt.clientX - (rect.left) # y: evt.clientY - (rect.top) # } x = Math.round((evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width) y = Math.round((evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height) return [x, y] calcPercent: -> Math.round @clickPercent * @width / (@waveWidth + @iGutterWidth) # new fire event to use observables fireEvent: (name, data...) -> @notify(name, data) return # bind the event handlers bindEventHandlers: () -> @canvas.addEventListener('mousedown', @onMouseDown) @canvas.addEventListener('mousemove', @onMouseOver) @canvas.addEventListener('mouseout', @onMouseOut) @canvas.addEventListener('mouseup', @onMouseUp) onMouseOut: (e) => @selected = -1 @redrawWithAlpha(1) # redraw back to full opacity return onMouseUp: (e) => @isDragging = false return # this will be true if the waveform has been paused after it has started playing isPausedAfterPlaying: () -> return @hasStartedPlaying is on and @isPaused() is on # redraw the canvas with alpha redrawWithAlpha: (iAlpha = Waveform.DEFAULT_MAX_OPACITY) -> # if the alpha has changed, then redraw if iAlpha isnt @fadeOpacity @context.globalAlpha = iAlpha @redraw() onMouseOver: (e) => # do not perform hover animation if waveform is paused if @isPausedAfterPlaying() @redrawWithAlpha(@fadeOpacity) # redraw with faded opacity return on aPos = @getMouseClickPosition(e) x = aPos[0] waveClicked = @getWaveClicked(x) mousePosTrackTime = @getMousePosTrackTime(x) @fireEvent Waveform.EVENT_HOVER, mousePosTrackTime, waveClicked if @isDragging == true @selected = -1 @clickPercent = x / @width @active = @calcPercent() else @selected = waveClicked @context.globalAlpha = 1 @redraw() return onMouseDown: (e) => @isDragging = true aPos = @getMouseClickPosition(e) x = aPos[0] @clickPercent = x / @width # this will fire the percentage clicked on the waveform @fireEvent Waveform.EVENT_CLICK, (@clickPercent * 100) @active = @calcPercent() @redraw() return ### this is to simulate play ### setPlaying: (val = on) -> @isPlaying = val return setPaused: () -> @setPlaying off return isPaused: () -> @active > 0 and @isPlaying is off # an alias to play progress play: (perct) -> @playProgress(perct) return pause: () -> @setPaused() console.log "is paused is ", @isPaused() return playProgress: (perct) -> # indicate that it has started playing if @hasStartedPlaying is null @hasStartedPlaying = on # set playing to true if @isPlaying is off @setPlaying on iActive = Math.round((perct / 100 ) * @wavesCollection.length) @active = iActive @redraw() return # this is relative to the waves collection calcPercent: -> Math.round @clickPercent * @width / (@waveWidth + @iGutterWidth) getWaveClicked: (x) -> waveClicked = Math.round(x / (@waveWidth + @iGutterWidth)) wavesCollection = @wavesCollection fReturn = 0 if waveClicked > wavesCollection.length fReturn = wavesCollection.length else if waveClicked < 0 fReturn = 0 else fReturn = waveClicked fReturn getMousePosTrackTime: (x) -> mousePosTrackTime = @trackLength / @wavesCollection.length * @getWaveClicked(x) fReturn = 0 if mousePosTrackTime > @trackLength fReturn = @trackLength else if mousePosTrackTime < 0 fReturn = 0 else fReturn = mousePosTrackTime fReturn #if typeof module is "object" and module.exports then `export default Waveform` module.exports = Waveform # export waveform to window global.window.Waveform = Waveform
118850
Observant = require('observant') ### requestAnimFrame shim copy the one from paul ir<NAME> ### window.requestAnimFrame = do -> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (callback) -> window.setTimeout callback, 1000 / 30 return # start of waveform class class Waveform extends Observant # opacity settings Waveform.DEFAULT_MAX_OPACITY = 1 Waveform.DEFAULT_MIN_OPACITY = 0.2 ### create color constants ### Waveform.WAVE_FOCUS = 'wave-focus' Waveform.WAVE = 'wave' Waveform.WAVE_ACTIVE = 'wave-active' Waveform.WAVE_SELECTED = 'wave-selected' Waveform.GUTTER = 'gutter' Waveform.GUTTER_ACTIVE = 'gutter-active' Waveform.GUTTER_SELECTED = 'gutter-selected' Waveform.REFLECTION = 'reflection' Waveform.REFLECTION_ACTIVE = 'reflection-active' ### create events constants ### Waveform.EVENT_READY = "ready" Waveform.EVENT_CLICK = "click" Waveform.EVENT_HOVER = "hover" Waveform.EVENT_RESIZED = "hover" constructor: (options) -> # initiate observable super() @container = options.container @canvas = options.canvas @data = options.data or [] @wavesCollection = @data @outerColor = options.outerColor or 'transparent' @reflection = options.reflection or 0 @interpolate = options.interpolate or true @bindResize = options.bindResize or false @fadeOpacity = options.fadeOpacity or Waveform.DEFAULT_MAX_OPACITY if(isNaN(@fadeOpacity)) throw new Error 'Fade Opacity Can Only Be A Number' else if @fadeOpacity < Waveform.DEFAULT_MIN_OPACITY or @fadeOpacity > Waveform.DEFAULT_MAX_OPACITY throw new Error "Fade Opacity Can Only Be A Number Between #{Waveform.DEFAULT_MIN_OPACITY} and #{Waveform.DEFAULT_MAX_OPACITY}" ### Cater for data interpolation right here ### if options.interpolate == false @interpolate = false if not @canvas if @container @canvas = @createCanvas(@container, options.width or @container.clientWidth, options.height or @container.clientHeight) else throw new Error 'Either canvas or container option must be passed' # add this for real in production to support IE # @patchCanvasForIE @canvas @context = @canvas.getContext('2d') @width = parseInt(@context.canvas.width, 10) @height = parseInt(@context.canvas.height, 10) #custom Talk @waveWidth = 2 @iGutterWidth = 1 @colors = {} # holds events @events = {} #active = highlighted section of track @active = -1 #slected = dimmer highlighted selections @selected = -1 #mouse dragging @isDragging = false #is playing @isPlaying = false @hasStartedPlaying = null #is in focus @isFocus = false # kick-start the process @initialize() return # initialize the whole process initialize: () -> # update height @updateHeight() # set the colors @setColors() # bind the event handler @bindEventHandlers() # Cache the waveform data @cache() # draw the waveform @redraw() # bind event for container redraw if @bindResize is on then @bindContainerResize() @fireEvent(Waveform.EVENT_READY) return ### this will make sure the container is bound to resize event ### bindContainerResize: () -> window.addEventListener("resize", ()=> iContWidth = @container.clientWidth @update(width: iContWidth) @redraw() @notify(Waveform.EVENT_RESIZED, iContWidth) ) return ### this method will set the colors to the main colors ### setColors: () -> @setColor(Waveform.WAVE_FOCUS, '#333333') @setGradient(Waveform.WAVE, ['#666666', 0, '#868686', 1]) @setGradient(Waveform.WAVE_ACTIVE, ['#FF3300', 0, '#FF5100', 1]) @setGradient(Waveform.WAVE_SELECTED, ['#993016', 0, '#973C15', 1]) @setGradient(Waveform.GUTTER, ['#6B6B6B', 0, '#c9c9c9', 1]) @setGradient(Waveform.GUTTER_ACTIVE, ['#FF3704', 0, '#FF8F63', 1]) @setGradient(Waveform.GUTTER_SELECTED, ['#9A371E', 0, '#CE9E8A', 1]) @setColor(Waveform.REFLECTION, '#999999') @setColor(Waveform.REFLECTION_ACTIVE, '#FFC0A0') return setColor: (name, color) -> @colors[name] = color setGradient: (name, colors) -> gradient = @context.createLinearGradient(0, @waveOffset, 0, 0) i = 0 while i < colors.length gradient.addColorStop colors[i + 1], colors[i] i += 2 @colors[name] = gradient return ### This will draw the waveform ### redraw: () -> requestAnimationFrame (@render) return # this will draw the waveform really render: () => i = 0 ref = @wavesCollection t = @width / @data.length # this should be reconsidered xPos = 0 # start from farthest left yPos = @waveOffset # clear the entire canvas for redraw @clear() j = 0 len = ref.length while j < len d = ref[j] dNext = ref[j + 1] ### Draw the wave here ### if @selected > 0 and (@selected <= j and j < @active) or (@selected > j and j >= @active) @context.fillStyle = @colors[Waveform.WAVE_SELECTED] else if @active > j @context.fillStyle = @colors[Waveform.WAVE_ACTIVE] else @context.fillStyle = @colors[Waveform.WAVE_FOCUS] @context.fillRect xPos, yPos, @waveWidth, d ### draw the gutter ### # if is hovered if @selected > 0 and (@selected <= j and j < @active) or (@selected > j and j >= @active) @context.fillStyle = @colors[Waveform.GUTTER_SELECTED] else if @active > j @context.fillStyle = @colors[Waveform.GUTTER_ACTIVE] else @context.fillStyle = @colors[Waveform.GUTTER] # smallest wave between butter is gutters height # note: Math.max because wave values are negative gutterX = Math.max d, dNext @context.fillRect(xPos + @waveWidth, yPos, @iGutterWidth, gutterX) ### draw the reflection ### # reflection wave if @reflection > 0 reflectionHeight = Math.abs(d) / (1 - (@reflection)) * @reflection if @active > i @context.fillStyle = @colors[Waveform.REFLECTION_ACTIVE] else @context.fillStyle = @colors[Waveform.REFLECTION] # draw reflection @context.fillRect xPos, yPos, @waveWidth, reflectionHeight #increment the x-axis position xPos += @waveWidth + @iGutterWidth j++ clear: () -> @context.fillStyle = @outerColor @context.clearRect(0, 0, @width, @height) @context.fillRect(0, 0, @width, @height) ### Data related codes ### setData: (data) -> @data = data getData: () -> @data setDataInterpolated: (data) -> @setData @interpolateArray(data, @width) setDataCropped: (data) -> @setData @expandArray(data, @width) linearInterpolate: (before, after, atPoint) -> before + (after - before) * atPoint; expandArray: (data, limit, defaultValue) -> i = undefined j = undefined newData = undefined ref = undefined if defaultValue == null defaultValue = 0.0 newData = [] if data.length > limit newData = data.slice(data.length - limit, data.length) else i = j = 0 ref = limit - 1 while (if 0 <= ref then j <= ref else j >= ref) newData[i] = data[i] or defaultValue i = (if 0 <= ref then ++j else --j) newData interpolateArray: (data, fitCount) -> after = undefined atPoint = undefined before = undefined i = undefined newData = undefined springFactor = undefined tmp = undefined newData = [] springFactor = new Number((data.length - 1) / (fitCount - 1)) newData[0] = data[0] i = 1 while i < fitCount - 1 tmp = i * springFactor before = new Number(Math.floor(tmp)).toFixed() after = new Number(Math.ceil(tmp)).toFixed() atPoint = tmp - before newData[i] = @linearInterpolate(data[before], data[after], atPoint) i++ newData[fitCount - 1] = data[data.length - 1] newData putDataIntoWaveBlock: () -> iWaveBlock = @waveWidth + @iGutterWidth data = @getData() newDataBlocks = [] iWaveCount = Math.ceil data.length / iWaveBlock i = 0 while i < iWaveCount sum = 0 j = 0 while j < iWaveBlock key = (i * iWaveBlock) + j sum += data[key] j++ fAverage = (sum / iWaveBlock ) fAbsValue = fAverage * @waveHeight # push it into the new block fWavePoint = Math.floor(-Math.abs(fAbsValue)) newDataBlocks.push fWavePoint # newDataBlocks.push Math.abs fAverage i++ # ... newDataBlocks cache: () -> if @interpolate == false @setDataCropped @data else @setDataInterpolated @data # split the data into waves collection @wavesCollection = @putDataIntoWaveBlock @data return ### Data update details here ### update: (options) -> if options if options.gutterWidth @gutterWidth = options.gutterWidth if options.waveWidth @waveWidth = options.waveWidth if options.width @width = options.width @canvas.width = @width if options.height @height = options.height @canvas.height = @height if options.reflection == 0 or options.reflection @reflection = options.reflection if options.interpolate @interpolate = @options.interpolate ### Re-calculate the wave block formations once one of the following is altered ### if options.gutterWidth or options.waveWidth or options.width or options.height or options.reflection or options.interpolate or options.reflection == 0 @cache() if options.height or options.reflection or options.reflection == 0 @updateHeight() #redraw the waveform @redraw() return updateHeight: () -> @waveOffset = Math.round(@height - (@height * @reflection)) @reflectionHeight = Math.round(@height - @waveOffset) @waveHeight = @height - @reflectionHeight return # patchCanvasForIE = (canvas) -> # oldGetContext = undefined # if typeof window.G_vmlCanvasManager != 'undefined' # canvas = window.G_vmlCanvasManager.initElement(canvas) # oldGetContext = canvas.getContext # return # canvas.getContext = (a) -> # ctx = undefined # ctx = oldGetContext.apply(canvas, arguments) # canvas.getContext = oldGetContext # ctx # return createCanvas: (container, width, height) -> canvas = document.createElement "canvas" container.appendChild canvas canvas.width = width canvas.height = height return canvas ### Events related ### getMouseClickPosition: (evt)-> canvas = @canvas rect = canvas.getBoundingClientRect() # { # x: evt.clientX - (rect.left) # y: evt.clientY - (rect.top) # } x = Math.round((evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width) y = Math.round((evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height) return [x, y] calcPercent: -> Math.round @clickPercent * @width / (@waveWidth + @iGutterWidth) # new fire event to use observables fireEvent: (name, data...) -> @notify(name, data) return # bind the event handlers bindEventHandlers: () -> @canvas.addEventListener('mousedown', @onMouseDown) @canvas.addEventListener('mousemove', @onMouseOver) @canvas.addEventListener('mouseout', @onMouseOut) @canvas.addEventListener('mouseup', @onMouseUp) onMouseOut: (e) => @selected = -1 @redrawWithAlpha(1) # redraw back to full opacity return onMouseUp: (e) => @isDragging = false return # this will be true if the waveform has been paused after it has started playing isPausedAfterPlaying: () -> return @hasStartedPlaying is on and @isPaused() is on # redraw the canvas with alpha redrawWithAlpha: (iAlpha = Waveform.DEFAULT_MAX_OPACITY) -> # if the alpha has changed, then redraw if iAlpha isnt @fadeOpacity @context.globalAlpha = iAlpha @redraw() onMouseOver: (e) => # do not perform hover animation if waveform is paused if @isPausedAfterPlaying() @redrawWithAlpha(@fadeOpacity) # redraw with faded opacity return on aPos = @getMouseClickPosition(e) x = aPos[0] waveClicked = @getWaveClicked(x) mousePosTrackTime = @getMousePosTrackTime(x) @fireEvent Waveform.EVENT_HOVER, mousePosTrackTime, waveClicked if @isDragging == true @selected = -1 @clickPercent = x / @width @active = @calcPercent() else @selected = waveClicked @context.globalAlpha = 1 @redraw() return onMouseDown: (e) => @isDragging = true aPos = @getMouseClickPosition(e) x = aPos[0] @clickPercent = x / @width # this will fire the percentage clicked on the waveform @fireEvent Waveform.EVENT_CLICK, (@clickPercent * 100) @active = @calcPercent() @redraw() return ### this is to simulate play ### setPlaying: (val = on) -> @isPlaying = val return setPaused: () -> @setPlaying off return isPaused: () -> @active > 0 and @isPlaying is off # an alias to play progress play: (perct) -> @playProgress(perct) return pause: () -> @setPaused() console.log "is paused is ", @isPaused() return playProgress: (perct) -> # indicate that it has started playing if @hasStartedPlaying is null @hasStartedPlaying = on # set playing to true if @isPlaying is off @setPlaying on iActive = Math.round((perct / 100 ) * @wavesCollection.length) @active = iActive @redraw() return # this is relative to the waves collection calcPercent: -> Math.round @clickPercent * @width / (@waveWidth + @iGutterWidth) getWaveClicked: (x) -> waveClicked = Math.round(x / (@waveWidth + @iGutterWidth)) wavesCollection = @wavesCollection fReturn = 0 if waveClicked > wavesCollection.length fReturn = wavesCollection.length else if waveClicked < 0 fReturn = 0 else fReturn = waveClicked fReturn getMousePosTrackTime: (x) -> mousePosTrackTime = @trackLength / @wavesCollection.length * @getWaveClicked(x) fReturn = 0 if mousePosTrackTime > @trackLength fReturn = @trackLength else if mousePosTrackTime < 0 fReturn = 0 else fReturn = mousePosTrackTime fReturn #if typeof module is "object" and module.exports then `export default Waveform` module.exports = Waveform # export waveform to window global.window.Waveform = Waveform
true
Observant = require('observant') ### requestAnimFrame shim copy the one from paul irPI:NAME:<NAME>END_PI ### window.requestAnimFrame = do -> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (callback) -> window.setTimeout callback, 1000 / 30 return # start of waveform class class Waveform extends Observant # opacity settings Waveform.DEFAULT_MAX_OPACITY = 1 Waveform.DEFAULT_MIN_OPACITY = 0.2 ### create color constants ### Waveform.WAVE_FOCUS = 'wave-focus' Waveform.WAVE = 'wave' Waveform.WAVE_ACTIVE = 'wave-active' Waveform.WAVE_SELECTED = 'wave-selected' Waveform.GUTTER = 'gutter' Waveform.GUTTER_ACTIVE = 'gutter-active' Waveform.GUTTER_SELECTED = 'gutter-selected' Waveform.REFLECTION = 'reflection' Waveform.REFLECTION_ACTIVE = 'reflection-active' ### create events constants ### Waveform.EVENT_READY = "ready" Waveform.EVENT_CLICK = "click" Waveform.EVENT_HOVER = "hover" Waveform.EVENT_RESIZED = "hover" constructor: (options) -> # initiate observable super() @container = options.container @canvas = options.canvas @data = options.data or [] @wavesCollection = @data @outerColor = options.outerColor or 'transparent' @reflection = options.reflection or 0 @interpolate = options.interpolate or true @bindResize = options.bindResize or false @fadeOpacity = options.fadeOpacity or Waveform.DEFAULT_MAX_OPACITY if(isNaN(@fadeOpacity)) throw new Error 'Fade Opacity Can Only Be A Number' else if @fadeOpacity < Waveform.DEFAULT_MIN_OPACITY or @fadeOpacity > Waveform.DEFAULT_MAX_OPACITY throw new Error "Fade Opacity Can Only Be A Number Between #{Waveform.DEFAULT_MIN_OPACITY} and #{Waveform.DEFAULT_MAX_OPACITY}" ### Cater for data interpolation right here ### if options.interpolate == false @interpolate = false if not @canvas if @container @canvas = @createCanvas(@container, options.width or @container.clientWidth, options.height or @container.clientHeight) else throw new Error 'Either canvas or container option must be passed' # add this for real in production to support IE # @patchCanvasForIE @canvas @context = @canvas.getContext('2d') @width = parseInt(@context.canvas.width, 10) @height = parseInt(@context.canvas.height, 10) #custom Talk @waveWidth = 2 @iGutterWidth = 1 @colors = {} # holds events @events = {} #active = highlighted section of track @active = -1 #slected = dimmer highlighted selections @selected = -1 #mouse dragging @isDragging = false #is playing @isPlaying = false @hasStartedPlaying = null #is in focus @isFocus = false # kick-start the process @initialize() return # initialize the whole process initialize: () -> # update height @updateHeight() # set the colors @setColors() # bind the event handler @bindEventHandlers() # Cache the waveform data @cache() # draw the waveform @redraw() # bind event for container redraw if @bindResize is on then @bindContainerResize() @fireEvent(Waveform.EVENT_READY) return ### this will make sure the container is bound to resize event ### bindContainerResize: () -> window.addEventListener("resize", ()=> iContWidth = @container.clientWidth @update(width: iContWidth) @redraw() @notify(Waveform.EVENT_RESIZED, iContWidth) ) return ### this method will set the colors to the main colors ### setColors: () -> @setColor(Waveform.WAVE_FOCUS, '#333333') @setGradient(Waveform.WAVE, ['#666666', 0, '#868686', 1]) @setGradient(Waveform.WAVE_ACTIVE, ['#FF3300', 0, '#FF5100', 1]) @setGradient(Waveform.WAVE_SELECTED, ['#993016', 0, '#973C15', 1]) @setGradient(Waveform.GUTTER, ['#6B6B6B', 0, '#c9c9c9', 1]) @setGradient(Waveform.GUTTER_ACTIVE, ['#FF3704', 0, '#FF8F63', 1]) @setGradient(Waveform.GUTTER_SELECTED, ['#9A371E', 0, '#CE9E8A', 1]) @setColor(Waveform.REFLECTION, '#999999') @setColor(Waveform.REFLECTION_ACTIVE, '#FFC0A0') return setColor: (name, color) -> @colors[name] = color setGradient: (name, colors) -> gradient = @context.createLinearGradient(0, @waveOffset, 0, 0) i = 0 while i < colors.length gradient.addColorStop colors[i + 1], colors[i] i += 2 @colors[name] = gradient return ### This will draw the waveform ### redraw: () -> requestAnimationFrame (@render) return # this will draw the waveform really render: () => i = 0 ref = @wavesCollection t = @width / @data.length # this should be reconsidered xPos = 0 # start from farthest left yPos = @waveOffset # clear the entire canvas for redraw @clear() j = 0 len = ref.length while j < len d = ref[j] dNext = ref[j + 1] ### Draw the wave here ### if @selected > 0 and (@selected <= j and j < @active) or (@selected > j and j >= @active) @context.fillStyle = @colors[Waveform.WAVE_SELECTED] else if @active > j @context.fillStyle = @colors[Waveform.WAVE_ACTIVE] else @context.fillStyle = @colors[Waveform.WAVE_FOCUS] @context.fillRect xPos, yPos, @waveWidth, d ### draw the gutter ### # if is hovered if @selected > 0 and (@selected <= j and j < @active) or (@selected > j and j >= @active) @context.fillStyle = @colors[Waveform.GUTTER_SELECTED] else if @active > j @context.fillStyle = @colors[Waveform.GUTTER_ACTIVE] else @context.fillStyle = @colors[Waveform.GUTTER] # smallest wave between butter is gutters height # note: Math.max because wave values are negative gutterX = Math.max d, dNext @context.fillRect(xPos + @waveWidth, yPos, @iGutterWidth, gutterX) ### draw the reflection ### # reflection wave if @reflection > 0 reflectionHeight = Math.abs(d) / (1 - (@reflection)) * @reflection if @active > i @context.fillStyle = @colors[Waveform.REFLECTION_ACTIVE] else @context.fillStyle = @colors[Waveform.REFLECTION] # draw reflection @context.fillRect xPos, yPos, @waveWidth, reflectionHeight #increment the x-axis position xPos += @waveWidth + @iGutterWidth j++ clear: () -> @context.fillStyle = @outerColor @context.clearRect(0, 0, @width, @height) @context.fillRect(0, 0, @width, @height) ### Data related codes ### setData: (data) -> @data = data getData: () -> @data setDataInterpolated: (data) -> @setData @interpolateArray(data, @width) setDataCropped: (data) -> @setData @expandArray(data, @width) linearInterpolate: (before, after, atPoint) -> before + (after - before) * atPoint; expandArray: (data, limit, defaultValue) -> i = undefined j = undefined newData = undefined ref = undefined if defaultValue == null defaultValue = 0.0 newData = [] if data.length > limit newData = data.slice(data.length - limit, data.length) else i = j = 0 ref = limit - 1 while (if 0 <= ref then j <= ref else j >= ref) newData[i] = data[i] or defaultValue i = (if 0 <= ref then ++j else --j) newData interpolateArray: (data, fitCount) -> after = undefined atPoint = undefined before = undefined i = undefined newData = undefined springFactor = undefined tmp = undefined newData = [] springFactor = new Number((data.length - 1) / (fitCount - 1)) newData[0] = data[0] i = 1 while i < fitCount - 1 tmp = i * springFactor before = new Number(Math.floor(tmp)).toFixed() after = new Number(Math.ceil(tmp)).toFixed() atPoint = tmp - before newData[i] = @linearInterpolate(data[before], data[after], atPoint) i++ newData[fitCount - 1] = data[data.length - 1] newData putDataIntoWaveBlock: () -> iWaveBlock = @waveWidth + @iGutterWidth data = @getData() newDataBlocks = [] iWaveCount = Math.ceil data.length / iWaveBlock i = 0 while i < iWaveCount sum = 0 j = 0 while j < iWaveBlock key = (i * iWaveBlock) + j sum += data[key] j++ fAverage = (sum / iWaveBlock ) fAbsValue = fAverage * @waveHeight # push it into the new block fWavePoint = Math.floor(-Math.abs(fAbsValue)) newDataBlocks.push fWavePoint # newDataBlocks.push Math.abs fAverage i++ # ... newDataBlocks cache: () -> if @interpolate == false @setDataCropped @data else @setDataInterpolated @data # split the data into waves collection @wavesCollection = @putDataIntoWaveBlock @data return ### Data update details here ### update: (options) -> if options if options.gutterWidth @gutterWidth = options.gutterWidth if options.waveWidth @waveWidth = options.waveWidth if options.width @width = options.width @canvas.width = @width if options.height @height = options.height @canvas.height = @height if options.reflection == 0 or options.reflection @reflection = options.reflection if options.interpolate @interpolate = @options.interpolate ### Re-calculate the wave block formations once one of the following is altered ### if options.gutterWidth or options.waveWidth or options.width or options.height or options.reflection or options.interpolate or options.reflection == 0 @cache() if options.height or options.reflection or options.reflection == 0 @updateHeight() #redraw the waveform @redraw() return updateHeight: () -> @waveOffset = Math.round(@height - (@height * @reflection)) @reflectionHeight = Math.round(@height - @waveOffset) @waveHeight = @height - @reflectionHeight return # patchCanvasForIE = (canvas) -> # oldGetContext = undefined # if typeof window.G_vmlCanvasManager != 'undefined' # canvas = window.G_vmlCanvasManager.initElement(canvas) # oldGetContext = canvas.getContext # return # canvas.getContext = (a) -> # ctx = undefined # ctx = oldGetContext.apply(canvas, arguments) # canvas.getContext = oldGetContext # ctx # return createCanvas: (container, width, height) -> canvas = document.createElement "canvas" container.appendChild canvas canvas.width = width canvas.height = height return canvas ### Events related ### getMouseClickPosition: (evt)-> canvas = @canvas rect = canvas.getBoundingClientRect() # { # x: evt.clientX - (rect.left) # y: evt.clientY - (rect.top) # } x = Math.round((evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width) y = Math.round((evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height) return [x, y] calcPercent: -> Math.round @clickPercent * @width / (@waveWidth + @iGutterWidth) # new fire event to use observables fireEvent: (name, data...) -> @notify(name, data) return # bind the event handlers bindEventHandlers: () -> @canvas.addEventListener('mousedown', @onMouseDown) @canvas.addEventListener('mousemove', @onMouseOver) @canvas.addEventListener('mouseout', @onMouseOut) @canvas.addEventListener('mouseup', @onMouseUp) onMouseOut: (e) => @selected = -1 @redrawWithAlpha(1) # redraw back to full opacity return onMouseUp: (e) => @isDragging = false return # this will be true if the waveform has been paused after it has started playing isPausedAfterPlaying: () -> return @hasStartedPlaying is on and @isPaused() is on # redraw the canvas with alpha redrawWithAlpha: (iAlpha = Waveform.DEFAULT_MAX_OPACITY) -> # if the alpha has changed, then redraw if iAlpha isnt @fadeOpacity @context.globalAlpha = iAlpha @redraw() onMouseOver: (e) => # do not perform hover animation if waveform is paused if @isPausedAfterPlaying() @redrawWithAlpha(@fadeOpacity) # redraw with faded opacity return on aPos = @getMouseClickPosition(e) x = aPos[0] waveClicked = @getWaveClicked(x) mousePosTrackTime = @getMousePosTrackTime(x) @fireEvent Waveform.EVENT_HOVER, mousePosTrackTime, waveClicked if @isDragging == true @selected = -1 @clickPercent = x / @width @active = @calcPercent() else @selected = waveClicked @context.globalAlpha = 1 @redraw() return onMouseDown: (e) => @isDragging = true aPos = @getMouseClickPosition(e) x = aPos[0] @clickPercent = x / @width # this will fire the percentage clicked on the waveform @fireEvent Waveform.EVENT_CLICK, (@clickPercent * 100) @active = @calcPercent() @redraw() return ### this is to simulate play ### setPlaying: (val = on) -> @isPlaying = val return setPaused: () -> @setPlaying off return isPaused: () -> @active > 0 and @isPlaying is off # an alias to play progress play: (perct) -> @playProgress(perct) return pause: () -> @setPaused() console.log "is paused is ", @isPaused() return playProgress: (perct) -> # indicate that it has started playing if @hasStartedPlaying is null @hasStartedPlaying = on # set playing to true if @isPlaying is off @setPlaying on iActive = Math.round((perct / 100 ) * @wavesCollection.length) @active = iActive @redraw() return # this is relative to the waves collection calcPercent: -> Math.round @clickPercent * @width / (@waveWidth + @iGutterWidth) getWaveClicked: (x) -> waveClicked = Math.round(x / (@waveWidth + @iGutterWidth)) wavesCollection = @wavesCollection fReturn = 0 if waveClicked > wavesCollection.length fReturn = wavesCollection.length else if waveClicked < 0 fReturn = 0 else fReturn = waveClicked fReturn getMousePosTrackTime: (x) -> mousePosTrackTime = @trackLength / @wavesCollection.length * @getWaveClicked(x) fReturn = 0 if mousePosTrackTime > @trackLength fReturn = @trackLength else if mousePosTrackTime < 0 fReturn = 0 else fReturn = mousePosTrackTime fReturn #if typeof module is "object" and module.exports then `export default Waveform` module.exports = Waveform # export waveform to window global.window.Waveform = Waveform
[ { "context": "rogress bar, according to Material Design\n\n@author Roelof Roos (https://github.com/roelofr)\n###\n\n{View} = requir", "end": 92, "score": 0.9998828768730164, "start": 81, "tag": "NAME", "value": "Roelof Roos" }, { "context": "l Design\n\n@author Roelof Roos (https://github.com/roelofr)\n###\n\n{View} = require 'space-pen'\n\nmodule.export", "end": 120, "score": 0.9996461272239685, "start": 113, "tag": "USERNAME", "value": "roelofr" } ]
lib/views/progressbar.coffee
roelofr/php-report
0
### PHP Report indeterminate progress bar, according to Material Design @author Roelof Roos (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class Progressbar extends View @content: -> @div class: 'php-report__progress', => @div class: 'php-report__progress-inner', => @span class: 'indeterminate' initialize: (phpReport) -> phpReport.on('start', => @show()) phpReport.on('stop', => @hide()) hide: -> @addClass 'php-report__progress--hidden' show: -> @removeClass 'php-report__progress--hidden'
148363
### PHP Report indeterminate progress bar, according to Material Design @author <NAME> (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class Progressbar extends View @content: -> @div class: 'php-report__progress', => @div class: 'php-report__progress-inner', => @span class: 'indeterminate' initialize: (phpReport) -> phpReport.on('start', => @show()) phpReport.on('stop', => @hide()) hide: -> @addClass 'php-report__progress--hidden' show: -> @removeClass 'php-report__progress--hidden'
true
### PHP Report indeterminate progress bar, according to Material Design @author PI:NAME:<NAME>END_PI (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class Progressbar extends View @content: -> @div class: 'php-report__progress', => @div class: 'php-report__progress-inner', => @span class: 'indeterminate' initialize: (phpReport) -> phpReport.on('start', => @show()) phpReport.on('stop', => @hide()) hide: -> @addClass 'php-report__progress--hidden' show: -> @removeClass 'php-report__progress--hidden'
[ { "context": "###\n fixtures\n###\nusername = \"user1@tiktai.lt\"\nuser = Meteor.users.findOne($or: [{username: use", "end": 46, "score": 0.9999241828918457, "start": 31, "tag": "EMAIL", "value": "user1@tiktai.lt" }, { "context": "i.lt\"\nuser = Meteor.users.findOne($or: [{username: username},{\"emails.address\" : username}]);\nif user\n userI", "end": 101, "score": 0.9953411221504211, "start": 93, "tag": "USERNAME", "value": "username" }, { "context": "\nelse\n userId = Accounts.createUser\n username: username\n password: \"aaa\"\n\nid = Locations.insert {\n ts", "end": 222, "score": 0.9973735809326172, "start": 214, "tag": "USERNAME", "value": "username" }, { "context": ".createUser\n username: username\n password: \"aaa\"\n\nid = Locations.insert {\n tsi: new Date()\n use", "end": 241, "score": 0.9992725253105164, "start": 238, "tag": "PASSWORD", "value": "aaa" }, { "context": "0695 ]\n}\n\nMeteor.users.remove {\"emails.address\": \"user3@tiktai.lt\"}\n\n#d \"Location inserted for #{userId}\", id\n\nTiny", "end": 412, "score": 0.9999293684959412, "start": 397, "tag": "EMAIL", "value": "user3@tiktai.lt" }, { "context": "pi/access_token'), {\n params:\n username: \"user1@tiktai.lt\"\n password: \"aaa\"\n }, (error, result) ->\n ", "end": 673, "score": 0.99992436170578, "start": 658, "tag": "EMAIL", "value": "user1@tiktai.lt" }, { "context": " username: \"user1@tiktai.lt\"\n password: \"aaa\"\n }, (error, result) ->\n #d \"Authentication r", "end": 695, "score": 0.9993557333946228, "start": 692, "tag": "PASSWORD", "value": "aaa" }, { "context": "l('/api/account'), {\n params:\n username: \"user3@tiktai.lt\"\n password: \"aaa\"\n name: \"RegistrationT", "end": 1324, "score": 0.9999276995658875, "start": 1309, "tag": "EMAIL", "value": "user3@tiktai.lt" }, { "context": " username: \"user3@tiktai.lt\"\n password: \"aaa\"\n name: \"RegistrationTest\"\n }, (error, resu", "end": 1346, "score": 0.9993017911911011, "start": 1343, "tag": "PASSWORD", "value": "aaa" } ]
src/packages/carpool-api/carpool-api-tests.coffee
ArnoldasSid/vilnius-carpool
11
### fixtures ### username = "user1@tiktai.lt" user = Meteor.users.findOne($or: [{username: username},{"emails.address" : username}]); if user userId = user._id else userId = Accounts.createUser username: username password: "aaa" id = Locations.insert { tsi: new Date() userId: userId loc: [ 25.272159576416016, 54.69387649850695 ] } Meteor.users.remove {"emails.address": "user3@tiktai.lt"} #d "Location inserted for #{userId}", id Tinytest.addAsync "API - get protected resource", (test, onComplete)-> #d "Test fn:", _(test).functions(); HTTP.call "GET", Meteor.absoluteUrl('/api/access_token'), { params: username: "user1@tiktai.lt" password: "aaa" }, (error, result) -> #d "Authentication result:", result, error test.isNull(error) test.isUndefined(result.data.error); token = result.data.token test.isNotNull(token) HTTP.call "GET", Meteor.absoluteUrl("/api/user/#{result.data.id}/location"), { params: access_token: token }, (error, result) -> #d "Got response", result test.isNull(error) test.isUndefined(result.data.error); onComplete(); Tinytest.addAsync "API - register user", (test, onComplete)-> HTTP.call "POST", Meteor.absoluteUrl('/api/account'), { params: username: "user3@tiktai.lt" password: "aaa" name: "RegistrationTest" }, (error, result) -> #console.log("Register user result:", result, error) test.isNull(error) test.isUndefined(result.data?.error); onComplete();
67632
### fixtures ### username = "<EMAIL>" user = Meteor.users.findOne($or: [{username: username},{"emails.address" : username}]); if user userId = user._id else userId = Accounts.createUser username: username password: "<PASSWORD>" id = Locations.insert { tsi: new Date() userId: userId loc: [ 25.272159576416016, 54.69387649850695 ] } Meteor.users.remove {"emails.address": "<EMAIL>"} #d "Location inserted for #{userId}", id Tinytest.addAsync "API - get protected resource", (test, onComplete)-> #d "Test fn:", _(test).functions(); HTTP.call "GET", Meteor.absoluteUrl('/api/access_token'), { params: username: "<EMAIL>" password: "<PASSWORD>" }, (error, result) -> #d "Authentication result:", result, error test.isNull(error) test.isUndefined(result.data.error); token = result.data.token test.isNotNull(token) HTTP.call "GET", Meteor.absoluteUrl("/api/user/#{result.data.id}/location"), { params: access_token: token }, (error, result) -> #d "Got response", result test.isNull(error) test.isUndefined(result.data.error); onComplete(); Tinytest.addAsync "API - register user", (test, onComplete)-> HTTP.call "POST", Meteor.absoluteUrl('/api/account'), { params: username: "<EMAIL>" password: "<PASSWORD>" name: "RegistrationTest" }, (error, result) -> #console.log("Register user result:", result, error) test.isNull(error) test.isUndefined(result.data?.error); onComplete();
true
### fixtures ### username = "PI:EMAIL:<EMAIL>END_PI" user = Meteor.users.findOne($or: [{username: username},{"emails.address" : username}]); if user userId = user._id else userId = Accounts.createUser username: username password: "PI:PASSWORD:<PASSWORD>END_PI" id = Locations.insert { tsi: new Date() userId: userId loc: [ 25.272159576416016, 54.69387649850695 ] } Meteor.users.remove {"emails.address": "PI:EMAIL:<EMAIL>END_PI"} #d "Location inserted for #{userId}", id Tinytest.addAsync "API - get protected resource", (test, onComplete)-> #d "Test fn:", _(test).functions(); HTTP.call "GET", Meteor.absoluteUrl('/api/access_token'), { params: username: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" }, (error, result) -> #d "Authentication result:", result, error test.isNull(error) test.isUndefined(result.data.error); token = result.data.token test.isNotNull(token) HTTP.call "GET", Meteor.absoluteUrl("/api/user/#{result.data.id}/location"), { params: access_token: token }, (error, result) -> #d "Got response", result test.isNull(error) test.isUndefined(result.data.error); onComplete(); Tinytest.addAsync "API - register user", (test, onComplete)-> HTTP.call "POST", Meteor.absoluteUrl('/api/account'), { params: username: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" name: "RegistrationTest" }, (error, result) -> #console.log("Register user result:", result, error) test.isNull(error) test.isUndefined(result.data?.error); onComplete();
[ { "context": " instance of Validator, it's a validator.\n@author: Christopher Thorn\n###\n{check, sanitize} = require 'validator'\n\nmodu", "end": 227, "score": 0.9998751878738403, "start": 210, "tag": "NAME", "value": "Christopher Thorn" } ]
node_modules_koding/bongo/lib/validator/inbuilts.coffee
ezgikaysi/koding
1
### Bongo.js Unfancy models for MongoDB @description: inbuilt validators and filters @convention: if it's a function, it's a filter, if it's an array, or an instance of Validator, it's a validator. @author: Christopher Thorn ### {check, sanitize} = require 'validator' module.exports = email: [ 'not an email address.' (value)-> do check(value).isEmail ] url: [ 'not a valid url' (value)-> do check(value).isUrl ] enum: [ 'nonenumerated value.' (set, value)-> value in set ] pattern: [ "doesn't match." (pattern, value)-> pattern.test value ] required: [ 'missed a required field.' (value)-> !!value ] validate: [ "doesn't validate." (userFn, value)-> userFn value, check ] xss:(string)-> do sanitize(string).xss
198666
### Bongo.js Unfancy models for MongoDB @description: inbuilt validators and filters @convention: if it's a function, it's a filter, if it's an array, or an instance of Validator, it's a validator. @author: <NAME> ### {check, sanitize} = require 'validator' module.exports = email: [ 'not an email address.' (value)-> do check(value).isEmail ] url: [ 'not a valid url' (value)-> do check(value).isUrl ] enum: [ 'nonenumerated value.' (set, value)-> value in set ] pattern: [ "doesn't match." (pattern, value)-> pattern.test value ] required: [ 'missed a required field.' (value)-> !!value ] validate: [ "doesn't validate." (userFn, value)-> userFn value, check ] xss:(string)-> do sanitize(string).xss
true
### Bongo.js Unfancy models for MongoDB @description: inbuilt validators and filters @convention: if it's a function, it's a filter, if it's an array, or an instance of Validator, it's a validator. @author: PI:NAME:<NAME>END_PI ### {check, sanitize} = require 'validator' module.exports = email: [ 'not an email address.' (value)-> do check(value).isEmail ] url: [ 'not a valid url' (value)-> do check(value).isUrl ] enum: [ 'nonenumerated value.' (set, value)-> value in set ] pattern: [ "doesn't match." (pattern, value)-> pattern.test value ] required: [ 'missed a required field.' (value)-> !!value ] validate: [ "doesn't validate." (userFn, value)-> userFn value, check ] xss:(string)-> do sanitize(string).xss
[ { "context": "r.Model\n # @index [[\"firstName\", \"asc\"], [\"lastName\", \"asc\"]], unique: true\n # \n # @example Emb", "end": 376, "score": 0.5956198573112488, "start": 368, "tag": "NAME", "value": "lastName" } ]
src/tower/model/indexing.coffee
vjsingh/tower
1
# @mixin Tower.Model.Indexing = ClassMethods: # Add indexing to the model. # # @todo # # @example Simple field # class App.User extends Tower.Model # @index "ssn", unique: true, background: true # # @example Indexing on multiple fields # class App.User extends Tower.Model # @index [["firstName", "asc"], ["lastName", "asc"]], unique: true # # @example Embedded field # class App.User extends Tower.Model # @hasMany "locations", embed: true # @index "locations.city" # # @example Geospatial indexing # class App.Location extends Tower.Model # @field "coordinates", type: "Array" # @index [["coordinates", "2d"]], min: 200, max: 200 # # @example Index a relationship # class App.Location extends Tower.Model # @belongsTo "user", index: true # # @param [String] key name of the index # @param [Object] options name of the index # # @option options [Boolean] unique whether the index has to be unique or not index: (name, options = {}) -> # options.name = name @store().addIndex(name) @indexes()[name] = options indexes: -> @metadata().indexes module.exports = Tower.Model.Indexing
150516
# @mixin Tower.Model.Indexing = ClassMethods: # Add indexing to the model. # # @todo # # @example Simple field # class App.User extends Tower.Model # @index "ssn", unique: true, background: true # # @example Indexing on multiple fields # class App.User extends Tower.Model # @index [["firstName", "asc"], ["<NAME>", "asc"]], unique: true # # @example Embedded field # class App.User extends Tower.Model # @hasMany "locations", embed: true # @index "locations.city" # # @example Geospatial indexing # class App.Location extends Tower.Model # @field "coordinates", type: "Array" # @index [["coordinates", "2d"]], min: 200, max: 200 # # @example Index a relationship # class App.Location extends Tower.Model # @belongsTo "user", index: true # # @param [String] key name of the index # @param [Object] options name of the index # # @option options [Boolean] unique whether the index has to be unique or not index: (name, options = {}) -> # options.name = name @store().addIndex(name) @indexes()[name] = options indexes: -> @metadata().indexes module.exports = Tower.Model.Indexing
true
# @mixin Tower.Model.Indexing = ClassMethods: # Add indexing to the model. # # @todo # # @example Simple field # class App.User extends Tower.Model # @index "ssn", unique: true, background: true # # @example Indexing on multiple fields # class App.User extends Tower.Model # @index [["firstName", "asc"], ["PI:NAME:<NAME>END_PI", "asc"]], unique: true # # @example Embedded field # class App.User extends Tower.Model # @hasMany "locations", embed: true # @index "locations.city" # # @example Geospatial indexing # class App.Location extends Tower.Model # @field "coordinates", type: "Array" # @index [["coordinates", "2d"]], min: 200, max: 200 # # @example Index a relationship # class App.Location extends Tower.Model # @belongsTo "user", index: true # # @param [String] key name of the index # @param [Object] options name of the index # # @option options [Boolean] unique whether the index has to be unique or not index: (name, options = {}) -> # options.name = name @store().addIndex(name) @indexes()[name] = options indexes: -> @metadata().indexes module.exports = Tower.Model.Indexing
[ { "context": "()\n token = privateKey.decrypt(encryptedToken).toString()\n\n options =\n baseUrl: @dropboxServiceUr", "end": 1216, "score": 0.7141614556312561, "start": 1208, "tag": "KEY", "value": "toString" } ]
src/services/dropbox-link-service.coffee
octoblu/dropbox-link-service
0
MeshbluHttp = require 'meshblu-http' request = require 'request' class DropboxLinkService constructor: ({@meshbluConfig,@dropboxServiceUri}) -> generate: ({token,path,fileName}, callback) => meshbluHttp = new MeshbluHttp @meshbluConfig privateKey = meshbluHttp.setPrivateKey @meshbluConfig.privateKey encryptedToken = privateKey.encrypt token, 'base64' encryptedPath = privateKey.encrypt path, 'base64' meshbluHttp.register dropbox: {encryptedToken,encryptedPath}, (error, device) => return callback @_createError 500, error.message if error? link = "https://#{device.uuid}:#{device.token}@dropbox-link.octoblu.com/meshblu/links" callback null, {link,fileName} download: ({meshbluAuth}, callback) => {device} = meshbluAuth {encryptedToken,encryptedPath} = device.dropbox return callback @_createError 422, 'Invalid Device' unless encryptedPath? return callback @_createError 422, 'Invalid Device' unless encryptedToken? meshbluHttp = new MeshbluHttp @meshbluConfig privateKey = meshbluHttp.setPrivateKey @meshbluConfig.privateKey path = privateKey.decrypt(encryptedPath).toString() token = privateKey.decrypt(encryptedToken).toString() options = baseUrl: @dropboxServiceUri uri: "/1/media/auto/#{path}" auth: bearer: token json: true request.post options, (error, response, body) => return callback @_createError 500, error.message if error? return callback @_createError response.statusCode, body if response.statusCode > 299 meshbluHttp = new MeshbluHttp meshbluAuth meshbluHttp.unregister uuid: meshbluAuth.uuid, (error) => return callback @_createError 500, error.message if error? callback null, request.get body.url _createError: (code, message) => error = new Error message error.code = code if code? return error module.exports = DropboxLinkService
60182
MeshbluHttp = require 'meshblu-http' request = require 'request' class DropboxLinkService constructor: ({@meshbluConfig,@dropboxServiceUri}) -> generate: ({token,path,fileName}, callback) => meshbluHttp = new MeshbluHttp @meshbluConfig privateKey = meshbluHttp.setPrivateKey @meshbluConfig.privateKey encryptedToken = privateKey.encrypt token, 'base64' encryptedPath = privateKey.encrypt path, 'base64' meshbluHttp.register dropbox: {encryptedToken,encryptedPath}, (error, device) => return callback @_createError 500, error.message if error? link = "https://#{device.uuid}:#{device.token}@dropbox-link.octoblu.com/meshblu/links" callback null, {link,fileName} download: ({meshbluAuth}, callback) => {device} = meshbluAuth {encryptedToken,encryptedPath} = device.dropbox return callback @_createError 422, 'Invalid Device' unless encryptedPath? return callback @_createError 422, 'Invalid Device' unless encryptedToken? meshbluHttp = new MeshbluHttp @meshbluConfig privateKey = meshbluHttp.setPrivateKey @meshbluConfig.privateKey path = privateKey.decrypt(encryptedPath).toString() token = privateKey.decrypt(encryptedToken).<KEY>() options = baseUrl: @dropboxServiceUri uri: "/1/media/auto/#{path}" auth: bearer: token json: true request.post options, (error, response, body) => return callback @_createError 500, error.message if error? return callback @_createError response.statusCode, body if response.statusCode > 299 meshbluHttp = new MeshbluHttp meshbluAuth meshbluHttp.unregister uuid: meshbluAuth.uuid, (error) => return callback @_createError 500, error.message if error? callback null, request.get body.url _createError: (code, message) => error = new Error message error.code = code if code? return error module.exports = DropboxLinkService
true
MeshbluHttp = require 'meshblu-http' request = require 'request' class DropboxLinkService constructor: ({@meshbluConfig,@dropboxServiceUri}) -> generate: ({token,path,fileName}, callback) => meshbluHttp = new MeshbluHttp @meshbluConfig privateKey = meshbluHttp.setPrivateKey @meshbluConfig.privateKey encryptedToken = privateKey.encrypt token, 'base64' encryptedPath = privateKey.encrypt path, 'base64' meshbluHttp.register dropbox: {encryptedToken,encryptedPath}, (error, device) => return callback @_createError 500, error.message if error? link = "https://#{device.uuid}:#{device.token}@dropbox-link.octoblu.com/meshblu/links" callback null, {link,fileName} download: ({meshbluAuth}, callback) => {device} = meshbluAuth {encryptedToken,encryptedPath} = device.dropbox return callback @_createError 422, 'Invalid Device' unless encryptedPath? return callback @_createError 422, 'Invalid Device' unless encryptedToken? meshbluHttp = new MeshbluHttp @meshbluConfig privateKey = meshbluHttp.setPrivateKey @meshbluConfig.privateKey path = privateKey.decrypt(encryptedPath).toString() token = privateKey.decrypt(encryptedToken).PI:KEY:<KEY>END_PI() options = baseUrl: @dropboxServiceUri uri: "/1/media/auto/#{path}" auth: bearer: token json: true request.post options, (error, response, body) => return callback @_createError 500, error.message if error? return callback @_createError response.statusCode, body if response.statusCode > 299 meshbluHttp = new MeshbluHttp meshbluAuth meshbluHttp.unregister uuid: meshbluAuth.uuid, (error) => return callback @_createError 500, error.message if error? callback null, request.get body.url _createError: (code, message) => error = new Error message error.code = code if code? return error module.exports = DropboxLinkService
[ { "context": "serinfo=\n accountNumber:undefined\n passWord:undefined\n userorpwdIsError:undefined\n\n $scope=undefined\n", "end": 83, "score": 0.9989538192749023, "start": 74, "tag": "PASSWORD", "value": "undefined" } ]
test/main/accountSpec.coffee
rongcloud/sealtalk-web
195
describe "账户部分测试",-> userinfo= accountNumber:undefined passWord:undefined userorpwdIsError:undefined $scope=undefined beforeEach module "webim.account" beforeEach inject((_$rootScope_, _$compile_)-> $compile = _$compile_ $rootScope = _$rootScope_ )
45054
describe "账户部分测试",-> userinfo= accountNumber:undefined passWord:<PASSWORD> userorpwdIsError:undefined $scope=undefined beforeEach module "webim.account" beforeEach inject((_$rootScope_, _$compile_)-> $compile = _$compile_ $rootScope = _$rootScope_ )
true
describe "账户部分测试",-> userinfo= accountNumber:undefined passWord:PI:PASSWORD:<PASSWORD>END_PI userorpwdIsError:undefined $scope=undefined beforeEach module "webim.account" beforeEach inject((_$rootScope_, _$compile_)-> $compile = _$compile_ $rootScope = _$rootScope_ )
[ { "context": "ird the head-body size.\n '''\n\n scientificName: 'Leptailurus serval'\n mainImage: 'assets/fieldguide-", "end": 420, "score": 0.5992802977561951, "start": 418, "tag": "NAME", "value": "Le" } ]
app/lib/field-guide-content/serval.coffee
zooniverse/wildcam-gorongosa-facebook
7
module.exports = description: ''' A small cat species, servals have many characteristics of domestic cats. They are strongly built with long legs, long necks, and tall, pointed ears. Their coat is tawny with black spots, which sometimes causes people to misidentify them as young leopards or cheetahs. Their tail is short, reaching a total length of about one-third the head-body size. ''' scientificName: 'Leptailurus serval' mainImage: 'assets/fieldguide-content/mammals/serval/serval-feature.jpg' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '67-100 cm' }, { label: 'Height' value: '55 cm' }, { label: 'Weight' value: '8.7-19 kg' }, { label: 'Lifespan' value: '20 years in captivity' }, { label: 'Gestation' value: '65-75 days' }, { label: 'Avg. number of offspring' value: '1-5' }] sections: [{ title: 'Habitat' content: 'Servals are most commonly found in grasslands or reed beds, but also spend time in forest brush, thickets, marshes, and streams within their home range.' }, { title: 'Diet' content: 'Small rodents, birds, reptiles, frogs, and insects ' }, { title: 'Predators' content: 'Hyenas, leopards, wild dogs' }, { title: 'Behavior' content: ''' <p>Servals are primarily solitary animals, only coming together to mate and sometimes to temporarily travel, hunt, or rest when they happen to encounter each other. They hunt during the early morning and late afternoon and rest at mid-day and at night as well. They catch most of their prey by leaping high into the air and pouncing. They mark their territory by spraying urine, rubbing the side of their face (which contains scent glands) on the ground or brush, defecating, and by making marks or scratches in the ground.</p> ''' }, { title: 'Breeding' content: ''' <p>The serval’s mating system is based on core territories with larger shared hunting ranges. Servals come together in pairs for a few days when the female is in heat. The serval gives birth to a litter of one to five kittens after a gestation period of between 65 and 75 days. Servals reproduce annually, year-round in the tropics, from December through March in southern Africa.<p> ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>Servals are native to more than 35 African countries.</li> <li>Servals can jump up to 10 feet in the air.</li> <li>Serval kittens often “play with” their food; they will toss rats, mice, and birds in the air if they are not immediately killed.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/serval/serval-map.jpg"/>' }]
55557
module.exports = description: ''' A small cat species, servals have many characteristics of domestic cats. They are strongly built with long legs, long necks, and tall, pointed ears. Their coat is tawny with black spots, which sometimes causes people to misidentify them as young leopards or cheetahs. Their tail is short, reaching a total length of about one-third the head-body size. ''' scientificName: '<NAME>ptailurus serval' mainImage: 'assets/fieldguide-content/mammals/serval/serval-feature.jpg' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '67-100 cm' }, { label: 'Height' value: '55 cm' }, { label: 'Weight' value: '8.7-19 kg' }, { label: 'Lifespan' value: '20 years in captivity' }, { label: 'Gestation' value: '65-75 days' }, { label: 'Avg. number of offspring' value: '1-5' }] sections: [{ title: 'Habitat' content: 'Servals are most commonly found in grasslands or reed beds, but also spend time in forest brush, thickets, marshes, and streams within their home range.' }, { title: 'Diet' content: 'Small rodents, birds, reptiles, frogs, and insects ' }, { title: 'Predators' content: 'Hyenas, leopards, wild dogs' }, { title: 'Behavior' content: ''' <p>Servals are primarily solitary animals, only coming together to mate and sometimes to temporarily travel, hunt, or rest when they happen to encounter each other. They hunt during the early morning and late afternoon and rest at mid-day and at night as well. They catch most of their prey by leaping high into the air and pouncing. They mark their territory by spraying urine, rubbing the side of their face (which contains scent glands) on the ground or brush, defecating, and by making marks or scratches in the ground.</p> ''' }, { title: 'Breeding' content: ''' <p>The serval’s mating system is based on core territories with larger shared hunting ranges. Servals come together in pairs for a few days when the female is in heat. The serval gives birth to a litter of one to five kittens after a gestation period of between 65 and 75 days. Servals reproduce annually, year-round in the tropics, from December through March in southern Africa.<p> ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>Servals are native to more than 35 African countries.</li> <li>Servals can jump up to 10 feet in the air.</li> <li>Serval kittens often “play with” their food; they will toss rats, mice, and birds in the air if they are not immediately killed.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/serval/serval-map.jpg"/>' }]
true
module.exports = description: ''' A small cat species, servals have many characteristics of domestic cats. They are strongly built with long legs, long necks, and tall, pointed ears. Their coat is tawny with black spots, which sometimes causes people to misidentify them as young leopards or cheetahs. Their tail is short, reaching a total length of about one-third the head-body size. ''' scientificName: 'PI:NAME:<NAME>END_PIptailurus serval' mainImage: 'assets/fieldguide-content/mammals/serval/serval-feature.jpg' conservationStatus: 'Least Concern' # Options are Least Concern, Near Threatened, Vulnerable, and Endangered; all have their own little icons as well. information: [{ label: 'Length' value: '67-100 cm' }, { label: 'Height' value: '55 cm' }, { label: 'Weight' value: '8.7-19 kg' }, { label: 'Lifespan' value: '20 years in captivity' }, { label: 'Gestation' value: '65-75 days' }, { label: 'Avg. number of offspring' value: '1-5' }] sections: [{ title: 'Habitat' content: 'Servals are most commonly found in grasslands or reed beds, but also spend time in forest brush, thickets, marshes, and streams within their home range.' }, { title: 'Diet' content: 'Small rodents, birds, reptiles, frogs, and insects ' }, { title: 'Predators' content: 'Hyenas, leopards, wild dogs' }, { title: 'Behavior' content: ''' <p>Servals are primarily solitary animals, only coming together to mate and sometimes to temporarily travel, hunt, or rest when they happen to encounter each other. They hunt during the early morning and late afternoon and rest at mid-day and at night as well. They catch most of their prey by leaping high into the air and pouncing. They mark their territory by spraying urine, rubbing the side of their face (which contains scent glands) on the ground or brush, defecating, and by making marks or scratches in the ground.</p> ''' }, { title: 'Breeding' content: ''' <p>The serval’s mating system is based on core territories with larger shared hunting ranges. Servals come together in pairs for a few days when the female is in heat. The serval gives birth to a litter of one to five kittens after a gestation period of between 65 and 75 days. Servals reproduce annually, year-round in the tropics, from December through March in southern Africa.<p> ''' }, { title: 'Fun Facts' style: 'focus-box' content: ''' <ol> <li>Servals are native to more than 35 African countries.</li> <li>Servals can jump up to 10 feet in the air.</li> <li>Serval kittens often “play with” their food; they will toss rats, mice, and birds in the air if they are not immediately killed.</li> </ol> ''' },{ title: 'Distribution' content: '<img src="assets/fieldguide-content/mammals/serval/serval-map.jpg"/>' }]
[ { "context": ".1 安装相关包\n \n PIL 2009年之后就没有更新了,也不支持 Python3 ,于是有了 Alex Clark 领导的公益项目 [Pillow](https://github.com/python-pillow", "end": 776, "score": 0.8991022109985352, "start": 766, "tag": "NAME", "value": "Alex Clark" }, { "context": "有了 Alex Clark 领导的公益项目 [Pillow](https://github.com/python-pillow/Pillow),Pillow 是一个对 PIL 友好的分支,支持 Python3,所以我们这里安装", "end": 826, "score": 0.9990065097808838, "start": 813, "tag": "USERNAME", "value": "python-pillow" } ]
notes/f67ed79932652dd2c4d4.cson
Shadowalker1995/Boostnote
0
createdAt: "2018-05-18T06:08:03.074Z" updatedAt: "2018-05-18T06:08:05.862Z" type: "MARKDOWN_NOTE" folder: "46ccafb94878584d989c" title: "Python 3 色情图片识别" content: ''' # Python 3 色情图片识别 ## 一、实验简介 ### 1.1 实验内容 本实验将使用 Python3 去识别图片是否为色情图片,我们会使用到 PIL 这个图像处理库,会编写算法来划分图像的皮肤区域 ### 1.2 实验知识点 - Python 3 的模块的安装 - Python 3 基础知识 - 肤色像素检测与皮肤区域划分算法 - [Pillow](https://pillow.readthedocs.io/en/latest/index.html) 模块的使用 - [argparse](https://docs.python.org/3/library/argparse.html) 模块的使用 ### 1.3 效果展示 ![img](https://labfile.oss.aliyuncs.com/courses/589/%E6%8D%95%E8%8E%B7.PNG) ![img](https://labfile.oss.aliyuncs.com/courses/589/%E6%8D%95%E8%8E%B73.PNG) ## 二、实验步骤 ### 2.1 安装相关包 PIL 2009年之后就没有更新了,也不支持 Python3 ,于是有了 Alex Clark 领导的公益项目 [Pillow](https://github.com/python-pillow/Pillow),Pillow 是一个对 PIL 友好的分支,支持 Python3,所以我们这里安装的是 Pillow,其[官方文档](https://pillow.readthedocs.io/en/latest/index.html) 安装前更新源 ```sh $ sudo apt-get update ``` 首先我们需要处理一个问题:当前实验楼的环境中 python3 命令使用的 python 版本为 3.5,但源中却没有 python3.5-dev,这会导致安装 Pillow 出错。所以我们必须将 python3 命令使用的 python 版本切换为 3.4,然后再安装 python3-dev 和 python3-setuptools。 ```sh $ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.4 70 --slave /usr/bin/python3m python3m /usr/bin/python3.4m $ sudo apt-get install python3-dev python3-setuptools ``` 然后安装 Pillow 依赖包 ```sh $ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev \\ libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk ``` 安装 `pip3`,`pip` 是 Python2 的软件包管理系统,使用它来安装 Python2 的模块非常简便,而 `pip3` 则是对应于 Python3 的版本 ```sh $ sudo apt-get install python3-pip ``` 最后安装 Pillow: ```sh $ sudo pip3 install Pillow ``` ### 2.2 程序原理 本程序根据颜色(肤色)找出图片中皮肤的区域,然后通过一些条件判断是否为色情图片 程序的关键步骤如下 1. 遍历每个像素,检测像素颜色是否为肤色 2. 将相邻的肤色像素归为一个皮肤区域,得到若干个皮肤区域 3. 剔除像素数量极少的皮肤区域 我们定义**非**色情图片的判定规则如下(满足任意一个判定为真): 1. 皮肤区域的个数小于 3 个 2. 皮肤区域的像素与图像所有像素的比值小于 15% 3. 最大皮肤区域小于总皮肤面积的 45% 4. 皮肤区域数量超过60个 这些规则你可以尝试更改,直到程序效果让你满意为止 关于像素肤色判定这方面,公式可以在网上找到很多,但世界上不可能有正确率 100% 的公式 你可以用自己找到的公式,在程序完成后慢慢调试 - RGB 颜色模式 第一种:`r > 95 and g > 40 and g < 100 and b > 20 and max([r, g, b]) - min([r, g, b]) > 15 and abs(r - g) > 15 and r > g and r > b` 第二种:`nr = r / (r + g + b), ng = g / (r + g + b), nb = b / (r +g + b)`, `nr / ng > 1.185 and r * b / (r + g + b) ** 2 > 0.107 and r * g / (r + g + b) ** 2 > 0.112` - HSV 颜色模式 `h > 0 and h < 35 and s > 0.23 and s < 0.68` - YCbCr 颜色模式 `97.5 <= cb <= 142.5 and 134 <= cr <= 176` 一幅图像有零个到多个的皮肤区域,程序按发现顺序给它们编号,第一个发现的区域编号为 0,第 n 个发现的区域编号为 n-1 我们用一种类型来表示像素,我们给这个类型取名为 `Skin`,包含了像素的一些信息:唯一的 编号(`id`),是/否肤色(`skin`),皮肤区域号(`region`),横坐标(`x`),纵坐标(`y`) 遍历所有像素时,我们为每个像素创建一个与之对应的 `Skin` 对象,并设置对象的所有属性 其中 `region` 属性即为像素所在的皮肤区域编号,创建对象时初始化为无意义的 `None` 关于每个像素的 id 值,左上角为原点,像素的 id 值按像素坐标排布,那么看起来如下图 ![img](https://labfile.oss.aliyuncs.com/courses/589/id%20%E6%8E%92%E5%B8%83%E5%9B%BE.PNG) 其实 id 的顺序也即遍历的顺序 遍历所有像素时,创建 `Skin` 对象后,如果当前像素为肤色,且相邻的像素有肤色的,那么我们把这些肤色像素归到一个皮肤区域 相邻像素的定义:通常都能想到是当前像素周围的 **8** 个像素,然而实际上只需要定义 **4** 个就可以了,位置分别在当前像素的左方,左上方,正上方,右上方;因为另外四个像素都在当前像素后面,我们还未给这4个像素创建对应的 Skin 对象 ![img](https://labfile.oss.aliyuncs.com/courses/589/%E7%9B%B8%E9%82%BB%E5%83%8F%E7%B4%A0.png) 接下来实现细节部分 ### 2.3 实现脚本 导入所需要的模块 ```python import sys import os import _io from collections import namedtuple from PIL import Image ``` 我们将设计一个 `Nude` 类: ```python class Nude(object): ``` 这个类里面我们首先使用 `collections.namedtuple()` 定义一个 `Skin` 类型 ```python Skin = namedtuple("Skin", "id skin region x y") ``` `collections.namedtuple()` 函数实际上是一个返回Python中标准元组类型子类的一个工厂方法。 你需要传递一个类型名和你需要的字段给它,然后它就会返回一个类,你可以初始化这个类,为你定义的字段传递值等。 详情参见[官方文档](https://docs.python.org/3/library/collections.html#collections.namedtuple)。 然后定义 `Nude` 类的初始化方法 ```python def __init__(self, path_or_image): # 若 path_or_image 为 Image.Image 类型的实例,直接赋值 if isinstance(path_or_image, Image.Image): self.image = path_or_image # 若 path_or_image 为 str 类型的实例,打开图片 elif isinstance(path_or_image, str): self.image = Image.open(path_or_image) # 获得图片所有颜色通道 bands = self.image.getbands() # 判断是否为单通道图片(也即灰度图),是则将灰度图转换为 RGB 图 if len(bands) == 1: # 新建相同大小的 RGB 图像 new_img = Image.new("RGB", self.image.size) # 拷贝灰度图 self.image 到 RGB图 new_img.paste (PIL 自动进行颜色通道转换) new_img.paste(self.image) f = self.image.filename # 替换 self.image self.image = new_img self.image.filename = f # 存储对应图像所有像素的全部 Skin 对象 self.skin_map = [] # 检测到的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.detected_regions = [] # 元素都是包含一些 int 对象(区域号)的列表 # 这些元素中的区域号代表的区域都是待合并的区域 self.merge_regions = [] # 整合后的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.skin_regions = [] # 最近合并的两个皮肤区域的区域号,初始化为 -1 self.last_from, self.last_to = -1, -1 # 色情图像判断结果 self.result = None # 处理得到的信息 self.message = None # 图像宽高 self.width, self.height = self.image.size # 图像总像素 self.total_pixels = self.width * self.height ``` 本实验代码中使用到的模块中的函数均可以在其模块的文档中找到,一定要培养查阅文档的习惯 > - `isinstane(object, classinfo)` 如果参数 `object` 是参数 `classinfo` 的实例,返回真,否则假;参数 `classinfo` 可以是一个包含若干 `type` 对象的元祖,如果参数 `object` 是其中任意一个类型的实例,返回真,否则假 涉及到效率问题,越大的图片所需要消耗的资源与时间越大,因此有时候可能需要对图片进行缩小 所以需要有图片缩小方法 ```python def resize(self, maxwidth=1000, maxheight=1000): """ 基于最大宽高按比例重设图片大小, 注意:这可能影响检测算法的结果 如果没有变化返回 0 原宽度大于 maxwidth 返回 1 原高度大于 maxheight 返回 2 原宽高大于 maxwidth, maxheight 返回 3 maxwidth - 图片最大宽度 maxheight - 图片最大高度 传递参数时都可以设置为 False 来忽略 """ # 存储返回值 ret = 0 if maxwidth: if self.width > maxwidth: wpercent = (maxwidth / self.width) hsize = int((self.height * wpercent)) fname = self.image.filename # Image.LANCZOS 是重采样滤波器,用于抗锯齿 self.image = self.image.resize((maxwidth, hsize), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 1 if maxheight: if self.height > maxheight: hpercent = (maxheight / float(self.height)) wsize = int((float(self.width) * float(hpercent))) fname = self.image.filename self.image = self.image.resize((wsize, maxheight), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 2 return ret ``` > - `Image.resize(size, resample=0)` > > size – 包含宽高像素数的元祖 (width, height) resample – 可选的重采样滤波器 > > 返回 `Image` 对象 然后便是最关键之一的解析方法了 ```python def parse(self): # 如果已有结果,返回本对象 if self.result is not None: return self # 获得图片所有像素数据 pixels = self.image.load() ``` 接着,遍历每个像素,为每个像素创建对应的 `Skin` 对象,代码见下 其中 `self._classify_skin()` 这个方法是检测像素颜色是否为肤色 ```python for y in range(self.height): for x in range(self.width): # 得到像素的 RGB 三个通道的值 # [x, y] 是 [(x,y)] 的简便写法 r = pixels[x, y][0] # red g = pixels[x, y][1] # green b = pixels[x, y][2] # blue # 判断当前像素是否为肤色像素 isSkin = True if self._classify_skin(r, g, b) else False # 给每个像素分配唯一 id 值(1, 2, 3...height*width) # 注意 x, y 的值从零开始 _id = x + y * self.width + 1 # 为每个像素创建一个对应的 Skin 对象,并添加到 self.skin_map 中 self.skin_map.append(self.Skin(_id, isSkin, None, x, y)) ``` 若当前像素并不是肤色,那么跳过本次循环,继续遍历 ```python # 若当前像素不为肤色像素,跳过此次循环 if not isSkin: continue ``` 若当前像素是肤色像素,那么就需要处理了,先遍历其相邻像素 一定要注意相邻像素的索引值,因为像素的 `id` 值是从 **1** 开始编起的,而索引是从 **0** 编起的。变量 `_id` 是存有当前像素的 `id` 值, 所以当前像素在 `self.skin_map` 中的索引值为 `_id - 1`,以此类推,那么其左方的相邻像素在 `self.skin_map` 中的索引值为 `_id - 1 - 1` ,左上方为 `_id - 1 - self.width - 1`,上方为 `_id - 1 - self.width` ,右上方为 `_id - 1 - self.width + 1` ```python # 设左上角为原点,相邻像素为符号 *,当前像素为符号 ^,那么相互位置关系通常如下图 # *** # *^ # 存有相邻像素索引的列表,存放顺序为由大到小,顺序改变有影响 # 注意 _id 是从 1 开始的,对应的索引则是 _id-1 check_indexes = [_id - 2, # 当前像素左方的像素 _id - self.width - 2, # 当前像素左上方的像素 _id - self.width - 1, # 当前像素的上方的像素 _id - self.width] # 当前像素右上方的像素 ``` 说起来复杂,其实看上面代码并不复杂,说这么多是怕同学搞混,你要是觉得有点绕的话,你也可以把 `id` 值从 0 编起 ```python # 用来记录相邻像素中肤色像素所在的区域号,初始化为 -1 region = -1 # 遍历每一个相邻像素的索引 for index in check_indexes: # 尝试索引相邻像素的 Skin 对象,没有则跳出循环 try: self.skin_map[index] except IndexError: break # 相邻像素若为肤色像素: if self.skin_map[index].skin: # 若相邻像素与当前像素的 region 均为有效值,且二者不同,且尚未添加相同的合并任务 if (self.skin_map[index].region != None and region != None and region != -1 and self.skin_map[index].region != region and self.last_from != region and self.last_to != self.skin_map[index].region) : # 那么这添加这两个区域的合并任务 self._add_merge(region, self.skin_map[index].region) # 记录此相邻像素所在的区域号 region = self.skin_map[index].region ``` `self._add_merge()` 这个方法接收两个区域号,它将会把两个区域号添加到 `self.merge_regions` 中的元素中,`self.merge_regions` 的每一个元素都是一个列表,这些列表中存放了 1 到多个的区域号,区域号代表的区域是连通的,需要合并 检测的图像里,有些前几行的像素的相邻像素并没有 4 个,所以需要用 `try`“试错” 然后相邻像素的若是肤色像素,如果两个像素的皮肤区域号都为有效值且不同,因为两个区域中的像素相邻,那么其实这两个区域是连通的,说明需要合并这两个区域。记录下此相邻肤色像素的区域号,之后便可以将当前像素归到这个皮肤区域里了。 遍历完所有相邻像素后,分两种情况处理 1. 所有相邻像素都不是肤色像素:发现了新的皮肤区域 2. 存在区域号为有效值的相邻肤色像素:region 的中存储的值有用了,把当前像素归到这个相邻像素所在的区域 ```python # 遍历完所有相邻像素后,若 region 仍等于 -1,说明所有相邻像素都不是肤色像素 if region == -1: # 更改属性为新的区域号,注意元祖是不可变类型,不能直接更改属性 _skin = self.skin_map[_id - 1]._replace(region=len(self.detected_regions)) self.skin_map[_id - 1] = _skin # 将此肤色像素所在区域创建为新区域 self.detected_regions.append([self.skin_map[_id - 1]]) # region 不等于 -1 的同时不等于 None,说明有区域号为有效值的相邻肤色像素 elif region != None: # 将此像素的区域号更改为与相邻像素相同 _skin = self.skin_map[_id - 1]._replace(region=region) self.skin_map[_id - 1] = _skin # 向这个区域的像素列表中添加此像素 self.detected_regions[region].append(self.skin_map[_id - 1]) ``` > - `somenamedtuple._replace(kwargs)` 返回一个替换指定字段的值为参数的 `namedtuple` 实例 遍历完所有像素之后,图片的皮肤区域划分初步完成了,只是在变量 `self.merge_regions` 中还有一些连通的皮肤区域号,它们需要合并,合并之后就可以进行色情图片判定了 ```python # 完成所有区域合并任务,合并整理后的区域存储到 self.skin_regions self._merge(self.detected_regions, self.merge_regions) # 分析皮肤区域,得到判定结果 self._analyse_regions() return self ``` 方法 `self._merge()` 便是用来合并这些连通的皮肤区域的 方法 `self._analyse_regions()`,运用之前在程序原理一节定义的非色情图像判定规则,从而得到判定结果 现在编写我们还没写过的调用过的 `Nude` 类的方法 首先是 `self._classify_skin()` 方法,这个方法是检测像素颜色是否为肤色,之前在程序原理一节已经把肤色判定该公式列举了出来,现在是用的时候了 ```python # 基于像素的肤色检测技术 def _classify_skin(self, r, g, b): # 根据RGB值判定 rgb_classifier = r > 95 and \\ g > 40 and g < 100 and \\ b > 20 and \\ max([r, g, b]) - min([r, g, b]) > 15 and \\ abs(r - g) > 15 and \\ r > g and \\ r > b # 根据处理后的 RGB 值判定 nr, ng, nb = self._to_normalized(r, g, b) norm_rgb_classifier = nr / ng > 1.185 and \\ float(r * b) / ((r + g + b) ** 2) > 0.107 and \\ float(r * g) / ((r + g + b) ** 2) > 0.112 # HSV 颜色模式下的判定 h, s, v = self._to_hsv(r, g, b) hsv_classifier = h > 0 and \\ h < 35 and \\ s > 0.23 and \\ s < 0.68 # YCbCr 颜色模式下的判定 y, cb, cr = self._to_ycbcr(r, g, b) ycbcr_classifier = 97.5 <= cb <= 142.5 and 134 <= cr <= 176 # 效果不是很好,还需改公式 # return rgb_classifier or norm_rgb_classifier or hsv_classifier or ycbcr_classifier return ycbcr_classifier ``` 颜色模式的转换并不是本实验的重点,转换公式可以在网上找到,这里我们直接拿来用就行 ```python def _to_normalized(self, r, g, b): if r == 0: r = 0.0001 if g == 0: g = 0.0001 if b == 0: b = 0.0001 _sum = float(r + g + b) return [r / _sum, g / _sum, b / _sum] def _to_ycbcr(self, r, g, b): # 公式来源: # http://stackoverflow.com/questions/19459831/rgb-to-ycbcr-conversion-problems y = .299*r + .587*g + .114*b cb = 128 - 0.168736*r - 0.331364*g + 0.5*b cr = 128 + 0.5*r - 0.418688*g - 0.081312*b return y, cb, cr def _to_hsv(self, r, g, b): h = 0 _sum = float(r + g + b) _max = float(max([r, g, b])) _min = float(min([r, g, b])) diff = float(_max - _min) if _sum == 0: _sum = 0.0001 if _max == r: if diff == 0: h = sys.maxsize else: h = (g - b) / diff elif _max == g: h = 2 + ((g - r) / diff) else: h = 4 + ((r - g) / diff) h *= 60 if h < 0: h += 360 return [h, 1.0 - (3.0 * (_min / _sum)), (1.0 / 3.0) * _max] ``` `self._add_merge()` 方法主要是对 `self.merge_regions` 操作,而self.merge_regions 的元素都是包含一些 int 对象(区域号)的列表,列表中的区域号代表的区域都是待合并的区域 `self._add_merge()` 方法接收两个区域号,将之添加到 `self.merge_regions`中 这两个区域号以怎样的形式添加,要分3种情况处理, 1. 传入的两个区域号都存在于 `self.merge_regions` 中 2. 传入的两个区域号有一个区域号存在于 `self.merge_regions` 中 3. 传入的两个区域号都不存在于 `self.merge_regions` 中 具体的处理方法,见代码 ```python def _add_merge(self, _from, _to): # 两个区域号赋值给类属性 self.last_from = _from self.last_to = _to # 记录 self.merge_regions 的某个索引值,初始化为 -1 from_index = -1 # 记录 self.merge_regions 的某个索引值,初始化为 -1 to_index = -1 # 遍历每个 self.merge_regions 的元素 for index, region in enumerate(self.merge_regions): # 遍历元素中的每个区域号 for r_index in region: if r_index == _from: from_index = index if r_index == _to: to_index = index # 若两个区域号都存在于 self.merge_regions 中 if from_index != -1 and to_index != -1: # 如果这两个区域号分别存在于两个列表中 # 那么合并这两个列表 if from_index != to_index: self.merge_regions[from_index].extend(self.merge_regions[to_index]) del(self.merge_regions[to_index]) return # 若两个区域号都不存在于 self.merge_regions 中 if from_index == -1 and to_index == -1: # 创建新的区域号列表 self.merge_regions.append([_from, _to]) return # 若两个区域号中有一个存在于 self.merge_regions 中 if from_index != -1 and to_index == -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[from_index].append(_to) return # 若两个待合并的区域号中有一个存在于 self.merge_regions 中 if from_index == -1 and to_index != -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[to_index].append(_from) return ``` 在序列中循环时,索引位置和对应值可以使用 [enumerate()](https://docs.python.org/3/library/functions.html#enumerate) 函数同时得到,在上面的代码中,索引位置即为 `index` ,对应值即为`region` `self._merge()` 方法则是将 `self.merge_regions` 中的元素中的区域号所代表的区域合并,得到新的皮肤区域列表 ```python def _merge(self, detected_regions, merge_regions): # 新建列表 new_detected_regions # 其元素将是包含一些代表像素的 Skin 对象的列表 # new_detected_regions 的元素即代表皮肤区域,元素索引为区域号 new_detected_regions = [] # 将 merge_regions 中的元素中的区域号代表的所有区域合并 for index, region in enumerate(merge_regions): try: new_detected_regions[index] except IndexError: new_detected_regions.append([]) for r_index in region: new_detected_regions[index].extend(detected_regions[r_index]) detected_regions[r_index] = [] # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) ``` `self._clear_regions()` 方法只将像素数大于指定数量的皮肤区域保留到 `self.skin_regions` ```python # 皮肤区域清理函数 # 只保存像素数大于指定数量的皮肤区域 def _clear_regions(self, detected_regions): for region in detected_regions: if len(region) > 30: self.skin_regions.append(region) ``` `self._analyse_regions()` 是很简单的,它的工作只是进行一系列判断,得出图片是否色情的结论 ```python # 分析区域 def _analyse_regions(self): # 如果皮肤区域小于 3 个,不是色情 if len(self.skin_regions) < 3: self.message = "Less than 3 skin regions ({_skin_regions_size})".format( _skin_regions_size=len(self.skin_regions)) self.result = False return self.result # 为皮肤区域排序 self.skin_regions = sorted(self.skin_regions, key=lambda s: len(s), reverse=True) # 计算皮肤总像素数 total_skin = float(sum([len(skin_region) for skin_region in self.skin_regions])) # 如果皮肤区域与整个图像的比值小于 15%,那么不是色情图片 if total_skin / self.total_pixels * 100 < 15: self.message = "Total skin percentage lower than 15 ({:.2f})".format(total_skin / self.total_pixels * 100) self.result = False return self.result # 如果最大皮肤区域小于总皮肤面积的 45%,不是色情图片 if len(self.skin_regions[0]) / total_skin * 100 < 45: self.message = "The biggest region contains less than 45 ({:.2f})".format(len(self.skin_regions[0]) / total_skin * 100) self.result = False return self.result # 皮肤区域数量超过 60个,不是色情图片 if len(self.skin_regions) > 60: self.message = "More than 60 skin regions ({})".format(len(self.skin_regions)) self.result = False return self.result # 其它情况为色情图片 self.message = "Nude!!" self.result = True return self.result ``` 然后可以组织下分析得出的信息 ```python def inspect(self): _image = '{} {} {}×{}'.format(self.image.filename, self.image.format, self.width, self.height) return "{_image}: result={_result} message='{_message}'".format(_image=_image, _result=self.result, _message=self.message) ``` `Nude` 类如果就这样完成了,最后运行脚本时只能得到一些真或假的结果,我们需要更直观的感受程序的分析效果,我们可以生成一张原图的副本,不过这个副本图片中只有黑白色,白色代表皮肤区域,那么这样我们能直观感受到程序分析的效果了 前面的代码中我们有获得图像的像素的 RGB 值的操作,设置像素的 RGB 值也就是其逆操作,还是很简单的,不过注意设置像素的 RGB 值时不能在原图上操作 ```python # 将在源文件目录生成图片文件,将皮肤区域可视化 def showSkinRegions(self): # 未得出结果时方法返回 if self.result is None: return # 皮肤像素的 ID 的集合 skinIdSet = set() # 将原图做一份拷贝 simage = self.image # 加载数据 simageData = simage.load() # 将皮肤像素的 id 存入 skinIdSet for sr in self.skin_regions: for pixel in sr: skinIdSet.add(pixel.id) # 将图像中的皮肤像素设为白色,其余设为黑色 for pixel in self.skin_map: if pixel.id not in skinIdSet: simageData[pixel.x, pixel.y] = 0, 0, 0 else: simageData[pixel.x, pixel.y] = 255, 255, 255 # 源文件绝对路径 filePath = os.path.abspath(self.image.filename) # 源文件所在目录 fileDirectory = os.path.dirname(filePath) + '/' # 源文件的完整文件名 fileFullName = os.path.basename(filePath) # 分离源文件的完整文件名得到文件名和扩展名 fileName, fileExtName = os.path.splitext(fileFullName) # 保存图片 simage.save('{}{}_{}{}'.format(fileDirectory, fileName,'Nude' if self.result else 'Normal', fileExtName)) ``` 变量 `skinIdSet` 使用集合而不是列表是有性能上的考量的,Python 中的集合是哈希表实现的,查询效率很高 最后支持一下命令行参数就大功告成啦!我们使用 `argparse` 这个模块来实现命令行的支持。argparse 模块使得编写用户友好的命令行接口非常容易。程序只需定义好它要求的参数,然后 argparse 将负责如何从 sys.argv 中解析出这些参数。argparse 模块还会自动生成帮助和使用信息并且当用户赋给程序非法的参数时产生错误信息 具体使用方法请查看argparse的 [官方文档](https://docs.python.org/3/library/argparse.html),这里就不多说了 ```python if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Detect nudity in images.') parser.add_argument('files', metavar='image', nargs='+', help='Images you wish to test') parser.add_argument('-r', '--resize', action='store_true', help='Reduce image size to increase speed of scanning') parser.add_argument('-v', '--visualization', action='store_true', help='Generating areas of skin image') args = parser.parse_args() for fname in args.files: if os.path.isfile(fname): n = Nude(fname) if args.resize: n.resize(maxheight=800, maxwidth=600) n.parse() if args.visualization: n.showSkinRegions() print(n.result, n.inspect()) else: print(fname, "is not a file") ``` ### 2.4. 测试效果 使用 `wget` 把测试用图片下载下来 ```sh $ wget http://labfile.oss.aliyuncs.com/courses/589/1.jpg ``` 假设你的脚本名为 nude.py,运行下面的命令执行脚本,注意是 `python3` 而不是`python` ```sh $ python3 nude.py -v 0.jpg 1.jpg ``` 现在你可以等待程序结果,结果出来后,你还可以查看 `-v` 选项生成的效果展示图片 ## 三、实验总结 本次实验熟悉了下 PIL 的使用,了解了色情图片检测的原理,整个实验难点是在皮肤区域的检测与整合这一方面,这方面不是很清楚的同学多多阅读思考,如果有什么疑问或者建议的话可以留言,实验楼会尽力解答你的问题,建议写下实验报告,将自己的思考过程记录下来是很有好处的 本实验还有许多可以改进的地方,比如肤色检测的公式,色情判定条件,还有性能问题,同学可以自己尝试改进,比如性能问题可以尝试多线程或多进程 ## 四、完整代码 代码也可以下载下来 ```sh $ wget http://labfile.oss.aliyuncs.com/courses/589/nude.py ``` 代码: ```python import sys import os import _io from collections import namedtuple from PIL import Image class Nude(object): Skin = namedtuple("Skin", "id skin region x y") def __init__(self, path_or_image): # 若 path_or_image 为 Image.Image 类型的实例,直接赋值 if isinstance(path_or_image, Image.Image): self.image = path_or_image # 若 path_or_image 为 str 类型的实例,打开图片 elif isinstance(path_or_image, str): self.image = Image.open(path_or_image) # 获得图片所有颜色通道 bands = self.image.getbands() # 判断是否为单通道图片(也即灰度图),是则将灰度图转换为 RGB 图 if len(bands) == 1: # 新建相同大小的 RGB 图像 new_img = Image.new("RGB", self.image.size) # 拷贝灰度图 self.image 到 RGB图 new_img.paste (PIL 自动进行颜色通道转换) new_img.paste(self.image) f = self.image.filename # 替换 self.image self.image = new_img self.image.filename = f # 存储对应图像所有像素的全部 Skin 对象 self.skin_map = [] # 检测到的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.detected_regions = [] # 元素都是包含一些 int 对象(区域号)的列表 # 这些元素中的区域号代表的区域都是待合并的区域 self.merge_regions = [] # 整合后的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.skin_regions = [] # 最近合并的两个皮肤区域的区域号,初始化为 -1 self.last_from, self.last_to = -1, -1 # 色情图像判断结果 self.result = None # 处理得到的信息 self.message = None # 图像宽高 self.width, self.height = self.image.size # 图像总像素 self.total_pixels = self.width * self.height def resize(self, maxwidth=1000, maxheight=1000): """ 基于最大宽高按比例重设图片大小, 注意:这可能影响检测算法的结果 如果没有变化返回 0 原宽度大于 maxwidth 返回 1 原高度大于 maxheight 返回 2 原宽高大于 maxwidth, maxheight 返回 3 maxwidth - 图片最大宽度 maxheight - 图片最大高度 传递参数时都可以设置为 False 来忽略 """ # 存储返回值 ret = 0 if maxwidth: if self.width > maxwidth: wpercent = (maxwidth / self.width) hsize = int((self.height * wpercent)) fname = self.image.filename # Image.LANCZOS 是重采样滤波器,用于抗锯齿 self.image = self.image.resize((maxwidth, hsize), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 1 if maxheight: if self.height > maxheight: hpercent = (maxheight / float(self.height)) wsize = int((float(self.width) * float(hpercent))) fname = self.image.filename self.image = self.image.resize((wsize, maxheight), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 2 return ret # 分析函数 def parse(self): # 如果已有结果,返回本对象 if self.result is not None: return self # 获得图片所有像素数据 pixels = self.image.load() # 遍历每个像素 for y in range(self.height): for x in range(self.width): # 得到像素的 RGB 三个通道的值 # [x, y] 是 [(x,y)] 的简便写法 r = pixels[x, y][0] # red g = pixels[x, y][1] # green b = pixels[x, y][2] # blue # 判断当前像素是否为肤色像素 isSkin = True if self._classify_skin(r, g, b) else False # 给每个像素分配唯一 id 值(1, 2, 3...height*width) # 注意 x, y 的值从零开始 _id = x + y * self.width + 1 # 为每个像素创建一个对应的 Skin 对象,并添加到 self.skin_map 中 self.skin_map.append(self.Skin(_id, isSkin, None, x, y)) # 若当前像素不为肤色像素,跳过此次循环 if not isSkin: continue # 设左上角为原点,相邻像素为符号 *,当前像素为符号 ^,那么相互位置关系通常如下图 # *** # *^ # 存有相邻像素索引的列表,存放顺序为由大到小,顺序改变有影响 # 注意 _id 是从 1 开始的,对应的索引则是 _id-1 check_indexes = [_id - 2, # 当前像素左方的像素 _id - self.width - 2, # 当前像素左上方的像素 _id - self.width - 1, # 当前像素的上方的像素 _id - self.width] # 当前像素右上方的像素 # 用来记录相邻像素中肤色像素所在的区域号,初始化为 -1 region = -1 # 遍历每一个相邻像素的索引 for index in check_indexes: # 尝试索引相邻像素的 Skin 对象,没有则跳出循环 try: self.skin_map[index] except IndexError: break # 相邻像素若为肤色像素: if self.skin_map[index].skin: # 若相邻像素与当前像素的 region 均为有效值,且二者不同,且尚未添加相同的合并任务 if (self.skin_map[index].region != None and region != None and region != -1 and self.skin_map[index].region != region and self.last_from != region and self.last_to != self.skin_map[index].region) : # 那么这添加这两个区域的合并任务 self._add_merge(region, self.skin_map[index].region) # 记录此相邻像素所在的区域号 region = self.skin_map[index].region # 遍历完所有相邻像素后,若 region 仍等于 -1,说明所有相邻像素都不是肤色像素 if region == -1: # 更改属性为新的区域号,注意元祖是不可变类型,不能直接更改属性 _skin = self.skin_map[_id - 1]._replace(region=len(self.detected_regions)) self.skin_map[_id - 1] = _skin # 将此肤色像素所在区域创建为新区域 self.detected_regions.append([self.skin_map[_id - 1]]) # region 不等于 -1 的同时不等于 None,说明有区域号为有效值的相邻肤色像素 elif region != None: # 将此像素的区域号更改为与相邻像素相同 _skin = self.skin_map[_id - 1]._replace(region=region) self.skin_map[_id - 1] = _skin # 向这个区域的像素列表中添加此像素 self.detected_regions[region].append(self.skin_map[_id - 1]) # 完成所有区域合并任务,合并整理后的区域存储到 self.skin_regions self._merge(self.detected_regions, self.merge_regions) # 分析皮肤区域,得到判定结果 self._analyse_regions() return self # self.merge_regions 的元素都是包含一些 int 对象(区域号)的列表 # self.merge_regions 的元素中的区域号代表的区域都是待合并的区域 # 这个方法便是将两个待合并的区域号添加到 self.merge_regions 中 def _add_merge(self, _from, _to): # 两个区域号赋值给类属性 self.last_from = _from self.last_to = _to # 记录 self.merge_regions 的某个索引值,初始化为 -1 from_index = -1 # 记录 self.merge_regions 的某个索引值,初始化为 -1 to_index = -1 # 遍历每个 self.merge_regions 的元素 for index, region in enumerate(self.merge_regions): # 遍历元素中的每个区域号 for r_index in region: if r_index == _from: from_index = index if r_index == _to: to_index = index # 若两个区域号都存在于 self.merge_regions 中 if from_index != -1 and to_index != -1: # 如果这两个区域号分别存在于两个列表中 # 那么合并这两个列表 if from_index != to_index: self.merge_regions[from_index].extend(self.merge_regions[to_index]) del(self.merge_regions[to_index]) return # 若两个区域号都不存在于 self.merge_regions 中 if from_index == -1 and to_index == -1: # 创建新的区域号列表 self.merge_regions.append([_from, _to]) return # 若两个区域号中有一个存在于 self.merge_regions 中 if from_index != -1 and to_index == -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[from_index].append(_to) return # 若两个待合并的区域号中有一个存在于 self.merge_regions 中 if from_index == -1 and to_index != -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[to_index].append(_from) return # 合并该合并的皮肤区域 def _merge(self, detected_regions, merge_regions): # 新建列表 new_detected_regions # 其元素将是包含一些代表像素的 Skin 对象的列表 # new_detected_regions 的元素即代表皮肤区域,元素索引为区域号 new_detected_regions = [] # 将 merge_regions 中的元素中的区域号代表的所有区域合并 for index, region in enumerate(merge_regions): try: new_detected_regions[index] except IndexError: new_detected_regions.append([]) for r_index in region: new_detected_regions[index].extend(detected_regions[r_index]) detected_regions[r_index] = [] # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) # 皮肤区域清理函数 # 只保存像素数大于指定数量的皮肤区域 def _clear_regions(self, detected_regions): for region in detected_regions: if len(region) > 30: self.skin_regions.append(region) # 分析区域 def _analyse_regions(self): # 如果皮肤区域小于 3 个,不是色情 if len(self.skin_regions) < 3: self.message = "Less than 3 skin regions ({_skin_regions_size})".format( _skin_regions_size=len(self.skin_regions)) self.result = False return self.result # 为皮肤区域排序 self.skin_regions = sorted(self.skin_regions, key=lambda s: len(s), reverse=True) # 计算皮肤总像素数 total_skin = float(sum([len(skin_region) for skin_region in self.skin_regions])) # 如果皮肤区域与整个图像的比值小于 15%,那么不是色情图片 if total_skin / self.total_pixels * 100 < 15: self.message = "Total skin percentage lower than 15 ({:.2f})".format(total_skin / self.total_pixels * 100) self.result = False return self.result # 如果最大皮肤区域小于总皮肤面积的 45%,不是色情图片 if len(self.skin_regions[0]) / total_skin * 100 < 45: self.message = "The biggest region contains less than 45 ({:.2f})".format(len(self.skin_regions[0]) / total_skin * 100) self.result = False return self.result # 皮肤区域数量超过 60个,不是色情图片 if len(self.skin_regions) > 60: self.message = "More than 60 skin regions ({})".format(len(self.skin_regions)) self.result = False return self.result # 其它情况为色情图片 self.message = "Nude!!" self.result = True return self.result # 基于像素的肤色检测技术 def _classify_skin(self, r, g, b): # 根据RGB值判定 rgb_classifier = r > 95 and \\ g > 40 and g < 100 and \\ b > 20 and \\ max([r, g, b]) - min([r, g, b]) > 15 and \\ abs(r - g) > 15 and \\ r > g and \\ r > b # 根据处理后的 RGB 值判定 nr, ng, nb = self._to_normalized(r, g, b) norm_rgb_classifier = nr / ng > 1.185 and \\ float(r * b) / ((r + g + b) ** 2) > 0.107 and \\ float(r * g) / ((r + g + b) ** 2) > 0.112 # HSV 颜色模式下的判定 h, s, v = self._to_hsv(r, g, b) hsv_classifier = h > 0 and \\ h < 35 and \\ s > 0.23 and \\ s < 0.68 # YCbCr 颜色模式下的判定 y, cb, cr = self._to_ycbcr(r, g, b) ycbcr_classifier = 97.5 <= cb <= 142.5 and 134 <= cr <= 176 # 效果不是很好,还需改公式 # return rgb_classifier or norm_rgb_classifier or hsv_classifier or ycbcr_classifier return ycbcr_classifier def _to_normalized(self, r, g, b): if r == 0: r = 0.0001 if g == 0: g = 0.0001 if b == 0: b = 0.0001 _sum = float(r + g + b) return [r / _sum, g / _sum, b / _sum] def _to_ycbcr(self, r, g, b): # 公式来源: # http://stackoverflow.com/questions/19459831/rgb-to-ycbcr-conversion-problems y = .299*r + .587*g + .114*b cb = 128 - 0.168736*r - 0.331364*g + 0.5*b cr = 128 + 0.5*r - 0.418688*g - 0.081312*b return y, cb, cr def _to_hsv(self, r, g, b): h = 0 _sum = float(r + g + b) _max = float(max([r, g, b])) _min = float(min([r, g, b])) diff = float(_max - _min) if _sum == 0: _sum = 0.0001 if _max == r: if diff == 0: h = sys.maxsize else: h = (g - b) / diff elif _max == g: h = 2 + ((g - r) / diff) else: h = 4 + ((r - g) / diff) h *= 60 if h < 0: h += 360 return [h, 1.0 - (3.0 * (_min / _sum)), (1.0 / 3.0) * _max] def inspect(self): _image = '{} {} {}×{}'.format(self.image.filename, self.image.format, self.width, self.height) return "{_image}: result={_result} message='{_message}'".format(_image=_image, _result=self.result, _message=self.message) # 将在源文件目录生成图片文件,将皮肤区域可视化 def showSkinRegions(self): # 未得出结果时方法返回 if self.result is None: return # 皮肤像素的 ID 的集合 skinIdSet = set() # 将原图做一份拷贝 simage = self.image # 加载数据 simageData = simage.load() # 将皮肤像素的 id 存入 skinIdSet for sr in self.skin_regions: for pixel in sr: skinIdSet.add(pixel.id) # 将图像中的皮肤像素设为白色,其余设为黑色 for pixel in self.skin_map: if pixel.id not in skinIdSet: simageData[pixel.x, pixel.y] = 0, 0, 0 else: simageData[pixel.x, pixel.y] = 255, 255, 255 # 源文件绝对路径 filePath = os.path.abspath(self.image.filename) # 源文件所在目录 fileDirectory = os.path.dirname(filePath) + '/' # 源文件的完整文件名 fileFullName = os.path.basename(filePath) # 分离源文件的完整文件名得到文件名和扩展名 fileName, fileExtName = os.path.splitext(fileFullName) # 保存图片 simage.save('{}{}_{}{}'.format(fileDirectory, fileName,'Nude' if self.result else 'Normal', fileExtName)) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Detect nudity in images.') parser.add_argument('files', metavar='image', nargs='+', help='Images you wish to test') parser.add_argument('-r', '--resize', action='store_true', help='Reduce image size to increase speed of scanning') parser.add_argument('-v', '--visualization', action='store_true', help='Generating areas of skin image') args = parser.parse_args() for fname in args.files: if os.path.isfile(fname): n = Nude(fname) if args.resize: n.resize(maxheight=800, maxwidth=600) n.parse() if args.visualization: n.showSkinRegions() print(n.result, n.inspect()) else: print(fname, "is not a file") ``` ''' tags: [] isStarred: false isTrashed: false
33033
createdAt: "2018-05-18T06:08:03.074Z" updatedAt: "2018-05-18T06:08:05.862Z" type: "MARKDOWN_NOTE" folder: "46ccafb94878584d989c" title: "Python 3 色情图片识别" content: ''' # Python 3 色情图片识别 ## 一、实验简介 ### 1.1 实验内容 本实验将使用 Python3 去识别图片是否为色情图片,我们会使用到 PIL 这个图像处理库,会编写算法来划分图像的皮肤区域 ### 1.2 实验知识点 - Python 3 的模块的安装 - Python 3 基础知识 - 肤色像素检测与皮肤区域划分算法 - [Pillow](https://pillow.readthedocs.io/en/latest/index.html) 模块的使用 - [argparse](https://docs.python.org/3/library/argparse.html) 模块的使用 ### 1.3 效果展示 ![img](https://labfile.oss.aliyuncs.com/courses/589/%E6%8D%95%E8%8E%B7.PNG) ![img](https://labfile.oss.aliyuncs.com/courses/589/%E6%8D%95%E8%8E%B73.PNG) ## 二、实验步骤 ### 2.1 安装相关包 PIL 2009年之后就没有更新了,也不支持 Python3 ,于是有了 <NAME> 领导的公益项目 [Pillow](https://github.com/python-pillow/Pillow),Pillow 是一个对 PIL 友好的分支,支持 Python3,所以我们这里安装的是 Pillow,其[官方文档](https://pillow.readthedocs.io/en/latest/index.html) 安装前更新源 ```sh $ sudo apt-get update ``` 首先我们需要处理一个问题:当前实验楼的环境中 python3 命令使用的 python 版本为 3.5,但源中却没有 python3.5-dev,这会导致安装 Pillow 出错。所以我们必须将 python3 命令使用的 python 版本切换为 3.4,然后再安装 python3-dev 和 python3-setuptools。 ```sh $ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.4 70 --slave /usr/bin/python3m python3m /usr/bin/python3.4m $ sudo apt-get install python3-dev python3-setuptools ``` 然后安装 Pillow 依赖包 ```sh $ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev \\ libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk ``` 安装 `pip3`,`pip` 是 Python2 的软件包管理系统,使用它来安装 Python2 的模块非常简便,而 `pip3` 则是对应于 Python3 的版本 ```sh $ sudo apt-get install python3-pip ``` 最后安装 Pillow: ```sh $ sudo pip3 install Pillow ``` ### 2.2 程序原理 本程序根据颜色(肤色)找出图片中皮肤的区域,然后通过一些条件判断是否为色情图片 程序的关键步骤如下 1. 遍历每个像素,检测像素颜色是否为肤色 2. 将相邻的肤色像素归为一个皮肤区域,得到若干个皮肤区域 3. 剔除像素数量极少的皮肤区域 我们定义**非**色情图片的判定规则如下(满足任意一个判定为真): 1. 皮肤区域的个数小于 3 个 2. 皮肤区域的像素与图像所有像素的比值小于 15% 3. 最大皮肤区域小于总皮肤面积的 45% 4. 皮肤区域数量超过60个 这些规则你可以尝试更改,直到程序效果让你满意为止 关于像素肤色判定这方面,公式可以在网上找到很多,但世界上不可能有正确率 100% 的公式 你可以用自己找到的公式,在程序完成后慢慢调试 - RGB 颜色模式 第一种:`r > 95 and g > 40 and g < 100 and b > 20 and max([r, g, b]) - min([r, g, b]) > 15 and abs(r - g) > 15 and r > g and r > b` 第二种:`nr = r / (r + g + b), ng = g / (r + g + b), nb = b / (r +g + b)`, `nr / ng > 1.185 and r * b / (r + g + b) ** 2 > 0.107 and r * g / (r + g + b) ** 2 > 0.112` - HSV 颜色模式 `h > 0 and h < 35 and s > 0.23 and s < 0.68` - YCbCr 颜色模式 `97.5 <= cb <= 142.5 and 134 <= cr <= 176` 一幅图像有零个到多个的皮肤区域,程序按发现顺序给它们编号,第一个发现的区域编号为 0,第 n 个发现的区域编号为 n-1 我们用一种类型来表示像素,我们给这个类型取名为 `Skin`,包含了像素的一些信息:唯一的 编号(`id`),是/否肤色(`skin`),皮肤区域号(`region`),横坐标(`x`),纵坐标(`y`) 遍历所有像素时,我们为每个像素创建一个与之对应的 `Skin` 对象,并设置对象的所有属性 其中 `region` 属性即为像素所在的皮肤区域编号,创建对象时初始化为无意义的 `None` 关于每个像素的 id 值,左上角为原点,像素的 id 值按像素坐标排布,那么看起来如下图 ![img](https://labfile.oss.aliyuncs.com/courses/589/id%20%E6%8E%92%E5%B8%83%E5%9B%BE.PNG) 其实 id 的顺序也即遍历的顺序 遍历所有像素时,创建 `Skin` 对象后,如果当前像素为肤色,且相邻的像素有肤色的,那么我们把这些肤色像素归到一个皮肤区域 相邻像素的定义:通常都能想到是当前像素周围的 **8** 个像素,然而实际上只需要定义 **4** 个就可以了,位置分别在当前像素的左方,左上方,正上方,右上方;因为另外四个像素都在当前像素后面,我们还未给这4个像素创建对应的 Skin 对象 ![img](https://labfile.oss.aliyuncs.com/courses/589/%E7%9B%B8%E9%82%BB%E5%83%8F%E7%B4%A0.png) 接下来实现细节部分 ### 2.3 实现脚本 导入所需要的模块 ```python import sys import os import _io from collections import namedtuple from PIL import Image ``` 我们将设计一个 `Nude` 类: ```python class Nude(object): ``` 这个类里面我们首先使用 `collections.namedtuple()` 定义一个 `Skin` 类型 ```python Skin = namedtuple("Skin", "id skin region x y") ``` `collections.namedtuple()` 函数实际上是一个返回Python中标准元组类型子类的一个工厂方法。 你需要传递一个类型名和你需要的字段给它,然后它就会返回一个类,你可以初始化这个类,为你定义的字段传递值等。 详情参见[官方文档](https://docs.python.org/3/library/collections.html#collections.namedtuple)。 然后定义 `Nude` 类的初始化方法 ```python def __init__(self, path_or_image): # 若 path_or_image 为 Image.Image 类型的实例,直接赋值 if isinstance(path_or_image, Image.Image): self.image = path_or_image # 若 path_or_image 为 str 类型的实例,打开图片 elif isinstance(path_or_image, str): self.image = Image.open(path_or_image) # 获得图片所有颜色通道 bands = self.image.getbands() # 判断是否为单通道图片(也即灰度图),是则将灰度图转换为 RGB 图 if len(bands) == 1: # 新建相同大小的 RGB 图像 new_img = Image.new("RGB", self.image.size) # 拷贝灰度图 self.image 到 RGB图 new_img.paste (PIL 自动进行颜色通道转换) new_img.paste(self.image) f = self.image.filename # 替换 self.image self.image = new_img self.image.filename = f # 存储对应图像所有像素的全部 Skin 对象 self.skin_map = [] # 检测到的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.detected_regions = [] # 元素都是包含一些 int 对象(区域号)的列表 # 这些元素中的区域号代表的区域都是待合并的区域 self.merge_regions = [] # 整合后的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.skin_regions = [] # 最近合并的两个皮肤区域的区域号,初始化为 -1 self.last_from, self.last_to = -1, -1 # 色情图像判断结果 self.result = None # 处理得到的信息 self.message = None # 图像宽高 self.width, self.height = self.image.size # 图像总像素 self.total_pixels = self.width * self.height ``` 本实验代码中使用到的模块中的函数均可以在其模块的文档中找到,一定要培养查阅文档的习惯 > - `isinstane(object, classinfo)` 如果参数 `object` 是参数 `classinfo` 的实例,返回真,否则假;参数 `classinfo` 可以是一个包含若干 `type` 对象的元祖,如果参数 `object` 是其中任意一个类型的实例,返回真,否则假 涉及到效率问题,越大的图片所需要消耗的资源与时间越大,因此有时候可能需要对图片进行缩小 所以需要有图片缩小方法 ```python def resize(self, maxwidth=1000, maxheight=1000): """ 基于最大宽高按比例重设图片大小, 注意:这可能影响检测算法的结果 如果没有变化返回 0 原宽度大于 maxwidth 返回 1 原高度大于 maxheight 返回 2 原宽高大于 maxwidth, maxheight 返回 3 maxwidth - 图片最大宽度 maxheight - 图片最大高度 传递参数时都可以设置为 False 来忽略 """ # 存储返回值 ret = 0 if maxwidth: if self.width > maxwidth: wpercent = (maxwidth / self.width) hsize = int((self.height * wpercent)) fname = self.image.filename # Image.LANCZOS 是重采样滤波器,用于抗锯齿 self.image = self.image.resize((maxwidth, hsize), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 1 if maxheight: if self.height > maxheight: hpercent = (maxheight / float(self.height)) wsize = int((float(self.width) * float(hpercent))) fname = self.image.filename self.image = self.image.resize((wsize, maxheight), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 2 return ret ``` > - `Image.resize(size, resample=0)` > > size – 包含宽高像素数的元祖 (width, height) resample – 可选的重采样滤波器 > > 返回 `Image` 对象 然后便是最关键之一的解析方法了 ```python def parse(self): # 如果已有结果,返回本对象 if self.result is not None: return self # 获得图片所有像素数据 pixels = self.image.load() ``` 接着,遍历每个像素,为每个像素创建对应的 `Skin` 对象,代码见下 其中 `self._classify_skin()` 这个方法是检测像素颜色是否为肤色 ```python for y in range(self.height): for x in range(self.width): # 得到像素的 RGB 三个通道的值 # [x, y] 是 [(x,y)] 的简便写法 r = pixels[x, y][0] # red g = pixels[x, y][1] # green b = pixels[x, y][2] # blue # 判断当前像素是否为肤色像素 isSkin = True if self._classify_skin(r, g, b) else False # 给每个像素分配唯一 id 值(1, 2, 3...height*width) # 注意 x, y 的值从零开始 _id = x + y * self.width + 1 # 为每个像素创建一个对应的 Skin 对象,并添加到 self.skin_map 中 self.skin_map.append(self.Skin(_id, isSkin, None, x, y)) ``` 若当前像素并不是肤色,那么跳过本次循环,继续遍历 ```python # 若当前像素不为肤色像素,跳过此次循环 if not isSkin: continue ``` 若当前像素是肤色像素,那么就需要处理了,先遍历其相邻像素 一定要注意相邻像素的索引值,因为像素的 `id` 值是从 **1** 开始编起的,而索引是从 **0** 编起的。变量 `_id` 是存有当前像素的 `id` 值, 所以当前像素在 `self.skin_map` 中的索引值为 `_id - 1`,以此类推,那么其左方的相邻像素在 `self.skin_map` 中的索引值为 `_id - 1 - 1` ,左上方为 `_id - 1 - self.width - 1`,上方为 `_id - 1 - self.width` ,右上方为 `_id - 1 - self.width + 1` ```python # 设左上角为原点,相邻像素为符号 *,当前像素为符号 ^,那么相互位置关系通常如下图 # *** # *^ # 存有相邻像素索引的列表,存放顺序为由大到小,顺序改变有影响 # 注意 _id 是从 1 开始的,对应的索引则是 _id-1 check_indexes = [_id - 2, # 当前像素左方的像素 _id - self.width - 2, # 当前像素左上方的像素 _id - self.width - 1, # 当前像素的上方的像素 _id - self.width] # 当前像素右上方的像素 ``` 说起来复杂,其实看上面代码并不复杂,说这么多是怕同学搞混,你要是觉得有点绕的话,你也可以把 `id` 值从 0 编起 ```python # 用来记录相邻像素中肤色像素所在的区域号,初始化为 -1 region = -1 # 遍历每一个相邻像素的索引 for index in check_indexes: # 尝试索引相邻像素的 Skin 对象,没有则跳出循环 try: self.skin_map[index] except IndexError: break # 相邻像素若为肤色像素: if self.skin_map[index].skin: # 若相邻像素与当前像素的 region 均为有效值,且二者不同,且尚未添加相同的合并任务 if (self.skin_map[index].region != None and region != None and region != -1 and self.skin_map[index].region != region and self.last_from != region and self.last_to != self.skin_map[index].region) : # 那么这添加这两个区域的合并任务 self._add_merge(region, self.skin_map[index].region) # 记录此相邻像素所在的区域号 region = self.skin_map[index].region ``` `self._add_merge()` 这个方法接收两个区域号,它将会把两个区域号添加到 `self.merge_regions` 中的元素中,`self.merge_regions` 的每一个元素都是一个列表,这些列表中存放了 1 到多个的区域号,区域号代表的区域是连通的,需要合并 检测的图像里,有些前几行的像素的相邻像素并没有 4 个,所以需要用 `try`“试错” 然后相邻像素的若是肤色像素,如果两个像素的皮肤区域号都为有效值且不同,因为两个区域中的像素相邻,那么其实这两个区域是连通的,说明需要合并这两个区域。记录下此相邻肤色像素的区域号,之后便可以将当前像素归到这个皮肤区域里了。 遍历完所有相邻像素后,分两种情况处理 1. 所有相邻像素都不是肤色像素:发现了新的皮肤区域 2. 存在区域号为有效值的相邻肤色像素:region 的中存储的值有用了,把当前像素归到这个相邻像素所在的区域 ```python # 遍历完所有相邻像素后,若 region 仍等于 -1,说明所有相邻像素都不是肤色像素 if region == -1: # 更改属性为新的区域号,注意元祖是不可变类型,不能直接更改属性 _skin = self.skin_map[_id - 1]._replace(region=len(self.detected_regions)) self.skin_map[_id - 1] = _skin # 将此肤色像素所在区域创建为新区域 self.detected_regions.append([self.skin_map[_id - 1]]) # region 不等于 -1 的同时不等于 None,说明有区域号为有效值的相邻肤色像素 elif region != None: # 将此像素的区域号更改为与相邻像素相同 _skin = self.skin_map[_id - 1]._replace(region=region) self.skin_map[_id - 1] = _skin # 向这个区域的像素列表中添加此像素 self.detected_regions[region].append(self.skin_map[_id - 1]) ``` > - `somenamedtuple._replace(kwargs)` 返回一个替换指定字段的值为参数的 `namedtuple` 实例 遍历完所有像素之后,图片的皮肤区域划分初步完成了,只是在变量 `self.merge_regions` 中还有一些连通的皮肤区域号,它们需要合并,合并之后就可以进行色情图片判定了 ```python # 完成所有区域合并任务,合并整理后的区域存储到 self.skin_regions self._merge(self.detected_regions, self.merge_regions) # 分析皮肤区域,得到判定结果 self._analyse_regions() return self ``` 方法 `self._merge()` 便是用来合并这些连通的皮肤区域的 方法 `self._analyse_regions()`,运用之前在程序原理一节定义的非色情图像判定规则,从而得到判定结果 现在编写我们还没写过的调用过的 `Nude` 类的方法 首先是 `self._classify_skin()` 方法,这个方法是检测像素颜色是否为肤色,之前在程序原理一节已经把肤色判定该公式列举了出来,现在是用的时候了 ```python # 基于像素的肤色检测技术 def _classify_skin(self, r, g, b): # 根据RGB值判定 rgb_classifier = r > 95 and \\ g > 40 and g < 100 and \\ b > 20 and \\ max([r, g, b]) - min([r, g, b]) > 15 and \\ abs(r - g) > 15 and \\ r > g and \\ r > b # 根据处理后的 RGB 值判定 nr, ng, nb = self._to_normalized(r, g, b) norm_rgb_classifier = nr / ng > 1.185 and \\ float(r * b) / ((r + g + b) ** 2) > 0.107 and \\ float(r * g) / ((r + g + b) ** 2) > 0.112 # HSV 颜色模式下的判定 h, s, v = self._to_hsv(r, g, b) hsv_classifier = h > 0 and \\ h < 35 and \\ s > 0.23 and \\ s < 0.68 # YCbCr 颜色模式下的判定 y, cb, cr = self._to_ycbcr(r, g, b) ycbcr_classifier = 97.5 <= cb <= 142.5 and 134 <= cr <= 176 # 效果不是很好,还需改公式 # return rgb_classifier or norm_rgb_classifier or hsv_classifier or ycbcr_classifier return ycbcr_classifier ``` 颜色模式的转换并不是本实验的重点,转换公式可以在网上找到,这里我们直接拿来用就行 ```python def _to_normalized(self, r, g, b): if r == 0: r = 0.0001 if g == 0: g = 0.0001 if b == 0: b = 0.0001 _sum = float(r + g + b) return [r / _sum, g / _sum, b / _sum] def _to_ycbcr(self, r, g, b): # 公式来源: # http://stackoverflow.com/questions/19459831/rgb-to-ycbcr-conversion-problems y = .299*r + .587*g + .114*b cb = 128 - 0.168736*r - 0.331364*g + 0.5*b cr = 128 + 0.5*r - 0.418688*g - 0.081312*b return y, cb, cr def _to_hsv(self, r, g, b): h = 0 _sum = float(r + g + b) _max = float(max([r, g, b])) _min = float(min([r, g, b])) diff = float(_max - _min) if _sum == 0: _sum = 0.0001 if _max == r: if diff == 0: h = sys.maxsize else: h = (g - b) / diff elif _max == g: h = 2 + ((g - r) / diff) else: h = 4 + ((r - g) / diff) h *= 60 if h < 0: h += 360 return [h, 1.0 - (3.0 * (_min / _sum)), (1.0 / 3.0) * _max] ``` `self._add_merge()` 方法主要是对 `self.merge_regions` 操作,而self.merge_regions 的元素都是包含一些 int 对象(区域号)的列表,列表中的区域号代表的区域都是待合并的区域 `self._add_merge()` 方法接收两个区域号,将之添加到 `self.merge_regions`中 这两个区域号以怎样的形式添加,要分3种情况处理, 1. 传入的两个区域号都存在于 `self.merge_regions` 中 2. 传入的两个区域号有一个区域号存在于 `self.merge_regions` 中 3. 传入的两个区域号都不存在于 `self.merge_regions` 中 具体的处理方法,见代码 ```python def _add_merge(self, _from, _to): # 两个区域号赋值给类属性 self.last_from = _from self.last_to = _to # 记录 self.merge_regions 的某个索引值,初始化为 -1 from_index = -1 # 记录 self.merge_regions 的某个索引值,初始化为 -1 to_index = -1 # 遍历每个 self.merge_regions 的元素 for index, region in enumerate(self.merge_regions): # 遍历元素中的每个区域号 for r_index in region: if r_index == _from: from_index = index if r_index == _to: to_index = index # 若两个区域号都存在于 self.merge_regions 中 if from_index != -1 and to_index != -1: # 如果这两个区域号分别存在于两个列表中 # 那么合并这两个列表 if from_index != to_index: self.merge_regions[from_index].extend(self.merge_regions[to_index]) del(self.merge_regions[to_index]) return # 若两个区域号都不存在于 self.merge_regions 中 if from_index == -1 and to_index == -1: # 创建新的区域号列表 self.merge_regions.append([_from, _to]) return # 若两个区域号中有一个存在于 self.merge_regions 中 if from_index != -1 and to_index == -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[from_index].append(_to) return # 若两个待合并的区域号中有一个存在于 self.merge_regions 中 if from_index == -1 and to_index != -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[to_index].append(_from) return ``` 在序列中循环时,索引位置和对应值可以使用 [enumerate()](https://docs.python.org/3/library/functions.html#enumerate) 函数同时得到,在上面的代码中,索引位置即为 `index` ,对应值即为`region` `self._merge()` 方法则是将 `self.merge_regions` 中的元素中的区域号所代表的区域合并,得到新的皮肤区域列表 ```python def _merge(self, detected_regions, merge_regions): # 新建列表 new_detected_regions # 其元素将是包含一些代表像素的 Skin 对象的列表 # new_detected_regions 的元素即代表皮肤区域,元素索引为区域号 new_detected_regions = [] # 将 merge_regions 中的元素中的区域号代表的所有区域合并 for index, region in enumerate(merge_regions): try: new_detected_regions[index] except IndexError: new_detected_regions.append([]) for r_index in region: new_detected_regions[index].extend(detected_regions[r_index]) detected_regions[r_index] = [] # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) ``` `self._clear_regions()` 方法只将像素数大于指定数量的皮肤区域保留到 `self.skin_regions` ```python # 皮肤区域清理函数 # 只保存像素数大于指定数量的皮肤区域 def _clear_regions(self, detected_regions): for region in detected_regions: if len(region) > 30: self.skin_regions.append(region) ``` `self._analyse_regions()` 是很简单的,它的工作只是进行一系列判断,得出图片是否色情的结论 ```python # 分析区域 def _analyse_regions(self): # 如果皮肤区域小于 3 个,不是色情 if len(self.skin_regions) < 3: self.message = "Less than 3 skin regions ({_skin_regions_size})".format( _skin_regions_size=len(self.skin_regions)) self.result = False return self.result # 为皮肤区域排序 self.skin_regions = sorted(self.skin_regions, key=lambda s: len(s), reverse=True) # 计算皮肤总像素数 total_skin = float(sum([len(skin_region) for skin_region in self.skin_regions])) # 如果皮肤区域与整个图像的比值小于 15%,那么不是色情图片 if total_skin / self.total_pixels * 100 < 15: self.message = "Total skin percentage lower than 15 ({:.2f})".format(total_skin / self.total_pixels * 100) self.result = False return self.result # 如果最大皮肤区域小于总皮肤面积的 45%,不是色情图片 if len(self.skin_regions[0]) / total_skin * 100 < 45: self.message = "The biggest region contains less than 45 ({:.2f})".format(len(self.skin_regions[0]) / total_skin * 100) self.result = False return self.result # 皮肤区域数量超过 60个,不是色情图片 if len(self.skin_regions) > 60: self.message = "More than 60 skin regions ({})".format(len(self.skin_regions)) self.result = False return self.result # 其它情况为色情图片 self.message = "Nude!!" self.result = True return self.result ``` 然后可以组织下分析得出的信息 ```python def inspect(self): _image = '{} {} {}×{}'.format(self.image.filename, self.image.format, self.width, self.height) return "{_image}: result={_result} message='{_message}'".format(_image=_image, _result=self.result, _message=self.message) ``` `Nude` 类如果就这样完成了,最后运行脚本时只能得到一些真或假的结果,我们需要更直观的感受程序的分析效果,我们可以生成一张原图的副本,不过这个副本图片中只有黑白色,白色代表皮肤区域,那么这样我们能直观感受到程序分析的效果了 前面的代码中我们有获得图像的像素的 RGB 值的操作,设置像素的 RGB 值也就是其逆操作,还是很简单的,不过注意设置像素的 RGB 值时不能在原图上操作 ```python # 将在源文件目录生成图片文件,将皮肤区域可视化 def showSkinRegions(self): # 未得出结果时方法返回 if self.result is None: return # 皮肤像素的 ID 的集合 skinIdSet = set() # 将原图做一份拷贝 simage = self.image # 加载数据 simageData = simage.load() # 将皮肤像素的 id 存入 skinIdSet for sr in self.skin_regions: for pixel in sr: skinIdSet.add(pixel.id) # 将图像中的皮肤像素设为白色,其余设为黑色 for pixel in self.skin_map: if pixel.id not in skinIdSet: simageData[pixel.x, pixel.y] = 0, 0, 0 else: simageData[pixel.x, pixel.y] = 255, 255, 255 # 源文件绝对路径 filePath = os.path.abspath(self.image.filename) # 源文件所在目录 fileDirectory = os.path.dirname(filePath) + '/' # 源文件的完整文件名 fileFullName = os.path.basename(filePath) # 分离源文件的完整文件名得到文件名和扩展名 fileName, fileExtName = os.path.splitext(fileFullName) # 保存图片 simage.save('{}{}_{}{}'.format(fileDirectory, fileName,'Nude' if self.result else 'Normal', fileExtName)) ``` 变量 `skinIdSet` 使用集合而不是列表是有性能上的考量的,Python 中的集合是哈希表实现的,查询效率很高 最后支持一下命令行参数就大功告成啦!我们使用 `argparse` 这个模块来实现命令行的支持。argparse 模块使得编写用户友好的命令行接口非常容易。程序只需定义好它要求的参数,然后 argparse 将负责如何从 sys.argv 中解析出这些参数。argparse 模块还会自动生成帮助和使用信息并且当用户赋给程序非法的参数时产生错误信息 具体使用方法请查看argparse的 [官方文档](https://docs.python.org/3/library/argparse.html),这里就不多说了 ```python if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Detect nudity in images.') parser.add_argument('files', metavar='image', nargs='+', help='Images you wish to test') parser.add_argument('-r', '--resize', action='store_true', help='Reduce image size to increase speed of scanning') parser.add_argument('-v', '--visualization', action='store_true', help='Generating areas of skin image') args = parser.parse_args() for fname in args.files: if os.path.isfile(fname): n = Nude(fname) if args.resize: n.resize(maxheight=800, maxwidth=600) n.parse() if args.visualization: n.showSkinRegions() print(n.result, n.inspect()) else: print(fname, "is not a file") ``` ### 2.4. 测试效果 使用 `wget` 把测试用图片下载下来 ```sh $ wget http://labfile.oss.aliyuncs.com/courses/589/1.jpg ``` 假设你的脚本名为 nude.py,运行下面的命令执行脚本,注意是 `python3` 而不是`python` ```sh $ python3 nude.py -v 0.jpg 1.jpg ``` 现在你可以等待程序结果,结果出来后,你还可以查看 `-v` 选项生成的效果展示图片 ## 三、实验总结 本次实验熟悉了下 PIL 的使用,了解了色情图片检测的原理,整个实验难点是在皮肤区域的检测与整合这一方面,这方面不是很清楚的同学多多阅读思考,如果有什么疑问或者建议的话可以留言,实验楼会尽力解答你的问题,建议写下实验报告,将自己的思考过程记录下来是很有好处的 本实验还有许多可以改进的地方,比如肤色检测的公式,色情判定条件,还有性能问题,同学可以自己尝试改进,比如性能问题可以尝试多线程或多进程 ## 四、完整代码 代码也可以下载下来 ```sh $ wget http://labfile.oss.aliyuncs.com/courses/589/nude.py ``` 代码: ```python import sys import os import _io from collections import namedtuple from PIL import Image class Nude(object): Skin = namedtuple("Skin", "id skin region x y") def __init__(self, path_or_image): # 若 path_or_image 为 Image.Image 类型的实例,直接赋值 if isinstance(path_or_image, Image.Image): self.image = path_or_image # 若 path_or_image 为 str 类型的实例,打开图片 elif isinstance(path_or_image, str): self.image = Image.open(path_or_image) # 获得图片所有颜色通道 bands = self.image.getbands() # 判断是否为单通道图片(也即灰度图),是则将灰度图转换为 RGB 图 if len(bands) == 1: # 新建相同大小的 RGB 图像 new_img = Image.new("RGB", self.image.size) # 拷贝灰度图 self.image 到 RGB图 new_img.paste (PIL 自动进行颜色通道转换) new_img.paste(self.image) f = self.image.filename # 替换 self.image self.image = new_img self.image.filename = f # 存储对应图像所有像素的全部 Skin 对象 self.skin_map = [] # 检测到的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.detected_regions = [] # 元素都是包含一些 int 对象(区域号)的列表 # 这些元素中的区域号代表的区域都是待合并的区域 self.merge_regions = [] # 整合后的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.skin_regions = [] # 最近合并的两个皮肤区域的区域号,初始化为 -1 self.last_from, self.last_to = -1, -1 # 色情图像判断结果 self.result = None # 处理得到的信息 self.message = None # 图像宽高 self.width, self.height = self.image.size # 图像总像素 self.total_pixels = self.width * self.height def resize(self, maxwidth=1000, maxheight=1000): """ 基于最大宽高按比例重设图片大小, 注意:这可能影响检测算法的结果 如果没有变化返回 0 原宽度大于 maxwidth 返回 1 原高度大于 maxheight 返回 2 原宽高大于 maxwidth, maxheight 返回 3 maxwidth - 图片最大宽度 maxheight - 图片最大高度 传递参数时都可以设置为 False 来忽略 """ # 存储返回值 ret = 0 if maxwidth: if self.width > maxwidth: wpercent = (maxwidth / self.width) hsize = int((self.height * wpercent)) fname = self.image.filename # Image.LANCZOS 是重采样滤波器,用于抗锯齿 self.image = self.image.resize((maxwidth, hsize), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 1 if maxheight: if self.height > maxheight: hpercent = (maxheight / float(self.height)) wsize = int((float(self.width) * float(hpercent))) fname = self.image.filename self.image = self.image.resize((wsize, maxheight), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 2 return ret # 分析函数 def parse(self): # 如果已有结果,返回本对象 if self.result is not None: return self # 获得图片所有像素数据 pixels = self.image.load() # 遍历每个像素 for y in range(self.height): for x in range(self.width): # 得到像素的 RGB 三个通道的值 # [x, y] 是 [(x,y)] 的简便写法 r = pixels[x, y][0] # red g = pixels[x, y][1] # green b = pixels[x, y][2] # blue # 判断当前像素是否为肤色像素 isSkin = True if self._classify_skin(r, g, b) else False # 给每个像素分配唯一 id 值(1, 2, 3...height*width) # 注意 x, y 的值从零开始 _id = x + y * self.width + 1 # 为每个像素创建一个对应的 Skin 对象,并添加到 self.skin_map 中 self.skin_map.append(self.Skin(_id, isSkin, None, x, y)) # 若当前像素不为肤色像素,跳过此次循环 if not isSkin: continue # 设左上角为原点,相邻像素为符号 *,当前像素为符号 ^,那么相互位置关系通常如下图 # *** # *^ # 存有相邻像素索引的列表,存放顺序为由大到小,顺序改变有影响 # 注意 _id 是从 1 开始的,对应的索引则是 _id-1 check_indexes = [_id - 2, # 当前像素左方的像素 _id - self.width - 2, # 当前像素左上方的像素 _id - self.width - 1, # 当前像素的上方的像素 _id - self.width] # 当前像素右上方的像素 # 用来记录相邻像素中肤色像素所在的区域号,初始化为 -1 region = -1 # 遍历每一个相邻像素的索引 for index in check_indexes: # 尝试索引相邻像素的 Skin 对象,没有则跳出循环 try: self.skin_map[index] except IndexError: break # 相邻像素若为肤色像素: if self.skin_map[index].skin: # 若相邻像素与当前像素的 region 均为有效值,且二者不同,且尚未添加相同的合并任务 if (self.skin_map[index].region != None and region != None and region != -1 and self.skin_map[index].region != region and self.last_from != region and self.last_to != self.skin_map[index].region) : # 那么这添加这两个区域的合并任务 self._add_merge(region, self.skin_map[index].region) # 记录此相邻像素所在的区域号 region = self.skin_map[index].region # 遍历完所有相邻像素后,若 region 仍等于 -1,说明所有相邻像素都不是肤色像素 if region == -1: # 更改属性为新的区域号,注意元祖是不可变类型,不能直接更改属性 _skin = self.skin_map[_id - 1]._replace(region=len(self.detected_regions)) self.skin_map[_id - 1] = _skin # 将此肤色像素所在区域创建为新区域 self.detected_regions.append([self.skin_map[_id - 1]]) # region 不等于 -1 的同时不等于 None,说明有区域号为有效值的相邻肤色像素 elif region != None: # 将此像素的区域号更改为与相邻像素相同 _skin = self.skin_map[_id - 1]._replace(region=region) self.skin_map[_id - 1] = _skin # 向这个区域的像素列表中添加此像素 self.detected_regions[region].append(self.skin_map[_id - 1]) # 完成所有区域合并任务,合并整理后的区域存储到 self.skin_regions self._merge(self.detected_regions, self.merge_regions) # 分析皮肤区域,得到判定结果 self._analyse_regions() return self # self.merge_regions 的元素都是包含一些 int 对象(区域号)的列表 # self.merge_regions 的元素中的区域号代表的区域都是待合并的区域 # 这个方法便是将两个待合并的区域号添加到 self.merge_regions 中 def _add_merge(self, _from, _to): # 两个区域号赋值给类属性 self.last_from = _from self.last_to = _to # 记录 self.merge_regions 的某个索引值,初始化为 -1 from_index = -1 # 记录 self.merge_regions 的某个索引值,初始化为 -1 to_index = -1 # 遍历每个 self.merge_regions 的元素 for index, region in enumerate(self.merge_regions): # 遍历元素中的每个区域号 for r_index in region: if r_index == _from: from_index = index if r_index == _to: to_index = index # 若两个区域号都存在于 self.merge_regions 中 if from_index != -1 and to_index != -1: # 如果这两个区域号分别存在于两个列表中 # 那么合并这两个列表 if from_index != to_index: self.merge_regions[from_index].extend(self.merge_regions[to_index]) del(self.merge_regions[to_index]) return # 若两个区域号都不存在于 self.merge_regions 中 if from_index == -1 and to_index == -1: # 创建新的区域号列表 self.merge_regions.append([_from, _to]) return # 若两个区域号中有一个存在于 self.merge_regions 中 if from_index != -1 and to_index == -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[from_index].append(_to) return # 若两个待合并的区域号中有一个存在于 self.merge_regions 中 if from_index == -1 and to_index != -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[to_index].append(_from) return # 合并该合并的皮肤区域 def _merge(self, detected_regions, merge_regions): # 新建列表 new_detected_regions # 其元素将是包含一些代表像素的 Skin 对象的列表 # new_detected_regions 的元素即代表皮肤区域,元素索引为区域号 new_detected_regions = [] # 将 merge_regions 中的元素中的区域号代表的所有区域合并 for index, region in enumerate(merge_regions): try: new_detected_regions[index] except IndexError: new_detected_regions.append([]) for r_index in region: new_detected_regions[index].extend(detected_regions[r_index]) detected_regions[r_index] = [] # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) # 皮肤区域清理函数 # 只保存像素数大于指定数量的皮肤区域 def _clear_regions(self, detected_regions): for region in detected_regions: if len(region) > 30: self.skin_regions.append(region) # 分析区域 def _analyse_regions(self): # 如果皮肤区域小于 3 个,不是色情 if len(self.skin_regions) < 3: self.message = "Less than 3 skin regions ({_skin_regions_size})".format( _skin_regions_size=len(self.skin_regions)) self.result = False return self.result # 为皮肤区域排序 self.skin_regions = sorted(self.skin_regions, key=lambda s: len(s), reverse=True) # 计算皮肤总像素数 total_skin = float(sum([len(skin_region) for skin_region in self.skin_regions])) # 如果皮肤区域与整个图像的比值小于 15%,那么不是色情图片 if total_skin / self.total_pixels * 100 < 15: self.message = "Total skin percentage lower than 15 ({:.2f})".format(total_skin / self.total_pixels * 100) self.result = False return self.result # 如果最大皮肤区域小于总皮肤面积的 45%,不是色情图片 if len(self.skin_regions[0]) / total_skin * 100 < 45: self.message = "The biggest region contains less than 45 ({:.2f})".format(len(self.skin_regions[0]) / total_skin * 100) self.result = False return self.result # 皮肤区域数量超过 60个,不是色情图片 if len(self.skin_regions) > 60: self.message = "More than 60 skin regions ({})".format(len(self.skin_regions)) self.result = False return self.result # 其它情况为色情图片 self.message = "Nude!!" self.result = True return self.result # 基于像素的肤色检测技术 def _classify_skin(self, r, g, b): # 根据RGB值判定 rgb_classifier = r > 95 and \\ g > 40 and g < 100 and \\ b > 20 and \\ max([r, g, b]) - min([r, g, b]) > 15 and \\ abs(r - g) > 15 and \\ r > g and \\ r > b # 根据处理后的 RGB 值判定 nr, ng, nb = self._to_normalized(r, g, b) norm_rgb_classifier = nr / ng > 1.185 and \\ float(r * b) / ((r + g + b) ** 2) > 0.107 and \\ float(r * g) / ((r + g + b) ** 2) > 0.112 # HSV 颜色模式下的判定 h, s, v = self._to_hsv(r, g, b) hsv_classifier = h > 0 and \\ h < 35 and \\ s > 0.23 and \\ s < 0.68 # YCbCr 颜色模式下的判定 y, cb, cr = self._to_ycbcr(r, g, b) ycbcr_classifier = 97.5 <= cb <= 142.5 and 134 <= cr <= 176 # 效果不是很好,还需改公式 # return rgb_classifier or norm_rgb_classifier or hsv_classifier or ycbcr_classifier return ycbcr_classifier def _to_normalized(self, r, g, b): if r == 0: r = 0.0001 if g == 0: g = 0.0001 if b == 0: b = 0.0001 _sum = float(r + g + b) return [r / _sum, g / _sum, b / _sum] def _to_ycbcr(self, r, g, b): # 公式来源: # http://stackoverflow.com/questions/19459831/rgb-to-ycbcr-conversion-problems y = .299*r + .587*g + .114*b cb = 128 - 0.168736*r - 0.331364*g + 0.5*b cr = 128 + 0.5*r - 0.418688*g - 0.081312*b return y, cb, cr def _to_hsv(self, r, g, b): h = 0 _sum = float(r + g + b) _max = float(max([r, g, b])) _min = float(min([r, g, b])) diff = float(_max - _min) if _sum == 0: _sum = 0.0001 if _max == r: if diff == 0: h = sys.maxsize else: h = (g - b) / diff elif _max == g: h = 2 + ((g - r) / diff) else: h = 4 + ((r - g) / diff) h *= 60 if h < 0: h += 360 return [h, 1.0 - (3.0 * (_min / _sum)), (1.0 / 3.0) * _max] def inspect(self): _image = '{} {} {}×{}'.format(self.image.filename, self.image.format, self.width, self.height) return "{_image}: result={_result} message='{_message}'".format(_image=_image, _result=self.result, _message=self.message) # 将在源文件目录生成图片文件,将皮肤区域可视化 def showSkinRegions(self): # 未得出结果时方法返回 if self.result is None: return # 皮肤像素的 ID 的集合 skinIdSet = set() # 将原图做一份拷贝 simage = self.image # 加载数据 simageData = simage.load() # 将皮肤像素的 id 存入 skinIdSet for sr in self.skin_regions: for pixel in sr: skinIdSet.add(pixel.id) # 将图像中的皮肤像素设为白色,其余设为黑色 for pixel in self.skin_map: if pixel.id not in skinIdSet: simageData[pixel.x, pixel.y] = 0, 0, 0 else: simageData[pixel.x, pixel.y] = 255, 255, 255 # 源文件绝对路径 filePath = os.path.abspath(self.image.filename) # 源文件所在目录 fileDirectory = os.path.dirname(filePath) + '/' # 源文件的完整文件名 fileFullName = os.path.basename(filePath) # 分离源文件的完整文件名得到文件名和扩展名 fileName, fileExtName = os.path.splitext(fileFullName) # 保存图片 simage.save('{}{}_{}{}'.format(fileDirectory, fileName,'Nude' if self.result else 'Normal', fileExtName)) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Detect nudity in images.') parser.add_argument('files', metavar='image', nargs='+', help='Images you wish to test') parser.add_argument('-r', '--resize', action='store_true', help='Reduce image size to increase speed of scanning') parser.add_argument('-v', '--visualization', action='store_true', help='Generating areas of skin image') args = parser.parse_args() for fname in args.files: if os.path.isfile(fname): n = Nude(fname) if args.resize: n.resize(maxheight=800, maxwidth=600) n.parse() if args.visualization: n.showSkinRegions() print(n.result, n.inspect()) else: print(fname, "is not a file") ``` ''' tags: [] isStarred: false isTrashed: false
true
createdAt: "2018-05-18T06:08:03.074Z" updatedAt: "2018-05-18T06:08:05.862Z" type: "MARKDOWN_NOTE" folder: "46ccafb94878584d989c" title: "Python 3 色情图片识别" content: ''' # Python 3 色情图片识别 ## 一、实验简介 ### 1.1 实验内容 本实验将使用 Python3 去识别图片是否为色情图片,我们会使用到 PIL 这个图像处理库,会编写算法来划分图像的皮肤区域 ### 1.2 实验知识点 - Python 3 的模块的安装 - Python 3 基础知识 - 肤色像素检测与皮肤区域划分算法 - [Pillow](https://pillow.readthedocs.io/en/latest/index.html) 模块的使用 - [argparse](https://docs.python.org/3/library/argparse.html) 模块的使用 ### 1.3 效果展示 ![img](https://labfile.oss.aliyuncs.com/courses/589/%E6%8D%95%E8%8E%B7.PNG) ![img](https://labfile.oss.aliyuncs.com/courses/589/%E6%8D%95%E8%8E%B73.PNG) ## 二、实验步骤 ### 2.1 安装相关包 PIL 2009年之后就没有更新了,也不支持 Python3 ,于是有了 PI:NAME:<NAME>END_PI 领导的公益项目 [Pillow](https://github.com/python-pillow/Pillow),Pillow 是一个对 PIL 友好的分支,支持 Python3,所以我们这里安装的是 Pillow,其[官方文档](https://pillow.readthedocs.io/en/latest/index.html) 安装前更新源 ```sh $ sudo apt-get update ``` 首先我们需要处理一个问题:当前实验楼的环境中 python3 命令使用的 python 版本为 3.5,但源中却没有 python3.5-dev,这会导致安装 Pillow 出错。所以我们必须将 python3 命令使用的 python 版本切换为 3.4,然后再安装 python3-dev 和 python3-setuptools。 ```sh $ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.4 70 --slave /usr/bin/python3m python3m /usr/bin/python3.4m $ sudo apt-get install python3-dev python3-setuptools ``` 然后安装 Pillow 依赖包 ```sh $ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev \\ libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk ``` 安装 `pip3`,`pip` 是 Python2 的软件包管理系统,使用它来安装 Python2 的模块非常简便,而 `pip3` 则是对应于 Python3 的版本 ```sh $ sudo apt-get install python3-pip ``` 最后安装 Pillow: ```sh $ sudo pip3 install Pillow ``` ### 2.2 程序原理 本程序根据颜色(肤色)找出图片中皮肤的区域,然后通过一些条件判断是否为色情图片 程序的关键步骤如下 1. 遍历每个像素,检测像素颜色是否为肤色 2. 将相邻的肤色像素归为一个皮肤区域,得到若干个皮肤区域 3. 剔除像素数量极少的皮肤区域 我们定义**非**色情图片的判定规则如下(满足任意一个判定为真): 1. 皮肤区域的个数小于 3 个 2. 皮肤区域的像素与图像所有像素的比值小于 15% 3. 最大皮肤区域小于总皮肤面积的 45% 4. 皮肤区域数量超过60个 这些规则你可以尝试更改,直到程序效果让你满意为止 关于像素肤色判定这方面,公式可以在网上找到很多,但世界上不可能有正确率 100% 的公式 你可以用自己找到的公式,在程序完成后慢慢调试 - RGB 颜色模式 第一种:`r > 95 and g > 40 and g < 100 and b > 20 and max([r, g, b]) - min([r, g, b]) > 15 and abs(r - g) > 15 and r > g and r > b` 第二种:`nr = r / (r + g + b), ng = g / (r + g + b), nb = b / (r +g + b)`, `nr / ng > 1.185 and r * b / (r + g + b) ** 2 > 0.107 and r * g / (r + g + b) ** 2 > 0.112` - HSV 颜色模式 `h > 0 and h < 35 and s > 0.23 and s < 0.68` - YCbCr 颜色模式 `97.5 <= cb <= 142.5 and 134 <= cr <= 176` 一幅图像有零个到多个的皮肤区域,程序按发现顺序给它们编号,第一个发现的区域编号为 0,第 n 个发现的区域编号为 n-1 我们用一种类型来表示像素,我们给这个类型取名为 `Skin`,包含了像素的一些信息:唯一的 编号(`id`),是/否肤色(`skin`),皮肤区域号(`region`),横坐标(`x`),纵坐标(`y`) 遍历所有像素时,我们为每个像素创建一个与之对应的 `Skin` 对象,并设置对象的所有属性 其中 `region` 属性即为像素所在的皮肤区域编号,创建对象时初始化为无意义的 `None` 关于每个像素的 id 值,左上角为原点,像素的 id 值按像素坐标排布,那么看起来如下图 ![img](https://labfile.oss.aliyuncs.com/courses/589/id%20%E6%8E%92%E5%B8%83%E5%9B%BE.PNG) 其实 id 的顺序也即遍历的顺序 遍历所有像素时,创建 `Skin` 对象后,如果当前像素为肤色,且相邻的像素有肤色的,那么我们把这些肤色像素归到一个皮肤区域 相邻像素的定义:通常都能想到是当前像素周围的 **8** 个像素,然而实际上只需要定义 **4** 个就可以了,位置分别在当前像素的左方,左上方,正上方,右上方;因为另外四个像素都在当前像素后面,我们还未给这4个像素创建对应的 Skin 对象 ![img](https://labfile.oss.aliyuncs.com/courses/589/%E7%9B%B8%E9%82%BB%E5%83%8F%E7%B4%A0.png) 接下来实现细节部分 ### 2.3 实现脚本 导入所需要的模块 ```python import sys import os import _io from collections import namedtuple from PIL import Image ``` 我们将设计一个 `Nude` 类: ```python class Nude(object): ``` 这个类里面我们首先使用 `collections.namedtuple()` 定义一个 `Skin` 类型 ```python Skin = namedtuple("Skin", "id skin region x y") ``` `collections.namedtuple()` 函数实际上是一个返回Python中标准元组类型子类的一个工厂方法。 你需要传递一个类型名和你需要的字段给它,然后它就会返回一个类,你可以初始化这个类,为你定义的字段传递值等。 详情参见[官方文档](https://docs.python.org/3/library/collections.html#collections.namedtuple)。 然后定义 `Nude` 类的初始化方法 ```python def __init__(self, path_or_image): # 若 path_or_image 为 Image.Image 类型的实例,直接赋值 if isinstance(path_or_image, Image.Image): self.image = path_or_image # 若 path_or_image 为 str 类型的实例,打开图片 elif isinstance(path_or_image, str): self.image = Image.open(path_or_image) # 获得图片所有颜色通道 bands = self.image.getbands() # 判断是否为单通道图片(也即灰度图),是则将灰度图转换为 RGB 图 if len(bands) == 1: # 新建相同大小的 RGB 图像 new_img = Image.new("RGB", self.image.size) # 拷贝灰度图 self.image 到 RGB图 new_img.paste (PIL 自动进行颜色通道转换) new_img.paste(self.image) f = self.image.filename # 替换 self.image self.image = new_img self.image.filename = f # 存储对应图像所有像素的全部 Skin 对象 self.skin_map = [] # 检测到的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.detected_regions = [] # 元素都是包含一些 int 对象(区域号)的列表 # 这些元素中的区域号代表的区域都是待合并的区域 self.merge_regions = [] # 整合后的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.skin_regions = [] # 最近合并的两个皮肤区域的区域号,初始化为 -1 self.last_from, self.last_to = -1, -1 # 色情图像判断结果 self.result = None # 处理得到的信息 self.message = None # 图像宽高 self.width, self.height = self.image.size # 图像总像素 self.total_pixels = self.width * self.height ``` 本实验代码中使用到的模块中的函数均可以在其模块的文档中找到,一定要培养查阅文档的习惯 > - `isinstane(object, classinfo)` 如果参数 `object` 是参数 `classinfo` 的实例,返回真,否则假;参数 `classinfo` 可以是一个包含若干 `type` 对象的元祖,如果参数 `object` 是其中任意一个类型的实例,返回真,否则假 涉及到效率问题,越大的图片所需要消耗的资源与时间越大,因此有时候可能需要对图片进行缩小 所以需要有图片缩小方法 ```python def resize(self, maxwidth=1000, maxheight=1000): """ 基于最大宽高按比例重设图片大小, 注意:这可能影响检测算法的结果 如果没有变化返回 0 原宽度大于 maxwidth 返回 1 原高度大于 maxheight 返回 2 原宽高大于 maxwidth, maxheight 返回 3 maxwidth - 图片最大宽度 maxheight - 图片最大高度 传递参数时都可以设置为 False 来忽略 """ # 存储返回值 ret = 0 if maxwidth: if self.width > maxwidth: wpercent = (maxwidth / self.width) hsize = int((self.height * wpercent)) fname = self.image.filename # Image.LANCZOS 是重采样滤波器,用于抗锯齿 self.image = self.image.resize((maxwidth, hsize), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 1 if maxheight: if self.height > maxheight: hpercent = (maxheight / float(self.height)) wsize = int((float(self.width) * float(hpercent))) fname = self.image.filename self.image = self.image.resize((wsize, maxheight), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 2 return ret ``` > - `Image.resize(size, resample=0)` > > size – 包含宽高像素数的元祖 (width, height) resample – 可选的重采样滤波器 > > 返回 `Image` 对象 然后便是最关键之一的解析方法了 ```python def parse(self): # 如果已有结果,返回本对象 if self.result is not None: return self # 获得图片所有像素数据 pixels = self.image.load() ``` 接着,遍历每个像素,为每个像素创建对应的 `Skin` 对象,代码见下 其中 `self._classify_skin()` 这个方法是检测像素颜色是否为肤色 ```python for y in range(self.height): for x in range(self.width): # 得到像素的 RGB 三个通道的值 # [x, y] 是 [(x,y)] 的简便写法 r = pixels[x, y][0] # red g = pixels[x, y][1] # green b = pixels[x, y][2] # blue # 判断当前像素是否为肤色像素 isSkin = True if self._classify_skin(r, g, b) else False # 给每个像素分配唯一 id 值(1, 2, 3...height*width) # 注意 x, y 的值从零开始 _id = x + y * self.width + 1 # 为每个像素创建一个对应的 Skin 对象,并添加到 self.skin_map 中 self.skin_map.append(self.Skin(_id, isSkin, None, x, y)) ``` 若当前像素并不是肤色,那么跳过本次循环,继续遍历 ```python # 若当前像素不为肤色像素,跳过此次循环 if not isSkin: continue ``` 若当前像素是肤色像素,那么就需要处理了,先遍历其相邻像素 一定要注意相邻像素的索引值,因为像素的 `id` 值是从 **1** 开始编起的,而索引是从 **0** 编起的。变量 `_id` 是存有当前像素的 `id` 值, 所以当前像素在 `self.skin_map` 中的索引值为 `_id - 1`,以此类推,那么其左方的相邻像素在 `self.skin_map` 中的索引值为 `_id - 1 - 1` ,左上方为 `_id - 1 - self.width - 1`,上方为 `_id - 1 - self.width` ,右上方为 `_id - 1 - self.width + 1` ```python # 设左上角为原点,相邻像素为符号 *,当前像素为符号 ^,那么相互位置关系通常如下图 # *** # *^ # 存有相邻像素索引的列表,存放顺序为由大到小,顺序改变有影响 # 注意 _id 是从 1 开始的,对应的索引则是 _id-1 check_indexes = [_id - 2, # 当前像素左方的像素 _id - self.width - 2, # 当前像素左上方的像素 _id - self.width - 1, # 当前像素的上方的像素 _id - self.width] # 当前像素右上方的像素 ``` 说起来复杂,其实看上面代码并不复杂,说这么多是怕同学搞混,你要是觉得有点绕的话,你也可以把 `id` 值从 0 编起 ```python # 用来记录相邻像素中肤色像素所在的区域号,初始化为 -1 region = -1 # 遍历每一个相邻像素的索引 for index in check_indexes: # 尝试索引相邻像素的 Skin 对象,没有则跳出循环 try: self.skin_map[index] except IndexError: break # 相邻像素若为肤色像素: if self.skin_map[index].skin: # 若相邻像素与当前像素的 region 均为有效值,且二者不同,且尚未添加相同的合并任务 if (self.skin_map[index].region != None and region != None and region != -1 and self.skin_map[index].region != region and self.last_from != region and self.last_to != self.skin_map[index].region) : # 那么这添加这两个区域的合并任务 self._add_merge(region, self.skin_map[index].region) # 记录此相邻像素所在的区域号 region = self.skin_map[index].region ``` `self._add_merge()` 这个方法接收两个区域号,它将会把两个区域号添加到 `self.merge_regions` 中的元素中,`self.merge_regions` 的每一个元素都是一个列表,这些列表中存放了 1 到多个的区域号,区域号代表的区域是连通的,需要合并 检测的图像里,有些前几行的像素的相邻像素并没有 4 个,所以需要用 `try`“试错” 然后相邻像素的若是肤色像素,如果两个像素的皮肤区域号都为有效值且不同,因为两个区域中的像素相邻,那么其实这两个区域是连通的,说明需要合并这两个区域。记录下此相邻肤色像素的区域号,之后便可以将当前像素归到这个皮肤区域里了。 遍历完所有相邻像素后,分两种情况处理 1. 所有相邻像素都不是肤色像素:发现了新的皮肤区域 2. 存在区域号为有效值的相邻肤色像素:region 的中存储的值有用了,把当前像素归到这个相邻像素所在的区域 ```python # 遍历完所有相邻像素后,若 region 仍等于 -1,说明所有相邻像素都不是肤色像素 if region == -1: # 更改属性为新的区域号,注意元祖是不可变类型,不能直接更改属性 _skin = self.skin_map[_id - 1]._replace(region=len(self.detected_regions)) self.skin_map[_id - 1] = _skin # 将此肤色像素所在区域创建为新区域 self.detected_regions.append([self.skin_map[_id - 1]]) # region 不等于 -1 的同时不等于 None,说明有区域号为有效值的相邻肤色像素 elif region != None: # 将此像素的区域号更改为与相邻像素相同 _skin = self.skin_map[_id - 1]._replace(region=region) self.skin_map[_id - 1] = _skin # 向这个区域的像素列表中添加此像素 self.detected_regions[region].append(self.skin_map[_id - 1]) ``` > - `somenamedtuple._replace(kwargs)` 返回一个替换指定字段的值为参数的 `namedtuple` 实例 遍历完所有像素之后,图片的皮肤区域划分初步完成了,只是在变量 `self.merge_regions` 中还有一些连通的皮肤区域号,它们需要合并,合并之后就可以进行色情图片判定了 ```python # 完成所有区域合并任务,合并整理后的区域存储到 self.skin_regions self._merge(self.detected_regions, self.merge_regions) # 分析皮肤区域,得到判定结果 self._analyse_regions() return self ``` 方法 `self._merge()` 便是用来合并这些连通的皮肤区域的 方法 `self._analyse_regions()`,运用之前在程序原理一节定义的非色情图像判定规则,从而得到判定结果 现在编写我们还没写过的调用过的 `Nude` 类的方法 首先是 `self._classify_skin()` 方法,这个方法是检测像素颜色是否为肤色,之前在程序原理一节已经把肤色判定该公式列举了出来,现在是用的时候了 ```python # 基于像素的肤色检测技术 def _classify_skin(self, r, g, b): # 根据RGB值判定 rgb_classifier = r > 95 and \\ g > 40 and g < 100 and \\ b > 20 and \\ max([r, g, b]) - min([r, g, b]) > 15 and \\ abs(r - g) > 15 and \\ r > g and \\ r > b # 根据处理后的 RGB 值判定 nr, ng, nb = self._to_normalized(r, g, b) norm_rgb_classifier = nr / ng > 1.185 and \\ float(r * b) / ((r + g + b) ** 2) > 0.107 and \\ float(r * g) / ((r + g + b) ** 2) > 0.112 # HSV 颜色模式下的判定 h, s, v = self._to_hsv(r, g, b) hsv_classifier = h > 0 and \\ h < 35 and \\ s > 0.23 and \\ s < 0.68 # YCbCr 颜色模式下的判定 y, cb, cr = self._to_ycbcr(r, g, b) ycbcr_classifier = 97.5 <= cb <= 142.5 and 134 <= cr <= 176 # 效果不是很好,还需改公式 # return rgb_classifier or norm_rgb_classifier or hsv_classifier or ycbcr_classifier return ycbcr_classifier ``` 颜色模式的转换并不是本实验的重点,转换公式可以在网上找到,这里我们直接拿来用就行 ```python def _to_normalized(self, r, g, b): if r == 0: r = 0.0001 if g == 0: g = 0.0001 if b == 0: b = 0.0001 _sum = float(r + g + b) return [r / _sum, g / _sum, b / _sum] def _to_ycbcr(self, r, g, b): # 公式来源: # http://stackoverflow.com/questions/19459831/rgb-to-ycbcr-conversion-problems y = .299*r + .587*g + .114*b cb = 128 - 0.168736*r - 0.331364*g + 0.5*b cr = 128 + 0.5*r - 0.418688*g - 0.081312*b return y, cb, cr def _to_hsv(self, r, g, b): h = 0 _sum = float(r + g + b) _max = float(max([r, g, b])) _min = float(min([r, g, b])) diff = float(_max - _min) if _sum == 0: _sum = 0.0001 if _max == r: if diff == 0: h = sys.maxsize else: h = (g - b) / diff elif _max == g: h = 2 + ((g - r) / diff) else: h = 4 + ((r - g) / diff) h *= 60 if h < 0: h += 360 return [h, 1.0 - (3.0 * (_min / _sum)), (1.0 / 3.0) * _max] ``` `self._add_merge()` 方法主要是对 `self.merge_regions` 操作,而self.merge_regions 的元素都是包含一些 int 对象(区域号)的列表,列表中的区域号代表的区域都是待合并的区域 `self._add_merge()` 方法接收两个区域号,将之添加到 `self.merge_regions`中 这两个区域号以怎样的形式添加,要分3种情况处理, 1. 传入的两个区域号都存在于 `self.merge_regions` 中 2. 传入的两个区域号有一个区域号存在于 `self.merge_regions` 中 3. 传入的两个区域号都不存在于 `self.merge_regions` 中 具体的处理方法,见代码 ```python def _add_merge(self, _from, _to): # 两个区域号赋值给类属性 self.last_from = _from self.last_to = _to # 记录 self.merge_regions 的某个索引值,初始化为 -1 from_index = -1 # 记录 self.merge_regions 的某个索引值,初始化为 -1 to_index = -1 # 遍历每个 self.merge_regions 的元素 for index, region in enumerate(self.merge_regions): # 遍历元素中的每个区域号 for r_index in region: if r_index == _from: from_index = index if r_index == _to: to_index = index # 若两个区域号都存在于 self.merge_regions 中 if from_index != -1 and to_index != -1: # 如果这两个区域号分别存在于两个列表中 # 那么合并这两个列表 if from_index != to_index: self.merge_regions[from_index].extend(self.merge_regions[to_index]) del(self.merge_regions[to_index]) return # 若两个区域号都不存在于 self.merge_regions 中 if from_index == -1 and to_index == -1: # 创建新的区域号列表 self.merge_regions.append([_from, _to]) return # 若两个区域号中有一个存在于 self.merge_regions 中 if from_index != -1 and to_index == -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[from_index].append(_to) return # 若两个待合并的区域号中有一个存在于 self.merge_regions 中 if from_index == -1 and to_index != -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[to_index].append(_from) return ``` 在序列中循环时,索引位置和对应值可以使用 [enumerate()](https://docs.python.org/3/library/functions.html#enumerate) 函数同时得到,在上面的代码中,索引位置即为 `index` ,对应值即为`region` `self._merge()` 方法则是将 `self.merge_regions` 中的元素中的区域号所代表的区域合并,得到新的皮肤区域列表 ```python def _merge(self, detected_regions, merge_regions): # 新建列表 new_detected_regions # 其元素将是包含一些代表像素的 Skin 对象的列表 # new_detected_regions 的元素即代表皮肤区域,元素索引为区域号 new_detected_regions = [] # 将 merge_regions 中的元素中的区域号代表的所有区域合并 for index, region in enumerate(merge_regions): try: new_detected_regions[index] except IndexError: new_detected_regions.append([]) for r_index in region: new_detected_regions[index].extend(detected_regions[r_index]) detected_regions[r_index] = [] # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) ``` `self._clear_regions()` 方法只将像素数大于指定数量的皮肤区域保留到 `self.skin_regions` ```python # 皮肤区域清理函数 # 只保存像素数大于指定数量的皮肤区域 def _clear_regions(self, detected_regions): for region in detected_regions: if len(region) > 30: self.skin_regions.append(region) ``` `self._analyse_regions()` 是很简单的,它的工作只是进行一系列判断,得出图片是否色情的结论 ```python # 分析区域 def _analyse_regions(self): # 如果皮肤区域小于 3 个,不是色情 if len(self.skin_regions) < 3: self.message = "Less than 3 skin regions ({_skin_regions_size})".format( _skin_regions_size=len(self.skin_regions)) self.result = False return self.result # 为皮肤区域排序 self.skin_regions = sorted(self.skin_regions, key=lambda s: len(s), reverse=True) # 计算皮肤总像素数 total_skin = float(sum([len(skin_region) for skin_region in self.skin_regions])) # 如果皮肤区域与整个图像的比值小于 15%,那么不是色情图片 if total_skin / self.total_pixels * 100 < 15: self.message = "Total skin percentage lower than 15 ({:.2f})".format(total_skin / self.total_pixels * 100) self.result = False return self.result # 如果最大皮肤区域小于总皮肤面积的 45%,不是色情图片 if len(self.skin_regions[0]) / total_skin * 100 < 45: self.message = "The biggest region contains less than 45 ({:.2f})".format(len(self.skin_regions[0]) / total_skin * 100) self.result = False return self.result # 皮肤区域数量超过 60个,不是色情图片 if len(self.skin_regions) > 60: self.message = "More than 60 skin regions ({})".format(len(self.skin_regions)) self.result = False return self.result # 其它情况为色情图片 self.message = "Nude!!" self.result = True return self.result ``` 然后可以组织下分析得出的信息 ```python def inspect(self): _image = '{} {} {}×{}'.format(self.image.filename, self.image.format, self.width, self.height) return "{_image}: result={_result} message='{_message}'".format(_image=_image, _result=self.result, _message=self.message) ``` `Nude` 类如果就这样完成了,最后运行脚本时只能得到一些真或假的结果,我们需要更直观的感受程序的分析效果,我们可以生成一张原图的副本,不过这个副本图片中只有黑白色,白色代表皮肤区域,那么这样我们能直观感受到程序分析的效果了 前面的代码中我们有获得图像的像素的 RGB 值的操作,设置像素的 RGB 值也就是其逆操作,还是很简单的,不过注意设置像素的 RGB 值时不能在原图上操作 ```python # 将在源文件目录生成图片文件,将皮肤区域可视化 def showSkinRegions(self): # 未得出结果时方法返回 if self.result is None: return # 皮肤像素的 ID 的集合 skinIdSet = set() # 将原图做一份拷贝 simage = self.image # 加载数据 simageData = simage.load() # 将皮肤像素的 id 存入 skinIdSet for sr in self.skin_regions: for pixel in sr: skinIdSet.add(pixel.id) # 将图像中的皮肤像素设为白色,其余设为黑色 for pixel in self.skin_map: if pixel.id not in skinIdSet: simageData[pixel.x, pixel.y] = 0, 0, 0 else: simageData[pixel.x, pixel.y] = 255, 255, 255 # 源文件绝对路径 filePath = os.path.abspath(self.image.filename) # 源文件所在目录 fileDirectory = os.path.dirname(filePath) + '/' # 源文件的完整文件名 fileFullName = os.path.basename(filePath) # 分离源文件的完整文件名得到文件名和扩展名 fileName, fileExtName = os.path.splitext(fileFullName) # 保存图片 simage.save('{}{}_{}{}'.format(fileDirectory, fileName,'Nude' if self.result else 'Normal', fileExtName)) ``` 变量 `skinIdSet` 使用集合而不是列表是有性能上的考量的,Python 中的集合是哈希表实现的,查询效率很高 最后支持一下命令行参数就大功告成啦!我们使用 `argparse` 这个模块来实现命令行的支持。argparse 模块使得编写用户友好的命令行接口非常容易。程序只需定义好它要求的参数,然后 argparse 将负责如何从 sys.argv 中解析出这些参数。argparse 模块还会自动生成帮助和使用信息并且当用户赋给程序非法的参数时产生错误信息 具体使用方法请查看argparse的 [官方文档](https://docs.python.org/3/library/argparse.html),这里就不多说了 ```python if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Detect nudity in images.') parser.add_argument('files', metavar='image', nargs='+', help='Images you wish to test') parser.add_argument('-r', '--resize', action='store_true', help='Reduce image size to increase speed of scanning') parser.add_argument('-v', '--visualization', action='store_true', help='Generating areas of skin image') args = parser.parse_args() for fname in args.files: if os.path.isfile(fname): n = Nude(fname) if args.resize: n.resize(maxheight=800, maxwidth=600) n.parse() if args.visualization: n.showSkinRegions() print(n.result, n.inspect()) else: print(fname, "is not a file") ``` ### 2.4. 测试效果 使用 `wget` 把测试用图片下载下来 ```sh $ wget http://labfile.oss.aliyuncs.com/courses/589/1.jpg ``` 假设你的脚本名为 nude.py,运行下面的命令执行脚本,注意是 `python3` 而不是`python` ```sh $ python3 nude.py -v 0.jpg 1.jpg ``` 现在你可以等待程序结果,结果出来后,你还可以查看 `-v` 选项生成的效果展示图片 ## 三、实验总结 本次实验熟悉了下 PIL 的使用,了解了色情图片检测的原理,整个实验难点是在皮肤区域的检测与整合这一方面,这方面不是很清楚的同学多多阅读思考,如果有什么疑问或者建议的话可以留言,实验楼会尽力解答你的问题,建议写下实验报告,将自己的思考过程记录下来是很有好处的 本实验还有许多可以改进的地方,比如肤色检测的公式,色情判定条件,还有性能问题,同学可以自己尝试改进,比如性能问题可以尝试多线程或多进程 ## 四、完整代码 代码也可以下载下来 ```sh $ wget http://labfile.oss.aliyuncs.com/courses/589/nude.py ``` 代码: ```python import sys import os import _io from collections import namedtuple from PIL import Image class Nude(object): Skin = namedtuple("Skin", "id skin region x y") def __init__(self, path_or_image): # 若 path_or_image 为 Image.Image 类型的实例,直接赋值 if isinstance(path_or_image, Image.Image): self.image = path_or_image # 若 path_or_image 为 str 类型的实例,打开图片 elif isinstance(path_or_image, str): self.image = Image.open(path_or_image) # 获得图片所有颜色通道 bands = self.image.getbands() # 判断是否为单通道图片(也即灰度图),是则将灰度图转换为 RGB 图 if len(bands) == 1: # 新建相同大小的 RGB 图像 new_img = Image.new("RGB", self.image.size) # 拷贝灰度图 self.image 到 RGB图 new_img.paste (PIL 自动进行颜色通道转换) new_img.paste(self.image) f = self.image.filename # 替换 self.image self.image = new_img self.image.filename = f # 存储对应图像所有像素的全部 Skin 对象 self.skin_map = [] # 检测到的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.detected_regions = [] # 元素都是包含一些 int 对象(区域号)的列表 # 这些元素中的区域号代表的区域都是待合并的区域 self.merge_regions = [] # 整合后的皮肤区域,元素的索引即为皮肤区域号,元素都是包含一些 Skin 对象的列表 self.skin_regions = [] # 最近合并的两个皮肤区域的区域号,初始化为 -1 self.last_from, self.last_to = -1, -1 # 色情图像判断结果 self.result = None # 处理得到的信息 self.message = None # 图像宽高 self.width, self.height = self.image.size # 图像总像素 self.total_pixels = self.width * self.height def resize(self, maxwidth=1000, maxheight=1000): """ 基于最大宽高按比例重设图片大小, 注意:这可能影响检测算法的结果 如果没有变化返回 0 原宽度大于 maxwidth 返回 1 原高度大于 maxheight 返回 2 原宽高大于 maxwidth, maxheight 返回 3 maxwidth - 图片最大宽度 maxheight - 图片最大高度 传递参数时都可以设置为 False 来忽略 """ # 存储返回值 ret = 0 if maxwidth: if self.width > maxwidth: wpercent = (maxwidth / self.width) hsize = int((self.height * wpercent)) fname = self.image.filename # Image.LANCZOS 是重采样滤波器,用于抗锯齿 self.image = self.image.resize((maxwidth, hsize), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 1 if maxheight: if self.height > maxheight: hpercent = (maxheight / float(self.height)) wsize = int((float(self.width) * float(hpercent))) fname = self.image.filename self.image = self.image.resize((wsize, maxheight), Image.LANCZOS) self.image.filename = fname self.width, self.height = self.image.size self.total_pixels = self.width * self.height ret += 2 return ret # 分析函数 def parse(self): # 如果已有结果,返回本对象 if self.result is not None: return self # 获得图片所有像素数据 pixels = self.image.load() # 遍历每个像素 for y in range(self.height): for x in range(self.width): # 得到像素的 RGB 三个通道的值 # [x, y] 是 [(x,y)] 的简便写法 r = pixels[x, y][0] # red g = pixels[x, y][1] # green b = pixels[x, y][2] # blue # 判断当前像素是否为肤色像素 isSkin = True if self._classify_skin(r, g, b) else False # 给每个像素分配唯一 id 值(1, 2, 3...height*width) # 注意 x, y 的值从零开始 _id = x + y * self.width + 1 # 为每个像素创建一个对应的 Skin 对象,并添加到 self.skin_map 中 self.skin_map.append(self.Skin(_id, isSkin, None, x, y)) # 若当前像素不为肤色像素,跳过此次循环 if not isSkin: continue # 设左上角为原点,相邻像素为符号 *,当前像素为符号 ^,那么相互位置关系通常如下图 # *** # *^ # 存有相邻像素索引的列表,存放顺序为由大到小,顺序改变有影响 # 注意 _id 是从 1 开始的,对应的索引则是 _id-1 check_indexes = [_id - 2, # 当前像素左方的像素 _id - self.width - 2, # 当前像素左上方的像素 _id - self.width - 1, # 当前像素的上方的像素 _id - self.width] # 当前像素右上方的像素 # 用来记录相邻像素中肤色像素所在的区域号,初始化为 -1 region = -1 # 遍历每一个相邻像素的索引 for index in check_indexes: # 尝试索引相邻像素的 Skin 对象,没有则跳出循环 try: self.skin_map[index] except IndexError: break # 相邻像素若为肤色像素: if self.skin_map[index].skin: # 若相邻像素与当前像素的 region 均为有效值,且二者不同,且尚未添加相同的合并任务 if (self.skin_map[index].region != None and region != None and region != -1 and self.skin_map[index].region != region and self.last_from != region and self.last_to != self.skin_map[index].region) : # 那么这添加这两个区域的合并任务 self._add_merge(region, self.skin_map[index].region) # 记录此相邻像素所在的区域号 region = self.skin_map[index].region # 遍历完所有相邻像素后,若 region 仍等于 -1,说明所有相邻像素都不是肤色像素 if region == -1: # 更改属性为新的区域号,注意元祖是不可变类型,不能直接更改属性 _skin = self.skin_map[_id - 1]._replace(region=len(self.detected_regions)) self.skin_map[_id - 1] = _skin # 将此肤色像素所在区域创建为新区域 self.detected_regions.append([self.skin_map[_id - 1]]) # region 不等于 -1 的同时不等于 None,说明有区域号为有效值的相邻肤色像素 elif region != None: # 将此像素的区域号更改为与相邻像素相同 _skin = self.skin_map[_id - 1]._replace(region=region) self.skin_map[_id - 1] = _skin # 向这个区域的像素列表中添加此像素 self.detected_regions[region].append(self.skin_map[_id - 1]) # 完成所有区域合并任务,合并整理后的区域存储到 self.skin_regions self._merge(self.detected_regions, self.merge_regions) # 分析皮肤区域,得到判定结果 self._analyse_regions() return self # self.merge_regions 的元素都是包含一些 int 对象(区域号)的列表 # self.merge_regions 的元素中的区域号代表的区域都是待合并的区域 # 这个方法便是将两个待合并的区域号添加到 self.merge_regions 中 def _add_merge(self, _from, _to): # 两个区域号赋值给类属性 self.last_from = _from self.last_to = _to # 记录 self.merge_regions 的某个索引值,初始化为 -1 from_index = -1 # 记录 self.merge_regions 的某个索引值,初始化为 -1 to_index = -1 # 遍历每个 self.merge_regions 的元素 for index, region in enumerate(self.merge_regions): # 遍历元素中的每个区域号 for r_index in region: if r_index == _from: from_index = index if r_index == _to: to_index = index # 若两个区域号都存在于 self.merge_regions 中 if from_index != -1 and to_index != -1: # 如果这两个区域号分别存在于两个列表中 # 那么合并这两个列表 if from_index != to_index: self.merge_regions[from_index].extend(self.merge_regions[to_index]) del(self.merge_regions[to_index]) return # 若两个区域号都不存在于 self.merge_regions 中 if from_index == -1 and to_index == -1: # 创建新的区域号列表 self.merge_regions.append([_from, _to]) return # 若两个区域号中有一个存在于 self.merge_regions 中 if from_index != -1 and to_index == -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[from_index].append(_to) return # 若两个待合并的区域号中有一个存在于 self.merge_regions 中 if from_index == -1 and to_index != -1: # 将不存在于 self.merge_regions 中的那个区域号 # 添加到另一个区域号所在的列表 self.merge_regions[to_index].append(_from) return # 合并该合并的皮肤区域 def _merge(self, detected_regions, merge_regions): # 新建列表 new_detected_regions # 其元素将是包含一些代表像素的 Skin 对象的列表 # new_detected_regions 的元素即代表皮肤区域,元素索引为区域号 new_detected_regions = [] # 将 merge_regions 中的元素中的区域号代表的所有区域合并 for index, region in enumerate(merge_regions): try: new_detected_regions[index] except IndexError: new_detected_regions.append([]) for r_index in region: new_detected_regions[index].extend(detected_regions[r_index]) detected_regions[r_index] = [] # 添加剩下的其余皮肤区域到 new_detected_regions for region in detected_regions: if len(region) > 0: new_detected_regions.append(region) # 清理 new_detected_regions self._clear_regions(new_detected_regions) # 皮肤区域清理函数 # 只保存像素数大于指定数量的皮肤区域 def _clear_regions(self, detected_regions): for region in detected_regions: if len(region) > 30: self.skin_regions.append(region) # 分析区域 def _analyse_regions(self): # 如果皮肤区域小于 3 个,不是色情 if len(self.skin_regions) < 3: self.message = "Less than 3 skin regions ({_skin_regions_size})".format( _skin_regions_size=len(self.skin_regions)) self.result = False return self.result # 为皮肤区域排序 self.skin_regions = sorted(self.skin_regions, key=lambda s: len(s), reverse=True) # 计算皮肤总像素数 total_skin = float(sum([len(skin_region) for skin_region in self.skin_regions])) # 如果皮肤区域与整个图像的比值小于 15%,那么不是色情图片 if total_skin / self.total_pixels * 100 < 15: self.message = "Total skin percentage lower than 15 ({:.2f})".format(total_skin / self.total_pixels * 100) self.result = False return self.result # 如果最大皮肤区域小于总皮肤面积的 45%,不是色情图片 if len(self.skin_regions[0]) / total_skin * 100 < 45: self.message = "The biggest region contains less than 45 ({:.2f})".format(len(self.skin_regions[0]) / total_skin * 100) self.result = False return self.result # 皮肤区域数量超过 60个,不是色情图片 if len(self.skin_regions) > 60: self.message = "More than 60 skin regions ({})".format(len(self.skin_regions)) self.result = False return self.result # 其它情况为色情图片 self.message = "Nude!!" self.result = True return self.result # 基于像素的肤色检测技术 def _classify_skin(self, r, g, b): # 根据RGB值判定 rgb_classifier = r > 95 and \\ g > 40 and g < 100 and \\ b > 20 and \\ max([r, g, b]) - min([r, g, b]) > 15 and \\ abs(r - g) > 15 and \\ r > g and \\ r > b # 根据处理后的 RGB 值判定 nr, ng, nb = self._to_normalized(r, g, b) norm_rgb_classifier = nr / ng > 1.185 and \\ float(r * b) / ((r + g + b) ** 2) > 0.107 and \\ float(r * g) / ((r + g + b) ** 2) > 0.112 # HSV 颜色模式下的判定 h, s, v = self._to_hsv(r, g, b) hsv_classifier = h > 0 and \\ h < 35 and \\ s > 0.23 and \\ s < 0.68 # YCbCr 颜色模式下的判定 y, cb, cr = self._to_ycbcr(r, g, b) ycbcr_classifier = 97.5 <= cb <= 142.5 and 134 <= cr <= 176 # 效果不是很好,还需改公式 # return rgb_classifier or norm_rgb_classifier or hsv_classifier or ycbcr_classifier return ycbcr_classifier def _to_normalized(self, r, g, b): if r == 0: r = 0.0001 if g == 0: g = 0.0001 if b == 0: b = 0.0001 _sum = float(r + g + b) return [r / _sum, g / _sum, b / _sum] def _to_ycbcr(self, r, g, b): # 公式来源: # http://stackoverflow.com/questions/19459831/rgb-to-ycbcr-conversion-problems y = .299*r + .587*g + .114*b cb = 128 - 0.168736*r - 0.331364*g + 0.5*b cr = 128 + 0.5*r - 0.418688*g - 0.081312*b return y, cb, cr def _to_hsv(self, r, g, b): h = 0 _sum = float(r + g + b) _max = float(max([r, g, b])) _min = float(min([r, g, b])) diff = float(_max - _min) if _sum == 0: _sum = 0.0001 if _max == r: if diff == 0: h = sys.maxsize else: h = (g - b) / diff elif _max == g: h = 2 + ((g - r) / diff) else: h = 4 + ((r - g) / diff) h *= 60 if h < 0: h += 360 return [h, 1.0 - (3.0 * (_min / _sum)), (1.0 / 3.0) * _max] def inspect(self): _image = '{} {} {}×{}'.format(self.image.filename, self.image.format, self.width, self.height) return "{_image}: result={_result} message='{_message}'".format(_image=_image, _result=self.result, _message=self.message) # 将在源文件目录生成图片文件,将皮肤区域可视化 def showSkinRegions(self): # 未得出结果时方法返回 if self.result is None: return # 皮肤像素的 ID 的集合 skinIdSet = set() # 将原图做一份拷贝 simage = self.image # 加载数据 simageData = simage.load() # 将皮肤像素的 id 存入 skinIdSet for sr in self.skin_regions: for pixel in sr: skinIdSet.add(pixel.id) # 将图像中的皮肤像素设为白色,其余设为黑色 for pixel in self.skin_map: if pixel.id not in skinIdSet: simageData[pixel.x, pixel.y] = 0, 0, 0 else: simageData[pixel.x, pixel.y] = 255, 255, 255 # 源文件绝对路径 filePath = os.path.abspath(self.image.filename) # 源文件所在目录 fileDirectory = os.path.dirname(filePath) + '/' # 源文件的完整文件名 fileFullName = os.path.basename(filePath) # 分离源文件的完整文件名得到文件名和扩展名 fileName, fileExtName = os.path.splitext(fileFullName) # 保存图片 simage.save('{}{}_{}{}'.format(fileDirectory, fileName,'Nude' if self.result else 'Normal', fileExtName)) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Detect nudity in images.') parser.add_argument('files', metavar='image', nargs='+', help='Images you wish to test') parser.add_argument('-r', '--resize', action='store_true', help='Reduce image size to increase speed of scanning') parser.add_argument('-v', '--visualization', action='store_true', help='Generating areas of skin image') args = parser.parse_args() for fname in args.files: if os.path.isfile(fname): n = Nude(fname) if args.resize: n.resize(maxheight=800, maxwidth=600) n.parse() if args.visualization: n.showSkinRegions() print(n.result, n.inspect()) else: print(fname, "is not a file") ``` ''' tags: [] isStarred: false isTrashed: false
[ { "context": " given title. <title> is required \n#\n# Author:\n# Nithin Shenoy <nshenoy@mimeo.com>\n\nvstsToken = 'Basic ' + new B", "end": 649, "score": 0.9998753070831299, "start": 636, "tag": "NAME", "value": "Nithin Shenoy" }, { "context": "itle> is required \n#\n# Author:\n# Nithin Shenoy <nshenoy@mimeo.com>\n\nvstsToken = 'Basic ' + new Buffer(\":#{process.e", "end": 668, "score": 0.9999325275421143, "start": 651, "tag": "EMAIL", "value": "nshenoy@mimeo.com" }, { "context": " user for which new PBIs to be opened with (e.g. 'Hubot <hubot@organization.com>')\"\n missingConfig |= ", "end": 6740, "score": 0.9941417574882507, "start": 6735, "tag": "USERNAME", "value": "Hubot" }, { "context": "or which new PBIs to be opened with (e.g. 'Hubot <hubot@organization.com>')\"\n missingConfig |= true\n \n missingConfi", "end": 6764, "score": 0.9999213814735413, "start": 6742, "tag": "EMAIL", "value": "hubot@organization.com" }, { "context": "rkdwn_in: [\"text\",\"fields\"]\n author_name: \"Visual Studio Team Services\"\n author_icon: \"https://zapier.cachefly.ne", "end": 9676, "score": 0.6060007214546204, "start": 9649, "tag": "NAME", "value": "Visual Studio Team Services" } ]
src/vsts-slack.coffee
Mimeo/Hubot-Slack-VSTS
0
# Description # A Hubot script for Visual Studio Team Services integration tailored for Slack # # Configuration: # HUBOT_VSTS_API_TOKEN # HUBOT_VSTS_API_URL # HUBOT_VSTS_SERVICEACCOUNT # # Commands: # hubot vsts projects - Gets the list of projects available in Visual Studio Team Services # hubot vsts <project> pullrequests <showDetails>- Gets the active pull requests for the specified Visual Studio Team Services project. <showDetails> is optional # hubot vsts <project> newPBI <title>- Creates a new PBI in the specified Visual Studio Team Services project with the given title. <title> is required # # Author: # Nithin Shenoy <nshenoy@mimeo.com> vstsToken = 'Basic ' + new Buffer(":#{process.env.HUBOT_VSTS_API_TOKEN}").toString('base64') vstsBaseUrl = process.env.HUBOT_VSTS_DEFAULTCOLLECTION_URL vstsServiceAccount = process.env.HUBOT_VSTS_SERVICEACCOUNT module.exports = (robot) -> prWaitMessages = [ "Hold on, checking for active PRs ", "Wait a sec, let me see if I can find the active PRs ", "Mmmmkay, searching for PRs " ] pbiWaitMessages = [ "Give me a sec to create your new PBI ", "Creating new PBI ", "On it, homeslice. Creating a new PBI " ] robot.respond /vsts projects$/i, (res) -> unless (ensureEnvironment res) res.send "Retrieving list of VSTS projects..." retrieveProjects res, "Here's what I found: " robot.respond /vsts (.*) (pr|prs|pullrequest|pullrequests)\s?(details|detailed|showdetails)?$/i, (res) -> unless (ensureEnvironment res) project = res.match[1] showDetails = res.match[3]? waitMessage = res.random prWaitMessages res.send waitMessage + "in `#{project}` ..." # get the list of repositories reposUrl = "#{vstsBaseUrl}/_apis/git/repositories" res.http(reposUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err repos = (JSON.parse body).value # Get only the repos for the specified project projectRepos = repos.filter((x) -> x.project.name.toLowerCase() is project.toLowerCase()) if projectRepos.length is 0 # Most likely a bad project was given. Let's fetch the valid project names as a hint. retrieveProjects res, "Sorry, `#{project}` doesn't appear to be a project in VSTS. Here's a list of valid projects: " return repositories = {} hasPullRequests = false for projectRepo in projectRepos repositories[projectRepo.id] = projectRepo.name id = projectRepo.id repoPrUrl = "#{reposUrl}/#{id}/pullRequests?status=active" res.http(repoPrUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, prbody) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err pullRequests = (JSON.parse prbody).value if pullRequests.length > 0 hasPullRequests = true for pr in pullRequests attachment = createPullRequestAttachment showDetails, pr, repositories[pr.repository.id], project res.send channel: res.envelope.room username: res.robot.name attachments: [attachment] setTimeout () -> res.send "No active pull requests for #{project}" unless hasPullRequests , 2000 robot.respond /vsts (.*) (newPBI|newProductBacklogItem|newStory|newBug) (.*)?$/i, (res) -> unless (ensureEnvironment res) project = res.match[1] pbiTitle = res.match[3] unless pbiTitle? res.send 'I think you may have forgotten to give me a title for the PBI. Please use the format `vsts <project> newPBI <title>`.' return waitMessage = res.random pbiWaitMessages res.send waitMessage + "in `#{project}` with title `#{pbiTitle}` ..." newPbi = [ { op : "add", path : "/fields/System.Title", value : "#{pbiTitle}" }, { op : "add", path : "/fields/System.CreatedBy", value : "#{vstsServiceAccount}" }, { op : "add", path : "/fields/System.ChangedBy", value : "#{vstsServiceAccount}" } ] # create a new PBI pbiUrl = "#{vstsBaseUrl}/#{project}/_apis/wit/workitems/$Product%20Backlog%20Item?bypassRules=true&api-version=1.0" res.http(pbiUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json-patch+json') .patch(JSON.stringify(newPbi)) (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err pbiDetails = JSON.parse(body) attachment = createPBIAttachment pbiDetails res.send channel: res.envelope.room username: res.robot.name attachments: [attachment] ################################################# ## Checks the presence of required env variables ################################################# ensureEnvironment = (msg) -> missingConfig = false unless process.env.HUBOT_VSTS_API_TOKEN? msg.send "VSTS API Token is missing: Make sure the HUBOT_VSTS_API_TOKEN is set" missingConfig |= true unless process.env.HUBOT_VSTS_DEFAULTCOLLECTION_URL? msg.send "VSTS DefaultCollection URL is missing: Make sure the HUBOT_VSTS_DEFAULTCOLLECTION_URL is set" missingConfig |= true unless process.env.HUBOT_VSTS_SERVICEACCOUNT? msg.send "VSTS Service Account is missing: Make sure the HUBOT_VSTS_SERVICEACCOUNT is set to a user for which new PBIs to be opened with (e.g. 'Hubot <hubot@organization.com>')" missingConfig |= true missingConfig ################################################# ## Creates attachment message object for pull request ################################################# createPullRequestAttachment = (showDetails, pullRequestInfo, repository, project) -> repo = encodeURIComponent repository repositoryUrl = "#{vstsBaseUrl}/#{project}/_git/#{repo}" pullRequestUrl = "#{vstsBaseUrl}/#{project}/_git/#{repo}/pullrequest/#{pullRequestInfo.pullRequestId}" attachment = fallback: "Pull Request #{pullRequestInfo.pullRequestId} in #{repository} \"#{pullRequestInfo.title}\" #{pullRequestInfo.pullRequestUrl}" text: "<#{pullRequestUrl}|Pull Request #{pullRequestInfo.pullRequestId}> - \"#{pullRequestInfo.title}\" in <#{repositoryUrl}|#{repository}>" color: "#68217A" mrkdwn_in: ["text","fields"] author_name: "Visual Studio Team Services" author_icon: "https://zapier.cachefly.net/storage/services/59152a3a91bfe0ddd2fc9b978448593a.128x128.png" if showDetails details = fields: [ { title: "Source" value: "`#{pullRequestInfo.sourceRefName}`" short: true }, { title: "Target" value: "`#{pullRequestInfo.targetRefName}`" short: true }, { title: "Repository" value: "`#{repository}`" short: true }, { title: "Merge Status" value: "`#{pullRequestInfo.mergeStatus}`" short: true }, { title: "Description" value: "#{pullRequestInfo.description}" short: false } ] attachment.fields = details.fields return attachment ################################################################# ## Creates attachment message object for new Product Backlog Item ################################################################# createPBIAttachment = (pbiDetails, showDetails) -> pbiId = pbiDetails.id pbiTitle = pbiDetails.fields['System.Title'] project = pbiDetails.fields['System.AreaPath'] projectUrl = "#{vstsBaseUrl}/#{project}/_backlogs" pbiUrl = "#{vstsBaseUrl}/#{project}/_workitems?id=#{pbiId}&_a=edit" attachment = fallback: "Product Backlog Item #{pbiId} in #{project} \"#{pbiTitle}\" #{pbiUrl}" text: "<#{pbiUrl}|Product Backlog Item #{pbiId}> - \"#{pbiTitle}\" in <#{projectUrl}|#{project}>" color: "#68217A" mrkdwn_in: ["text","fields"] author_name: "Visual Studio Team Services" author_icon: "https://zapier.cachefly.net/storage/services/59152a3a91bfe0ddd2fc9b978448593a.128x128.png" if showDetails details = fields: [ { title: "State" value: "`#{pbiDetails.fields['System.State']}`" short: true }, { title: "Backlog Status" value: "`#{pbiDetails.fields['System.BoardColumn']}`" short: true }, { title: "Created By" value: "`#{pbiDetails.fields['System.CreatedBy']}`" short: true }, { title: "Created Dated" value: "`#{pbiDetails.fields['System.CreatedDate']}`" short: true }, { title: "Description" value: "#{pbiDetails.fields['System.Description']}" short: false } ] attachment.fields = details.fields return attachment ################################################# ## Retrieves list of projects ################################################# retrieveProjects = (res, messageHeader) -> url = "#{vstsBaseUrl}/_apis/projects?stateFilter=WellFormed" res.http(url) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err projects = JSON.parse body projectNames = [] for project in projects.value projectNames.push("`#{project.name}`") message = projectNames.join(", ") res.send "#{messageHeader} #{message}"
215864
# Description # A Hubot script for Visual Studio Team Services integration tailored for Slack # # Configuration: # HUBOT_VSTS_API_TOKEN # HUBOT_VSTS_API_URL # HUBOT_VSTS_SERVICEACCOUNT # # Commands: # hubot vsts projects - Gets the list of projects available in Visual Studio Team Services # hubot vsts <project> pullrequests <showDetails>- Gets the active pull requests for the specified Visual Studio Team Services project. <showDetails> is optional # hubot vsts <project> newPBI <title>- Creates a new PBI in the specified Visual Studio Team Services project with the given title. <title> is required # # Author: # <NAME> <<EMAIL>> vstsToken = 'Basic ' + new Buffer(":#{process.env.HUBOT_VSTS_API_TOKEN}").toString('base64') vstsBaseUrl = process.env.HUBOT_VSTS_DEFAULTCOLLECTION_URL vstsServiceAccount = process.env.HUBOT_VSTS_SERVICEACCOUNT module.exports = (robot) -> prWaitMessages = [ "Hold on, checking for active PRs ", "Wait a sec, let me see if I can find the active PRs ", "Mmmmkay, searching for PRs " ] pbiWaitMessages = [ "Give me a sec to create your new PBI ", "Creating new PBI ", "On it, homeslice. Creating a new PBI " ] robot.respond /vsts projects$/i, (res) -> unless (ensureEnvironment res) res.send "Retrieving list of VSTS projects..." retrieveProjects res, "Here's what I found: " robot.respond /vsts (.*) (pr|prs|pullrequest|pullrequests)\s?(details|detailed|showdetails)?$/i, (res) -> unless (ensureEnvironment res) project = res.match[1] showDetails = res.match[3]? waitMessage = res.random prWaitMessages res.send waitMessage + "in `#{project}` ..." # get the list of repositories reposUrl = "#{vstsBaseUrl}/_apis/git/repositories" res.http(reposUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err repos = (JSON.parse body).value # Get only the repos for the specified project projectRepos = repos.filter((x) -> x.project.name.toLowerCase() is project.toLowerCase()) if projectRepos.length is 0 # Most likely a bad project was given. Let's fetch the valid project names as a hint. retrieveProjects res, "Sorry, `#{project}` doesn't appear to be a project in VSTS. Here's a list of valid projects: " return repositories = {} hasPullRequests = false for projectRepo in projectRepos repositories[projectRepo.id] = projectRepo.name id = projectRepo.id repoPrUrl = "#{reposUrl}/#{id}/pullRequests?status=active" res.http(repoPrUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, prbody) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err pullRequests = (JSON.parse prbody).value if pullRequests.length > 0 hasPullRequests = true for pr in pullRequests attachment = createPullRequestAttachment showDetails, pr, repositories[pr.repository.id], project res.send channel: res.envelope.room username: res.robot.name attachments: [attachment] setTimeout () -> res.send "No active pull requests for #{project}" unless hasPullRequests , 2000 robot.respond /vsts (.*) (newPBI|newProductBacklogItem|newStory|newBug) (.*)?$/i, (res) -> unless (ensureEnvironment res) project = res.match[1] pbiTitle = res.match[3] unless pbiTitle? res.send 'I think you may have forgotten to give me a title for the PBI. Please use the format `vsts <project> newPBI <title>`.' return waitMessage = res.random pbiWaitMessages res.send waitMessage + "in `#{project}` with title `#{pbiTitle}` ..." newPbi = [ { op : "add", path : "/fields/System.Title", value : "#{pbiTitle}" }, { op : "add", path : "/fields/System.CreatedBy", value : "#{vstsServiceAccount}" }, { op : "add", path : "/fields/System.ChangedBy", value : "#{vstsServiceAccount}" } ] # create a new PBI pbiUrl = "#{vstsBaseUrl}/#{project}/_apis/wit/workitems/$Product%20Backlog%20Item?bypassRules=true&api-version=1.0" res.http(pbiUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json-patch+json') .patch(JSON.stringify(newPbi)) (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err pbiDetails = JSON.parse(body) attachment = createPBIAttachment pbiDetails res.send channel: res.envelope.room username: res.robot.name attachments: [attachment] ################################################# ## Checks the presence of required env variables ################################################# ensureEnvironment = (msg) -> missingConfig = false unless process.env.HUBOT_VSTS_API_TOKEN? msg.send "VSTS API Token is missing: Make sure the HUBOT_VSTS_API_TOKEN is set" missingConfig |= true unless process.env.HUBOT_VSTS_DEFAULTCOLLECTION_URL? msg.send "VSTS DefaultCollection URL is missing: Make sure the HUBOT_VSTS_DEFAULTCOLLECTION_URL is set" missingConfig |= true unless process.env.HUBOT_VSTS_SERVICEACCOUNT? msg.send "VSTS Service Account is missing: Make sure the HUBOT_VSTS_SERVICEACCOUNT is set to a user for which new PBIs to be opened with (e.g. 'Hubot <<EMAIL>>')" missingConfig |= true missingConfig ################################################# ## Creates attachment message object for pull request ################################################# createPullRequestAttachment = (showDetails, pullRequestInfo, repository, project) -> repo = encodeURIComponent repository repositoryUrl = "#{vstsBaseUrl}/#{project}/_git/#{repo}" pullRequestUrl = "#{vstsBaseUrl}/#{project}/_git/#{repo}/pullrequest/#{pullRequestInfo.pullRequestId}" attachment = fallback: "Pull Request #{pullRequestInfo.pullRequestId} in #{repository} \"#{pullRequestInfo.title}\" #{pullRequestInfo.pullRequestUrl}" text: "<#{pullRequestUrl}|Pull Request #{pullRequestInfo.pullRequestId}> - \"#{pullRequestInfo.title}\" in <#{repositoryUrl}|#{repository}>" color: "#68217A" mrkdwn_in: ["text","fields"] author_name: "Visual Studio Team Services" author_icon: "https://zapier.cachefly.net/storage/services/59152a3a91bfe0ddd2fc9b978448593a.128x128.png" if showDetails details = fields: [ { title: "Source" value: "`#{pullRequestInfo.sourceRefName}`" short: true }, { title: "Target" value: "`#{pullRequestInfo.targetRefName}`" short: true }, { title: "Repository" value: "`#{repository}`" short: true }, { title: "Merge Status" value: "`#{pullRequestInfo.mergeStatus}`" short: true }, { title: "Description" value: "#{pullRequestInfo.description}" short: false } ] attachment.fields = details.fields return attachment ################################################################# ## Creates attachment message object for new Product Backlog Item ################################################################# createPBIAttachment = (pbiDetails, showDetails) -> pbiId = pbiDetails.id pbiTitle = pbiDetails.fields['System.Title'] project = pbiDetails.fields['System.AreaPath'] projectUrl = "#{vstsBaseUrl}/#{project}/_backlogs" pbiUrl = "#{vstsBaseUrl}/#{project}/_workitems?id=#{pbiId}&_a=edit" attachment = fallback: "Product Backlog Item #{pbiId} in #{project} \"#{pbiTitle}\" #{pbiUrl}" text: "<#{pbiUrl}|Product Backlog Item #{pbiId}> - \"#{pbiTitle}\" in <#{projectUrl}|#{project}>" color: "#68217A" mrkdwn_in: ["text","fields"] author_name: "<NAME>" author_icon: "https://zapier.cachefly.net/storage/services/59152a3a91bfe0ddd2fc9b978448593a.128x128.png" if showDetails details = fields: [ { title: "State" value: "`#{pbiDetails.fields['System.State']}`" short: true }, { title: "Backlog Status" value: "`#{pbiDetails.fields['System.BoardColumn']}`" short: true }, { title: "Created By" value: "`#{pbiDetails.fields['System.CreatedBy']}`" short: true }, { title: "Created Dated" value: "`#{pbiDetails.fields['System.CreatedDate']}`" short: true }, { title: "Description" value: "#{pbiDetails.fields['System.Description']}" short: false } ] attachment.fields = details.fields return attachment ################################################# ## Retrieves list of projects ################################################# retrieveProjects = (res, messageHeader) -> url = "#{vstsBaseUrl}/_apis/projects?stateFilter=WellFormed" res.http(url) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err projects = JSON.parse body projectNames = [] for project in projects.value projectNames.push("`#{project.name}`") message = projectNames.join(", ") res.send "#{messageHeader} #{message}"
true
# Description # A Hubot script for Visual Studio Team Services integration tailored for Slack # # Configuration: # HUBOT_VSTS_API_TOKEN # HUBOT_VSTS_API_URL # HUBOT_VSTS_SERVICEACCOUNT # # Commands: # hubot vsts projects - Gets the list of projects available in Visual Studio Team Services # hubot vsts <project> pullrequests <showDetails>- Gets the active pull requests for the specified Visual Studio Team Services project. <showDetails> is optional # hubot vsts <project> newPBI <title>- Creates a new PBI in the specified Visual Studio Team Services project with the given title. <title> is required # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> vstsToken = 'Basic ' + new Buffer(":#{process.env.HUBOT_VSTS_API_TOKEN}").toString('base64') vstsBaseUrl = process.env.HUBOT_VSTS_DEFAULTCOLLECTION_URL vstsServiceAccount = process.env.HUBOT_VSTS_SERVICEACCOUNT module.exports = (robot) -> prWaitMessages = [ "Hold on, checking for active PRs ", "Wait a sec, let me see if I can find the active PRs ", "Mmmmkay, searching for PRs " ] pbiWaitMessages = [ "Give me a sec to create your new PBI ", "Creating new PBI ", "On it, homeslice. Creating a new PBI " ] robot.respond /vsts projects$/i, (res) -> unless (ensureEnvironment res) res.send "Retrieving list of VSTS projects..." retrieveProjects res, "Here's what I found: " robot.respond /vsts (.*) (pr|prs|pullrequest|pullrequests)\s?(details|detailed|showdetails)?$/i, (res) -> unless (ensureEnvironment res) project = res.match[1] showDetails = res.match[3]? waitMessage = res.random prWaitMessages res.send waitMessage + "in `#{project}` ..." # get the list of repositories reposUrl = "#{vstsBaseUrl}/_apis/git/repositories" res.http(reposUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err repos = (JSON.parse body).value # Get only the repos for the specified project projectRepos = repos.filter((x) -> x.project.name.toLowerCase() is project.toLowerCase()) if projectRepos.length is 0 # Most likely a bad project was given. Let's fetch the valid project names as a hint. retrieveProjects res, "Sorry, `#{project}` doesn't appear to be a project in VSTS. Here's a list of valid projects: " return repositories = {} hasPullRequests = false for projectRepo in projectRepos repositories[projectRepo.id] = projectRepo.name id = projectRepo.id repoPrUrl = "#{reposUrl}/#{id}/pullRequests?status=active" res.http(repoPrUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, prbody) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err pullRequests = (JSON.parse prbody).value if pullRequests.length > 0 hasPullRequests = true for pr in pullRequests attachment = createPullRequestAttachment showDetails, pr, repositories[pr.repository.id], project res.send channel: res.envelope.room username: res.robot.name attachments: [attachment] setTimeout () -> res.send "No active pull requests for #{project}" unless hasPullRequests , 2000 robot.respond /vsts (.*) (newPBI|newProductBacklogItem|newStory|newBug) (.*)?$/i, (res) -> unless (ensureEnvironment res) project = res.match[1] pbiTitle = res.match[3] unless pbiTitle? res.send 'I think you may have forgotten to give me a title for the PBI. Please use the format `vsts <project> newPBI <title>`.' return waitMessage = res.random pbiWaitMessages res.send waitMessage + "in `#{project}` with title `#{pbiTitle}` ..." newPbi = [ { op : "add", path : "/fields/System.Title", value : "#{pbiTitle}" }, { op : "add", path : "/fields/System.CreatedBy", value : "#{vstsServiceAccount}" }, { op : "add", path : "/fields/System.ChangedBy", value : "#{vstsServiceAccount}" } ] # create a new PBI pbiUrl = "#{vstsBaseUrl}/#{project}/_apis/wit/workitems/$Product%20Backlog%20Item?bypassRules=true&api-version=1.0" res.http(pbiUrl) .header('Authorization', vstsToken) .header('Content-type', 'application/json-patch+json') .patch(JSON.stringify(newPbi)) (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err pbiDetails = JSON.parse(body) attachment = createPBIAttachment pbiDetails res.send channel: res.envelope.room username: res.robot.name attachments: [attachment] ################################################# ## Checks the presence of required env variables ################################################# ensureEnvironment = (msg) -> missingConfig = false unless process.env.HUBOT_VSTS_API_TOKEN? msg.send "VSTS API Token is missing: Make sure the HUBOT_VSTS_API_TOKEN is set" missingConfig |= true unless process.env.HUBOT_VSTS_DEFAULTCOLLECTION_URL? msg.send "VSTS DefaultCollection URL is missing: Make sure the HUBOT_VSTS_DEFAULTCOLLECTION_URL is set" missingConfig |= true unless process.env.HUBOT_VSTS_SERVICEACCOUNT? msg.send "VSTS Service Account is missing: Make sure the HUBOT_VSTS_SERVICEACCOUNT is set to a user for which new PBIs to be opened with (e.g. 'Hubot <PI:EMAIL:<EMAIL>END_PI>')" missingConfig |= true missingConfig ################################################# ## Creates attachment message object for pull request ################################################# createPullRequestAttachment = (showDetails, pullRequestInfo, repository, project) -> repo = encodeURIComponent repository repositoryUrl = "#{vstsBaseUrl}/#{project}/_git/#{repo}" pullRequestUrl = "#{vstsBaseUrl}/#{project}/_git/#{repo}/pullrequest/#{pullRequestInfo.pullRequestId}" attachment = fallback: "Pull Request #{pullRequestInfo.pullRequestId} in #{repository} \"#{pullRequestInfo.title}\" #{pullRequestInfo.pullRequestUrl}" text: "<#{pullRequestUrl}|Pull Request #{pullRequestInfo.pullRequestId}> - \"#{pullRequestInfo.title}\" in <#{repositoryUrl}|#{repository}>" color: "#68217A" mrkdwn_in: ["text","fields"] author_name: "Visual Studio Team Services" author_icon: "https://zapier.cachefly.net/storage/services/59152a3a91bfe0ddd2fc9b978448593a.128x128.png" if showDetails details = fields: [ { title: "Source" value: "`#{pullRequestInfo.sourceRefName}`" short: true }, { title: "Target" value: "`#{pullRequestInfo.targetRefName}`" short: true }, { title: "Repository" value: "`#{repository}`" short: true }, { title: "Merge Status" value: "`#{pullRequestInfo.mergeStatus}`" short: true }, { title: "Description" value: "#{pullRequestInfo.description}" short: false } ] attachment.fields = details.fields return attachment ################################################################# ## Creates attachment message object for new Product Backlog Item ################################################################# createPBIAttachment = (pbiDetails, showDetails) -> pbiId = pbiDetails.id pbiTitle = pbiDetails.fields['System.Title'] project = pbiDetails.fields['System.AreaPath'] projectUrl = "#{vstsBaseUrl}/#{project}/_backlogs" pbiUrl = "#{vstsBaseUrl}/#{project}/_workitems?id=#{pbiId}&_a=edit" attachment = fallback: "Product Backlog Item #{pbiId} in #{project} \"#{pbiTitle}\" #{pbiUrl}" text: "<#{pbiUrl}|Product Backlog Item #{pbiId}> - \"#{pbiTitle}\" in <#{projectUrl}|#{project}>" color: "#68217A" mrkdwn_in: ["text","fields"] author_name: "PI:NAME:<NAME>END_PI" author_icon: "https://zapier.cachefly.net/storage/services/59152a3a91bfe0ddd2fc9b978448593a.128x128.png" if showDetails details = fields: [ { title: "State" value: "`#{pbiDetails.fields['System.State']}`" short: true }, { title: "Backlog Status" value: "`#{pbiDetails.fields['System.BoardColumn']}`" short: true }, { title: "Created By" value: "`#{pbiDetails.fields['System.CreatedBy']}`" short: true }, { title: "Created Dated" value: "`#{pbiDetails.fields['System.CreatedDate']}`" short: true }, { title: "Description" value: "#{pbiDetails.fields['System.Description']}" short: false } ] attachment.fields = details.fields return attachment ################################################# ## Retrieves list of projects ################################################# retrieveProjects = (res, messageHeader) -> url = "#{vstsBaseUrl}/_apis/projects?stateFilter=WellFormed" res.http(url) .header('Authorization', vstsToken) .header('Content-type', 'application/json') .get() (err, _, body) -> if err res.send ":fire: An error was thrown in Node.js/CoffeeScript" res.send err projects = JSON.parse body projectNames = [] for project in projects.value projectNames.push("`#{project.name}`") message = projectNames.join(", ") res.send "#{messageHeader} #{message}"
[ { "context": " (req) ->\n pubkey = @getPayplugPublicKey().toString()\n _sign = forge.util.decode64(req.header", "end": 3873, "score": 0.9644688963890076, "start": 3865, "tag": "KEY", "value": "toString" } ]
src/payplug.coffee
WorkingBox/payplug
0
config = require '../config/payplug.json' ipn = require '../config/ipn.json' uuid = require 'node-uuid' querystring = require 'querystring' fs = require 'fs' forge = require('node-forge') path = require('path') R = require('ramda') crypto = require('crypto') #Q = require('q') module.exports = exports = getCurrency: -> config.currencies[0] getAmountMax: -> config.amount_max getAmountMin: -> config.amount_min getBaseUrl: -> config.url getPayplugPublicKey: -> fs.readFileSync(path.join(__dirname, '../', "payplugPublicKey"), "utf8") getYourPrivateKey: -> fs.readFileSync(path.join(__dirname, '../', "yourPrivateKey"), "utf8") # fs.readFileSync("yourPrivateKey", "utf8") getIpnUrl: -> ipn.ipn_url getReturnUrl: -> ipn.return_url getCancelUrl: -> ipn.cancel_url createPayment: (res, options) -> # createPayment: (options) -> # console.log "In createPayment : options.order" # console.log options.order # console.log options.custom_data # console.log options.custom_datas # testid = uuid.v1() # console.log "testid : " + testid deferred = Q.defer() data = 'amount' : options.amount 'currency' : options.currency ||'EUR' 'ipn_url' : @getIpnUrl() 'return_url' : @getReturnUrl() 'cancel_url' : @getCancelUrl() 'order' : options.order || uuid.v1() 'email' : options.email 'first_name' : options.first_name 'last_name' : options.last_name 'custom_data' : options.custom_data || uuid.v1() 'custom_datas' : options.custom_datas || uuid.v1() payPLUGUrl = @prepareUrl(data) answer = 'url' : @prepareUrl(data) # console.log "payPLUGUrl : " + payPLUGUrl # console.log answer res.json answer # deferred.resolve(answer) # deferred.promise @ prepareUrl: (data) -> base_url = @getBaseUrl() pem = @getYourPrivateKey() # convert a PEM-formatted private key to a Forge private key pki = forge.pki privateKey = pki.privateKeyFromPem(pem) # data needs to be transormed to http query string param = querystring.stringify data # data has to be base64 encoded dataSixtyFour= new Buffer(param).toString('base64') # next dataSixtyFour needs to be urlencoded : use encodeURIComponent! urldata = encodeURIComponent dataSixtyFour # sign param with our private key md = forge.md.sha1.create() md.update(param, 'utf8') signature = privateKey.sign(md) # base64 encode the signature signature64 = forge.util.encode64(signature) # url encode the signature urlsign = encodeURIComponent signature64 # create a new URL newUrl = base_url + "?data=" + urldata + "&sign=" + urlsign newUrl verifySignature : (req)-> # We need to verify if there is an order for the payment in our database! # Your have to implement this for yourself! order = req.body.order console.log "The following order exists and can be saved : " + order @checkIdentity(req) # /** # * Checks if a message and its signature match with the given public key # * @param {String} message The message with format "field1=val1&field2=val2..." # * @param {String} signature The RSA SHA1 signature of the message # * @param {String} pubkey The public key in UTF8 # * @return {Boolean} If the message is signed by the owner of the public key # */ checkSignature : (message, signature, pubkey) -> check = crypto.createVerify('SHA1') check.update(message); return check.verify(pubkey, signature, 'base64') checkIdentity : (req) -> pubkey = @getPayplugPublicKey().toString() _sign = forge.util.decode64(req.headers['payplug-signature']) message = R.mapObj(@encodeUri, req.body) _message = querystring.stringify message _message = new Buffer(_message).toString('base64') _check = @checkSignature(_message, _sign, pubkey) console.log _check encodeUri : (value) -> #encodeURIComponent value value
103298
config = require '../config/payplug.json' ipn = require '../config/ipn.json' uuid = require 'node-uuid' querystring = require 'querystring' fs = require 'fs' forge = require('node-forge') path = require('path') R = require('ramda') crypto = require('crypto') #Q = require('q') module.exports = exports = getCurrency: -> config.currencies[0] getAmountMax: -> config.amount_max getAmountMin: -> config.amount_min getBaseUrl: -> config.url getPayplugPublicKey: -> fs.readFileSync(path.join(__dirname, '../', "payplugPublicKey"), "utf8") getYourPrivateKey: -> fs.readFileSync(path.join(__dirname, '../', "yourPrivateKey"), "utf8") # fs.readFileSync("yourPrivateKey", "utf8") getIpnUrl: -> ipn.ipn_url getReturnUrl: -> ipn.return_url getCancelUrl: -> ipn.cancel_url createPayment: (res, options) -> # createPayment: (options) -> # console.log "In createPayment : options.order" # console.log options.order # console.log options.custom_data # console.log options.custom_datas # testid = uuid.v1() # console.log "testid : " + testid deferred = Q.defer() data = 'amount' : options.amount 'currency' : options.currency ||'EUR' 'ipn_url' : @getIpnUrl() 'return_url' : @getReturnUrl() 'cancel_url' : @getCancelUrl() 'order' : options.order || uuid.v1() 'email' : options.email 'first_name' : options.first_name 'last_name' : options.last_name 'custom_data' : options.custom_data || uuid.v1() 'custom_datas' : options.custom_datas || uuid.v1() payPLUGUrl = @prepareUrl(data) answer = 'url' : @prepareUrl(data) # console.log "payPLUGUrl : " + payPLUGUrl # console.log answer res.json answer # deferred.resolve(answer) # deferred.promise @ prepareUrl: (data) -> base_url = @getBaseUrl() pem = @getYourPrivateKey() # convert a PEM-formatted private key to a Forge private key pki = forge.pki privateKey = pki.privateKeyFromPem(pem) # data needs to be transormed to http query string param = querystring.stringify data # data has to be base64 encoded dataSixtyFour= new Buffer(param).toString('base64') # next dataSixtyFour needs to be urlencoded : use encodeURIComponent! urldata = encodeURIComponent dataSixtyFour # sign param with our private key md = forge.md.sha1.create() md.update(param, 'utf8') signature = privateKey.sign(md) # base64 encode the signature signature64 = forge.util.encode64(signature) # url encode the signature urlsign = encodeURIComponent signature64 # create a new URL newUrl = base_url + "?data=" + urldata + "&sign=" + urlsign newUrl verifySignature : (req)-> # We need to verify if there is an order for the payment in our database! # Your have to implement this for yourself! order = req.body.order console.log "The following order exists and can be saved : " + order @checkIdentity(req) # /** # * Checks if a message and its signature match with the given public key # * @param {String} message The message with format "field1=val1&field2=val2..." # * @param {String} signature The RSA SHA1 signature of the message # * @param {String} pubkey The public key in UTF8 # * @return {Boolean} If the message is signed by the owner of the public key # */ checkSignature : (message, signature, pubkey) -> check = crypto.createVerify('SHA1') check.update(message); return check.verify(pubkey, signature, 'base64') checkIdentity : (req) -> pubkey = @getPayplugPublicKey().<KEY>() _sign = forge.util.decode64(req.headers['payplug-signature']) message = R.mapObj(@encodeUri, req.body) _message = querystring.stringify message _message = new Buffer(_message).toString('base64') _check = @checkSignature(_message, _sign, pubkey) console.log _check encodeUri : (value) -> #encodeURIComponent value value
true
config = require '../config/payplug.json' ipn = require '../config/ipn.json' uuid = require 'node-uuid' querystring = require 'querystring' fs = require 'fs' forge = require('node-forge') path = require('path') R = require('ramda') crypto = require('crypto') #Q = require('q') module.exports = exports = getCurrency: -> config.currencies[0] getAmountMax: -> config.amount_max getAmountMin: -> config.amount_min getBaseUrl: -> config.url getPayplugPublicKey: -> fs.readFileSync(path.join(__dirname, '../', "payplugPublicKey"), "utf8") getYourPrivateKey: -> fs.readFileSync(path.join(__dirname, '../', "yourPrivateKey"), "utf8") # fs.readFileSync("yourPrivateKey", "utf8") getIpnUrl: -> ipn.ipn_url getReturnUrl: -> ipn.return_url getCancelUrl: -> ipn.cancel_url createPayment: (res, options) -> # createPayment: (options) -> # console.log "In createPayment : options.order" # console.log options.order # console.log options.custom_data # console.log options.custom_datas # testid = uuid.v1() # console.log "testid : " + testid deferred = Q.defer() data = 'amount' : options.amount 'currency' : options.currency ||'EUR' 'ipn_url' : @getIpnUrl() 'return_url' : @getReturnUrl() 'cancel_url' : @getCancelUrl() 'order' : options.order || uuid.v1() 'email' : options.email 'first_name' : options.first_name 'last_name' : options.last_name 'custom_data' : options.custom_data || uuid.v1() 'custom_datas' : options.custom_datas || uuid.v1() payPLUGUrl = @prepareUrl(data) answer = 'url' : @prepareUrl(data) # console.log "payPLUGUrl : " + payPLUGUrl # console.log answer res.json answer # deferred.resolve(answer) # deferred.promise @ prepareUrl: (data) -> base_url = @getBaseUrl() pem = @getYourPrivateKey() # convert a PEM-formatted private key to a Forge private key pki = forge.pki privateKey = pki.privateKeyFromPem(pem) # data needs to be transormed to http query string param = querystring.stringify data # data has to be base64 encoded dataSixtyFour= new Buffer(param).toString('base64') # next dataSixtyFour needs to be urlencoded : use encodeURIComponent! urldata = encodeURIComponent dataSixtyFour # sign param with our private key md = forge.md.sha1.create() md.update(param, 'utf8') signature = privateKey.sign(md) # base64 encode the signature signature64 = forge.util.encode64(signature) # url encode the signature urlsign = encodeURIComponent signature64 # create a new URL newUrl = base_url + "?data=" + urldata + "&sign=" + urlsign newUrl verifySignature : (req)-> # We need to verify if there is an order for the payment in our database! # Your have to implement this for yourself! order = req.body.order console.log "The following order exists and can be saved : " + order @checkIdentity(req) # /** # * Checks if a message and its signature match with the given public key # * @param {String} message The message with format "field1=val1&field2=val2..." # * @param {String} signature The RSA SHA1 signature of the message # * @param {String} pubkey The public key in UTF8 # * @return {Boolean} If the message is signed by the owner of the public key # */ checkSignature : (message, signature, pubkey) -> check = crypto.createVerify('SHA1') check.update(message); return check.verify(pubkey, signature, 'base64') checkIdentity : (req) -> pubkey = @getPayplugPublicKey().PI:KEY:<KEY>END_PI() _sign = forge.util.decode64(req.headers['payplug-signature']) message = R.mapObj(@encodeUri, req.body) _message = querystring.stringify message _message = new Buffer(_message).toString('base64') _check = @checkSignature(_message, _sign, pubkey) console.log _check encodeUri : (value) -> #encodeURIComponent value value
[ { "context": " id : 'register-task-id'\n name : 'test-register'\n pickle : -> null\n }\n\n id ", "end": 7796, "score": 0.6922578811645508, "start": 7783, "tag": "NAME", "value": "test-register" }, { "context": "\n id : 'ready-task-id'\n name : 'test1'\n pickle: -> null\n }\n\n queue.on ", "end": 9480, "score": 0.7804217338562012, "start": 9475, "tag": "NAME", "value": "test1" }, { "context": "Name, taskId) ->\n expect(taskName).to.eql 'test1'\n expect(taskId).to.eql 'ready-task-id'\n ", "end": 9605, "score": 0.9417896270751953, "start": 9600, "tag": "USERNAME", "value": "test1" } ]
test/lib/queue.spec.coffee
scull7/uow
0
Queue = require '../../lib/queue.js' TaskRequest = require '../../lib/task/request.js' TaskLock = require 'uow-lock' { inherits } = require 'util' { EventEmitter } = require 'events' { MemoryStore } = require 'uow-store' describe 'Queue', -> queue = null store = null beforeEach -> store = MemoryStore() queue = new Queue(store) it 'should follow the optional new pattern', -> queue = Queue(store) expect(queue instanceof Queue).to.be.true describe '::taskComplete', -> completeTask = null caughtCompleteEvent = false beforeEach (done) -> queue.on 'task::finished', -> caughtCompleteEvent = true queue.taskAdd({ name: 'complete-task' }) .then (task) -> queue.taskComplete('complete-worker', task.id, 'complete') .then (task) -> completeTask = task done() it 'should call the store to update the task', -> expect(completeTask.status).to.eql 'success' expect(completeTask.response[0]).to.eql 'complete' it 'should emit a task::update event', -> expect(caughtCompleteEvent).to.be.true it 'should change the response to an array if it\'s not currently an array', -> queue.taskAdd({ name : 'test-not-array' }) .then (task) -> task.response = 'not-an-array' queue.store.updateTask('worker-id', task) .then (task) -> queue.taskComplete('worker-id', task.id, 'done') .then (task) -> expect(task.response).to.eql [ 'not-an-array' 'done' ] describe '::taskFail', -> failedTask = null caughtFailedEvent = false beforeEach (done) -> queue.on 'task::failed', (task) -> caughtFailedEvent = true queue.taskAdd({ name: 'fail-task' }) .then (task) -> queue.taskFail('fail-worker', task.id, 'fail-response') .then (task) -> failedTask = task done() it 'should call the store to mark the task as failed', -> expect(failedTask.status).to.eql 'failed' expect(failedTask.response[0]).to.eql 'fail-response' it 'should emit a task::fail event', -> expect(caughtFailedEvent).to.be.true describe '::taskCancel', -> cancelledTask = null caughtCancelEvent = false beforeEach (done) -> queue.on 'task::cancelled', (task) -> caughtCancelEvent = true queue.taskAdd({ name: 'cancel-test' }) .then (task) -> queue.taskCancel('cancel-worker', task.id, 'response') .then (task) -> cancelledTask = task done() it 'should call the store to mark the task as cancelled', -> expect(cancelledTask.status).to.eql 'cancelled' expect(cancelledTask.response[0]).to.eql 'response' it 'should emit a task::cancel event', -> expect(caughtCancelEvent).to.be.true describe '::taskGetById', -> it 'should call the store to get a task by its identifier', -> queue.taskAdd({ name: 'get-by-id-task' }) .then (task) -> queue.taskGetById(task.id) .then (task) -> expect(task.name).to.eql 'get-by-id-task' describe '::taskAdd', -> it 'should call the store to persist the given task object.', -> queue.taskAdd({ name: 'test-add-task' }) .then (task) -> expect(task.id).to.not.be.undefined return queue.taskGetById(task.id) .then (task) -> expect(task.name).to.eql 'test-add-task' it 'should throw an TypeError given a task with an ID', -> queue.taskAdd({ id : 'my-task-id' name : 'test-add-task' }) .then -> throw new Error('UnexpectedSuccess') .catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject' describe '::taskLock', -> result = null workerId = 'lock-worker' task = { name: 'lock-task' } caughtEvent = false before (done) -> queue.on 'task::locked', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskLock(workerId, task.id) .then (task) -> result = task it 'should call the store to lock the task', -> expect(result.id).to.not.be.undefined expect(result.id).to.be.a 'string' expect(result.semaphore.key).to.be.a 'string' it 'should emit a task::lock event', -> expect(caughtEvent).to.be.true describe '::taskUnlock', -> result = null workerId = 'lock-worker' task = { name: 'lock-task' } caughtEvent = false before (done) -> queue.on 'task::unlocked', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskLock(workerId, task.id) .then (task) -> queue.taskUnlock(workerId, task.id) .then (task) -> result = task it 'should call the store to unlock the task', -> expect(result.semaphore).to.be.null expect(result.id).to.be.a 'string' it 'should emit a task::unlock event', -> expect(caughtEvent).to.be.true describe '::taskYield', -> result = null workerId = 'yield-worker' task = { name : 'yield-task' } yieldEvent = false clock = null startTime = 1434734400000 tenMinutes = 10 * 60 * 1000 before (done) -> clock = sinon.useFakeTimers(startTime) queue.on 'task::finished', -> yieldEvent = true task = new TaskRequest('yield-task', queue) task.later('every 10 minutes') task.send() .tap -> clock.tick tenMinutes .then (task) -> queue.taskYield(workerId, task.id, 'something') .then (task) -> result = task .then -> done() after -> clock.restore() it 'should throw a TypeError if the task doesn\'t have a schedule', -> no_schedule_task = { name : 'no-schedule-for-me' } queue.taskAdd(task) .then (task) -> queue.taskYield('my-worker-id', task.id, 'blah') .then -> throw new Error('UnexpectedSuccess') .catch TypeError, (e) -> expect(e.message).to.eql 'TaskNotScheduled' it 'should emit a task finished event', -> expect(yieldEvent).to.be.true it 'should not update the task status', -> expect(result.status).to.eql 'new' it 'should update the after time', -> expect(result.after).to.eql (new Date().getTime()) + tenMinutes describe '::taskProgress', -> result = null workerId = 'progress-worker' task = { name: 'progress-task' } caughtEvent = false before (done) -> queue.on 'task::progress', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskProgress(workerId, task.id, 'some-progress') .then (task) -> result = task it 'should lock the task before updating', -> expect(result.semaphore).to.not.be.undefined it 'should call the store to update the task progress', -> expect(result.progress).to.eql 'some-progress' it 'should emit a task::progress event', -> expect(caughtEvent).to.be.true describe '::workerRegister', -> it 'should add the given worker to the registry', -> worker = taskReady : sinon.spy() id = queue.workerRegister(['test1', 'test2'], worker) expect(queue.registry[id].worker).to.eql worker expect(queue.registry[id].types).to.eql [ 'test1', 'test2' ] it 'should bind the worker to the task::ready event', (done) -> worker = taskReady : (type, id) -> expect(type).to.eql 'test-register' expect(id).to.eql 'register-task-id' done() task = { id : 'register-task-id' name : 'test-register' pickle : -> null } id = queue.workerRegister([ 'test-register' ], worker) queue.workerNotify(task) it 'should not call the worker if the task name is not in the type list', (done) -> worker = taskReady : sinon.spy() notType = { id : 'not-type-task' name : 'not-in-list' pickle : -> null } queue.workerRegister([ 'test1', 'test2' ], worker) queue.workerNotify(notType) setTimeout -> expect(worker.taskReady.called).to.be.false done() , 5 describe '::workerNotify', -> it 'should throw a TypeError if the task is not persisted', -> not_persisted = { name : 'not-persisted' pickle : -> null } test = -> queue.workerNotify(not_persisted) expect(test).to.throw TypeError, /TaskNotPersisted/ it 'should throw a TypeError if the task name is missing', -> persisted = { id : 'i-am-persisted' pickle : -> null } test = -> queue.workerNotify(persisted) expect(test).to.throw TypeError, /TaskTypeMissing/ it 'should emit a task ready event', (done) -> test_task = { id : 'worker-notify-id' name : 'worker-notify-task' pickle : -> null } queue.on 'task::ready', (taskName, taskId) -> expect(taskId).to.eql 'worker-notify-id' expect(taskName).to.eql 'worker-notify-task' done() queue.workerNotify(test_task) it 'should be called when the store emits a ready event.', (done) -> task = { id : 'ready-task-id' name : 'test1' pickle: -> null } queue.on 'task::ready', (taskName, taskId) -> expect(taskName).to.eql 'test1' expect(taskId).to.eql 'ready-task-id' done() store.emit 'ready', task describe '::workerStatus', -> it 'should throw an Error', -> test = -> queue.workerStatus() expect(test).to.throw Error, /NotImplemented/
178624
Queue = require '../../lib/queue.js' TaskRequest = require '../../lib/task/request.js' TaskLock = require 'uow-lock' { inherits } = require 'util' { EventEmitter } = require 'events' { MemoryStore } = require 'uow-store' describe 'Queue', -> queue = null store = null beforeEach -> store = MemoryStore() queue = new Queue(store) it 'should follow the optional new pattern', -> queue = Queue(store) expect(queue instanceof Queue).to.be.true describe '::taskComplete', -> completeTask = null caughtCompleteEvent = false beforeEach (done) -> queue.on 'task::finished', -> caughtCompleteEvent = true queue.taskAdd({ name: 'complete-task' }) .then (task) -> queue.taskComplete('complete-worker', task.id, 'complete') .then (task) -> completeTask = task done() it 'should call the store to update the task', -> expect(completeTask.status).to.eql 'success' expect(completeTask.response[0]).to.eql 'complete' it 'should emit a task::update event', -> expect(caughtCompleteEvent).to.be.true it 'should change the response to an array if it\'s not currently an array', -> queue.taskAdd({ name : 'test-not-array' }) .then (task) -> task.response = 'not-an-array' queue.store.updateTask('worker-id', task) .then (task) -> queue.taskComplete('worker-id', task.id, 'done') .then (task) -> expect(task.response).to.eql [ 'not-an-array' 'done' ] describe '::taskFail', -> failedTask = null caughtFailedEvent = false beforeEach (done) -> queue.on 'task::failed', (task) -> caughtFailedEvent = true queue.taskAdd({ name: 'fail-task' }) .then (task) -> queue.taskFail('fail-worker', task.id, 'fail-response') .then (task) -> failedTask = task done() it 'should call the store to mark the task as failed', -> expect(failedTask.status).to.eql 'failed' expect(failedTask.response[0]).to.eql 'fail-response' it 'should emit a task::fail event', -> expect(caughtFailedEvent).to.be.true describe '::taskCancel', -> cancelledTask = null caughtCancelEvent = false beforeEach (done) -> queue.on 'task::cancelled', (task) -> caughtCancelEvent = true queue.taskAdd({ name: 'cancel-test' }) .then (task) -> queue.taskCancel('cancel-worker', task.id, 'response') .then (task) -> cancelledTask = task done() it 'should call the store to mark the task as cancelled', -> expect(cancelledTask.status).to.eql 'cancelled' expect(cancelledTask.response[0]).to.eql 'response' it 'should emit a task::cancel event', -> expect(caughtCancelEvent).to.be.true describe '::taskGetById', -> it 'should call the store to get a task by its identifier', -> queue.taskAdd({ name: 'get-by-id-task' }) .then (task) -> queue.taskGetById(task.id) .then (task) -> expect(task.name).to.eql 'get-by-id-task' describe '::taskAdd', -> it 'should call the store to persist the given task object.', -> queue.taskAdd({ name: 'test-add-task' }) .then (task) -> expect(task.id).to.not.be.undefined return queue.taskGetById(task.id) .then (task) -> expect(task.name).to.eql 'test-add-task' it 'should throw an TypeError given a task with an ID', -> queue.taskAdd({ id : 'my-task-id' name : 'test-add-task' }) .then -> throw new Error('UnexpectedSuccess') .catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject' describe '::taskLock', -> result = null workerId = 'lock-worker' task = { name: 'lock-task' } caughtEvent = false before (done) -> queue.on 'task::locked', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskLock(workerId, task.id) .then (task) -> result = task it 'should call the store to lock the task', -> expect(result.id).to.not.be.undefined expect(result.id).to.be.a 'string' expect(result.semaphore.key).to.be.a 'string' it 'should emit a task::lock event', -> expect(caughtEvent).to.be.true describe '::taskUnlock', -> result = null workerId = 'lock-worker' task = { name: 'lock-task' } caughtEvent = false before (done) -> queue.on 'task::unlocked', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskLock(workerId, task.id) .then (task) -> queue.taskUnlock(workerId, task.id) .then (task) -> result = task it 'should call the store to unlock the task', -> expect(result.semaphore).to.be.null expect(result.id).to.be.a 'string' it 'should emit a task::unlock event', -> expect(caughtEvent).to.be.true describe '::taskYield', -> result = null workerId = 'yield-worker' task = { name : 'yield-task' } yieldEvent = false clock = null startTime = 1434734400000 tenMinutes = 10 * 60 * 1000 before (done) -> clock = sinon.useFakeTimers(startTime) queue.on 'task::finished', -> yieldEvent = true task = new TaskRequest('yield-task', queue) task.later('every 10 minutes') task.send() .tap -> clock.tick tenMinutes .then (task) -> queue.taskYield(workerId, task.id, 'something') .then (task) -> result = task .then -> done() after -> clock.restore() it 'should throw a TypeError if the task doesn\'t have a schedule', -> no_schedule_task = { name : 'no-schedule-for-me' } queue.taskAdd(task) .then (task) -> queue.taskYield('my-worker-id', task.id, 'blah') .then -> throw new Error('UnexpectedSuccess') .catch TypeError, (e) -> expect(e.message).to.eql 'TaskNotScheduled' it 'should emit a task finished event', -> expect(yieldEvent).to.be.true it 'should not update the task status', -> expect(result.status).to.eql 'new' it 'should update the after time', -> expect(result.after).to.eql (new Date().getTime()) + tenMinutes describe '::taskProgress', -> result = null workerId = 'progress-worker' task = { name: 'progress-task' } caughtEvent = false before (done) -> queue.on 'task::progress', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskProgress(workerId, task.id, 'some-progress') .then (task) -> result = task it 'should lock the task before updating', -> expect(result.semaphore).to.not.be.undefined it 'should call the store to update the task progress', -> expect(result.progress).to.eql 'some-progress' it 'should emit a task::progress event', -> expect(caughtEvent).to.be.true describe '::workerRegister', -> it 'should add the given worker to the registry', -> worker = taskReady : sinon.spy() id = queue.workerRegister(['test1', 'test2'], worker) expect(queue.registry[id].worker).to.eql worker expect(queue.registry[id].types).to.eql [ 'test1', 'test2' ] it 'should bind the worker to the task::ready event', (done) -> worker = taskReady : (type, id) -> expect(type).to.eql 'test-register' expect(id).to.eql 'register-task-id' done() task = { id : 'register-task-id' name : '<NAME>' pickle : -> null } id = queue.workerRegister([ 'test-register' ], worker) queue.workerNotify(task) it 'should not call the worker if the task name is not in the type list', (done) -> worker = taskReady : sinon.spy() notType = { id : 'not-type-task' name : 'not-in-list' pickle : -> null } queue.workerRegister([ 'test1', 'test2' ], worker) queue.workerNotify(notType) setTimeout -> expect(worker.taskReady.called).to.be.false done() , 5 describe '::workerNotify', -> it 'should throw a TypeError if the task is not persisted', -> not_persisted = { name : 'not-persisted' pickle : -> null } test = -> queue.workerNotify(not_persisted) expect(test).to.throw TypeError, /TaskNotPersisted/ it 'should throw a TypeError if the task name is missing', -> persisted = { id : 'i-am-persisted' pickle : -> null } test = -> queue.workerNotify(persisted) expect(test).to.throw TypeError, /TaskTypeMissing/ it 'should emit a task ready event', (done) -> test_task = { id : 'worker-notify-id' name : 'worker-notify-task' pickle : -> null } queue.on 'task::ready', (taskName, taskId) -> expect(taskId).to.eql 'worker-notify-id' expect(taskName).to.eql 'worker-notify-task' done() queue.workerNotify(test_task) it 'should be called when the store emits a ready event.', (done) -> task = { id : 'ready-task-id' name : '<NAME>' pickle: -> null } queue.on 'task::ready', (taskName, taskId) -> expect(taskName).to.eql 'test1' expect(taskId).to.eql 'ready-task-id' done() store.emit 'ready', task describe '::workerStatus', -> it 'should throw an Error', -> test = -> queue.workerStatus() expect(test).to.throw Error, /NotImplemented/
true
Queue = require '../../lib/queue.js' TaskRequest = require '../../lib/task/request.js' TaskLock = require 'uow-lock' { inherits } = require 'util' { EventEmitter } = require 'events' { MemoryStore } = require 'uow-store' describe 'Queue', -> queue = null store = null beforeEach -> store = MemoryStore() queue = new Queue(store) it 'should follow the optional new pattern', -> queue = Queue(store) expect(queue instanceof Queue).to.be.true describe '::taskComplete', -> completeTask = null caughtCompleteEvent = false beforeEach (done) -> queue.on 'task::finished', -> caughtCompleteEvent = true queue.taskAdd({ name: 'complete-task' }) .then (task) -> queue.taskComplete('complete-worker', task.id, 'complete') .then (task) -> completeTask = task done() it 'should call the store to update the task', -> expect(completeTask.status).to.eql 'success' expect(completeTask.response[0]).to.eql 'complete' it 'should emit a task::update event', -> expect(caughtCompleteEvent).to.be.true it 'should change the response to an array if it\'s not currently an array', -> queue.taskAdd({ name : 'test-not-array' }) .then (task) -> task.response = 'not-an-array' queue.store.updateTask('worker-id', task) .then (task) -> queue.taskComplete('worker-id', task.id, 'done') .then (task) -> expect(task.response).to.eql [ 'not-an-array' 'done' ] describe '::taskFail', -> failedTask = null caughtFailedEvent = false beforeEach (done) -> queue.on 'task::failed', (task) -> caughtFailedEvent = true queue.taskAdd({ name: 'fail-task' }) .then (task) -> queue.taskFail('fail-worker', task.id, 'fail-response') .then (task) -> failedTask = task done() it 'should call the store to mark the task as failed', -> expect(failedTask.status).to.eql 'failed' expect(failedTask.response[0]).to.eql 'fail-response' it 'should emit a task::fail event', -> expect(caughtFailedEvent).to.be.true describe '::taskCancel', -> cancelledTask = null caughtCancelEvent = false beforeEach (done) -> queue.on 'task::cancelled', (task) -> caughtCancelEvent = true queue.taskAdd({ name: 'cancel-test' }) .then (task) -> queue.taskCancel('cancel-worker', task.id, 'response') .then (task) -> cancelledTask = task done() it 'should call the store to mark the task as cancelled', -> expect(cancelledTask.status).to.eql 'cancelled' expect(cancelledTask.response[0]).to.eql 'response' it 'should emit a task::cancel event', -> expect(caughtCancelEvent).to.be.true describe '::taskGetById', -> it 'should call the store to get a task by its identifier', -> queue.taskAdd({ name: 'get-by-id-task' }) .then (task) -> queue.taskGetById(task.id) .then (task) -> expect(task.name).to.eql 'get-by-id-task' describe '::taskAdd', -> it 'should call the store to persist the given task object.', -> queue.taskAdd({ name: 'test-add-task' }) .then (task) -> expect(task.id).to.not.be.undefined return queue.taskGetById(task.id) .then (task) -> expect(task.name).to.eql 'test-add-task' it 'should throw an TypeError given a task with an ID', -> queue.taskAdd({ id : 'my-task-id' name : 'test-add-task' }) .then -> throw new Error('UnexpectedSuccess') .catch TypeError, (e) -> expect(e.message).to.eql 'InvalidTaskObject' describe '::taskLock', -> result = null workerId = 'lock-worker' task = { name: 'lock-task' } caughtEvent = false before (done) -> queue.on 'task::locked', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskLock(workerId, task.id) .then (task) -> result = task it 'should call the store to lock the task', -> expect(result.id).to.not.be.undefined expect(result.id).to.be.a 'string' expect(result.semaphore.key).to.be.a 'string' it 'should emit a task::lock event', -> expect(caughtEvent).to.be.true describe '::taskUnlock', -> result = null workerId = 'lock-worker' task = { name: 'lock-task' } caughtEvent = false before (done) -> queue.on 'task::unlocked', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskLock(workerId, task.id) .then (task) -> queue.taskUnlock(workerId, task.id) .then (task) -> result = task it 'should call the store to unlock the task', -> expect(result.semaphore).to.be.null expect(result.id).to.be.a 'string' it 'should emit a task::unlock event', -> expect(caughtEvent).to.be.true describe '::taskYield', -> result = null workerId = 'yield-worker' task = { name : 'yield-task' } yieldEvent = false clock = null startTime = 1434734400000 tenMinutes = 10 * 60 * 1000 before (done) -> clock = sinon.useFakeTimers(startTime) queue.on 'task::finished', -> yieldEvent = true task = new TaskRequest('yield-task', queue) task.later('every 10 minutes') task.send() .tap -> clock.tick tenMinutes .then (task) -> queue.taskYield(workerId, task.id, 'something') .then (task) -> result = task .then -> done() after -> clock.restore() it 'should throw a TypeError if the task doesn\'t have a schedule', -> no_schedule_task = { name : 'no-schedule-for-me' } queue.taskAdd(task) .then (task) -> queue.taskYield('my-worker-id', task.id, 'blah') .then -> throw new Error('UnexpectedSuccess') .catch TypeError, (e) -> expect(e.message).to.eql 'TaskNotScheduled' it 'should emit a task finished event', -> expect(yieldEvent).to.be.true it 'should not update the task status', -> expect(result.status).to.eql 'new' it 'should update the after time', -> expect(result.after).to.eql (new Date().getTime()) + tenMinutes describe '::taskProgress', -> result = null workerId = 'progress-worker' task = { name: 'progress-task' } caughtEvent = false before (done) -> queue.on 'task::progress', (task) -> caughtEvent = true done() queue.taskAdd(task) .then (task) -> queue.taskProgress(workerId, task.id, 'some-progress') .then (task) -> result = task it 'should lock the task before updating', -> expect(result.semaphore).to.not.be.undefined it 'should call the store to update the task progress', -> expect(result.progress).to.eql 'some-progress' it 'should emit a task::progress event', -> expect(caughtEvent).to.be.true describe '::workerRegister', -> it 'should add the given worker to the registry', -> worker = taskReady : sinon.spy() id = queue.workerRegister(['test1', 'test2'], worker) expect(queue.registry[id].worker).to.eql worker expect(queue.registry[id].types).to.eql [ 'test1', 'test2' ] it 'should bind the worker to the task::ready event', (done) -> worker = taskReady : (type, id) -> expect(type).to.eql 'test-register' expect(id).to.eql 'register-task-id' done() task = { id : 'register-task-id' name : 'PI:NAME:<NAME>END_PI' pickle : -> null } id = queue.workerRegister([ 'test-register' ], worker) queue.workerNotify(task) it 'should not call the worker if the task name is not in the type list', (done) -> worker = taskReady : sinon.spy() notType = { id : 'not-type-task' name : 'not-in-list' pickle : -> null } queue.workerRegister([ 'test1', 'test2' ], worker) queue.workerNotify(notType) setTimeout -> expect(worker.taskReady.called).to.be.false done() , 5 describe '::workerNotify', -> it 'should throw a TypeError if the task is not persisted', -> not_persisted = { name : 'not-persisted' pickle : -> null } test = -> queue.workerNotify(not_persisted) expect(test).to.throw TypeError, /TaskNotPersisted/ it 'should throw a TypeError if the task name is missing', -> persisted = { id : 'i-am-persisted' pickle : -> null } test = -> queue.workerNotify(persisted) expect(test).to.throw TypeError, /TaskTypeMissing/ it 'should emit a task ready event', (done) -> test_task = { id : 'worker-notify-id' name : 'worker-notify-task' pickle : -> null } queue.on 'task::ready', (taskName, taskId) -> expect(taskId).to.eql 'worker-notify-id' expect(taskName).to.eql 'worker-notify-task' done() queue.workerNotify(test_task) it 'should be called when the store emits a ready event.', (done) -> task = { id : 'ready-task-id' name : 'PI:NAME:<NAME>END_PI' pickle: -> null } queue.on 'task::ready', (taskName, taskId) -> expect(taskName).to.eql 'test1' expect(taskId).to.eql 'ready-task-id' done() store.emit 'ready', task describe '::workerStatus', -> it 'should throw an Error', -> test = -> queue.workerStatus() expect(test).to.throw Error, /NotImplemented/
[ { "context": " id: 'coolbox4life.dfc12b44'\n accessToken: \"pk.eyJ1IjoiY29vbGJveDRsaWZlIiwiYSI6ImY2Zjk2YmQ1ZjMyYWM2ZDZk\\\n YjI2OWIzY2U3YzMwY2NhIn0.WGZ5HU-CIlNshi1UVm4z-g\"\n })\n .addTo @map\n\n @map.on 'locationfou", "end": 730, "score": 0.977211594581604, "start": 617, "tag": "KEY", "value": "pk.eyJ1IjoiY29vbGJveDRsaWZlIiwiYSI6ImY2Zjk2YmQ1ZjMyYWM2ZDZk\\\n YjI2OWIzY2U3YzMwY2NhIn0.WGZ5HU-CIlNshi1UVm4z-g" } ]
www/coffee/services.coffee
CEPFU/ionic-front
0
angular.module 'starter.services', ['ionic.service.core', 'starter.config'] .service 'MapService', () -> @map = null @listeners = [] @init = (cssId) => @map = L.map cssId L.tileLayer("https://api.tiles.mapbox.com/v4/{id}\ /{z}/{x}/{y}.png?access_token={accessToken}", { attribution: """Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>""" maxZoom: 18 id: 'coolbox4life.dfc12b44' accessToken: "pk.eyJ1IjoiY29vbGJveDRsaWZlIiwiYSI6ImY2Zjk2YmQ1ZjMyYWM2ZDZk\ YjI2OWIzY2U3YzMwY2NhIn0.WGZ5HU-CIlNshi1UVm4z-g" }) .addTo @map @map.on 'locationfound', @applyListeners @applyListeners = (location) => for listener in @listeners listener(location) @registerListener = (listener) -> @listeners.push(listener) @popListener = (idx = -1) -> @listeners.splice(idx, 1) # Copies the relevant properties from the leaflet location @simpleLocation = (location) -> propertiesToCopy = [ 'accuracy', 'bounds', 'latlng', 'timestamp' ] simple = {} for prop in propertiesToCopy simple[prop] = location[prop] simple @setView = (location) -> zoom = if location.accuracy? then Math.round(location.accuracy / 2) else 16 @map.setView location.latlng, zoom # Adds a pin at the specified location and adds an optional popup @addPin = (location, popup) => marker = L.marker location.latlng .addTo @map if popup? marker.bindPopup popup .openPopup() @locate = (popup, circle = false, options = {setView: true, maxZoom: 16}) -> @registerListener (location) => radius = location.accuracy / 2 popupText = if popup? then popup(location) else null @addPin location, popupText if circle L.circle location.latlng, radius .addTo @map @popListener() @map.locate options null .service 'ProfileService', ($localStorage, RestService) -> @newLocation = undefined @persist = (profileData) -> if not profileData? profileData = @profileData console.log 'Persisting:', JSON.stringify profileData $localStorage.setObject 'profiles', profileData @getProfiles = () -> @profileData.profiles @getProfile = (id) -> @profileData.profiles[id] @putProfile = (id, profile) -> @profileData.profiles[id] = profile @putProfile = (profile) -> @profileData.profiles[profile.id] = profile @newProfile = () -> @profileData.lastId += 1 newProfile = { id: @profileData.lastId ? 0 } @putProfile newProfile newProfile @deleteProfile = (profile) -> delete @profileData.profiles[profile.id] @persist() RestService.deleteProfile profile @profileData = $localStorage.getObject 'profiles' if not @profileData? @profileData = lastId: 0 profiles: {} @persist @profileData null .service 'LocationService', () -> @currentLocation = undefined null .service 'RestService', ($rootScope, $ionicUser, $http, filterFilter, $ionicCoreSettings, ConfigService) -> @endpointUrl = ConfigService.api.mainUrl @getApiUrl = (target) -> @endpointUrl + ConfigService.api.endpoints[target].url @getUser = () -> user = Ionic.User.current() if not user.id user.id = Ionic.User.anonymousId() user.save() user @findNearbyStations = (location, callback, limit=3) -> url = @getApiUrl 'nearby' $http.post(url + limit, latitude: location.latlng.lat longitude: location.latlng.lng ).then( (succ) -> console.log 'Success:', succ locations = succ.data if callback? callback locations , (fail) -> console.log 'Failure:', fail ) # Copies the specified properties into a new object (shallow?) @selectiveCopy = (obj, properties) -> newObj = {} for prop in properties newObj[prop] = obj[prop] newObj @findJavaClass = (inputConfig, inputValue) -> if inputConfig.javaClass? inputConfig.javaClass else if inputConfig.options? inputConfig.options[inputValue.value]?.javaClass @getValue = (config, input) -> value = input.value if config.valueType? switch config.valueType when 'int' value = parseInt value when 'float' value = parseFloat value value @transformLocation = (location) -> accuracy: location.accuracy position: latitude: location.latlng.lat longitude: location.latlng.lng timestamp: location.timestamp @transformProfile = (profile) -> newProfile = @selectiveCopy profile, ['name', 'id'] newProfile.userId = @getUser().id newProfile.location = @transformLocation profile.location newProfile.appId = $ionicCoreSettings.get('app_id') rule = '@class': 'JSONAnd' ofOperands: [] for prop in (profile.properties ? []) config = ConfigService.profile.properties[prop.name] operand = { '@class': 'JSONMatchToStation' toStation: profile.station.locationId # TODO: Find new format?! } # console.log 'Prop:', prop # console.log 'Config:', config switch config.javaStructure.type when 'attributeToObject' classFrom = config.javaStructure.classFrom valueFrom = config.javaStructure.valueFrom javaClass = @findJavaClass config.inputs[classFrom], prop.inputs[classFrom] value = @getValue config.inputs[valueFrom], prop.inputs[valueFrom] operand.matchOperator = { '@class': javaClass attribute: prop.name toObject: value } rule.ofOperands.push operand newProfile.profile = rule: rule newProfile @sendProfile = (profile) -> url = @getApiUrl 'profile' payload = @transformProfile profile # console.log 'API URL:', url # console.log 'Payload:', payload # console.log 'JSON Payload:', JSON.stringify payload $http.post url, payload null @deleteProfile = (profile) -> url = @getApiUrl 'deleteProfile' # TODO: simplify this, we only really need the user and profile ID! payload = @transformProfile profile $http.post url, payload null
124064
angular.module 'starter.services', ['ionic.service.core', 'starter.config'] .service 'MapService', () -> @map = null @listeners = [] @init = (cssId) => @map = L.map cssId L.tileLayer("https://api.tiles.mapbox.com/v4/{id}\ /{z}/{x}/{y}.png?access_token={accessToken}", { attribution: """Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>""" maxZoom: 18 id: 'coolbox4life.dfc12b44' accessToken: "<KEY>" }) .addTo @map @map.on 'locationfound', @applyListeners @applyListeners = (location) => for listener in @listeners listener(location) @registerListener = (listener) -> @listeners.push(listener) @popListener = (idx = -1) -> @listeners.splice(idx, 1) # Copies the relevant properties from the leaflet location @simpleLocation = (location) -> propertiesToCopy = [ 'accuracy', 'bounds', 'latlng', 'timestamp' ] simple = {} for prop in propertiesToCopy simple[prop] = location[prop] simple @setView = (location) -> zoom = if location.accuracy? then Math.round(location.accuracy / 2) else 16 @map.setView location.latlng, zoom # Adds a pin at the specified location and adds an optional popup @addPin = (location, popup) => marker = L.marker location.latlng .addTo @map if popup? marker.bindPopup popup .openPopup() @locate = (popup, circle = false, options = {setView: true, maxZoom: 16}) -> @registerListener (location) => radius = location.accuracy / 2 popupText = if popup? then popup(location) else null @addPin location, popupText if circle L.circle location.latlng, radius .addTo @map @popListener() @map.locate options null .service 'ProfileService', ($localStorage, RestService) -> @newLocation = undefined @persist = (profileData) -> if not profileData? profileData = @profileData console.log 'Persisting:', JSON.stringify profileData $localStorage.setObject 'profiles', profileData @getProfiles = () -> @profileData.profiles @getProfile = (id) -> @profileData.profiles[id] @putProfile = (id, profile) -> @profileData.profiles[id] = profile @putProfile = (profile) -> @profileData.profiles[profile.id] = profile @newProfile = () -> @profileData.lastId += 1 newProfile = { id: @profileData.lastId ? 0 } @putProfile newProfile newProfile @deleteProfile = (profile) -> delete @profileData.profiles[profile.id] @persist() RestService.deleteProfile profile @profileData = $localStorage.getObject 'profiles' if not @profileData? @profileData = lastId: 0 profiles: {} @persist @profileData null .service 'LocationService', () -> @currentLocation = undefined null .service 'RestService', ($rootScope, $ionicUser, $http, filterFilter, $ionicCoreSettings, ConfigService) -> @endpointUrl = ConfigService.api.mainUrl @getApiUrl = (target) -> @endpointUrl + ConfigService.api.endpoints[target].url @getUser = () -> user = Ionic.User.current() if not user.id user.id = Ionic.User.anonymousId() user.save() user @findNearbyStations = (location, callback, limit=3) -> url = @getApiUrl 'nearby' $http.post(url + limit, latitude: location.latlng.lat longitude: location.latlng.lng ).then( (succ) -> console.log 'Success:', succ locations = succ.data if callback? callback locations , (fail) -> console.log 'Failure:', fail ) # Copies the specified properties into a new object (shallow?) @selectiveCopy = (obj, properties) -> newObj = {} for prop in properties newObj[prop] = obj[prop] newObj @findJavaClass = (inputConfig, inputValue) -> if inputConfig.javaClass? inputConfig.javaClass else if inputConfig.options? inputConfig.options[inputValue.value]?.javaClass @getValue = (config, input) -> value = input.value if config.valueType? switch config.valueType when 'int' value = parseInt value when 'float' value = parseFloat value value @transformLocation = (location) -> accuracy: location.accuracy position: latitude: location.latlng.lat longitude: location.latlng.lng timestamp: location.timestamp @transformProfile = (profile) -> newProfile = @selectiveCopy profile, ['name', 'id'] newProfile.userId = @getUser().id newProfile.location = @transformLocation profile.location newProfile.appId = $ionicCoreSettings.get('app_id') rule = '@class': 'JSONAnd' ofOperands: [] for prop in (profile.properties ? []) config = ConfigService.profile.properties[prop.name] operand = { '@class': 'JSONMatchToStation' toStation: profile.station.locationId # TODO: Find new format?! } # console.log 'Prop:', prop # console.log 'Config:', config switch config.javaStructure.type when 'attributeToObject' classFrom = config.javaStructure.classFrom valueFrom = config.javaStructure.valueFrom javaClass = @findJavaClass config.inputs[classFrom], prop.inputs[classFrom] value = @getValue config.inputs[valueFrom], prop.inputs[valueFrom] operand.matchOperator = { '@class': javaClass attribute: prop.name toObject: value } rule.ofOperands.push operand newProfile.profile = rule: rule newProfile @sendProfile = (profile) -> url = @getApiUrl 'profile' payload = @transformProfile profile # console.log 'API URL:', url # console.log 'Payload:', payload # console.log 'JSON Payload:', JSON.stringify payload $http.post url, payload null @deleteProfile = (profile) -> url = @getApiUrl 'deleteProfile' # TODO: simplify this, we only really need the user and profile ID! payload = @transformProfile profile $http.post url, payload null
true
angular.module 'starter.services', ['ionic.service.core', 'starter.config'] .service 'MapService', () -> @map = null @listeners = [] @init = (cssId) => @map = L.map cssId L.tileLayer("https://api.tiles.mapbox.com/v4/{id}\ /{z}/{x}/{y}.png?access_token={accessToken}", { attribution: """Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>""" maxZoom: 18 id: 'coolbox4life.dfc12b44' accessToken: "PI:KEY:<KEY>END_PI" }) .addTo @map @map.on 'locationfound', @applyListeners @applyListeners = (location) => for listener in @listeners listener(location) @registerListener = (listener) -> @listeners.push(listener) @popListener = (idx = -1) -> @listeners.splice(idx, 1) # Copies the relevant properties from the leaflet location @simpleLocation = (location) -> propertiesToCopy = [ 'accuracy', 'bounds', 'latlng', 'timestamp' ] simple = {} for prop in propertiesToCopy simple[prop] = location[prop] simple @setView = (location) -> zoom = if location.accuracy? then Math.round(location.accuracy / 2) else 16 @map.setView location.latlng, zoom # Adds a pin at the specified location and adds an optional popup @addPin = (location, popup) => marker = L.marker location.latlng .addTo @map if popup? marker.bindPopup popup .openPopup() @locate = (popup, circle = false, options = {setView: true, maxZoom: 16}) -> @registerListener (location) => radius = location.accuracy / 2 popupText = if popup? then popup(location) else null @addPin location, popupText if circle L.circle location.latlng, radius .addTo @map @popListener() @map.locate options null .service 'ProfileService', ($localStorage, RestService) -> @newLocation = undefined @persist = (profileData) -> if not profileData? profileData = @profileData console.log 'Persisting:', JSON.stringify profileData $localStorage.setObject 'profiles', profileData @getProfiles = () -> @profileData.profiles @getProfile = (id) -> @profileData.profiles[id] @putProfile = (id, profile) -> @profileData.profiles[id] = profile @putProfile = (profile) -> @profileData.profiles[profile.id] = profile @newProfile = () -> @profileData.lastId += 1 newProfile = { id: @profileData.lastId ? 0 } @putProfile newProfile newProfile @deleteProfile = (profile) -> delete @profileData.profiles[profile.id] @persist() RestService.deleteProfile profile @profileData = $localStorage.getObject 'profiles' if not @profileData? @profileData = lastId: 0 profiles: {} @persist @profileData null .service 'LocationService', () -> @currentLocation = undefined null .service 'RestService', ($rootScope, $ionicUser, $http, filterFilter, $ionicCoreSettings, ConfigService) -> @endpointUrl = ConfigService.api.mainUrl @getApiUrl = (target) -> @endpointUrl + ConfigService.api.endpoints[target].url @getUser = () -> user = Ionic.User.current() if not user.id user.id = Ionic.User.anonymousId() user.save() user @findNearbyStations = (location, callback, limit=3) -> url = @getApiUrl 'nearby' $http.post(url + limit, latitude: location.latlng.lat longitude: location.latlng.lng ).then( (succ) -> console.log 'Success:', succ locations = succ.data if callback? callback locations , (fail) -> console.log 'Failure:', fail ) # Copies the specified properties into a new object (shallow?) @selectiveCopy = (obj, properties) -> newObj = {} for prop in properties newObj[prop] = obj[prop] newObj @findJavaClass = (inputConfig, inputValue) -> if inputConfig.javaClass? inputConfig.javaClass else if inputConfig.options? inputConfig.options[inputValue.value]?.javaClass @getValue = (config, input) -> value = input.value if config.valueType? switch config.valueType when 'int' value = parseInt value when 'float' value = parseFloat value value @transformLocation = (location) -> accuracy: location.accuracy position: latitude: location.latlng.lat longitude: location.latlng.lng timestamp: location.timestamp @transformProfile = (profile) -> newProfile = @selectiveCopy profile, ['name', 'id'] newProfile.userId = @getUser().id newProfile.location = @transformLocation profile.location newProfile.appId = $ionicCoreSettings.get('app_id') rule = '@class': 'JSONAnd' ofOperands: [] for prop in (profile.properties ? []) config = ConfigService.profile.properties[prop.name] operand = { '@class': 'JSONMatchToStation' toStation: profile.station.locationId # TODO: Find new format?! } # console.log 'Prop:', prop # console.log 'Config:', config switch config.javaStructure.type when 'attributeToObject' classFrom = config.javaStructure.classFrom valueFrom = config.javaStructure.valueFrom javaClass = @findJavaClass config.inputs[classFrom], prop.inputs[classFrom] value = @getValue config.inputs[valueFrom], prop.inputs[valueFrom] operand.matchOperator = { '@class': javaClass attribute: prop.name toObject: value } rule.ofOperands.push operand newProfile.profile = rule: rule newProfile @sendProfile = (profile) -> url = @getApiUrl 'profile' payload = @transformProfile profile # console.log 'API URL:', url # console.log 'Payload:', payload # console.log 'JSON Payload:', JSON.stringify payload $http.post url, payload null @deleteProfile = (profile) -> url = @getApiUrl 'deleteProfile' # TODO: simplify this, we only really need the user and profile ID! payload = @transformProfile profile $http.post url, payload null
[ { "context": "1', [])\n attacker = new Pokemon(species: \"Farfetch'd\", item: 'Stick')\n defender = new Pokemon()", "end": 2147, "score": 0.5990298390388489, "start": 2142, "tag": "NAME", "value": "fetch" }, { "context": "r).should.equal 3\n\n it \"is 3 if the attacker is Chansey with a Lucky Punch\", ->\n battle = new Bat", "end": 2338, "score": 0.7787144780158997, "start": 2334, "tag": "NAME", "value": "Chan" }, { "context": "e('1', [])\n attacker = new Pokemon(species: \"Chansey\", item: 'Lucky Punch')\n defender = new Pokem", "end": 2447, "score": 0.81419837474823, "start": 2440, "tag": "NAME", "value": "Chansey" }, { "context": "\n shared.create.call(this, team2: [Factory(\"Gengar\")])\n oldHP = @p1.stat('hp')\n @battle.", "end": 16109, "score": 0.44023290276527405, "start": 16106, "tag": "NAME", "value": "eng" }, { "context": " oldHP = @p1.stat('hp')\n @battle.recordMove(@id2, @battle.getMove(\"Protect\"))\n @battle.record", "end": 16422, "score": 0.5763225555419922, "start": 16419, "tag": "USERNAME", "value": "id2" }, { "context": "shared.create.call this,\n team1: [Factory('Conkeldurr')]\n team2: [Factory('Hitmonchan')]\n", "end": 16771, "score": 0.49268820881843567, "start": 16768, "tag": "USERNAME", "value": "Con" }, { "context": ".create.call this,\n team1: [Factory('Conkeldurr')]\n team2: [Factory('Hitmonchan')]\n s", "end": 16778, "score": 0.4896273910999298, "start": 16774, "tag": "USERNAME", "value": "durr" }, { "context": "eate.call this,\n team1: [Factory('Conkeldurr')]\n team2: [Factory('Hitmonchan')]\n h", "end": 17171, "score": 0.5954742431640625, "start": 17170, "tag": "NAME", "value": "r" }, { "context": "actory('Conkeldurr')]\n team2: [Factory('Hitmonchan')]\n hp = @p1.currentHP = @p1.stat('hp')\n ", "end": 17210, "score": 0.6919862031936646, "start": 17203, "tag": "NAME", "value": "monchan" }, { "context": "am1: [Factory('Celebi')]\n team2: [Factory('Hitmonchan')]\n hp = @p2.currentHP\n @battle.perform", "end": 17920, "score": 0.901007890701294, "start": 17910, "tag": "NAME", "value": "Hitmonchan" }, { "context": "[Factory('Gyarados')]\n team2: [Factory('Hitmonchan')]\n @battle.performMove(@p1, @battle.get", "end": 18553, "score": 0.5746979117393494, "start": 18550, "tag": "NAME", "value": "mon" }, { "context": "shared.create.call this,\n team1: [Factory('Gyarados')]\n team2: [Factory('Hitmonchan')]\n @", "end": 18778, "score": 0.784570038318634, "start": 18770, "tag": "NAME", "value": "Gyarados" }, { "context": "[Factory('Gyarados')]\n team2: [Factory('Hitmonchan')]\n @battle.performMove(@p1, @battle.getMove", "end": 18817, "score": 0.7001367807388306, "start": 18810, "tag": "NAME", "value": "monchan" }, { "context": "shared.create.call this,\n team1: [Factory('Audino')]\n team2: [Factory('Gengar')]\n @batt", "end": 19044, "score": 0.8529815673828125, "start": 19038, "tag": "NAME", "value": "Audino" }, { "context": "m1: [Factory('Audino')]\n team2: [Factory('Gengar')]\n @battle.performMove(@p1, @battle.getMove", "end": 19079, "score": 0.7042219638824463, "start": 19074, "tag": "NAME", "value": "engar" }, { "context": ">\n shared.create.call(this, team1: (Factory(\"Magikarp\") for x in [1..2]))\n @battle.performMove(@p", "end": 19283, "score": 0.6972687840461731, "start": 19275, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: [Factory('Celebi')]\n team2: [Factory('Gyarados')]\n hp ", "end": 19646, "score": 0.7676873803138733, "start": 19640, "tag": "NAME", "value": "Celebi" }, { "context": "m1: [Factory('Celebi')]\n team2: [Factory('Gyarados')]\n hp = @p2.currentHP\n @battle.per", "end": 19679, "score": 0.514670193195343, "start": 19676, "tag": "NAME", "value": "yar" }, { "context": "shared.create.call this,\n team1: [Factory('Gliscor')]\n team2: [Factory('Regirock')]\n hp ", "end": 21944, "score": 0.9889022707939148, "start": 21937, "tag": "NAME", "value": "Gliscor" }, { "context": "m1: [Factory('Gliscor')]\n team2: [Factory('Regirock')]\n hp = @p2.currentHP\n @battle.perform", "end": 21981, "score": 0.9014420509338379, "start": 21973, "tag": "NAME", "value": "Regirock" }, { "context": "shared.create.call this,\n team1: [Factory('Gliscor', item: 'Leftovers')]\n team2: [Factory('Re", "end": 22249, "score": 0.9887183308601379, "start": 22242, "tag": "NAME", "value": "Gliscor" }, { "context": "l this,\n team1: [Factory('Gliscor', item: 'Leftovers')]\n team2: [Factory('Regirock')]\n hp ", "end": 22268, "score": 0.5816475749015808, "start": 22259, "tag": "NAME", "value": "Leftovers" }, { "context": "or', item: 'Leftovers')]\n team2: [Factory('Regirock')]\n hp = @p2.currentHP\n @battle.perform", "end": 22305, "score": 0.9274594187736511, "start": 22297, "tag": "NAME", "value": "Regirock" }, { "context": "1: [Factory('Zangoose')]\n team2: [Factory('Magikarp')]\n hp = @p2.currentHP\n @p1.attach", "end": 27609, "score": 0.6977797746658325, "start": 27606, "tag": "NAME", "value": "Mag" }, { "context": "red.create.call this,\n team1: [Factory('Camerupt')]\n team2: [Factory('Mew')]\n @attacke", "end": 28591, "score": 0.5670137405395508, "start": 28586, "tag": "NAME", "value": "erupt" }, { "context": " team2: [Factory('Mew')]\n @attacker = @p1\n @defender = @p2\n @move = @battle.getMo", "end": 28648, "score": 0.5842447280883789, "start": 28647, "tag": "USERNAME", "value": "1" }, { "context": "('Mew')]\n @attacker = @p1\n @defender = @p2\n @move = @battle.getMove('Eruption')\n\n it", "end": 28670, "score": 0.7675541639328003, "start": 28668, "tag": "USERNAME", "value": "p2" }, { "context": "ve = @battle.getMove('Gyro Ball')\n attacker = @p1\n defender = @p2\n attacker.stages.speed ", "end": 29420, "score": 0.8748864531517029, "start": 29417, "tag": "USERNAME", "value": "@p1" }, { "context": "yro Ball')\n attacker = @p1\n defender = @p2\n attacker.stages.speed = -6\n move.baseP", "end": 29441, "score": 0.8273531198501587, "start": 29439, "tag": "USERNAME", "value": "p2" }, { "context": "1: [Factory('Empoleon')]\n team2: [Factory('Magikarp')]\n move = @battle.getMove('Brine')\n @p", "end": 30146, "score": 0.6568876504898071, "start": 30138, "tag": "NAME", "value": "Magikarp" }, { "context": "1: [Factory('Empoleon')]\n team2: [Factory('Magikarp')]\n move = @battle.getMove('Brine')\n @p", "end": 30467, "score": 0.6923918724060059, "start": 30459, "tag": "NAME", "value": "Magikarp" }, { "context": "red.create.call this,\n team1: [Factory('Magikarp', ivs: ivs)]\n team2: [Factory('Magikarp')]", "end": 33265, "score": 0.5253870487213135, "start": 33260, "tag": "NAME", "value": "ikarp" }, { "context": "shared.create.call this,\n team1: [Factory('Magikarp', ivs: ivs)]\n team2: [Factory('Magikarp')]", "end": 33629, "score": 0.6543288230895996, "start": 33621, "tag": "NAME", "value": "Magikarp" }, { "context": "gikarp', ivs: ivs)]\n team2: [Factory('Magikarp')]\n move = @battle.getMove('Hidden Power')\n ", "end": 33676, "score": 0.5451602935791016, "start": 33673, "tag": "NAME", "value": "arp" }, { "context": "shared.create.call this,\n team1: [Factory('Magikarp', ivs: ivs)]\n team2: [Factory('Magikarp')]", "end": 34005, "score": 0.6878926157951355, "start": 33997, "tag": "NAME", "value": "Magikarp" }, { "context": "y('Magikarp', ivs: ivs)]\n team2: [Factory('Magikarp')]\n move = @battle.getMove('Hidden Power')\n ", "end": 34052, "score": 0.7647822499275208, "start": 34044, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: [Factory('Magikarp', ivs: ivs)]\n team2: [Factory('Magikarp')]", "end": 34380, "score": 0.7679795622825623, "start": 34372, "tag": "NAME", "value": "Magikarp" }, { "context": "y('Magikarp', ivs: ivs)]\n team2: [Factory('Magikarp')]\n move = @battle.getMove('Hidden Power')\n ", "end": 34427, "score": 0.7563204765319824, "start": 34419, "tag": "NAME", "value": "Magikarp" }, { "context": "red.create.call this,\n team1: [Factory('Camerupt')]\n team2: [Factory('Magikarp')]\n ", "end": 34737, "score": 0.5147385001182556, "start": 34735, "tag": "NAME", "value": "er" }, { "context": "1: [Factory('Camerupt')]\n team2: [Factory('Magikarp')]\n @battle.performMove(@p1, @battle.getMove", "end": 34777, "score": 0.7518541216850281, "start": 34769, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: [Factory('Camerupt')]\n team2: [Factory('Magikarp')]\n @ba", "end": 35018, "score": 0.6772709488868713, "start": 35010, "tag": "NAME", "value": "Camerupt" }, { "context": "1: [Factory('Camerupt')]\n team2: [Factory('Magikarp')]\n @battle.performMove(@p1, @battle.getMove", "end": 35055, "score": 0.67156583070755, "start": 35047, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: [Factory('Lapras')]\n team2: [Factory('Magikarp')]\n @p2", "end": 35909, "score": 0.833857536315918, "start": 35903, "tag": "NAME", "value": "Lapras" }, { "context": "am1: [Factory('Lapras')]\n team2: [Factory('Magikarp')]\n @p2.currentHP = Math.floor(@p2.stat('hp'", "end": 35946, "score": 0.7777369618415833, "start": 35938, "tag": "NAME", "value": "Magikarp" }, { "context": "arp')]\n team2: [Factory('Magikarp', item: \"Sitrus Berry\")]\n @p2.currentHP = 2\n move = @ba", "end": 38870, "score": 0.7028031945228577, "start": 38864, "tag": "NAME", "value": "Sitrus" }, { "context": "shared.create.call this,\n team1: [Factory('Alakazam', item: 'Stick')]\n team2: [Factory('Magika", "end": 39634, "score": 0.8833185434341431, "start": 39626, "tag": "NAME", "value": "Alakazam" }, { "context": "m', item: 'Stick')]\n team2: [Factory('Magikarp', item: \"Leftovers\")]\n item1 = @p1.item\n ", "end": 39686, "score": 0.6709209084510803, "start": 39683, "tag": "NAME", "value": "arp" }, { "context": "shared.create.call this,\n team1: [Factory('Alakazam', ability: \"Sticky Hold\", item: 'Stick')]\n ", "end": 40021, "score": 0.8620383739471436, "start": 40013, "tag": "NAME", "value": "Alakazam" }, { "context": "y Hold\", item: 'Stick')]\n team2: [Factory('Gastrodon', item: \"Leftovers\")]\n trick = @battle.getMo", "end": 40098, "score": 0.955791175365448, "start": 40089, "tag": "NAME", "value": "Gastrodon" }, { "context": "shared.create.call this,\n team1: [Factory('Alakazam', item: 'Stick')]\n team2: [Factory('Magika", "end": 40389, "score": 0.9230953454971313, "start": 40381, "tag": "NAME", "value": "Alakazam" }, { "context": "akazam', item: 'Stick')]\n team2: [Factory('Magikarp', ability: \"Sticky Hold\", item: \"Leftovers\")]\n ", "end": 40441, "score": 0.6629435420036316, "start": 40433, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: [Factory('Alakazam', item: 'Stick')]\n team2: [Factory('Magika", "end": 40761, "score": 0.8995267152786255, "start": 40753, "tag": "NAME", "value": "Alakazam" }, { "context": "akazam', item: 'Stick')]\n team2: [Factory('Magikarp')]\n trick = @battle.getMove('Trick')\n i", "end": 40813, "score": 0.9678080081939697, "start": 40805, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: [Factory('Alakazam')]\n team2: [Factory('Magikarp')]\n tri", "end": 41116, "score": 0.9166422486305237, "start": 41108, "tag": "NAME", "value": "Alakazam" }, { "context": "1: [Factory('Alakazam')]\n team2: [Factory('Magikarp')]\n trick = @battle.getMove('Trick')\n m", "end": 41153, "score": 0.8795598149299622, "start": 41145, "tag": "NAME", "value": "Magikarp" }, { "context": "hared.create.call this,\n team1: [Factory('Dugtrio')]\n team2: [Factory('Magikarp')]\n mov", "end": 45908, "score": 0.563975989818573, "start": 45902, "tag": "NAME", "value": "ugtrio" }, { "context": "m1: [Factory('Dugtrio')]\n team2: [Factory('Magikarp')]\n move = @battle.getMove('Magnitude')", "end": 45940, "score": 0.6355217695236206, "start": 45937, "tag": "NAME", "value": "Mag" }, { "context": "Factory('Dugtrio')]\n team2: [Factory('Magikarp')]\n move = @battle.getMove('Magnitude')\n ", "end": 45945, "score": 0.5527517795562744, "start": 45942, "tag": "NAME", "value": "arp" }, { "context": "ry('Magikarp')]\n @controller.makeMove(@id1, 'Belly Drum')\n @controller.makeMove(@id2, 'Splash')\n\n ", "end": 48150, "score": 0.9982373714447021, "start": 48140, "tag": "NAME", "value": "Belly Drum" }, { "context": "('hp') / 2) - 1\n @controller.makeMove(@id1, 'Belly Drum')\n @controller.makeMove(@id2, 'Splash')\n\n ", "end": 48552, "score": 0.996307909488678, "start": 48542, "tag": "NAME", "value": "Belly Drum" }, { "context": "@p1.boost(attack: 12)\n bd = @battle.getMove('Belly Drum')\n mock = @sandbox.mock(bd).expects('fail').", "end": 48911, "score": 0.8726592063903809, "start": 48901, "tag": "NAME", "value": "Belly Drum" }, { "context": "eight()\n\n it 'cannot go below .1kg', ->\n # Magikarp weighs 100kg.\n shared.create.call this,", "end": 63237, "score": 0.6395618319511414, "start": 63234, "tag": "NAME", "value": "Mag" }, { "context": ")\n\n it 'cannot go below .1kg', ->\n # Magikarp weighs 100kg.\n shared.create.call this, team", "end": 63242, "score": 0.5053688883781433, "start": 63239, "tag": "NAME", "value": "arp" }, { "context": "\n shared.create.call this, team1: [ Factory('Magikarp')]\n @battle.performMove(@p1, @battle.getMove", "end": 63314, "score": 0.8429219722747803, "start": 63306, "tag": "NAME", "value": "Magikarp" }, { "context": "han .1\n\n it 'stacks weight changes', ->\n # Abomasnow weighs 1355kg.\n shared.create.call this, tea", "end": 63488, "score": 0.7078068852424622, "start": 63479, "tag": "NAME", "value": "Abomasnow" }, { "context": "\n shared.create.call this, team1: [ Factory('Abomasnow')]\n\n @battle.performMove(@p1, @battle.getMov", "end": 63562, "score": 0.9221944808959961, "start": 63553, "tag": "NAME", "value": "Abomasnow" }, { "context": ">\n shared.create.call(this, team1: [Factory(\"Magikarp\", evs: {speed: 4})])\n @battle.performMove(@p", "end": 68602, "score": 0.5991706252098083, "start": 68594, "tag": "NAME", "value": "Magikarp" }, { "context": "ttle.getMove('Splash'))\n @battle.recordMove(@id1, @battle.getMove('Taunt'))\n @battle.recordMo", "end": 68711, "score": 0.7962033748626709, "start": 68708, "tag": "USERNAME", "value": "id1" }, { "context": "attle.getMove('Taunt'))\n @battle.recordMove(@id2, @battle.getMove('Tackle'))\n @battle.continu", "end": 68768, "score": 0.8340988159179688, "start": 68765, "tag": "USERNAME", "value": "id2" }, { "context": "ared.create.call this,\n team1: [Factory(\"Gliscor\")]\n\n @p1.currentHP = 1\n @battle.perform", "end": 77669, "score": 0.6021537780761719, "start": 77664, "tag": "NAME", "value": "iscor" }, { "context": "battle.getMove('Splash'))\n @battle.recordMove(@id1, @battle.getMove('Encore'))\n @battle.recordM", "end": 78768, "score": 0.9116588234901428, "start": 78764, "tag": "USERNAME", "value": "@id1" }, { "context": "battle.getMove('Encore'))\n @battle.recordMove(@id2, @battle.getMove('Tackle'))\n @battle.continu", "end": 78826, "score": 0.9424477219581604, "start": 78822, "tag": "USERNAME", "value": "@id2" }, { "context": "ttle.getMove('Splash'))\n @battle.recordMove(@id1, @battle.getMove('Encore'))\n @battle.recordM", "end": 79672, "score": 0.9340978860855103, "start": 79669, "tag": "USERNAME", "value": "id1" }, { "context": "ttle.getMove('Encore'))\n @battle.recordMove(@id2, @battle.getMove('Tackle'))\n @battle.continu", "end": 79730, "score": 0.6148096323013306, "start": 79727, "tag": "USERNAME", "value": "id2" }, { "context": "@team2, 'switch')\n @controller.makeMove(@id1, moveName)\n @controller.makeMove(@id2, mov", "end": 98361, "score": 0.6502760648727417, "start": 98360, "tag": "USERNAME", "value": "1" }, { "context": " shared.create.call(this, team2: [Factory(\"Shedinja\")])\n @p2.types = [ \"Normal\" ]\n move", "end": 99486, "score": 0.8298966884613037, "start": 99479, "tag": "NAME", "value": "hedinja" }, { "context": " shared.create.call(this, team2: [Factory(\"Blissey\")])\n shared.biasRNG.call(this, \"randInt\", ", "end": 100545, "score": 0.6260881423950195, "start": 100540, "tag": "NAME", "value": "issey" }, { "context": " @battle.endTurn()\n\n @battle.recordMove(@id1, @battle.getMove(\"Protect\"))\n @battle.rec", "end": 103098, "score": 0.8584032654762268, "start": 103096, "tag": "USERNAME", "value": "id" }, { "context": "e.getMove(\"Protect\"))\n @battle.recordMove(@id2, @battle.getMove(\"Splash\"))\n @battle.cont", "end": 103159, "score": 0.8694170713424683, "start": 103157, "tag": "USERNAME", "value": "id" }, { "context": "makeSwitch(@id1, 1)\n @controller.makeMove(@id2, \"Splash\")\n\n @p2.isSwitchBlocked().should", "end": 103347, "score": 0.6213637590408325, "start": 103345, "tag": "USERNAME", "value": "id" }, { "context": "shared.create.call this,\n team1: [Factory(\"Magikarp\", gender: \"F\")]\n team2: [Factory(\"Magikarp", "end": 106063, "score": 0.9540091156959534, "start": 106055, "tag": "NAME", "value": "Magikarp" }, { "context": "Magikarp\", gender: \"F\")]\n team2: [Factory(\"Magikarp\", gender: \"F\")]\n\n mock = @sandbox.mock(@batt", "end": 106113, "score": 0.9450828433036804, "start": 106105, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: (Factory(\"Magikarp\", gender: \"M\") for x in [1..2])\n team2: [", "end": 106411, "score": 0.9119786620140076, "start": 106403, "tag": "NAME", "value": "Magikarp" }, { "context": ": \"M\") for x in [1..2])\n team2: [Factory(\"Magikarp\", gender: \"F\")]\n @battle.performMove(@p1, @b", "end": 106478, "score": 0.937031090259552, "start": 106470, "tag": "NAME", "value": "Magikarp" }, { "context": "hared.create.call(this)\n @battle.recordMove(@id1, @battle.getMove(\"Focus Punch\"))\n @battle.r", "end": 119765, "score": 0.6288121938705444, "start": 119763, "tag": "USERNAME", "value": "id" }, { "context": "getMove(\"Focus Punch\"))\n @battle.recordMove(@id2, @battle.getMove(\"Tackle\"))\n @battle.contin", "end": 119828, "score": 0.8468990325927734, "start": 119826, "tag": "USERNAME", "value": "id" }, { "context": " shared.create.call(this)\n @battle.recordMove(@id1, @battle.getMove(\"Focus Punch\"))\n @battle.re", "end": 120074, "score": 0.8253522515296936, "start": 120070, "tag": "USERNAME", "value": "@id1" }, { "context": "getMove(\"Focus Punch\"))\n @battle.recordMove(@id2, @battle.getMove(\"Will-O-Wisp\"))\n @battle.c", "end": 120136, "score": 0.6215367913246155, "start": 120134, "tag": "USERNAME", "value": "id" }, { "context": ": (@p1.currentHP >> 2))\n @battle.recordMove(@id1, @battle.getMove(\"Focus Punch\"))\n @battle.r", "end": 120441, "score": 0.7480719685554504, "start": 120439, "tag": "USERNAME", "value": "id" }, { "context": "getMove(\"Focus Punch\"))\n @battle.recordMove(@id2, @battle.getMove(\"Tackle\"))\n @battle.contin", "end": 120504, "score": 0.6849560737609863, "start": 120502, "tag": "USERNAME", "value": "id" }, { "context": "ment.Substitute, hp: 1)\n @battle.recordMove(@id1, @battle.getMove(\"Focus Punch\"))\n @battle.re", "end": 120776, "score": 0.8441423177719116, "start": 120773, "tag": "USERNAME", "value": "id1" }, { "context": "getMove(\"Focus Punch\"))\n @battle.recordMove(@id2, @battle.getMove(\"Tackle\"))\n @battle.contin", "end": 120838, "score": 0.7357502579689026, "start": 120836, "tag": "USERNAME", "value": "id" }, { "context": "shared.create.call(this)\n @battle.performMove(@p2, @battle.getMove(\"Tackle\"))\n @battle.endTurn", "end": 121077, "score": 0.7739432454109192, "start": 121074, "tag": "USERNAME", "value": "@p2" }, { "context": " @battle.beginTurn()\n @battle.recordMove(@id1, @battle.getMove(\"Focus Punch\"))\n @battle.co", "end": 121185, "score": 0.9309918284416199, "start": 121181, "tag": "USERNAME", "value": "@id1" }, { "context": "le.getMove(\"Focus Punch\")\n @battle.recordMove(@id1, @battle.getMove(\"Focus Punch\"))\n @battle.re", "end": 121509, "score": 0.7503121495246887, "start": 121505, "tag": "USERNAME", "value": "@id1" }, { "context": "getMove(\"Focus Punch\"))\n @battle.recordMove(@id2, @battle.getMove(\"Splash\"))\n @battle.contin", "end": 121571, "score": 0.9229716062545776, "start": 121569, "tag": "USERNAME", "value": "id" }, { "context": "\n hp = @p2.currentHP\n @battle.recordMove(@id1, @battle.getMove(\"Tackle\"))\n @battle.recordM", "end": 121735, "score": 0.8806045651435852, "start": 121731, "tag": "USERNAME", "value": "@id1" }, { "context": "ttle.getMove(\"Tackle\"))\n @battle.recordMove(@id2, @battle.getMove(\"Tackle\"))\n @battle.contin", "end": 121792, "score": 0.8161908984184265, "start": 121790, "tag": "USERNAME", "value": "id" }, { "context": "pects('hit').never()\n\n @battle.recordMove(@id2, move)\n @battle.determineTurnOrder()\n ", "end": 123853, "score": 0.9416037797927856, "start": 123850, "tag": "USERNAME", "value": "id2" }, { "context": "d.create.call this,\n team1: [ Factory(\"Shuckle\") ]\n\n momentumMove = @battle.getMove(moveN", "end": 131056, "score": 0.6878994703292847, "start": 131051, "tag": "USERNAME", "value": "uckle" }, { "context": ").expects('fail').once()\n\n @battle.recordMove(@id1, move)\n @battle.recordMove(@id2, @battle.get", "end": 133305, "score": 0.6172451972961426, "start": 133301, "tag": "USERNAME", "value": "@id1" }, { "context": "ttle.getMove(\"Tackle\")\n\n @battle.recordMove(@id1, @battle.getMove(\"Me First\"))\n @battle.reco", "end": 134080, "score": 0.514872670173645, "start": 134078, "tag": "USERNAME", "value": "id" }, { "context": "expects('fail').once()\n\n @battle.recordMove(@id2, @battle.getMove(\"Tackle\"))\n @battle.determi", "end": 143613, "score": 0.6307851076126099, "start": 143610, "tag": "USERNAME", "value": "id2" }, { "context": "ttle.getMove(moveName)\n\n @battle.recordMove(@id2, @battle.getMove(\"Tackle\"))\n @battle.determ", "end": 143951, "score": 0.5227096080780029, "start": 143949, "tag": "USERNAME", "value": "id" }, { "context": "ared.create.call(this)\n\n @battle.recordMove(@id2, @battle.getMove(\"Tackle\"))\n @battle.determi", "end": 146697, "score": 0.6744815707206726, "start": 146694, "tag": "USERNAME", "value": "id2" }, { "context": "spy(move, 'basePower')\n\n @battle.recordMove(@id2, @battle.getMove(\"Splash\"))\n @battle.perform", "end": 148001, "score": 0.585543155670166, "start": 147998, "tag": "USERNAME", "value": "id2" }, { "context": " @battle.beginTurn()\n\n @battle.recordMove(@id2, @battle.getMove(\"Splash\"))\n @battle.perform", "end": 148446, "score": 0.787193775177002, "start": 148443, "tag": "USERNAME", "value": "id2" }, { "context": "= @battle.getMove(moveName)\n poke = { user: @p1, target: @p2 }\n {user, target} = poke\n\n ", "end": 150985, "score": 0.5219874382019043, "start": 150985, "tag": "USERNAME", "value": "" }, { "context": "= @battle.getMove(moveName)\n poke = { user: @p1, target: @p2 }\n {user, target} = poke\n\n ", "end": 151632, "score": 0.9701544642448425, "start": 151629, "tag": "USERNAME", "value": "@p1" }, { "context": "ursuit, 'basePower')\n\n @battle.recordSwitch(@id2, 1)\n @battle.recordMove(@id1, pursuit)\n ", "end": 154728, "score": 0.564913272857666, "start": 154725, "tag": "USERNAME", "value": "id2" }, { "context": "e.recordSwitch(@id2, 1)\n @battle.recordMove(@id1, pursuit)\n @battle.continueTurn()\n spy.", "end": 154762, "score": 0.6864967942237854, "start": 154759, "tag": "USERNAME", "value": "id1" }, { "context": "le.getMove(\"Pursuit\")\n @battle.recordSwitch(@id2, 1)\n @battle.recordMove(@id1, pursuit)\n ", "end": 156339, "score": 0.8794896006584167, "start": 156336, "tag": "USERNAME", "value": "id2" }, { "context": "tle.recordSwitch(@id2, 1)\n @battle.recordMove(@id1, pursuit)\n @battle.continueTurn()\n spy.", "end": 156373, "score": 0.8492792248725891, "start": 156369, "tag": "USERNAME", "value": "@id1" }, { "context": "ttle.getMove(\"Pursuit\")\n @battle.recordSwitch(@id2, 1)\n @battle.recordMove(@id1, pursuit)\n ", "end": 156756, "score": 0.9288075566291809, "start": 156752, "tag": "USERNAME", "value": "@id2" }, { "context": "tle.recordSwitch(@id2, 1)\n @battle.recordMove(@id1, pursuit)\n @battle.continueTurn()\n @bat", "end": 156790, "score": 0.9412793517112732, "start": 156786, "tag": "USERNAME", "value": "@id1" }, { "context": " @battle.continueTurn()\n @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request\n @", "end": 156861, "score": 0.856036365032196, "start": 156857, "tag": "USERNAME", "value": "@id2" }, { "context": "py(pursuit, 'basePower')\n\n @battle.recordMove(@id1, pursuit)\n @battle.recordMove(@id2, @battle.", "end": 157277, "score": 0.9685500264167786, "start": 157273, "tag": "USERNAME", "value": "@id1" }, { "context": "recordMove(@id1, pursuit)\n @battle.recordMove(@id2, @battle.getMove(\"Baton Pass\"))\n @battle.con", "end": 157317, "score": 0.9522197842597961, "start": 157313, "tag": "USERNAME", "value": "@id2" }, { "context": " @battle.continueTurn()\n @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request\n @", "end": 157410, "score": 0.8802362084388733, "start": 157406, "tag": "USERNAME", "value": "@id2" }, { "context": "box.spy(@battle, 'tell')\n\n @battle.recordMove(@id1, pursuit)\n @battle.recordSwitch(@id2, 1)\n ", "end": 157854, "score": 0.8639944195747375, "start": 157850, "tag": "USERNAME", "value": "@id1" }, { "context": "rdMove(@id1, pursuit)\n @battle.recordSwitch(@id2, 1)\n @battle.continueTurn()\n spy.called", "end": 157896, "score": 0.8768215775489807, "start": 157893, "tag": "USERNAME", "value": "id2" }, { "context": "s('recordMove').once()\n\n @battle.recordMove(@id1, pursuit)\n @battle.recordSwitch(@id2, 1)\n ", "end": 158319, "score": 0.758436918258667, "start": 158316, "tag": "USERNAME", "value": "id1" }, { "context": "cordMove(@id1, pursuit)\n @battle.recordSwitch(@id2, 1)\n @battle.continueTurn()\n mock.verif", "end": 158361, "score": 0.874711275100708, "start": 158357, "tag": "USERNAME", "value": "@id2" }, { "context": ").expects('hit').never()\n\n @battle.recordMove(@id1, pursuit)\n @battle.recordSwitch(@id2, 1)\n ", "end": 158661, "score": 0.810063362121582, "start": 158657, "tag": "USERNAME", "value": "@id1" }, { "context": "cordMove(@id1, pursuit)\n @battle.recordSwitch(@id2, 1)\n @battle.continueTurn()\n mock.verif", "end": 158703, "score": 0.8358626961708069, "start": 158699, "tag": "USERNAME", "value": "@id2" }, { "context": "tack: 6, defense: -1)\n\n @battle.performMove(@p1, @battle.getMove('Power Swap'))\n\n @p1.stages", "end": 159072, "score": 0.5849039554595947, "start": 159070, "tag": "USERNAME", "value": "p1" }, { "context": "cts('execute').once()\n @battle.recordMove(@id1, move)\n @battle.continueTurn()\n moc", "end": 185643, "score": 0.6328569650650024, "start": 185640, "tag": "USERNAME", "value": "id1" }, { "context": "ve(vulnerableMove)\n\n @battle.recordMove(@id1, move)\n @battle.recordMove(@id2, vulne", "end": 187884, "score": 0.7862318158149719, "start": 187880, "tag": "USERNAME", "value": "@id1" }, { "context": "', 0) # 100% chance\n\n @battle.recordMove(@id1, skyAttack)\n @battle.continueTurn()\n @p", "end": 189660, "score": 0.5222094058990479, "start": 189659, "tag": "USERNAME", "value": "1" }, { "context": "@battle.getMove(\"Fly\")\n\n @battle.recordMove(@id1, fly)\n @battle.continueTurn()\n\n @p1.has", "end": 212678, "score": 0.7231262922286987, "start": 212675, "tag": "USERNAME", "value": "id1" }, { "context": "ttle.getMove(\"Bounce\")\n\n @battle.recordMove(@id1, bounce)\n @battle.continueTurn()\n\n @p1.", "end": 213035, "score": 0.8239657878875732, "start": 213032, "tag": "USERNAME", "value": "id1" }, { "context": " @battle.beginTurn()\n\n @battle.recordMove(@id2, protect)\n @battle.recordMove(@id1, rampag", "end": 221607, "score": 0.9132949113845825, "start": 221604, "tag": "USERNAME", "value": "id2" }, { "context": "rmMove(@p1, trickRoom)\n\n @battle.recordMove(@id1, splash)\n @battle.recordMove(@id2, splash)\n ", "end": 224799, "score": 0.7485228180885315, "start": 224796, "tag": "USERNAME", "value": "id1" }, { "context": "g).expects('fail').once()\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n mock.v", "end": 232402, "score": 0.8550556302070618, "start": 232398, "tag": "USERNAME", "value": "@id1" }, { "context": "g).expects('fail').once()\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n mock.v", "end": 232722, "score": 0.9295234680175781, "start": 232718, "tag": "USERNAME", "value": "@id1" }, { "context": "g).expects('fail').once()\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n mock.v", "end": 233077, "score": 0.8433585166931152, "start": 233073, "tag": "USERNAME", "value": "@id1" }, { "context": " @battle.getMove(\"Fling\")\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.ha", "end": 233676, "score": 0.8833029270172119, "start": 233672, "tag": "USERNAME", "value": "@id1" }, { "context": " @battle.getMove(\"Fling\")\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.ha", "end": 233975, "score": 0.8702776432037354, "start": 233971, "tag": "USERNAME", "value": "@id1" }, { "context": "battle.getMove(\"Fling\")\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.ha", "end": 234270, "score": 0.8765422105789185, "start": 234267, "tag": "USERNAME", "value": "id1" }, { "context": "battle.getMove(\"Fling\")\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.ha", "end": 234568, "score": 0.9311912059783936, "start": 234565, "tag": "USERNAME", "value": "id1" }, { "context": " @battle.getMove(\"Fling\")\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.ha", "end": 234867, "score": 0.9803071022033691, "start": 234863, "tag": "USERNAME", "value": "@id1" }, { "context": "ttach(Attachment.Torment)\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.ha", "end": 235214, "score": 0.9911773800849915, "start": 235210, "tag": "USERNAME", "value": "@id1" }, { "context": "(attack: 1, accuracy: -2)\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.st", "end": 235564, "score": 0.9888715744018555, "start": 235560, "tag": "USERNAME", "value": "@id1" }, { "context": " @battle.getMove(\"Fling\")\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.ha", "end": 235885, "score": 0.981224000453949, "start": 235881, "tag": "USERNAME", "value": "@id1" }, { "context": " @battle.getMove(\"Fling\")\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.st", "end": 236194, "score": 0.978614866733551, "start": 236190, "tag": "USERNAME", "value": "@id1" }, { "context": "chment.Substitute, hp: 1)\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p2.ha", "end": 236546, "score": 0.8963415026664734, "start": 236542, "tag": "USERNAME", "value": "@id1" }, { "context": " @battle.getMove(\"Fling\")\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n @p1.ha", "end": 236821, "score": 0.949786901473999, "start": 236817, "tag": "USERNAME", "value": "@id1" }, { "context": "g).expects('hit').never()\n @battle.recordMove(@id2, protect)\n @battle.recordMove(@id1, fling)\n ", "end": 237222, "score": 0.920417308807373, "start": 237218, "tag": "USERNAME", "value": "@id2" }, { "context": "recordMove(@id2, protect)\n @battle.recordMove(@id1, fling)\n @battle.continueTurn()\n mock.v", "end": 237262, "score": 0.9332501292228699, "start": 237258, "tag": "USERNAME", "value": "@id1" }, { "context": ",\n team1: [ Factory(\"Magikarp\"), Factory(\"Scyther\"), Factory(\"Celebi\"),\n Factory(\"", "end": 238978, "score": 0.589747965335846, "start": 238971, "tag": "NAME", "value": "Scyther" }, { "context": " Factory(\"Totodile\"), Factory(\"Rayquaza\"), Factory(\"Seedot\") ]\n beatUp = @battle.get", "end": 239057, "score": 0.553105354309082, "start": 239052, "tag": "NAME", "value": "quaza" }, { "context": "shared.create.call this,\n team1: (Factory(\"Magikarp\") for i in [0...2])\n @team1.at(1).fain", "end": 239776, "score": 0.7647154331207275, "start": 239773, "tag": "NAME", "value": "Mag" }, { "context": "d.create.call this,\n team1: (Factory(\"Magikarp\") for i in [0...2])\n @team1.at(1).faint()\n ", "end": 239781, "score": 0.568030834197998, "start": 239778, "tag": "NAME", "value": "arp" }, { "context": ">\n shared.create.call(this, team1: [Factory(\"Magikarp\", ability: \"Technician\")])\n beatUp = @battle", "end": 240112, "score": 0.8071238994598389, "start": 240104, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: [Factory(\"Magikarp\")]\n team2: [Factory(\"Smeargle\")]\n @p2", "end": 263289, "score": 0.6182900071144104, "start": 263281, "tag": "NAME", "value": "Magikarp" }, { "context": "[Factory(\"Smeargle\")]\n team2: [Factory(\"Magikarp\")]\n @p2.types.should.eql ['Water']\n soa", "end": 263619, "score": 0.5300480723381042, "start": 263614, "tag": "NAME", "value": "ikarp" }, { "context": "[Factory(\"Smeargle\")]\n team2: [Factory(\"Magikarp\", ability: \"Swift Swim\")]\n @battle.performMo", "end": 265153, "score": 0.5531525611877441, "start": 265148, "tag": "NAME", "value": "ikarp" }, { "context": "1: [Factory(\"Smeargle\")]\n team2: [Factory(\"Magikarp\", ability: \"Swift Swim\")]\n @battle.performMo", "end": 265814, "score": 0.6891637444496155, "start": 265806, "tag": "NAME", "value": "Magikarp" }, { "context": "shared.create.call this,\n team1: [Factory(\"Magikarp\", ability: \"Swift Swim\")]\n team2: [Factory", "end": 270010, "score": 0.6815109848976135, "start": 270002, "tag": "NAME", "value": "Magikarp" }, { "context": " ability: \"Swift Swim\")]\n team2: [Factory(\"Shedinja\", ability: \"Wonder Guard\")]\n skillSwap = @ba", "end": 270070, "score": 0.7286556363105774, "start": 270062, "tag": "NAME", "value": "Shedinja" }, { "context": "red.create.call this,\n team1: [Factory(\"Magikarp\", ability: \"Swift Swim\")]\n team2: [Factory", "end": 270395, "score": 0.64519202709198, "start": 270390, "tag": "NAME", "value": "ikarp" }, { "context": "shared.create.call this,\n team1: [Factory(\"Magikarp\", ability: \"Swift Swim\")]\n team2: [Factory", "end": 270766, "score": 0.6413283944129944, "start": 270758, "tag": "NAME", "value": "Magikarp" }, { "context": " ability: \"Swift Swim\")]\n team2: [Factory(\"Gyarados\", ability: \"Intimidate\")]\n @battle.performMo", "end": 270826, "score": 0.8439202308654785, "start": 270818, "tag": "NAME", "value": "Gyarados" }, { "context": "d.create.call this,\n team1: [Factory(\"Magikarp\", item: \"Salac Berry\")]\n recycle = @battle.g", "end": 274833, "score": 0.5838298201560974, "start": 274830, "tag": "NAME", "value": "arp" }, { "context": " this,\n team1: [Factory(\"Magikarp\", item: \"Salac Berry\")]\n recycle = @battle.getMove(\"Recycle\")", "end": 274850, "score": 0.7187792658805847, "start": 274843, "tag": "NAME", "value": "Salac B" }, { "context": "@p2, @battle.getMove(\"Covet\"))\n @p1.hasItem(\"Salac Berry\").should.be.false\n @p2.hasItem(\"Salac ", "end": 274982, "score": 0.8510679006576538, "start": 274977, "tag": "NAME", "value": "Salac" }, { "context": "\"Salac Berry\").should.be.false\n @p2.hasItem(\"Salac Berry\").should.be.true\n\n mock = @sandbox.moc", "end": 275031, "score": 0.7885048389434814, "start": 275026, "tag": "NAME", "value": "Salac" }, { "context": " this,\n team1: [Factory(\"Magikarp\", item: \"Salac Berry\")]\n team2: [Factory(\"Magikarp\", item: \"Fig", "end": 275347, "score": 0.7337134480476379, "start": 275336, "tag": "NAME", "value": "Salac Berry" }, { "context": "rry\")]\n team2: [Factory(\"Magikarp\", item: \"Figy Berry\")]\n recycle = @battle.getMove(\"Recycle\")\n ", "end": 275404, "score": 0.8412187695503235, "start": 275394, "tag": "NAME", "value": "Figy Berry" }, { "context": "@p2, @battle.getMove(\"Trick\"))\n @p1.hasItem(\"Figy Berry\").should.be.true\n @battle.performMove(@p2, @", "end": 275557, "score": 0.8931184411048889, "start": 275547, "tag": "NAME", "value": "Figy Berry" }, { "context": "ttle.performMove(@p1, recycle)\n @p1.hasItem(\"Salac Berry\").should.be.true\n\n it \"cannot restore th", "end": 275701, "score": 0.8145901560783386, "start": 275696, "tag": "NAME", "value": "Salac" }, { "context": " this,\n team1: [Factory(\"Magikarp\", item: \"Salac Berry\")]\n recycle = @battle.getMove(\"Recycle\")\n ", "end": 275900, "score": 0.78819340467453, "start": 275889, "tag": "NAME", "value": "Salac Berry" }, { "context": "ttle.performMove(@p1, recycle)\n @p1.hasItem(\"Salac Berry\").should.be.true\n @battle.performMove(@p2, @", "end": 276037, "score": 0.7275843024253845, "start": 276026, "tag": "NAME", "value": "Salac Berry" } ]
test/bw/moves.coffee
sarenji/pokebattle-sim
5
require '../helpers' {Attachment, Status} = require('../../server/bw/attachment') {Battle} = require('../../server/bw/battle') {Pokemon} = require('../../server/bw/pokemon') {Weather} = require('../../shared/weather') {Move} = require('../../server/bw/move') util = require '../../server/bw/util' {Protocol} = require '../../shared/protocol' {Factory} = require '../factory' should = require 'should' {_} = require 'underscore' shared = require '../shared' describe 'Move:', -> # Test every single move for their primary effects. shared.testEveryMove(Battle::MoveList, 'bw') it "multiplies critical hits by 2x", -> Move::criticalMultiplier.should.equal(2) it 'takes the name as the first parameter', -> new Move('Smooth Move').name.should.equal 'Smooth Move' it 'should have a priority of 0 by default', -> new Move().priority.should.equal 0 it 'can change the default priority', -> new Move(null, priority: -1).priority.should.equal -1 it 'should have a type of ??? by default', -> new Move().type.should.equal '???' it 'can change the default type', -> new Move(null, type: 'Grass').type.should.equal 'Grass' describe 'critical hit level', -> it "is 1 by default", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 1 it "can be changed from the default", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.activate() new Move(null, criticalHitLevel: 2) .criticalHitLevel(battle, attacker, defender).should.equal 2 it "is 3 if the attacker has Focus Energy", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.attach(Attachment.FocusEnergy) attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 it "is 3 if the attacker is Farfetch'd with a Stick", -> battle = new Battle('1', []) attacker = new Pokemon(species: "Farfetch'd", item: 'Stick') defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 it "is 3 if the attacker is Chansey with a Lucky Punch", -> battle = new Battle('1', []) attacker = new Pokemon(species: "Chansey", item: 'Lucky Punch') defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 for item in ["Razor Claw", "Scope Lens"] do (item) -> it "is 2 if the attacker has a #{item}", -> battle = new Battle('1', []) attacker = new Pokemon(item: item) defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 2 describe "a critical hit", -> it "occurs when the RNG output < the critical hit level", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() move = new Move() @sandbox.stub(move, 'criticalHitLevel', -> 3) @sandbox.stub(battle.rng, 'next', -> 0.2) move.isCriticalHit(battle, attacker, defender).should.be.true it "does not occur when the RNG output >= the critical hit level", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() @sandbox.stub(battle.rng, 'next', -> 0.0700) new Move().isCriticalHit(battle, attacker, defender).should.be.false it "ignores opponent defensive boosts", -> shared.create.call(this) defense = @p2.stat('defense') specialDefense = @p2.stat('specialDefense') @p1.crit = true @p2.boost(defense: 1, specialDefense: 2) move = new Move(null, damage: 'physical') move.pickDefenseStat(@p1, @p2).should.equal(defense) move = new Move(null, damage: 'special') move.pickDefenseStat(@p1, @p2).should.equal(specialDefense) it "does not ignore opponent defensive drops", -> shared.create.call(this) defense = @p2.stat('defense') specialDefense = @p2.stat('specialDefense') @p1.crit = true @p2.boost(defense: -1, specialDefense: -2) move = new Move(null, damage: 'physical') move.pickDefenseStat(@p1, @p2).should.equal Math.floor(2 / 3 * defense) move = new Move(null, damage: 'special') move.pickDefenseStat(@p1, @p2).should.equal(specialDefense >> 1) it "ignores user stat drops", -> shared.create.call(this) attack = @p1.stat('attack') specialAttack = @p1.stat('specialAttack') @p1.crit = true @p1.boost(attack: -1, specialAttack: -2) move = new Move(null, damage: 'physical') move.pickAttackStat(@p1, @p2).should.equal(attack) move = new Move(null, damage: 'special') move.pickAttackStat(@p1, @p2).should.equal(specialAttack) it "does not ignore user stat boosts", -> shared.create.call(this) attack = @p1.stat('attack') specialAttack = @p1.stat('specialAttack') @p1.crit = true @p1.boost(attack: 1, specialAttack: 2) move = new Move(null, damage: 'physical') move.pickAttackStat(@p1, @p2).should.equal Math.floor(1.5 * attack) move = new Move(null, damage: 'special') move.pickAttackStat(@p1, @p2).should.equal(2 * specialAttack) it "does not carry over in multihit moves", -> shared.create.call(this) move = new Move("multihit", minHits: 4, maxHits: 4, power: 20) # Crit only once move.isCriticalHit = -> move.isCriticalHit = -> false true mock = @sandbox.mock(@p2).expects('informCriticalHit').once() move.execute(@battle, @p1, [ @p2 ]) mock.verify() describe "-1 crit ratios", -> beforeEach -> @battle = new Battle('1', []) @attacker = new Pokemon() @move = new Move("TestMove", criticalHitLevel: -1) @sandbox.stub(@battle.rng, 'next', -> 1) it "fails if the defender has Battle Armor", -> defender = new Pokemon(ability: 'Battle Armor') @move.isCriticalHit(@battle, @attacker, defender).should.be.false it "fails if the defender has Shell Armor", -> defender = new Pokemon(ability: 'Shell Armor') @move.isCriticalHit(@battle, @attacker, defender).should.be.false it "always succeeds if opponent does not have Battle or Shell Armor", -> defender = new Pokemon() @move.isCriticalHit(@battle, @attacker, defender).should.be.true describe 'type effectiveness', -> testTypeEffectiveness = (type, defense, expected) -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() defender.types = defense move = new Move(null, type: type) move.typeEffectiveness(battle, attacker, defender).should.equal expected it 'is 0 if the enemy has an immunity to the type', -> testTypeEffectiveness('Ground', ['Electric', 'Flying'], 0) it 'is 1 if the enemy is neutral to the type', -> testTypeEffectiveness('Ground', ['Normal'], 1) it 'is 2 if the enemy is weak to the type', -> testTypeEffectiveness('Ground', ['Electric'], 2) it 'is 4 if the enemy is extra weak to the type', -> testTypeEffectiveness('Rock', ['Fire', 'Flying'], 4) it 'is 1/2 if the enemy is resistant to the type', -> testTypeEffectiveness('Fire', ['Fire', 'Flying'], .5) it 'is 1/4 if the enemy is extra resistant to the type', -> testTypeEffectiveness('Fire', ['Fire', 'Water'], .25) describe "#burnCalculation", -> it "returns 1 normally", -> attacker = new Pokemon() new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal 1 it "returns .5 with a physical move, no Guts ability, and a burned user", -> attacker = new Pokemon() attacker.attach(Status.Burn) new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal .5 it "returns 1 with a special move, no Guts ability, and a burned user", -> attacker = new Pokemon() attacker.attach(Status.Burn) new Move(null, damage: 'special') .burnCalculation(attacker).should.equal 1 it "returns 1 with a physical move, Guts ability, and a burned user", -> attacker = new Pokemon(ability: "Guts") attacker.attach(Status.Burn) new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal 1 describe 'an attack with 0 accuracy', -> it 'can never miss', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(accuracy: 0).willMiss(battle, a, d).should.be.false describe 'accuracy and evasion boosts', -> it 'heighten and lower the chances of a move hitting', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(null, accuracy: 100).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = 3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = 3 d.stages.evasion = 3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 50 it 'keeps heightening and lowering chances when negative', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(null, accuracy: 100).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = -3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 25 a.stages.accuracy = -3 d.stages.evasion = -3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 50 describe '#hasFlag', -> it 'returns true if a move has a specific flag', -> new Move(null, flags: ['superman', 'batman']) .hasFlag('batman').should.be.true it "returns false if a move doesn't have a specific flag", -> new Move(null, flags: ['superman', 'batman']) .hasFlag('catwoman').should.be.false describe '#execute', -> it 'calls hit multiple times for multihit moves', -> shared.create.call(this) move = new Move("multihit", minHits: 4, maxHits: 4) mock = @sandbox.mock(move).expects('hit').exactly(4) move.execute(@battle, @p1, [@p2]) mock.verify() it 'only hits up until user faints', -> shared.create.call(this, team2: [Factory('Ferrothorn', ability: 'Iron Barbs')]) move = new Move("multihit", minHits: 4, maxHits: 4, flags: ["contact"]) mock = @sandbox.mock(move).expects('hit').exactly(1) @p1.currentHP = 1 move.execute(@battle, @p1, [@p2]) mock.verify() it 'only hits up until user falls asleep', -> shared.create.call(this, team2: [Factory('Shroomish', ability: 'Effect Spore')]) shared.biasRNG.call(this, "randInt", 'effect spore', 4) # Never trigger move = new Move("multihit", minHits: 4, maxHits: 4, flags: ["contact"]) hit = move.hit times = 0 @sandbox.stub move, 'hit', => times++ if times == 2 shared.biasRNG.call(this, "randInt", 'effect spore', 1) # Sleep else shared.biasRNG.call(this, "randInt", 'effect spore', 4) # Nothing hit.apply(move, arguments) @p1.currentHP = 1 move.execute(@battle, @p1, [@p2]) times.should.equal(2) describe "#use", -> it "returns false if the target's type is immune", -> shared.create.call(this) move = new Move("attacking", damage: "special", type: "Normal") @p2.types = [ "Ghost" ] move.use(@battle, @p1, @p2).should.be.false it "returns true if target is immune but move is non-damaging", -> shared.create.call(this) move = new Move("attacking", damage: "non-damaging", type: "Normal") @p2.types = [ "Ghost" ] should.not.exist move.use(@battle, @p1, @p2) describe '#hit', -> it "deals damage no higher than the pokemon's remaining HP", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Tackle")) @p2.currentHP.should.equal(0) it "deals normal damage if the Pokemon has a substitute", -> shared.create.call(this) spy = @sandbox.spy(@p2, 'damage') @p2.currentHP = (@p2.currentHP >> 2) + 1 @battle.performMove(@p2, @battle.getMove("Substitute")) @battle.performMove(@p1, @battle.getMove("Tackle")) spy.returned(1).should.be.false describe '#weatherModifier', -> it "is 0x1800 when the move is Fire-type and the weather is sunny", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1800) it "is 0x800 when the move is Fire-type and the weather is rainy", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x800) it "is 0x1800 when the move is Water-type and the weather is rainy", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = new Move(null, type: "Water") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1800) it "is 0x1800 when the move is Water-type and the weather is sunny", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = new Move(null, type: "Water") move.weatherModifier(@battle, @p1, @p2).should.equal(0x800) it "is 0x1000 otherwise", -> shared.create.call(this) @battle.setWeather(Weather.SAND) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1000) describe "#baseDamage", -> it "reduces damage by ~1.5 if the weather is sandstorm", -> shared.create.call(this) @p2.types = [ "Rock" ] move = new Move(null, power: 50, type: "Fire", damage: 'special') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.be.lessThan(damage) it "doesn't apply the sandstorm effect if target isn't Rock-type", -> shared.create.call(this) @p2.types = [ "Ground" ] move = new Move(null, power: 50, type: "Fire", damage: 'special') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.equal(damage) it "doesn't apply the sandstorm effect if move is non-special", -> shared.create.call(this) @p2.types = [ "Rock" ] move = new Move(null, power: 50, type: "Fire", damage: 'physical') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.equal(damage) describe "BW Moves:", -> describe "Splash", -> shared.shouldDoNoDamage('Splash') describe 'a multi-hit move', -> it 'potentially activates Berries after each hit', -> shared.create.call this, team1: [Factory('Magikarp', item: "Sitrus Berry", ability: "Skill Link")] team2: [Factory('Magikarp', item: "Sitrus Berry", ability: "Iron Barbs")] hp = @p1.currentHP @p1.currentHP = (hp >> 1) + 1 @p2.currentHP = 4 move = @battle.getMove('Tail Slap') @sandbox.stub(move, 'calculateDamage', -> 1) @battle.performMove(@p1, move) @p1.currentHP.should.equal (hp >> 1) + 1 - (5 * (hp >> 3)) + (hp >> 2) @p2.currentHP.should.equal 4 + (hp >> 2) - 5 describe 'jump kick attacks', -> it 'has 50% recoil if it misses', -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'miss', 100) oldHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Hi Jump Kick')) (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) it "has 50% recoil if the target is immune", -> shared.create.call(this, team2: [Factory("Gengar")]) oldHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Hi Jump Kick')) (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) it "has 50% recoil if the target protects itself", -> shared.create.call(this) oldHP = @p1.stat('hp') @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove("Hi Jump Kick")) @battle.continueTurn() (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) describe 'a drain attack', -> it 'recovers a percentage of the damage dealt, rounded down', -> shared.create.call this, team1: [Factory('Conkeldurr')] team2: [Factory('Hitmonchan')] startHP = 1 @p1.currentHP = startHP hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Drain Punch')) damage = (hp - @p2.currentHP) (@p1.currentHP - startHP).should.equal Math.ceil(damage / 2) it 'cannot recover to over 100% HP', -> shared.create.call this, team1: [Factory('Conkeldurr')] team2: [Factory('Hitmonchan')] hp = @p1.currentHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Drain Punch')) (@p1.currentHP - hp).should.equal 0 it "does not recover more than the damage dealt", -> shared.create.call(this) drainPunch = @battle.getMove('Drain Punch') @sandbox.stub(drainPunch, 'baseDamage', -> 9999) @p2.currentHP = 2 @p1.currentHP = 1 @battle.performMove(@p1, drainPunch) @p2.currentHP.should.be.lessThan(1) @p1.currentHP.should.equal(2) describe 'weight-based attacks', -> it 'has 80 base power if the pokemon is 50.2kg', -> shared.create.call this, team1: [Factory('Celebi')] team2: [Factory('Hitmonchan')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Grass Knot')) (hp - @p2.currentHP).should.equal 94 it 'has 120 base power if the pokemon is >200kg', -> shared.create.call this, team1: [Factory('Celebi')] team2: [Factory('Gyarados')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Grass Knot')) (hp - @p2.currentHP).should.equal 153 describe 'a pokemon using a primary boosting move', -> it "doesn't do damage if base power is 0", -> shared.create.call this, team1: [Factory('Gyarados')] team2: [Factory('Hitmonchan')] @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @p2.currentHP.should.equal @p2.stat('hp') it "boosts the pokemon's stats", -> shared.create.call this, team1: [Factory('Gyarados')] team2: [Factory('Hitmonchan')] @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @p1.stages.should.containEql attack: 1, speed: 1 it "affects type-immune pokemon", -> shared.create.call this, team1: [Factory('Audino')] team2: [Factory('Gengar')] @battle.performMove(@p1, @battle.getMove('Growl')) @p2.stages.attack.should.equal -1 it "has the boosts removed on switch", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @battle.performSwitch(@p1, 1) @p1.stages.should.containEql(attack: 0, speed: 0) describe 'a pokemon using a damaging move that also boosts stats on hit', -> it "deals damage and boosts stats", -> shared.create.call this, team1: [Factory('Celebi')] team2: [Factory('Gyarados')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Leaf Storm')) @p1.stages.specialAttack.should.equal -2 (hp - @p2.currentHP).should.equal 178 describe 'Low Sweep', -> it "lowers the target's speed by 1", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.equal(-1) it "does not lower the target's speed by 1 if the target faints", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.not.equal(-1) it "does not lower the target's speed by 1 if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute) @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.not.equal(-1) describe 'Flame Charge', -> it "raises the user's speed by 1", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) it "raises the user's speed by 1 even if the target faints", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) it "raises the user's speed by 1 even if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute) @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) describe 'a pokemon using a move with a secondary boosting effect', -> it "has a chance to activate", -> shared.create.call this, team1: [Factory('Mew')] team2: [Factory('Hitmonchan')] shared.biasRNG.call(this, "next", 'secondary boost', 0) # 100% chance attack = @p1.stat('attack') speed = @p1.stat('speed') @battle.performMove(@p1, @battle.getMove('AncientPower')) @p1.stages.should.containEql { attack: 1, defense: 1, speed: 1, specialAttack: 1, specialDefense: 1 } describe 'a pokemon using Acrobatics', -> it 'gets double the base power without an item', -> shared.create.call this, team1: [Factory('Gliscor')] team2: [Factory('Regirock')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Acrobatics')) damage = (hp - @p2.currentHP) damage.should.equal 36 it 'has normal base power with an item', -> shared.create.call this, team1: [Factory('Gliscor', item: 'Leftovers')] team2: [Factory('Regirock')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Acrobatics')) damage = (hp - @p2.currentHP) damage.should.equal 18 testRecoilMove = (moveName) -> describe "a pokemon using #{moveName}", -> it 'receives a percentage of the damage rounded half up', -> shared.create.call(this) startHP = @p1.currentHP hp = @p2.currentHP move = @battle.getMove(moveName) @battle.performMove(@p1, move) recoil = -move.recoil / 100 damage = (hp - @p2.currentHP) (startHP - @p1.currentHP).should.equal Math.round(damage * recoil) it 'receives a minimum of 1 HP of recoil', -> shared.create.call(this) startHP = @p1.currentHP hp = @p2.currentHP move = @battle.getMove(moveName) stub = @sandbox.stub(move, 'calculateDamage', -> .6) move = @battle.getMove(moveName) @battle.performMove(@p1, move) damage = (hp - @p2.currentHP) (startHP - @p1.currentHP).should.equal 1 it "does not recoil if no damage was dealt", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove(moveName)) @battle.continueTurn() @p1.currentHP.should.equal(@p1.stat('hp')) testRecoilMove("Brave Bird") testRecoilMove("Double-Edge") testRecoilMove("Flare Blitz") testRecoilMove("Head Charge") testRecoilMove("Head Smash") testRecoilMove("Submission") testRecoilMove("Take Down") testRecoilMove("Volt Tackle") testRecoilMove("Wild Charge") testRecoilMove("Wood Hammer") testDrainMove = (moveName) -> describe moveName, -> it "absorbs a percentage of the damage rounded up", -> shared.create.call(this) @p1.currentHP = 1 move = @battle.getMove(moveName) @battle.performMove(@p1, move) drain = move.recoil / 100 damage = (@p2.stat('hp') - @p2.currentHP) (@p1.currentHP - 1).should.equal Math.ceil(damage * drain) it 'receives a minimum of 1 HP of drain', -> shared.create.call(this) @p1.currentHP = @p2.currentHP = 1 move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p1.currentHP.should.equal(2) it "does not drain if no damage was dealt", -> shared.create.call(this) @p1.currentHP = 1 @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove(moveName)) @battle.continueTurn() @p1.currentHP.should.equal(1) testDrainMove("Absorb") testDrainMove("Drain Punch") testDrainMove("Giga Drain") testDrainMove("Horn Leech") testDrainMove("Leech Life") testDrainMove("Mega Drain") describe 'Haze', -> shared.shouldDoNoDamage('Haze') it 'removes all status boosts from each pokemon', -> shared.create.call(this) # Create artificial boosts. @p1.stages.attack = 2 @p1.stages.evasion = -1 @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Haze")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p1.stages.should.eql neutralBoosts @p2.stages.should.eql neutralBoosts describe 'Seismic Toss and Night Shade', -> it 'does exactly the same damage as their level', -> shared.create.call this, team1: [Factory('Blissey')] team2: [Factory('Mew')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Seismic Toss')) (hp - @p2.currentHP).should.equal 100 it 'triggers Focus Sash', -> shared.create.call this, team1: [Factory('Blissey')] team2: [Factory('Mew', level: 1, item: "Focus Sash")] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Seismic Toss')) @p2.currentHP.should.equal(1) describe 'Psywave', -> it 'does user.level/2 damage minimum', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] shared.biasRNG.call(this, "randInt", 'psywave', 5) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 50 it 'does user.level * 1.5 damage maximum', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] move = @battle.getMove('Psywave') shared.biasRNG.call(this, "randInt", 'psywave', 15) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 150 it 'rounds down to the nearest .1 multiplier', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] move = @battle.getMove('Psywave') shared.biasRNG.call(this, "randInt", 'psywave', 6.09) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 60 describe 'facade', -> it 'doubles the base power if burned, poisoned, or paralyzed', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('Magikarp')] hp = @p2.currentHP @p1.attach(Status.Paralyze) move = @battle.getMove('Facade') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) describe 'reversal and flail', -> it 'have 200 base power at 1 hp', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('Magikarp')] @p1.currentHP = 1 move = @battle.getMove('Flail') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal 200 it 'have 40 base power at 50% hp', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('Magikarp')] @p1.currentHP = Math.floor(@p1.stat('hp') / 2) move = @battle.getMove('Flail') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal 40 describe 'eruption and water spout', -> beforeEach -> shared.create.call this, team1: [Factory('Camerupt')] team2: [Factory('Mew')] @attacker = @p1 @defender = @p2 @move = @battle.getMove('Eruption') it 'has at least one base power', -> @attacker.currentHP = 1 @move.basePower(@battle, @attacker, @defender).should.equal 1 it 'has 75 base power at 50% hp', -> @attacker.currentHP = @attacker.stat('hp') / 2 @move.basePower(@battle, @attacker, @defender).should.equal 75 it 'has 150 base power at 100% hp', -> @move.basePower(@battle, @attacker, @defender).should.equal 150 describe 'gyro ball', -> it 'has 150 base power maximum', -> shared.create.call this, team1: [Factory('Forretress', ivs: {speed: 0})] team2: [Factory('Jolteon', evs: {speed: 252}, nature: "Timid")] move = @battle.getMove('Gyro Ball') attacker = @p1 defender = @p2 attacker.stages.speed = -6 move.basePower(@battle, attacker, defender).should.equal 150 it 'has variable base power based on speed of target and user', -> shared.create.call this, team1: [Factory('Electrode', evs: {speed: 252}, nature: "Jolly")] team2: [Factory('Magikarp', ivs: {speed: 0})] move = @battle.getMove('Gyro Ball') attacker = @p1 defender = @p2 attacker.stages.speed = -6 move.basePower(@battle, attacker, defender).should.equal 40 describe 'brine', -> it 'has normal base power if the target has over 50% HP', -> shared.create.call this, team1: [Factory('Empoleon')] team2: [Factory('Magikarp')] move = @battle.getMove('Brine') @p2.currentHP = Math.floor(@p2.currentHP / 2) + 1 move.basePower(@battle, @p1, @p2).should.equal 65 it 'doubles base power if the target has 50% or less HP', -> shared.create.call this, team1: [Factory('Empoleon')] team2: [Factory('Magikarp')] move = @battle.getMove('Brine') @p2.currentHP = Math.floor(@p2.currentHP / 2) move.basePower(@battle, @p1, @p2).should.equal 130 describe 'Disable', -> shared.shouldDoNoDamage('Disable') it 'gives the disabled attachment', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @p2.has(Attachment.Disable).should.be.true it "prevents the target's last move from being selected", -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @battle.beginTurn() @p2.validMoves().should.not.containEql(move) @p2.validMoves().should.have.length(@p2.moves.length - 1) it 'wears off after 4 turns', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @battle.endTurn() @battle.endTurn() @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Disable).should.be.false it 'stops the execution of a disabled move', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) mock = @sandbox.mock(move).expects('execute').never() @battle.performMove(@p2, move) mock.verify() it 'fails if the target has not moved since it was active', -> shared.create.call(this) disable = @battle.getMove("Disable") mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p1, disable) mock.verify() it 'fails if the target does not know the move it used', -> shared.create.call(this) disable = @battle.getMove("Disable") struggle = @battle.getMove("Struggle") mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p2, struggle) @battle.performMove(@p1, disable) mock.verify() it "fails if the target's last move has 0 PP", -> shared.create.call(this) disable = @battle.getMove("Disable") splash = @battle.getMove("Splash") @battle.performMove(@p2, splash) @p2.setPP(splash, 0) mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p1, disable) mock.verify() describe 'hidden power', -> it 'has a max power of 70', -> ivs = { hp: 31, attack: 31, defense: 31, specialAttack: 31, specialDefense: 31, speed: 31 } shared.create.call this, team1: [Factory('Magikarp', ivs: ivs)] team2: [Factory('Magikarp')] move = @battle.getMove('Hidden Power') move.basePower(@battle, @p1, @p2).should.eql 70 it 'has a min power of 30', -> ivs = { hp: 0, attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0 } shared.create.call this, team1: [Factory('Magikarp', ivs: ivs)] team2: [Factory('Magikarp')] move = @battle.getMove('Hidden Power') move.basePower(@battle, @p1, @p2).should.eql 30 it 'is dark when all ivs are 31', -> ivs = { hp: 31, attack: 31, defense: 31, specialAttack: 31, specialDefense: 31, speed: 31 } shared.create.call this, team1: [Factory('Magikarp', ivs: ivs)] team2: [Factory('Magikarp')] move = @battle.getMove('Hidden Power') move.getType(@battle, @p1, @p2).should.eql 'Dark' it 'is fighting when all ivs are 0', -> ivs = { hp: 0, attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0 } shared.create.call this, team1: [Factory('Magikarp', ivs: ivs)] team2: [Factory('Magikarp')] move = @battle.getMove('Hidden Power') move.getType(@battle, @p1, @p2).should.eql 'Fighting' describe 'yawn', -> shared.shouldDoNoDamage('Yawn') shared.shouldFailIfUsedTwice("Yawn") it 'gives the yawn attachment', -> shared.create.call this, team1: [Factory('Camerupt')] team2: [Factory('Magikarp')] @battle.performMove(@p1, @battle.getMove('Yawn')) @p2.has(Attachment.Yawn).should.be.true it 'puts the opponent to sleep at the end of the second turn', -> shared.create.call this, team1: [Factory('Camerupt')] team2: [Factory('Magikarp')] @battle.performMove(@p1, @battle.getMove('Yawn')) @battle.endTurn() @p2.has(Status.Sleep).should.be.false @battle.endTurn() @p2.has(Status.Sleep).should.be.true it "fails if the target already is statused", -> shared.create.call(this) yawn = @battle.getMove('Yawn') mock = @sandbox.mock(yawn).expects('fail').once() @p2.attach(Status.Paralyze) @battle.performMove(@p1, yawn) mock.verify() describe 'an OHKO move', -> it 'ignores accuracy/evasion modifiers', -> shared.create.call(this) @p1.stages.accuracy = -6 @p2.stages.evasion = 6 acc = @battle.getMove('Sheer Cold').chanceToHit(@battle, @p1, @p2) acc.should.equal 30 it "does damage equal to the target's total hp", -> shared.create.call this, team1: [Factory('Lapras')] team2: [Factory('Magikarp')] @p2.currentHP = Math.floor(@p2.stat('hp') / 2) @controller.makeMove(@id1, 'Sheer Cold') @controller.makeMove(@id2, 'Splash') move = @battle.getMove('Sheer Cold') damage = move.calculateDamage(@battle, @p1, @p2) damage.should.equal @p2.stat('hp') describe 'a recovery move', -> shared.shouldDoNoDamage('Recover') it "recovers 50% of the target's HP, rounded half up", -> shared.create.call(this) hp = @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Softboiled')) recoverHP = Math.round(@p1.stat('hp') / 2) (@p1.currentHP - hp).should.equal recoverHP it "fails if the user's HP is full", -> shared.create.call(this) softboiled = @battle.getMove('Softboiled') mock = @sandbox.mock(softboiled).expects('fail').once() @battle.performMove(@p1, softboiled) mock.verify() describe 'Knock Off', -> it "deals damage", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.currentHP.should.be.lessThan @p2.stat('hp') it "removes the target's item", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) should.not.exist @p2.item it "does not remove unremovable items", -> shared.create.call this, team2: [Factory('Magikarp', item: "Air Mail")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "does not knock off items from pokemon with Sticky Hold", -> shared.create.call this, team2: [Factory('Magikarp', ability: "Sticky Hold", item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "takes damage from Rocky Helmet", -> shared.create.call this, team2: [Factory('Magikarp', item: "Rocky Helmet")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.false @p1.currentHP.should.be.lessThan(@p1.stat('hp')) it "doesn't knock off if substitute fades", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "doesn't knock off if user is fainted", -> shared.create.call this, team2: [Factory('Magikarp', item: "Rocky Helmet")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true @p1.isFainted().should.be.true it 'removes healing Berries before they can activate', -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Sitrus Berry")] @p2.currentHP = 2 move = @battle.getMove('Knock Off') @sandbox.stub(move, 'calculateDamage', -> 1) @battle.performMove(@p1, move) @p2.currentHP.should.equal 1 describe 'trick and switcheroo', -> shared.shouldDoNoDamage('Trick') it "isn't affected by type-immunities", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Stick')] team2: [Factory('Drapion', item: "Leftovers")] item1 = @p1.item item2 = @p2.item trick = @battle.getMove('Trick') @battle.performMove(@p1, trick) @p2.item.should.equal item1 @p1.item.should.equal item2 it "swaps the target and user's item", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Stick')] team2: [Factory('Magikarp', item: "Leftovers")] item1 = @p1.item item2 = @p2.item @controller.makeMove(@id1, 'Trick') @controller.makeMove(@id2, 'Splash') @p2.item.should.equal item1 @p1.item.should.equal item2 it "fails if the user has Sticky Hold", -> shared.create.call this, team1: [Factory('Alakazam', ability: "Sticky Hold", item: 'Stick')] team2: [Factory('Gastrodon', item: "Leftovers")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has Sticky Hold", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Stick')] team2: [Factory('Magikarp', ability: "Sticky Hold", item: "Leftovers")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "succeeds if only one pokemon has an item", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Stick')] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') item1 = @p1.item @battle.performMove(@p1, trick) should.not.exist(@p1.item) @p2.item.should.equal(item1) it "fails if neither the user nor the target has an item", -> shared.create.call this, team1: [Factory('Alakazam')] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is holding a Mail", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Air Mail')] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is holding a Mail", -> shared.create.call this, team1: [Factory('Alakazam')] team2: [Factory('Magikarp', item: 'Air Mail')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is Giratina-O", -> shared.create.call this, team1: [Factory('Giratina', forme: "origin")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is Giratina-O", -> shared.create.call this, team2: [Factory('Giratina', forme: "origin")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has a Substitute", -> shared.create.call(this) trick = @battle.getMove('Trick') substitute = @battle.getMove('Substitute') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p2, substitute) @battle.performMove(@p1, trick) mock.verify() it "fails if the user has Multitype with a plate item", -> shared.create.call this, team1: [Factory('Magikarp', ability: "Multitype", item: "Grass Plate")] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has Multitype with a plate item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', ability: "Multitype", item: "Grass Plate")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is Genesect with a Drive item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Genesect', item: "Burn Drive")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is Genesect with a Drive item", -> shared.create.call this, team1: [Factory('Genesect', item: "Burn Drive")] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() describe 'memento', -> shared.shouldDoNoDamage('Memento') it "faints the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Memento")) @p1.isFainted().should.be.true it "reduces the attack and special attack of the target by two stages", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.containEql attack: -2, specialAttack: -2 it "doesn't reduce stats if target is protected, and doesn't faint user", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove("Memento")) @battle.continueTurn() @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.false it "doesn't reduce stats if target has a substitute, and doesn't faint user", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Substitute")) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.false it "doesn't reduce stats if target has Clear Body, but faints user", -> shared.create.call(this, team2: [Factory('Magikarp', ability: 'Clear Body')]) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.true describe 'magnitude', -> it "has variable base power", -> shared.create.call this, team1: [Factory('Dugtrio')] team2: [Factory('Magikarp')] move = @battle.getMove('Magnitude') shared.biasRNG.call(this, "randInt", 'magnitude', 50) move.basePower(@battle, @p1, @p2).should.equal 70 describe 'Pain Split', -> it "doesn't make a pokemon's HP go over their max", -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @controller.makeMove(@id1, 'Pain Split') @controller.makeMove(@id1, 'Seismic Toss') @p1.currentHP.should.equal @p1.stat('hp') it "averages user and target current HP", -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @p1.currentHP = 2 @controller.makeMove(@id1, 'Pain Split') @controller.makeMove(@id2, 'Seismic Toss') @p1.currentHP.should.equal Math.min(326, @p1.stat('hp')) @p2.currentHP.should.equal Math.min(326, @p2.stat('hp')) it "affects Ghosts", -> shared.create.call this, team2: [Factory('Gengar')] painSplit = @battle.getMove("Pain Split") mock = @sandbox.mock(painSplit).expects('hit').once() @battle.performMove(@p1, painSplit) mock.verify() it "is blocked by Protect", -> shared.create.call(this) @p1.currentHP = 1 painSplit = @battle.getMove("Pain Split") mock = @sandbox.mock(painSplit).expects('hit').never() @battle.recordMove(@id1, painSplit) @battle.determineTurnOrder() @battle.performMove(@p2, @battle.getMove("Protect")) @battle.performMove(@p1, painSplit) mock.verify() @p1.currentHP.should.equal(1) @p2.currentHP.should.equal(@p2.stat('hp')) describe 'Belly Drum', -> shared.shouldDoNoDamage('Belly Drum') it "maximizes attack", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @p1.stages.attack = -6 @controller.makeMove(@id1, 'Belly Drum') @controller.makeMove(@id2, 'Splash') @p1.stages.attack.should.equal 6 it "cuts the pokemon's HP by half", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @controller.makeMove(@id1, 'Belly Drum') @controller.makeMove(@id2, 'Splash') hp = @p1.stat('hp') (hp - @p1.currentHP).should.equal Math.floor(hp / 2) it "fails if the pokemon's HP is less than half", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] hp = @p1.currentHP = Math.floor(@p1.stat('hp') / 2) - 1 @controller.makeMove(@id1, 'Belly Drum') @controller.makeMove(@id2, 'Splash') @p1.currentHP.should.equal hp @p1.stages.attack.should.equal 0 it "fails if the pokemon's attack is already maximized", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @p1.boost(attack: 12) bd = @battle.getMove('Belly Drum') mock = @sandbox.mock(bd).expects('fail').once() @battle.performMove(@p1, bd) mock.verify() @p1.currentHP.should.equal(@p1.stat('hp')) describe 'acupressure', -> shared.shouldDoNoDamage('Acupressure') it "raises a random stat that can be raised", -> shared.create.call this, team1: [Factory('Shuckle')] team2: [Factory('Magikarp')] stages = _.clone(@p1.stages) @controller.makeMove(@id1, 'Acupressure') @controller.makeMove(@id2, 'Splash') @p1.stages.should.not.eql stages it "fails if the Pokemon has maximum stats", -> shared.create.call this, team1: [Factory('Shuckle')] team2: [Factory('Magikarp')] @p1.stages.attack = 6 @p1.stages.defense = 6 @p1.stages.specialAttack = 6 @p1.stages.specialDefense = 6 @p1.stages.accuracy = 6 @p1.stages.evasion = 6 mock = @sandbox.mock(@p2) mock.expects('boost').never() @controller.makeMove(@id1, 'Acupressure') @controller.makeMove(@id2, 'Splash') mock.verify() describe 'Dragon Rage', -> it 'always does 40 damage', -> shared.create.call(this) move = @battle.getMove('Dragon Rage') move.calculateDamage(@battle, @p1, @p2).should.equal 40 describe 'SonicBoom', -> it 'always does 20 damage', -> shared.create.call(this) sonicBoom = @battle.getMove('SonicBoom') sonicBoom.calculateDamage(@battle, @p1, @p2).should.equal 20 describe 'explosion moves', -> it 'faints the user', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @battle.performMove(@p1, @battle.getMove('Explosion')) @p1.isFainted().should.be.true it 'faints the user even if enemy is immune', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Gengar')] @battle.performMove(@p1, @battle.getMove('Explosion')) @p1.isFainted().should.be.true it 'fails if an active Pokemon has Damp', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Politoed', ability: 'Damp')] explosion = @battle.getMove('Explosion') mock = @sandbox.mock(explosion).expects('fail').once() @battle.performMove(@p1, explosion) mock.verify() describe 'endeavor', -> it "brings the target's hp down to the user's hp", -> shared.create.call(this) hp = 4 @p1.currentHP = hp @battle.performMove(@p1, @battle.getMove('Endeavor')) @p2.currentHP.should.equal hp it "fails if the target's hp is less than the user's hp", -> shared.create.call(this) move = @battle.getMove('Endeavor') mock = @sandbox.mock(move).expects('fail').once() @p2.currentHP = hp = 4 @battle.performMove(@p1, move) mock.verify() it "doesn't hit ghost pokemon", -> shared.create.call this, team1: [Factory('Politoed')] team2: [Factory('Gengar')] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Endeavor')) @p2.currentHP.should.equal @p2.stat('hp') describe 'a thief move', -> it "should steal the target's item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.item.should.equal item2 should.not.exist @p2.item it "should not steal the target's item if it has none", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp')] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item should.not.exist @p2.item it "should not steal the target's item if user already has an item", -> shared.create.call this, team1: [Factory('Magikarp', item: "Stick")] team2: [Factory('Magikarp', item: "Leftovers")] item1 = @p1.item item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.item.should.equal item1 @p2.item.should.equal item2 it "should not steal the target's item if target has Sticky Hold", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers", ability: "Sticky Hold")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal target's item if target has Multitype and a plate", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Draco Plate", ability: "Multitype")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if the target has no item", -> shared.create.call(this) item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.hasItem().should.be.false @p2.hasItem().should.be.false it "should not steal the target's item if target is Giratina-O", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Giratina', forme: "origin", item: "Griseous Orb")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if target is Genesect with Drive", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Genesect', item: "Burn Drive")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if target holds Mail", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Air Mail")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if user is fainted", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers", ability: "Iron Barbs")] item2 = @p2.item @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 describe 'crush grip', -> it 'has a base power of 1 minimum', -> shared.create.call(this) move = @battle.getMove('Crush Grip') @p2.currentHP = 1 move.basePower(@battle, @p1, @p2).should.equal 1 it 'has a base power of 121 maximum', -> shared.create.call(this) move = @battle.getMove('Crush Grip') @p2.currentHP = @p2.stat('hp') move.basePower(@battle, @p1, @p2).should.equal 121 describe 'hex', -> it 'doubles the base power if target is burned, poisoned, or paralyzed', -> shared.create.call(this) move = @battle.getMove('Hex') @p2.attach(Status.Paralyze) move.basePower(@battle, @p1, @p2).should.equal 100 describe 'heavy slam and heat crash', -> it 'has variable base power based on the difference in weight', -> shared.create.call(this) move = @battle.getMove('Heavy Slam') move.basePower(@battle, @p1, @p2).should.equal 40 move.basePower(@battle, @p1, calculateWeight: -> -1000).should.equal 120 describe 'a status cure move', -> it 'heals the entire team of status effects', -> shared.create.call this, team1: [Factory('Magikarp'), Factory('Magikarp'), Factory('Magikarp')] shared.biasRNG.call(this, 'next', 'paralyze chance', 1) # never pars @team1.pokemon.forEach((pokemon) -> pokemon.attach(Status.Paralyze)) @battle.performMove(@p1, @battle.getMove('Aromatherapy')) _.all(@team1.pokemon, (pokemon) -> !pokemon.hasStatus()).should.be.true describe 'copycat', -> beforeEach -> shared.create.call this, team1: [Factory('Magikarp', evs: {speed: 4})] # make faster than team2 it 'copies the last move used', -> @battle.lastMove = @battle.getMove('Tackle') mock = @sandbox.mock(@battle.getMove('Tackle')) mock.expects('execute').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it "changes the move's target properly", -> tackle = @battle.getMove('Tackle') @battle.lastMove = tackle mock = @sandbox.mock(tackle) mock.expects('execute').once().withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it 'fails if no last move was used', -> @battle.lastMove = null mock = @sandbox.mock(@battle.getMove('Copycat')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it 'fails if the last move was copycat', -> @battle.lastMove = @battle.getMove('Copycat') mock = @sandbox.mock(@battle.getMove('Copycat')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() describe 'a move that targets a different stat', -> it "uses the correct stat", -> shared.create.call(this) move = @battle.getMove('Secret Sword') defStat = @p2.stat('defense') move.pickDefenseStat(@p1, @p2).should.equal defStat describe 'foul play', -> it "uses the target's attack stat, not the user's", -> shared.create.call this, team1: [Factory('Celebi')] move = @battle.getMove('Foul Play') atkStat = @p2.stat('attack') move.pickAttackStat(@p1, @p2).should.equal atkStat describe 'foul play', -> it "uses the target's attack stat, not the user's", -> shared.create.call this, team1: [Factory('Celebi')] move = @battle.getMove('Foul Play') atkStat = @p2.stat('attack') move.pickAttackStat(@p1, @p2).should.equal atkStat describe 'teleport', -> it "always fails", -> shared.create.call(this) move = @battle.getMove('Teleport') mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() describe 'Super Fang', -> it "deals half of the target's current HP", -> shared.create.call(this) hp = @p2.currentHP hp = @p2.currentHP = (hp - (1 - hp % 2)) # Always odd @battle.performMove(@p1, @battle.getMove('Super Fang')) @p2.currentHP.should.equal Math.ceil(hp / 2) it "deals 1 damage minimum", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Super Fang')) @p2.currentHP.should.equal 0 describe "A weather-based recovery move", -> it "heals 50% HP in no weather, rounded half down", -> shared.create.call(this) @battle.setWeather(Weather.NONE) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') / 2) @p1.currentHP.should.equal(1 + hp) it "heals 25% HP in bad weather, rounded half down", -> shared.create.call(this, team1: [Factory("Shuckle")]) @battle.setWeather(Weather.SAND) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') / 4) @p1.currentHP.should.equal(1 + hp) it "heals 66% HP in good weather, rounded half down", -> shared.create.call(this) @battle.setWeather(Weather.SUN) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') * 2 / 3) @p1.currentHP.should.equal(1 + hp) describe 'a flinching move', -> it "prevents the other person from executing their move", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Splash')) mock.expects('execute').never() @battle.performMove(@p1, @battle.getMove('Fake Out')) @battle.performMove(@p2, @battle.getMove('Splash')) mock.verify() it "removes the flinch attachment at the end of the turn", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Fake Out')) @battle.endTurn() @p2.has(Attachment.Flinch).should.be.false describe 'weather ball', -> it "is a 50 base power normal move in normal conditions", -> shared.create.call(this) @battle.setWeather(Weather.NONE) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Normal' move.basePower(@battle, @p1, @p2).should.equal 50 it "is a 100 base power Water move in rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Water' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Fire move in sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Fire' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Ice move in hail", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Ice' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Rock move in sandstorm", -> shared.create.call(this) @battle.setWeather(Weather.SAND) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Rock' move.basePower(@battle, @p1, @p2).should.equal 100 describe 'Autotomize', -> it 'changes your weight on success', -> shared.create.call(this) weight = @p1.calculateWeight() @battle.performMove(@p1, @battle.getMove('Autotomize')) weight.should.not.equal @p1.calculateWeight() it 'cannot go below .1kg', -> # Magikarp weighs 100kg. shared.create.call this, team1: [ Factory('Magikarp')] @battle.performMove(@p1, @battle.getMove('Autotomize')) @p1.calculateWeight().should.not.be.lessThan .1 it 'stacks weight changes', -> # Abomasnow weighs 1355kg. shared.create.call this, team1: [ Factory('Abomasnow')] @battle.performMove(@p1, @battle.getMove('Autotomize')) @battle.performMove(@p1, @battle.getMove('Autotomize')) @p1.calculateWeight().should.equal 1155 describe 'heart swap', -> shared.shouldDoNoDamage('Heart Swap') it 'swaps user and target boosts', -> shared.create.call(this) @p1.stages.attack = 2 @p2.stages.speed = -2 @battle.performMove(@p1, @battle.getMove('Heart Swap')) @p1.stages.should.containEql speed: -2 @p2.stages.should.containEql attack: 2 describe 'Nightmare', -> shared.shouldDoNoDamage('Nightmare') it 'fails if the pokemon is awake', -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Nightmare')).expects('fail').once() @battle.performMove(@p1, @battle.getMove('Nightmare')) mock.verify() it 'fails if used twice', -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) nightmare = @battle.getMove('Nightmare') @p2.attach(Status.Sleep) mock = @sandbox.mock(nightmare).expects('fail').once() @battle.performMove(@p1, nightmare) @battle.performMove(@p1, nightmare) mock.verify() it "cuts the target's HP by 25% each turn", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) hp = @p2.currentHP quarter = Math.floor(hp / 4) @battle.performMove(@p1, @battle.getMove('Nightmare')) @battle.endTurn() @p2.currentHP.should.equal(hp - quarter) @battle.endTurn() @p2.currentHP.should.equal(hp - 2*quarter) it "deals 1 damage minimum", -> shared.create.call(this, team2: [Factory("Shedinja")]) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove('Nightmare')) @battle.endTurn() @p2.currentHP.should.equal(0) it "stops the nightmare if the target wakes up", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove('Nightmare')) @p2.cureStatus() @battle.endTurn() # The check is in endTurn() @p2.has(Attachment.Nightmare).should.be.false describe 'Incinerate', -> it 'destroys the berry of the target', -> shared.create.call this, team2: [ Factory('Magikarp', item: 'Bluk Berry') ] @battle.performMove(@p1, @battle.getMove('Incinerate')) should.not.exist @p2.item it 'does not destroy non-berries', -> shared.create.call this, team2: [ Factory('Magikarp', item: 'Leftovers') ] @battle.performMove(@p1, @battle.getMove('Incinerate')) should.exist @p2.item describe 'Judgment', -> it 'is normal type by default', -> shared.create.call(this) move = @battle.getMove('Judgment') move.getType(@battle, @p1, @p2).should.equal 'Normal' it 'changes type depending on the Plate held by the user', -> shared.create.call this, team1: [ Factory('Magikarp', item: 'Earth Plate') ] move = @battle.getMove('Judgment') move.getType(@battle, @p1, @p2).should.equal 'Ground' describe 'Tailwind', -> shared.shouldDoNoDamage("Tailwind") shared.shouldFailIfUsedTwice("Tailwind") it "doubles the speed of the user's team", -> shared.create.call this oldSpeed = @p1.stat('speed') @battle.performMove(@p1, @battle.getMove('Tailwind')) newSpeed = @p1.stat('speed') newSpeed.should.equal(oldSpeed * 2) it "lasts three turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Tailwind')) @battle.endTurn() @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.team.has(Attachment.Tailwind).should.be.false describe 'Taunt', -> shared.shouldDoNoDamage("Taunt") shared.shouldFailIfUsedTwice("Taunt") it 'prevents the target from using a non-attacking move that turn', -> shared.create.call(this, team1: [ Factory('Magikarp', evs: {speed: 4}) ]) move = @battle.getMove('Calm Mind') taunt = @battle.getMove('Taunt') mock = @sandbox.mock(move) mock.expects('execute').never() @battle.performMove(@p1, taunt) @battle.performMove(@p2, move) mock.verify() it "lasts 4 turns if the user moved after the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p1, @battle.getMove('Splash')) @battle.performMove(@p2, @battle.getMove('Taunt')) @p1.has(Attachment.Taunt).should.be.true @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.has(Attachment.Taunt).should.be.true @battle.endTurn() @p1.has(Attachment.Taunt).should.be.false it "lasts 3 turns if the user moved before the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Taunt')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.has(Attachment.Taunt).should.be.true @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Taunt).should.be.true @battle.endTurn() @p2.has(Attachment.Taunt).should.be.false it 'prevents the target from selecting that move the next turn', -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Taunt')) @battle.beginTurn() requestedMoves = @battle.requestFor(@p2).moves requestedMoves.should.not.containEql 'Splash' for moveName in [ "U-turn", "Volt Switch" ] do (moveName) -> describe moveName, -> it 'forces the owner to switch', -> shared.create.call(this, team1: (Factory("Magikarp") for i in [1..2])) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.requests.should.have.property(@id1) it "makes a request containing all the possible switches", -> shared.create.call(this, team1: (Factory("Magikarp") for i in [1..3])) @battle.performMove(@p1, @battle.getMove(moveName)) request = @battle.requestFor(@p1) request.switches.should.eql([ 1, 2 ]) describe 'venoshock', -> it 'doubles the base power if target is poisoned', -> shared.create.call(this) move = @battle.getMove("Venoshock") @p2.attach(Status.Poison) basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) it 'doubles the base power if target is toxiced', -> shared.create.call(this) move = @battle.getMove("Venoshock") @p2.attach(Status.Toxic) basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) describe 'Wish', -> shared.shouldDoNoDamage("Wish") shared.shouldFailIfUsedTwice("Wish") it "restores half of the user's total hit points the next end of turn", -> shared.create.call(this) hp = @p1.currentHP @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() @p1.currentHP.should.equal 1 @battle.endTurn() @p1.currentHP.should.equal(Math.round(hp / 2) + 1) it "restores the same total amount of HP to an ally", -> shared.create.call(this, team1: [Factory("Magikarp"), Factory("Celebi")]) hp = @p1.currentHP @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() receiver = @team1.at(1) receiver.currentHP = 1 @battle.performSwitch(@p1, 1) @battle.endTurn() receiver.currentHP.should.equal(Math.round(hp / 2) + 1) it "fails if the pokemon faints", -> shared.create.call(this, team1: [Factory("Magikarp"), Factory("Celebi")]) @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() @p1.currentHP = 1 @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.endTurn() @team1.has(Attachment.Wish).should.be.false describe "Counter", -> it "returns double the damage if attacked by a physical move", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Tackle')) @battle.performMove(@p1, @battle.getMove('Counter')) dhp1 = @p1.stat('hp') - @p1.currentHP dhp2 = @p2.stat('hp') - @p2.currentHP dhp2.should.equal 2*dhp1 it "fails if attacked by a special move", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Counter')) mock.expects('fail').once() @battle.performMove(@p2, @battle.getMove('ThunderShock')) @battle.performMove(@p1, @battle.getMove('Counter')) mock.verify() it "fails if not hit by an attack this turn", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Counter')) mock.expects('fail').once() @controller.makeMove(@id1, "Splash") @controller.makeMove(@id2, "Tackle") @battle.performMove(@p1, @battle.getMove('Counter')) mock.verify() it "hits the pokemon who is currently in that slot, not who was", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('U-turn')) @battle.performSwitch(@p1, 1) @battle.performMove(@p2, @battle.getMove('Counter')) @team1.first().currentHP.should.be.lessThan(@team1.first().stat('hp')) @team1.at(1).currentHP.should.equal(@team1.at(1).stat('hp')) it "doesn't activate Rough Skin if it fails", -> shared.create.call this, team2: [Factory("Garchomp", ability: "Rough Skin")] counter = @battle.getMove("Counter") mock = @sandbox.mock(counter) mock.expects('fail').once() @battle.performMove(@p1, counter) mock.verify() @p1.currentHP.should.equal(@p1.stat('hp')) describe "Perish Song", -> it "attaches to every pokemon in the field", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Perish Song')) result = _.all @battle.getActivePokemon(), (pokemon) -> pokemon.has(Attachment.PerishSong) result.should.be.true it "faints pokemon at the end of 4 turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Perish Song')) @battle.endTurn() @battle.endTurn() @battle.endTurn() result = _.all @battle.getActivePokemon(), (pokemon) -> !pokemon.isFainted() result.should.be.true @battle.endTurn() result = _.all @battle.getActivePokemon(), (pokemon) -> pokemon.isFainted() result.should.be.true it "fails against Pokemon with Soundproof", -> shared.create.call(this, team1: [Factory("Magikarp", ability: "Soundproof")]) @battle.performMove(@p2, @battle.getMove("Perish Song")) @p1.has(Attachment.PerishSong).should.be.false @p2.has(Attachment.PerishSong).should.be.true describe "Techno Blast", -> it "is Fire-type if the user holds a Burn Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Burn Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Fire" it "is Water-type if the user holds a Douse Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Douse Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Water" it "is Electric-type if the user holds a Shock Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Shock Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Electric" it "is Ice-type if the user holds a Chill Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Chill Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Ice" it "is Normal-type otherwise", -> shared.create.call(this) move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Normal" describe "Synchronoise", -> it "fails on Pokemon not of the user's type", -> shared.create.call this, team1: [Factory("Magikarp")] team2: [Factory("Celebi")] move = @battle.getMove('Synchronoise') mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "works on Pokemon that share one type with the user", -> shared.create.call this, team1: [Factory("Ferrothorn")] team2: [Factory("Celebi")] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Synchronoise')) @p2.currentHP.should.be.lessThan hp describe "Roost", -> shared.shouldDoNoDamage('Roost') it "removes the user's flying type during the turn", -> shared.create.call this, team1: [Factory("Gliscor")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) ('Flying' in @p1.types).should.be.false @p1.types.should.eql ['Ground'] it "turns pure-Flying pokemon into Normal pokemon", -> shared.create.call this, team1: [Factory("Tornadus")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) ('Flying' in @p1.types).should.be.false @p1.types.should.eql ['Normal'] it "keeps the user's types the same if non-Flying", -> shared.create.call this, team1: [Factory("Celebi")] oldTypes = @p1.types @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) @p1.types.should.eql oldTypes it "restores the user's old types after the turn", -> shared.create.call this, team1: [Factory("Gliscor")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) @battle.endTurn() ('Flying' in @p1.types).should.be.true ('Ground' in @p1.types).should.be.true describe 'Encore', -> shared.shouldDoNoDamage('Encore') it "fails if the target has not yet used a move", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p1, encore) mock.verify() it "forces the target to repeat its last used move", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Splash') ] it "changes the target's decision if it has not moved yet", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Encore')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.lastMove.should.equal @battle.getMove('Splash') it "lasts 4 turns if the user moved after the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p1, @battle.getMove('Splash')) @battle.performMove(@p2, @battle.getMove('Encore')) @p1.has(Attachment.Encore).should.be.true @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.has(Attachment.Encore).should.be.true @battle.endTurn() @p1.has(Attachment.Encore).should.be.false it "lasts 3 turns if the user moved before the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Encore')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.has(Attachment.Encore).should.be.true @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Encore).should.be.true @battle.endTurn() @p2.has(Attachment.Encore).should.be.false it "fails on certain moves like mimic", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p2, @battle.getMove('Mimic')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "fails if the pokemon is already encored", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "fails if the move has 0 PP", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @p2.setPP(@battle.getMove('Splash'), 1) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "removes itself if the pokemon's move reaches 0 PP", -> shared.create.call(this) @p2.setPP(@battle.getMove('Splash'), 2) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.endTurn() @p2.has(Attachment.Encore).should.be.true @battle.performMove(@p2, @battle.getMove('Splash')) @battle.endTurn() @p2.has(Attachment.Encore).should.be.false describe "Swagger", -> it "confuses the target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Swagger")) @p2.has(Attachment.Confusion).should.be.true it "boosts the target's attack by two stages", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Swagger")) @p2.stages.attack.should.equal 2 describe "Flatter", -> it "confuses the target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Flatter")) @p2.has(Attachment.Confusion).should.be.true it "boosts the target's special attack by one stage", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Flatter")) @p2.stages.specialAttack.should.equal 1 describe "Torment", -> shared.shouldDoNoDamage("Torment") shared.shouldFailIfUsedTwice("Torment") it "prevents the target from using its last move", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Torment")) @battle.performMove(@p2, @battle.getMove("Splash")) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Tackle') ] @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Splash') ] it "still works even if a new pokemon has just switched in", -> shared.create.call(this, team2: [Factory("Magikarp"), Factory("Magikarp")]) @battle.performSwitch(@p2, 1) @battle.performMove(@p1, @battle.getMove("Torment")) @battle.beginTurn() @team2.first().validMoves().should.eql [ @battle.getMove('Splash'), @battle.getMove('Tackle') ] xit "does not force the Outrage user to struggle", -> xit "does not prevent consecutive use of Struggle", -> describe "Psych Up", -> it "copies the target's stat changes", -> shared.create.call(this) @p1.stages.specialAttack = 5 @p1.stages.evasion = 2 @p2.stages.attack = 6 @p2.stages.defense = -2 @p2.stages.speed = -1 @battle.performMove(@p1, @battle.getMove("Psych Up")) @p1.stages.should.eql { attack: 6, defense: -2, specialAttack: 0, specialDefense: 0, speed: -1, accuracy: 0, evasion: 0 } describe "Spikes", -> it "puts a layer of spikes on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.Spikes).should.be.false @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true it "fails if there are 3 layers", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Spikes')).expects('fail').once() for i in [1..4] @battle.performMove(@p1, @battle.getMove("Spikes")) mock.verify() it "deals a minimum of 1 damage", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Shedinja")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() (pokemon.stat('hp') - pokemon.currentHP).should.equal(1) it "does damage to pokemon switching in according to # of layers", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] hp = @team2.first().stat('hp') @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@p2, 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) @team2.first().currentHP = hp @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 6) @team2.first().currentHP = hp @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 4) it "does not affect pokemon with immunity to ground", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp", item: "Air Balloon")] @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().currentHP.should.equal @team2.first().stat('hp') it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() hp = @team2.first().stat('hp') (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) describe "Stealth Rock", -> shared.shouldDoNoDamage("Stealth Rock") shared.shouldFailIfUsedTwice("Stealth Rock") it "puts a layer of rocks on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.StealthRock).should.be.false @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @team2.has(Attachment.StealthRock).should.be.true it "does damage to pokemon switching in according to type", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Moltres")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() hp = pokemon.stat('hp') (hp - pokemon.currentHP).should.equal Math.floor(hp / 2) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() hp = pokemon.stat('hp') (hp - pokemon.currentHP).should.equal Math.floor(hp / 8) it "deals a minimum of 1 damage", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Aron", level: 1)] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() (pokemon.stat('hp') - pokemon.currentHP).should.equal(1) it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() hp = @team2.first().stat('hp') (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) describe "Toxic Spikes", -> it "puts a layer of toxic spikes on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.ToxicSpikes).should.be.false @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @team2.has(Attachment.ToxicSpikes).should.be.true it "fails if there are 2 layers", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Toxic Spikes')) mock.expects('fail').once() for i in [1..3] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) mock.verify() it "poisons or severely poisons the switch-in if not immune", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.true @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Toxic).should.be.true it "does not affect the pokemon if it's immune to Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Ferrothorn")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.false it "does not affect the pokemon if it's immune to Ground", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Gyarados")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.false it "disappears if the pokemon switching in is a grounded Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Drapion")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.has(Attachment.ToxicSpikes).should.be.false it "doesn't disappear if the pokemon switching in is a flying Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Drapion", item: "Air Balloon")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.has(Attachment.ToxicSpikes).should.be.true it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() @team2.first().has(Status.Poison).should.be.true testWeatherMove = (moveName, weather, item) -> describe moveName, -> it "changes the weather to #{weather.toLowerCase()} for 5 turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.weather.should.equal(weather) @battle.weatherDuration.should.equal 5 it "changes the weather to #{weather.toLowerCase()} for 8 turns if user holds a #{item}", -> shared.create.call this, team1: [Factory("Magikarp", item: item)] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.weather.should.equal(weather) @battle.weatherDuration.should.equal 8 it "fails if the weather is already #{weather}", -> shared.create.call this, team1: [Factory("Magikarp", item: item)] @battle.setWeather(weather) theMove = @battle.getMove(moveName) mock = @sandbox.mock(theMove).expects('fail').once() @battle.performMove(@p1, theMove) mock.verify() testWeatherMove("Rain Dance", Weather.RAIN, "Damp Rock") testWeatherMove("Sunny Day", Weather.SUN, "Heat Rock") testWeatherMove("Hail", Weather.HAIL, "Icy Rock") testWeatherMove("Sandstorm", Weather.SAND, "Smooth Rock") testStatusMove = (moveName, status) -> describe moveName, -> it "changes the status on a Pokemon if it has no status", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(status).should.be.true it "does not change the status if Pokemon already has a status", -> shared.create.call(this) oldStatus = if status == Status.Paralyze Status.Sleep else Status.Paralyze @p2.attach(oldStatus) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(status).should.be.false @p2.has(oldStatus).should.be.true testStatusMove("Dark Void", Status.Sleep) testStatusMove("GrassWhistle", Status.Sleep) testStatusMove("Hypnosis", Status.Sleep) testStatusMove("Lovely Kiss", Status.Sleep) testStatusMove("Poison Gas", Status.Poison) testStatusMove("PoisonPowder", Status.Poison) testStatusMove("Sing", Status.Sleep) testStatusMove("Sleep Powder", Status.Sleep) testStatusMove("Spore", Status.Sleep) testStatusMove("Stun Spore", Status.Paralyze) testStatusMove("Thunder Wave", Status.Paralyze) testStatusMove("Toxic", Status.Toxic) testStatusMove("Will-O-Wisp", Status.Burn) testEffectMove = (moveName, Effect) -> describe moveName, -> it "adds the effect to the Pokemon if it doesn't have it", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(Effect).should.be.true it "fails if the Pokemon already has it", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move) mock.expects('fail').once() shared.biasRNG.call(this, "randInt", 'confusion turns', 4) @p2.attach(Effect, {@battle}) move = @battle.getMove(moveName) @battle.performMove(@p1, move) mock.verify() testEffectMove 'Confuse Ray', Attachment.Confusion testEffectMove 'Supersonic', Attachment.Confusion testEffectMove 'Sweet Kiss', Attachment.Confusion testEffectMove 'Teeter Dance', Attachment.Confusion describe "Trump Card", -> it "has 40 base power by default", -> shared.create.call(this) @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 40 it "has 50 base power if the move has 3 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 3] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 3 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 50 it "has 60 base power if the move has 2 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 2] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 2 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 60 it "has 80 base power if the move has 1 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 1] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 1 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 80 it "has 200 base power if the move has 0 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 0] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 0 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 200 testRandomSwitchMove = (moveName) -> describe moveName, -> it "should switch opponent out to a random member", -> shared.create.call(this, team2: [Factory("Magikarp"), Factory("Abra")]) target = @team2.at(1) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @team2.first().should.equal target it "does not force a switch if the target faints", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() @team2.at(0).setHP(1) @battle.performMove(@p1, move) mock.verify() it "does not force a switch if the hit was indirect", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, move) mock.verify() it "does not force a switch if the user faints", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp", ability: "Iron Barbs"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() else mock.expects("switch").once() @p1.currentHP = 1 @battle.performMove(@p1, move) mock.verify() it "should not force switches if opponent is the last pokemon", -> shared.create.call(this, team2: [Factory("Magikarp")]) mock = @sandbox.mock(@team2) mock.expects("switch").never() move = @battle.getMove(moveName) @battle.performMove(@p1, move) mock.verify() it "cancels the opponent's move if user moves first", -> shared.create.call this, team1: [ Factory("Magikarp", moves: [ moveName ], evs: {speed: 4}), Factory("Magikarp")] team2: [ Factory("Magikarp", moves: [ moveName ]), Factory("Magikarp")] spy1 = @sandbox.spy(@team1, 'switch') spy2 = @sandbox.spy(@team2, 'switch') @controller.makeMove(@id1, moveName) @controller.makeMove(@id2, moveName) spy1.callCount.should.equal(0) spy2.callCount.should.equal(1) testRandomSwitchMove "Roar" testRandomSwitchMove "Whirlwind" testRandomSwitchMove "Dragon Tail" testRandomSwitchMove "Circle Throw" testTrappingMove = (name) -> describe name, -> it "blocks switching", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.Trap).should.be.true @p1.has(Attachment.TrapLeash).should.be.true it "deals 1/16 of the pokemon's max hp every turn", -> shared.create.call(this, team2: [Factory("Blissey")]) @battle.performMove(@p1, @battle.getMove(name)) @p2.currentHP = @p2.stat('hp') @battle.endTurn() maxHP = @p2.stat('hp') expected = maxHP - Math.floor(maxHP / 16) @p2.currentHP.should.equal expected it "deals a minimum of 1 damage", -> shared.create.call(this, team2: [Factory("Shedinja")]) @p2.types = [ "Normal" ] move = @battle.getMove(name) @sandbox.stub(move, 'calculateDamage', -> 0) @battle.performMove(@p1, move) @battle.endTurn() @p2.currentHP.should.equal(0) it "lasts several turns", -> shared.create.call(this, team2: [Factory("Blissey")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @p2.currentHP = @p2.stat('hp') # loop for 5 more turns. One of the turns has already passed. # These moves hurt for 5 moves and wear off on the 6th. for i in [1..5] @p2.has(Attachment.Trap).should.be.true @battle.endTurn() # Test if the actual damage checks out. It should have damaged only 5 times maxHP = @p2.stat('hp') expected = maxHP - (Math.floor(maxHP / 16) * 5) @p2.currentHP.should.equal expected it "wears off after a certain number of turns", -> shared.create.call(this, team2: [Factory("Blissey")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() # loop for 5 more turns. One of the turns has already passed. # These moves hurt for 5 moves and wear off on the 6th. We need # turn number 6 to pass before the attachment should wear off. for i in [1..5] @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "does not reset the duration if used twice", -> shared.create.call(this, team2: [Factory("Blissey")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() # loop for 4 more turns. These moves wear off after numTurns + 1. # 2 have already passed. for i in [1..4] @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "wears off if the user switches", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "wears off if the user faints", -> shared.create.call(this, team1: [Factory("Heatran")], team2: [Factory("Blissey")]) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.Trap).should.be.true @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "properly removes from a list of attachments", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.recordMove(@id1, @battle.getMove("Protect")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "is always 7 turns if the user is holding grip claw", -> shared.create.call(this, team1: [Factory("Magikarp", item: "Grip Claw")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) move = @battle.getMove(name) @battle.performMove(@p1, move) @battle.performMove(@p2, @battle.getMove("Recover")) # The user is damaged 7 times, but the attachment actually lasts # for 8 turns including the turn it is first used. for i in [1..8] @p2.has(Attachment.Trap).should.be.true @battle.endTurn() @p2.has(Attachment.Trap).should.be.false it "does not start the effect if it hits a substitute", -> shared.create.call(this, team2: [Factory("Blissey")]) @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false testTrappingMove "Bind" testTrappingMove "Clamp" testTrappingMove "Fire Spin" testTrappingMove "Magma Storm" testTrappingMove "Sand Tomb" testTrappingMove "Whirlpool" testTrappingMove "Wrap" describe "Attract", -> shared.shouldDoNoDamage('Attract') shared.shouldFailIfUsedTwice "Attract", team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] it "has a 50% chance to immobilize a pokemon", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] shared.biasRNG.call(this, "next", 'attract chance', 0) # 100% immobilizes mock = @sandbox.mock(@battle.getMove('Tackle')).expects('execute').never() @battle.performMove(@p1, @battle.getMove("Attract")) @battle.performMove(@p2, @battle.getMove("Tackle")) mock.verify() it "has a 50% chance to not immobilize a pokemon", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] shared.biasRNG.call(this, "next", 'attract chance', .5) # 0% immobilizes mock = @sandbox.mock(@battle.getMove('Tackle')).expects('execute').once() @battle.performMove(@p1, @battle.getMove("Attract")) @battle.performMove(@p2, @battle.getMove("Tackle")) mock.verify() it "fails if the Pokemon are not opposite genders", -> shared.create.call this, team1: [Factory("Magikarp", gender: "F")] team2: [Factory("Magikarp", gender: "F")] mock = @sandbox.mock(@battle.getMove('Attract')).expects('fail').once() @battle.performMove(@p1, @battle.getMove("Attract")) mock.verify() it "disappears if the source is no longer active", -> shared.create.call this, team1: (Factory("Magikarp", gender: "M") for x in [1..2]) team2: [Factory("Magikarp", gender: "F")] @battle.performMove(@p1, @battle.getMove('Attract')) @battle.performMove(@p2, @battle.getMove('Splash')) @p2.has(Attachment.Attract).should.be.true @battle.performSwitch(@team1.first(), 1) @battle.performMove(@p2, @battle.getMove('Splash')) @p2.has(Attachment.Attract).should.be.false describe "Reflect", -> it "halves physical damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.Reflect) tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x800) it "does not halve non-physical damage", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.Reflect) thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) it "lasts five turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Reflect')) for i in [1..5] @team1.has(Attachment.Reflect).should.be.true @battle.endTurn() @team1.has(Attachment.Reflect).should.be.false it "fails if the user already used it", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Reflect')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Reflect')) @battle.performMove(@p1, @battle.getMove('Reflect')) mock.verify() it "does not halve on critical hits", -> shared.create.call(this) tackle = @battle.getMove('Tackle') @team2.attach(Attachment.Reflect) @p1.crit = true tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) describe "Light Screen", -> it "halves special damage", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.LightScreen) thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x800) it "does not halve non-physical damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.LightScreen) tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) it "lasts five turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Light Screen')) for i in [1..5] @team1.has(Attachment.LightScreen).should.be.true @battle.endTurn() @team1.has(Attachment.LightScreen).should.be.false it "fails if the user already used it", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Light Screen')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Light Screen')) @battle.performMove(@p1, @battle.getMove('Light Screen')) mock.verify() it "does not halve on critical hits", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') @team2.attach(Attachment.LightScreen) @p1.crit = true thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) describe "Rapid Spin", -> it "removes spikes", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false it "removes stealth rock", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @team2.has(Attachment.StealthRock).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.StealthRock).should.be.false it "removes toxic spikes", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @team2.has(Attachment.ToxicSpikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.ToxicSpikes).should.be.false it "removes multiple layers of entry hazards", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false it "removes trapping moves", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Fire Spin")) @p2.has(Attachment.Trap).should.be.true @p1.has(Attachment.TrapLeash).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "removes leech seed", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p2.has(Attachment.LeechSeed).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @p2.has(Attachment.LeechSeed).should.be.false it "does not remove entry hazards if the user faints from rough skin", -> shared.create.call(this, team1: [Factory("Magikarp", ability: "Rough Skin")]) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.true it "does remove entry hazards if the user faints from life orb", -> shared.create.call(this, team2: [Factory("Magikarp", item: "Life Orb")]) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false describe "Brick Break", -> it "shatters Light Screen", -> shared.create.call(this) @team2.attach(Attachment.LightScreen) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.LightScreen).should.be.false it "shatters Reflect", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.false it "shatters both at the same time", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.false @team2.has(Attachment.LightScreen).should.be.false it "shatters before damage calculation", -> shared.create.call(this) move = @battle.getMove("Brick Break") damage = move.calculateDamage(@battle, @p1, @p2) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) spy = @sandbox.spy(move, 'calculateDamage') @battle.performMove(@p1, move) spy.returned(damage).should.be.true it "does not shatter if the target is immune", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) @sandbox.stub(@p2, 'isImmune', -> true) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.true @team2.has(Attachment.LightScreen).should.be.true it "does not shatter if Brick Break misses", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) shared.biasRNG.call(this, 'randInt', 'miss', 101) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.true @team2.has(Attachment.LightScreen).should.be.true describe "Return", -> it "has 102 base power", -> shared.create.call(this) move = @battle.getMove("Return") bp = move.basePower(@battle, @p1, @p2) bp.should.equal 102 describe "Frustration", -> it "has 102 base power", -> shared.create.call(this) move = @battle.getMove("Frustration") bp = move.basePower(@battle, @p1, @p2) bp.should.equal 102 describe "Fake Out", -> it "flinches the enemy", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Fake Out")) @p2.has(Attachment.Flinch).should.be.true it "fails if the Pokemon has been in play one turn or more", -> shared.create.call(this) @battle.endTurn() @battle.beginTurn() fakeOut = @battle.getMove("Fake Out") mock = @sandbox.mock(fakeOut).expects('fail').once() @battle.performMove(@p1, fakeOut) mock.verify() it "works if the Pokemon is newly switched", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @battle.performSwitch(@team1.first(), 1) @battle.endTurn() @battle.beginTurn() fakeOut = @battle.getMove("Fake Out") mock = @sandbox.mock(fakeOut).expects('fail').never() @battle.performMove(@team1.first(), fakeOut) mock.verify() describe "Focus Energy", -> it "adds a Focus Energy attachment to the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Focus Energy")) @p1.has(Attachment.FocusEnergy).should.be.true it "fails the second time it is used", -> shared.create.call(this) move = @battle.getMove("Focus Energy") mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) @battle.performMove(@p1, move) mock.verify() testIdentifyMove = (moveName, types) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "makes the target vulnerable to #{types} moves", -> shared.create.call(this, team2: [Factory("Spiritomb")]) _.each(types, ((type) -> @isImmune(type).should.be.true), @p2) @battle.performMove(@p1, @battle.getMove(moveName)) @p2.has(Attachment.Identify).should.be.true _.each(types, ((type) -> @isImmune(type).should.be.false), @p2) it "makes the target's evasion be ignored", -> shared.create.call(this) @p2.boost(evasion: 2) @p2.editBoosts().evasion.should.equal 2 @battle.performMove(@p1, @battle.getMove(moveName)) @p2.editBoosts().evasion.should.equal 0 testIdentifyMove("Foresight", ["Normal", "Fighting"]) testIdentifyMove("Odor Sleuth", ["Normal", "Fighting"]) testIdentifyMove("Miracle Eye", ["Psychic"]) describe "Conversion", -> it "changes the user's type to a random type based on moves", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Thunderbolt", "Ice Beam", "Conversion" ])] shared.biasRNG.call(this, "randInt", 'conversion types', 0) @p1.types.should.eql [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Conversion")) @p1.types.should.eql [ 'Electric' ] it "ignores Conversion as part of the move types", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Conversion", "Ice Beam" ])] shared.biasRNG.call(this, "randInt", 'conversion types', 0) @p1.types = [ "Fake Type" ] @battle.performMove(@p1, @battle.getMove("Conversion")) @p1.types.should.eql [ 'Ice' ] it "fails if there is no type to convert to", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Conversion" ])] move = @battle.getMove("Conversion") mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) mock.verify() describe "Conversion 2", -> it "fails if the target has not yet moved", -> shared.create.call(this) move = @battle.getMove("Conversion 2") mock = @sandbox.mock(move).expects('fail').once() @p2.lastMove = null @battle.performMove(@p1, move) mock.verify() it "changes user's type to one resisting or is immune to target's move", -> shared.create.call(this) @p1.types = [ "Normal" ] move = @battle.getMove("Ember") type = move.type @p2.lastMove = move @battle.performMove(@p1, @battle.getMove("Conversion 2")) @p1.types.should.have.length 1 util.typeEffectiveness(type, @p1.types).should.be.lessThan 1 describe "Defense Curl", -> it "raises defense by 1 stage", -> shared.create.call(this) @p1.stages.defense.should.equal 0 @battle.performMove(@p1, @battle.getMove("Defense Curl")) @p1.stages.defense.should.equal 1 it "attaches a volatile attachment", -> shared.create.call(this) @p1.has(Attachment.DefenseCurl).should.be.false @battle.performMove(@p1, @battle.getMove("Defense Curl")) @p1.has(Attachment.DefenseCurl).should.be.true describe "Focus Punch", -> it "causes the user to flinch if hit", -> shared.create.call(this) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.not.be.lessThan @p2.stat('hp') it "does not cause flinching if hit by a non-damaging move", -> shared.create.call(this) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Will-O-Wisp")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if behind a substitute", -> shared.create.call(this) @p1.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2)) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if sub fades", -> shared.create.call(this) @p1.attach(Attachment.Substitute, hp: 1) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if hit by a move last turn", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching afterwards", -> shared.create.call(this, team2: [Factory("Magikarp", evs: {speed: 4})]) focusPunch = @battle.getMove("Focus Punch") @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() hp = @p2.currentHP @battle.recordMove(@id1, @battle.getMove("Tackle")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan(hp) describe "Magnet Rise", -> shared.shouldDoNoDamage("Magnet Rise") shared.shouldFailIfUsedTwice("Magnet Rise") it "makes the user immune to ground moves", -> shared.create.call(this) @p1.isImmune("Ground").should.be.false @battle.performMove(@p1, @battle.getMove("Magnet Rise")) @p1.isImmune("Ground").should.be.true it "lasts 5 turns", -> shared.create.call(this) @p1.isImmune("Ground").should.be.false @battle.performMove(@p1, @battle.getMove("Magnet Rise")) for i in [1..5] @p1.isImmune("Ground").should.be.true @battle.endTurn() @p1.isImmune("Ground").should.be.false testLockOnMove = (moveName) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "makes the user's next move never miss on this target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) shared.biasRNG.call(this, 'randInt', 'miss', 101) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @p2) .should.be.false it "lasts only two turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) for i in [1..2] @p1.has(Attachment.LockOn).should.be.true @battle.endTurn() @p1.has(Attachment.LockOn).should.be.false it "hits through two-turn fade-away moves", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, @battle.getMove("Fly")) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @p2) .should.be.false it "does not hit through Protect", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('hit').never() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Protect")) @battle.performMove(@p2, move) mock.verify() it "does not affect accuracy on another target", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performSwitch(@p2, 1) shared.biasRNG.call(this, 'randInt', 'miss', 101) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @team2.first()) .should.be.true it "re-locks on when used on another target", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performSwitch(@p2, 1) @battle.performMove(@p1, @battle.getMove(moveName)) @p1.has(Attachment.LockOn).should.be.true testLockOnMove("Lock-On") testLockOnMove("Mind Reader") describe "Minimize", -> it "boosts the user's evasion by 2", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Minimize")) @p1.stages.evasion.should.equal 2 it "adds a Minimize volatile attachment to the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Minimize")) @p1.has(Attachment.Minimize).should.be.true testStompMove = (moveName) -> describe moveName, -> it "doubles its base power when the target is minimized", -> shared.create.call(this) @p2.attach(Attachment.Minimize) move = @battle.getMove(moveName) bp = move.basePower(@battle, @p1, @p2) bp.should.equal(move.power * 2) it "has normal base power otherwise", -> shared.create.call(this) move = @battle.getMove(moveName) bp = move.basePower(@battle, @p1, @p2) bp.should.equal(move.power) it "has a 30% chance to flinch", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'flinch', 0) # 100% chance @battle.performMove(@p1, @battle.getMove(moveName)) @p2.has(Attachment.Flinch).should.be.true testStompMove("Stomp") testStompMove("Steamroller") testMeanLookMove = (moveName) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "blocks the target from switching", -> shared.create.call(this) @p2.isSwitchBlocked().should.be.false @battle.performMove(@p1, @battle.getMove(moveName)) @battle.beginTurn() @p2.isSwitchBlocked().should.be.true it "wears off if the user faints", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.MeanLook).should.be.true @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.MeanLook).should.be.false it "wears off if the user switches", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.MeanLook).should.be.false testMeanLookMove("Block") testMeanLookMove("Mean Look") testMeanLookMove("Spider Web") testRechargeMove = (moveName) -> describe moveName, -> it "blocks the target from switching the next turn", -> shared.create.call(this) @p1.isSwitchBlocked().should.be.false theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "blocks the target from picking a new move the next turn", -> shared.create.call(this) theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() for move in @p1.moves @p1.isMoveBlocked(move).should.be.true it "automatically selects a special recharge move the next turn", -> shared.create.call(this) specialMove = @battle.getMove("Recharge") theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @battle.requests.should.not.have.property @id1 action = @battle.getAction(@p1) should.exist(action) action.should.have.property("move") action.move.should.equal(specialMove) it "prevents the user from moving the next turn", -> shared.create.call(this) spy = @sandbox.spy(@p1, 'beforeMove') theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @battle.continueTurn() spy.returned(false).should.be.true testRechargeMove("Hyper Beam") testRechargeMove("Giga Impact") testRechargeMove("Blast Burn") testRechargeMove("Frenzy Plant") testRechargeMove("Hydro Cannon") testRechargeMove("Roar of Time") testRechargeMove("Rock Wrecker") describe 'Clear Smog', -> it 'removes all status boosts on the target pokemon', -> shared.create.call(this) # Create artificial boosts. @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Clear Smog")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p2.stages.should.eql neutralBoosts it "does not reset stats if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute, hp: 1) # Create artificial boosts. @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Clear Smog")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p2.stages.should.not.eql neutralBoosts testMomentumMove = (moveName) -> describe moveName, -> it "prevents the user from switching", -> shared.create.call(this) @p1.isSwitchBlocked().should.be.false @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "locks the user into using this particular move", -> shared.create.call this, team1: [ Factory("Shuckle") ] momentumMove = @battle.getMove(moveName) @p1.moves = [ momentumMove, @battle.getMove("Rest") ] @p1.resetAllPP() @battle.performMove(@p1, momentumMove) @battle.endTurn() @battle.beginTurn() for move in @p1.moves if move == momentumMove @p1.isMoveBlocked(move).should.be.false else @p1.isMoveBlocked(move).should.be.true it "stops if it misses", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'miss', 100) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Momentum).should.be.false it "lasts 5 turns", -> shared.create.call(this) for i in [1..5] @battle.performMove(@p1, @battle.getMove(moveName)) @p1.has(Attachment.Momentum).should.be.true @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Momentum).should.be.false it "doubles base power every time", -> shared.create.call(this) move = @battle.getMove(moveName) basePower = move.power for i in [1..5] bp = move.basePower(@battle, @p1, @p2) bp.should.equal(basePower * Math.pow(2, i - 1)) @battle.performMove(@p1, move) @battle.endTurn() @battle.beginTurn() @p2.currentHP = @p2.stat('hp') it "doubles base power again if user has defense curl's effect", -> shared.create.call(this) @p1.attach(Attachment.DefenseCurl) move = @battle.getMove(moveName) basePower = 2 * move.power for i in [1..5] bp = move.basePower(@battle, @p1, @p2) bp.should.equal(basePower * Math.pow(2, i - 1)) @battle.performMove(@p1, move) @battle.endTurn() @battle.beginTurn() @p2.currentHP = @p2.stat('hp') testMomentumMove("Rollout") testMomentumMove("Ice Ball") describe "Me First", -> it "fails if the user goes second", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.delay @p1 @battle.popAction(@p2) @battle.performMove(@p1, move) mock.verify() it "uses the target's move", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('execute').once() @battle.recordMove(@id1, @battle.getMove("Me First")) @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, @battle.getMove("Me First")) mock.verify() it "has 1.5x the base power of the target's move", -> shared.create.call(this) move = @battle.getMove("Tackle") @battle.recordMove(@id1, @battle.getMove("Me First")) @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, @battle.getMove("Me First")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x1800 for moveName in [ "Chatter", "Counter", "Covet", "Focus Punch", "Me First", "Metal Burst", "Mirror Coat", "Struggle", "Thief" ] do (moveName) -> it "fails if the target is using #{moveName}", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove(moveName)) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, move) mock.verify() it "fails if the target is using a non-damaging move", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, move) mock.verify() describe "Dream Eater", -> it "fails if the target is not asleep", -> shared.create.call(this) move = @battle.getMove("Dream Eater") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "does not fail if the target is asleep", -> shared.create.call(this) move = @battle.getMove("Dream Eater") mock = @sandbox.mock(move).expects('fail').never() @p2.attach(Status.Sleep) @battle.performMove(@p1, move) mock.verify() it "drains 1/2 of damage", -> shared.create.call(this) @p1.currentHP = initialHP = 1 @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove("Dream Eater")) damage = @p2.stat('hp') - @p2.currentHP healed = Math.floor(damage / 2) @p1.currentHP.should.equal(initialHP + healed) describe "Camouflage", -> it "changes the user's type to Ground type in Wi-Fi battles", -> shared.create.call(this) @p1.types = [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Camouflage")) @p1.types.should.eql [ "Ground" ] describe "Charge", -> shared.shouldDoNoDamage("Charge") it "raises the user's special defense by 1", -> shared.create.call(this) @p1.stages.specialDefense.should.equal 0 @battle.performMove(@p1, @battle.getMove("Charge")) @p1.stages.specialDefense.should.equal 1 it "doubles the base power of the user's next move", -> shared.create.call(this) move = @battle.getMove("Thunderbolt") move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 @battle.performMove(@p1, @battle.getMove("Charge")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x2000 it "doesn't double the next move if it is non-electric type", -> shared.create.call(this) move = @battle.getMove("Flamethrower") move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 @battle.performMove(@p1, @battle.getMove("Charge")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 it "can be used twice in a row", -> shared.create.call(this) move = @battle.getMove("Charge") mock = @sandbox.mock(move).expects('fail').never() @battle.performMove(@p1, move) @battle.endTurn() @battle.performMove(@p1, move) @battle.endTurn() @p1.has(Attachment.Charge).should.be.true mock.verify() describe "Tri Attack", -> it "has a 20% chance to activate its secondary effect", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.hasStatus().should.be.true it "has a 1/3 chance for the secondary effect to be paralysis", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 0) # par @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Paralyze).should.be.true it "has a 1/3 chance for the secondary effect to be burn", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 1) # brn @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Burn).should.be.true it "has a 1/3 chance for the secondary effect to be freeze", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 2) # frz @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Freeze).should.be.true describe "Mirror Move", -> it "copies the opponent's last move", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('execute').once() @p2.lastMove = move @battle.performMove(@p1, @battle.getMove("Mirror Move")) mock.verify() it "fails if the opponent has not moved the past turn", -> shared.create.call(this) move = @battle.getMove("Mirror Move") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "fails if the move does not have a `mirror` flag", -> shared.create.call(this) @p2.lastMove = @battle.getMove("Dragon Dance") move = @battle.getMove("Mirror Move") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() # TODO: Find out if this is true: when is lastMove nullified? it "fails if the pokemon was unable to move the previous turn" describe "Leech Seed", -> shared.shouldFailIfUsedTwice("Leech Seed") it "saps 1/8 of the target's max HP each turn", -> shared.create.call(this) move = @battle.getMove("Leech Seed") @p1.currentHP = 1 @battle.performMove(@p1, move) @battle.endTurn() p = @p2 fullHP = p.stat('hp') (fullHP - p.currentHP).should.equal Math.floor(fullHP / 8) @p1.currentHP.should.equal(fullHP - p.currentHP + 1) it "saps up to 1/8 HP", -> shared.create.call(this) move = @battle.getMove("Leech Seed") @p1.currentHP = 1 @p2.currentHP = 1 @battle.performMove(@p1, move) @battle.endTurn() @p1.currentHP.should.equal 2 it "saps a minimum of 1 damage", -> shared.create.call(this, team2: [Factory("Shedinja")]) move = @battle.getMove("Leech Seed") @battle.performMove(@p1, move) @battle.endTurn() @p2.currentHP.should.equal(0) it "always misses on Grass type Pokemon", -> shared.create.call(this) move = @battle.getMove("Leech Seed") mock = @sandbox.mock(move).expects('afterMiss').once() @p2.types = [ "Water", "Grass"] @battle.performMove(@p1, move) mock.verify() it "does not trigger if the user has fainted", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p1.faint() @battle.endTurn() @p2.currentHP.should.equal @p2.stat('hp') it "leeches next pokemon to switch in at that slot", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p1.faint() @battle.endTurn() @battle.performSwitch(@team1.first(), 1) @p2.currentHP.should.equal @p2.stat('hp') newFirst = @team1.first() newFirst.currentHP = 1 @battle.endTurn() hp = @p2.stat('hp') - @p2.currentHP hp.should.be.greaterThan(0) newFirst.currentHP.should.equal(hp + 1) it "stops if the target has fainted", -> shared.create.call(this, team2: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p2.faint() @battle.endTurn() @battle.performSwitch(@team2.first(), 1) @team2.first().currentHP.should.equal @team2.first().stat('hp') @p1.currentHP.should.equal(1) testProtectCounterMove = (moveName) -> it "fails if the user moves last this turn", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('fail').once() @battle.determineTurnOrder() @battle.performMove(@p1, move) mock.verify() it "has decreasing chances of success", -> shared.create.call(this) p = @p1 for x in [0..7] attachment = p.attach(Attachment.ProtectCounter) attachment.successChance().should.equal Math.pow(2, x) attachment = p.attach(Attachment.ProtectCounter) attachment.successChance().should.equal Math.pow(2, 32) it "fails if not successful", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 2) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) mock.verify() it "resets to 100% chance of success if move fails", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 2) move = @battle.getMove(moveName) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) @p1.has(Attachment.ProtectCounter).should.be.false it "resets to 100% chance of success if user selects a different move", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 1) move = @battle.getMove(moveName) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) @battle.endTurn() @p1.has(Attachment.ProtectCounter).should.be.true @battle.performMove(@p1, @battle.getMove('Splash')) @battle.endTurn() @p1.has(Attachment.ProtectCounter).should.be.false testProtectMove = (moveName) -> describe moveName, -> testProtectCounterMove(moveName) it "completely protects the user from attacks", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('hit').never() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) mock.verify() it "does not carry over to the next turn", -> shared.create.call(this) move = @battle.getMove("Tackle") @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) @battle.endTurn() mock = @sandbox.mock(move).expects('hit').once() @battle.performMove(@p2, move) mock.verify() it "does not protect the user from attacks without the protect flag", -> shared.create.call(this) move = @battle.getMove("Feint") mock = @sandbox.mock(move).expects('hit').once() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) mock.verify() testProtectMove 'Protect' testProtectMove 'Detect' describe "Endure", -> testProtectCounterMove("Endure") it "always survives moves that would otherwise KO with 1 HP", -> shared.create.call(this) move = @battle.getMove("Tackle") hp = @p1.currentHP @sandbox.stub(move, 'baseDamage', -> hp) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Endure")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.currentHP.should.equal 1 it "disappears at the end of the turn", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Endure")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.has(Attachment.Endure).should.be.true @battle.endTurn() @p1.has(Attachment.Endure).should.be.false describe "Feint", -> it "removes the Protect attachment, if any, on the target", -> shared.create.call(this) @p1.attach(Attachment.Protect) @p1.has(Attachment.Protect).should.be.true @battle.performMove(@p2, @battle.getMove("Feint")) @p1.has(Attachment.Protect).should.be.false it "removes the Wide Guard attachment, if any, on the target" it "removes the Quick Guard attachment, if any, on the target" describe "Payback", -> it "doubles base power if target has made a move this turn", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.performMove(@p2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(2 * move.power).should.be.true it "doesn't double base power otherwise", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(move.power).should.be.true it "doesn't double BP if target moved last turn, but not this turn", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.performMove(@p2, @battle.getMove("Splash")) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(move.power).should.be.true describe "Curse", -> it "silently chooses a random enemy as the target", -> shared.create.call(this) move = @battle.getMove("Curse") targets = move.getTargets(@battle, @p1) should.exist targets targets.should.eql [ @p2 ] describe "for Ghost types", -> it "curses the opponent", -> shared.create.call(this) @p1.types = [ "Ghost" ] @battle.performMove(@p1, @battle.getMove("Curse")) @p2.has(Attachment.Curse).should.be.true it "damages the user for half of its HP, rounded down", -> shared.create.call(this) p = @p1 p.types = [ "Ghost" ] maxHP = p.stat('hp') @battle.performMove(@p1, @battle.getMove("Curse")) p.currentHP.should.equal(maxHP - Math.floor(maxHP / 2)) it "causes the opponent to lose 25% of their HP at end of turns", -> shared.create.call(this) @p1.types = [ "Ghost" ] p = @p2 maxHP = p.stat('hp') quarterHP = Math.floor(maxHP / 4) @battle.performMove(@p1, @battle.getMove("Curse")) p.currentHP.should.equal(maxHP) @battle.endTurn() p.currentHP.should.equal(maxHP - quarterHP) @battle.endTurn() p.currentHP.should.equal(maxHP - 2 * quarterHP) it "causes the opponent to lose a minimum of 1 HP per turn", -> shared.create.call(this, team2: [Factory("Shedinja"), Factory("Magikarp")]) @p1.types = [ "Ghost" ] @battle.performMove(@p1, @battle.getMove("Curse")) @battle.endTurn() @p2.currentHP.should.equal(0) it "can faint the user", -> shared.create.call(this) p = @p1 p.types = [ "Ghost" ] p.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Curse")) p.isFainted().should.be.true describe "for non-Ghost types", -> it "raises Attack and Defense and lowers Speed", -> shared.create.call(this) p = @p1 p.types = [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Curse")) p.stages.should.containEql attack: 1, defense: 1, speed: -1 testBasePowerBoostMove = (moveName, rawBasePower, maxBasePower, which) -> describe moveName, -> it "increases base power by 20 for each positive stat boost on #{which}", -> shared.create.call(this) move = @battle.getMove(moveName) poke = { user: @p1, target: @p2 } {user, target} = poke move.basePower(@battle, user, target).should.equal rawBasePower poke[which].boost(attack: 1) move.basePower(@battle, user, target).should.equal rawBasePower + 20 poke[which].boost(defense: 1) move.basePower(@battle, user, target).should.equal rawBasePower + 40 poke[which].boost(speed: 2, specialAttack: -1) move.basePower(@battle, user, target).should.equal rawBasePower + 80 it "has a maximum of #{maxBasePower} base power", -> shared.create.call(this) move = @battle.getMove(moveName) poke = { user: @p1, target: @p2 } {user, target} = poke # Total base power would theoretically be rawBasePower + 840 stats = { speed: 6, specialAttack: 6, attack: 6, defense: 6, specialDefense: 6, evasion: 6, accuracy: 6 } poke[which].boost(stats) move.basePower(@battle, user, target).should.equal maxBasePower testBasePowerBoostMove("Stored Power", 20, 860, "user") testBasePowerBoostMove("Punishment", 60, 200, "target") describe "Destiny Bond", -> it "causes the attacker to faint the turn of use if the user faints", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.true it "causes the attacker to faint any time before the user moves again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.endTurn() @battle.beginTurn() @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.true it "does not cause attacker to faint after user moves again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p1, @battle.getMove("Splash")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.false it "does not cause attacker to faint after user attempts to move again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.endTurn() @battle.beginTurn() @p1.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove("Tackle")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.false it "does not faint attacker if pokemon fainted naturally", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @p1.faint() @battle.endTurn() @p2.isFainted().should.be.false it "does not faint attacker if opponent made move, but did not faint", -> shared.create.call(this) @battle.setWeather(Weather.SAND) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.currentHP = 1 @battle.endTurn() @p1.isFainted().should.be.true @p2.isFainted().should.be.false it "does not cause a party member to faint" it "handles 2+ pokemon destiny-bonding and all fainting at once" describe "Pursuit", -> it "doubles base power if the target switches", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() spy.alwaysReturned(2 * pursuit.power).should.be.true it "doubles BP if a faster target uses a damaging switch move", -> shared.create.call this, team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id2, @battle.getMove("U-turn")) @battle.recordMove(@id1, pursuit) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(2 * pursuit.power).should.be.true it "doesn't double BP if a slower target uses a damaging switch move", -> shared.create.call this, team1: [ Factory("Magikarp", evs: {speed: 4}) ] team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id1, pursuit) @battle.recordMove(@id2, @battle.getMove("U-turn")) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(pursuit.power).should.be.true it "has perfect accuracy if target is switching", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'chanceToHit') pursuit = @battle.getMove("Pursuit") @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() spy.alwaysReturned(0).should.be.true it "runs only once", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(pursuit).expects('execute').once() pursuit = @battle.getMove("Pursuit") @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() mock.verify() it "doesn't double BP on a faster Baton Passer", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id1, pursuit) @battle.recordMove(@id2, @battle.getMove("Baton Pass")) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(pursuit.power).should.be.true it "emits the move name when target switches", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(@battle, 'tell') @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() spy.calledWith(Protocol.MAKE_MOVE).should.be.true it "records the move when target switches", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(@p1).expects('recordMove').once() @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() mock.verify() it "does not trigger if asleep", -> shared.create.call(this) @p1.attach(Status.Sleep, turns: 4) pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(pursuit).expects('hit').never() @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() mock.verify() it "does not trigger on team members" describe 'Power Swap', -> it 'swaps attack and special attack boosts with the target', -> shared.create.call(this) @p1.boost(attack: 1, specialAttack: -3, speed: 1) @p2.boost(attack: 2, specialAttack: 6, defense: -1) @battle.performMove(@p1, @battle.getMove('Power Swap')) @p1.stages.should.containEql attack: 2, specialAttack: 6, speed: 1 @p2.stages.should.containEql attack: 1, specialAttack: -3, defense: -1 describe 'Guard Swap', -> it 'swaps defense and special defense boosts with the target', -> shared.create.call(this) @p1.boost(attack: 1, specialDefense: -3, defense: 1) @p2.boost(speed: 2, specialDefense: 6, defense: -1) @battle.performMove(@p1, @battle.getMove('Guard Swap')) @p1.stages.should.containEql defense: -1, specialDefense: 6, attack: 1 @p2.stages.should.containEql defense: 1, specialDefense: -3, speed: 2 describe 'Spite', -> it 'reduces the last move used by the target by 4', -> shared.create.call(this) move = @p2.moves[0] pp = @p2.pp(move) @battle.performMove(@p2, move) @battle.performMove(@p1, @battle.getMove('Spite')) @p2.pp(move).should.equal(pp - 4 - 1) it 'fails if the target has not recorded their last move', -> shared.create.call(this) spite = @battle.getMove('Spite') mock = @sandbox.mock(spite).expects('fail').once() @battle.performMove(@p1, spite) mock.verify() it "fails if the target's move has 0 PP", -> shared.create.call(this) spite = @battle.getMove('Spite') move = @p2.moves[0] mock = @sandbox.mock(spite).expects('fail').once() @p2.setPP(move, 0) @battle.performMove(@p2, move) @battle.performMove(@p1, spite) mock.verify() it 'fails if the target no longer knows the move', -> shared.create.call(this) spite = @battle.getMove('Spite') move = @p2.moves[0] mock = @sandbox.mock(spite).expects('fail').once() @battle.performMove(@p2, move) @p2.moves.splice(@p2.moves.indexOf(move), 1) @battle.performMove(@p1, spite) mock.verify() describe 'Wring Out', -> it 'has 120 power at maximum HP', -> shared.create.call(this) move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 120 it 'has 59 power at half-of-odd HP (rounded down)', -> shared.create.call(this) @p1.currentHP >>= 1 move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 59 it 'has 1 power minimum', -> shared.create.call(this) @p1.currentHP = 1 move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 1 describe 'Assurance', -> it 'doubles base power if the user was damaged this turn', -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Tackle')) power = move.basePower(@battle, @p1, @p2) power.should.equal(2 * move.power) it "doesn't double base power if the user was damaged a different turn", -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Tackle')) @battle.endTurn() @battle.beginTurn() power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) it "doesn't double base power if the user has never used a move", -> shared.create.call(this) move = @battle.getMove('Assurance') power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) it "doesn't double base power if hit by a non-damaging move", -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Will-O-Wisp')) power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) describe "Substitute", -> shared.shouldDoNoDamage("Substitute") shared.shouldFailIfUsedTwice("Substitute") it "removes 25% of the owner's health, rounded down", -> shared.create.call(this) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') @battle.performMove(@p1, sub) @p1.currentHP.should.equal(hp - (hp >> 2)) it "fails if the pokemon has 25% HP or less", -> shared.create.call(this) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') mock = @sandbox.mock(sub).expects('fail').once() @p1.currentHP = hp >> 2 @battle.performMove(@p1, sub) mock.verify() it "fails if the pokemon does not have enough total HP", -> shared.create.call(this, team1: [Factory("Shedinja")]) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') mock = @sandbox.mock(sub).expects('fail').once() @battle.performMove(@p1, sub) mock.verify() it "takes damage for the user", -> shared.create.call(this) sub = @battle.getMove('Substitute') subHP = (@p1.stat('hp') >> 2) @battle.performMove(@p1, sub) hp = @p1.currentHP attachment = @p1.get(Attachment.Substitute) attachment.hp.should.equal subHP @battle.performMove(@p2, @battle.getMove('Tackle')) attachment.hp.should.be.lessThan subHP @p1.currentHP.should.equal hp it "breaks after taking too much damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) hp = @p1.currentHP @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(tackle, 'baseDamage', -> 9999) @battle.performMove(@p2, tackle) @p1.has(Attachment.Substitute).should.be.false @p1.currentHP.should.equal hp it "fails most non-damaging moves", -> shared.create.call(this) hypnosis = @battle.getMove('Hypnosis') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(hypnosis).expects('fail').once() @battle.performMove(@p2, hypnosis) mock.verify() it "does not fail stat-up moves", -> shared.create.call(this) dragonDance = @battle.getMove('Dragon Dance') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(dragonDance).expects('fail').never() @battle.performMove(@p1, dragonDance) mock.verify() it "does not fail non-damaging moves with an authentic flag", -> shared.create.call(this) foresight = @battle.getMove('Foresight') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(foresight).expects('fail').never() @battle.performMove(@p2, foresight) mock.verify() it "still stores the actual damage", -> shared.create.call(this) gigaDrain = @battle.getMove('Giga Drain') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true spy = @sandbox.spy(@p2, 'drain') @battle.performMove(@p2, gigaDrain) spy.calledWith(0).should.be.false @p1.lastHitBy.damage.should.be.greaterThan 0 it "blocks secondary effects", -> shared.create.call(this) shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn flamethrower = @battle.getMove('Flamethrower') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(flamethrower, 'baseDamage', -> 1) @battle.performMove(@p2, flamethrower) @p1.has(Status.Burn).should.be.false it "blocks secondary effects even if sub fades", -> shared.create.call(this) shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn flamethrower = @battle.getMove('Flamethrower') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(flamethrower, 'baseDamage', -> 9999) @battle.performMove(@p2, flamethrower) @p1.has(Status.Burn).should.be.false it "does not block sandstorm damage", -> shared.create.call(this) @battle.setWeather(Weather.SAND) @battle.performMove(@p1, @battle.getMove('Substitute')) hp = @p1.currentHP @battle.endTurn() @p1.currentHP.should.be.lessThan(hp) it "does not block leech seed damage", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Leech Seed')) @battle.performMove(@p1, @battle.getMove('Substitute')) hp = @p1.currentHP @battle.endTurn() @p1.currentHP.should.be.lessThan(hp) it "is baton-passable" describe "Sucker Punch", -> it "fails if the target is not moving after the user", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') mock = @sandbox.mock(suckerPunch).expects('fail').once() @battle.performMove(@p1, suckerPunch) mock.verify() it "executes normally if the target is moving after the user", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') tackle = @battle.getMove('Tackle') mock = @sandbox.mock(suckerPunch).expects('afterSuccessfulHit').once() @battle.recordMove(@id2, tackle) @battle.determineTurnOrder() @battle.performMove(@p1, suckerPunch) mock.verify() it "fails if the target is using a status move", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') willOWisp = @battle.getMove('Will-O-Wisp') mock = @sandbox.mock(suckerPunch).expects('fail').once() @battle.recordMove(@id2, willOWisp) @battle.determineTurnOrder() @battle.performMove(@p1, suckerPunch) mock.verify() describe 'Grudge', -> it "causes the last move to lose all its PP if the user faints", -> shared.create.call(this) grudge = @battle.getMove("Grudge") tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p2, tackle) @battle.performFaints() @p1.isFainted().should.be.true @p2.pp(tackle).should.equal 0 it "causes the attacker to lose PP any time before the user moves again", -> shared.create.call(this) grudge = @battle.getMove("Grudge") tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.endTurn() @battle.beginTurn() @battle.performMove(@p2, tackle) @battle.performFaints() @p2.pp(tackle).should.equal 0 it "does not cause attacker to lose PP after user moves again", -> shared.create.call(this) grudge = @battle.getMove("Grudge") splash = @battle.getMove('Splash') tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p1, splash) @battle.performMove(@p2, tackle) @battle.performFaints() @p2.pp(tackle).should.not.equal 0 it "does not trigger from natural causes", -> shared.create.call(this) grudge = @battle.getMove("Grudge") splash = @battle.getMove('Splash') leechSeed = @battle.getMove('Leech Seed') @p2.moves = [ leechSeed ] @p2.resetAllPP() @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p2, leechSeed) @battle.endTurn() @p2.pp(leechSeed).should.equal(@p2.maxPP(leechSeed) - 1) describe "Stockpile", -> it "raises def and spdef", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, stockpile) @p1.stages.should.containEql defense: 1, specialDefense: 1 it "cannot raise if stockpile is at its limit", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") for i in [0...Attachment.Stockpile::maxLayers] @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 it "fails if stockpile is at its limit", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") mock = @sandbox.mock(stockpile).expects('fail').once() for i in [0...Attachment.Stockpile::maxLayers] @p1.attach(Attachment.Stockpile) @battle.performMove(@p1, stockpile) mock.verify() describe 'Spit Up', -> it 'fails if user has no stockpiles', -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") mock = @sandbox.mock(spitUp).expects('fail').once() @battle.performMove(@p1, spitUp) mock.verify() it "has 100 base power with 1 layer of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 100 it "has 200 base power with 2 layers of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 200 it "has 300 base power with 3 layers of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 300 it "resets stockpile count to 0", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.get(Attachment.Stockpile).layers.should.equal 1 @battle.performMove(@p1, spitUp) @p1.has(Attachment.Stockpile).should.be.false it "loses def/sp. def according to number of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, spitUp) @p1.stages.should.containEql defense: -2, specialDefense: -2 describe 'Swallow', -> it 'fails if user has no stockpiles', -> shared.create.call(this) swallow = @battle.getMove("Swallow") mock = @sandbox.mock(swallow).expects('fail').once() @battle.performMove(@p1, swallow) mock.verify() it "heals 25% of its HP, rounded half-down, with 1 layer of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal(1 + util.roundHalfDown(@p1.stat('hp') / 4)) it "heals 50% of its HP, rounded half-down, with 2 layers of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal(1 + util.roundHalfDown(@p1.stat('hp') / 2)) it "heals all of its HP with 3 layers of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal @p1.stat('hp') it "resets stockpile count to 0", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.get(Attachment.Stockpile).layers.should.equal 1 @battle.performMove(@p1, swallow) @p1.has(Attachment.Stockpile).should.be.false it "loses def/sp. def according to number of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, swallow) @p1.stages.should.containEql defense: -2, specialDefense: -2 describe 'Rage', -> it "raises the user's attack if hit by a move", -> shared.create.call(this) rage = @battle.getMove('Rage') tackle = @battle.getMove('Tackle') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p2, tackle) @p1.stages.attack.should.equal 1 it "doesn't raise the user's attack if user chooses another move", -> shared.create.call(this) rage = @battle.getMove('Rage') tackle = @battle.getMove('Tackle') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p1, tackle) @battle.performMove(@p2, tackle) @p1.stages.attack.should.equal 0 it "doesn't raise the user's attack if hit by a non-damaging move", -> shared.create.call(this) rage = @battle.getMove('Rage') willOWisp = @battle.getMove('Will-O-Wisp') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p2, willOWisp) @p1.stages.attack.should.equal 0 testRevengeMove = (moveName) -> describe moveName, -> it "doubles base power if hit by an attack that turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.performMove(@p2, tackle) revenge.basePower(@battle, @p1, @p2).should.equal(2 * revenge.power) it "doesn't double base power if not hit by an attack that turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) it "doesn't double base power if hit by a non-damaging move", -> shared.create.call(this) revenge = @battle.getMove(moveName) willOWisp = @battle.getMove("Will-O-Wisp") @battle.performMove(@p2, willOWisp) revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) it "doesn't double base power if hit last turn, but not this turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.performMove(@p2, tackle) @battle.beginTurn() revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) testRevengeMove("Avalanche") testRevengeMove("Revenge") testIgnoreStagesMove = (moveName) -> describe moveName, -> it "ignores the target's defensive and evasive stat stages", -> shared.create.call(this) move = @battle.getMove(moveName) stats = [ 'defense', 'specialDefense', 'evasion' ] values = ( @p2.stat(stat) for stat in stats ) spy = @sandbox.spy(@p2, 'stat') spy.withArgs(stat) for stat in stats @p2.boost(defense: -3, specialDefense: 2, evasion: 6) @battle.performMove(@p1, move) for i in [0...stats.length] stat = stats[i] value = values[i] continue if spy.withArgs(stat).returnValues.length == 0 spy.withArgs(stat).alwaysReturned(value).should.be.true testIgnoreStagesMove("Chip Away") testIgnoreStagesMove("Sacred Sword") describe 'Captivate', -> it 'fails if the user and target are not opposite genders', -> shared.create.call this, team1: [Factory("Magikarp", gender: "M")] team2: [Factory("Magikarp", gender: "M")] captivate = @battle.getMove('Captivate') mock = @sandbox.mock(captivate).expects('fail').once() @battle.performMove(@p1, captivate) mock.verify() it "lowers the target's special attack by 2", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M")] team2: [Factory("Magikarp", gender: "F")] captivate = @battle.getMove('Captivate') @p2.stages.specialAttack.should.equal 0 @battle.performMove(@p1, captivate) @p2.stages.specialAttack.should.equal -2 testStatusCureAttackMove = (moveName, status) -> describe moveName, -> it "doubles base power if the target has #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.attach(status) move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) it "doesn't double if the target doesn't have #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) move.basePower(@battle, @p1, @p2).should.equal(move.power) it "cures the target of #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.attach(status) @p2.has(status).should.be.true @battle.performMove(@p1, move) @p2.hasStatus().should.be.false it "does not cure #{status.name} if the user faints", -> shared.create.call(this, team2: [Factory("Magikarp", ability: "Iron Barbs")]) move = @battle.getMove(moveName) @p1.currentHP = 1 @p2.attach(status) @p2.has(status).should.be.true @battle.performMove(@p1, move) @p2.hasStatus().should.be.true testStatusCureAttackMove("Wake-Up Slap", Status.Sleep) testStatusCureAttackMove("SmellingSalt", Status.Paralyze) describe 'Aqua Ring', -> it "restores 1/16 max HP at the end of each turn", -> shared.create.call(this) aquaRing = @battle.getMove('Aqua Ring') delta = @p1.currentHP >> 4 @p1.currentHP = 1 @battle.performMove(@p1, aquaRing) @p1.currentHP.should.equal(1) @battle.endTurn() @p1.currentHP.should.equal(1 + delta) describe 'Ingrain', -> it "restores 1/16 max HP at the end of each turn", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') delta = @p1.currentHP >> 4 @p1.currentHP = 1 @battle.performMove(@p1, ingrain) @p1.currentHP.should.equal(1) @battle.endTurn() @p1.currentHP.should.equal(1 + delta) it "prevents switching", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') @battle.performMove(@p1, ingrain) @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "prevents self from being phased", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] ingrain = @battle.getMove('Ingrain') whirlwind = @battle.getMove('Whirlwind') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(@team1).expects('switch').never() @battle.performMove(@p2, whirlwind) mock.verify() it "lets self be switched out if using self-switching moves", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') uTurn = @battle.getMove('U-turn') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(@battle).expects('requestActions').once() @battle.performMove(@p1, uTurn) mock.verify() it "makes self vulnerable to Ground moves", -> shared.create.call(this, team1: [ Factory("Gyarados") ]) ingrain = @battle.getMove('Ingrain') uTurn = @battle.getMove('U-turn') @p1.isImmune('Ground').should.be.true @battle.performMove(@p1, ingrain) @p1.isImmune('Ground').should.be.false it "causes Telekinesis to fail", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') telekinesis = @battle.getMove('Telekinesis') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(telekinesis).expects('fail').once() @battle.performMove(@p2, telekinesis) mock.verify() describe "Embargo", -> it "prevents the target's use of items", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) @battle.endTurn() mock.verify() it "lasts 5 turns", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) for i in [0...5] @p2.has(Attachment.Embargo).should.be.true @battle.endTurn() @p2.has(Attachment.Embargo).should.be.false it "prevents the target's use of items in subsequent turns", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) for i in [0...5] @battle.endTurn() @battle.beginTurn() mock.verify() testChargeMove = (moveName, vulnerable) -> describe moveName, -> it "chooses the player's next action for them", -> shared.create.call(this) move = @battle.getMove(moveName) @p1.moves = [ move ] @battle.recordMove(@id1, move) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @battle.requests.should.not.have.property(@id1) should.exist(@battle.getAction(@p1)) it "only spends 1 PP for the entire attack", -> shared.create.call(this) move = @battle.getMove(moveName) @p1.moves = [ move ] @p1.resetAllPP() pp = @p1.pp(move) @battle.recordMove(@id1, move) @battle.continueTurn() @p1.pp(move).should.equal(pp) @battle.beginTurn() @battle.continueTurn() @p1.pp(move).should.equal(pp - 1) it "skips the charge turn if the user is holding a Power Herb", -> shared.create.call this, team1: [Factory("Magikarp", item: "Power Herb")] move = @battle.getMove(moveName) @p1.hasItem("Power Herb").should.be.true mock = @sandbox.mock(move).expects('execute').once() @battle.recordMove(@id1, move) @battle.continueTurn() mock.verify() @p1.hasItem().should.be.false if vulnerable?.length? it "makes target invulnerable to moves", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) clearSmog = @battle.getMove("Clear Smog") @battle.recordMove(@id1, move) @battle.recordMove(@id2, clearSmog) mock = @sandbox.mock(clearSmog).expects('hit').never() @battle.continueTurn() mock.verify() it "makes target invulnerable to moves *after* use", -> shared.create.call this, team2: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() it "is vulnerable to attacks from a No Guard pokemon", -> shared.create.call this, team2: [Factory("Magikarp", ability: "No Guard")] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() it "is vulnerable to attacks if locked on", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Lock-On")) @battle.performMove(@p2, @battle.getMove(moveName)) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() for vulnerableMove in vulnerable it "is vulnerable to #{vulnerableMove}", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) vulnerable = @battle.getMove(vulnerableMove) @battle.recordMove(@id1, move) @battle.recordMove(@id2, vulnerable) mock = @sandbox.mock(vulnerable).expects('hit').once() @battle.continueTurn() mock.verify() else # no vulnerable moves it "doesn't make target invulnerable to moves", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() testChargeMove('Skull Bash') testChargeMove('Razor Wind') testChargeMove('Shadow Force', []) testChargeMove('Ice Burn') testChargeMove('Freeze Shock') testChargeMove('Fly', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down"]) testChargeMove('Bounce', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down"]) # Additional 30% chance to par testChargeMove('Dig', ["Earthquake", "Magnitude"]) testChargeMove('Dive', ["Surf", "Whirlpool"]) testChargeMove('SolarBeam') testChargeMove('Sky Attack') describe "Skull Bash", -> it "raises defense of the user on the charge turn", -> shared.create.call(this) skullBash = @battle.getMove('Skull Bash') @p1.stages.defense.should.equal(0) @battle.performMove(@p1, skullBash) @p1.stages.defense.should.equal(1) describe "Sky Attack", -> it "has a 30% chance to flinch after execution", -> shared.create.call(this) skyAttack = @battle.getMove('Sky Attack') shared.biasRNG.call(this, "randInt", 'flinch', 0) # 100% chance @battle.recordMove(@id1, skyAttack) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.false @battle.beginTurn() @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true for moveName in [ "Gust", "Twister" ] for chargeMoveName in [ "Fly", "Bounce" ] do (moveName, chargeMoveName) -> describe moveName, -> it "deals double damage to Pokemon using #{chargeMoveName}", -> shared.create.call(this) chargeMove = @battle.getMove(chargeMoveName) move = @battle.getMove(moveName) # Make the Pokemon charge @battle.recordMove(@id2, chargeMove) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) for moveName in [ "Surf", "Whirlpool" ] do (moveName) -> describe moveName, -> it "deals double damage to Pokemon using Dive", -> shared.create.call(this) dive = @battle.getMove("Dive") move = @battle.getMove(moveName) # Make the Pokemon charge @battle.recordMove(@id2, dive) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) for moveName in [ "Earthquake", "Magnitude" ] do (moveName) -> describe moveName, -> it "deals double damage to Pokemon using Dig", -> shared.create.call(this) dig = @battle.getMove("Dig") move = @battle.getMove(moveName) power = move.power if moveName == 'Magnitude' power = 50 shared.biasRNG.call(this, 'randInt', 'magnitude', 20) # Make the Pokemon charge @battle.recordMove(@id2, dig) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * power) describe "SolarBeam", -> it "skips the charge turn under Sun", -> shared.create.call(this) solarBeam = @battle.getMove("SolarBeam") @battle.setWeather(Weather.SUN) mock = @sandbox.mock(solarBeam).expects('execute').once() @battle.recordMove(@id1, solarBeam) @battle.continueTurn() mock.verify() for weather in [ Weather.RAIN, Weather.SAND, Weather.HAIL ] do (weather) -> it "halves base power under #{weather}", -> shared.create.call(this) move = @battle.getMove("SolarBeam") @battle.setWeather(weather) move.basePower(@battle, @p1, @p2).should.equal(move.power >> 1) describe "Fury Cutter", -> it "doubles base power after every use, to a max of 160", -> shared.create.call(this) furyCutter = @battle.getMove("Fury Cutter") furyCutter.basePower(@battle, @p1, @p2).should.equal(20) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(40) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(80) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(160) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(160) it "resets to normal base power if using a different move", -> shared.create.call(this) furyCutter = @battle.getMove("Fury Cutter") splash = @battle.getMove("Splash") @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(40) @battle.performMove(@p1, splash) furyCutter.basePower(@battle, @p1, @p2).should.equal(20) describe "Imprison", -> shared.shouldDoNoDamage("Imprison") shared.shouldFailIfUsedTwice("Imprison") it "prevents the opponent from selecting moves that the user knows", -> shared.create.call(this) imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @p2.validMoves().should.eql [ furyCutter, tackle, splash ] @battle.performMove(@p1, imprison) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter ] it "prevents the opponent from executing moves that the user knows", -> shared.create.call(this) imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @battle.performMove(@p1, imprison) mock = @sandbox.mock(tackle).expects('execute').never() @battle.performMove(@p2, tackle) mock.verify() it "lets opponents use moves again after user switches out", -> shared.create.call this, team1: [Factory("Magikarp"), Factory("Magikarp")] imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @battle.performMove(@p1, imprison) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter ] @battle.performSwitch(@team1.first(), 1) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter, tackle, splash ] describe "Present", -> it "has a 40% chance for 40 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .6) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(40).should.be.true it "has a 30% chance for 80 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .3) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(80).should.be.true it "has a 10% chance for 120 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", 0) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(120).should.be.true it "has a 20% chance to heal target by 25% HP, rounded down", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .1) present = @battle.getMove("Present") @p2.currentHP = 1 spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(0).should.be.true @p2.currentHP.should.equal(1 + (@p2.stat('hp') >> 2)) describe "Final Gambit", -> it "faints the user", -> shared.create.call(this) finalGambit = @battle.getMove("Final Gambit") @battle.performMove(@p1, finalGambit) @p1.isFainted().should.be.true it "deals damage equal to the user's HP to the target", -> shared.create.call(this, team2: [Factory("Magikarp", evs: {hp: 4})]) finalGambit = @battle.getMove("Final Gambit") @battle.performMove(@p1, finalGambit) @p2.currentHP.should.equal(1) describe "Lucky Chant", -> shared.shouldDoNoDamage("Lucky Chant") shared.shouldFailIfUsedTwice("Lucky Chant") it "prevents critical hits on the defender's team", -> shared.create.call(this) luckyChant = @battle.getMove("Lucky Chant") stormThrow = @battle.getMove("Storm Throw") @battle.performMove(@p1, luckyChant) stormThrow.isCriticalHit(@battle, @p2, @p1).should.be.false it "lasts 5 turns", -> shared.create.call(this) luckyChant = @battle.getMove("Lucky Chant") @battle.performMove(@p1, luckyChant) for i in [0...5] @team1.has(Attachment.LuckyChant).should.be.true @battle.endTurn() @team1.has(Attachment.LuckyChant).should.be.false describe "Lunar Dance", -> it "faints the user", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") @battle.performMove(@p1, lunarDance) @p1.isFainted().should.be.true it "fails if the user is the last active pokemon", -> shared.create.call(this, team1: [Factory('Magikarp')]) lunarDance = @battle.getMove("Lunar Dance") mock = @sandbox.mock(lunarDance).expects('fail').once() @battle.performMove(@p1, lunarDance) mock.verify() @p1.isFainted().should.be.false it "completely restores the switchin's HP, PP, and status", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") benched = @team1.at(1) benched.attach(Status.Burn) benched.currentHP = 1 benched.setPP(benched.moves[0], 1) @battle.performMove(@p1, lunarDance) @battle.performSwitch(@team1.first(), 1) benched.currentHP.should.equal(benched.stat('hp')) benched.hasStatus().should.be.false for move in benched.moves benched.pp(move).should.equal(benched.maxPP(move)) it "disappears afterward", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") @battle.performMove(@p1, lunarDance) @team1.has(Attachment.LunarDance).should.be.true @battle.performSwitch(@team1.first(), 1) @team1.has(Attachment.LunarDance).should.be.false it "works for 2v2" describe "Healing Wish", -> it "faints the user", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") @battle.performMove(@p1, healingWish) @p1.isFainted().should.be.true it "fails if the user is the last active pokemon", -> shared.create.call(this, team1: [Factory('Magikarp')]) healingWish = @battle.getMove("Healing Wish") mock = @sandbox.mock(healingWish).expects('fail').once() @battle.performMove(@p1, healingWish) mock.verify() @p1.isFainted().should.be.false it "completely restores the switchin's HP and status", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") benched = @team1.at(1) benched.attach(Status.Burn) benched.currentHP = 1 benched.setPP(benched.moves[0], 1) @battle.performMove(@p1, healingWish) @battle.performSwitch(@team1.first(), 1) benched.currentHP.should.equal(benched.stat('hp')) benched.hasStatus().should.be.false it "disappears afterward", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") @battle.performMove(@p1, healingWish) @team1.has(Attachment.HealingWish).should.be.true @battle.performSwitch(@team1.first(), 1) @team1.has(Attachment.HealingWish).should.be.false it "works for 2v2" describe "Last Resort", -> it "fails if the pokemon only has one move", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") @p1.moves = [ lastResort ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() it "works if the pokemon uses all other moves before Last Resort", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] @battle.performMove(@p1, splash) mock = @sandbox.mock(lastResort).expects('afterSuccessfulHit').once() @battle.performMove(@p1, lastResort) mock.verify() it "fails if using all moves, but switches out and back in", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, splash) @battle.performSwitch(@team1.first(), 1) @battle.performMove(@team1.first(), lastResort) @battle.performSwitch(@team1.first(), 1) mock.verify() it "fails if the pokemon does not know Last Resort", -> shared.create.call(this) splash = @battle.getMove("Splash") tackle = @battle.getMove("Tackle") @p1.moves = [ splash, tackle ] lastResort = @battle.getMove("Last Resort") mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() it "fails if the pokemon has not used another move since it was active", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() describe "Assist", -> it "fails if no team member exists", -> shared.create.call this, team1: [ Factory("Magikarp") ] assist = @battle.getMove("Assist") mock = @sandbox.mock(assist).expects('fail').once() @battle.performMove(@p1, assist) mock.verify() it "chooses a team member's move at random", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] assist = @battle.getMove("Assist") move = @team1.at(1).moves[0] shared.biasRNG.call(this, "randInt", "assist", 0) mock = @sandbox.mock(move) mock.expects('execute').once().withArgs(@battle, @p1, [ @p1 ]) @battle.performMove(@p1, assist) mock.verify() it "fails if all team member moves are illegal", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] assist = @battle.getMove("Assist") @team1.at(1).moves = [] @team1.at(1).moves.push @battle.getMove("Assist") @team1.at(1).moves.push @battle.getMove("Bestow") @team1.at(1).moves.push @battle.getMove("Chatter") @team1.at(1).moves.push @battle.getMove("Circle Throw") @team1.at(1).moves.push @battle.getMove("Copycat") @team1.at(1).moves.push @battle.getMove("Counter") @team1.at(1).moves.push @battle.getMove("Covet") @team1.at(1).moves.push @battle.getMove("Destiny Bond") @team1.at(1).moves.push @battle.getMove("Detect") @team1.at(1).moves.push @battle.getMove("Dragon Tail") @team1.at(1).moves.push @battle.getMove("Endure") @team1.at(1).moves.push @battle.getMove("Feint") @team1.at(1).moves.push @battle.getMove("Focus Punch") @team1.at(1).moves.push @battle.getMove("Follow Me") @team1.at(1).moves.push @battle.getMove("Helping Hand") @team1.at(1).moves.push @battle.getMove("Me First") @team1.at(1).moves.push @battle.getMove("Metronome") @team1.at(1).moves.push @battle.getMove("Mimic") @team1.at(1).moves.push @battle.getMove("Mirror Coat") @team1.at(1).moves.push @battle.getMove("Mirror Move") @team1.at(1).moves.push @battle.getMove("Nature Power") @team1.at(1).moves.push @battle.getMove("Protect") @team1.at(1).moves.push @battle.getMove("Rage Powder") @team1.at(1).moves.push @battle.getMove("Sketch") @team1.at(1).moves.push @battle.getMove("Sleep Talk") @team1.at(1).moves.push @battle.getMove("Snatch") @team1.at(1).moves.push @battle.getMove("Struggle") @team1.at(1).moves.push @battle.getMove("Switcheroo") @team1.at(1).moves.push @battle.getMove("Thief") @team1.at(1).moves.push @battle.getMove("Transform") @team1.at(1).moves.push @battle.getMove("Trick") mock = @sandbox.mock(assist).expects('fail').once() @battle.performMove(@p1, assist) mock.verify() describe "Metronome", -> it "chooses a random move to execute", -> shared.create.call(this) @p1.moves = [] metronome = @battle.getMove("Metronome") tackle = @battle.getMove("Tackle") index = @battle.MoveList.indexOf(tackle) shared.biasRNG.call(this, 'randInt', "metronome", index) mock = @sandbox.mock(tackle).expects('execute').once() @battle.performMove(@p1, metronome) mock.verify() it "reselects if chosen an illegal move", -> shared.create.call(this) @p1.moves = [ metronome ] metronome = @battle.getMove("Metronome") technoBlast = @battle.getMove("Techno Blast") tackle = @battle.getMove("Tackle") index = @battle.MoveList.indexOf(technoBlast) reselectIndex = @battle.MoveList.indexOf(tackle) shared.biasRNG.call(this, 'randInt', "metronome", index) shared.biasRNG.call(this, 'randInt', "metronome reselect", reselectIndex) mock = @sandbox.mock(tackle).expects('execute').once() @battle.performMove(@p1, metronome) mock.verify() describe "Magic Coat", -> shared.shouldDoNoDamage("Magic Coat") it "causes certain moves directed at the user to be bounced back", -> shared.create.call(this) whirlwind = @battle.getMove("Whirlwind") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(whirlwind, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, whirlwind) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.true it "bounces back spikes", -> shared.create.call(this) spikes = @battle.getMove("Spikes") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(spikes, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, spikes) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @id2 ).should.be.true @team1.has(Attachment.Spikes).should.be.false @team2.has(Attachment.Spikes).should.be.true it "cannot bounce spikes more than once", -> shared.create.call(this) spikes = @battle.getMove("Spikes") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, magicCoat) (=> @battle.performMove(@p2, spikes) ).should.not.throw(/Maximum call stack size exceeded/) it "does not bounce certain moves back", -> shared.create.call(this) tackle = @battle.getMove("Tackle") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(tackle, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, tackle) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.false it "lasts until the end of the turn", -> shared.create.call(this) magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @p1.has(Attachment.MagicCoat).should.be.true @battle.endTurn() @p1.has(Attachment.MagicCoat).should.be.false it "cannot bounce more than once in the same turn", -> shared.create.call(this) willOWisp = @battle.getMove("Will-O-Wisp") thunderWave = @battle.getMove("Thunder Wave") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, willOWisp) spy = @sandbox.spy(thunderWave, 'execute') @battle.performMove(@p2, thunderWave) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.false it "cannot bounce a certain move more than once in the same turn", -> shared.create.call(this) willOWisp = @battle.getMove("Will-O-Wisp") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, magicCoat) spy = @sandbox.spy(willOWisp, 'execute') (=> @battle.performMove(@p2, willOWisp) ).should.not.throw(/Maximum call stack size exceeded/) spy.calledTwice.should.be.true spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.true spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p2 && targets[0] == @p1 ).should.be.true describe "Telekinesis", -> shared.shouldDoNoDamage("Telekinesis") shared.shouldFailIfUsedTwice("Telekinesis") it "makes the target immune to ground moves", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") @p1.isImmune('Ground').should.be.false @battle.performMove(@p2, telekinesis) @p1.isImmune('Ground').should.be.true it "lasts 3 turns", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p2, telekinesis) for x in [0...3] @p1.isImmune('Ground').should.be.true @battle.endTurn() @p1.isImmune('Ground').should.be.false it "makes the target unable to avoid attacks other than ohko moves", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") inferno = @battle.getMove("Inferno") sheerCold = @battle.getMove("Sheer Cold") inferno.chanceToHit(@battle, @p2, @p1).should.equal(50) sheerCold.chanceToHit(@battle, @p2, @p1).should.equal(30) @battle.performMove(@p2, telekinesis) inferno.chanceToHit(@battle, @p2, @p1).should.equal(0) sheerCold.chanceToHit(@battle, @p2, @p1).should.equal(30) describe "Smack Down", -> it "doesn't crash on secondary effect", -> shared.create.call(this, team2: [ Factory("Gyarados") ]) shared.biasRNG.call(this, "next", "secondary effect", 0) smackDown = @battle.getMove("Smack Down") (=> @battle.performMove(@p1, smackDown)).should.not.throw() it "removes target's Ground immunity", -> shared.create.call(this, team2: [ Factory("Gyarados") ]) smackDown = @battle.getMove("Smack Down") @p2.isImmune("Ground").should.be.true @battle.performMove(@p1, smackDown) @p2.isImmune("Ground").should.be.false it "stops Fly", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") fly = @battle.getMove("Fly") @battle.recordMove(@id1, fly) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.false it "stops Bounce", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") bounce = @battle.getMove("Bounce") @battle.recordMove(@id1, bounce) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.false it "does not stop other charge moves like Dive", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") dive = @battle.getMove("Dive") @battle.recordMove(@id1, dive) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.true it "stops Magnet Rise", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") magnetRise = @battle.getMove("Magnet Rise") @battle.performMove(@p1, magnetRise) @p1.has(Attachment.MagnetRise).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.MagnetRise).should.be.false it "stops Telekinesis", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p2, telekinesis) @p1.has(Attachment.Telekinesis).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Telekinesis).should.be.false it "makes Magnet Rise execution fail", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") magnetRise = @battle.getMove("Magnet Rise") @battle.performMove(@p1, smackDown) mock = @sandbox.mock(magnetRise).expects('fail').once() @battle.performMove(@p2, magnetRise) mock.verify() it "causes Telekinesis execution to fail", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p1, smackDown) mock = @sandbox.mock(telekinesis).expects('fail').once() @battle.performMove(@p1, telekinesis) mock.verify() describe "Echoed Voice", -> it "has 80 base power the second turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) it "has 120 base power the third turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...3] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(120) it "has 160 base power the fourth turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...4] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(160) it "has 200 base power the fifth turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...5] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(200) it "has 200 base power the sixth and above turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...6] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(200) it "resets to 40 base power if nobody uses this move the previous turn", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") splash = @battle.getMove("Splash") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) @battle.performMove(@p1, splash) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(40) it "has the same base power that turn for all users", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") splash = @battle.getMove("Splash") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) echoedVoice.basePower(@battle, @p2, @p1).should.equal(80) it "does not reset even if missing", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) @sandbox.stub(echoedVoice, 'willMiss', -> true) @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(120) describe "Struggle", -> it "deals typless damage", -> shared.create.call(this) struggle = @battle.getMove('Struggle') for type of util.Type util.typeEffectiveness(struggle.type, [type]).should.equal(1) it "deals 25% in recoil to the attacker, rounded down", -> shared.create.call(this) struggle = @battle.getMove('Struggle') hp = @p1.currentHP @p1.currentHP.should.equal @p1.stat('hp') @battle.performMove(@p1, struggle) (hp - @p1.currentHP).should.equal(hp >> 2) describe "Nature Power", -> it "uses Earthquake in Wi-Fi battles", -> shared.create.call(this) naturePower = @battle.getMove('Nature Power') earthquake = @battle.getMove('Earthquake') mock = @sandbox.mock(earthquake).expects('execute').once() .withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, naturePower) mock.verify() testRampageMove = (moveName) -> describe moveName, -> it "lasts 2-3 turns", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p1.has(Attachment.Rampage).should.be.true @battle.endTurn() @battle.performMove(@p1, rampageMove) @battle.endTurn() @p1.has(Attachment.Rampage).should.be.false it "locks the user into that move until execution ends", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) splash = @battle.getMove("Splash") @p1.moves = [ rampageMove, splash ] @p1.resetAllPP() @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.validMoves().should.eql [ rampageMove ] @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.validMoves().should.eql [ rampageMove, splash ] it "blocks switching until execution ends", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.false it "confuses the user after use", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Confusion).should.be.false @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Confusion).should.be.true it "stops immediately if the user's move did not hit", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 3) rampageMove = @battle.getMove(moveName) protect = @battle.getMove("Protect") @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id2, protect) @battle.recordMove(@id1, rampageMove) @battle.continueTurn() @battle.endTurn() @p1.has(Attachment.Rampage).should.be.false testRampageMove("Outrage") testRampageMove("Petal Dance") testRampageMove("Thrash") test2To5MulthitMove = (moveName) -> describe moveName, -> it "deals 2 to 5 hits with a probability distribution of 1/3, 1/3, 1/6, 1/6", -> shared.create.call(this) move = @battle.getMove(moveName) spy = @sandbox.spy(@battle.rng, 'choice') spy = spy.withArgs([2, 2, 3, 3, 4, 5], 'num hits') @battle.performMove(@p1, move) spy.calledOnce.should.be.true it "hits 5 times if the user has Skill Link", -> shared.create.call(this, team1: [Factory('Cloyster', ability: 'Skill Link')]) # try to "trick" the system into giving an invalid result. It should always hit # 5 times regardless of the rng shared.biasRNG.call(this, "choice", 'num hits', 2) shared.biasRNG.call(this, "randInt", 'num hits', 2) move = @battle.getMove(moveName) move.calculateNumberOfHits(@battle, @p1, [ @p2 ]).should.equal(5) it "only hits up until the target Pokemon faints", -> shared.create.call(this, team1: [Factory('Cloyster', ability: 'Skill Link')]) # try to "trick" the system into giving an invalid result. It should always hit # 5 times regardless of the rng shared.biasRNG.call(this, "choice", 'num hits', 3) shared.biasRNG.call(this, "randInt", 'num hits', 3) @p2.currentHP = 1 move = @battle.getMove(moveName) spy = @sandbox.spy(move, 'hit') @battle.performMove(@p1, move) spy.calledOnce.should.be.true test2To5MulthitMove('Arm Thrust') test2To5MulthitMove('Barrage') test2To5MulthitMove('Bone Rush') test2To5MulthitMove('Bullet Seed') test2To5MulthitMove('Comet Punch') test2To5MulthitMove('DoubleSlap') test2To5MulthitMove('Fury Attack') test2To5MulthitMove('Fury Swipes') test2To5MulthitMove('Icicle Spear') test2To5MulthitMove('Pin Missile') test2To5MulthitMove('Rock Blast') test2To5MulthitMove('Spike Cannon') test2To5MulthitMove('Tail Slap') describe "Trick Room", -> it "lasts 5 turns", -> shared.create.call(this) trickRoom = @battle.getMove("Trick Room") @battle.performMove(@p1, trickRoom) for x in [0...5] @battle.has(Attachment.TrickRoom).should.be.true @battle.endTurn() @battle.has(Attachment.TrickRoom).should.be.false it "ends a previous use of Trick Room", -> shared.create.call(this) trickRoom = @battle.getMove("Trick Room") @battle.performMove(@p1, trickRoom) @battle.has(Attachment.TrickRoom).should.be.true @battle.performMove(@p1, trickRoom) @battle.has(Attachment.TrickRoom).should.be.false it "reverses the order that moves are performed in", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) trickRoom = @battle.getMove("Trick Room") splash = @battle.getMove("Splash") @battle.performMove(@p1, trickRoom) @battle.recordMove(@id1, splash) @battle.recordMove(@id2, splash) @battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ] describe "Transform", -> shared.shouldDoNoDamage("Transform") shared.shouldFailIfUsedTwice("Transform") it "fails on a substitute", -> shared.create.call(this) substitute = @battle.getMove("Substitute") transform = @battle.getMove("Transform") @battle.performMove(@p2, substitute) mock = @sandbox.mock(transform).expects('fail').once() @battle.performMove(@p1, transform) mock.verify() it "changes the user's type to match the target's", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.types.should.eql @p2.types it "forces a sprite change", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") mock = @sandbox.mock(@p1).expects('changeSprite').once() @battle.performMove(@p1, transform) mock.verify() it "does not change species or forme", -> shared.create.call(this, team2: [Factory("Latias")]) transform = @battle.getMove("Transform") oldSpecies = @p1.species oldForme = @p1.forme @battle.performMove(@p1, transform) @p1.species.should.equal(oldSpecies) @p1.forme.should.equal(oldForme) it "changes the user's stats to match the target's, except HP", -> shared.create.call(this, team2: [Factory("Celebi", evs: {speed: 252})]) transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) for stat of @p2.baseStats if stat == 'hp' @p1.stat(stat).should.not.equal(@p2.stat(stat)) else @p1.stat(stat).should.equal(@p2.stat(stat)) it "copies the target's gender", -> shared.create.call this, team1: [Factory("Magikarp", gender: "F")] team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.gender.should.equal(@p2.gender) it "copies the target's moveset, setting each PP and max PP to 5", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @p2.boost(attack: 3, speed: -2, accuracy: 1) @battle.performMove(@p1, transform) @p1.moves.should.eql @p2.moves for move in @p1.moves @p1.pp(move).should.equal(5) @p1.maxPP(move).should.equal(5) it "copies the target's stat boosts", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @p2.boost(attack: 3, speed: -2, accuracy: 1) @battle.performMove(@p1, transform) @p1.stages.should.containEql(attack: 3, speed: -2, accuracy: 1) it "copies the target's ability", -> shared.create.call this, team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.hasAbility("Natural Cure").should.be.true it "copies the target's weight", -> shared.create.call this, team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.weight.should.equal(@p2.weight) it "copies the target's gender", -> shared.create.call this, team1: [Factory("Magikarp", gender: "F")] team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.gender.should.equal(@p2.gender) it "restores the original stats after switching out", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure", evs: {speed: 252})] transform = @battle.getMove("Transform") baseStats = _.clone(@p1.baseStats) evs = _.clone(@p1.evs) stats = {} for stat of baseStats stats[stat] = @p1.stat(stat) @battle.performMove(@p1, transform) @p1.baseStats.should.not.eql(baseStats) @p1.evs.should.not.eql(evs) for stat, value of stats @p1.stat(stat).should.not.equal(value) @battle.performSwitch(@p1, 1) @p1.baseStats.should.eql(baseStats) @p1.evs.should.eql(evs) for stat, value of stats @p1.stat(stat).should.equal(value) it "restores the original species and type after switching out", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") species = @p1.species types = _.clone(@p1.types) @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.types.should.eql(types) @p1.species.should.eql(species) it "restores the original ability after switching out", -> # Ditto has a fake ability so we can test abilities being restored. shared.create.call this, team1: [Factory("Ditto", ability: "Sniper"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") ability = @p1.ability @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.ability.should.eql(ability) it "restores original moveset after switch, but Transform PP decreases", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") moves = _.clone(@p1.moves) ppHash = _.clone(@p1.ppHash) maxPPHash = _.clone(@p1.maxPPHash) @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.moves.should.eql(moves) @p1.maxPPHash.should.eql(maxPPHash) # Transform's PP should go down! ppHash[transform.name] -= 1 @p1.ppHash.should.eql(ppHash) it "restores original gender after switch", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") gender = @p1.gender @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.gender.should.eql(gender) it "restores original weight after switch", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") weight = @p1.weight @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.weight.should.eql(weight) it "fails if the target is transformed", -> shared.create.call(this) transform = @battle.getMove("Transform") @battle.performMove(@p2, transform) mock = @sandbox.mock(transform).expects('fail').once() @battle.performMove(@p1, transform) mock.verify() it "fails if the target is under an illusion" it "fails if the user is under an illusion" it "cannot change formes if it has the ability to do so" describe "Fling", -> it "fails if the pokemon has no item", -> shared.create.call(this) fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "fails if the item is not removeable", -> shared.create.call this, team1: [Factory("Magikarp", item: "Acro Bike")] fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "fails if the user is blocked from using items", -> shared.create.call this, team1: [Factory("Magikarp", item: "Armor Fossil")] fling = @battle.getMove("Fling") @p1.blockItem() mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "has a base power depending on the item held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Armor Fossil")] fling = @battle.getMove("Fling") fling.beforeTurn(@battle, @p1) @p1.beforeMove(fling, @p1, [@p2]) fling.basePower(@battle, @p1, @p2).should.equal(100) it "inflicts Burn on the target if Flame Orb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Flame Orb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Burn).should.be.true it "inflicts Toxic on the target if Toxic Orb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Toxic Orb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Toxic).should.be.true it "flinches the target if King's Rock is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "King's Rock")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true it "flinches the target if Razor Fang is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Razor Fang")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true it "paralyzes the target if Light Ball is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Light Ball")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Paralyze).should.be.true it "removes negative status effects if Mental Herb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Mental Herb")] fling = @battle.getMove("Fling") @p2.attach(Attachment.Torment) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Torment).should.be.false it "removes negative stat boosts if White Herb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "White Herb")] fling = @battle.getMove("Fling") @p2.boost(attack: 1, accuracy: -2) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.stages.should.containEql(attack: 1, accuracy: 0) it "inflicts Poison on the target if Poison Barb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Barb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Poison).should.be.true it "causes target to eat the flung berry if a berry is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.stages.speed.should.equal(1) it "does not activate an item effect when hitting a substitute", -> shared.create.call this, team1: [Factory("Magikarp", item: "Toxic Orb")] fling = @battle.getMove("Fling") @p2.attach(Attachment.Substitute, hp: 1) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Toxic).should.be.false it "loses the user's item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Barb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p1.hasItem().should.be.false it "loses the item even if execution is canceled by protect", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Herb")] protect = @battle.getMove("Protect") fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('hit').never() @battle.recordMove(@id2, protect) @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() @p1.hasItem().should.be.false describe "Bug Bite", -> it "eats the target's berry and gets its effects", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry")] bugBite = @battle.getMove("Bug Bite") @battle.performMove(@p1, bugBite) @p2.hasItem().should.be.false @p1.stages.should.containEql(speed: 1) it "does eat the target's berry if the target fainted", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry")] bugBite = @battle.getMove("Bug Bite") @p2.currentHP = 1 @battle.performMove(@p1, bugBite) @p2.isFainted().should.be.true @p1.stages.should.containEql(speed: 1) it "does not eat the target's berry if the user fainted", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry", ability: "Iron Barbs")] bugBite = @battle.getMove("Bug Bite") @p1.currentHP = 1 @battle.performMove(@p1, bugBite) @p1.isFainted().should.be.true @p2.hasItem().should.be.true describe "Beat Up", -> it "deals 1 less hit for each unhealthy member in the user's party", -> shared.create.call this, team1: (Factory("Magikarp") for i in [0...6]) @team1.at(5).attach(Status.Paralyze) @team1.at(1).faint() beatUp = @battle.getMove("Beat Up") mock = @sandbox.mock(beatUp).expects('hit').exactly(4) @battle.performMove(@p1, beatUp) mock.verify() it "has 5 + X/10 base power for X in team, where X is base attack", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Scyther"), Factory("Celebi"), Factory("Totodile"), Factory("Rayquaza"), Factory("Seedot") ] beatUp = @battle.getMove("Beat Up") spy = @sandbox.spy(beatUp, "basePower") @battle.performMove(@p1, beatUp) for pokemon in @team1.pokemon basePower = 5 + Math.floor(pokemon.baseStats.attack / 10) spy.returned(basePower).should.be.true it "works for teams smaller than 6", -> shared.create.call this, team1: (Factory("Magikarp") for i in [0...4]) beatUp = @battle.getMove("Beat Up") mock = @sandbox.mock(beatUp).expects('hit').exactly(4) @battle.performMove(@p1, beatUp) mock.verify() it "doesn't crash if all pokemon are statused or fainted", -> shared.create.call this, team1: (Factory("Magikarp") for i in [0...2]) @team1.at(1).faint() @team1.at(0).attach(Status.Burn) beatUp = @battle.getMove("Beat Up") (=> @battle.performMove(@p1, beatUp) ).should.not.throw() it "doesn't crash when used by a pokemon with technician", -> shared.create.call(this, team1: [Factory("Magikarp", ability: "Technician")]) beatUp = @battle.getMove("Beat Up") (=> @battle.performMove(@p1, beatUp) ).should.not.throw() describe "Psycho Shift", -> it "fails if the user doesn't have a status", -> shared.create.call(this) psychoShift = @battle.getMove("Psycho Shift") mock = @sandbox.mock(psychoShift).expects('fail').once() @battle.performMove(@p1, psychoShift) mock.verify() it "fails if the target already has a status", -> shared.create.call(this) @p1.attach(Status.Toxic) @p2.attach(Status.Paralyze) psychoShift = @battle.getMove("Psycho Shift") mock = @sandbox.mock(psychoShift).expects('fail').once() @battle.performMove(@p1, psychoShift) mock.verify() it "cures the user of its status", -> shared.create.call(this) @p1.attach(Status.Poison) psychoShift = @battle.getMove("Psycho Shift") @battle.performMove(@p1, psychoShift) @p1.hasStatus().should.be.false it "gives the user's former status to the target", -> shared.create.call(this) @p1.attach(Status.Burn) psychoShift = @battle.getMove("Psycho Shift") @battle.performMove(@p1, psychoShift) @p2.has(Status.Burn).should.be.true describe "Gravity", -> shared.shouldDoNoDamage("Gravity") shared.shouldFailIfUsedTwice("Gravity") it "raises accuracy of all attacks by 5/3", -> shared.create.call(this) gravity = @battle.getMove("Gravity") focusBlast = @battle.getMove("Focus Blast") @battle.performMove(@p1, gravity) accuracy = focusBlast.chanceToHit(@battle, @p1, @p2) accuracy.should.equal Math.floor(focusBlast.accuracy * 5 / 3) it "lasts 5 turns", -> shared.create.call(this) gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) for i in [0...5] @battle.has(Attachment.Gravity).should.be.true @battle.endTurn() @battle.has(Attachment.Gravity).should.be.false it "makes Flying Pokemon no longer immune to Ground", -> shared.create.call(this) @p2.types = [ "Flying" ] @p2.isImmune("Ground").should.be.true gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) @p2.isImmune("Ground").should.be.false it "makes Levitating Pokemon no longer immune to Ground", -> shared.create.call(this, team2: [Factory("Magikarp", ability: "Levitate")]) @p2.isImmune("Ground").should.be.true gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) @p2.isImmune("Ground").should.be.false it "deals damage to Flying Pokemon", -> shared.create.call(this) @p2.types = [ "Flying" ] gravity = @battle.getMove("Gravity") earthquake = @battle.getMove("Earthquake") earthquake.typeEffectiveness(@battle, @p1, @p2).should.equal(0) @battle.performMove(@p1, gravity) earthquake.typeEffectiveness(@battle, @p1, @p2).should.equal(1) # TODO: Sky Drop for moveName in [ "Bounce", "Fly" ] do (moveName) -> it "grounds pokemon using #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @battle.recordMove(@id2, move) @battle.continueTurn() @p2.has(Attachment.Charging).should.be.true @battle.recordMove(@id1, gravity) @battle.continueTurn() @p2.has(Attachment.Charging).should.be.false it "removes Telekinesis", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") gravity = @battle.getMove("Gravity") @battle.performMove(@p1, telekinesis) @p2.has(Attachment.Telekinesis).should.be.true @battle.performMove(@p1, gravity) @p2.has(Attachment.Telekinesis).should.be.false it "removes Magnet Rise", -> shared.create.call(this) magnetRise = @battle.getMove("Magnet Rise") gravity = @battle.getMove("Gravity") @battle.performMove(@p2, magnetRise) @p2.has(Attachment.MagnetRise).should.be.true @battle.performMove(@p1, gravity) @p2.has(Attachment.MagnetRise).should.be.false for moveName in [ "Jump Kick", "Hi Jump Kick", "Bounce", "Fly", "Sky Drop", "Splash", "Telekinesis" ] do (moveName) -> it "disables #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @p1.moves = [ move ] @p2.moves = [ move ] @battle.performMove(@p1, gravity) @battle.beginTurn() @p1.validMoves().should.not.containEql(move) @p2.validMoves().should.not.containEql(move) it "prevents the execution of #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) mock = @sandbox.mock(move).expects('execute').never() @battle.performMove(@p2, move) mock.verify() testDelayedAttackMove = (moveName, type) -> describe moveName, -> shared.shouldFailIfUsedTwice(moveName) it "waits three turns before attacking", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) for x in [0...3] @p2.currentHP.should.equal @p2.stat('hp') @battle.endTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not initialize and error if the target has fainted", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.faint() (=> @battle.performMove(@p1, move)).should.not.throw() it "does not hit if the target has fainted", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) for x in [0...2] @battle.endTurn() @p2.faint() mock = @sandbox.mock(move).expects('hit').never() @battle.endTurn() mock.verify() it "is considered a direct attack", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.attach(Attachment.Substitute, hp: 1) @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Substitute).should.be.true @battle.endTurn() @p2.has(Attachment.Substitute).should.be.false it "can target multiple positions" testDelayedAttackMove("Future Sight") testDelayedAttackMove("Doom Desire") describe "Baton Pass", -> it "fails if there is no benched pokemon to BP to", -> shared.create.call(this, team1: [Factory('Magikarp')]) batonPass = @battle.getMove("Baton Pass") mock = @sandbox.mock(batonPass).expects('fail').once() @battle.performMove(@p1, batonPass) mock.verify() it "switches to another pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @battle.performMove(@p1, batonPass) @battle.requests.should.have.property @id1 it "passes certain attachments to the next pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @p1.attach(Attachment.Ingrain) @p1.attach(Attachment.Torment) @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().has(Attachment.Torment).should.be.false @team1.first().has(Attachment.Ingrain).should.be.true it "continues Perish Song's counter", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") perishSong = @battle.getMove("Perish Song") @battle.performMove(@p1, perishSong) for i in [0...3] @battle.endTurn() @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().isFainted().should.be.false @battle.endTurn() @team1.first().isFainted().should.be.true it "passes status boosts to the next pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @p1.boost(attack: 1, evasion: -3) @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().stages.should.containEql(attack: 1, evasion: -3) describe "Thunder Wave", -> it "is affected by immunities", -> shared.create.call(this) thunderWave = @battle.getMove("Thunder Wave") @p2.types = [ 'Ground' ] @battle.performMove(@p1, thunderWave) @p2.has(Status.Paralyze).should.be.false describe "Thunder", -> it "has 50% accuracy in Sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(50) it "has perfect accuracy in Rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Hurricane", -> it "has 50% accuracy in Sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(50) it "has perfect accuracy in Rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Blizzard", -> it "has perfect accuracy in Hail", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) blizzard = @battle.getMove("Blizzard") blizzard.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) blizzard = @battle.getMove("Blizzard") blizzard.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Sleep Talk", -> it "fails if the pokemon is awake", -> shared.create.call(this) sleepTalk = @battle.getMove("Sleep Talk") mock = @sandbox.mock(sleepTalk).expects('fail').once() @battle.performMove(@p1, sleepTalk) mock.verify() it "performs a random move when the pokemon is asleep", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ tackle, sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) spy = @sandbox.spy(@battle, 'executeMove') @battle.performMove(@p1, sleepTalk) spy.calledWith(tackle).should.be.true it "does not choose sleep talk or other moves", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") assist = @battle.getMove("Assist") @p1.moves = [ sleepTalk, assist, tackle ] @p1.resetAllPP() @p1.attach(Status.Sleep) spy = @sandbox.spy(@battle, 'executeMove') @battle.performMove(@p1, sleepTalk) spy.calledWith(tackle).should.be.true it "fails if there are no viable moves", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) mock = @sandbox.mock(sleepTalk).expects('fail').once() @battle.performMove(@p1, sleepTalk) mock.verify() it "changes the move's target properly", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ tackle, sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) mock = @sandbox.mock(tackle) mock.expects('execute').once().withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, sleepTalk) mock.verify() describe "Rest", -> it "fails if the pokemon is at full HP", -> shared.create.call(this) rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(@p1.stat('hp')) @battle.performMove(@p1, rest) mock.verify() it "restores the pokemon to full HP otherwise", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @battle.performMove(@p1, rest) @p1.currentHP.should.equal @p1.stat('hp') it "sleeps the pokemon", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @p1.has(Status.Sleep).should.be.false @battle.performMove(@p1, rest) @p1.has(Status.Sleep).should.be.true it "fails if the pokemon is already asleep", -> shared.create.call(this) rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(1) @p1.attach(Status.Sleep) # execute instead of perform to avoid beforeMove callbacks. @battle.executeMove(rest, @p1, [ @p1 ]) mock.verify() it "cures the pokemon of adverse status effects", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @p1.attach(Status.Burn) @p1.has(Status.Burn).should.be.true @battle.performMove(@p1, rest) @p1.has(Status.Sleep).should.be.true @p1.has(Status.Burn).should.be.false it "always forces sleep turns to be 2", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", "sleep turns", 3) rest = @battle.getMove("Rest") @p1.setHP(1) @battle.performMove(@p1, rest) attachment = @p1.get(Status.Sleep) should.exist(attachment) attachment.should.have.property("turns") attachment.turns.should.equal(2) it "fails if the Pokemon cannot be slept", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Vital Spirit")] rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(1) @battle.performMove(@p1, rest) mock.verify() describe "Defog", -> it "lowers target's evasion by 1", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, defog) @p2.stages.should.containEql(evasion: -1) it "removes Reflect on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Reflect")) @p2.team.has(Attachment.Reflect).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Reflect).should.be.false it "removes Light Screen on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Light Screen")) @p2.team.has(Attachment.LightScreen).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.LightScreen).should.be.false it "removes Spikes on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Spikes")) @p2.team.has(Attachment.Spikes).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Spikes).should.be.false it "removes Stealth Rock on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @p2.team.has(Attachment.StealthRock).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.StealthRock).should.be.false it "removes Toxic Spikes on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @p2.team.has(Attachment.ToxicSpikes).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.ToxicSpikes).should.be.false it "removes Safeguard on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Safeguard")) @p2.team.has(Attachment.Safeguard).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Safeguard).should.be.false it "removes Mist on target's side" describe "Refresh", -> it "fails if the Pokemon has no status", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") mock = @sandbox.mock(refresh).expects('fail').once() @battle.performMove(@p1, refresh) mock.verify() it "restores a Pokemon's status", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") @p1.attach(Status.Burn) @p1.has(Status.Burn).should.be.true @battle.performMove(@p1, refresh) @p1.has(Status.Burn).should.be.false it "sends a message about status being restored", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") @p1.attach(Status.Burn) spy = @sandbox.spy(@battle, 'message') @battle.performMove(@p1, refresh) spy.args.join(',').should.containEql("#{@p1.name} healed its burn!") describe "Growth", -> it "boosts the pokemon's stats", -> shared.create.call(this, gen: 'bw') @battle.setWeather(Weather.SUN) @battle.performMove(@p1, @battle.getMove('Growth')) @p1.stages.should.containEql attack: 2, specialAttack: 2 describe "Reflect Type", -> it "copies the target's types", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Charmander")]) @battle.performMove(@p1, @battle.getMove('Reflect Type')) @p1.types.should.containEql "Fire" it "fails if the user has multitype", -> shared.create.call(this, team1: [Factory("Arceus", ability: "Multitype")], team2: [Factory("Toxicroak")]) @battle.performMove(@p1, @battle.getMove('Reflect Type')) @p1.types.should.containEql "Normal" describe "Retaliate", -> it "doubles in power if a pokemon on the user's side fainted last turn", -> shared.create.call this, team1: [Factory("Magikarp"), Factory("Slaking")] @p2.currentHP = 1 @battle.beginTurn() @battle.recordMove(@id1, @battle.getMove("Aqua Jet")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() retaliate = @battle.getMove("Retaliate") spy = @sandbox.spy(retaliate, 'basePower') @battle.performMove(@p2, retaliate) spy.returned(140).should.be.true it "deals normal damage otherwise", -> shared.create.call(this) retaliate = @battle.getMove("Retaliate") spy = @sandbox.spy(retaliate, 'basePower') @battle.performMove(@p1, retaliate) spy.returned(70).should.be.true describe "Role Play", -> it "copies the target's ability", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Magikarp", ability: "Levitate")] @battle.performMove(@p1, @battle.getMove('Role Play')) @p1.hasAbility("Levitate").should.be.true it "does not copy certain abilities", -> shared.create.call this, team1: [Factory("Magikarp"), ability: "Swift Swim"] team2: [Factory("Arceus", ability: "Multitype")] @battle.performMove(@p1, @battle.getMove('Role Play')) @p1.hasAbility("Multitype").should.be.false describe "Relic Song", -> it "transforms Meloetta", -> shared.create.call this, team1: [Factory("Meloetta")] team2: [Factory("Arceus")] @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("pirouette") @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("default") it "changes Meloetta to default forme after switching out", -> shared.create.call this, team1: [Factory("Meloetta"), Factory("Magikarp")] team2: [Factory("Arceus")] @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("pirouette") @battle.performSwitch(@p1, 1) @battle.performSwitch(@team1.first(), 1) @p1.forme.should.equal("default") it "does not transform Pokemon that are not Meloetta", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Magikarp")] @p1.forme.should.equal("default") @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("default") describe "Safeguard", -> it "protects the user's team from status", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Safeguard")) @battle.performMove(@p2, @battle.getMove("Thunder Wave")) @p1.has(Status.Paralyze).should.be.false it "protects the user's team from confusion", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Safeguard")) @battle.performMove(@p2, @battle.getMove("Confuse Ray")) @p1.has(Attachment.Confusion).should.be.false it "doesn't protect against status inflicted by the user", -> shared.create.call(this) @p1.team.attach(Attachment.Safeguard) @p1.setHP(1) @battle.performMove(@p1, @battle.getMove("Rest")) @p1.has(Status.Sleep).should.be.true it "protects against yawn being inflicted", -> shared.create.call(this) @p1.team.attach(Attachment.Safeguard) @battle.performMove(@p2, @battle.getMove("Yawn")) @p1.has(Attachment.Yawn).should.be.false it "doesn't prevent yawn's effect", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Yawn')) @battle.endTurn() @p2.has(Status.Sleep).should.be.false @p2.team.attach(Attachment.Safeguard) @battle.endTurn() @p2.has(Status.Sleep).should.be.true describe "Soak", -> it "changes the target's type to Water", -> shared.create.call this, team1: [Factory("Magikarp")] team2: [Factory("Smeargle")] @p2.types.should.not.eql ['Water'] @battle.performMove(@p1, @battle.getMove('Soak')) @p2.types.should.eql ['Water'] it "does not affect pure Water type Pokemon", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Magikarp")] @p2.types.should.eql ['Water'] soak = @battle.getMove("Soak") mock = @sandbox.mock(soak).expects('fail').once() @battle.performMove(@p1, soak) mock.verify() it "does not affect Arceus", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus")] soak = @battle.getMove("Soak") mock = @sandbox.mock(soak).expects('fail').once() @battle.performMove(@p1, soak) mock.verify() describe 'Electro Ball', -> it 'has variable base power based on speed of user and target', -> shared.create.call this, team1: [Factory('Electrode', evs: {speed: 252}, nature: "Timid")] team2: [Factory('Smeargle')] move = @battle.getMove('Electro Ball') move.basePower(@battle, @p1, @p2).should.equal 80 describe "Snore", -> it "fails if the pokemon is awake", -> shared.create.call(this) snore = @battle.getMove("Snore") mock = @sandbox.mock(snore).expects('fail').once() @battle.performMove(@p1, snore) mock.verify() it "attacks the target when the user is asleep", -> shared.create.call this, snore = @battle.getMove("Snore") @p1.attach(Status.Sleep) mock = @sandbox.mock(snore).expects('hit').once() @battle.performMove(@p1, snore) mock.verify() describe "Worry Seed", -> it "changes the target's ability to Insomnia", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Magikarp", ability: "Swift Swim")] @battle.performMove(@p1, @battle.getMove('Worry Seed')) @p2.hasAbility("Insomnia").should.be.true it "does not change some abilities", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus", ability: "Multitype")] worrySeed = @battle.getMove("Worry Seed") mock = @sandbox.mock(worrySeed).expects('fail').once() @battle.performMove(@p1, worrySeed) mock.verify() describe "Simple Beam", -> it "changes the target's ability to Simple", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Magikarp", ability: "Swift Swim")] @battle.performMove(@p1, @battle.getMove('Simple Beam')) @p2.hasAbility("Simple").should.be.true it "does not change some abilities", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus", ability: "Multitype")] simpleBeam = @battle.getMove("Simple Beam") mock = @sandbox.mock(simpleBeam).expects('fail').once() @battle.performMove(@p1, simpleBeam) mock.verify() describe "Entrainment", -> it "copies the user's ability to the target", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Smeargle", ability: "Own Tempo")] @battle.performMove(@p1, @battle.getMove('Entrainment')) @p2.hasAbility("Swift Swim").should.be.true it "does not copy some abilities", -> shared.create.call this, team1: [Factory("Arceus", ability: "Multitype")] team2: [Factory("Magikarp", ability: "Swift Swim")] entrainment = @battle.getMove("Entrainment") mock = @sandbox.mock(entrainment).expects('fail').once() @battle.performMove(@p1, entrainment) mock.verify() describe "Natural Gift", -> it "changes power and type depending on the berry held by the user", -> shared.create.call this, team1: [Factory("Smeargle", item: 'Liechi Berry')] team2: [Factory("Magikarp")] move = @battle.getMove('Natural Gift') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(80) move.typeEffectiveness(@battle, @p1, @p2).should.equal(2) it "only works with certain items", -> shared.create.call this, team1: [Factory("Smeargle", item: 'Leftovers')] naturalGift = @battle.getMove('Natural Gift') mock = @sandbox.mock(naturalGift).expects('fail').once() @battle.performMove(@p1, naturalGift) mock.verify() it "should remove the item even if missing" describe "False Swipe", -> it "leaves the target with at least 1 HP", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("False Swipe")) @p2.currentHP.should.equal 1 it "does normal damage if the target has a substitute", -> shared.create.call(this) @p2.currentHP = 1 @p2.attach(Attachment.Substitute) falseSwipe = @battle.getMove("False Swipe") spy = @sandbox.spy(falseSwipe, 'calculateDamage') @battle.performMove(@p1, falseSwipe) spy.returned(0).should.be.false describe "Gastro Acid", -> it "suppresses the target's ability", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Gastro Acid")) @p2.has(Attachment.AbilitySuppress).should.be.true @p2.isAbilityBlocked().should.be.true it "continues turn by turn", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Gastro Acid")) @battle.endTurn() @battle.beginTurn() @p2.has(Attachment.AbilitySuppress).should.be.true @p2.isAbilityBlocked().should.be.true it "fails against some abilities", -> shared.create.call(this, team2: [Factory("Arceus", ability: "Multitype")]) gastroAcid = @battle.getMove("Gastro Acid") mock = @sandbox.mock(gastroAcid).expects('fail').once() @battle.performMove(@p1, gastroAcid) mock.verify() describe "Helping Hand", -> it "fails if there is no target", -> shared.create.call(this) helpingHand = @battle.getMove("Helping Hand") mock = @sandbox.mock(helpingHand).expects('fail').once() @battle.performMove(@p1, helpingHand) mock.verify() describe "Skill Swap", -> it "swaps the user's ability with the target's", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Smeargle", ability: "Own Tempo")] @battle.performMove(@p1, @battle.getMove('Skill Swap')) @p1.hasAbility("Own Tempo").should.be.true @p2.hasAbility("Swift Swim").should.be.true it "cannot swap some abilities", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Shedinja", ability: "Wonder Guard")] skillSwap = @battle.getMove("Skill Swap") mock = @sandbox.mock(skillSwap).expects('fail').once() @battle.performMove(@p1, skillSwap) mock.verify() it "cannot swap the abilities if they are the same", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Magikarp", ability: "Swift Swim")] skillSwap = @battle.getMove("Skill Swap") mock = @sandbox.mock(skillSwap).expects('fail').once() @battle.performMove(@p1, skillSwap) mock.verify() it "activates abilities after swapping", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Gyarados", ability: "Intimidate")] @battle.performMove(@p1, @battle.getMove('Skill Swap')) @p1.hasAbility("Intimidate").should.be.true @p2.hasAbility("Swift Swim").should.be.true @p2.stages.should.containEql(attack: -1) describe "Heal Block", -> it "lasts 5 turns", -> shared.create.call(this) healBlock = @battle.getMove("Heal Block") @battle.performMove(@p1, healBlock) for x in [0...5] @p2.has(Attachment.HealBlock).should.be.true @battle.endTurn() @p2.has(Attachment.HealBlock).should.be.false it 'prevents the target from executing a healing move', -> shared.create.call(this, team1: [ Factory('Magikarp', evs: {speed: 4}) ]) move = @battle.getMove('Recover') healBlock = @battle.getMove('Heal Block') mock = @sandbox.mock(move) mock.expects('execute').never() @battle.performMove(@p1, healBlock) @battle.performMove(@p2, move) mock.verify() it 'prevents the target from selecting a healing move', -> shared.create.call this, team2: [Factory("Magikarp", moves: [ "Splash", "Recover" ])] @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.beginTurn() requestedMoves = @battle.requestFor(@p2).moves requestedMoves.should.not.containEql 'Recover' it "prevents Abilities that heal from healing", -> shared.create.call this, team2: [Factory("Magikarp", ability: "Water Absorb")] @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @battle.performMove(@p1, @battle.getMove('Water Gun')) @p2.currentHP.should.equal 1 it "does not prevent Regenerator from healing", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Regenerator")] @p1.currentHP = 1 @battle.performMove(@p2, @battle.getMove('Heal Block')) @p1.switchOut(@battle) hp = Math.floor(@p1.stat('hp') / 3) @p1.currentHP.should.equal(1 + hp) it "prevents items that heal from healing", -> shared.create.call this, team2: [Factory("Magikarp", item: "Leftovers")] @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @p2.currentHP.should.equal 1 it "prevents Berries that heal from attempting to activate", -> shared.create.call this, team2: [Factory("Magikarp", item: "Sitrus Berry")] item = @p2.item hp = @p2.currentHP @p2.currentHP >>= 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @battle.performMove(@p1, @battle.getMove('Tackle')) @p2.currentHP.should.be.lessThan hp >> 1 @p2.item.should.equal item describe "Recycle", -> it "restores the user's last used item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] @p1.useItem() @battle.performMove(@p1, @battle.getMove("Recycle")) @p1.hasItem("Salac Berry").should.be.true it "fails if the user has an item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p1, recycle) @p1.hasItem("Salac Berry").should.be.true mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "fails if the user has no last used item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Air Balloon")] recycle = @battle.getMove("Recycle") @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.hasItem("Air Balloon").should.be.false mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "cannot restore an item that was forcefully removed", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] recycle = @battle.getMove("Recycle") @battle.performMove(@p2, @battle.getMove("Covet")) @p1.hasItem("Salac Berry").should.be.false @p2.hasItem("Salac Berry").should.be.true mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "can restore the last used item if the current item is forcefully removed", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] team2: [Factory("Magikarp", item: "Figy Berry")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p2, @battle.getMove("Trick")) @p1.hasItem("Figy Berry").should.be.true @battle.performMove(@p2, @battle.getMove("Knock Off")) @battle.performMove(@p1, recycle) @p1.hasItem("Salac Berry").should.be.true it "cannot restore the last used item if it was restored and forcefully removed", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p1, recycle) @p1.hasItem("Salac Berry").should.be.true @battle.performMove(@p2, @battle.getMove("Knock Off")) mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify()
27476
require '../helpers' {Attachment, Status} = require('../../server/bw/attachment') {Battle} = require('../../server/bw/battle') {Pokemon} = require('../../server/bw/pokemon') {Weather} = require('../../shared/weather') {Move} = require('../../server/bw/move') util = require '../../server/bw/util' {Protocol} = require '../../shared/protocol' {Factory} = require '../factory' should = require 'should' {_} = require 'underscore' shared = require '../shared' describe 'Move:', -> # Test every single move for their primary effects. shared.testEveryMove(Battle::MoveList, 'bw') it "multiplies critical hits by 2x", -> Move::criticalMultiplier.should.equal(2) it 'takes the name as the first parameter', -> new Move('Smooth Move').name.should.equal 'Smooth Move' it 'should have a priority of 0 by default', -> new Move().priority.should.equal 0 it 'can change the default priority', -> new Move(null, priority: -1).priority.should.equal -1 it 'should have a type of ??? by default', -> new Move().type.should.equal '???' it 'can change the default type', -> new Move(null, type: 'Grass').type.should.equal 'Grass' describe 'critical hit level', -> it "is 1 by default", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 1 it "can be changed from the default", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.activate() new Move(null, criticalHitLevel: 2) .criticalHitLevel(battle, attacker, defender).should.equal 2 it "is 3 if the attacker has Focus Energy", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.attach(Attachment.FocusEnergy) attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 it "is 3 if the attacker is Farfetch'd with a Stick", -> battle = new Battle('1', []) attacker = new Pokemon(species: "Far<NAME>'d", item: 'Stick') defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 it "is 3 if the attacker is <NAME>sey with a Lucky Punch", -> battle = new Battle('1', []) attacker = new Pokemon(species: "<NAME>", item: 'Lucky Punch') defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 for item in ["Razor Claw", "Scope Lens"] do (item) -> it "is 2 if the attacker has a #{item}", -> battle = new Battle('1', []) attacker = new Pokemon(item: item) defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 2 describe "a critical hit", -> it "occurs when the RNG output < the critical hit level", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() move = new Move() @sandbox.stub(move, 'criticalHitLevel', -> 3) @sandbox.stub(battle.rng, 'next', -> 0.2) move.isCriticalHit(battle, attacker, defender).should.be.true it "does not occur when the RNG output >= the critical hit level", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() @sandbox.stub(battle.rng, 'next', -> 0.0700) new Move().isCriticalHit(battle, attacker, defender).should.be.false it "ignores opponent defensive boosts", -> shared.create.call(this) defense = @p2.stat('defense') specialDefense = @p2.stat('specialDefense') @p1.crit = true @p2.boost(defense: 1, specialDefense: 2) move = new Move(null, damage: 'physical') move.pickDefenseStat(@p1, @p2).should.equal(defense) move = new Move(null, damage: 'special') move.pickDefenseStat(@p1, @p2).should.equal(specialDefense) it "does not ignore opponent defensive drops", -> shared.create.call(this) defense = @p2.stat('defense') specialDefense = @p2.stat('specialDefense') @p1.crit = true @p2.boost(defense: -1, specialDefense: -2) move = new Move(null, damage: 'physical') move.pickDefenseStat(@p1, @p2).should.equal Math.floor(2 / 3 * defense) move = new Move(null, damage: 'special') move.pickDefenseStat(@p1, @p2).should.equal(specialDefense >> 1) it "ignores user stat drops", -> shared.create.call(this) attack = @p1.stat('attack') specialAttack = @p1.stat('specialAttack') @p1.crit = true @p1.boost(attack: -1, specialAttack: -2) move = new Move(null, damage: 'physical') move.pickAttackStat(@p1, @p2).should.equal(attack) move = new Move(null, damage: 'special') move.pickAttackStat(@p1, @p2).should.equal(specialAttack) it "does not ignore user stat boosts", -> shared.create.call(this) attack = @p1.stat('attack') specialAttack = @p1.stat('specialAttack') @p1.crit = true @p1.boost(attack: 1, specialAttack: 2) move = new Move(null, damage: 'physical') move.pickAttackStat(@p1, @p2).should.equal Math.floor(1.5 * attack) move = new Move(null, damage: 'special') move.pickAttackStat(@p1, @p2).should.equal(2 * specialAttack) it "does not carry over in multihit moves", -> shared.create.call(this) move = new Move("multihit", minHits: 4, maxHits: 4, power: 20) # Crit only once move.isCriticalHit = -> move.isCriticalHit = -> false true mock = @sandbox.mock(@p2).expects('informCriticalHit').once() move.execute(@battle, @p1, [ @p2 ]) mock.verify() describe "-1 crit ratios", -> beforeEach -> @battle = new Battle('1', []) @attacker = new Pokemon() @move = new Move("TestMove", criticalHitLevel: -1) @sandbox.stub(@battle.rng, 'next', -> 1) it "fails if the defender has Battle Armor", -> defender = new Pokemon(ability: 'Battle Armor') @move.isCriticalHit(@battle, @attacker, defender).should.be.false it "fails if the defender has Shell Armor", -> defender = new Pokemon(ability: 'Shell Armor') @move.isCriticalHit(@battle, @attacker, defender).should.be.false it "always succeeds if opponent does not have Battle or Shell Armor", -> defender = new Pokemon() @move.isCriticalHit(@battle, @attacker, defender).should.be.true describe 'type effectiveness', -> testTypeEffectiveness = (type, defense, expected) -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() defender.types = defense move = new Move(null, type: type) move.typeEffectiveness(battle, attacker, defender).should.equal expected it 'is 0 if the enemy has an immunity to the type', -> testTypeEffectiveness('Ground', ['Electric', 'Flying'], 0) it 'is 1 if the enemy is neutral to the type', -> testTypeEffectiveness('Ground', ['Normal'], 1) it 'is 2 if the enemy is weak to the type', -> testTypeEffectiveness('Ground', ['Electric'], 2) it 'is 4 if the enemy is extra weak to the type', -> testTypeEffectiveness('Rock', ['Fire', 'Flying'], 4) it 'is 1/2 if the enemy is resistant to the type', -> testTypeEffectiveness('Fire', ['Fire', 'Flying'], .5) it 'is 1/4 if the enemy is extra resistant to the type', -> testTypeEffectiveness('Fire', ['Fire', 'Water'], .25) describe "#burnCalculation", -> it "returns 1 normally", -> attacker = new Pokemon() new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal 1 it "returns .5 with a physical move, no Guts ability, and a burned user", -> attacker = new Pokemon() attacker.attach(Status.Burn) new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal .5 it "returns 1 with a special move, no Guts ability, and a burned user", -> attacker = new Pokemon() attacker.attach(Status.Burn) new Move(null, damage: 'special') .burnCalculation(attacker).should.equal 1 it "returns 1 with a physical move, Guts ability, and a burned user", -> attacker = new Pokemon(ability: "Guts") attacker.attach(Status.Burn) new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal 1 describe 'an attack with 0 accuracy', -> it 'can never miss', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(accuracy: 0).willMiss(battle, a, d).should.be.false describe 'accuracy and evasion boosts', -> it 'heighten and lower the chances of a move hitting', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(null, accuracy: 100).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = 3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = 3 d.stages.evasion = 3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 50 it 'keeps heightening and lowering chances when negative', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(null, accuracy: 100).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = -3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 25 a.stages.accuracy = -3 d.stages.evasion = -3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 50 describe '#hasFlag', -> it 'returns true if a move has a specific flag', -> new Move(null, flags: ['superman', 'batman']) .hasFlag('batman').should.be.true it "returns false if a move doesn't have a specific flag", -> new Move(null, flags: ['superman', 'batman']) .hasFlag('catwoman').should.be.false describe '#execute', -> it 'calls hit multiple times for multihit moves', -> shared.create.call(this) move = new Move("multihit", minHits: 4, maxHits: 4) mock = @sandbox.mock(move).expects('hit').exactly(4) move.execute(@battle, @p1, [@p2]) mock.verify() it 'only hits up until user faints', -> shared.create.call(this, team2: [Factory('Ferrothorn', ability: 'Iron Barbs')]) move = new Move("multihit", minHits: 4, maxHits: 4, flags: ["contact"]) mock = @sandbox.mock(move).expects('hit').exactly(1) @p1.currentHP = 1 move.execute(@battle, @p1, [@p2]) mock.verify() it 'only hits up until user falls asleep', -> shared.create.call(this, team2: [Factory('Shroomish', ability: 'Effect Spore')]) shared.biasRNG.call(this, "randInt", 'effect spore', 4) # Never trigger move = new Move("multihit", minHits: 4, maxHits: 4, flags: ["contact"]) hit = move.hit times = 0 @sandbox.stub move, 'hit', => times++ if times == 2 shared.biasRNG.call(this, "randInt", 'effect spore', 1) # Sleep else shared.biasRNG.call(this, "randInt", 'effect spore', 4) # Nothing hit.apply(move, arguments) @p1.currentHP = 1 move.execute(@battle, @p1, [@p2]) times.should.equal(2) describe "#use", -> it "returns false if the target's type is immune", -> shared.create.call(this) move = new Move("attacking", damage: "special", type: "Normal") @p2.types = [ "Ghost" ] move.use(@battle, @p1, @p2).should.be.false it "returns true if target is immune but move is non-damaging", -> shared.create.call(this) move = new Move("attacking", damage: "non-damaging", type: "Normal") @p2.types = [ "Ghost" ] should.not.exist move.use(@battle, @p1, @p2) describe '#hit', -> it "deals damage no higher than the pokemon's remaining HP", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Tackle")) @p2.currentHP.should.equal(0) it "deals normal damage if the Pokemon has a substitute", -> shared.create.call(this) spy = @sandbox.spy(@p2, 'damage') @p2.currentHP = (@p2.currentHP >> 2) + 1 @battle.performMove(@p2, @battle.getMove("Substitute")) @battle.performMove(@p1, @battle.getMove("Tackle")) spy.returned(1).should.be.false describe '#weatherModifier', -> it "is 0x1800 when the move is Fire-type and the weather is sunny", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1800) it "is 0x800 when the move is Fire-type and the weather is rainy", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x800) it "is 0x1800 when the move is Water-type and the weather is rainy", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = new Move(null, type: "Water") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1800) it "is 0x1800 when the move is Water-type and the weather is sunny", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = new Move(null, type: "Water") move.weatherModifier(@battle, @p1, @p2).should.equal(0x800) it "is 0x1000 otherwise", -> shared.create.call(this) @battle.setWeather(Weather.SAND) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1000) describe "#baseDamage", -> it "reduces damage by ~1.5 if the weather is sandstorm", -> shared.create.call(this) @p2.types = [ "Rock" ] move = new Move(null, power: 50, type: "Fire", damage: 'special') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.be.lessThan(damage) it "doesn't apply the sandstorm effect if target isn't Rock-type", -> shared.create.call(this) @p2.types = [ "Ground" ] move = new Move(null, power: 50, type: "Fire", damage: 'special') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.equal(damage) it "doesn't apply the sandstorm effect if move is non-special", -> shared.create.call(this) @p2.types = [ "Rock" ] move = new Move(null, power: 50, type: "Fire", damage: 'physical') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.equal(damage) describe "BW Moves:", -> describe "Splash", -> shared.shouldDoNoDamage('Splash') describe 'a multi-hit move', -> it 'potentially activates Berries after each hit', -> shared.create.call this, team1: [Factory('Magikarp', item: "Sitrus Berry", ability: "Skill Link")] team2: [Factory('Magikarp', item: "Sitrus Berry", ability: "Iron Barbs")] hp = @p1.currentHP @p1.currentHP = (hp >> 1) + 1 @p2.currentHP = 4 move = @battle.getMove('Tail Slap') @sandbox.stub(move, 'calculateDamage', -> 1) @battle.performMove(@p1, move) @p1.currentHP.should.equal (hp >> 1) + 1 - (5 * (hp >> 3)) + (hp >> 2) @p2.currentHP.should.equal 4 + (hp >> 2) - 5 describe 'jump kick attacks', -> it 'has 50% recoil if it misses', -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'miss', 100) oldHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Hi Jump Kick')) (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) it "has 50% recoil if the target is immune", -> shared.create.call(this, team2: [Factory("G<NAME>ar")]) oldHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Hi Jump Kick')) (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) it "has 50% recoil if the target protects itself", -> shared.create.call(this) oldHP = @p1.stat('hp') @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove("Hi Jump Kick")) @battle.continueTurn() (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) describe 'a drain attack', -> it 'recovers a percentage of the damage dealt, rounded down', -> shared.create.call this, team1: [Factory('Conkeldurr')] team2: [Factory('Hitmonchan')] startHP = 1 @p1.currentHP = startHP hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Drain Punch')) damage = (hp - @p2.currentHP) (@p1.currentHP - startHP).should.equal Math.ceil(damage / 2) it 'cannot recover to over 100% HP', -> shared.create.call this, team1: [Factory('Conkeldur<NAME>')] team2: [Factory('Hit<NAME>')] hp = @p1.currentHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Drain Punch')) (@p1.currentHP - hp).should.equal 0 it "does not recover more than the damage dealt", -> shared.create.call(this) drainPunch = @battle.getMove('Drain Punch') @sandbox.stub(drainPunch, 'baseDamage', -> 9999) @p2.currentHP = 2 @p1.currentHP = 1 @battle.performMove(@p1, drainPunch) @p2.currentHP.should.be.lessThan(1) @p1.currentHP.should.equal(2) describe 'weight-based attacks', -> it 'has 80 base power if the pokemon is 50.2kg', -> shared.create.call this, team1: [Factory('Celebi')] team2: [Factory('<NAME>')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Grass Knot')) (hp - @p2.currentHP).should.equal 94 it 'has 120 base power if the pokemon is >200kg', -> shared.create.call this, team1: [Factory('Celebi')] team2: [Factory('Gyarados')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Grass Knot')) (hp - @p2.currentHP).should.equal 153 describe 'a pokemon using a primary boosting move', -> it "doesn't do damage if base power is 0", -> shared.create.call this, team1: [Factory('Gyarados')] team2: [Factory('Hit<NAME>chan')] @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @p2.currentHP.should.equal @p2.stat('hp') it "boosts the pokemon's stats", -> shared.create.call this, team1: [Factory('<NAME>')] team2: [Factory('Hit<NAME>')] @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @p1.stages.should.containEql attack: 1, speed: 1 it "affects type-immune pokemon", -> shared.create.call this, team1: [Factory('<NAME>')] team2: [Factory('G<NAME>')] @battle.performMove(@p1, @battle.getMove('Growl')) @p2.stages.attack.should.equal -1 it "has the boosts removed on switch", -> shared.create.call(this, team1: (Factory("<NAME>") for x in [1..2])) @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @battle.performSwitch(@p1, 1) @p1.stages.should.containEql(attack: 0, speed: 0) describe 'a pokemon using a damaging move that also boosts stats on hit', -> it "deals damage and boosts stats", -> shared.create.call this, team1: [Factory('<NAME>')] team2: [Factory('G<NAME>ados')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Leaf Storm')) @p1.stages.specialAttack.should.equal -2 (hp - @p2.currentHP).should.equal 178 describe 'Low Sweep', -> it "lowers the target's speed by 1", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.equal(-1) it "does not lower the target's speed by 1 if the target faints", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.not.equal(-1) it "does not lower the target's speed by 1 if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute) @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.not.equal(-1) describe 'Flame Charge', -> it "raises the user's speed by 1", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) it "raises the user's speed by 1 even if the target faints", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) it "raises the user's speed by 1 even if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute) @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) describe 'a pokemon using a move with a secondary boosting effect', -> it "has a chance to activate", -> shared.create.call this, team1: [Factory('Mew')] team2: [Factory('Hitmonchan')] shared.biasRNG.call(this, "next", 'secondary boost', 0) # 100% chance attack = @p1.stat('attack') speed = @p1.stat('speed') @battle.performMove(@p1, @battle.getMove('AncientPower')) @p1.stages.should.containEql { attack: 1, defense: 1, speed: 1, specialAttack: 1, specialDefense: 1 } describe 'a pokemon using Acrobatics', -> it 'gets double the base power without an item', -> shared.create.call this, team1: [Factory('<NAME>')] team2: [Factory('<NAME>')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Acrobatics')) damage = (hp - @p2.currentHP) damage.should.equal 36 it 'has normal base power with an item', -> shared.create.call this, team1: [Factory('<NAME>', item: '<NAME>')] team2: [Factory('<NAME>')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Acrobatics')) damage = (hp - @p2.currentHP) damage.should.equal 18 testRecoilMove = (moveName) -> describe "a pokemon using #{moveName}", -> it 'receives a percentage of the damage rounded half up', -> shared.create.call(this) startHP = @p1.currentHP hp = @p2.currentHP move = @battle.getMove(moveName) @battle.performMove(@p1, move) recoil = -move.recoil / 100 damage = (hp - @p2.currentHP) (startHP - @p1.currentHP).should.equal Math.round(damage * recoil) it 'receives a minimum of 1 HP of recoil', -> shared.create.call(this) startHP = @p1.currentHP hp = @p2.currentHP move = @battle.getMove(moveName) stub = @sandbox.stub(move, 'calculateDamage', -> .6) move = @battle.getMove(moveName) @battle.performMove(@p1, move) damage = (hp - @p2.currentHP) (startHP - @p1.currentHP).should.equal 1 it "does not recoil if no damage was dealt", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove(moveName)) @battle.continueTurn() @p1.currentHP.should.equal(@p1.stat('hp')) testRecoilMove("Brave Bird") testRecoilMove("Double-Edge") testRecoilMove("Flare Blitz") testRecoilMove("Head Charge") testRecoilMove("Head Smash") testRecoilMove("Submission") testRecoilMove("Take Down") testRecoilMove("Volt Tackle") testRecoilMove("Wild Charge") testRecoilMove("Wood Hammer") testDrainMove = (moveName) -> describe moveName, -> it "absorbs a percentage of the damage rounded up", -> shared.create.call(this) @p1.currentHP = 1 move = @battle.getMove(moveName) @battle.performMove(@p1, move) drain = move.recoil / 100 damage = (@p2.stat('hp') - @p2.currentHP) (@p1.currentHP - 1).should.equal Math.ceil(damage * drain) it 'receives a minimum of 1 HP of drain', -> shared.create.call(this) @p1.currentHP = @p2.currentHP = 1 move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p1.currentHP.should.equal(2) it "does not drain if no damage was dealt", -> shared.create.call(this) @p1.currentHP = 1 @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove(moveName)) @battle.continueTurn() @p1.currentHP.should.equal(1) testDrainMove("Absorb") testDrainMove("Drain Punch") testDrainMove("Giga Drain") testDrainMove("Horn Leech") testDrainMove("Leech Life") testDrainMove("Mega Drain") describe 'Haze', -> shared.shouldDoNoDamage('Haze') it 'removes all status boosts from each pokemon', -> shared.create.call(this) # Create artificial boosts. @p1.stages.attack = 2 @p1.stages.evasion = -1 @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Haze")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p1.stages.should.eql neutralBoosts @p2.stages.should.eql neutralBoosts describe 'Seismic Toss and Night Shade', -> it 'does exactly the same damage as their level', -> shared.create.call this, team1: [Factory('Blissey')] team2: [Factory('Mew')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Seismic Toss')) (hp - @p2.currentHP).should.equal 100 it 'triggers Focus Sash', -> shared.create.call this, team1: [Factory('Blissey')] team2: [Factory('Mew', level: 1, item: "Focus Sash")] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Seismic Toss')) @p2.currentHP.should.equal(1) describe 'Psywave', -> it 'does user.level/2 damage minimum', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] shared.biasRNG.call(this, "randInt", 'psywave', 5) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 50 it 'does user.level * 1.5 damage maximum', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] move = @battle.getMove('Psywave') shared.biasRNG.call(this, "randInt", 'psywave', 15) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 150 it 'rounds down to the nearest .1 multiplier', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] move = @battle.getMove('Psywave') shared.biasRNG.call(this, "randInt", 'psywave', 6.09) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 60 describe 'facade', -> it 'doubles the base power if burned, poisoned, or paralyzed', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('<NAME>ikarp')] hp = @p2.currentHP @p1.attach(Status.Paralyze) move = @battle.getMove('Facade') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) describe 'reversal and flail', -> it 'have 200 base power at 1 hp', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('Magikarp')] @p1.currentHP = 1 move = @battle.getMove('Flail') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal 200 it 'have 40 base power at 50% hp', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('Magikarp')] @p1.currentHP = Math.floor(@p1.stat('hp') / 2) move = @battle.getMove('Flail') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal 40 describe 'eruption and water spout', -> beforeEach -> shared.create.call this, team1: [Factory('Cam<NAME>')] team2: [Factory('Mew')] @attacker = @p1 @defender = @p2 @move = @battle.getMove('Eruption') it 'has at least one base power', -> @attacker.currentHP = 1 @move.basePower(@battle, @attacker, @defender).should.equal 1 it 'has 75 base power at 50% hp', -> @attacker.currentHP = @attacker.stat('hp') / 2 @move.basePower(@battle, @attacker, @defender).should.equal 75 it 'has 150 base power at 100% hp', -> @move.basePower(@battle, @attacker, @defender).should.equal 150 describe 'gyro ball', -> it 'has 150 base power maximum', -> shared.create.call this, team1: [Factory('Forretress', ivs: {speed: 0})] team2: [Factory('Jolteon', evs: {speed: 252}, nature: "Timid")] move = @battle.getMove('Gyro Ball') attacker = @p1 defender = @p2 attacker.stages.speed = -6 move.basePower(@battle, attacker, defender).should.equal 150 it 'has variable base power based on speed of target and user', -> shared.create.call this, team1: [Factory('Electrode', evs: {speed: 252}, nature: "Jolly")] team2: [Factory('Magikarp', ivs: {speed: 0})] move = @battle.getMove('Gyro Ball') attacker = @p1 defender = @p2 attacker.stages.speed = -6 move.basePower(@battle, attacker, defender).should.equal 40 describe 'brine', -> it 'has normal base power if the target has over 50% HP', -> shared.create.call this, team1: [Factory('Empoleon')] team2: [Factory('<NAME>')] move = @battle.getMove('Brine') @p2.currentHP = Math.floor(@p2.currentHP / 2) + 1 move.basePower(@battle, @p1, @p2).should.equal 65 it 'doubles base power if the target has 50% or less HP', -> shared.create.call this, team1: [Factory('Empoleon')] team2: [Factory('<NAME>')] move = @battle.getMove('Brine') @p2.currentHP = Math.floor(@p2.currentHP / 2) move.basePower(@battle, @p1, @p2).should.equal 130 describe 'Disable', -> shared.shouldDoNoDamage('Disable') it 'gives the disabled attachment', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @p2.has(Attachment.Disable).should.be.true it "prevents the target's last move from being selected", -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @battle.beginTurn() @p2.validMoves().should.not.containEql(move) @p2.validMoves().should.have.length(@p2.moves.length - 1) it 'wears off after 4 turns', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @battle.endTurn() @battle.endTurn() @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Disable).should.be.false it 'stops the execution of a disabled move', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) mock = @sandbox.mock(move).expects('execute').never() @battle.performMove(@p2, move) mock.verify() it 'fails if the target has not moved since it was active', -> shared.create.call(this) disable = @battle.getMove("Disable") mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p1, disable) mock.verify() it 'fails if the target does not know the move it used', -> shared.create.call(this) disable = @battle.getMove("Disable") struggle = @battle.getMove("Struggle") mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p2, struggle) @battle.performMove(@p1, disable) mock.verify() it "fails if the target's last move has 0 PP", -> shared.create.call(this) disable = @battle.getMove("Disable") splash = @battle.getMove("Splash") @battle.performMove(@p2, splash) @p2.setPP(splash, 0) mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p1, disable) mock.verify() describe 'hidden power', -> it 'has a max power of 70', -> ivs = { hp: 31, attack: 31, defense: 31, specialAttack: 31, specialDefense: 31, speed: 31 } shared.create.call this, team1: [Factory('Mag<NAME>', ivs: ivs)] team2: [Factory('Magikarp')] move = @battle.getMove('Hidden Power') move.basePower(@battle, @p1, @p2).should.eql 70 it 'has a min power of 30', -> ivs = { hp: 0, attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0 } shared.create.call this, team1: [Factory('<NAME>', ivs: ivs)] team2: [Factory('Magik<NAME>')] move = @battle.getMove('Hidden Power') move.basePower(@battle, @p1, @p2).should.eql 30 it 'is dark when all ivs are 31', -> ivs = { hp: 31, attack: 31, defense: 31, specialAttack: 31, specialDefense: 31, speed: 31 } shared.create.call this, team1: [Factory('<NAME>', ivs: ivs)] team2: [Factory('<NAME>')] move = @battle.getMove('Hidden Power') move.getType(@battle, @p1, @p2).should.eql 'Dark' it 'is fighting when all ivs are 0', -> ivs = { hp: 0, attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0 } shared.create.call this, team1: [Factory('<NAME>', ivs: ivs)] team2: [Factory('<NAME>')] move = @battle.getMove('Hidden Power') move.getType(@battle, @p1, @p2).should.eql 'Fighting' describe 'yawn', -> shared.shouldDoNoDamage('Yawn') shared.shouldFailIfUsedTwice("Yawn") it 'gives the yawn attachment', -> shared.create.call this, team1: [Factory('Cam<NAME>upt')] team2: [Factory('<NAME>')] @battle.performMove(@p1, @battle.getMove('Yawn')) @p2.has(Attachment.Yawn).should.be.true it 'puts the opponent to sleep at the end of the second turn', -> shared.create.call this, team1: [Factory('<NAME>')] team2: [Factory('<NAME>')] @battle.performMove(@p1, @battle.getMove('Yawn')) @battle.endTurn() @p2.has(Status.Sleep).should.be.false @battle.endTurn() @p2.has(Status.Sleep).should.be.true it "fails if the target already is statused", -> shared.create.call(this) yawn = @battle.getMove('Yawn') mock = @sandbox.mock(yawn).expects('fail').once() @p2.attach(Status.Paralyze) @battle.performMove(@p1, yawn) mock.verify() describe 'an OHKO move', -> it 'ignores accuracy/evasion modifiers', -> shared.create.call(this) @p1.stages.accuracy = -6 @p2.stages.evasion = 6 acc = @battle.getMove('Sheer Cold').chanceToHit(@battle, @p1, @p2) acc.should.equal 30 it "does damage equal to the target's total hp", -> shared.create.call this, team1: [Factory('<NAME>')] team2: [Factory('<NAME>')] @p2.currentHP = Math.floor(@p2.stat('hp') / 2) @controller.makeMove(@id1, 'Sheer Cold') @controller.makeMove(@id2, 'Splash') move = @battle.getMove('Sheer Cold') damage = move.calculateDamage(@battle, @p1, @p2) damage.should.equal @p2.stat('hp') describe 'a recovery move', -> shared.shouldDoNoDamage('Recover') it "recovers 50% of the target's HP, rounded half up", -> shared.create.call(this) hp = @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Softboiled')) recoverHP = Math.round(@p1.stat('hp') / 2) (@p1.currentHP - hp).should.equal recoverHP it "fails if the user's HP is full", -> shared.create.call(this) softboiled = @battle.getMove('Softboiled') mock = @sandbox.mock(softboiled).expects('fail').once() @battle.performMove(@p1, softboiled) mock.verify() describe 'Knock Off', -> it "deals damage", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.currentHP.should.be.lessThan @p2.stat('hp') it "removes the target's item", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) should.not.exist @p2.item it "does not remove unremovable items", -> shared.create.call this, team2: [Factory('Magikarp', item: "Air Mail")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "does not knock off items from pokemon with Sticky Hold", -> shared.create.call this, team2: [Factory('Magikarp', ability: "Sticky Hold", item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "takes damage from Rocky Helmet", -> shared.create.call this, team2: [Factory('Magikarp', item: "Rocky Helmet")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.false @p1.currentHP.should.be.lessThan(@p1.stat('hp')) it "doesn't knock off if substitute fades", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "doesn't knock off if user is fainted", -> shared.create.call this, team2: [Factory('Magikarp', item: "Rocky Helmet")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true @p1.isFainted().should.be.true it 'removes healing Berries before they can activate', -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "<NAME> Berry")] @p2.currentHP = 2 move = @battle.getMove('Knock Off') @sandbox.stub(move, 'calculateDamage', -> 1) @battle.performMove(@p1, move) @p2.currentHP.should.equal 1 describe 'trick and switcheroo', -> shared.shouldDoNoDamage('Trick') it "isn't affected by type-immunities", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Stick')] team2: [Factory('Drapion', item: "Leftovers")] item1 = @p1.item item2 = @p2.item trick = @battle.getMove('Trick') @battle.performMove(@p1, trick) @p2.item.should.equal item1 @p1.item.should.equal item2 it "swaps the target and user's item", -> shared.create.call this, team1: [Factory('<NAME>', item: 'Stick')] team2: [Factory('Magik<NAME>', item: "Leftovers")] item1 = @p1.item item2 = @p2.item @controller.makeMove(@id1, 'Trick') @controller.makeMove(@id2, 'Splash') @p2.item.should.equal item1 @p1.item.should.equal item2 it "fails if the user has Sticky Hold", -> shared.create.call this, team1: [Factory('<NAME>', ability: "Sticky Hold", item: 'Stick')] team2: [Factory('<NAME>', item: "Leftovers")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has Sticky Hold", -> shared.create.call this, team1: [Factory('<NAME>', item: 'Stick')] team2: [Factory('<NAME>', ability: "Sticky Hold", item: "Leftovers")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "succeeds if only one pokemon has an item", -> shared.create.call this, team1: [Factory('<NAME>', item: 'Stick')] team2: [Factory('<NAME>')] trick = @battle.getMove('Trick') item1 = @p1.item @battle.performMove(@p1, trick) should.not.exist(@p1.item) @p2.item.should.equal(item1) it "fails if neither the user nor the target has an item", -> shared.create.call this, team1: [Factory('<NAME>')] team2: [Factory('<NAME>')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is holding a Mail", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Air Mail')] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is holding a Mail", -> shared.create.call this, team1: [Factory('Alakazam')] team2: [Factory('Magikarp', item: 'Air Mail')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is Giratina-O", -> shared.create.call this, team1: [Factory('Giratina', forme: "origin")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is Giratina-O", -> shared.create.call this, team2: [Factory('Giratina', forme: "origin")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has a Substitute", -> shared.create.call(this) trick = @battle.getMove('Trick') substitute = @battle.getMove('Substitute') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p2, substitute) @battle.performMove(@p1, trick) mock.verify() it "fails if the user has Multitype with a plate item", -> shared.create.call this, team1: [Factory('Magikarp', ability: "Multitype", item: "Grass Plate")] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has Multitype with a plate item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', ability: "Multitype", item: "Grass Plate")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is Genesect with a Drive item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Genesect', item: "Burn Drive")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is Genesect with a Drive item", -> shared.create.call this, team1: [Factory('Genesect', item: "Burn Drive")] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() describe 'memento', -> shared.shouldDoNoDamage('Memento') it "faints the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Memento")) @p1.isFainted().should.be.true it "reduces the attack and special attack of the target by two stages", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.containEql attack: -2, specialAttack: -2 it "doesn't reduce stats if target is protected, and doesn't faint user", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove("Memento")) @battle.continueTurn() @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.false it "doesn't reduce stats if target has a substitute, and doesn't faint user", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Substitute")) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.false it "doesn't reduce stats if target has Clear Body, but faints user", -> shared.create.call(this, team2: [Factory('Magikarp', ability: 'Clear Body')]) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.true describe 'magnitude', -> it "has variable base power", -> shared.create.call this, team1: [Factory('D<NAME>')] team2: [Factory('<NAME>ik<NAME>')] move = @battle.getMove('Magnitude') shared.biasRNG.call(this, "randInt", 'magnitude', 50) move.basePower(@battle, @p1, @p2).should.equal 70 describe 'Pain Split', -> it "doesn't make a pokemon's HP go over their max", -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @controller.makeMove(@id1, 'Pain Split') @controller.makeMove(@id1, 'Seismic Toss') @p1.currentHP.should.equal @p1.stat('hp') it "averages user and target current HP", -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @p1.currentHP = 2 @controller.makeMove(@id1, 'Pain Split') @controller.makeMove(@id2, 'Seismic Toss') @p1.currentHP.should.equal Math.min(326, @p1.stat('hp')) @p2.currentHP.should.equal Math.min(326, @p2.stat('hp')) it "affects Ghosts", -> shared.create.call this, team2: [Factory('Gengar')] painSplit = @battle.getMove("Pain Split") mock = @sandbox.mock(painSplit).expects('hit').once() @battle.performMove(@p1, painSplit) mock.verify() it "is blocked by Protect", -> shared.create.call(this) @p1.currentHP = 1 painSplit = @battle.getMove("Pain Split") mock = @sandbox.mock(painSplit).expects('hit').never() @battle.recordMove(@id1, painSplit) @battle.determineTurnOrder() @battle.performMove(@p2, @battle.getMove("Protect")) @battle.performMove(@p1, painSplit) mock.verify() @p1.currentHP.should.equal(1) @p2.currentHP.should.equal(@p2.stat('hp')) describe 'Belly Drum', -> shared.shouldDoNoDamage('Belly Drum') it "maximizes attack", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @p1.stages.attack = -6 @controller.makeMove(@id1, 'Belly Drum') @controller.makeMove(@id2, 'Splash') @p1.stages.attack.should.equal 6 it "cuts the pokemon's HP by half", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @controller.makeMove(@id1, '<NAME>') @controller.makeMove(@id2, 'Splash') hp = @p1.stat('hp') (hp - @p1.currentHP).should.equal Math.floor(hp / 2) it "fails if the pokemon's HP is less than half", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] hp = @p1.currentHP = Math.floor(@p1.stat('hp') / 2) - 1 @controller.makeMove(@id1, '<NAME>') @controller.makeMove(@id2, 'Splash') @p1.currentHP.should.equal hp @p1.stages.attack.should.equal 0 it "fails if the pokemon's attack is already maximized", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @p1.boost(attack: 12) bd = @battle.getMove('<NAME>') mock = @sandbox.mock(bd).expects('fail').once() @battle.performMove(@p1, bd) mock.verify() @p1.currentHP.should.equal(@p1.stat('hp')) describe 'acupressure', -> shared.shouldDoNoDamage('Acupressure') it "raises a random stat that can be raised", -> shared.create.call this, team1: [Factory('Shuckle')] team2: [Factory('Magikarp')] stages = _.clone(@p1.stages) @controller.makeMove(@id1, 'Acupressure') @controller.makeMove(@id2, 'Splash') @p1.stages.should.not.eql stages it "fails if the Pokemon has maximum stats", -> shared.create.call this, team1: [Factory('Shuckle')] team2: [Factory('Magikarp')] @p1.stages.attack = 6 @p1.stages.defense = 6 @p1.stages.specialAttack = 6 @p1.stages.specialDefense = 6 @p1.stages.accuracy = 6 @p1.stages.evasion = 6 mock = @sandbox.mock(@p2) mock.expects('boost').never() @controller.makeMove(@id1, 'Acupressure') @controller.makeMove(@id2, 'Splash') mock.verify() describe 'Dragon Rage', -> it 'always does 40 damage', -> shared.create.call(this) move = @battle.getMove('Dragon Rage') move.calculateDamage(@battle, @p1, @p2).should.equal 40 describe 'SonicBoom', -> it 'always does 20 damage', -> shared.create.call(this) sonicBoom = @battle.getMove('SonicBoom') sonicBoom.calculateDamage(@battle, @p1, @p2).should.equal 20 describe 'explosion moves', -> it 'faints the user', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @battle.performMove(@p1, @battle.getMove('Explosion')) @p1.isFainted().should.be.true it 'faints the user even if enemy is immune', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Gengar')] @battle.performMove(@p1, @battle.getMove('Explosion')) @p1.isFainted().should.be.true it 'fails if an active Pokemon has Damp', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Politoed', ability: 'Damp')] explosion = @battle.getMove('Explosion') mock = @sandbox.mock(explosion).expects('fail').once() @battle.performMove(@p1, explosion) mock.verify() describe 'endeavor', -> it "brings the target's hp down to the user's hp", -> shared.create.call(this) hp = 4 @p1.currentHP = hp @battle.performMove(@p1, @battle.getMove('Endeavor')) @p2.currentHP.should.equal hp it "fails if the target's hp is less than the user's hp", -> shared.create.call(this) move = @battle.getMove('Endeavor') mock = @sandbox.mock(move).expects('fail').once() @p2.currentHP = hp = 4 @battle.performMove(@p1, move) mock.verify() it "doesn't hit ghost pokemon", -> shared.create.call this, team1: [Factory('Politoed')] team2: [Factory('Gengar')] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Endeavor')) @p2.currentHP.should.equal @p2.stat('hp') describe 'a thief move', -> it "should steal the target's item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.item.should.equal item2 should.not.exist @p2.item it "should not steal the target's item if it has none", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp')] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item should.not.exist @p2.item it "should not steal the target's item if user already has an item", -> shared.create.call this, team1: [Factory('Magikarp', item: "Stick")] team2: [Factory('Magikarp', item: "Leftovers")] item1 = @p1.item item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.item.should.equal item1 @p2.item.should.equal item2 it "should not steal the target's item if target has Sticky Hold", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers", ability: "Sticky Hold")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal target's item if target has Multitype and a plate", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Draco Plate", ability: "Multitype")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if the target has no item", -> shared.create.call(this) item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.hasItem().should.be.false @p2.hasItem().should.be.false it "should not steal the target's item if target is Giratina-O", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Giratina', forme: "origin", item: "Griseous Orb")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if target is Genesect with Drive", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Genesect', item: "Burn Drive")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if target holds Mail", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Air Mail")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if user is fainted", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers", ability: "Iron Barbs")] item2 = @p2.item @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 describe 'crush grip', -> it 'has a base power of 1 minimum', -> shared.create.call(this) move = @battle.getMove('Crush Grip') @p2.currentHP = 1 move.basePower(@battle, @p1, @p2).should.equal 1 it 'has a base power of 121 maximum', -> shared.create.call(this) move = @battle.getMove('Crush Grip') @p2.currentHP = @p2.stat('hp') move.basePower(@battle, @p1, @p2).should.equal 121 describe 'hex', -> it 'doubles the base power if target is burned, poisoned, or paralyzed', -> shared.create.call(this) move = @battle.getMove('Hex') @p2.attach(Status.Paralyze) move.basePower(@battle, @p1, @p2).should.equal 100 describe 'heavy slam and heat crash', -> it 'has variable base power based on the difference in weight', -> shared.create.call(this) move = @battle.getMove('Heavy Slam') move.basePower(@battle, @p1, @p2).should.equal 40 move.basePower(@battle, @p1, calculateWeight: -> -1000).should.equal 120 describe 'a status cure move', -> it 'heals the entire team of status effects', -> shared.create.call this, team1: [Factory('Magikarp'), Factory('Magikarp'), Factory('Magikarp')] shared.biasRNG.call(this, 'next', 'paralyze chance', 1) # never pars @team1.pokemon.forEach((pokemon) -> pokemon.attach(Status.Paralyze)) @battle.performMove(@p1, @battle.getMove('Aromatherapy')) _.all(@team1.pokemon, (pokemon) -> !pokemon.hasStatus()).should.be.true describe 'copycat', -> beforeEach -> shared.create.call this, team1: [Factory('Magikarp', evs: {speed: 4})] # make faster than team2 it 'copies the last move used', -> @battle.lastMove = @battle.getMove('Tackle') mock = @sandbox.mock(@battle.getMove('Tackle')) mock.expects('execute').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it "changes the move's target properly", -> tackle = @battle.getMove('Tackle') @battle.lastMove = tackle mock = @sandbox.mock(tackle) mock.expects('execute').once().withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it 'fails if no last move was used', -> @battle.lastMove = null mock = @sandbox.mock(@battle.getMove('Copycat')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it 'fails if the last move was copycat', -> @battle.lastMove = @battle.getMove('Copycat') mock = @sandbox.mock(@battle.getMove('Copycat')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() describe 'a move that targets a different stat', -> it "uses the correct stat", -> shared.create.call(this) move = @battle.getMove('Secret Sword') defStat = @p2.stat('defense') move.pickDefenseStat(@p1, @p2).should.equal defStat describe 'foul play', -> it "uses the target's attack stat, not the user's", -> shared.create.call this, team1: [Factory('Celebi')] move = @battle.getMove('Foul Play') atkStat = @p2.stat('attack') move.pickAttackStat(@p1, @p2).should.equal atkStat describe 'foul play', -> it "uses the target's attack stat, not the user's", -> shared.create.call this, team1: [Factory('Celebi')] move = @battle.getMove('Foul Play') atkStat = @p2.stat('attack') move.pickAttackStat(@p1, @p2).should.equal atkStat describe 'teleport', -> it "always fails", -> shared.create.call(this) move = @battle.getMove('Teleport') mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() describe 'Super Fang', -> it "deals half of the target's current HP", -> shared.create.call(this) hp = @p2.currentHP hp = @p2.currentHP = (hp - (1 - hp % 2)) # Always odd @battle.performMove(@p1, @battle.getMove('Super Fang')) @p2.currentHP.should.equal Math.ceil(hp / 2) it "deals 1 damage minimum", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Super Fang')) @p2.currentHP.should.equal 0 describe "A weather-based recovery move", -> it "heals 50% HP in no weather, rounded half down", -> shared.create.call(this) @battle.setWeather(Weather.NONE) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') / 2) @p1.currentHP.should.equal(1 + hp) it "heals 25% HP in bad weather, rounded half down", -> shared.create.call(this, team1: [Factory("Shuckle")]) @battle.setWeather(Weather.SAND) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') / 4) @p1.currentHP.should.equal(1 + hp) it "heals 66% HP in good weather, rounded half down", -> shared.create.call(this) @battle.setWeather(Weather.SUN) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') * 2 / 3) @p1.currentHP.should.equal(1 + hp) describe 'a flinching move', -> it "prevents the other person from executing their move", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Splash')) mock.expects('execute').never() @battle.performMove(@p1, @battle.getMove('Fake Out')) @battle.performMove(@p2, @battle.getMove('Splash')) mock.verify() it "removes the flinch attachment at the end of the turn", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Fake Out')) @battle.endTurn() @p2.has(Attachment.Flinch).should.be.false describe 'weather ball', -> it "is a 50 base power normal move in normal conditions", -> shared.create.call(this) @battle.setWeather(Weather.NONE) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Normal' move.basePower(@battle, @p1, @p2).should.equal 50 it "is a 100 base power Water move in rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Water' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Fire move in sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Fire' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Ice move in hail", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Ice' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Rock move in sandstorm", -> shared.create.call(this) @battle.setWeather(Weather.SAND) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Rock' move.basePower(@battle, @p1, @p2).should.equal 100 describe 'Autotomize', -> it 'changes your weight on success', -> shared.create.call(this) weight = @p1.calculateWeight() @battle.performMove(@p1, @battle.getMove('Autotomize')) weight.should.not.equal @p1.calculateWeight() it 'cannot go below .1kg', -> # <NAME>ik<NAME> weighs 100kg. shared.create.call this, team1: [ Factory('<NAME>')] @battle.performMove(@p1, @battle.getMove('Autotomize')) @p1.calculateWeight().should.not.be.lessThan .1 it 'stacks weight changes', -> # <NAME> weighs 1355kg. shared.create.call this, team1: [ Factory('<NAME>')] @battle.performMove(@p1, @battle.getMove('Autotomize')) @battle.performMove(@p1, @battle.getMove('Autotomize')) @p1.calculateWeight().should.equal 1155 describe 'heart swap', -> shared.shouldDoNoDamage('Heart Swap') it 'swaps user and target boosts', -> shared.create.call(this) @p1.stages.attack = 2 @p2.stages.speed = -2 @battle.performMove(@p1, @battle.getMove('Heart Swap')) @p1.stages.should.containEql speed: -2 @p2.stages.should.containEql attack: 2 describe 'Nightmare', -> shared.shouldDoNoDamage('Nightmare') it 'fails if the pokemon is awake', -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Nightmare')).expects('fail').once() @battle.performMove(@p1, @battle.getMove('Nightmare')) mock.verify() it 'fails if used twice', -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) nightmare = @battle.getMove('Nightmare') @p2.attach(Status.Sleep) mock = @sandbox.mock(nightmare).expects('fail').once() @battle.performMove(@p1, nightmare) @battle.performMove(@p1, nightmare) mock.verify() it "cuts the target's HP by 25% each turn", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) hp = @p2.currentHP quarter = Math.floor(hp / 4) @battle.performMove(@p1, @battle.getMove('Nightmare')) @battle.endTurn() @p2.currentHP.should.equal(hp - quarter) @battle.endTurn() @p2.currentHP.should.equal(hp - 2*quarter) it "deals 1 damage minimum", -> shared.create.call(this, team2: [Factory("Shedinja")]) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove('Nightmare')) @battle.endTurn() @p2.currentHP.should.equal(0) it "stops the nightmare if the target wakes up", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove('Nightmare')) @p2.cureStatus() @battle.endTurn() # The check is in endTurn() @p2.has(Attachment.Nightmare).should.be.false describe 'Incinerate', -> it 'destroys the berry of the target', -> shared.create.call this, team2: [ Factory('Magikarp', item: 'Bluk Berry') ] @battle.performMove(@p1, @battle.getMove('Incinerate')) should.not.exist @p2.item it 'does not destroy non-berries', -> shared.create.call this, team2: [ Factory('Magikarp', item: 'Leftovers') ] @battle.performMove(@p1, @battle.getMove('Incinerate')) should.exist @p2.item describe 'Judgment', -> it 'is normal type by default', -> shared.create.call(this) move = @battle.getMove('Judgment') move.getType(@battle, @p1, @p2).should.equal 'Normal' it 'changes type depending on the Plate held by the user', -> shared.create.call this, team1: [ Factory('Magikarp', item: 'Earth Plate') ] move = @battle.getMove('Judgment') move.getType(@battle, @p1, @p2).should.equal 'Ground' describe 'Tailwind', -> shared.shouldDoNoDamage("Tailwind") shared.shouldFailIfUsedTwice("Tailwind") it "doubles the speed of the user's team", -> shared.create.call this oldSpeed = @p1.stat('speed') @battle.performMove(@p1, @battle.getMove('Tailwind')) newSpeed = @p1.stat('speed') newSpeed.should.equal(oldSpeed * 2) it "lasts three turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Tailwind')) @battle.endTurn() @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.team.has(Attachment.Tailwind).should.be.false describe 'Taunt', -> shared.shouldDoNoDamage("Taunt") shared.shouldFailIfUsedTwice("Taunt") it 'prevents the target from using a non-attacking move that turn', -> shared.create.call(this, team1: [ Factory('Magikarp', evs: {speed: 4}) ]) move = @battle.getMove('Calm Mind') taunt = @battle.getMove('Taunt') mock = @sandbox.mock(move) mock.expects('execute').never() @battle.performMove(@p1, taunt) @battle.performMove(@p2, move) mock.verify() it "lasts 4 turns if the user moved after the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p1, @battle.getMove('Splash')) @battle.performMove(@p2, @battle.getMove('Taunt')) @p1.has(Attachment.Taunt).should.be.true @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.has(Attachment.Taunt).should.be.true @battle.endTurn() @p1.has(Attachment.Taunt).should.be.false it "lasts 3 turns if the user moved before the target", -> shared.create.call(this, team1: [Factory("<NAME>", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Taunt')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.has(Attachment.Taunt).should.be.true @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Taunt).should.be.true @battle.endTurn() @p2.has(Attachment.Taunt).should.be.false it 'prevents the target from selecting that move the next turn', -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Taunt')) @battle.beginTurn() requestedMoves = @battle.requestFor(@p2).moves requestedMoves.should.not.containEql 'Splash' for moveName in [ "U-turn", "Volt Switch" ] do (moveName) -> describe moveName, -> it 'forces the owner to switch', -> shared.create.call(this, team1: (Factory("Magikarp") for i in [1..2])) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.requests.should.have.property(@id1) it "makes a request containing all the possible switches", -> shared.create.call(this, team1: (Factory("Magikarp") for i in [1..3])) @battle.performMove(@p1, @battle.getMove(moveName)) request = @battle.requestFor(@p1) request.switches.should.eql([ 1, 2 ]) describe 'venoshock', -> it 'doubles the base power if target is poisoned', -> shared.create.call(this) move = @battle.getMove("Venoshock") @p2.attach(Status.Poison) basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) it 'doubles the base power if target is toxiced', -> shared.create.call(this) move = @battle.getMove("Venoshock") @p2.attach(Status.Toxic) basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) describe 'Wish', -> shared.shouldDoNoDamage("Wish") shared.shouldFailIfUsedTwice("Wish") it "restores half of the user's total hit points the next end of turn", -> shared.create.call(this) hp = @p1.currentHP @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() @p1.currentHP.should.equal 1 @battle.endTurn() @p1.currentHP.should.equal(Math.round(hp / 2) + 1) it "restores the same total amount of HP to an ally", -> shared.create.call(this, team1: [Factory("Magikarp"), Factory("Celebi")]) hp = @p1.currentHP @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() receiver = @team1.at(1) receiver.currentHP = 1 @battle.performSwitch(@p1, 1) @battle.endTurn() receiver.currentHP.should.equal(Math.round(hp / 2) + 1) it "fails if the pokemon faints", -> shared.create.call(this, team1: [Factory("Magikarp"), Factory("Celebi")]) @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() @p1.currentHP = 1 @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.endTurn() @team1.has(Attachment.Wish).should.be.false describe "Counter", -> it "returns double the damage if attacked by a physical move", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Tackle')) @battle.performMove(@p1, @battle.getMove('Counter')) dhp1 = @p1.stat('hp') - @p1.currentHP dhp2 = @p2.stat('hp') - @p2.currentHP dhp2.should.equal 2*dhp1 it "fails if attacked by a special move", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Counter')) mock.expects('fail').once() @battle.performMove(@p2, @battle.getMove('ThunderShock')) @battle.performMove(@p1, @battle.getMove('Counter')) mock.verify() it "fails if not hit by an attack this turn", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Counter')) mock.expects('fail').once() @controller.makeMove(@id1, "Splash") @controller.makeMove(@id2, "Tackle") @battle.performMove(@p1, @battle.getMove('Counter')) mock.verify() it "hits the pokemon who is currently in that slot, not who was", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('U-turn')) @battle.performSwitch(@p1, 1) @battle.performMove(@p2, @battle.getMove('Counter')) @team1.first().currentHP.should.be.lessThan(@team1.first().stat('hp')) @team1.at(1).currentHP.should.equal(@team1.at(1).stat('hp')) it "doesn't activate Rough Skin if it fails", -> shared.create.call this, team2: [Factory("Garchomp", ability: "Rough Skin")] counter = @battle.getMove("Counter") mock = @sandbox.mock(counter) mock.expects('fail').once() @battle.performMove(@p1, counter) mock.verify() @p1.currentHP.should.equal(@p1.stat('hp')) describe "Perish Song", -> it "attaches to every pokemon in the field", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Perish Song')) result = _.all @battle.getActivePokemon(), (pokemon) -> pokemon.has(Attachment.PerishSong) result.should.be.true it "faints pokemon at the end of 4 turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Perish Song')) @battle.endTurn() @battle.endTurn() @battle.endTurn() result = _.all @battle.getActivePokemon(), (pokemon) -> !pokemon.isFainted() result.should.be.true @battle.endTurn() result = _.all @battle.getActivePokemon(), (pokemon) -> pokemon.isFainted() result.should.be.true it "fails against Pokemon with Soundproof", -> shared.create.call(this, team1: [Factory("Magikarp", ability: "Soundproof")]) @battle.performMove(@p2, @battle.getMove("Perish Song")) @p1.has(Attachment.PerishSong).should.be.false @p2.has(Attachment.PerishSong).should.be.true describe "Techno Blast", -> it "is Fire-type if the user holds a Burn Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Burn Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Fire" it "is Water-type if the user holds a Douse Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Douse Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Water" it "is Electric-type if the user holds a Shock Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Shock Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Electric" it "is Ice-type if the user holds a Chill Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Chill Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Ice" it "is Normal-type otherwise", -> shared.create.call(this) move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Normal" describe "Synchronoise", -> it "fails on Pokemon not of the user's type", -> shared.create.call this, team1: [Factory("Magikarp")] team2: [Factory("Celebi")] move = @battle.getMove('Synchronoise') mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "works on Pokemon that share one type with the user", -> shared.create.call this, team1: [Factory("Ferrothorn")] team2: [Factory("Celebi")] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Synchronoise')) @p2.currentHP.should.be.lessThan hp describe "Roost", -> shared.shouldDoNoDamage('Roost') it "removes the user's flying type during the turn", -> shared.create.call this, team1: [Factory("Gliscor")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) ('Flying' in @p1.types).should.be.false @p1.types.should.eql ['Ground'] it "turns pure-Flying pokemon into Normal pokemon", -> shared.create.call this, team1: [Factory("Tornadus")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) ('Flying' in @p1.types).should.be.false @p1.types.should.eql ['Normal'] it "keeps the user's types the same if non-Flying", -> shared.create.call this, team1: [Factory("Celebi")] oldTypes = @p1.types @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) @p1.types.should.eql oldTypes it "restores the user's old types after the turn", -> shared.create.call this, team1: [Factory("Gl<NAME>")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) @battle.endTurn() ('Flying' in @p1.types).should.be.true ('Ground' in @p1.types).should.be.true describe 'Encore', -> shared.shouldDoNoDamage('Encore') it "fails if the target has not yet used a move", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p1, encore) mock.verify() it "forces the target to repeat its last used move", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Splash') ] it "changes the target's decision if it has not moved yet", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Encore')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.lastMove.should.equal @battle.getMove('Splash') it "lasts 4 turns if the user moved after the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p1, @battle.getMove('Splash')) @battle.performMove(@p2, @battle.getMove('Encore')) @p1.has(Attachment.Encore).should.be.true @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.has(Attachment.Encore).should.be.true @battle.endTurn() @p1.has(Attachment.Encore).should.be.false it "lasts 3 turns if the user moved before the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Encore')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.has(Attachment.Encore).should.be.true @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Encore).should.be.true @battle.endTurn() @p2.has(Attachment.Encore).should.be.false it "fails on certain moves like mimic", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p2, @battle.getMove('Mimic')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "fails if the pokemon is already encored", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "fails if the move has 0 PP", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @p2.setPP(@battle.getMove('Splash'), 1) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "removes itself if the pokemon's move reaches 0 PP", -> shared.create.call(this) @p2.setPP(@battle.getMove('Splash'), 2) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.endTurn() @p2.has(Attachment.Encore).should.be.true @battle.performMove(@p2, @battle.getMove('Splash')) @battle.endTurn() @p2.has(Attachment.Encore).should.be.false describe "Swagger", -> it "confuses the target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Swagger")) @p2.has(Attachment.Confusion).should.be.true it "boosts the target's attack by two stages", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Swagger")) @p2.stages.attack.should.equal 2 describe "Flatter", -> it "confuses the target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Flatter")) @p2.has(Attachment.Confusion).should.be.true it "boosts the target's special attack by one stage", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Flatter")) @p2.stages.specialAttack.should.equal 1 describe "Torment", -> shared.shouldDoNoDamage("Torment") shared.shouldFailIfUsedTwice("Torment") it "prevents the target from using its last move", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Torment")) @battle.performMove(@p2, @battle.getMove("Splash")) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Tackle') ] @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Splash') ] it "still works even if a new pokemon has just switched in", -> shared.create.call(this, team2: [Factory("Magikarp"), Factory("Magikarp")]) @battle.performSwitch(@p2, 1) @battle.performMove(@p1, @battle.getMove("Torment")) @battle.beginTurn() @team2.first().validMoves().should.eql [ @battle.getMove('Splash'), @battle.getMove('Tackle') ] xit "does not force the Outrage user to struggle", -> xit "does not prevent consecutive use of Struggle", -> describe "Psych Up", -> it "copies the target's stat changes", -> shared.create.call(this) @p1.stages.specialAttack = 5 @p1.stages.evasion = 2 @p2.stages.attack = 6 @p2.stages.defense = -2 @p2.stages.speed = -1 @battle.performMove(@p1, @battle.getMove("Psych Up")) @p1.stages.should.eql { attack: 6, defense: -2, specialAttack: 0, specialDefense: 0, speed: -1, accuracy: 0, evasion: 0 } describe "Spikes", -> it "puts a layer of spikes on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.Spikes).should.be.false @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true it "fails if there are 3 layers", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Spikes')).expects('fail').once() for i in [1..4] @battle.performMove(@p1, @battle.getMove("Spikes")) mock.verify() it "deals a minimum of 1 damage", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Shedinja")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() (pokemon.stat('hp') - pokemon.currentHP).should.equal(1) it "does damage to pokemon switching in according to # of layers", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] hp = @team2.first().stat('hp') @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@p2, 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) @team2.first().currentHP = hp @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 6) @team2.first().currentHP = hp @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 4) it "does not affect pokemon with immunity to ground", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp", item: "Air Balloon")] @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().currentHP.should.equal @team2.first().stat('hp') it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() hp = @team2.first().stat('hp') (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) describe "Stealth Rock", -> shared.shouldDoNoDamage("Stealth Rock") shared.shouldFailIfUsedTwice("Stealth Rock") it "puts a layer of rocks on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.StealthRock).should.be.false @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @team2.has(Attachment.StealthRock).should.be.true it "does damage to pokemon switching in according to type", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Moltres")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() hp = pokemon.stat('hp') (hp - pokemon.currentHP).should.equal Math.floor(hp / 2) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() hp = pokemon.stat('hp') (hp - pokemon.currentHP).should.equal Math.floor(hp / 8) it "deals a minimum of 1 damage", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Aron", level: 1)] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() (pokemon.stat('hp') - pokemon.currentHP).should.equal(1) it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() hp = @team2.first().stat('hp') (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) describe "Toxic Spikes", -> it "puts a layer of toxic spikes on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.ToxicSpikes).should.be.false @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @team2.has(Attachment.ToxicSpikes).should.be.true it "fails if there are 2 layers", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Toxic Spikes')) mock.expects('fail').once() for i in [1..3] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) mock.verify() it "poisons or severely poisons the switch-in if not immune", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.true @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Toxic).should.be.true it "does not affect the pokemon if it's immune to Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Ferrothorn")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.false it "does not affect the pokemon if it's immune to Ground", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Gyarados")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.false it "disappears if the pokemon switching in is a grounded Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Drapion")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.has(Attachment.ToxicSpikes).should.be.false it "doesn't disappear if the pokemon switching in is a flying Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Drapion", item: "Air Balloon")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.has(Attachment.ToxicSpikes).should.be.true it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() @team2.first().has(Status.Poison).should.be.true testWeatherMove = (moveName, weather, item) -> describe moveName, -> it "changes the weather to #{weather.toLowerCase()} for 5 turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.weather.should.equal(weather) @battle.weatherDuration.should.equal 5 it "changes the weather to #{weather.toLowerCase()} for 8 turns if user holds a #{item}", -> shared.create.call this, team1: [Factory("Magikarp", item: item)] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.weather.should.equal(weather) @battle.weatherDuration.should.equal 8 it "fails if the weather is already #{weather}", -> shared.create.call this, team1: [Factory("Magikarp", item: item)] @battle.setWeather(weather) theMove = @battle.getMove(moveName) mock = @sandbox.mock(theMove).expects('fail').once() @battle.performMove(@p1, theMove) mock.verify() testWeatherMove("Rain Dance", Weather.RAIN, "Damp Rock") testWeatherMove("Sunny Day", Weather.SUN, "Heat Rock") testWeatherMove("Hail", Weather.HAIL, "Icy Rock") testWeatherMove("Sandstorm", Weather.SAND, "Smooth Rock") testStatusMove = (moveName, status) -> describe moveName, -> it "changes the status on a Pokemon if it has no status", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(status).should.be.true it "does not change the status if Pokemon already has a status", -> shared.create.call(this) oldStatus = if status == Status.Paralyze Status.Sleep else Status.Paralyze @p2.attach(oldStatus) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(status).should.be.false @p2.has(oldStatus).should.be.true testStatusMove("Dark Void", Status.Sleep) testStatusMove("GrassWhistle", Status.Sleep) testStatusMove("Hypnosis", Status.Sleep) testStatusMove("Lovely Kiss", Status.Sleep) testStatusMove("Poison Gas", Status.Poison) testStatusMove("PoisonPowder", Status.Poison) testStatusMove("Sing", Status.Sleep) testStatusMove("Sleep Powder", Status.Sleep) testStatusMove("Spore", Status.Sleep) testStatusMove("Stun Spore", Status.Paralyze) testStatusMove("Thunder Wave", Status.Paralyze) testStatusMove("Toxic", Status.Toxic) testStatusMove("Will-O-Wisp", Status.Burn) testEffectMove = (moveName, Effect) -> describe moveName, -> it "adds the effect to the Pokemon if it doesn't have it", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(Effect).should.be.true it "fails if the Pokemon already has it", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move) mock.expects('fail').once() shared.biasRNG.call(this, "randInt", 'confusion turns', 4) @p2.attach(Effect, {@battle}) move = @battle.getMove(moveName) @battle.performMove(@p1, move) mock.verify() testEffectMove 'Confuse Ray', Attachment.Confusion testEffectMove 'Supersonic', Attachment.Confusion testEffectMove 'Sweet Kiss', Attachment.Confusion testEffectMove 'Teeter Dance', Attachment.Confusion describe "Trump Card", -> it "has 40 base power by default", -> shared.create.call(this) @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 40 it "has 50 base power if the move has 3 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 3] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 3 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 50 it "has 60 base power if the move has 2 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 2] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 2 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 60 it "has 80 base power if the move has 1 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 1] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 1 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 80 it "has 200 base power if the move has 0 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 0] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 0 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 200 testRandomSwitchMove = (moveName) -> describe moveName, -> it "should switch opponent out to a random member", -> shared.create.call(this, team2: [Factory("Magikarp"), Factory("Abra")]) target = @team2.at(1) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @team2.first().should.equal target it "does not force a switch if the target faints", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() @team2.at(0).setHP(1) @battle.performMove(@p1, move) mock.verify() it "does not force a switch if the hit was indirect", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, move) mock.verify() it "does not force a switch if the user faints", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp", ability: "Iron Barbs"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() else mock.expects("switch").once() @p1.currentHP = 1 @battle.performMove(@p1, move) mock.verify() it "should not force switches if opponent is the last pokemon", -> shared.create.call(this, team2: [Factory("Magikarp")]) mock = @sandbox.mock(@team2) mock.expects("switch").never() move = @battle.getMove(moveName) @battle.performMove(@p1, move) mock.verify() it "cancels the opponent's move if user moves first", -> shared.create.call this, team1: [ Factory("Magikarp", moves: [ moveName ], evs: {speed: 4}), Factory("Magikarp")] team2: [ Factory("Magikarp", moves: [ moveName ]), Factory("Magikarp")] spy1 = @sandbox.spy(@team1, 'switch') spy2 = @sandbox.spy(@team2, 'switch') @controller.makeMove(@id1, moveName) @controller.makeMove(@id2, moveName) spy1.callCount.should.equal(0) spy2.callCount.should.equal(1) testRandomSwitchMove "Roar" testRandomSwitchMove "Whirlwind" testRandomSwitchMove "Dragon Tail" testRandomSwitchMove "Circle Throw" testTrappingMove = (name) -> describe name, -> it "blocks switching", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.Trap).should.be.true @p1.has(Attachment.TrapLeash).should.be.true it "deals 1/16 of the pokemon's max hp every turn", -> shared.create.call(this, team2: [Factory("Blissey")]) @battle.performMove(@p1, @battle.getMove(name)) @p2.currentHP = @p2.stat('hp') @battle.endTurn() maxHP = @p2.stat('hp') expected = maxHP - Math.floor(maxHP / 16) @p2.currentHP.should.equal expected it "deals a minimum of 1 damage", -> shared.create.call(this, team2: [Factory("S<NAME>")]) @p2.types = [ "Normal" ] move = @battle.getMove(name) @sandbox.stub(move, 'calculateDamage', -> 0) @battle.performMove(@p1, move) @battle.endTurn() @p2.currentHP.should.equal(0) it "lasts several turns", -> shared.create.call(this, team2: [Factory("Blissey")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @p2.currentHP = @p2.stat('hp') # loop for 5 more turns. One of the turns has already passed. # These moves hurt for 5 moves and wear off on the 6th. for i in [1..5] @p2.has(Attachment.Trap).should.be.true @battle.endTurn() # Test if the actual damage checks out. It should have damaged only 5 times maxHP = @p2.stat('hp') expected = maxHP - (Math.floor(maxHP / 16) * 5) @p2.currentHP.should.equal expected it "wears off after a certain number of turns", -> shared.create.call(this, team2: [Factory("Bl<NAME>")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() # loop for 5 more turns. One of the turns has already passed. # These moves hurt for 5 moves and wear off on the 6th. We need # turn number 6 to pass before the attachment should wear off. for i in [1..5] @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "does not reset the duration if used twice", -> shared.create.call(this, team2: [Factory("Blissey")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() # loop for 4 more turns. These moves wear off after numTurns + 1. # 2 have already passed. for i in [1..4] @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "wears off if the user switches", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "wears off if the user faints", -> shared.create.call(this, team1: [Factory("Heatran")], team2: [Factory("Blissey")]) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.Trap).should.be.true @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "properly removes from a list of attachments", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.recordMove(@id1, @battle.getMove("Protect")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "is always 7 turns if the user is holding grip claw", -> shared.create.call(this, team1: [Factory("Magikarp", item: "Grip Claw")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) move = @battle.getMove(name) @battle.performMove(@p1, move) @battle.performMove(@p2, @battle.getMove("Recover")) # The user is damaged 7 times, but the attachment actually lasts # for 8 turns including the turn it is first used. for i in [1..8] @p2.has(Attachment.Trap).should.be.true @battle.endTurn() @p2.has(Attachment.Trap).should.be.false it "does not start the effect if it hits a substitute", -> shared.create.call(this, team2: [Factory("Blissey")]) @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false testTrappingMove "Bind" testTrappingMove "Clamp" testTrappingMove "Fire Spin" testTrappingMove "Magma Storm" testTrappingMove "Sand Tomb" testTrappingMove "Whirlpool" testTrappingMove "Wrap" describe "Attract", -> shared.shouldDoNoDamage('Attract') shared.shouldFailIfUsedTwice "Attract", team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] it "has a 50% chance to immobilize a pokemon", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] shared.biasRNG.call(this, "next", 'attract chance', 0) # 100% immobilizes mock = @sandbox.mock(@battle.getMove('Tackle')).expects('execute').never() @battle.performMove(@p1, @battle.getMove("Attract")) @battle.performMove(@p2, @battle.getMove("Tackle")) mock.verify() it "has a 50% chance to not immobilize a pokemon", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] shared.biasRNG.call(this, "next", 'attract chance', .5) # 0% immobilizes mock = @sandbox.mock(@battle.getMove('Tackle')).expects('execute').once() @battle.performMove(@p1, @battle.getMove("Attract")) @battle.performMove(@p2, @battle.getMove("Tackle")) mock.verify() it "fails if the Pokemon are not opposite genders", -> shared.create.call this, team1: [Factory("<NAME>", gender: "F")] team2: [Factory("<NAME>", gender: "F")] mock = @sandbox.mock(@battle.getMove('Attract')).expects('fail').once() @battle.performMove(@p1, @battle.getMove("Attract")) mock.verify() it "disappears if the source is no longer active", -> shared.create.call this, team1: (Factory("<NAME>", gender: "M") for x in [1..2]) team2: [Factory("<NAME>", gender: "F")] @battle.performMove(@p1, @battle.getMove('Attract')) @battle.performMove(@p2, @battle.getMove('Splash')) @p2.has(Attachment.Attract).should.be.true @battle.performSwitch(@team1.first(), 1) @battle.performMove(@p2, @battle.getMove('Splash')) @p2.has(Attachment.Attract).should.be.false describe "Reflect", -> it "halves physical damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.Reflect) tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x800) it "does not halve non-physical damage", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.Reflect) thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) it "lasts five turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Reflect')) for i in [1..5] @team1.has(Attachment.Reflect).should.be.true @battle.endTurn() @team1.has(Attachment.Reflect).should.be.false it "fails if the user already used it", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Reflect')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Reflect')) @battle.performMove(@p1, @battle.getMove('Reflect')) mock.verify() it "does not halve on critical hits", -> shared.create.call(this) tackle = @battle.getMove('Tackle') @team2.attach(Attachment.Reflect) @p1.crit = true tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) describe "Light Screen", -> it "halves special damage", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.LightScreen) thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x800) it "does not halve non-physical damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.LightScreen) tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) it "lasts five turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Light Screen')) for i in [1..5] @team1.has(Attachment.LightScreen).should.be.true @battle.endTurn() @team1.has(Attachment.LightScreen).should.be.false it "fails if the user already used it", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Light Screen')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Light Screen')) @battle.performMove(@p1, @battle.getMove('Light Screen')) mock.verify() it "does not halve on critical hits", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') @team2.attach(Attachment.LightScreen) @p1.crit = true thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) describe "Rapid Spin", -> it "removes spikes", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false it "removes stealth rock", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @team2.has(Attachment.StealthRock).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.StealthRock).should.be.false it "removes toxic spikes", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @team2.has(Attachment.ToxicSpikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.ToxicSpikes).should.be.false it "removes multiple layers of entry hazards", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false it "removes trapping moves", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Fire Spin")) @p2.has(Attachment.Trap).should.be.true @p1.has(Attachment.TrapLeash).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "removes leech seed", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p2.has(Attachment.LeechSeed).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @p2.has(Attachment.LeechSeed).should.be.false it "does not remove entry hazards if the user faints from rough skin", -> shared.create.call(this, team1: [Factory("Magikarp", ability: "Rough Skin")]) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.true it "does remove entry hazards if the user faints from life orb", -> shared.create.call(this, team2: [Factory("Magikarp", item: "Life Orb")]) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false describe "Brick Break", -> it "shatters Light Screen", -> shared.create.call(this) @team2.attach(Attachment.LightScreen) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.LightScreen).should.be.false it "shatters Reflect", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.false it "shatters both at the same time", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.false @team2.has(Attachment.LightScreen).should.be.false it "shatters before damage calculation", -> shared.create.call(this) move = @battle.getMove("Brick Break") damage = move.calculateDamage(@battle, @p1, @p2) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) spy = @sandbox.spy(move, 'calculateDamage') @battle.performMove(@p1, move) spy.returned(damage).should.be.true it "does not shatter if the target is immune", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) @sandbox.stub(@p2, 'isImmune', -> true) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.true @team2.has(Attachment.LightScreen).should.be.true it "does not shatter if Brick Break misses", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) shared.biasRNG.call(this, 'randInt', 'miss', 101) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.true @team2.has(Attachment.LightScreen).should.be.true describe "Return", -> it "has 102 base power", -> shared.create.call(this) move = @battle.getMove("Return") bp = move.basePower(@battle, @p1, @p2) bp.should.equal 102 describe "Frustration", -> it "has 102 base power", -> shared.create.call(this) move = @battle.getMove("Frustration") bp = move.basePower(@battle, @p1, @p2) bp.should.equal 102 describe "Fake Out", -> it "flinches the enemy", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Fake Out")) @p2.has(Attachment.Flinch).should.be.true it "fails if the Pokemon has been in play one turn or more", -> shared.create.call(this) @battle.endTurn() @battle.beginTurn() fakeOut = @battle.getMove("Fake Out") mock = @sandbox.mock(fakeOut).expects('fail').once() @battle.performMove(@p1, fakeOut) mock.verify() it "works if the Pokemon is newly switched", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @battle.performSwitch(@team1.first(), 1) @battle.endTurn() @battle.beginTurn() fakeOut = @battle.getMove("Fake Out") mock = @sandbox.mock(fakeOut).expects('fail').never() @battle.performMove(@team1.first(), fakeOut) mock.verify() describe "Focus Energy", -> it "adds a Focus Energy attachment to the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Focus Energy")) @p1.has(Attachment.FocusEnergy).should.be.true it "fails the second time it is used", -> shared.create.call(this) move = @battle.getMove("Focus Energy") mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) @battle.performMove(@p1, move) mock.verify() testIdentifyMove = (moveName, types) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "makes the target vulnerable to #{types} moves", -> shared.create.call(this, team2: [Factory("Spiritomb")]) _.each(types, ((type) -> @isImmune(type).should.be.true), @p2) @battle.performMove(@p1, @battle.getMove(moveName)) @p2.has(Attachment.Identify).should.be.true _.each(types, ((type) -> @isImmune(type).should.be.false), @p2) it "makes the target's evasion be ignored", -> shared.create.call(this) @p2.boost(evasion: 2) @p2.editBoosts().evasion.should.equal 2 @battle.performMove(@p1, @battle.getMove(moveName)) @p2.editBoosts().evasion.should.equal 0 testIdentifyMove("Foresight", ["Normal", "Fighting"]) testIdentifyMove("Odor Sleuth", ["Normal", "Fighting"]) testIdentifyMove("Miracle Eye", ["Psychic"]) describe "Conversion", -> it "changes the user's type to a random type based on moves", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Thunderbolt", "Ice Beam", "Conversion" ])] shared.biasRNG.call(this, "randInt", 'conversion types', 0) @p1.types.should.eql [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Conversion")) @p1.types.should.eql [ 'Electric' ] it "ignores Conversion as part of the move types", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Conversion", "Ice Beam" ])] shared.biasRNG.call(this, "randInt", 'conversion types', 0) @p1.types = [ "Fake Type" ] @battle.performMove(@p1, @battle.getMove("Conversion")) @p1.types.should.eql [ 'Ice' ] it "fails if there is no type to convert to", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Conversion" ])] move = @battle.getMove("Conversion") mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) mock.verify() describe "Conversion 2", -> it "fails if the target has not yet moved", -> shared.create.call(this) move = @battle.getMove("Conversion 2") mock = @sandbox.mock(move).expects('fail').once() @p2.lastMove = null @battle.performMove(@p1, move) mock.verify() it "changes user's type to one resisting or is immune to target's move", -> shared.create.call(this) @p1.types = [ "Normal" ] move = @battle.getMove("Ember") type = move.type @p2.lastMove = move @battle.performMove(@p1, @battle.getMove("Conversion 2")) @p1.types.should.have.length 1 util.typeEffectiveness(type, @p1.types).should.be.lessThan 1 describe "Defense Curl", -> it "raises defense by 1 stage", -> shared.create.call(this) @p1.stages.defense.should.equal 0 @battle.performMove(@p1, @battle.getMove("Defense Curl")) @p1.stages.defense.should.equal 1 it "attaches a volatile attachment", -> shared.create.call(this) @p1.has(Attachment.DefenseCurl).should.be.false @battle.performMove(@p1, @battle.getMove("Defense Curl")) @p1.has(Attachment.DefenseCurl).should.be.true describe "Focus Punch", -> it "causes the user to flinch if hit", -> shared.create.call(this) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.not.be.lessThan @p2.stat('hp') it "does not cause flinching if hit by a non-damaging move", -> shared.create.call(this) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Will-O-Wisp")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if behind a substitute", -> shared.create.call(this) @p1.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2)) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if sub fades", -> shared.create.call(this) @p1.attach(Attachment.Substitute, hp: 1) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if hit by a move last turn", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching afterwards", -> shared.create.call(this, team2: [Factory("Magikarp", evs: {speed: 4})]) focusPunch = @battle.getMove("Focus Punch") @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() hp = @p2.currentHP @battle.recordMove(@id1, @battle.getMove("Tackle")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan(hp) describe "Magnet Rise", -> shared.shouldDoNoDamage("Magnet Rise") shared.shouldFailIfUsedTwice("Magnet Rise") it "makes the user immune to ground moves", -> shared.create.call(this) @p1.isImmune("Ground").should.be.false @battle.performMove(@p1, @battle.getMove("Magnet Rise")) @p1.isImmune("Ground").should.be.true it "lasts 5 turns", -> shared.create.call(this) @p1.isImmune("Ground").should.be.false @battle.performMove(@p1, @battle.getMove("Magnet Rise")) for i in [1..5] @p1.isImmune("Ground").should.be.true @battle.endTurn() @p1.isImmune("Ground").should.be.false testLockOnMove = (moveName) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "makes the user's next move never miss on this target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) shared.biasRNG.call(this, 'randInt', 'miss', 101) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @p2) .should.be.false it "lasts only two turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) for i in [1..2] @p1.has(Attachment.LockOn).should.be.true @battle.endTurn() @p1.has(Attachment.LockOn).should.be.false it "hits through two-turn fade-away moves", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, @battle.getMove("Fly")) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @p2) .should.be.false it "does not hit through Protect", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('hit').never() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Protect")) @battle.performMove(@p2, move) mock.verify() it "does not affect accuracy on another target", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performSwitch(@p2, 1) shared.biasRNG.call(this, 'randInt', 'miss', 101) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @team2.first()) .should.be.true it "re-locks on when used on another target", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performSwitch(@p2, 1) @battle.performMove(@p1, @battle.getMove(moveName)) @p1.has(Attachment.LockOn).should.be.true testLockOnMove("Lock-On") testLockOnMove("Mind Reader") describe "Minimize", -> it "boosts the user's evasion by 2", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Minimize")) @p1.stages.evasion.should.equal 2 it "adds a Minimize volatile attachment to the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Minimize")) @p1.has(Attachment.Minimize).should.be.true testStompMove = (moveName) -> describe moveName, -> it "doubles its base power when the target is minimized", -> shared.create.call(this) @p2.attach(Attachment.Minimize) move = @battle.getMove(moveName) bp = move.basePower(@battle, @p1, @p2) bp.should.equal(move.power * 2) it "has normal base power otherwise", -> shared.create.call(this) move = @battle.getMove(moveName) bp = move.basePower(@battle, @p1, @p2) bp.should.equal(move.power) it "has a 30% chance to flinch", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'flinch', 0) # 100% chance @battle.performMove(@p1, @battle.getMove(moveName)) @p2.has(Attachment.Flinch).should.be.true testStompMove("Stomp") testStompMove("Steamroller") testMeanLookMove = (moveName) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "blocks the target from switching", -> shared.create.call(this) @p2.isSwitchBlocked().should.be.false @battle.performMove(@p1, @battle.getMove(moveName)) @battle.beginTurn() @p2.isSwitchBlocked().should.be.true it "wears off if the user faints", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.MeanLook).should.be.true @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.MeanLook).should.be.false it "wears off if the user switches", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.MeanLook).should.be.false testMeanLookMove("Block") testMeanLookMove("Mean Look") testMeanLookMove("Spider Web") testRechargeMove = (moveName) -> describe moveName, -> it "blocks the target from switching the next turn", -> shared.create.call(this) @p1.isSwitchBlocked().should.be.false theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "blocks the target from picking a new move the next turn", -> shared.create.call(this) theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() for move in @p1.moves @p1.isMoveBlocked(move).should.be.true it "automatically selects a special recharge move the next turn", -> shared.create.call(this) specialMove = @battle.getMove("Recharge") theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @battle.requests.should.not.have.property @id1 action = @battle.getAction(@p1) should.exist(action) action.should.have.property("move") action.move.should.equal(specialMove) it "prevents the user from moving the next turn", -> shared.create.call(this) spy = @sandbox.spy(@p1, 'beforeMove') theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @battle.continueTurn() spy.returned(false).should.be.true testRechargeMove("Hyper Beam") testRechargeMove("Giga Impact") testRechargeMove("Blast Burn") testRechargeMove("Frenzy Plant") testRechargeMove("Hydro Cannon") testRechargeMove("Roar of Time") testRechargeMove("Rock Wrecker") describe 'Clear Smog', -> it 'removes all status boosts on the target pokemon', -> shared.create.call(this) # Create artificial boosts. @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Clear Smog")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p2.stages.should.eql neutralBoosts it "does not reset stats if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute, hp: 1) # Create artificial boosts. @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Clear Smog")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p2.stages.should.not.eql neutralBoosts testMomentumMove = (moveName) -> describe moveName, -> it "prevents the user from switching", -> shared.create.call(this) @p1.isSwitchBlocked().should.be.false @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "locks the user into using this particular move", -> shared.create.call this, team1: [ Factory("Shuckle") ] momentumMove = @battle.getMove(moveName) @p1.moves = [ momentumMove, @battle.getMove("Rest") ] @p1.resetAllPP() @battle.performMove(@p1, momentumMove) @battle.endTurn() @battle.beginTurn() for move in @p1.moves if move == momentumMove @p1.isMoveBlocked(move).should.be.false else @p1.isMoveBlocked(move).should.be.true it "stops if it misses", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'miss', 100) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Momentum).should.be.false it "lasts 5 turns", -> shared.create.call(this) for i in [1..5] @battle.performMove(@p1, @battle.getMove(moveName)) @p1.has(Attachment.Momentum).should.be.true @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Momentum).should.be.false it "doubles base power every time", -> shared.create.call(this) move = @battle.getMove(moveName) basePower = move.power for i in [1..5] bp = move.basePower(@battle, @p1, @p2) bp.should.equal(basePower * Math.pow(2, i - 1)) @battle.performMove(@p1, move) @battle.endTurn() @battle.beginTurn() @p2.currentHP = @p2.stat('hp') it "doubles base power again if user has defense curl's effect", -> shared.create.call(this) @p1.attach(Attachment.DefenseCurl) move = @battle.getMove(moveName) basePower = 2 * move.power for i in [1..5] bp = move.basePower(@battle, @p1, @p2) bp.should.equal(basePower * Math.pow(2, i - 1)) @battle.performMove(@p1, move) @battle.endTurn() @battle.beginTurn() @p2.currentHP = @p2.stat('hp') testMomentumMove("Rollout") testMomentumMove("Ice Ball") describe "Me First", -> it "fails if the user goes second", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.delay @p1 @battle.popAction(@p2) @battle.performMove(@p1, move) mock.verify() it "uses the target's move", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('execute').once() @battle.recordMove(@id1, @battle.getMove("Me First")) @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, @battle.getMove("Me First")) mock.verify() it "has 1.5x the base power of the target's move", -> shared.create.call(this) move = @battle.getMove("Tackle") @battle.recordMove(@id1, @battle.getMove("Me First")) @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, @battle.getMove("Me First")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x1800 for moveName in [ "Chatter", "Counter", "Covet", "Focus Punch", "Me First", "Metal Burst", "Mirror Coat", "Struggle", "Thief" ] do (moveName) -> it "fails if the target is using #{moveName}", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove(moveName)) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, move) mock.verify() it "fails if the target is using a non-damaging move", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, move) mock.verify() describe "Dream Eater", -> it "fails if the target is not asleep", -> shared.create.call(this) move = @battle.getMove("Dream Eater") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "does not fail if the target is asleep", -> shared.create.call(this) move = @battle.getMove("Dream Eater") mock = @sandbox.mock(move).expects('fail').never() @p2.attach(Status.Sleep) @battle.performMove(@p1, move) mock.verify() it "drains 1/2 of damage", -> shared.create.call(this) @p1.currentHP = initialHP = 1 @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove("Dream Eater")) damage = @p2.stat('hp') - @p2.currentHP healed = Math.floor(damage / 2) @p1.currentHP.should.equal(initialHP + healed) describe "Camouflage", -> it "changes the user's type to Ground type in Wi-Fi battles", -> shared.create.call(this) @p1.types = [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Camouflage")) @p1.types.should.eql [ "Ground" ] describe "Charge", -> shared.shouldDoNoDamage("Charge") it "raises the user's special defense by 1", -> shared.create.call(this) @p1.stages.specialDefense.should.equal 0 @battle.performMove(@p1, @battle.getMove("Charge")) @p1.stages.specialDefense.should.equal 1 it "doubles the base power of the user's next move", -> shared.create.call(this) move = @battle.getMove("Thunderbolt") move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 @battle.performMove(@p1, @battle.getMove("Charge")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x2000 it "doesn't double the next move if it is non-electric type", -> shared.create.call(this) move = @battle.getMove("Flamethrower") move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 @battle.performMove(@p1, @battle.getMove("Charge")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 it "can be used twice in a row", -> shared.create.call(this) move = @battle.getMove("Charge") mock = @sandbox.mock(move).expects('fail').never() @battle.performMove(@p1, move) @battle.endTurn() @battle.performMove(@p1, move) @battle.endTurn() @p1.has(Attachment.Charge).should.be.true mock.verify() describe "Tri Attack", -> it "has a 20% chance to activate its secondary effect", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.hasStatus().should.be.true it "has a 1/3 chance for the secondary effect to be paralysis", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 0) # par @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Paralyze).should.be.true it "has a 1/3 chance for the secondary effect to be burn", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 1) # brn @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Burn).should.be.true it "has a 1/3 chance for the secondary effect to be freeze", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 2) # frz @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Freeze).should.be.true describe "Mirror Move", -> it "copies the opponent's last move", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('execute').once() @p2.lastMove = move @battle.performMove(@p1, @battle.getMove("Mirror Move")) mock.verify() it "fails if the opponent has not moved the past turn", -> shared.create.call(this) move = @battle.getMove("Mirror Move") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "fails if the move does not have a `mirror` flag", -> shared.create.call(this) @p2.lastMove = @battle.getMove("Dragon Dance") move = @battle.getMove("Mirror Move") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() # TODO: Find out if this is true: when is lastMove nullified? it "fails if the pokemon was unable to move the previous turn" describe "Leech Seed", -> shared.shouldFailIfUsedTwice("Leech Seed") it "saps 1/8 of the target's max HP each turn", -> shared.create.call(this) move = @battle.getMove("Leech Seed") @p1.currentHP = 1 @battle.performMove(@p1, move) @battle.endTurn() p = @p2 fullHP = p.stat('hp') (fullHP - p.currentHP).should.equal Math.floor(fullHP / 8) @p1.currentHP.should.equal(fullHP - p.currentHP + 1) it "saps up to 1/8 HP", -> shared.create.call(this) move = @battle.getMove("Leech Seed") @p1.currentHP = 1 @p2.currentHP = 1 @battle.performMove(@p1, move) @battle.endTurn() @p1.currentHP.should.equal 2 it "saps a minimum of 1 damage", -> shared.create.call(this, team2: [Factory("Shedinja")]) move = @battle.getMove("Leech Seed") @battle.performMove(@p1, move) @battle.endTurn() @p2.currentHP.should.equal(0) it "always misses on Grass type Pokemon", -> shared.create.call(this) move = @battle.getMove("Leech Seed") mock = @sandbox.mock(move).expects('afterMiss').once() @p2.types = [ "Water", "Grass"] @battle.performMove(@p1, move) mock.verify() it "does not trigger if the user has fainted", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p1.faint() @battle.endTurn() @p2.currentHP.should.equal @p2.stat('hp') it "leeches next pokemon to switch in at that slot", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p1.faint() @battle.endTurn() @battle.performSwitch(@team1.first(), 1) @p2.currentHP.should.equal @p2.stat('hp') newFirst = @team1.first() newFirst.currentHP = 1 @battle.endTurn() hp = @p2.stat('hp') - @p2.currentHP hp.should.be.greaterThan(0) newFirst.currentHP.should.equal(hp + 1) it "stops if the target has fainted", -> shared.create.call(this, team2: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p2.faint() @battle.endTurn() @battle.performSwitch(@team2.first(), 1) @team2.first().currentHP.should.equal @team2.first().stat('hp') @p1.currentHP.should.equal(1) testProtectCounterMove = (moveName) -> it "fails if the user moves last this turn", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('fail').once() @battle.determineTurnOrder() @battle.performMove(@p1, move) mock.verify() it "has decreasing chances of success", -> shared.create.call(this) p = @p1 for x in [0..7] attachment = p.attach(Attachment.ProtectCounter) attachment.successChance().should.equal Math.pow(2, x) attachment = p.attach(Attachment.ProtectCounter) attachment.successChance().should.equal Math.pow(2, 32) it "fails if not successful", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 2) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) mock.verify() it "resets to 100% chance of success if move fails", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 2) move = @battle.getMove(moveName) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) @p1.has(Attachment.ProtectCounter).should.be.false it "resets to 100% chance of success if user selects a different move", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 1) move = @battle.getMove(moveName) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) @battle.endTurn() @p1.has(Attachment.ProtectCounter).should.be.true @battle.performMove(@p1, @battle.getMove('Splash')) @battle.endTurn() @p1.has(Attachment.ProtectCounter).should.be.false testProtectMove = (moveName) -> describe moveName, -> testProtectCounterMove(moveName) it "completely protects the user from attacks", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('hit').never() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) mock.verify() it "does not carry over to the next turn", -> shared.create.call(this) move = @battle.getMove("Tackle") @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) @battle.endTurn() mock = @sandbox.mock(move).expects('hit').once() @battle.performMove(@p2, move) mock.verify() it "does not protect the user from attacks without the protect flag", -> shared.create.call(this) move = @battle.getMove("Feint") mock = @sandbox.mock(move).expects('hit').once() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) mock.verify() testProtectMove 'Protect' testProtectMove 'Detect' describe "Endure", -> testProtectCounterMove("Endure") it "always survives moves that would otherwise KO with 1 HP", -> shared.create.call(this) move = @battle.getMove("Tackle") hp = @p1.currentHP @sandbox.stub(move, 'baseDamage', -> hp) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Endure")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.currentHP.should.equal 1 it "disappears at the end of the turn", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Endure")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.has(Attachment.Endure).should.be.true @battle.endTurn() @p1.has(Attachment.Endure).should.be.false describe "Feint", -> it "removes the Protect attachment, if any, on the target", -> shared.create.call(this) @p1.attach(Attachment.Protect) @p1.has(Attachment.Protect).should.be.true @battle.performMove(@p2, @battle.getMove("Feint")) @p1.has(Attachment.Protect).should.be.false it "removes the Wide Guard attachment, if any, on the target" it "removes the Quick Guard attachment, if any, on the target" describe "Payback", -> it "doubles base power if target has made a move this turn", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.performMove(@p2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(2 * move.power).should.be.true it "doesn't double base power otherwise", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(move.power).should.be.true it "doesn't double BP if target moved last turn, but not this turn", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.performMove(@p2, @battle.getMove("Splash")) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(move.power).should.be.true describe "Curse", -> it "silently chooses a random enemy as the target", -> shared.create.call(this) move = @battle.getMove("Curse") targets = move.getTargets(@battle, @p1) should.exist targets targets.should.eql [ @p2 ] describe "for Ghost types", -> it "curses the opponent", -> shared.create.call(this) @p1.types = [ "Ghost" ] @battle.performMove(@p1, @battle.getMove("Curse")) @p2.has(Attachment.Curse).should.be.true it "damages the user for half of its HP, rounded down", -> shared.create.call(this) p = @p1 p.types = [ "Ghost" ] maxHP = p.stat('hp') @battle.performMove(@p1, @battle.getMove("Curse")) p.currentHP.should.equal(maxHP - Math.floor(maxHP / 2)) it "causes the opponent to lose 25% of their HP at end of turns", -> shared.create.call(this) @p1.types = [ "Ghost" ] p = @p2 maxHP = p.stat('hp') quarterHP = Math.floor(maxHP / 4) @battle.performMove(@p1, @battle.getMove("Curse")) p.currentHP.should.equal(maxHP) @battle.endTurn() p.currentHP.should.equal(maxHP - quarterHP) @battle.endTurn() p.currentHP.should.equal(maxHP - 2 * quarterHP) it "causes the opponent to lose a minimum of 1 HP per turn", -> shared.create.call(this, team2: [Factory("Shedinja"), Factory("Magikarp")]) @p1.types = [ "Ghost" ] @battle.performMove(@p1, @battle.getMove("Curse")) @battle.endTurn() @p2.currentHP.should.equal(0) it "can faint the user", -> shared.create.call(this) p = @p1 p.types = [ "Ghost" ] p.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Curse")) p.isFainted().should.be.true describe "for non-Ghost types", -> it "raises Attack and Defense and lowers Speed", -> shared.create.call(this) p = @p1 p.types = [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Curse")) p.stages.should.containEql attack: 1, defense: 1, speed: -1 testBasePowerBoostMove = (moveName, rawBasePower, maxBasePower, which) -> describe moveName, -> it "increases base power by 20 for each positive stat boost on #{which}", -> shared.create.call(this) move = @battle.getMove(moveName) poke = { user: @p1, target: @p2 } {user, target} = poke move.basePower(@battle, user, target).should.equal rawBasePower poke[which].boost(attack: 1) move.basePower(@battle, user, target).should.equal rawBasePower + 20 poke[which].boost(defense: 1) move.basePower(@battle, user, target).should.equal rawBasePower + 40 poke[which].boost(speed: 2, specialAttack: -1) move.basePower(@battle, user, target).should.equal rawBasePower + 80 it "has a maximum of #{maxBasePower} base power", -> shared.create.call(this) move = @battle.getMove(moveName) poke = { user: @p1, target: @p2 } {user, target} = poke # Total base power would theoretically be rawBasePower + 840 stats = { speed: 6, specialAttack: 6, attack: 6, defense: 6, specialDefense: 6, evasion: 6, accuracy: 6 } poke[which].boost(stats) move.basePower(@battle, user, target).should.equal maxBasePower testBasePowerBoostMove("Stored Power", 20, 860, "user") testBasePowerBoostMove("Punishment", 60, 200, "target") describe "Destiny Bond", -> it "causes the attacker to faint the turn of use if the user faints", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.true it "causes the attacker to faint any time before the user moves again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.endTurn() @battle.beginTurn() @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.true it "does not cause attacker to faint after user moves again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p1, @battle.getMove("Splash")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.false it "does not cause attacker to faint after user attempts to move again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.endTurn() @battle.beginTurn() @p1.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove("Tackle")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.false it "does not faint attacker if pokemon fainted naturally", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @p1.faint() @battle.endTurn() @p2.isFainted().should.be.false it "does not faint attacker if opponent made move, but did not faint", -> shared.create.call(this) @battle.setWeather(Weather.SAND) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.currentHP = 1 @battle.endTurn() @p1.isFainted().should.be.true @p2.isFainted().should.be.false it "does not cause a party member to faint" it "handles 2+ pokemon destiny-bonding and all fainting at once" describe "Pursuit", -> it "doubles base power if the target switches", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() spy.alwaysReturned(2 * pursuit.power).should.be.true it "doubles BP if a faster target uses a damaging switch move", -> shared.create.call this, team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id2, @battle.getMove("U-turn")) @battle.recordMove(@id1, pursuit) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(2 * pursuit.power).should.be.true it "doesn't double BP if a slower target uses a damaging switch move", -> shared.create.call this, team1: [ Factory("Magikarp", evs: {speed: 4}) ] team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id1, pursuit) @battle.recordMove(@id2, @battle.getMove("U-turn")) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(pursuit.power).should.be.true it "has perfect accuracy if target is switching", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'chanceToHit') pursuit = @battle.getMove("Pursuit") @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() spy.alwaysReturned(0).should.be.true it "runs only once", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(pursuit).expects('execute').once() pursuit = @battle.getMove("Pursuit") @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() mock.verify() it "doesn't double BP on a faster Baton Passer", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id1, pursuit) @battle.recordMove(@id2, @battle.getMove("Baton Pass")) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(pursuit.power).should.be.true it "emits the move name when target switches", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(@battle, 'tell') @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() spy.calledWith(Protocol.MAKE_MOVE).should.be.true it "records the move when target switches", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(@p1).expects('recordMove').once() @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() mock.verify() it "does not trigger if asleep", -> shared.create.call(this) @p1.attach(Status.Sleep, turns: 4) pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(pursuit).expects('hit').never() @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() mock.verify() it "does not trigger on team members" describe 'Power Swap', -> it 'swaps attack and special attack boosts with the target', -> shared.create.call(this) @p1.boost(attack: 1, specialAttack: -3, speed: 1) @p2.boost(attack: 2, specialAttack: 6, defense: -1) @battle.performMove(@p1, @battle.getMove('Power Swap')) @p1.stages.should.containEql attack: 2, specialAttack: 6, speed: 1 @p2.stages.should.containEql attack: 1, specialAttack: -3, defense: -1 describe 'Guard Swap', -> it 'swaps defense and special defense boosts with the target', -> shared.create.call(this) @p1.boost(attack: 1, specialDefense: -3, defense: 1) @p2.boost(speed: 2, specialDefense: 6, defense: -1) @battle.performMove(@p1, @battle.getMove('Guard Swap')) @p1.stages.should.containEql defense: -1, specialDefense: 6, attack: 1 @p2.stages.should.containEql defense: 1, specialDefense: -3, speed: 2 describe 'Spite', -> it 'reduces the last move used by the target by 4', -> shared.create.call(this) move = @p2.moves[0] pp = @p2.pp(move) @battle.performMove(@p2, move) @battle.performMove(@p1, @battle.getMove('Spite')) @p2.pp(move).should.equal(pp - 4 - 1) it 'fails if the target has not recorded their last move', -> shared.create.call(this) spite = @battle.getMove('Spite') mock = @sandbox.mock(spite).expects('fail').once() @battle.performMove(@p1, spite) mock.verify() it "fails if the target's move has 0 PP", -> shared.create.call(this) spite = @battle.getMove('Spite') move = @p2.moves[0] mock = @sandbox.mock(spite).expects('fail').once() @p2.setPP(move, 0) @battle.performMove(@p2, move) @battle.performMove(@p1, spite) mock.verify() it 'fails if the target no longer knows the move', -> shared.create.call(this) spite = @battle.getMove('Spite') move = @p2.moves[0] mock = @sandbox.mock(spite).expects('fail').once() @battle.performMove(@p2, move) @p2.moves.splice(@p2.moves.indexOf(move), 1) @battle.performMove(@p1, spite) mock.verify() describe 'Wring Out', -> it 'has 120 power at maximum HP', -> shared.create.call(this) move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 120 it 'has 59 power at half-of-odd HP (rounded down)', -> shared.create.call(this) @p1.currentHP >>= 1 move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 59 it 'has 1 power minimum', -> shared.create.call(this) @p1.currentHP = 1 move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 1 describe 'Assurance', -> it 'doubles base power if the user was damaged this turn', -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Tackle')) power = move.basePower(@battle, @p1, @p2) power.should.equal(2 * move.power) it "doesn't double base power if the user was damaged a different turn", -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Tackle')) @battle.endTurn() @battle.beginTurn() power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) it "doesn't double base power if the user has never used a move", -> shared.create.call(this) move = @battle.getMove('Assurance') power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) it "doesn't double base power if hit by a non-damaging move", -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Will-O-Wisp')) power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) describe "Substitute", -> shared.shouldDoNoDamage("Substitute") shared.shouldFailIfUsedTwice("Substitute") it "removes 25% of the owner's health, rounded down", -> shared.create.call(this) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') @battle.performMove(@p1, sub) @p1.currentHP.should.equal(hp - (hp >> 2)) it "fails if the pokemon has 25% HP or less", -> shared.create.call(this) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') mock = @sandbox.mock(sub).expects('fail').once() @p1.currentHP = hp >> 2 @battle.performMove(@p1, sub) mock.verify() it "fails if the pokemon does not have enough total HP", -> shared.create.call(this, team1: [Factory("Shedinja")]) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') mock = @sandbox.mock(sub).expects('fail').once() @battle.performMove(@p1, sub) mock.verify() it "takes damage for the user", -> shared.create.call(this) sub = @battle.getMove('Substitute') subHP = (@p1.stat('hp') >> 2) @battle.performMove(@p1, sub) hp = @p1.currentHP attachment = @p1.get(Attachment.Substitute) attachment.hp.should.equal subHP @battle.performMove(@p2, @battle.getMove('Tackle')) attachment.hp.should.be.lessThan subHP @p1.currentHP.should.equal hp it "breaks after taking too much damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) hp = @p1.currentHP @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(tackle, 'baseDamage', -> 9999) @battle.performMove(@p2, tackle) @p1.has(Attachment.Substitute).should.be.false @p1.currentHP.should.equal hp it "fails most non-damaging moves", -> shared.create.call(this) hypnosis = @battle.getMove('Hypnosis') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(hypnosis).expects('fail').once() @battle.performMove(@p2, hypnosis) mock.verify() it "does not fail stat-up moves", -> shared.create.call(this) dragonDance = @battle.getMove('Dragon Dance') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(dragonDance).expects('fail').never() @battle.performMove(@p1, dragonDance) mock.verify() it "does not fail non-damaging moves with an authentic flag", -> shared.create.call(this) foresight = @battle.getMove('Foresight') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(foresight).expects('fail').never() @battle.performMove(@p2, foresight) mock.verify() it "still stores the actual damage", -> shared.create.call(this) gigaDrain = @battle.getMove('Giga Drain') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true spy = @sandbox.spy(@p2, 'drain') @battle.performMove(@p2, gigaDrain) spy.calledWith(0).should.be.false @p1.lastHitBy.damage.should.be.greaterThan 0 it "blocks secondary effects", -> shared.create.call(this) shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn flamethrower = @battle.getMove('Flamethrower') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(flamethrower, 'baseDamage', -> 1) @battle.performMove(@p2, flamethrower) @p1.has(Status.Burn).should.be.false it "blocks secondary effects even if sub fades", -> shared.create.call(this) shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn flamethrower = @battle.getMove('Flamethrower') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(flamethrower, 'baseDamage', -> 9999) @battle.performMove(@p2, flamethrower) @p1.has(Status.Burn).should.be.false it "does not block sandstorm damage", -> shared.create.call(this) @battle.setWeather(Weather.SAND) @battle.performMove(@p1, @battle.getMove('Substitute')) hp = @p1.currentHP @battle.endTurn() @p1.currentHP.should.be.lessThan(hp) it "does not block leech seed damage", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Leech Seed')) @battle.performMove(@p1, @battle.getMove('Substitute')) hp = @p1.currentHP @battle.endTurn() @p1.currentHP.should.be.lessThan(hp) it "is baton-passable" describe "Sucker Punch", -> it "fails if the target is not moving after the user", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') mock = @sandbox.mock(suckerPunch).expects('fail').once() @battle.performMove(@p1, suckerPunch) mock.verify() it "executes normally if the target is moving after the user", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') tackle = @battle.getMove('Tackle') mock = @sandbox.mock(suckerPunch).expects('afterSuccessfulHit').once() @battle.recordMove(@id2, tackle) @battle.determineTurnOrder() @battle.performMove(@p1, suckerPunch) mock.verify() it "fails if the target is using a status move", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') willOWisp = @battle.getMove('Will-O-Wisp') mock = @sandbox.mock(suckerPunch).expects('fail').once() @battle.recordMove(@id2, willOWisp) @battle.determineTurnOrder() @battle.performMove(@p1, suckerPunch) mock.verify() describe 'Grudge', -> it "causes the last move to lose all its PP if the user faints", -> shared.create.call(this) grudge = @battle.getMove("Grudge") tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p2, tackle) @battle.performFaints() @p1.isFainted().should.be.true @p2.pp(tackle).should.equal 0 it "causes the attacker to lose PP any time before the user moves again", -> shared.create.call(this) grudge = @battle.getMove("Grudge") tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.endTurn() @battle.beginTurn() @battle.performMove(@p2, tackle) @battle.performFaints() @p2.pp(tackle).should.equal 0 it "does not cause attacker to lose PP after user moves again", -> shared.create.call(this) grudge = @battle.getMove("Grudge") splash = @battle.getMove('Splash') tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p1, splash) @battle.performMove(@p2, tackle) @battle.performFaints() @p2.pp(tackle).should.not.equal 0 it "does not trigger from natural causes", -> shared.create.call(this) grudge = @battle.getMove("Grudge") splash = @battle.getMove('Splash') leechSeed = @battle.getMove('Leech Seed') @p2.moves = [ leechSeed ] @p2.resetAllPP() @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p2, leechSeed) @battle.endTurn() @p2.pp(leechSeed).should.equal(@p2.maxPP(leechSeed) - 1) describe "Stockpile", -> it "raises def and spdef", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, stockpile) @p1.stages.should.containEql defense: 1, specialDefense: 1 it "cannot raise if stockpile is at its limit", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") for i in [0...Attachment.Stockpile::maxLayers] @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 it "fails if stockpile is at its limit", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") mock = @sandbox.mock(stockpile).expects('fail').once() for i in [0...Attachment.Stockpile::maxLayers] @p1.attach(Attachment.Stockpile) @battle.performMove(@p1, stockpile) mock.verify() describe 'Spit Up', -> it 'fails if user has no stockpiles', -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") mock = @sandbox.mock(spitUp).expects('fail').once() @battle.performMove(@p1, spitUp) mock.verify() it "has 100 base power with 1 layer of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 100 it "has 200 base power with 2 layers of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 200 it "has 300 base power with 3 layers of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 300 it "resets stockpile count to 0", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.get(Attachment.Stockpile).layers.should.equal 1 @battle.performMove(@p1, spitUp) @p1.has(Attachment.Stockpile).should.be.false it "loses def/sp. def according to number of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, spitUp) @p1.stages.should.containEql defense: -2, specialDefense: -2 describe 'Swallow', -> it 'fails if user has no stockpiles', -> shared.create.call(this) swallow = @battle.getMove("Swallow") mock = @sandbox.mock(swallow).expects('fail').once() @battle.performMove(@p1, swallow) mock.verify() it "heals 25% of its HP, rounded half-down, with 1 layer of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal(1 + util.roundHalfDown(@p1.stat('hp') / 4)) it "heals 50% of its HP, rounded half-down, with 2 layers of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal(1 + util.roundHalfDown(@p1.stat('hp') / 2)) it "heals all of its HP with 3 layers of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal @p1.stat('hp') it "resets stockpile count to 0", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.get(Attachment.Stockpile).layers.should.equal 1 @battle.performMove(@p1, swallow) @p1.has(Attachment.Stockpile).should.be.false it "loses def/sp. def according to number of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, swallow) @p1.stages.should.containEql defense: -2, specialDefense: -2 describe 'Rage', -> it "raises the user's attack if hit by a move", -> shared.create.call(this) rage = @battle.getMove('Rage') tackle = @battle.getMove('Tackle') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p2, tackle) @p1.stages.attack.should.equal 1 it "doesn't raise the user's attack if user chooses another move", -> shared.create.call(this) rage = @battle.getMove('Rage') tackle = @battle.getMove('Tackle') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p1, tackle) @battle.performMove(@p2, tackle) @p1.stages.attack.should.equal 0 it "doesn't raise the user's attack if hit by a non-damaging move", -> shared.create.call(this) rage = @battle.getMove('Rage') willOWisp = @battle.getMove('Will-O-Wisp') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p2, willOWisp) @p1.stages.attack.should.equal 0 testRevengeMove = (moveName) -> describe moveName, -> it "doubles base power if hit by an attack that turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.performMove(@p2, tackle) revenge.basePower(@battle, @p1, @p2).should.equal(2 * revenge.power) it "doesn't double base power if not hit by an attack that turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) it "doesn't double base power if hit by a non-damaging move", -> shared.create.call(this) revenge = @battle.getMove(moveName) willOWisp = @battle.getMove("Will-O-Wisp") @battle.performMove(@p2, willOWisp) revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) it "doesn't double base power if hit last turn, but not this turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.performMove(@p2, tackle) @battle.beginTurn() revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) testRevengeMove("Avalanche") testRevengeMove("Revenge") testIgnoreStagesMove = (moveName) -> describe moveName, -> it "ignores the target's defensive and evasive stat stages", -> shared.create.call(this) move = @battle.getMove(moveName) stats = [ 'defense', 'specialDefense', 'evasion' ] values = ( @p2.stat(stat) for stat in stats ) spy = @sandbox.spy(@p2, 'stat') spy.withArgs(stat) for stat in stats @p2.boost(defense: -3, specialDefense: 2, evasion: 6) @battle.performMove(@p1, move) for i in [0...stats.length] stat = stats[i] value = values[i] continue if spy.withArgs(stat).returnValues.length == 0 spy.withArgs(stat).alwaysReturned(value).should.be.true testIgnoreStagesMove("Chip Away") testIgnoreStagesMove("Sacred Sword") describe 'Captivate', -> it 'fails if the user and target are not opposite genders', -> shared.create.call this, team1: [Factory("Magikarp", gender: "M")] team2: [Factory("Magikarp", gender: "M")] captivate = @battle.getMove('Captivate') mock = @sandbox.mock(captivate).expects('fail').once() @battle.performMove(@p1, captivate) mock.verify() it "lowers the target's special attack by 2", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M")] team2: [Factory("Magikarp", gender: "F")] captivate = @battle.getMove('Captivate') @p2.stages.specialAttack.should.equal 0 @battle.performMove(@p1, captivate) @p2.stages.specialAttack.should.equal -2 testStatusCureAttackMove = (moveName, status) -> describe moveName, -> it "doubles base power if the target has #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.attach(status) move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) it "doesn't double if the target doesn't have #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) move.basePower(@battle, @p1, @p2).should.equal(move.power) it "cures the target of #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.attach(status) @p2.has(status).should.be.true @battle.performMove(@p1, move) @p2.hasStatus().should.be.false it "does not cure #{status.name} if the user faints", -> shared.create.call(this, team2: [Factory("Magikarp", ability: "Iron Barbs")]) move = @battle.getMove(moveName) @p1.currentHP = 1 @p2.attach(status) @p2.has(status).should.be.true @battle.performMove(@p1, move) @p2.hasStatus().should.be.true testStatusCureAttackMove("Wake-Up Slap", Status.Sleep) testStatusCureAttackMove("SmellingSalt", Status.Paralyze) describe 'Aqua Ring', -> it "restores 1/16 max HP at the end of each turn", -> shared.create.call(this) aquaRing = @battle.getMove('Aqua Ring') delta = @p1.currentHP >> 4 @p1.currentHP = 1 @battle.performMove(@p1, aquaRing) @p1.currentHP.should.equal(1) @battle.endTurn() @p1.currentHP.should.equal(1 + delta) describe 'Ingrain', -> it "restores 1/16 max HP at the end of each turn", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') delta = @p1.currentHP >> 4 @p1.currentHP = 1 @battle.performMove(@p1, ingrain) @p1.currentHP.should.equal(1) @battle.endTurn() @p1.currentHP.should.equal(1 + delta) it "prevents switching", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') @battle.performMove(@p1, ingrain) @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "prevents self from being phased", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] ingrain = @battle.getMove('Ingrain') whirlwind = @battle.getMove('Whirlwind') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(@team1).expects('switch').never() @battle.performMove(@p2, whirlwind) mock.verify() it "lets self be switched out if using self-switching moves", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') uTurn = @battle.getMove('U-turn') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(@battle).expects('requestActions').once() @battle.performMove(@p1, uTurn) mock.verify() it "makes self vulnerable to Ground moves", -> shared.create.call(this, team1: [ Factory("Gyarados") ]) ingrain = @battle.getMove('Ingrain') uTurn = @battle.getMove('U-turn') @p1.isImmune('Ground').should.be.true @battle.performMove(@p1, ingrain) @p1.isImmune('Ground').should.be.false it "causes Telekinesis to fail", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') telekinesis = @battle.getMove('Telekinesis') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(telekinesis).expects('fail').once() @battle.performMove(@p2, telekinesis) mock.verify() describe "Embargo", -> it "prevents the target's use of items", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) @battle.endTurn() mock.verify() it "lasts 5 turns", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) for i in [0...5] @p2.has(Attachment.Embargo).should.be.true @battle.endTurn() @p2.has(Attachment.Embargo).should.be.false it "prevents the target's use of items in subsequent turns", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) for i in [0...5] @battle.endTurn() @battle.beginTurn() mock.verify() testChargeMove = (moveName, vulnerable) -> describe moveName, -> it "chooses the player's next action for them", -> shared.create.call(this) move = @battle.getMove(moveName) @p1.moves = [ move ] @battle.recordMove(@id1, move) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @battle.requests.should.not.have.property(@id1) should.exist(@battle.getAction(@p1)) it "only spends 1 PP for the entire attack", -> shared.create.call(this) move = @battle.getMove(moveName) @p1.moves = [ move ] @p1.resetAllPP() pp = @p1.pp(move) @battle.recordMove(@id1, move) @battle.continueTurn() @p1.pp(move).should.equal(pp) @battle.beginTurn() @battle.continueTurn() @p1.pp(move).should.equal(pp - 1) it "skips the charge turn if the user is holding a Power Herb", -> shared.create.call this, team1: [Factory("Magikarp", item: "Power Herb")] move = @battle.getMove(moveName) @p1.hasItem("Power Herb").should.be.true mock = @sandbox.mock(move).expects('execute').once() @battle.recordMove(@id1, move) @battle.continueTurn() mock.verify() @p1.hasItem().should.be.false if vulnerable?.length? it "makes target invulnerable to moves", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) clearSmog = @battle.getMove("Clear Smog") @battle.recordMove(@id1, move) @battle.recordMove(@id2, clearSmog) mock = @sandbox.mock(clearSmog).expects('hit').never() @battle.continueTurn() mock.verify() it "makes target invulnerable to moves *after* use", -> shared.create.call this, team2: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() it "is vulnerable to attacks from a No Guard pokemon", -> shared.create.call this, team2: [Factory("Magikarp", ability: "No Guard")] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() it "is vulnerable to attacks if locked on", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Lock-On")) @battle.performMove(@p2, @battle.getMove(moveName)) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() for vulnerableMove in vulnerable it "is vulnerable to #{vulnerableMove}", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) vulnerable = @battle.getMove(vulnerableMove) @battle.recordMove(@id1, move) @battle.recordMove(@id2, vulnerable) mock = @sandbox.mock(vulnerable).expects('hit').once() @battle.continueTurn() mock.verify() else # no vulnerable moves it "doesn't make target invulnerable to moves", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() testChargeMove('Skull Bash') testChargeMove('Razor Wind') testChargeMove('Shadow Force', []) testChargeMove('Ice Burn') testChargeMove('Freeze Shock') testChargeMove('Fly', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down"]) testChargeMove('Bounce', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down"]) # Additional 30% chance to par testChargeMove('Dig', ["Earthquake", "Magnitude"]) testChargeMove('Dive', ["Surf", "Whirlpool"]) testChargeMove('SolarBeam') testChargeMove('Sky Attack') describe "Skull Bash", -> it "raises defense of the user on the charge turn", -> shared.create.call(this) skullBash = @battle.getMove('Skull Bash') @p1.stages.defense.should.equal(0) @battle.performMove(@p1, skullBash) @p1.stages.defense.should.equal(1) describe "Sky Attack", -> it "has a 30% chance to flinch after execution", -> shared.create.call(this) skyAttack = @battle.getMove('Sky Attack') shared.biasRNG.call(this, "randInt", 'flinch', 0) # 100% chance @battle.recordMove(@id1, skyAttack) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.false @battle.beginTurn() @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true for moveName in [ "Gust", "Twister" ] for chargeMoveName in [ "Fly", "Bounce" ] do (moveName, chargeMoveName) -> describe moveName, -> it "deals double damage to Pokemon using #{chargeMoveName}", -> shared.create.call(this) chargeMove = @battle.getMove(chargeMoveName) move = @battle.getMove(moveName) # Make the Pokemon charge @battle.recordMove(@id2, chargeMove) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) for moveName in [ "Surf", "Whirlpool" ] do (moveName) -> describe moveName, -> it "deals double damage to Pokemon using Dive", -> shared.create.call(this) dive = @battle.getMove("Dive") move = @battle.getMove(moveName) # Make the Pokemon charge @battle.recordMove(@id2, dive) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) for moveName in [ "Earthquake", "Magnitude" ] do (moveName) -> describe moveName, -> it "deals double damage to Pokemon using Dig", -> shared.create.call(this) dig = @battle.getMove("Dig") move = @battle.getMove(moveName) power = move.power if moveName == 'Magnitude' power = 50 shared.biasRNG.call(this, 'randInt', 'magnitude', 20) # Make the Pokemon charge @battle.recordMove(@id2, dig) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * power) describe "SolarBeam", -> it "skips the charge turn under Sun", -> shared.create.call(this) solarBeam = @battle.getMove("SolarBeam") @battle.setWeather(Weather.SUN) mock = @sandbox.mock(solarBeam).expects('execute').once() @battle.recordMove(@id1, solarBeam) @battle.continueTurn() mock.verify() for weather in [ Weather.RAIN, Weather.SAND, Weather.HAIL ] do (weather) -> it "halves base power under #{weather}", -> shared.create.call(this) move = @battle.getMove("SolarBeam") @battle.setWeather(weather) move.basePower(@battle, @p1, @p2).should.equal(move.power >> 1) describe "Fury Cutter", -> it "doubles base power after every use, to a max of 160", -> shared.create.call(this) furyCutter = @battle.getMove("Fury Cutter") furyCutter.basePower(@battle, @p1, @p2).should.equal(20) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(40) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(80) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(160) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(160) it "resets to normal base power if using a different move", -> shared.create.call(this) furyCutter = @battle.getMove("Fury Cutter") splash = @battle.getMove("Splash") @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(40) @battle.performMove(@p1, splash) furyCutter.basePower(@battle, @p1, @p2).should.equal(20) describe "Imprison", -> shared.shouldDoNoDamage("Imprison") shared.shouldFailIfUsedTwice("Imprison") it "prevents the opponent from selecting moves that the user knows", -> shared.create.call(this) imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @p2.validMoves().should.eql [ furyCutter, tackle, splash ] @battle.performMove(@p1, imprison) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter ] it "prevents the opponent from executing moves that the user knows", -> shared.create.call(this) imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @battle.performMove(@p1, imprison) mock = @sandbox.mock(tackle).expects('execute').never() @battle.performMove(@p2, tackle) mock.verify() it "lets opponents use moves again after user switches out", -> shared.create.call this, team1: [Factory("Magikarp"), Factory("Magikarp")] imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @battle.performMove(@p1, imprison) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter ] @battle.performSwitch(@team1.first(), 1) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter, tackle, splash ] describe "Present", -> it "has a 40% chance for 40 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .6) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(40).should.be.true it "has a 30% chance for 80 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .3) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(80).should.be.true it "has a 10% chance for 120 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", 0) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(120).should.be.true it "has a 20% chance to heal target by 25% HP, rounded down", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .1) present = @battle.getMove("Present") @p2.currentHP = 1 spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(0).should.be.true @p2.currentHP.should.equal(1 + (@p2.stat('hp') >> 2)) describe "Final Gambit", -> it "faints the user", -> shared.create.call(this) finalGambit = @battle.getMove("Final Gambit") @battle.performMove(@p1, finalGambit) @p1.isFainted().should.be.true it "deals damage equal to the user's HP to the target", -> shared.create.call(this, team2: [Factory("Magikarp", evs: {hp: 4})]) finalGambit = @battle.getMove("Final Gambit") @battle.performMove(@p1, finalGambit) @p2.currentHP.should.equal(1) describe "Lucky Chant", -> shared.shouldDoNoDamage("Lucky Chant") shared.shouldFailIfUsedTwice("Lucky Chant") it "prevents critical hits on the defender's team", -> shared.create.call(this) luckyChant = @battle.getMove("Lucky Chant") stormThrow = @battle.getMove("Storm Throw") @battle.performMove(@p1, luckyChant) stormThrow.isCriticalHit(@battle, @p2, @p1).should.be.false it "lasts 5 turns", -> shared.create.call(this) luckyChant = @battle.getMove("Lucky Chant") @battle.performMove(@p1, luckyChant) for i in [0...5] @team1.has(Attachment.LuckyChant).should.be.true @battle.endTurn() @team1.has(Attachment.LuckyChant).should.be.false describe "Lunar Dance", -> it "faints the user", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") @battle.performMove(@p1, lunarDance) @p1.isFainted().should.be.true it "fails if the user is the last active pokemon", -> shared.create.call(this, team1: [Factory('Magikarp')]) lunarDance = @battle.getMove("Lunar Dance") mock = @sandbox.mock(lunarDance).expects('fail').once() @battle.performMove(@p1, lunarDance) mock.verify() @p1.isFainted().should.be.false it "completely restores the switchin's HP, PP, and status", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") benched = @team1.at(1) benched.attach(Status.Burn) benched.currentHP = 1 benched.setPP(benched.moves[0], 1) @battle.performMove(@p1, lunarDance) @battle.performSwitch(@team1.first(), 1) benched.currentHP.should.equal(benched.stat('hp')) benched.hasStatus().should.be.false for move in benched.moves benched.pp(move).should.equal(benched.maxPP(move)) it "disappears afterward", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") @battle.performMove(@p1, lunarDance) @team1.has(Attachment.LunarDance).should.be.true @battle.performSwitch(@team1.first(), 1) @team1.has(Attachment.LunarDance).should.be.false it "works for 2v2" describe "Healing Wish", -> it "faints the user", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") @battle.performMove(@p1, healingWish) @p1.isFainted().should.be.true it "fails if the user is the last active pokemon", -> shared.create.call(this, team1: [Factory('Magikarp')]) healingWish = @battle.getMove("Healing Wish") mock = @sandbox.mock(healingWish).expects('fail').once() @battle.performMove(@p1, healingWish) mock.verify() @p1.isFainted().should.be.false it "completely restores the switchin's HP and status", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") benched = @team1.at(1) benched.attach(Status.Burn) benched.currentHP = 1 benched.setPP(benched.moves[0], 1) @battle.performMove(@p1, healingWish) @battle.performSwitch(@team1.first(), 1) benched.currentHP.should.equal(benched.stat('hp')) benched.hasStatus().should.be.false it "disappears afterward", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") @battle.performMove(@p1, healingWish) @team1.has(Attachment.HealingWish).should.be.true @battle.performSwitch(@team1.first(), 1) @team1.has(Attachment.HealingWish).should.be.false it "works for 2v2" describe "Last Resort", -> it "fails if the pokemon only has one move", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") @p1.moves = [ lastResort ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() it "works if the pokemon uses all other moves before Last Resort", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] @battle.performMove(@p1, splash) mock = @sandbox.mock(lastResort).expects('afterSuccessfulHit').once() @battle.performMove(@p1, lastResort) mock.verify() it "fails if using all moves, but switches out and back in", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, splash) @battle.performSwitch(@team1.first(), 1) @battle.performMove(@team1.first(), lastResort) @battle.performSwitch(@team1.first(), 1) mock.verify() it "fails if the pokemon does not know Last Resort", -> shared.create.call(this) splash = @battle.getMove("Splash") tackle = @battle.getMove("Tackle") @p1.moves = [ splash, tackle ] lastResort = @battle.getMove("Last Resort") mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() it "fails if the pokemon has not used another move since it was active", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() describe "Assist", -> it "fails if no team member exists", -> shared.create.call this, team1: [ Factory("Magikarp") ] assist = @battle.getMove("Assist") mock = @sandbox.mock(assist).expects('fail').once() @battle.performMove(@p1, assist) mock.verify() it "chooses a team member's move at random", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] assist = @battle.getMove("Assist") move = @team1.at(1).moves[0] shared.biasRNG.call(this, "randInt", "assist", 0) mock = @sandbox.mock(move) mock.expects('execute').once().withArgs(@battle, @p1, [ @p1 ]) @battle.performMove(@p1, assist) mock.verify() it "fails if all team member moves are illegal", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] assist = @battle.getMove("Assist") @team1.at(1).moves = [] @team1.at(1).moves.push @battle.getMove("Assist") @team1.at(1).moves.push @battle.getMove("Bestow") @team1.at(1).moves.push @battle.getMove("Chatter") @team1.at(1).moves.push @battle.getMove("Circle Throw") @team1.at(1).moves.push @battle.getMove("Copycat") @team1.at(1).moves.push @battle.getMove("Counter") @team1.at(1).moves.push @battle.getMove("Covet") @team1.at(1).moves.push @battle.getMove("Destiny Bond") @team1.at(1).moves.push @battle.getMove("Detect") @team1.at(1).moves.push @battle.getMove("Dragon Tail") @team1.at(1).moves.push @battle.getMove("Endure") @team1.at(1).moves.push @battle.getMove("Feint") @team1.at(1).moves.push @battle.getMove("Focus Punch") @team1.at(1).moves.push @battle.getMove("Follow Me") @team1.at(1).moves.push @battle.getMove("Helping Hand") @team1.at(1).moves.push @battle.getMove("Me First") @team1.at(1).moves.push @battle.getMove("Metronome") @team1.at(1).moves.push @battle.getMove("Mimic") @team1.at(1).moves.push @battle.getMove("Mirror Coat") @team1.at(1).moves.push @battle.getMove("Mirror Move") @team1.at(1).moves.push @battle.getMove("Nature Power") @team1.at(1).moves.push @battle.getMove("Protect") @team1.at(1).moves.push @battle.getMove("Rage Powder") @team1.at(1).moves.push @battle.getMove("Sketch") @team1.at(1).moves.push @battle.getMove("Sleep Talk") @team1.at(1).moves.push @battle.getMove("Snatch") @team1.at(1).moves.push @battle.getMove("Struggle") @team1.at(1).moves.push @battle.getMove("Switcheroo") @team1.at(1).moves.push @battle.getMove("Thief") @team1.at(1).moves.push @battle.getMove("Transform") @team1.at(1).moves.push @battle.getMove("Trick") mock = @sandbox.mock(assist).expects('fail').once() @battle.performMove(@p1, assist) mock.verify() describe "Metronome", -> it "chooses a random move to execute", -> shared.create.call(this) @p1.moves = [] metronome = @battle.getMove("Metronome") tackle = @battle.getMove("Tackle") index = @battle.MoveList.indexOf(tackle) shared.biasRNG.call(this, 'randInt', "metronome", index) mock = @sandbox.mock(tackle).expects('execute').once() @battle.performMove(@p1, metronome) mock.verify() it "reselects if chosen an illegal move", -> shared.create.call(this) @p1.moves = [ metronome ] metronome = @battle.getMove("Metronome") technoBlast = @battle.getMove("Techno Blast") tackle = @battle.getMove("Tackle") index = @battle.MoveList.indexOf(technoBlast) reselectIndex = @battle.MoveList.indexOf(tackle) shared.biasRNG.call(this, 'randInt', "metronome", index) shared.biasRNG.call(this, 'randInt', "metronome reselect", reselectIndex) mock = @sandbox.mock(tackle).expects('execute').once() @battle.performMove(@p1, metronome) mock.verify() describe "Magic Coat", -> shared.shouldDoNoDamage("Magic Coat") it "causes certain moves directed at the user to be bounced back", -> shared.create.call(this) whirlwind = @battle.getMove("Whirlwind") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(whirlwind, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, whirlwind) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.true it "bounces back spikes", -> shared.create.call(this) spikes = @battle.getMove("Spikes") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(spikes, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, spikes) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @id2 ).should.be.true @team1.has(Attachment.Spikes).should.be.false @team2.has(Attachment.Spikes).should.be.true it "cannot bounce spikes more than once", -> shared.create.call(this) spikes = @battle.getMove("Spikes") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, magicCoat) (=> @battle.performMove(@p2, spikes) ).should.not.throw(/Maximum call stack size exceeded/) it "does not bounce certain moves back", -> shared.create.call(this) tackle = @battle.getMove("Tackle") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(tackle, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, tackle) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.false it "lasts until the end of the turn", -> shared.create.call(this) magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @p1.has(Attachment.MagicCoat).should.be.true @battle.endTurn() @p1.has(Attachment.MagicCoat).should.be.false it "cannot bounce more than once in the same turn", -> shared.create.call(this) willOWisp = @battle.getMove("Will-O-Wisp") thunderWave = @battle.getMove("Thunder Wave") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, willOWisp) spy = @sandbox.spy(thunderWave, 'execute') @battle.performMove(@p2, thunderWave) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.false it "cannot bounce a certain move more than once in the same turn", -> shared.create.call(this) willOWisp = @battle.getMove("Will-O-Wisp") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, magicCoat) spy = @sandbox.spy(willOWisp, 'execute') (=> @battle.performMove(@p2, willOWisp) ).should.not.throw(/Maximum call stack size exceeded/) spy.calledTwice.should.be.true spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.true spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p2 && targets[0] == @p1 ).should.be.true describe "Telekinesis", -> shared.shouldDoNoDamage("Telekinesis") shared.shouldFailIfUsedTwice("Telekinesis") it "makes the target immune to ground moves", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") @p1.isImmune('Ground').should.be.false @battle.performMove(@p2, telekinesis) @p1.isImmune('Ground').should.be.true it "lasts 3 turns", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p2, telekinesis) for x in [0...3] @p1.isImmune('Ground').should.be.true @battle.endTurn() @p1.isImmune('Ground').should.be.false it "makes the target unable to avoid attacks other than ohko moves", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") inferno = @battle.getMove("Inferno") sheerCold = @battle.getMove("Sheer Cold") inferno.chanceToHit(@battle, @p2, @p1).should.equal(50) sheerCold.chanceToHit(@battle, @p2, @p1).should.equal(30) @battle.performMove(@p2, telekinesis) inferno.chanceToHit(@battle, @p2, @p1).should.equal(0) sheerCold.chanceToHit(@battle, @p2, @p1).should.equal(30) describe "Smack Down", -> it "doesn't crash on secondary effect", -> shared.create.call(this, team2: [ Factory("Gyarados") ]) shared.biasRNG.call(this, "next", "secondary effect", 0) smackDown = @battle.getMove("Smack Down") (=> @battle.performMove(@p1, smackDown)).should.not.throw() it "removes target's Ground immunity", -> shared.create.call(this, team2: [ Factory("Gyarados") ]) smackDown = @battle.getMove("Smack Down") @p2.isImmune("Ground").should.be.true @battle.performMove(@p1, smackDown) @p2.isImmune("Ground").should.be.false it "stops Fly", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") fly = @battle.getMove("Fly") @battle.recordMove(@id1, fly) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.false it "stops Bounce", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") bounce = @battle.getMove("Bounce") @battle.recordMove(@id1, bounce) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.false it "does not stop other charge moves like Dive", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") dive = @battle.getMove("Dive") @battle.recordMove(@id1, dive) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.true it "stops Magnet Rise", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") magnetRise = @battle.getMove("Magnet Rise") @battle.performMove(@p1, magnetRise) @p1.has(Attachment.MagnetRise).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.MagnetRise).should.be.false it "stops Telekinesis", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p2, telekinesis) @p1.has(Attachment.Telekinesis).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Telekinesis).should.be.false it "makes Magnet Rise execution fail", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") magnetRise = @battle.getMove("Magnet Rise") @battle.performMove(@p1, smackDown) mock = @sandbox.mock(magnetRise).expects('fail').once() @battle.performMove(@p2, magnetRise) mock.verify() it "causes Telekinesis execution to fail", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p1, smackDown) mock = @sandbox.mock(telekinesis).expects('fail').once() @battle.performMove(@p1, telekinesis) mock.verify() describe "Echoed Voice", -> it "has 80 base power the second turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) it "has 120 base power the third turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...3] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(120) it "has 160 base power the fourth turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...4] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(160) it "has 200 base power the fifth turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...5] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(200) it "has 200 base power the sixth and above turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...6] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(200) it "resets to 40 base power if nobody uses this move the previous turn", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") splash = @battle.getMove("Splash") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) @battle.performMove(@p1, splash) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(40) it "has the same base power that turn for all users", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") splash = @battle.getMove("Splash") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) echoedVoice.basePower(@battle, @p2, @p1).should.equal(80) it "does not reset even if missing", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) @sandbox.stub(echoedVoice, 'willMiss', -> true) @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(120) describe "Struggle", -> it "deals typless damage", -> shared.create.call(this) struggle = @battle.getMove('Struggle') for type of util.Type util.typeEffectiveness(struggle.type, [type]).should.equal(1) it "deals 25% in recoil to the attacker, rounded down", -> shared.create.call(this) struggle = @battle.getMove('Struggle') hp = @p1.currentHP @p1.currentHP.should.equal @p1.stat('hp') @battle.performMove(@p1, struggle) (hp - @p1.currentHP).should.equal(hp >> 2) describe "Nature Power", -> it "uses Earthquake in Wi-Fi battles", -> shared.create.call(this) naturePower = @battle.getMove('Nature Power') earthquake = @battle.getMove('Earthquake') mock = @sandbox.mock(earthquake).expects('execute').once() .withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, naturePower) mock.verify() testRampageMove = (moveName) -> describe moveName, -> it "lasts 2-3 turns", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p1.has(Attachment.Rampage).should.be.true @battle.endTurn() @battle.performMove(@p1, rampageMove) @battle.endTurn() @p1.has(Attachment.Rampage).should.be.false it "locks the user into that move until execution ends", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) splash = @battle.getMove("Splash") @p1.moves = [ rampageMove, splash ] @p1.resetAllPP() @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.validMoves().should.eql [ rampageMove ] @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.validMoves().should.eql [ rampageMove, splash ] it "blocks switching until execution ends", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.false it "confuses the user after use", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Confusion).should.be.false @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Confusion).should.be.true it "stops immediately if the user's move did not hit", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 3) rampageMove = @battle.getMove(moveName) protect = @battle.getMove("Protect") @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id2, protect) @battle.recordMove(@id1, rampageMove) @battle.continueTurn() @battle.endTurn() @p1.has(Attachment.Rampage).should.be.false testRampageMove("Outrage") testRampageMove("Petal Dance") testRampageMove("Thrash") test2To5MulthitMove = (moveName) -> describe moveName, -> it "deals 2 to 5 hits with a probability distribution of 1/3, 1/3, 1/6, 1/6", -> shared.create.call(this) move = @battle.getMove(moveName) spy = @sandbox.spy(@battle.rng, 'choice') spy = spy.withArgs([2, 2, 3, 3, 4, 5], 'num hits') @battle.performMove(@p1, move) spy.calledOnce.should.be.true it "hits 5 times if the user has Skill Link", -> shared.create.call(this, team1: [Factory('Cloyster', ability: 'Skill Link')]) # try to "trick" the system into giving an invalid result. It should always hit # 5 times regardless of the rng shared.biasRNG.call(this, "choice", 'num hits', 2) shared.biasRNG.call(this, "randInt", 'num hits', 2) move = @battle.getMove(moveName) move.calculateNumberOfHits(@battle, @p1, [ @p2 ]).should.equal(5) it "only hits up until the target Pokemon faints", -> shared.create.call(this, team1: [Factory('Cloyster', ability: 'Skill Link')]) # try to "trick" the system into giving an invalid result. It should always hit # 5 times regardless of the rng shared.biasRNG.call(this, "choice", 'num hits', 3) shared.biasRNG.call(this, "randInt", 'num hits', 3) @p2.currentHP = 1 move = @battle.getMove(moveName) spy = @sandbox.spy(move, 'hit') @battle.performMove(@p1, move) spy.calledOnce.should.be.true test2To5MulthitMove('Arm Thrust') test2To5MulthitMove('Barrage') test2To5MulthitMove('Bone Rush') test2To5MulthitMove('Bullet Seed') test2To5MulthitMove('Comet Punch') test2To5MulthitMove('DoubleSlap') test2To5MulthitMove('Fury Attack') test2To5MulthitMove('Fury Swipes') test2To5MulthitMove('Icicle Spear') test2To5MulthitMove('Pin Missile') test2To5MulthitMove('Rock Blast') test2To5MulthitMove('Spike Cannon') test2To5MulthitMove('Tail Slap') describe "Trick Room", -> it "lasts 5 turns", -> shared.create.call(this) trickRoom = @battle.getMove("Trick Room") @battle.performMove(@p1, trickRoom) for x in [0...5] @battle.has(Attachment.TrickRoom).should.be.true @battle.endTurn() @battle.has(Attachment.TrickRoom).should.be.false it "ends a previous use of Trick Room", -> shared.create.call(this) trickRoom = @battle.getMove("Trick Room") @battle.performMove(@p1, trickRoom) @battle.has(Attachment.TrickRoom).should.be.true @battle.performMove(@p1, trickRoom) @battle.has(Attachment.TrickRoom).should.be.false it "reverses the order that moves are performed in", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) trickRoom = @battle.getMove("Trick Room") splash = @battle.getMove("Splash") @battle.performMove(@p1, trickRoom) @battle.recordMove(@id1, splash) @battle.recordMove(@id2, splash) @battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ] describe "Transform", -> shared.shouldDoNoDamage("Transform") shared.shouldFailIfUsedTwice("Transform") it "fails on a substitute", -> shared.create.call(this) substitute = @battle.getMove("Substitute") transform = @battle.getMove("Transform") @battle.performMove(@p2, substitute) mock = @sandbox.mock(transform).expects('fail').once() @battle.performMove(@p1, transform) mock.verify() it "changes the user's type to match the target's", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.types.should.eql @p2.types it "forces a sprite change", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") mock = @sandbox.mock(@p1).expects('changeSprite').once() @battle.performMove(@p1, transform) mock.verify() it "does not change species or forme", -> shared.create.call(this, team2: [Factory("Latias")]) transform = @battle.getMove("Transform") oldSpecies = @p1.species oldForme = @p1.forme @battle.performMove(@p1, transform) @p1.species.should.equal(oldSpecies) @p1.forme.should.equal(oldForme) it "changes the user's stats to match the target's, except HP", -> shared.create.call(this, team2: [Factory("Celebi", evs: {speed: 252})]) transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) for stat of @p2.baseStats if stat == 'hp' @p1.stat(stat).should.not.equal(@p2.stat(stat)) else @p1.stat(stat).should.equal(@p2.stat(stat)) it "copies the target's gender", -> shared.create.call this, team1: [Factory("Magikarp", gender: "F")] team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.gender.should.equal(@p2.gender) it "copies the target's moveset, setting each PP and max PP to 5", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @p2.boost(attack: 3, speed: -2, accuracy: 1) @battle.performMove(@p1, transform) @p1.moves.should.eql @p2.moves for move in @p1.moves @p1.pp(move).should.equal(5) @p1.maxPP(move).should.equal(5) it "copies the target's stat boosts", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @p2.boost(attack: 3, speed: -2, accuracy: 1) @battle.performMove(@p1, transform) @p1.stages.should.containEql(attack: 3, speed: -2, accuracy: 1) it "copies the target's ability", -> shared.create.call this, team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.hasAbility("Natural Cure").should.be.true it "copies the target's weight", -> shared.create.call this, team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.weight.should.equal(@p2.weight) it "copies the target's gender", -> shared.create.call this, team1: [Factory("Magikarp", gender: "F")] team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.gender.should.equal(@p2.gender) it "restores the original stats after switching out", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure", evs: {speed: 252})] transform = @battle.getMove("Transform") baseStats = _.clone(@p1.baseStats) evs = _.clone(@p1.evs) stats = {} for stat of baseStats stats[stat] = @p1.stat(stat) @battle.performMove(@p1, transform) @p1.baseStats.should.not.eql(baseStats) @p1.evs.should.not.eql(evs) for stat, value of stats @p1.stat(stat).should.not.equal(value) @battle.performSwitch(@p1, 1) @p1.baseStats.should.eql(baseStats) @p1.evs.should.eql(evs) for stat, value of stats @p1.stat(stat).should.equal(value) it "restores the original species and type after switching out", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") species = @p1.species types = _.clone(@p1.types) @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.types.should.eql(types) @p1.species.should.eql(species) it "restores the original ability after switching out", -> # Ditto has a fake ability so we can test abilities being restored. shared.create.call this, team1: [Factory("Ditto", ability: "Sniper"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") ability = @p1.ability @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.ability.should.eql(ability) it "restores original moveset after switch, but Transform PP decreases", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") moves = _.clone(@p1.moves) ppHash = _.clone(@p1.ppHash) maxPPHash = _.clone(@p1.maxPPHash) @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.moves.should.eql(moves) @p1.maxPPHash.should.eql(maxPPHash) # Transform's PP should go down! ppHash[transform.name] -= 1 @p1.ppHash.should.eql(ppHash) it "restores original gender after switch", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") gender = @p1.gender @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.gender.should.eql(gender) it "restores original weight after switch", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") weight = @p1.weight @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.weight.should.eql(weight) it "fails if the target is transformed", -> shared.create.call(this) transform = @battle.getMove("Transform") @battle.performMove(@p2, transform) mock = @sandbox.mock(transform).expects('fail').once() @battle.performMove(@p1, transform) mock.verify() it "fails if the target is under an illusion" it "fails if the user is under an illusion" it "cannot change formes if it has the ability to do so" describe "Fling", -> it "fails if the pokemon has no item", -> shared.create.call(this) fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "fails if the item is not removeable", -> shared.create.call this, team1: [Factory("Magikarp", item: "Acro Bike")] fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "fails if the user is blocked from using items", -> shared.create.call this, team1: [Factory("Magikarp", item: "Armor Fossil")] fling = @battle.getMove("Fling") @p1.blockItem() mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "has a base power depending on the item held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Armor Fossil")] fling = @battle.getMove("Fling") fling.beforeTurn(@battle, @p1) @p1.beforeMove(fling, @p1, [@p2]) fling.basePower(@battle, @p1, @p2).should.equal(100) it "inflicts Burn on the target if Flame Orb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Flame Orb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Burn).should.be.true it "inflicts Toxic on the target if Toxic Orb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Toxic Orb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Toxic).should.be.true it "flinches the target if King's Rock is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "King's Rock")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true it "flinches the target if Razor Fang is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Razor Fang")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true it "paralyzes the target if Light Ball is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Light Ball")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Paralyze).should.be.true it "removes negative status effects if Mental Herb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Mental Herb")] fling = @battle.getMove("Fling") @p2.attach(Attachment.Torment) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Torment).should.be.false it "removes negative stat boosts if White Herb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "White Herb")] fling = @battle.getMove("Fling") @p2.boost(attack: 1, accuracy: -2) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.stages.should.containEql(attack: 1, accuracy: 0) it "inflicts Poison on the target if Poison Barb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Barb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Poison).should.be.true it "causes target to eat the flung berry if a berry is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.stages.speed.should.equal(1) it "does not activate an item effect when hitting a substitute", -> shared.create.call this, team1: [Factory("Magikarp", item: "Toxic Orb")] fling = @battle.getMove("Fling") @p2.attach(Attachment.Substitute, hp: 1) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Toxic).should.be.false it "loses the user's item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Barb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p1.hasItem().should.be.false it "loses the item even if execution is canceled by protect", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Herb")] protect = @battle.getMove("Protect") fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('hit').never() @battle.recordMove(@id2, protect) @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() @p1.hasItem().should.be.false describe "Bug Bite", -> it "eats the target's berry and gets its effects", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry")] bugBite = @battle.getMove("Bug Bite") @battle.performMove(@p1, bugBite) @p2.hasItem().should.be.false @p1.stages.should.containEql(speed: 1) it "does eat the target's berry if the target fainted", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry")] bugBite = @battle.getMove("Bug Bite") @p2.currentHP = 1 @battle.performMove(@p1, bugBite) @p2.isFainted().should.be.true @p1.stages.should.containEql(speed: 1) it "does not eat the target's berry if the user fainted", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry", ability: "Iron Barbs")] bugBite = @battle.getMove("Bug Bite") @p1.currentHP = 1 @battle.performMove(@p1, bugBite) @p1.isFainted().should.be.true @p2.hasItem().should.be.true describe "Beat Up", -> it "deals 1 less hit for each unhealthy member in the user's party", -> shared.create.call this, team1: (Factory("Magikarp") for i in [0...6]) @team1.at(5).attach(Status.Paralyze) @team1.at(1).faint() beatUp = @battle.getMove("Beat Up") mock = @sandbox.mock(beatUp).expects('hit').exactly(4) @battle.performMove(@p1, beatUp) mock.verify() it "has 5 + X/10 base power for X in team, where X is base attack", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("<NAME>"), Factory("Celebi"), Factory("Totodile"), Factory("Ray<NAME>"), Factory("Seedot") ] beatUp = @battle.getMove("Beat Up") spy = @sandbox.spy(beatUp, "basePower") @battle.performMove(@p1, beatUp) for pokemon in @team1.pokemon basePower = 5 + Math.floor(pokemon.baseStats.attack / 10) spy.returned(basePower).should.be.true it "works for teams smaller than 6", -> shared.create.call this, team1: (Factory("Magikarp") for i in [0...4]) beatUp = @battle.getMove("Beat Up") mock = @sandbox.mock(beatUp).expects('hit').exactly(4) @battle.performMove(@p1, beatUp) mock.verify() it "doesn't crash if all pokemon are statused or fainted", -> shared.create.call this, team1: (Factory("<NAME>ik<NAME>") for i in [0...2]) @team1.at(1).faint() @team1.at(0).attach(Status.Burn) beatUp = @battle.getMove("Beat Up") (=> @battle.performMove(@p1, beatUp) ).should.not.throw() it "doesn't crash when used by a pokemon with technician", -> shared.create.call(this, team1: [Factory("<NAME>", ability: "Technician")]) beatUp = @battle.getMove("Beat Up") (=> @battle.performMove(@p1, beatUp) ).should.not.throw() describe "Psycho Shift", -> it "fails if the user doesn't have a status", -> shared.create.call(this) psychoShift = @battle.getMove("Psycho Shift") mock = @sandbox.mock(psychoShift).expects('fail').once() @battle.performMove(@p1, psychoShift) mock.verify() it "fails if the target already has a status", -> shared.create.call(this) @p1.attach(Status.Toxic) @p2.attach(Status.Paralyze) psychoShift = @battle.getMove("Psycho Shift") mock = @sandbox.mock(psychoShift).expects('fail').once() @battle.performMove(@p1, psychoShift) mock.verify() it "cures the user of its status", -> shared.create.call(this) @p1.attach(Status.Poison) psychoShift = @battle.getMove("Psycho Shift") @battle.performMove(@p1, psychoShift) @p1.hasStatus().should.be.false it "gives the user's former status to the target", -> shared.create.call(this) @p1.attach(Status.Burn) psychoShift = @battle.getMove("Psycho Shift") @battle.performMove(@p1, psychoShift) @p2.has(Status.Burn).should.be.true describe "Gravity", -> shared.shouldDoNoDamage("Gravity") shared.shouldFailIfUsedTwice("Gravity") it "raises accuracy of all attacks by 5/3", -> shared.create.call(this) gravity = @battle.getMove("Gravity") focusBlast = @battle.getMove("Focus Blast") @battle.performMove(@p1, gravity) accuracy = focusBlast.chanceToHit(@battle, @p1, @p2) accuracy.should.equal Math.floor(focusBlast.accuracy * 5 / 3) it "lasts 5 turns", -> shared.create.call(this) gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) for i in [0...5] @battle.has(Attachment.Gravity).should.be.true @battle.endTurn() @battle.has(Attachment.Gravity).should.be.false it "makes Flying Pokemon no longer immune to Ground", -> shared.create.call(this) @p2.types = [ "Flying" ] @p2.isImmune("Ground").should.be.true gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) @p2.isImmune("Ground").should.be.false it "makes Levitating Pokemon no longer immune to Ground", -> shared.create.call(this, team2: [Factory("Magikarp", ability: "Levitate")]) @p2.isImmune("Ground").should.be.true gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) @p2.isImmune("Ground").should.be.false it "deals damage to Flying Pokemon", -> shared.create.call(this) @p2.types = [ "Flying" ] gravity = @battle.getMove("Gravity") earthquake = @battle.getMove("Earthquake") earthquake.typeEffectiveness(@battle, @p1, @p2).should.equal(0) @battle.performMove(@p1, gravity) earthquake.typeEffectiveness(@battle, @p1, @p2).should.equal(1) # TODO: Sky Drop for moveName in [ "Bounce", "Fly" ] do (moveName) -> it "grounds pokemon using #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @battle.recordMove(@id2, move) @battle.continueTurn() @p2.has(Attachment.Charging).should.be.true @battle.recordMove(@id1, gravity) @battle.continueTurn() @p2.has(Attachment.Charging).should.be.false it "removes Telekinesis", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") gravity = @battle.getMove("Gravity") @battle.performMove(@p1, telekinesis) @p2.has(Attachment.Telekinesis).should.be.true @battle.performMove(@p1, gravity) @p2.has(Attachment.Telekinesis).should.be.false it "removes Magnet Rise", -> shared.create.call(this) magnetRise = @battle.getMove("Magnet Rise") gravity = @battle.getMove("Gravity") @battle.performMove(@p2, magnetRise) @p2.has(Attachment.MagnetRise).should.be.true @battle.performMove(@p1, gravity) @p2.has(Attachment.MagnetRise).should.be.false for moveName in [ "Jump Kick", "Hi Jump Kick", "Bounce", "Fly", "Sky Drop", "Splash", "Telekinesis" ] do (moveName) -> it "disables #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @p1.moves = [ move ] @p2.moves = [ move ] @battle.performMove(@p1, gravity) @battle.beginTurn() @p1.validMoves().should.not.containEql(move) @p2.validMoves().should.not.containEql(move) it "prevents the execution of #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) mock = @sandbox.mock(move).expects('execute').never() @battle.performMove(@p2, move) mock.verify() testDelayedAttackMove = (moveName, type) -> describe moveName, -> shared.shouldFailIfUsedTwice(moveName) it "waits three turns before attacking", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) for x in [0...3] @p2.currentHP.should.equal @p2.stat('hp') @battle.endTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not initialize and error if the target has fainted", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.faint() (=> @battle.performMove(@p1, move)).should.not.throw() it "does not hit if the target has fainted", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) for x in [0...2] @battle.endTurn() @p2.faint() mock = @sandbox.mock(move).expects('hit').never() @battle.endTurn() mock.verify() it "is considered a direct attack", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.attach(Attachment.Substitute, hp: 1) @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Substitute).should.be.true @battle.endTurn() @p2.has(Attachment.Substitute).should.be.false it "can target multiple positions" testDelayedAttackMove("Future Sight") testDelayedAttackMove("Doom Desire") describe "Baton Pass", -> it "fails if there is no benched pokemon to BP to", -> shared.create.call(this, team1: [Factory('Magikarp')]) batonPass = @battle.getMove("Baton Pass") mock = @sandbox.mock(batonPass).expects('fail').once() @battle.performMove(@p1, batonPass) mock.verify() it "switches to another pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @battle.performMove(@p1, batonPass) @battle.requests.should.have.property @id1 it "passes certain attachments to the next pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @p1.attach(Attachment.Ingrain) @p1.attach(Attachment.Torment) @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().has(Attachment.Torment).should.be.false @team1.first().has(Attachment.Ingrain).should.be.true it "continues Perish Song's counter", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") perishSong = @battle.getMove("Perish Song") @battle.performMove(@p1, perishSong) for i in [0...3] @battle.endTurn() @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().isFainted().should.be.false @battle.endTurn() @team1.first().isFainted().should.be.true it "passes status boosts to the next pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @p1.boost(attack: 1, evasion: -3) @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().stages.should.containEql(attack: 1, evasion: -3) describe "Thunder Wave", -> it "is affected by immunities", -> shared.create.call(this) thunderWave = @battle.getMove("Thunder Wave") @p2.types = [ 'Ground' ] @battle.performMove(@p1, thunderWave) @p2.has(Status.Paralyze).should.be.false describe "Thunder", -> it "has 50% accuracy in Sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(50) it "has perfect accuracy in Rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Hurricane", -> it "has 50% accuracy in Sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(50) it "has perfect accuracy in Rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Blizzard", -> it "has perfect accuracy in Hail", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) blizzard = @battle.getMove("Blizzard") blizzard.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) blizzard = @battle.getMove("Blizzard") blizzard.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Sleep Talk", -> it "fails if the pokemon is awake", -> shared.create.call(this) sleepTalk = @battle.getMove("Sleep Talk") mock = @sandbox.mock(sleepTalk).expects('fail').once() @battle.performMove(@p1, sleepTalk) mock.verify() it "performs a random move when the pokemon is asleep", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ tackle, sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) spy = @sandbox.spy(@battle, 'executeMove') @battle.performMove(@p1, sleepTalk) spy.calledWith(tackle).should.be.true it "does not choose sleep talk or other moves", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") assist = @battle.getMove("Assist") @p1.moves = [ sleepTalk, assist, tackle ] @p1.resetAllPP() @p1.attach(Status.Sleep) spy = @sandbox.spy(@battle, 'executeMove') @battle.performMove(@p1, sleepTalk) spy.calledWith(tackle).should.be.true it "fails if there are no viable moves", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) mock = @sandbox.mock(sleepTalk).expects('fail').once() @battle.performMove(@p1, sleepTalk) mock.verify() it "changes the move's target properly", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ tackle, sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) mock = @sandbox.mock(tackle) mock.expects('execute').once().withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, sleepTalk) mock.verify() describe "Rest", -> it "fails if the pokemon is at full HP", -> shared.create.call(this) rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(@p1.stat('hp')) @battle.performMove(@p1, rest) mock.verify() it "restores the pokemon to full HP otherwise", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @battle.performMove(@p1, rest) @p1.currentHP.should.equal @p1.stat('hp') it "sleeps the pokemon", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @p1.has(Status.Sleep).should.be.false @battle.performMove(@p1, rest) @p1.has(Status.Sleep).should.be.true it "fails if the pokemon is already asleep", -> shared.create.call(this) rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(1) @p1.attach(Status.Sleep) # execute instead of perform to avoid beforeMove callbacks. @battle.executeMove(rest, @p1, [ @p1 ]) mock.verify() it "cures the pokemon of adverse status effects", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @p1.attach(Status.Burn) @p1.has(Status.Burn).should.be.true @battle.performMove(@p1, rest) @p1.has(Status.Sleep).should.be.true @p1.has(Status.Burn).should.be.false it "always forces sleep turns to be 2", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", "sleep turns", 3) rest = @battle.getMove("Rest") @p1.setHP(1) @battle.performMove(@p1, rest) attachment = @p1.get(Status.Sleep) should.exist(attachment) attachment.should.have.property("turns") attachment.turns.should.equal(2) it "fails if the Pokemon cannot be slept", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Vital Spirit")] rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(1) @battle.performMove(@p1, rest) mock.verify() describe "Defog", -> it "lowers target's evasion by 1", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, defog) @p2.stages.should.containEql(evasion: -1) it "removes Reflect on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Reflect")) @p2.team.has(Attachment.Reflect).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Reflect).should.be.false it "removes Light Screen on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Light Screen")) @p2.team.has(Attachment.LightScreen).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.LightScreen).should.be.false it "removes Spikes on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Spikes")) @p2.team.has(Attachment.Spikes).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Spikes).should.be.false it "removes Stealth Rock on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @p2.team.has(Attachment.StealthRock).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.StealthRock).should.be.false it "removes Toxic Spikes on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @p2.team.has(Attachment.ToxicSpikes).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.ToxicSpikes).should.be.false it "removes Safeguard on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Safeguard")) @p2.team.has(Attachment.Safeguard).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Safeguard).should.be.false it "removes Mist on target's side" describe "Refresh", -> it "fails if the Pokemon has no status", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") mock = @sandbox.mock(refresh).expects('fail').once() @battle.performMove(@p1, refresh) mock.verify() it "restores a Pokemon's status", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") @p1.attach(Status.Burn) @p1.has(Status.Burn).should.be.true @battle.performMove(@p1, refresh) @p1.has(Status.Burn).should.be.false it "sends a message about status being restored", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") @p1.attach(Status.Burn) spy = @sandbox.spy(@battle, 'message') @battle.performMove(@p1, refresh) spy.args.join(',').should.containEql("#{@p1.name} healed its burn!") describe "Growth", -> it "boosts the pokemon's stats", -> shared.create.call(this, gen: 'bw') @battle.setWeather(Weather.SUN) @battle.performMove(@p1, @battle.getMove('Growth')) @p1.stages.should.containEql attack: 2, specialAttack: 2 describe "Reflect Type", -> it "copies the target's types", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Charmander")]) @battle.performMove(@p1, @battle.getMove('Reflect Type')) @p1.types.should.containEql "Fire" it "fails if the user has multitype", -> shared.create.call(this, team1: [Factory("Arceus", ability: "Multitype")], team2: [Factory("Toxicroak")]) @battle.performMove(@p1, @battle.getMove('Reflect Type')) @p1.types.should.containEql "Normal" describe "Retaliate", -> it "doubles in power if a pokemon on the user's side fainted last turn", -> shared.create.call this, team1: [Factory("Magikarp"), Factory("Slaking")] @p2.currentHP = 1 @battle.beginTurn() @battle.recordMove(@id1, @battle.getMove("Aqua Jet")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() retaliate = @battle.getMove("Retaliate") spy = @sandbox.spy(retaliate, 'basePower') @battle.performMove(@p2, retaliate) spy.returned(140).should.be.true it "deals normal damage otherwise", -> shared.create.call(this) retaliate = @battle.getMove("Retaliate") spy = @sandbox.spy(retaliate, 'basePower') @battle.performMove(@p1, retaliate) spy.returned(70).should.be.true describe "Role Play", -> it "copies the target's ability", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Magikarp", ability: "Levitate")] @battle.performMove(@p1, @battle.getMove('Role Play')) @p1.hasAbility("Levitate").should.be.true it "does not copy certain abilities", -> shared.create.call this, team1: [Factory("Magikarp"), ability: "Swift Swim"] team2: [Factory("Arceus", ability: "Multitype")] @battle.performMove(@p1, @battle.getMove('Role Play')) @p1.hasAbility("Multitype").should.be.false describe "Relic Song", -> it "transforms Meloetta", -> shared.create.call this, team1: [Factory("Meloetta")] team2: [Factory("Arceus")] @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("pirouette") @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("default") it "changes Meloetta to default forme after switching out", -> shared.create.call this, team1: [Factory("Meloetta"), Factory("Magikarp")] team2: [Factory("Arceus")] @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("pirouette") @battle.performSwitch(@p1, 1) @battle.performSwitch(@team1.first(), 1) @p1.forme.should.equal("default") it "does not transform Pokemon that are not Meloetta", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Magikarp")] @p1.forme.should.equal("default") @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("default") describe "Safeguard", -> it "protects the user's team from status", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Safeguard")) @battle.performMove(@p2, @battle.getMove("Thunder Wave")) @p1.has(Status.Paralyze).should.be.false it "protects the user's team from confusion", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Safeguard")) @battle.performMove(@p2, @battle.getMove("Confuse Ray")) @p1.has(Attachment.Confusion).should.be.false it "doesn't protect against status inflicted by the user", -> shared.create.call(this) @p1.team.attach(Attachment.Safeguard) @p1.setHP(1) @battle.performMove(@p1, @battle.getMove("Rest")) @p1.has(Status.Sleep).should.be.true it "protects against yawn being inflicted", -> shared.create.call(this) @p1.team.attach(Attachment.Safeguard) @battle.performMove(@p2, @battle.getMove("Yawn")) @p1.has(Attachment.Yawn).should.be.false it "doesn't prevent yawn's effect", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Yawn')) @battle.endTurn() @p2.has(Status.Sleep).should.be.false @p2.team.attach(Attachment.Safeguard) @battle.endTurn() @p2.has(Status.Sleep).should.be.true describe "Soak", -> it "changes the target's type to Water", -> shared.create.call this, team1: [Factory("<NAME>")] team2: [Factory("Smeargle")] @p2.types.should.not.eql ['Water'] @battle.performMove(@p1, @battle.getMove('Soak')) @p2.types.should.eql ['Water'] it "does not affect pure Water type Pokemon", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Mag<NAME>")] @p2.types.should.eql ['Water'] soak = @battle.getMove("Soak") mock = @sandbox.mock(soak).expects('fail').once() @battle.performMove(@p1, soak) mock.verify() it "does not affect Arceus", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus")] soak = @battle.getMove("Soak") mock = @sandbox.mock(soak).expects('fail').once() @battle.performMove(@p1, soak) mock.verify() describe 'Electro Ball', -> it 'has variable base power based on speed of user and target', -> shared.create.call this, team1: [Factory('Electrode', evs: {speed: 252}, nature: "Timid")] team2: [Factory('Smeargle')] move = @battle.getMove('Electro Ball') move.basePower(@battle, @p1, @p2).should.equal 80 describe "Snore", -> it "fails if the pokemon is awake", -> shared.create.call(this) snore = @battle.getMove("Snore") mock = @sandbox.mock(snore).expects('fail').once() @battle.performMove(@p1, snore) mock.verify() it "attacks the target when the user is asleep", -> shared.create.call this, snore = @battle.getMove("Snore") @p1.attach(Status.Sleep) mock = @sandbox.mock(snore).expects('hit').once() @battle.performMove(@p1, snore) mock.verify() describe "Worry Seed", -> it "changes the target's ability to Insomnia", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Mag<NAME>", ability: "Swift Swim")] @battle.performMove(@p1, @battle.getMove('Worry Seed')) @p2.hasAbility("Insomnia").should.be.true it "does not change some abilities", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus", ability: "Multitype")] worrySeed = @battle.getMove("Worry Seed") mock = @sandbox.mock(worrySeed).expects('fail').once() @battle.performMove(@p1, worrySeed) mock.verify() describe "Simple Beam", -> it "changes the target's ability to Simple", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("<NAME>", ability: "Swift Swim")] @battle.performMove(@p1, @battle.getMove('Simple Beam')) @p2.hasAbility("Simple").should.be.true it "does not change some abilities", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus", ability: "Multitype")] simpleBeam = @battle.getMove("Simple Beam") mock = @sandbox.mock(simpleBeam).expects('fail').once() @battle.performMove(@p1, simpleBeam) mock.verify() describe "Entrainment", -> it "copies the user's ability to the target", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Smeargle", ability: "Own Tempo")] @battle.performMove(@p1, @battle.getMove('Entrainment')) @p2.hasAbility("Swift Swim").should.be.true it "does not copy some abilities", -> shared.create.call this, team1: [Factory("Arceus", ability: "Multitype")] team2: [Factory("Magikarp", ability: "Swift Swim")] entrainment = @battle.getMove("Entrainment") mock = @sandbox.mock(entrainment).expects('fail').once() @battle.performMove(@p1, entrainment) mock.verify() describe "Natural Gift", -> it "changes power and type depending on the berry held by the user", -> shared.create.call this, team1: [Factory("Smeargle", item: 'Liechi Berry')] team2: [Factory("Magikarp")] move = @battle.getMove('Natural Gift') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(80) move.typeEffectiveness(@battle, @p1, @p2).should.equal(2) it "only works with certain items", -> shared.create.call this, team1: [Factory("Smeargle", item: 'Leftovers')] naturalGift = @battle.getMove('Natural Gift') mock = @sandbox.mock(naturalGift).expects('fail').once() @battle.performMove(@p1, naturalGift) mock.verify() it "should remove the item even if missing" describe "False Swipe", -> it "leaves the target with at least 1 HP", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("False Swipe")) @p2.currentHP.should.equal 1 it "does normal damage if the target has a substitute", -> shared.create.call(this) @p2.currentHP = 1 @p2.attach(Attachment.Substitute) falseSwipe = @battle.getMove("False Swipe") spy = @sandbox.spy(falseSwipe, 'calculateDamage') @battle.performMove(@p1, falseSwipe) spy.returned(0).should.be.false describe "Gastro Acid", -> it "suppresses the target's ability", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Gastro Acid")) @p2.has(Attachment.AbilitySuppress).should.be.true @p2.isAbilityBlocked().should.be.true it "continues turn by turn", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Gastro Acid")) @battle.endTurn() @battle.beginTurn() @p2.has(Attachment.AbilitySuppress).should.be.true @p2.isAbilityBlocked().should.be.true it "fails against some abilities", -> shared.create.call(this, team2: [Factory("Arceus", ability: "Multitype")]) gastroAcid = @battle.getMove("Gastro Acid") mock = @sandbox.mock(gastroAcid).expects('fail').once() @battle.performMove(@p1, gastroAcid) mock.verify() describe "Helping Hand", -> it "fails if there is no target", -> shared.create.call(this) helpingHand = @battle.getMove("Helping Hand") mock = @sandbox.mock(helpingHand).expects('fail').once() @battle.performMove(@p1, helpingHand) mock.verify() describe "Skill Swap", -> it "swaps the user's ability with the target's", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Smeargle", ability: "Own Tempo")] @battle.performMove(@p1, @battle.getMove('Skill Swap')) @p1.hasAbility("Own Tempo").should.be.true @p2.hasAbility("Swift Swim").should.be.true it "cannot swap some abilities", -> shared.create.call this, team1: [Factory("<NAME>", ability: "Swift Swim")] team2: [Factory("<NAME>", ability: "Wonder Guard")] skillSwap = @battle.getMove("Skill Swap") mock = @sandbox.mock(skillSwap).expects('fail').once() @battle.performMove(@p1, skillSwap) mock.verify() it "cannot swap the abilities if they are the same", -> shared.create.call this, team1: [Factory("Mag<NAME>", ability: "Swift Swim")] team2: [Factory("Magikarp", ability: "Swift Swim")] skillSwap = @battle.getMove("Skill Swap") mock = @sandbox.mock(skillSwap).expects('fail').once() @battle.performMove(@p1, skillSwap) mock.verify() it "activates abilities after swapping", -> shared.create.call this, team1: [Factory("<NAME>", ability: "Swift Swim")] team2: [Factory("<NAME>", ability: "Intimidate")] @battle.performMove(@p1, @battle.getMove('Skill Swap')) @p1.hasAbility("Intimidate").should.be.true @p2.hasAbility("Swift Swim").should.be.true @p2.stages.should.containEql(attack: -1) describe "Heal Block", -> it "lasts 5 turns", -> shared.create.call(this) healBlock = @battle.getMove("Heal Block") @battle.performMove(@p1, healBlock) for x in [0...5] @p2.has(Attachment.HealBlock).should.be.true @battle.endTurn() @p2.has(Attachment.HealBlock).should.be.false it 'prevents the target from executing a healing move', -> shared.create.call(this, team1: [ Factory('Magikarp', evs: {speed: 4}) ]) move = @battle.getMove('Recover') healBlock = @battle.getMove('Heal Block') mock = @sandbox.mock(move) mock.expects('execute').never() @battle.performMove(@p1, healBlock) @battle.performMove(@p2, move) mock.verify() it 'prevents the target from selecting a healing move', -> shared.create.call this, team2: [Factory("Magikarp", moves: [ "Splash", "Recover" ])] @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.beginTurn() requestedMoves = @battle.requestFor(@p2).moves requestedMoves.should.not.containEql 'Recover' it "prevents Abilities that heal from healing", -> shared.create.call this, team2: [Factory("Magikarp", ability: "Water Absorb")] @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @battle.performMove(@p1, @battle.getMove('Water Gun')) @p2.currentHP.should.equal 1 it "does not prevent Regenerator from healing", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Regenerator")] @p1.currentHP = 1 @battle.performMove(@p2, @battle.getMove('Heal Block')) @p1.switchOut(@battle) hp = Math.floor(@p1.stat('hp') / 3) @p1.currentHP.should.equal(1 + hp) it "prevents items that heal from healing", -> shared.create.call this, team2: [Factory("Magikarp", item: "Leftovers")] @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @p2.currentHP.should.equal 1 it "prevents Berries that heal from attempting to activate", -> shared.create.call this, team2: [Factory("Magikarp", item: "Sitrus Berry")] item = @p2.item hp = @p2.currentHP @p2.currentHP >>= 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @battle.performMove(@p1, @battle.getMove('Tackle')) @p2.currentHP.should.be.lessThan hp >> 1 @p2.item.should.equal item describe "Recycle", -> it "restores the user's last used item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] @p1.useItem() @battle.performMove(@p1, @battle.getMove("Recycle")) @p1.hasItem("Salac Berry").should.be.true it "fails if the user has an item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p1, recycle) @p1.hasItem("Salac Berry").should.be.true mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "fails if the user has no last used item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Air Balloon")] recycle = @battle.getMove("Recycle") @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.hasItem("Air Balloon").should.be.false mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "cannot restore an item that was forcefully removed", -> shared.create.call this, team1: [Factory("Magik<NAME>", item: "<NAME>erry")] recycle = @battle.getMove("Recycle") @battle.performMove(@p2, @battle.getMove("Covet")) @p1.hasItem("<NAME> Berry").should.be.false @p2.hasItem("<NAME> Berry").should.be.true mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "can restore the last used item if the current item is forcefully removed", -> shared.create.call this, team1: [Factory("Magikarp", item: "<NAME>")] team2: [Factory("Magikarp", item: "<NAME>")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p2, @battle.getMove("Trick")) @p1.hasItem("<NAME>").should.be.true @battle.performMove(@p2, @battle.getMove("Knock Off")) @battle.performMove(@p1, recycle) @p1.hasItem("<NAME> Berry").should.be.true it "cannot restore the last used item if it was restored and forcefully removed", -> shared.create.call this, team1: [Factory("Magikarp", item: "<NAME>")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p1, recycle) @p1.hasItem("<NAME>").should.be.true @battle.performMove(@p2, @battle.getMove("Knock Off")) mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify()
true
require '../helpers' {Attachment, Status} = require('../../server/bw/attachment') {Battle} = require('../../server/bw/battle') {Pokemon} = require('../../server/bw/pokemon') {Weather} = require('../../shared/weather') {Move} = require('../../server/bw/move') util = require '../../server/bw/util' {Protocol} = require '../../shared/protocol' {Factory} = require '../factory' should = require 'should' {_} = require 'underscore' shared = require '../shared' describe 'Move:', -> # Test every single move for their primary effects. shared.testEveryMove(Battle::MoveList, 'bw') it "multiplies critical hits by 2x", -> Move::criticalMultiplier.should.equal(2) it 'takes the name as the first parameter', -> new Move('Smooth Move').name.should.equal 'Smooth Move' it 'should have a priority of 0 by default', -> new Move().priority.should.equal 0 it 'can change the default priority', -> new Move(null, priority: -1).priority.should.equal -1 it 'should have a type of ??? by default', -> new Move().type.should.equal '???' it 'can change the default type', -> new Move(null, type: 'Grass').type.should.equal 'Grass' describe 'critical hit level', -> it "is 1 by default", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 1 it "can be changed from the default", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.activate() new Move(null, criticalHitLevel: 2) .criticalHitLevel(battle, attacker, defender).should.equal 2 it "is 3 if the attacker has Focus Energy", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() attacker.attach(Attachment.FocusEnergy) attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 it "is 3 if the attacker is Farfetch'd with a Stick", -> battle = new Battle('1', []) attacker = new Pokemon(species: "FarPI:NAME:<NAME>END_PI'd", item: 'Stick') defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 it "is 3 if the attacker is PI:NAME:<NAME>END_PIsey with a Lucky Punch", -> battle = new Battle('1', []) attacker = new Pokemon(species: "PI:NAME:<NAME>END_PI", item: 'Lucky Punch') defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 3 for item in ["Razor Claw", "Scope Lens"] do (item) -> it "is 2 if the attacker has a #{item}", -> battle = new Battle('1', []) attacker = new Pokemon(item: item) defender = new Pokemon() attacker.activate() new Move().criticalHitLevel(battle, attacker, defender).should.equal 2 describe "a critical hit", -> it "occurs when the RNG output < the critical hit level", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() move = new Move() @sandbox.stub(move, 'criticalHitLevel', -> 3) @sandbox.stub(battle.rng, 'next', -> 0.2) move.isCriticalHit(battle, attacker, defender).should.be.true it "does not occur when the RNG output >= the critical hit level", -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() @sandbox.stub(battle.rng, 'next', -> 0.0700) new Move().isCriticalHit(battle, attacker, defender).should.be.false it "ignores opponent defensive boosts", -> shared.create.call(this) defense = @p2.stat('defense') specialDefense = @p2.stat('specialDefense') @p1.crit = true @p2.boost(defense: 1, specialDefense: 2) move = new Move(null, damage: 'physical') move.pickDefenseStat(@p1, @p2).should.equal(defense) move = new Move(null, damage: 'special') move.pickDefenseStat(@p1, @p2).should.equal(specialDefense) it "does not ignore opponent defensive drops", -> shared.create.call(this) defense = @p2.stat('defense') specialDefense = @p2.stat('specialDefense') @p1.crit = true @p2.boost(defense: -1, specialDefense: -2) move = new Move(null, damage: 'physical') move.pickDefenseStat(@p1, @p2).should.equal Math.floor(2 / 3 * defense) move = new Move(null, damage: 'special') move.pickDefenseStat(@p1, @p2).should.equal(specialDefense >> 1) it "ignores user stat drops", -> shared.create.call(this) attack = @p1.stat('attack') specialAttack = @p1.stat('specialAttack') @p1.crit = true @p1.boost(attack: -1, specialAttack: -2) move = new Move(null, damage: 'physical') move.pickAttackStat(@p1, @p2).should.equal(attack) move = new Move(null, damage: 'special') move.pickAttackStat(@p1, @p2).should.equal(specialAttack) it "does not ignore user stat boosts", -> shared.create.call(this) attack = @p1.stat('attack') specialAttack = @p1.stat('specialAttack') @p1.crit = true @p1.boost(attack: 1, specialAttack: 2) move = new Move(null, damage: 'physical') move.pickAttackStat(@p1, @p2).should.equal Math.floor(1.5 * attack) move = new Move(null, damage: 'special') move.pickAttackStat(@p1, @p2).should.equal(2 * specialAttack) it "does not carry over in multihit moves", -> shared.create.call(this) move = new Move("multihit", minHits: 4, maxHits: 4, power: 20) # Crit only once move.isCriticalHit = -> move.isCriticalHit = -> false true mock = @sandbox.mock(@p2).expects('informCriticalHit').once() move.execute(@battle, @p1, [ @p2 ]) mock.verify() describe "-1 crit ratios", -> beforeEach -> @battle = new Battle('1', []) @attacker = new Pokemon() @move = new Move("TestMove", criticalHitLevel: -1) @sandbox.stub(@battle.rng, 'next', -> 1) it "fails if the defender has Battle Armor", -> defender = new Pokemon(ability: 'Battle Armor') @move.isCriticalHit(@battle, @attacker, defender).should.be.false it "fails if the defender has Shell Armor", -> defender = new Pokemon(ability: 'Shell Armor') @move.isCriticalHit(@battle, @attacker, defender).should.be.false it "always succeeds if opponent does not have Battle or Shell Armor", -> defender = new Pokemon() @move.isCriticalHit(@battle, @attacker, defender).should.be.true describe 'type effectiveness', -> testTypeEffectiveness = (type, defense, expected) -> battle = new Battle('1', []) attacker = new Pokemon() defender = new Pokemon() defender.types = defense move = new Move(null, type: type) move.typeEffectiveness(battle, attacker, defender).should.equal expected it 'is 0 if the enemy has an immunity to the type', -> testTypeEffectiveness('Ground', ['Electric', 'Flying'], 0) it 'is 1 if the enemy is neutral to the type', -> testTypeEffectiveness('Ground', ['Normal'], 1) it 'is 2 if the enemy is weak to the type', -> testTypeEffectiveness('Ground', ['Electric'], 2) it 'is 4 if the enemy is extra weak to the type', -> testTypeEffectiveness('Rock', ['Fire', 'Flying'], 4) it 'is 1/2 if the enemy is resistant to the type', -> testTypeEffectiveness('Fire', ['Fire', 'Flying'], .5) it 'is 1/4 if the enemy is extra resistant to the type', -> testTypeEffectiveness('Fire', ['Fire', 'Water'], .25) describe "#burnCalculation", -> it "returns 1 normally", -> attacker = new Pokemon() new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal 1 it "returns .5 with a physical move, no Guts ability, and a burned user", -> attacker = new Pokemon() attacker.attach(Status.Burn) new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal .5 it "returns 1 with a special move, no Guts ability, and a burned user", -> attacker = new Pokemon() attacker.attach(Status.Burn) new Move(null, damage: 'special') .burnCalculation(attacker).should.equal 1 it "returns 1 with a physical move, Guts ability, and a burned user", -> attacker = new Pokemon(ability: "Guts") attacker.attach(Status.Burn) new Move(null, damage: 'physical') .burnCalculation(attacker).should.equal 1 describe 'an attack with 0 accuracy', -> it 'can never miss', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(accuracy: 0).willMiss(battle, a, d).should.be.false describe 'accuracy and evasion boosts', -> it 'heighten and lower the chances of a move hitting', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(null, accuracy: 100).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = 3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = 3 d.stages.evasion = 3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 50 it 'keeps heightening and lowering chances when negative', -> battle = new Battle('1', []) a = new Pokemon() d = new Pokemon() new Move(null, accuracy: 100).chanceToHit(battle, a, d).should.eql 100 a.stages.accuracy = -3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 25 a.stages.accuracy = -3 d.stages.evasion = -3 new Move(null, accuracy: 50).chanceToHit(battle, a, d).should.eql 50 describe '#hasFlag', -> it 'returns true if a move has a specific flag', -> new Move(null, flags: ['superman', 'batman']) .hasFlag('batman').should.be.true it "returns false if a move doesn't have a specific flag", -> new Move(null, flags: ['superman', 'batman']) .hasFlag('catwoman').should.be.false describe '#execute', -> it 'calls hit multiple times for multihit moves', -> shared.create.call(this) move = new Move("multihit", minHits: 4, maxHits: 4) mock = @sandbox.mock(move).expects('hit').exactly(4) move.execute(@battle, @p1, [@p2]) mock.verify() it 'only hits up until user faints', -> shared.create.call(this, team2: [Factory('Ferrothorn', ability: 'Iron Barbs')]) move = new Move("multihit", minHits: 4, maxHits: 4, flags: ["contact"]) mock = @sandbox.mock(move).expects('hit').exactly(1) @p1.currentHP = 1 move.execute(@battle, @p1, [@p2]) mock.verify() it 'only hits up until user falls asleep', -> shared.create.call(this, team2: [Factory('Shroomish', ability: 'Effect Spore')]) shared.biasRNG.call(this, "randInt", 'effect spore', 4) # Never trigger move = new Move("multihit", minHits: 4, maxHits: 4, flags: ["contact"]) hit = move.hit times = 0 @sandbox.stub move, 'hit', => times++ if times == 2 shared.biasRNG.call(this, "randInt", 'effect spore', 1) # Sleep else shared.biasRNG.call(this, "randInt", 'effect spore', 4) # Nothing hit.apply(move, arguments) @p1.currentHP = 1 move.execute(@battle, @p1, [@p2]) times.should.equal(2) describe "#use", -> it "returns false if the target's type is immune", -> shared.create.call(this) move = new Move("attacking", damage: "special", type: "Normal") @p2.types = [ "Ghost" ] move.use(@battle, @p1, @p2).should.be.false it "returns true if target is immune but move is non-damaging", -> shared.create.call(this) move = new Move("attacking", damage: "non-damaging", type: "Normal") @p2.types = [ "Ghost" ] should.not.exist move.use(@battle, @p1, @p2) describe '#hit', -> it "deals damage no higher than the pokemon's remaining HP", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Tackle")) @p2.currentHP.should.equal(0) it "deals normal damage if the Pokemon has a substitute", -> shared.create.call(this) spy = @sandbox.spy(@p2, 'damage') @p2.currentHP = (@p2.currentHP >> 2) + 1 @battle.performMove(@p2, @battle.getMove("Substitute")) @battle.performMove(@p1, @battle.getMove("Tackle")) spy.returned(1).should.be.false describe '#weatherModifier', -> it "is 0x1800 when the move is Fire-type and the weather is sunny", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1800) it "is 0x800 when the move is Fire-type and the weather is rainy", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x800) it "is 0x1800 when the move is Water-type and the weather is rainy", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = new Move(null, type: "Water") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1800) it "is 0x1800 when the move is Water-type and the weather is sunny", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = new Move(null, type: "Water") move.weatherModifier(@battle, @p1, @p2).should.equal(0x800) it "is 0x1000 otherwise", -> shared.create.call(this) @battle.setWeather(Weather.SAND) move = new Move(null, type: "Fire") move.weatherModifier(@battle, @p1, @p2).should.equal(0x1000) describe "#baseDamage", -> it "reduces damage by ~1.5 if the weather is sandstorm", -> shared.create.call(this) @p2.types = [ "Rock" ] move = new Move(null, power: 50, type: "Fire", damage: 'special') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.be.lessThan(damage) it "doesn't apply the sandstorm effect if target isn't Rock-type", -> shared.create.call(this) @p2.types = [ "Ground" ] move = new Move(null, power: 50, type: "Fire", damage: 'special') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.equal(damage) it "doesn't apply the sandstorm effect if move is non-special", -> shared.create.call(this) @p2.types = [ "Rock" ] move = new Move(null, power: 50, type: "Fire", damage: 'physical') damage = move.baseDamage(@battle, @p1, @p2) @battle.setWeather(Weather.SAND) move.baseDamage(@battle, @p1, @p2).should.equal(damage) describe "BW Moves:", -> describe "Splash", -> shared.shouldDoNoDamage('Splash') describe 'a multi-hit move', -> it 'potentially activates Berries after each hit', -> shared.create.call this, team1: [Factory('Magikarp', item: "Sitrus Berry", ability: "Skill Link")] team2: [Factory('Magikarp', item: "Sitrus Berry", ability: "Iron Barbs")] hp = @p1.currentHP @p1.currentHP = (hp >> 1) + 1 @p2.currentHP = 4 move = @battle.getMove('Tail Slap') @sandbox.stub(move, 'calculateDamage', -> 1) @battle.performMove(@p1, move) @p1.currentHP.should.equal (hp >> 1) + 1 - (5 * (hp >> 3)) + (hp >> 2) @p2.currentHP.should.equal 4 + (hp >> 2) - 5 describe 'jump kick attacks', -> it 'has 50% recoil if it misses', -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'miss', 100) oldHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Hi Jump Kick')) (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) it "has 50% recoil if the target is immune", -> shared.create.call(this, team2: [Factory("GPI:NAME:<NAME>END_PIar")]) oldHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Hi Jump Kick')) (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) it "has 50% recoil if the target protects itself", -> shared.create.call(this) oldHP = @p1.stat('hp') @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove("Hi Jump Kick")) @battle.continueTurn() (oldHP - @p1.currentHP).should.equal Math.floor(oldHP / 2) describe 'a drain attack', -> it 'recovers a percentage of the damage dealt, rounded down', -> shared.create.call this, team1: [Factory('Conkeldurr')] team2: [Factory('Hitmonchan')] startHP = 1 @p1.currentHP = startHP hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Drain Punch')) damage = (hp - @p2.currentHP) (@p1.currentHP - startHP).should.equal Math.ceil(damage / 2) it 'cannot recover to over 100% HP', -> shared.create.call this, team1: [Factory('ConkeldurPI:NAME:<NAME>END_PI')] team2: [Factory('HitPI:NAME:<NAME>END_PI')] hp = @p1.currentHP = @p1.stat('hp') @battle.performMove(@p1, @battle.getMove('Drain Punch')) (@p1.currentHP - hp).should.equal 0 it "does not recover more than the damage dealt", -> shared.create.call(this) drainPunch = @battle.getMove('Drain Punch') @sandbox.stub(drainPunch, 'baseDamage', -> 9999) @p2.currentHP = 2 @p1.currentHP = 1 @battle.performMove(@p1, drainPunch) @p2.currentHP.should.be.lessThan(1) @p1.currentHP.should.equal(2) describe 'weight-based attacks', -> it 'has 80 base power if the pokemon is 50.2kg', -> shared.create.call this, team1: [Factory('Celebi')] team2: [Factory('PI:NAME:<NAME>END_PI')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Grass Knot')) (hp - @p2.currentHP).should.equal 94 it 'has 120 base power if the pokemon is >200kg', -> shared.create.call this, team1: [Factory('Celebi')] team2: [Factory('Gyarados')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Grass Knot')) (hp - @p2.currentHP).should.equal 153 describe 'a pokemon using a primary boosting move', -> it "doesn't do damage if base power is 0", -> shared.create.call this, team1: [Factory('Gyarados')] team2: [Factory('HitPI:NAME:<NAME>END_PIchan')] @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @p2.currentHP.should.equal @p2.stat('hp') it "boosts the pokemon's stats", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI')] team2: [Factory('HitPI:NAME:<NAME>END_PI')] @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @p1.stages.should.containEql attack: 1, speed: 1 it "affects type-immune pokemon", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI')] team2: [Factory('GPI:NAME:<NAME>END_PI')] @battle.performMove(@p1, @battle.getMove('Growl')) @p2.stages.attack.should.equal -1 it "has the boosts removed on switch", -> shared.create.call(this, team1: (Factory("PI:NAME:<NAME>END_PI") for x in [1..2])) @battle.performMove(@p1, @battle.getMove('Dragon Dance')) @battle.performSwitch(@p1, 1) @p1.stages.should.containEql(attack: 0, speed: 0) describe 'a pokemon using a damaging move that also boosts stats on hit', -> it "deals damage and boosts stats", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI')] team2: [Factory('GPI:NAME:<NAME>END_PIados')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Leaf Storm')) @p1.stages.specialAttack.should.equal -2 (hp - @p2.currentHP).should.equal 178 describe 'Low Sweep', -> it "lowers the target's speed by 1", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.equal(-1) it "does not lower the target's speed by 1 if the target faints", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.not.equal(-1) it "does not lower the target's speed by 1 if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute) @battle.performMove(@p1, @battle.getMove('Low Sweep')) @p2.stages.speed.should.not.equal(-1) describe 'Flame Charge', -> it "raises the user's speed by 1", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) it "raises the user's speed by 1 even if the target faints", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) it "raises the user's speed by 1 even if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute) @battle.performMove(@p1, @battle.getMove('Flame Charge')) @p1.stages.speed.should.equal(1) describe 'a pokemon using a move with a secondary boosting effect', -> it "has a chance to activate", -> shared.create.call this, team1: [Factory('Mew')] team2: [Factory('Hitmonchan')] shared.biasRNG.call(this, "next", 'secondary boost', 0) # 100% chance attack = @p1.stat('attack') speed = @p1.stat('speed') @battle.performMove(@p1, @battle.getMove('AncientPower')) @p1.stages.should.containEql { attack: 1, defense: 1, speed: 1, specialAttack: 1, specialDefense: 1 } describe 'a pokemon using Acrobatics', -> it 'gets double the base power without an item', -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI')] team2: [Factory('PI:NAME:<NAME>END_PI')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Acrobatics')) damage = (hp - @p2.currentHP) damage.should.equal 36 it 'has normal base power with an item', -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI', item: 'PI:NAME:<NAME>END_PI')] team2: [Factory('PI:NAME:<NAME>END_PI')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Acrobatics')) damage = (hp - @p2.currentHP) damage.should.equal 18 testRecoilMove = (moveName) -> describe "a pokemon using #{moveName}", -> it 'receives a percentage of the damage rounded half up', -> shared.create.call(this) startHP = @p1.currentHP hp = @p2.currentHP move = @battle.getMove(moveName) @battle.performMove(@p1, move) recoil = -move.recoil / 100 damage = (hp - @p2.currentHP) (startHP - @p1.currentHP).should.equal Math.round(damage * recoil) it 'receives a minimum of 1 HP of recoil', -> shared.create.call(this) startHP = @p1.currentHP hp = @p2.currentHP move = @battle.getMove(moveName) stub = @sandbox.stub(move, 'calculateDamage', -> .6) move = @battle.getMove(moveName) @battle.performMove(@p1, move) damage = (hp - @p2.currentHP) (startHP - @p1.currentHP).should.equal 1 it "does not recoil if no damage was dealt", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove(moveName)) @battle.continueTurn() @p1.currentHP.should.equal(@p1.stat('hp')) testRecoilMove("Brave Bird") testRecoilMove("Double-Edge") testRecoilMove("Flare Blitz") testRecoilMove("Head Charge") testRecoilMove("Head Smash") testRecoilMove("Submission") testRecoilMove("Take Down") testRecoilMove("Volt Tackle") testRecoilMove("Wild Charge") testRecoilMove("Wood Hammer") testDrainMove = (moveName) -> describe moveName, -> it "absorbs a percentage of the damage rounded up", -> shared.create.call(this) @p1.currentHP = 1 move = @battle.getMove(moveName) @battle.performMove(@p1, move) drain = move.recoil / 100 damage = (@p2.stat('hp') - @p2.currentHP) (@p1.currentHP - 1).should.equal Math.ceil(damage * drain) it 'receives a minimum of 1 HP of drain', -> shared.create.call(this) @p1.currentHP = @p2.currentHP = 1 move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p1.currentHP.should.equal(2) it "does not drain if no damage was dealt", -> shared.create.call(this) @p1.currentHP = 1 @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove(moveName)) @battle.continueTurn() @p1.currentHP.should.equal(1) testDrainMove("Absorb") testDrainMove("Drain Punch") testDrainMove("Giga Drain") testDrainMove("Horn Leech") testDrainMove("Leech Life") testDrainMove("Mega Drain") describe 'Haze', -> shared.shouldDoNoDamage('Haze') it 'removes all status boosts from each pokemon', -> shared.create.call(this) # Create artificial boosts. @p1.stages.attack = 2 @p1.stages.evasion = -1 @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Haze")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p1.stages.should.eql neutralBoosts @p2.stages.should.eql neutralBoosts describe 'Seismic Toss and Night Shade', -> it 'does exactly the same damage as their level', -> shared.create.call this, team1: [Factory('Blissey')] team2: [Factory('Mew')] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Seismic Toss')) (hp - @p2.currentHP).should.equal 100 it 'triggers Focus Sash', -> shared.create.call this, team1: [Factory('Blissey')] team2: [Factory('Mew', level: 1, item: "Focus Sash")] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Seismic Toss')) @p2.currentHP.should.equal(1) describe 'Psywave', -> it 'does user.level/2 damage minimum', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] shared.biasRNG.call(this, "randInt", 'psywave', 5) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 50 it 'does user.level * 1.5 damage maximum', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] move = @battle.getMove('Psywave') shared.biasRNG.call(this, "randInt", 'psywave', 15) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 150 it 'rounds down to the nearest .1 multiplier', -> shared.create.call this, team1: [Factory('Weezing')] team2: [Factory('Mew')] move = @battle.getMove('Psywave') shared.biasRNG.call(this, "randInt", 'psywave', 6.09) hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Psywave')) (hp - @p2.currentHP).should.equal 60 describe 'facade', -> it 'doubles the base power if burned, poisoned, or paralyzed', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('PI:NAME:<NAME>END_PIikarp')] hp = @p2.currentHP @p1.attach(Status.Paralyze) move = @battle.getMove('Facade') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) describe 'reversal and flail', -> it 'have 200 base power at 1 hp', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('Magikarp')] @p1.currentHP = 1 move = @battle.getMove('Flail') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal 200 it 'have 40 base power at 50% hp', -> shared.create.call this, team1: [Factory('Zangoose')] team2: [Factory('Magikarp')] @p1.currentHP = Math.floor(@p1.stat('hp') / 2) move = @battle.getMove('Flail') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal 40 describe 'eruption and water spout', -> beforeEach -> shared.create.call this, team1: [Factory('CamPI:NAME:<NAME>END_PI')] team2: [Factory('Mew')] @attacker = @p1 @defender = @p2 @move = @battle.getMove('Eruption') it 'has at least one base power', -> @attacker.currentHP = 1 @move.basePower(@battle, @attacker, @defender).should.equal 1 it 'has 75 base power at 50% hp', -> @attacker.currentHP = @attacker.stat('hp') / 2 @move.basePower(@battle, @attacker, @defender).should.equal 75 it 'has 150 base power at 100% hp', -> @move.basePower(@battle, @attacker, @defender).should.equal 150 describe 'gyro ball', -> it 'has 150 base power maximum', -> shared.create.call this, team1: [Factory('Forretress', ivs: {speed: 0})] team2: [Factory('Jolteon', evs: {speed: 252}, nature: "Timid")] move = @battle.getMove('Gyro Ball') attacker = @p1 defender = @p2 attacker.stages.speed = -6 move.basePower(@battle, attacker, defender).should.equal 150 it 'has variable base power based on speed of target and user', -> shared.create.call this, team1: [Factory('Electrode', evs: {speed: 252}, nature: "Jolly")] team2: [Factory('Magikarp', ivs: {speed: 0})] move = @battle.getMove('Gyro Ball') attacker = @p1 defender = @p2 attacker.stages.speed = -6 move.basePower(@battle, attacker, defender).should.equal 40 describe 'brine', -> it 'has normal base power if the target has over 50% HP', -> shared.create.call this, team1: [Factory('Empoleon')] team2: [Factory('PI:NAME:<NAME>END_PI')] move = @battle.getMove('Brine') @p2.currentHP = Math.floor(@p2.currentHP / 2) + 1 move.basePower(@battle, @p1, @p2).should.equal 65 it 'doubles base power if the target has 50% or less HP', -> shared.create.call this, team1: [Factory('Empoleon')] team2: [Factory('PI:NAME:<NAME>END_PI')] move = @battle.getMove('Brine') @p2.currentHP = Math.floor(@p2.currentHP / 2) move.basePower(@battle, @p1, @p2).should.equal 130 describe 'Disable', -> shared.shouldDoNoDamage('Disable') it 'gives the disabled attachment', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @p2.has(Attachment.Disable).should.be.true it "prevents the target's last move from being selected", -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @battle.beginTurn() @p2.validMoves().should.not.containEql(move) @p2.validMoves().should.have.length(@p2.moves.length - 1) it 'wears off after 4 turns', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) @battle.endTurn() @battle.endTurn() @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Disable).should.be.false it 'stops the execution of a disabled move', -> shared.create.call(this) disable = @battle.getMove("Disable") move = @p2.moves[0] @battle.performMove(@p2, move) @battle.performMove(@p1, disable) mock = @sandbox.mock(move).expects('execute').never() @battle.performMove(@p2, move) mock.verify() it 'fails if the target has not moved since it was active', -> shared.create.call(this) disable = @battle.getMove("Disable") mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p1, disable) mock.verify() it 'fails if the target does not know the move it used', -> shared.create.call(this) disable = @battle.getMove("Disable") struggle = @battle.getMove("Struggle") mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p2, struggle) @battle.performMove(@p1, disable) mock.verify() it "fails if the target's last move has 0 PP", -> shared.create.call(this) disable = @battle.getMove("Disable") splash = @battle.getMove("Splash") @battle.performMove(@p2, splash) @p2.setPP(splash, 0) mock = @sandbox.mock(disable).expects('fail').once() @battle.performMove(@p1, disable) mock.verify() describe 'hidden power', -> it 'has a max power of 70', -> ivs = { hp: 31, attack: 31, defense: 31, specialAttack: 31, specialDefense: 31, speed: 31 } shared.create.call this, team1: [Factory('MagPI:NAME:<NAME>END_PI', ivs: ivs)] team2: [Factory('Magikarp')] move = @battle.getMove('Hidden Power') move.basePower(@battle, @p1, @p2).should.eql 70 it 'has a min power of 30', -> ivs = { hp: 0, attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0 } shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI', ivs: ivs)] team2: [Factory('MagikPI:NAME:<NAME>END_PI')] move = @battle.getMove('Hidden Power') move.basePower(@battle, @p1, @p2).should.eql 30 it 'is dark when all ivs are 31', -> ivs = { hp: 31, attack: 31, defense: 31, specialAttack: 31, specialDefense: 31, speed: 31 } shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI', ivs: ivs)] team2: [Factory('PI:NAME:<NAME>END_PI')] move = @battle.getMove('Hidden Power') move.getType(@battle, @p1, @p2).should.eql 'Dark' it 'is fighting when all ivs are 0', -> ivs = { hp: 0, attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0 } shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI', ivs: ivs)] team2: [Factory('PI:NAME:<NAME>END_PI')] move = @battle.getMove('Hidden Power') move.getType(@battle, @p1, @p2).should.eql 'Fighting' describe 'yawn', -> shared.shouldDoNoDamage('Yawn') shared.shouldFailIfUsedTwice("Yawn") it 'gives the yawn attachment', -> shared.create.call this, team1: [Factory('CamPI:NAME:<NAME>END_PIupt')] team2: [Factory('PI:NAME:<NAME>END_PI')] @battle.performMove(@p1, @battle.getMove('Yawn')) @p2.has(Attachment.Yawn).should.be.true it 'puts the opponent to sleep at the end of the second turn', -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI')] team2: [Factory('PI:NAME:<NAME>END_PI')] @battle.performMove(@p1, @battle.getMove('Yawn')) @battle.endTurn() @p2.has(Status.Sleep).should.be.false @battle.endTurn() @p2.has(Status.Sleep).should.be.true it "fails if the target already is statused", -> shared.create.call(this) yawn = @battle.getMove('Yawn') mock = @sandbox.mock(yawn).expects('fail').once() @p2.attach(Status.Paralyze) @battle.performMove(@p1, yawn) mock.verify() describe 'an OHKO move', -> it 'ignores accuracy/evasion modifiers', -> shared.create.call(this) @p1.stages.accuracy = -6 @p2.stages.evasion = 6 acc = @battle.getMove('Sheer Cold').chanceToHit(@battle, @p1, @p2) acc.should.equal 30 it "does damage equal to the target's total hp", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI')] team2: [Factory('PI:NAME:<NAME>END_PI')] @p2.currentHP = Math.floor(@p2.stat('hp') / 2) @controller.makeMove(@id1, 'Sheer Cold') @controller.makeMove(@id2, 'Splash') move = @battle.getMove('Sheer Cold') damage = move.calculateDamage(@battle, @p1, @p2) damage.should.equal @p2.stat('hp') describe 'a recovery move', -> shared.shouldDoNoDamage('Recover') it "recovers 50% of the target's HP, rounded half up", -> shared.create.call(this) hp = @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Softboiled')) recoverHP = Math.round(@p1.stat('hp') / 2) (@p1.currentHP - hp).should.equal recoverHP it "fails if the user's HP is full", -> shared.create.call(this) softboiled = @battle.getMove('Softboiled') mock = @sandbox.mock(softboiled).expects('fail').once() @battle.performMove(@p1, softboiled) mock.verify() describe 'Knock Off', -> it "deals damage", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.currentHP.should.be.lessThan @p2.stat('hp') it "removes the target's item", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) should.not.exist @p2.item it "does not remove unremovable items", -> shared.create.call this, team2: [Factory('Magikarp', item: "Air Mail")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "does not knock off items from pokemon with Sticky Hold", -> shared.create.call this, team2: [Factory('Magikarp', ability: "Sticky Hold", item: "Leftovers")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "takes damage from Rocky Helmet", -> shared.create.call this, team2: [Factory('Magikarp', item: "Rocky Helmet")] @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.false @p1.currentHP.should.be.lessThan(@p1.stat('hp')) it "doesn't knock off if substitute fades", -> shared.create.call this, team2: [Factory('Magikarp', item: "Leftovers")] @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true it "doesn't knock off if user is fainted", -> shared.create.call this, team2: [Factory('Magikarp', item: "Rocky Helmet")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Knock Off")) @p2.hasItem().should.be.true @p1.isFainted().should.be.true it 'removes healing Berries before they can activate', -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "PI:NAME:<NAME>END_PI Berry")] @p2.currentHP = 2 move = @battle.getMove('Knock Off') @sandbox.stub(move, 'calculateDamage', -> 1) @battle.performMove(@p1, move) @p2.currentHP.should.equal 1 describe 'trick and switcheroo', -> shared.shouldDoNoDamage('Trick') it "isn't affected by type-immunities", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Stick')] team2: [Factory('Drapion', item: "Leftovers")] item1 = @p1.item item2 = @p2.item trick = @battle.getMove('Trick') @battle.performMove(@p1, trick) @p2.item.should.equal item1 @p1.item.should.equal item2 it "swaps the target and user's item", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI', item: 'Stick')] team2: [Factory('MagikPI:NAME:<NAME>END_PI', item: "Leftovers")] item1 = @p1.item item2 = @p2.item @controller.makeMove(@id1, 'Trick') @controller.makeMove(@id2, 'Splash') @p2.item.should.equal item1 @p1.item.should.equal item2 it "fails if the user has Sticky Hold", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI', ability: "Sticky Hold", item: 'Stick')] team2: [Factory('PI:NAME:<NAME>END_PI', item: "Leftovers")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has Sticky Hold", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI', item: 'Stick')] team2: [Factory('PI:NAME:<NAME>END_PI', ability: "Sticky Hold", item: "Leftovers")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "succeeds if only one pokemon has an item", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI', item: 'Stick')] team2: [Factory('PI:NAME:<NAME>END_PI')] trick = @battle.getMove('Trick') item1 = @p1.item @battle.performMove(@p1, trick) should.not.exist(@p1.item) @p2.item.should.equal(item1) it "fails if neither the user nor the target has an item", -> shared.create.call this, team1: [Factory('PI:NAME:<NAME>END_PI')] team2: [Factory('PI:NAME:<NAME>END_PI')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is holding a Mail", -> shared.create.call this, team1: [Factory('Alakazam', item: 'Air Mail')] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is holding a Mail", -> shared.create.call this, team1: [Factory('Alakazam')] team2: [Factory('Magikarp', item: 'Air Mail')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is Giratina-O", -> shared.create.call this, team1: [Factory('Giratina', forme: "origin")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is Giratina-O", -> shared.create.call this, team2: [Factory('Giratina', forme: "origin")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has a Substitute", -> shared.create.call(this) trick = @battle.getMove('Trick') substitute = @battle.getMove('Substitute') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p2, substitute) @battle.performMove(@p1, trick) mock.verify() it "fails if the user has Multitype with a plate item", -> shared.create.call this, team1: [Factory('Magikarp', ability: "Multitype", item: "Grass Plate")] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target has Multitype with a plate item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', ability: "Multitype", item: "Grass Plate")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the target is Genesect with a Drive item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Genesect', item: "Burn Drive")] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() it "fails if the user is Genesect with a Drive item", -> shared.create.call this, team1: [Factory('Genesect', item: "Burn Drive")] team2: [Factory('Magikarp')] trick = @battle.getMove('Trick') mock = @sandbox.mock(trick).expects('fail').once() @battle.performMove(@p1, trick) mock.verify() describe 'memento', -> shared.shouldDoNoDamage('Memento') it "faints the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Memento")) @p1.isFainted().should.be.true it "reduces the attack and special attack of the target by two stages", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.containEql attack: -2, specialAttack: -2 it "doesn't reduce stats if target is protected, and doesn't faint user", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Protect")) @battle.recordMove(@id1, @battle.getMove("Memento")) @battle.continueTurn() @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.false it "doesn't reduce stats if target has a substitute, and doesn't faint user", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Substitute")) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.false it "doesn't reduce stats if target has Clear Body, but faints user", -> shared.create.call(this, team2: [Factory('Magikarp', ability: 'Clear Body')]) @battle.performMove(@p1, @battle.getMove("Memento")) @p2.stages.should.not.containEql attack: -2, specialAttack: -2 @p1.isFainted().should.be.true describe 'magnitude', -> it "has variable base power", -> shared.create.call this, team1: [Factory('DPI:NAME:<NAME>END_PI')] team2: [Factory('PI:NAME:<NAME>END_PIikPI:NAME:<NAME>END_PI')] move = @battle.getMove('Magnitude') shared.biasRNG.call(this, "randInt", 'magnitude', 50) move.basePower(@battle, @p1, @p2).should.equal 70 describe 'Pain Split', -> it "doesn't make a pokemon's HP go over their max", -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @controller.makeMove(@id1, 'Pain Split') @controller.makeMove(@id1, 'Seismic Toss') @p1.currentHP.should.equal @p1.stat('hp') it "averages user and target current HP", -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @p1.currentHP = 2 @controller.makeMove(@id1, 'Pain Split') @controller.makeMove(@id2, 'Seismic Toss') @p1.currentHP.should.equal Math.min(326, @p1.stat('hp')) @p2.currentHP.should.equal Math.min(326, @p2.stat('hp')) it "affects Ghosts", -> shared.create.call this, team2: [Factory('Gengar')] painSplit = @battle.getMove("Pain Split") mock = @sandbox.mock(painSplit).expects('hit').once() @battle.performMove(@p1, painSplit) mock.verify() it "is blocked by Protect", -> shared.create.call(this) @p1.currentHP = 1 painSplit = @battle.getMove("Pain Split") mock = @sandbox.mock(painSplit).expects('hit').never() @battle.recordMove(@id1, painSplit) @battle.determineTurnOrder() @battle.performMove(@p2, @battle.getMove("Protect")) @battle.performMove(@p1, painSplit) mock.verify() @p1.currentHP.should.equal(1) @p2.currentHP.should.equal(@p2.stat('hp')) describe 'Belly Drum', -> shared.shouldDoNoDamage('Belly Drum') it "maximizes attack", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @p1.stages.attack = -6 @controller.makeMove(@id1, 'Belly Drum') @controller.makeMove(@id2, 'Splash') @p1.stages.attack.should.equal 6 it "cuts the pokemon's HP by half", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @controller.makeMove(@id1, 'PI:NAME:<NAME>END_PI') @controller.makeMove(@id2, 'Splash') hp = @p1.stat('hp') (hp - @p1.currentHP).should.equal Math.floor(hp / 2) it "fails if the pokemon's HP is less than half", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] hp = @p1.currentHP = Math.floor(@p1.stat('hp') / 2) - 1 @controller.makeMove(@id1, 'PI:NAME:<NAME>END_PI') @controller.makeMove(@id2, 'Splash') @p1.currentHP.should.equal hp @p1.stages.attack.should.equal 0 it "fails if the pokemon's attack is already maximized", -> shared.create.call this, team1: [Factory('Poliwrath')] team2: [Factory('Magikarp')] @p1.boost(attack: 12) bd = @battle.getMove('PI:NAME:<NAME>END_PI') mock = @sandbox.mock(bd).expects('fail').once() @battle.performMove(@p1, bd) mock.verify() @p1.currentHP.should.equal(@p1.stat('hp')) describe 'acupressure', -> shared.shouldDoNoDamage('Acupressure') it "raises a random stat that can be raised", -> shared.create.call this, team1: [Factory('Shuckle')] team2: [Factory('Magikarp')] stages = _.clone(@p1.stages) @controller.makeMove(@id1, 'Acupressure') @controller.makeMove(@id2, 'Splash') @p1.stages.should.not.eql stages it "fails if the Pokemon has maximum stats", -> shared.create.call this, team1: [Factory('Shuckle')] team2: [Factory('Magikarp')] @p1.stages.attack = 6 @p1.stages.defense = 6 @p1.stages.specialAttack = 6 @p1.stages.specialDefense = 6 @p1.stages.accuracy = 6 @p1.stages.evasion = 6 mock = @sandbox.mock(@p2) mock.expects('boost').never() @controller.makeMove(@id1, 'Acupressure') @controller.makeMove(@id2, 'Splash') mock.verify() describe 'Dragon Rage', -> it 'always does 40 damage', -> shared.create.call(this) move = @battle.getMove('Dragon Rage') move.calculateDamage(@battle, @p1, @p2).should.equal 40 describe 'SonicBoom', -> it 'always does 20 damage', -> shared.create.call(this) sonicBoom = @battle.getMove('SonicBoom') sonicBoom.calculateDamage(@battle, @p1, @p2).should.equal 20 describe 'explosion moves', -> it 'faints the user', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Blissey')] @battle.performMove(@p1, @battle.getMove('Explosion')) @p1.isFainted().should.be.true it 'faints the user even if enemy is immune', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Gengar')] @battle.performMove(@p1, @battle.getMove('Explosion')) @p1.isFainted().should.be.true it 'fails if an active Pokemon has Damp', -> shared.create.call this, team1: [Factory('Gengar')] team2: [Factory('Politoed', ability: 'Damp')] explosion = @battle.getMove('Explosion') mock = @sandbox.mock(explosion).expects('fail').once() @battle.performMove(@p1, explosion) mock.verify() describe 'endeavor', -> it "brings the target's hp down to the user's hp", -> shared.create.call(this) hp = 4 @p1.currentHP = hp @battle.performMove(@p1, @battle.getMove('Endeavor')) @p2.currentHP.should.equal hp it "fails if the target's hp is less than the user's hp", -> shared.create.call(this) move = @battle.getMove('Endeavor') mock = @sandbox.mock(move).expects('fail').once() @p2.currentHP = hp = 4 @battle.performMove(@p1, move) mock.verify() it "doesn't hit ghost pokemon", -> shared.create.call this, team1: [Factory('Politoed')] team2: [Factory('Gengar')] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Endeavor')) @p2.currentHP.should.equal @p2.stat('hp') describe 'a thief move', -> it "should steal the target's item", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.item.should.equal item2 should.not.exist @p2.item it "should not steal the target's item if it has none", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp')] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item should.not.exist @p2.item it "should not steal the target's item if user already has an item", -> shared.create.call this, team1: [Factory('Magikarp', item: "Stick")] team2: [Factory('Magikarp', item: "Leftovers")] item1 = @p1.item item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.item.should.equal item1 @p2.item.should.equal item2 it "should not steal the target's item if target has Sticky Hold", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers", ability: "Sticky Hold")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal target's item if target has Multitype and a plate", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Draco Plate", ability: "Multitype")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if the target has no item", -> shared.create.call(this) item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) @p1.hasItem().should.be.false @p2.hasItem().should.be.false it "should not steal the target's item if target is Giratina-O", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Giratina', forme: "origin", item: "Griseous Orb")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if target is Genesect with Drive", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Genesect', item: "Burn Drive")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if target holds Mail", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Air Mail")] item2 = @p2.item @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 it "should not steal the target's item if user is fainted", -> shared.create.call this, team1: [Factory('Magikarp')] team2: [Factory('Magikarp', item: "Leftovers", ability: "Iron Barbs")] item2 = @p2.item @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Thief')) should.not.exist @p1.item @p2.item.should.equal item2 describe 'crush grip', -> it 'has a base power of 1 minimum', -> shared.create.call(this) move = @battle.getMove('Crush Grip') @p2.currentHP = 1 move.basePower(@battle, @p1, @p2).should.equal 1 it 'has a base power of 121 maximum', -> shared.create.call(this) move = @battle.getMove('Crush Grip') @p2.currentHP = @p2.stat('hp') move.basePower(@battle, @p1, @p2).should.equal 121 describe 'hex', -> it 'doubles the base power if target is burned, poisoned, or paralyzed', -> shared.create.call(this) move = @battle.getMove('Hex') @p2.attach(Status.Paralyze) move.basePower(@battle, @p1, @p2).should.equal 100 describe 'heavy slam and heat crash', -> it 'has variable base power based on the difference in weight', -> shared.create.call(this) move = @battle.getMove('Heavy Slam') move.basePower(@battle, @p1, @p2).should.equal 40 move.basePower(@battle, @p1, calculateWeight: -> -1000).should.equal 120 describe 'a status cure move', -> it 'heals the entire team of status effects', -> shared.create.call this, team1: [Factory('Magikarp'), Factory('Magikarp'), Factory('Magikarp')] shared.biasRNG.call(this, 'next', 'paralyze chance', 1) # never pars @team1.pokemon.forEach((pokemon) -> pokemon.attach(Status.Paralyze)) @battle.performMove(@p1, @battle.getMove('Aromatherapy')) _.all(@team1.pokemon, (pokemon) -> !pokemon.hasStatus()).should.be.true describe 'copycat', -> beforeEach -> shared.create.call this, team1: [Factory('Magikarp', evs: {speed: 4})] # make faster than team2 it 'copies the last move used', -> @battle.lastMove = @battle.getMove('Tackle') mock = @sandbox.mock(@battle.getMove('Tackle')) mock.expects('execute').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it "changes the move's target properly", -> tackle = @battle.getMove('Tackle') @battle.lastMove = tackle mock = @sandbox.mock(tackle) mock.expects('execute').once().withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it 'fails if no last move was used', -> @battle.lastMove = null mock = @sandbox.mock(@battle.getMove('Copycat')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() it 'fails if the last move was copycat', -> @battle.lastMove = @battle.getMove('Copycat') mock = @sandbox.mock(@battle.getMove('Copycat')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Copycat')) mock.verify() describe 'a move that targets a different stat', -> it "uses the correct stat", -> shared.create.call(this) move = @battle.getMove('Secret Sword') defStat = @p2.stat('defense') move.pickDefenseStat(@p1, @p2).should.equal defStat describe 'foul play', -> it "uses the target's attack stat, not the user's", -> shared.create.call this, team1: [Factory('Celebi')] move = @battle.getMove('Foul Play') atkStat = @p2.stat('attack') move.pickAttackStat(@p1, @p2).should.equal atkStat describe 'foul play', -> it "uses the target's attack stat, not the user's", -> shared.create.call this, team1: [Factory('Celebi')] move = @battle.getMove('Foul Play') atkStat = @p2.stat('attack') move.pickAttackStat(@p1, @p2).should.equal atkStat describe 'teleport', -> it "always fails", -> shared.create.call(this) move = @battle.getMove('Teleport') mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() describe 'Super Fang', -> it "deals half of the target's current HP", -> shared.create.call(this) hp = @p2.currentHP hp = @p2.currentHP = (hp - (1 - hp % 2)) # Always odd @battle.performMove(@p1, @battle.getMove('Super Fang')) @p2.currentHP.should.equal Math.ceil(hp / 2) it "deals 1 damage minimum", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Super Fang')) @p2.currentHP.should.equal 0 describe "A weather-based recovery move", -> it "heals 50% HP in no weather, rounded half down", -> shared.create.call(this) @battle.setWeather(Weather.NONE) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') / 2) @p1.currentHP.should.equal(1 + hp) it "heals 25% HP in bad weather, rounded half down", -> shared.create.call(this, team1: [Factory("Shuckle")]) @battle.setWeather(Weather.SAND) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') / 4) @p1.currentHP.should.equal(1 + hp) it "heals 66% HP in good weather, rounded half down", -> shared.create.call(this) @battle.setWeather(Weather.SUN) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Moonlight')) hp = util.roundHalfDown(@p1.stat('hp') * 2 / 3) @p1.currentHP.should.equal(1 + hp) describe 'a flinching move', -> it "prevents the other person from executing their move", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Splash')) mock.expects('execute').never() @battle.performMove(@p1, @battle.getMove('Fake Out')) @battle.performMove(@p2, @battle.getMove('Splash')) mock.verify() it "removes the flinch attachment at the end of the turn", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Fake Out')) @battle.endTurn() @p2.has(Attachment.Flinch).should.be.false describe 'weather ball', -> it "is a 50 base power normal move in normal conditions", -> shared.create.call(this) @battle.setWeather(Weather.NONE) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Normal' move.basePower(@battle, @p1, @p2).should.equal 50 it "is a 100 base power Water move in rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Water' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Fire move in sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Fire' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Ice move in hail", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Ice' move.basePower(@battle, @p1, @p2).should.equal 100 it "is a 100 base power Rock move in sandstorm", -> shared.create.call(this) @battle.setWeather(Weather.SAND) move = @battle.getMove('Weather Ball') move.getType(@battle, @p1, @p2).should.equal 'Rock' move.basePower(@battle, @p1, @p2).should.equal 100 describe 'Autotomize', -> it 'changes your weight on success', -> shared.create.call(this) weight = @p1.calculateWeight() @battle.performMove(@p1, @battle.getMove('Autotomize')) weight.should.not.equal @p1.calculateWeight() it 'cannot go below .1kg', -> # PI:NAME:<NAME>END_PIikPI:NAME:<NAME>END_PI weighs 100kg. shared.create.call this, team1: [ Factory('PI:NAME:<NAME>END_PI')] @battle.performMove(@p1, @battle.getMove('Autotomize')) @p1.calculateWeight().should.not.be.lessThan .1 it 'stacks weight changes', -> # PI:NAME:<NAME>END_PI weighs 1355kg. shared.create.call this, team1: [ Factory('PI:NAME:<NAME>END_PI')] @battle.performMove(@p1, @battle.getMove('Autotomize')) @battle.performMove(@p1, @battle.getMove('Autotomize')) @p1.calculateWeight().should.equal 1155 describe 'heart swap', -> shared.shouldDoNoDamage('Heart Swap') it 'swaps user and target boosts', -> shared.create.call(this) @p1.stages.attack = 2 @p2.stages.speed = -2 @battle.performMove(@p1, @battle.getMove('Heart Swap')) @p1.stages.should.containEql speed: -2 @p2.stages.should.containEql attack: 2 describe 'Nightmare', -> shared.shouldDoNoDamage('Nightmare') it 'fails if the pokemon is awake', -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Nightmare')).expects('fail').once() @battle.performMove(@p1, @battle.getMove('Nightmare')) mock.verify() it 'fails if used twice', -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) nightmare = @battle.getMove('Nightmare') @p2.attach(Status.Sleep) mock = @sandbox.mock(nightmare).expects('fail').once() @battle.performMove(@p1, nightmare) @battle.performMove(@p1, nightmare) mock.verify() it "cuts the target's HP by 25% each turn", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) hp = @p2.currentHP quarter = Math.floor(hp / 4) @battle.performMove(@p1, @battle.getMove('Nightmare')) @battle.endTurn() @p2.currentHP.should.equal(hp - quarter) @battle.endTurn() @p2.currentHP.should.equal(hp - 2*quarter) it "deals 1 damage minimum", -> shared.create.call(this, team2: [Factory("Shedinja")]) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove('Nightmare')) @battle.endTurn() @p2.currentHP.should.equal(0) it "stops the nightmare if the target wakes up", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep turns', 3) @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove('Nightmare')) @p2.cureStatus() @battle.endTurn() # The check is in endTurn() @p2.has(Attachment.Nightmare).should.be.false describe 'Incinerate', -> it 'destroys the berry of the target', -> shared.create.call this, team2: [ Factory('Magikarp', item: 'Bluk Berry') ] @battle.performMove(@p1, @battle.getMove('Incinerate')) should.not.exist @p2.item it 'does not destroy non-berries', -> shared.create.call this, team2: [ Factory('Magikarp', item: 'Leftovers') ] @battle.performMove(@p1, @battle.getMove('Incinerate')) should.exist @p2.item describe 'Judgment', -> it 'is normal type by default', -> shared.create.call(this) move = @battle.getMove('Judgment') move.getType(@battle, @p1, @p2).should.equal 'Normal' it 'changes type depending on the Plate held by the user', -> shared.create.call this, team1: [ Factory('Magikarp', item: 'Earth Plate') ] move = @battle.getMove('Judgment') move.getType(@battle, @p1, @p2).should.equal 'Ground' describe 'Tailwind', -> shared.shouldDoNoDamage("Tailwind") shared.shouldFailIfUsedTwice("Tailwind") it "doubles the speed of the user's team", -> shared.create.call this oldSpeed = @p1.stat('speed') @battle.performMove(@p1, @battle.getMove('Tailwind')) newSpeed = @p1.stat('speed') newSpeed.should.equal(oldSpeed * 2) it "lasts three turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Tailwind')) @battle.endTurn() @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.team.has(Attachment.Tailwind).should.be.false describe 'Taunt', -> shared.shouldDoNoDamage("Taunt") shared.shouldFailIfUsedTwice("Taunt") it 'prevents the target from using a non-attacking move that turn', -> shared.create.call(this, team1: [ Factory('Magikarp', evs: {speed: 4}) ]) move = @battle.getMove('Calm Mind') taunt = @battle.getMove('Taunt') mock = @sandbox.mock(move) mock.expects('execute').never() @battle.performMove(@p1, taunt) @battle.performMove(@p2, move) mock.verify() it "lasts 4 turns if the user moved after the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p1, @battle.getMove('Splash')) @battle.performMove(@p2, @battle.getMove('Taunt')) @p1.has(Attachment.Taunt).should.be.true @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.has(Attachment.Taunt).should.be.true @battle.endTurn() @p1.has(Attachment.Taunt).should.be.false it "lasts 3 turns if the user moved before the target", -> shared.create.call(this, team1: [Factory("PI:NAME:<NAME>END_PI", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Taunt')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.has(Attachment.Taunt).should.be.true @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Taunt).should.be.true @battle.endTurn() @p2.has(Attachment.Taunt).should.be.false it 'prevents the target from selecting that move the next turn', -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Taunt')) @battle.beginTurn() requestedMoves = @battle.requestFor(@p2).moves requestedMoves.should.not.containEql 'Splash' for moveName in [ "U-turn", "Volt Switch" ] do (moveName) -> describe moveName, -> it 'forces the owner to switch', -> shared.create.call(this, team1: (Factory("Magikarp") for i in [1..2])) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.requests.should.have.property(@id1) it "makes a request containing all the possible switches", -> shared.create.call(this, team1: (Factory("Magikarp") for i in [1..3])) @battle.performMove(@p1, @battle.getMove(moveName)) request = @battle.requestFor(@p1) request.switches.should.eql([ 1, 2 ]) describe 'venoshock', -> it 'doubles the base power if target is poisoned', -> shared.create.call(this) move = @battle.getMove("Venoshock") @p2.attach(Status.Poison) basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) it 'doubles the base power if target is toxiced', -> shared.create.call(this) move = @battle.getMove("Venoshock") @p2.attach(Status.Toxic) basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(2 * move.power) describe 'Wish', -> shared.shouldDoNoDamage("Wish") shared.shouldFailIfUsedTwice("Wish") it "restores half of the user's total hit points the next end of turn", -> shared.create.call(this) hp = @p1.currentHP @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() @p1.currentHP.should.equal 1 @battle.endTurn() @p1.currentHP.should.equal(Math.round(hp / 2) + 1) it "restores the same total amount of HP to an ally", -> shared.create.call(this, team1: [Factory("Magikarp"), Factory("Celebi")]) hp = @p1.currentHP @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() receiver = @team1.at(1) receiver.currentHP = 1 @battle.performSwitch(@p1, 1) @battle.endTurn() receiver.currentHP.should.equal(Math.round(hp / 2) + 1) it "fails if the pokemon faints", -> shared.create.call(this, team1: [Factory("Magikarp"), Factory("Celebi")]) @battle.performMove(@p1, @battle.getMove('Wish')) @battle.endTurn() @p1.currentHP = 1 @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.endTurn() @team1.has(Attachment.Wish).should.be.false describe "Counter", -> it "returns double the damage if attacked by a physical move", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Tackle')) @battle.performMove(@p1, @battle.getMove('Counter')) dhp1 = @p1.stat('hp') - @p1.currentHP dhp2 = @p2.stat('hp') - @p2.currentHP dhp2.should.equal 2*dhp1 it "fails if attacked by a special move", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Counter')) mock.expects('fail').once() @battle.performMove(@p2, @battle.getMove('ThunderShock')) @battle.performMove(@p1, @battle.getMove('Counter')) mock.verify() it "fails if not hit by an attack this turn", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Counter')) mock.expects('fail').once() @controller.makeMove(@id1, "Splash") @controller.makeMove(@id2, "Tackle") @battle.performMove(@p1, @battle.getMove('Counter')) mock.verify() it "hits the pokemon who is currently in that slot, not who was", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('U-turn')) @battle.performSwitch(@p1, 1) @battle.performMove(@p2, @battle.getMove('Counter')) @team1.first().currentHP.should.be.lessThan(@team1.first().stat('hp')) @team1.at(1).currentHP.should.equal(@team1.at(1).stat('hp')) it "doesn't activate Rough Skin if it fails", -> shared.create.call this, team2: [Factory("Garchomp", ability: "Rough Skin")] counter = @battle.getMove("Counter") mock = @sandbox.mock(counter) mock.expects('fail').once() @battle.performMove(@p1, counter) mock.verify() @p1.currentHP.should.equal(@p1.stat('hp')) describe "Perish Song", -> it "attaches to every pokemon in the field", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Perish Song')) result = _.all @battle.getActivePokemon(), (pokemon) -> pokemon.has(Attachment.PerishSong) result.should.be.true it "faints pokemon at the end of 4 turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Perish Song')) @battle.endTurn() @battle.endTurn() @battle.endTurn() result = _.all @battle.getActivePokemon(), (pokemon) -> !pokemon.isFainted() result.should.be.true @battle.endTurn() result = _.all @battle.getActivePokemon(), (pokemon) -> pokemon.isFainted() result.should.be.true it "fails against Pokemon with Soundproof", -> shared.create.call(this, team1: [Factory("Magikarp", ability: "Soundproof")]) @battle.performMove(@p2, @battle.getMove("Perish Song")) @p1.has(Attachment.PerishSong).should.be.false @p2.has(Attachment.PerishSong).should.be.true describe "Techno Blast", -> it "is Fire-type if the user holds a Burn Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Burn Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Fire" it "is Water-type if the user holds a Douse Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Douse Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Water" it "is Electric-type if the user holds a Shock Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Shock Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Electric" it "is Ice-type if the user holds a Chill Drive", -> shared.create.call this, team1: [Factory("Magikarp", item: "Chill Drive")] move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Ice" it "is Normal-type otherwise", -> shared.create.call(this) move = @battle.getMove('Techno Blast') type = move.getType(@battle, @p1, @p2) type.should.equal "Normal" describe "Synchronoise", -> it "fails on Pokemon not of the user's type", -> shared.create.call this, team1: [Factory("Magikarp")] team2: [Factory("Celebi")] move = @battle.getMove('Synchronoise') mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "works on Pokemon that share one type with the user", -> shared.create.call this, team1: [Factory("Ferrothorn")] team2: [Factory("Celebi")] hp = @p2.currentHP @battle.performMove(@p1, @battle.getMove('Synchronoise')) @p2.currentHP.should.be.lessThan hp describe "Roost", -> shared.shouldDoNoDamage('Roost') it "removes the user's flying type during the turn", -> shared.create.call this, team1: [Factory("Gliscor")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) ('Flying' in @p1.types).should.be.false @p1.types.should.eql ['Ground'] it "turns pure-Flying pokemon into Normal pokemon", -> shared.create.call this, team1: [Factory("Tornadus")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) ('Flying' in @p1.types).should.be.false @p1.types.should.eql ['Normal'] it "keeps the user's types the same if non-Flying", -> shared.create.call this, team1: [Factory("Celebi")] oldTypes = @p1.types @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) @p1.types.should.eql oldTypes it "restores the user's old types after the turn", -> shared.create.call this, team1: [Factory("GlPI:NAME:<NAME>END_PI")] @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Roost")) @battle.endTurn() ('Flying' in @p1.types).should.be.true ('Ground' in @p1.types).should.be.true describe 'Encore', -> shared.shouldDoNoDamage('Encore') it "fails if the target has not yet used a move", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p1, encore) mock.verify() it "forces the target to repeat its last used move", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Splash') ] it "changes the target's decision if it has not moved yet", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Encore')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.lastMove.should.equal @battle.getMove('Splash') it "lasts 4 turns if the user moved after the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p1, @battle.getMove('Splash')) @battle.performMove(@p2, @battle.getMove('Encore')) @p1.has(Attachment.Encore).should.be.true @battle.endTurn() @battle.endTurn() @battle.endTurn() @p1.has(Attachment.Encore).should.be.true @battle.endTurn() @p1.has(Attachment.Encore).should.be.false it "lasts 3 turns if the user moved before the target", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.recordMove(@id1, @battle.getMove('Encore')) @battle.recordMove(@id2, @battle.getMove('Tackle')) @battle.continueTurn() @p2.has(Attachment.Encore).should.be.true @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Encore).should.be.true @battle.endTurn() @p2.has(Attachment.Encore).should.be.false it "fails on certain moves like mimic", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p2, @battle.getMove('Mimic')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "fails if the pokemon is already encored", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "fails if the move has 0 PP", -> shared.create.call(this) encore = @battle.getMove('Encore') mock = @sandbox.mock(encore).expects('fail').once() @p2.setPP(@battle.getMove('Splash'), 1) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) mock.verify() it "removes itself if the pokemon's move reaches 0 PP", -> shared.create.call(this) @p2.setPP(@battle.getMove('Splash'), 2) @battle.performMove(@p2, @battle.getMove('Splash')) @battle.performMove(@p1, @battle.getMove('Encore')) @battle.endTurn() @p2.has(Attachment.Encore).should.be.true @battle.performMove(@p2, @battle.getMove('Splash')) @battle.endTurn() @p2.has(Attachment.Encore).should.be.false describe "Swagger", -> it "confuses the target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Swagger")) @p2.has(Attachment.Confusion).should.be.true it "boosts the target's attack by two stages", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Swagger")) @p2.stages.attack.should.equal 2 describe "Flatter", -> it "confuses the target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Flatter")) @p2.has(Attachment.Confusion).should.be.true it "boosts the target's special attack by one stage", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Flatter")) @p2.stages.specialAttack.should.equal 1 describe "Torment", -> shared.shouldDoNoDamage("Torment") shared.shouldFailIfUsedTwice("Torment") it "prevents the target from using its last move", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Torment")) @battle.performMove(@p2, @battle.getMove("Splash")) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Tackle') ] @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.beginTurn() @p2.validMoves().should.eql [ @battle.getMove('Splash') ] it "still works even if a new pokemon has just switched in", -> shared.create.call(this, team2: [Factory("Magikarp"), Factory("Magikarp")]) @battle.performSwitch(@p2, 1) @battle.performMove(@p1, @battle.getMove("Torment")) @battle.beginTurn() @team2.first().validMoves().should.eql [ @battle.getMove('Splash'), @battle.getMove('Tackle') ] xit "does not force the Outrage user to struggle", -> xit "does not prevent consecutive use of Struggle", -> describe "Psych Up", -> it "copies the target's stat changes", -> shared.create.call(this) @p1.stages.specialAttack = 5 @p1.stages.evasion = 2 @p2.stages.attack = 6 @p2.stages.defense = -2 @p2.stages.speed = -1 @battle.performMove(@p1, @battle.getMove("Psych Up")) @p1.stages.should.eql { attack: 6, defense: -2, specialAttack: 0, specialDefense: 0, speed: -1, accuracy: 0, evasion: 0 } describe "Spikes", -> it "puts a layer of spikes on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.Spikes).should.be.false @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true it "fails if there are 3 layers", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Spikes')).expects('fail').once() for i in [1..4] @battle.performMove(@p1, @battle.getMove("Spikes")) mock.verify() it "deals a minimum of 1 damage", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Shedinja")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() (pokemon.stat('hp') - pokemon.currentHP).should.equal(1) it "does damage to pokemon switching in according to # of layers", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] hp = @team2.first().stat('hp') @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@p2, 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) @team2.first().currentHP = hp @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 6) @team2.first().currentHP = hp @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) (hp - @team2.first().currentHP).should.equal Math.floor(hp / 4) it "does not affect pokemon with immunity to ground", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp", item: "Air Balloon")] @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().currentHP.should.equal @team2.first().stat('hp') it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() hp = @team2.first().stat('hp') (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) describe "Stealth Rock", -> shared.shouldDoNoDamage("Stealth Rock") shared.shouldFailIfUsedTwice("Stealth Rock") it "puts a layer of rocks on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.StealthRock).should.be.false @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @team2.has(Attachment.StealthRock).should.be.true it "does damage to pokemon switching in according to type", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Moltres")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() hp = pokemon.stat('hp') (hp - pokemon.currentHP).should.equal Math.floor(hp / 2) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() hp = pokemon.stat('hp') (hp - pokemon.currentHP).should.equal Math.floor(hp / 8) it "deals a minimum of 1 damage", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Aron", level: 1)] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.performSwitch(@team2.first(), 1) pokemon = @team2.first() (pokemon.stat('hp') - pokemon.currentHP).should.equal(1) it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() hp = @team2.first().stat('hp') (hp - @team2.first().currentHP).should.equal Math.floor(hp / 8) describe "Toxic Spikes", -> it "puts a layer of toxic spikes on the opponents' field", -> shared.create.call(this) @team2.has(Attachment.ToxicSpikes).should.be.false @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @team2.has(Attachment.ToxicSpikes).should.be.true it "fails if there are 2 layers", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Toxic Spikes')) mock.expects('fail').once() for i in [1..3] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) mock.verify() it "poisons or severely poisons the switch-in if not immune", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.true @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Toxic).should.be.true it "does not affect the pokemon if it's immune to Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Ferrothorn")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.false it "does not affect the pokemon if it's immune to Ground", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Gyarados")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.first().has(Status.Poison).should.be.false it "disappears if the pokemon switching in is a grounded Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Drapion")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.has(Attachment.ToxicSpikes).should.be.false it "doesn't disappear if the pokemon switching in is a flying Poison", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Drapion", item: "Air Balloon")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.performSwitch(@team2.first(), 1) @team2.has(Attachment.ToxicSpikes).should.be.true it "affects replacements", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @battle.recordSwitch(@id2, 1) @battle.performReplacements() @team2.first().has(Status.Poison).should.be.true testWeatherMove = (moveName, weather, item) -> describe moveName, -> it "changes the weather to #{weather.toLowerCase()} for 5 turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.weather.should.equal(weather) @battle.weatherDuration.should.equal 5 it "changes the weather to #{weather.toLowerCase()} for 8 turns if user holds a #{item}", -> shared.create.call this, team1: [Factory("Magikarp", item: item)] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.weather.should.equal(weather) @battle.weatherDuration.should.equal 8 it "fails if the weather is already #{weather}", -> shared.create.call this, team1: [Factory("Magikarp", item: item)] @battle.setWeather(weather) theMove = @battle.getMove(moveName) mock = @sandbox.mock(theMove).expects('fail').once() @battle.performMove(@p1, theMove) mock.verify() testWeatherMove("Rain Dance", Weather.RAIN, "Damp Rock") testWeatherMove("Sunny Day", Weather.SUN, "Heat Rock") testWeatherMove("Hail", Weather.HAIL, "Icy Rock") testWeatherMove("Sandstorm", Weather.SAND, "Smooth Rock") testStatusMove = (moveName, status) -> describe moveName, -> it "changes the status on a Pokemon if it has no status", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(status).should.be.true it "does not change the status if Pokemon already has a status", -> shared.create.call(this) oldStatus = if status == Status.Paralyze Status.Sleep else Status.Paralyze @p2.attach(oldStatus) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(status).should.be.false @p2.has(oldStatus).should.be.true testStatusMove("Dark Void", Status.Sleep) testStatusMove("GrassWhistle", Status.Sleep) testStatusMove("Hypnosis", Status.Sleep) testStatusMove("Lovely Kiss", Status.Sleep) testStatusMove("Poison Gas", Status.Poison) testStatusMove("PoisonPowder", Status.Poison) testStatusMove("Sing", Status.Sleep) testStatusMove("Sleep Powder", Status.Sleep) testStatusMove("Spore", Status.Sleep) testStatusMove("Stun Spore", Status.Paralyze) testStatusMove("Thunder Wave", Status.Paralyze) testStatusMove("Toxic", Status.Toxic) testStatusMove("Will-O-Wisp", Status.Burn) testEffectMove = (moveName, Effect) -> describe moveName, -> it "adds the effect to the Pokemon if it doesn't have it", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.has(Effect).should.be.true it "fails if the Pokemon already has it", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move) mock.expects('fail').once() shared.biasRNG.call(this, "randInt", 'confusion turns', 4) @p2.attach(Effect, {@battle}) move = @battle.getMove(moveName) @battle.performMove(@p1, move) mock.verify() testEffectMove 'Confuse Ray', Attachment.Confusion testEffectMove 'Supersonic', Attachment.Confusion testEffectMove 'Sweet Kiss', Attachment.Confusion testEffectMove 'Teeter Dance', Attachment.Confusion describe "Trump Card", -> it "has 40 base power by default", -> shared.create.call(this) @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 40 it "has 50 base power if the move has 3 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 3] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 3 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 50 it "has 60 base power if the move has 2 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 2] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 2 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 60 it "has 80 base power if the move has 1 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 1] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 1 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 80 it "has 200 base power if the move has 0 PP after use", -> shared.create.call this, team1: [Factory("Corphish")] pp = @p1.pp(@battle.getMove('Trump Card')) for x in [0...pp - 0] @p1.reducePP(@battle.getMove('Trump Card')) @p1.pp(@battle.getMove('Trump Card')).should.equal 0 @battle.getMove('Trump Card').basePower(@battle, @p1, @p2).should.equal 200 testRandomSwitchMove = (moveName) -> describe moveName, -> it "should switch opponent out to a random member", -> shared.create.call(this, team2: [Factory("Magikarp"), Factory("Abra")]) target = @team2.at(1) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @team2.first().should.equal target it "does not force a switch if the target faints", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() @team2.at(0).setHP(1) @battle.performMove(@p1, move) mock.verify() it "does not force a switch if the hit was indirect", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, move) mock.verify() it "does not force a switch if the user faints", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Magikarp", ability: "Iron Barbs"), Factory("Abra")]) move = @battle.getMove(moveName) mock = @sandbox.mock(@team2) # Whirlwind, Roar if !move.isNonDamaging() mock.expects("switch").never() else mock.expects("switch").once() @p1.currentHP = 1 @battle.performMove(@p1, move) mock.verify() it "should not force switches if opponent is the last pokemon", -> shared.create.call(this, team2: [Factory("Magikarp")]) mock = @sandbox.mock(@team2) mock.expects("switch").never() move = @battle.getMove(moveName) @battle.performMove(@p1, move) mock.verify() it "cancels the opponent's move if user moves first", -> shared.create.call this, team1: [ Factory("Magikarp", moves: [ moveName ], evs: {speed: 4}), Factory("Magikarp")] team2: [ Factory("Magikarp", moves: [ moveName ]), Factory("Magikarp")] spy1 = @sandbox.spy(@team1, 'switch') spy2 = @sandbox.spy(@team2, 'switch') @controller.makeMove(@id1, moveName) @controller.makeMove(@id2, moveName) spy1.callCount.should.equal(0) spy2.callCount.should.equal(1) testRandomSwitchMove "Roar" testRandomSwitchMove "Whirlwind" testRandomSwitchMove "Dragon Tail" testRandomSwitchMove "Circle Throw" testTrappingMove = (name) -> describe name, -> it "blocks switching", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.Trap).should.be.true @p1.has(Attachment.TrapLeash).should.be.true it "deals 1/16 of the pokemon's max hp every turn", -> shared.create.call(this, team2: [Factory("Blissey")]) @battle.performMove(@p1, @battle.getMove(name)) @p2.currentHP = @p2.stat('hp') @battle.endTurn() maxHP = @p2.stat('hp') expected = maxHP - Math.floor(maxHP / 16) @p2.currentHP.should.equal expected it "deals a minimum of 1 damage", -> shared.create.call(this, team2: [Factory("SPI:NAME:<NAME>END_PI")]) @p2.types = [ "Normal" ] move = @battle.getMove(name) @sandbox.stub(move, 'calculateDamage', -> 0) @battle.performMove(@p1, move) @battle.endTurn() @p2.currentHP.should.equal(0) it "lasts several turns", -> shared.create.call(this, team2: [Factory("Blissey")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @p2.currentHP = @p2.stat('hp') # loop for 5 more turns. One of the turns has already passed. # These moves hurt for 5 moves and wear off on the 6th. for i in [1..5] @p2.has(Attachment.Trap).should.be.true @battle.endTurn() # Test if the actual damage checks out. It should have damaged only 5 times maxHP = @p2.stat('hp') expected = maxHP - (Math.floor(maxHP / 16) * 5) @p2.currentHP.should.equal expected it "wears off after a certain number of turns", -> shared.create.call(this, team2: [Factory("BlPI:NAME:<NAME>END_PI")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() # loop for 5 more turns. One of the turns has already passed. # These moves hurt for 5 moves and wear off on the 6th. We need # turn number 6 to pass before the attachment should wear off. for i in [1..5] @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "does not reset the duration if used twice", -> shared.create.call(this, team2: [Factory("Blissey")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() # loop for 4 more turns. These moves wear off after numTurns + 1. # 2 have already passed. for i in [1..4] @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "wears off if the user switches", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "wears off if the user faints", -> shared.create.call(this, team1: [Factory("Heatran")], team2: [Factory("Blissey")]) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.Trap).should.be.true @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "properly removes from a list of attachments", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @battle.recordMove(@id1, @battle.getMove("Protect")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false it "is always 7 turns if the user is holding grip claw", -> shared.create.call(this, team1: [Factory("Magikarp", item: "Grip Claw")]) shared.biasRNG.call(this, "randInt", 'trapping move', 5) move = @battle.getMove(name) @battle.performMove(@p1, move) @battle.performMove(@p2, @battle.getMove("Recover")) # The user is damaged 7 times, but the attachment actually lasts # for 8 turns including the turn it is first used. for i in [1..8] @p2.has(Attachment.Trap).should.be.true @battle.endTurn() @p2.has(Attachment.Trap).should.be.false it "does not start the effect if it hits a substitute", -> shared.create.call(this, team2: [Factory("Blissey")]) @p2.attach(Attachment.Substitute, hp: 1) @battle.performMove(@p1, @battle.getMove(name)) @battle.endTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false testTrappingMove "Bind" testTrappingMove "Clamp" testTrappingMove "Fire Spin" testTrappingMove "Magma Storm" testTrappingMove "Sand Tomb" testTrappingMove "Whirlpool" testTrappingMove "Wrap" describe "Attract", -> shared.shouldDoNoDamage('Attract') shared.shouldFailIfUsedTwice "Attract", team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] it "has a 50% chance to immobilize a pokemon", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] shared.biasRNG.call(this, "next", 'attract chance', 0) # 100% immobilizes mock = @sandbox.mock(@battle.getMove('Tackle')).expects('execute').never() @battle.performMove(@p1, @battle.getMove("Attract")) @battle.performMove(@p2, @battle.getMove("Tackle")) mock.verify() it "has a 50% chance to not immobilize a pokemon", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M", evs: {speed: 4})] team2: [Factory("Magikarp", gender: "F")] shared.biasRNG.call(this, "next", 'attract chance', .5) # 0% immobilizes mock = @sandbox.mock(@battle.getMove('Tackle')).expects('execute').once() @battle.performMove(@p1, @battle.getMove("Attract")) @battle.performMove(@p2, @battle.getMove("Tackle")) mock.verify() it "fails if the Pokemon are not opposite genders", -> shared.create.call this, team1: [Factory("PI:NAME:<NAME>END_PI", gender: "F")] team2: [Factory("PI:NAME:<NAME>END_PI", gender: "F")] mock = @sandbox.mock(@battle.getMove('Attract')).expects('fail').once() @battle.performMove(@p1, @battle.getMove("Attract")) mock.verify() it "disappears if the source is no longer active", -> shared.create.call this, team1: (Factory("PI:NAME:<NAME>END_PI", gender: "M") for x in [1..2]) team2: [Factory("PI:NAME:<NAME>END_PI", gender: "F")] @battle.performMove(@p1, @battle.getMove('Attract')) @battle.performMove(@p2, @battle.getMove('Splash')) @p2.has(Attachment.Attract).should.be.true @battle.performSwitch(@team1.first(), 1) @battle.performMove(@p2, @battle.getMove('Splash')) @p2.has(Attachment.Attract).should.be.false describe "Reflect", -> it "halves physical damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.Reflect) tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x800) it "does not halve non-physical damage", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.Reflect) thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) it "lasts five turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Reflect')) for i in [1..5] @team1.has(Attachment.Reflect).should.be.true @battle.endTurn() @team1.has(Attachment.Reflect).should.be.false it "fails if the user already used it", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Reflect')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Reflect')) @battle.performMove(@p1, @battle.getMove('Reflect')) mock.verify() it "does not halve on critical hits", -> shared.create.call(this) tackle = @battle.getMove('Tackle') @team2.attach(Attachment.Reflect) @p1.crit = true tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) describe "Light Screen", -> it "halves special damage", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.LightScreen) thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x800) it "does not halve non-physical damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) @team2.attach(Attachment.LightScreen) tackle.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) it "lasts five turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Light Screen')) for i in [1..5] @team1.has(Attachment.LightScreen).should.be.true @battle.endTurn() @team1.has(Attachment.LightScreen).should.be.false it "fails if the user already used it", -> shared.create.call(this) mock = @sandbox.mock(@battle.getMove('Light Screen')) mock.expects('fail').once() @battle.performMove(@p1, @battle.getMove('Light Screen')) @battle.performMove(@p1, @battle.getMove('Light Screen')) mock.verify() it "does not halve on critical hits", -> shared.create.call(this) thundershock = @battle.getMove('ThunderShock') @team2.attach(Attachment.LightScreen) @p1.crit = true thundershock.modifyDamage(@battle, @p1, @p2).should.equal(0x1000) describe "Rapid Spin", -> it "removes spikes", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false it "removes stealth rock", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @team2.has(Attachment.StealthRock).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.StealthRock).should.be.false it "removes toxic spikes", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @team2.has(Attachment.ToxicSpikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.ToxicSpikes).should.be.false it "removes multiple layers of entry hazards", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p1, @battle.getMove("Spikes")) @team2.has(Attachment.Spikes).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false it "removes trapping moves", -> shared.create.call this @battle.performMove(@p1, @battle.getMove("Fire Spin")) @p2.has(Attachment.Trap).should.be.true @p1.has(Attachment.TrapLeash).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @p2.has(Attachment.Trap).should.be.false @p1.has(Attachment.TrapLeash).should.be.false it "removes leech seed", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p2.has(Attachment.LeechSeed).should.be.true @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @p2.has(Attachment.LeechSeed).should.be.false it "does not remove entry hazards if the user faints from rough skin", -> shared.create.call(this, team1: [Factory("Magikarp", ability: "Rough Skin")]) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.true it "does remove entry hazards if the user faints from life orb", -> shared.create.call(this, team2: [Factory("Magikarp", item: "Life Orb")]) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Spikes")) @battle.performMove(@p2, @battle.getMove("Rapid Spin")) @team2.has(Attachment.Spikes).should.be.false describe "Brick Break", -> it "shatters Light Screen", -> shared.create.call(this) @team2.attach(Attachment.LightScreen) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.LightScreen).should.be.false it "shatters Reflect", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.false it "shatters both at the same time", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.false @team2.has(Attachment.LightScreen).should.be.false it "shatters before damage calculation", -> shared.create.call(this) move = @battle.getMove("Brick Break") damage = move.calculateDamage(@battle, @p1, @p2) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) spy = @sandbox.spy(move, 'calculateDamage') @battle.performMove(@p1, move) spy.returned(damage).should.be.true it "does not shatter if the target is immune", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) @sandbox.stub(@p2, 'isImmune', -> true) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.true @team2.has(Attachment.LightScreen).should.be.true it "does not shatter if Brick Break misses", -> shared.create.call(this) @team2.attach(Attachment.Reflect) @team2.attach(Attachment.LightScreen) shared.biasRNG.call(this, 'randInt', 'miss', 101) @battle.performMove(@p1, @battle.getMove('Brick Break')) @team2.has(Attachment.Reflect).should.be.true @team2.has(Attachment.LightScreen).should.be.true describe "Return", -> it "has 102 base power", -> shared.create.call(this) move = @battle.getMove("Return") bp = move.basePower(@battle, @p1, @p2) bp.should.equal 102 describe "Frustration", -> it "has 102 base power", -> shared.create.call(this) move = @battle.getMove("Frustration") bp = move.basePower(@battle, @p1, @p2) bp.should.equal 102 describe "Fake Out", -> it "flinches the enemy", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Fake Out")) @p2.has(Attachment.Flinch).should.be.true it "fails if the Pokemon has been in play one turn or more", -> shared.create.call(this) @battle.endTurn() @battle.beginTurn() fakeOut = @battle.getMove("Fake Out") mock = @sandbox.mock(fakeOut).expects('fail').once() @battle.performMove(@p1, fakeOut) mock.verify() it "works if the Pokemon is newly switched", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @battle.performSwitch(@team1.first(), 1) @battle.endTurn() @battle.beginTurn() fakeOut = @battle.getMove("Fake Out") mock = @sandbox.mock(fakeOut).expects('fail').never() @battle.performMove(@team1.first(), fakeOut) mock.verify() describe "Focus Energy", -> it "adds a Focus Energy attachment to the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Focus Energy")) @p1.has(Attachment.FocusEnergy).should.be.true it "fails the second time it is used", -> shared.create.call(this) move = @battle.getMove("Focus Energy") mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) @battle.performMove(@p1, move) mock.verify() testIdentifyMove = (moveName, types) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "makes the target vulnerable to #{types} moves", -> shared.create.call(this, team2: [Factory("Spiritomb")]) _.each(types, ((type) -> @isImmune(type).should.be.true), @p2) @battle.performMove(@p1, @battle.getMove(moveName)) @p2.has(Attachment.Identify).should.be.true _.each(types, ((type) -> @isImmune(type).should.be.false), @p2) it "makes the target's evasion be ignored", -> shared.create.call(this) @p2.boost(evasion: 2) @p2.editBoosts().evasion.should.equal 2 @battle.performMove(@p1, @battle.getMove(moveName)) @p2.editBoosts().evasion.should.equal 0 testIdentifyMove("Foresight", ["Normal", "Fighting"]) testIdentifyMove("Odor Sleuth", ["Normal", "Fighting"]) testIdentifyMove("Miracle Eye", ["Psychic"]) describe "Conversion", -> it "changes the user's type to a random type based on moves", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Thunderbolt", "Ice Beam", "Conversion" ])] shared.biasRNG.call(this, "randInt", 'conversion types', 0) @p1.types.should.eql [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Conversion")) @p1.types.should.eql [ 'Electric' ] it "ignores Conversion as part of the move types", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Conversion", "Ice Beam" ])] shared.biasRNG.call(this, "randInt", 'conversion types', 0) @p1.types = [ "Fake Type" ] @battle.performMove(@p1, @battle.getMove("Conversion")) @p1.types.should.eql [ 'Ice' ] it "fails if there is no type to convert to", -> shared.create.call this, team1: [Factory("Porygon", moves: [ "Conversion" ])] move = @battle.getMove("Conversion") mock = @sandbox.mock(move) mock.expects('fail').once() @battle.performMove(@p1, move) mock.verify() describe "Conversion 2", -> it "fails if the target has not yet moved", -> shared.create.call(this) move = @battle.getMove("Conversion 2") mock = @sandbox.mock(move).expects('fail').once() @p2.lastMove = null @battle.performMove(@p1, move) mock.verify() it "changes user's type to one resisting or is immune to target's move", -> shared.create.call(this) @p1.types = [ "Normal" ] move = @battle.getMove("Ember") type = move.type @p2.lastMove = move @battle.performMove(@p1, @battle.getMove("Conversion 2")) @p1.types.should.have.length 1 util.typeEffectiveness(type, @p1.types).should.be.lessThan 1 describe "Defense Curl", -> it "raises defense by 1 stage", -> shared.create.call(this) @p1.stages.defense.should.equal 0 @battle.performMove(@p1, @battle.getMove("Defense Curl")) @p1.stages.defense.should.equal 1 it "attaches a volatile attachment", -> shared.create.call(this) @p1.has(Attachment.DefenseCurl).should.be.false @battle.performMove(@p1, @battle.getMove("Defense Curl")) @p1.has(Attachment.DefenseCurl).should.be.true describe "Focus Punch", -> it "causes the user to flinch if hit", -> shared.create.call(this) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.not.be.lessThan @p2.stat('hp') it "does not cause flinching if hit by a non-damaging move", -> shared.create.call(this) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Will-O-Wisp")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if behind a substitute", -> shared.create.call(this) @p1.attach(Attachment.Substitute, hp: (@p1.currentHP >> 2)) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if sub fades", -> shared.create.call(this) @p1.attach(Attachment.Substitute, hp: 1) @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching if hit by a move last turn", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.continueTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not cause flinching afterwards", -> shared.create.call(this, team2: [Factory("Magikarp", evs: {speed: 4})]) focusPunch = @battle.getMove("Focus Punch") @battle.recordMove(@id1, @battle.getMove("Focus Punch")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() hp = @p2.currentHP @battle.recordMove(@id1, @battle.getMove("Tackle")) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @p2.currentHP.should.be.lessThan(hp) describe "Magnet Rise", -> shared.shouldDoNoDamage("Magnet Rise") shared.shouldFailIfUsedTwice("Magnet Rise") it "makes the user immune to ground moves", -> shared.create.call(this) @p1.isImmune("Ground").should.be.false @battle.performMove(@p1, @battle.getMove("Magnet Rise")) @p1.isImmune("Ground").should.be.true it "lasts 5 turns", -> shared.create.call(this) @p1.isImmune("Ground").should.be.false @battle.performMove(@p1, @battle.getMove("Magnet Rise")) for i in [1..5] @p1.isImmune("Ground").should.be.true @battle.endTurn() @p1.isImmune("Ground").should.be.false testLockOnMove = (moveName) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "makes the user's next move never miss on this target", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) shared.biasRNG.call(this, 'randInt', 'miss', 101) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @p2) .should.be.false it "lasts only two turns", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) for i in [1..2] @p1.has(Attachment.LockOn).should.be.true @battle.endTurn() @p1.has(Attachment.LockOn).should.be.false it "hits through two-turn fade-away moves", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, @battle.getMove("Fly")) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @p2) .should.be.false it "does not hit through Protect", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('hit').never() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Protect")) @battle.performMove(@p2, move) mock.verify() it "does not affect accuracy on another target", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performSwitch(@p2, 1) shared.biasRNG.call(this, 'randInt', 'miss', 101) missMove = @battle.getMove("Tackle") missMove.willMiss(@battle, @p1, @team2.first()) .should.be.true it "re-locks on when used on another target", -> shared.create.call this, team2: [Factory("Magikarp"), Factory("Magikarp")] @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performSwitch(@p2, 1) @battle.performMove(@p1, @battle.getMove(moveName)) @p1.has(Attachment.LockOn).should.be.true testLockOnMove("Lock-On") testLockOnMove("Mind Reader") describe "Minimize", -> it "boosts the user's evasion by 2", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Minimize")) @p1.stages.evasion.should.equal 2 it "adds a Minimize volatile attachment to the user", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Minimize")) @p1.has(Attachment.Minimize).should.be.true testStompMove = (moveName) -> describe moveName, -> it "doubles its base power when the target is minimized", -> shared.create.call(this) @p2.attach(Attachment.Minimize) move = @battle.getMove(moveName) bp = move.basePower(@battle, @p1, @p2) bp.should.equal(move.power * 2) it "has normal base power otherwise", -> shared.create.call(this) move = @battle.getMove(moveName) bp = move.basePower(@battle, @p1, @p2) bp.should.equal(move.power) it "has a 30% chance to flinch", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'flinch', 0) # 100% chance @battle.performMove(@p1, @battle.getMove(moveName)) @p2.has(Attachment.Flinch).should.be.true testStompMove("Stomp") testStompMove("Steamroller") testMeanLookMove = (moveName) -> describe moveName, -> shared.shouldDoNoDamage(moveName) shared.shouldFailIfUsedTwice(moveName) it "blocks the target from switching", -> shared.create.call(this) @p2.isSwitchBlocked().should.be.false @battle.performMove(@p1, @battle.getMove(moveName)) @battle.beginTurn() @p2.isSwitchBlocked().should.be.true it "wears off if the user faints", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.true @p2.has(Attachment.MeanLook).should.be.true @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.MeanLook).should.be.false it "wears off if the user switches", -> shared.create.call(this, team1: [Factory("Blissey"), Factory("Magikarp")]) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @controller.makeSwitch(@id1, 1) @controller.makeMove(@id2, "Splash") @p2.isSwitchBlocked().should.be.false @p2.has(Attachment.MeanLook).should.be.false testMeanLookMove("Block") testMeanLookMove("Mean Look") testMeanLookMove("Spider Web") testRechargeMove = (moveName) -> describe moveName, -> it "blocks the target from switching the next turn", -> shared.create.call(this) @p1.isSwitchBlocked().should.be.false theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "blocks the target from picking a new move the next turn", -> shared.create.call(this) theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() for move in @p1.moves @p1.isMoveBlocked(move).should.be.true it "automatically selects a special recharge move the next turn", -> shared.create.call(this) specialMove = @battle.getMove("Recharge") theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @battle.requests.should.not.have.property @id1 action = @battle.getAction(@p1) should.exist(action) action.should.have.property("move") action.move.should.equal(specialMove) it "prevents the user from moving the next turn", -> shared.create.call(this) spy = @sandbox.spy(@p1, 'beforeMove') theMove = @battle.getMove(moveName) @sandbox.stub(theMove, 'baseDamage', -> 2) @battle.performMove(@p1, theMove) @battle.endTurn() @battle.beginTurn() @battle.continueTurn() spy.returned(false).should.be.true testRechargeMove("Hyper Beam") testRechargeMove("Giga Impact") testRechargeMove("Blast Burn") testRechargeMove("Frenzy Plant") testRechargeMove("Hydro Cannon") testRechargeMove("Roar of Time") testRechargeMove("Rock Wrecker") describe 'Clear Smog', -> it 'removes all status boosts on the target pokemon', -> shared.create.call(this) # Create artificial boosts. @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Clear Smog")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p2.stages.should.eql neutralBoosts it "does not reset stats if it hits a substitute", -> shared.create.call(this) @p2.attach(Attachment.Substitute, hp: 1) # Create artificial boosts. @p2.stages.defense = -3 @p2.stages.specialAttack = 4 @battle.performMove(@p1, @battle.getMove("Clear Smog")) neutralBoosts = { attack: 0, defense: 0, specialAttack: 0, specialDefense: 0, speed: 0, evasion: 0, accuracy: 0 } @p2.stages.should.not.eql neutralBoosts testMomentumMove = (moveName) -> describe moveName, -> it "prevents the user from switching", -> shared.create.call(this) @p1.isSwitchBlocked().should.be.false @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "locks the user into using this particular move", -> shared.create.call this, team1: [ Factory("Shuckle") ] momentumMove = @battle.getMove(moveName) @p1.moves = [ momentumMove, @battle.getMove("Rest") ] @p1.resetAllPP() @battle.performMove(@p1, momentumMove) @battle.endTurn() @battle.beginTurn() for move in @p1.moves if move == momentumMove @p1.isMoveBlocked(move).should.be.false else @p1.isMoveBlocked(move).should.be.true it "stops if it misses", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'miss', 100) @battle.performMove(@p1, @battle.getMove(moveName)) @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Momentum).should.be.false it "lasts 5 turns", -> shared.create.call(this) for i in [1..5] @battle.performMove(@p1, @battle.getMove(moveName)) @p1.has(Attachment.Momentum).should.be.true @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Momentum).should.be.false it "doubles base power every time", -> shared.create.call(this) move = @battle.getMove(moveName) basePower = move.power for i in [1..5] bp = move.basePower(@battle, @p1, @p2) bp.should.equal(basePower * Math.pow(2, i - 1)) @battle.performMove(@p1, move) @battle.endTurn() @battle.beginTurn() @p2.currentHP = @p2.stat('hp') it "doubles base power again if user has defense curl's effect", -> shared.create.call(this) @p1.attach(Attachment.DefenseCurl) move = @battle.getMove(moveName) basePower = 2 * move.power for i in [1..5] bp = move.basePower(@battle, @p1, @p2) bp.should.equal(basePower * Math.pow(2, i - 1)) @battle.performMove(@p1, move) @battle.endTurn() @battle.beginTurn() @p2.currentHP = @p2.stat('hp') testMomentumMove("Rollout") testMomentumMove("Ice Ball") describe "Me First", -> it "fails if the user goes second", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.delay @p1 @battle.popAction(@p2) @battle.performMove(@p1, move) mock.verify() it "uses the target's move", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('execute').once() @battle.recordMove(@id1, @battle.getMove("Me First")) @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, @battle.getMove("Me First")) mock.verify() it "has 1.5x the base power of the target's move", -> shared.create.call(this) move = @battle.getMove("Tackle") @battle.recordMove(@id1, @battle.getMove("Me First")) @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, @battle.getMove("Me First")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x1800 for moveName in [ "Chatter", "Counter", "Covet", "Focus Punch", "Me First", "Metal Burst", "Mirror Coat", "Struggle", "Thief" ] do (moveName) -> it "fails if the target is using #{moveName}", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove(moveName)) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, move) mock.verify() it "fails if the target is using a non-damaging move", -> shared.create.call(this) move = @battle.getMove("Me First") mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id1, move) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.determineTurnOrder() @battle.bump @p1 @battle.performMove(@p1, move) mock.verify() describe "Dream Eater", -> it "fails if the target is not asleep", -> shared.create.call(this) move = @battle.getMove("Dream Eater") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "does not fail if the target is asleep", -> shared.create.call(this) move = @battle.getMove("Dream Eater") mock = @sandbox.mock(move).expects('fail').never() @p2.attach(Status.Sleep) @battle.performMove(@p1, move) mock.verify() it "drains 1/2 of damage", -> shared.create.call(this) @p1.currentHP = initialHP = 1 @p2.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove("Dream Eater")) damage = @p2.stat('hp') - @p2.currentHP healed = Math.floor(damage / 2) @p1.currentHP.should.equal(initialHP + healed) describe "Camouflage", -> it "changes the user's type to Ground type in Wi-Fi battles", -> shared.create.call(this) @p1.types = [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Camouflage")) @p1.types.should.eql [ "Ground" ] describe "Charge", -> shared.shouldDoNoDamage("Charge") it "raises the user's special defense by 1", -> shared.create.call(this) @p1.stages.specialDefense.should.equal 0 @battle.performMove(@p1, @battle.getMove("Charge")) @p1.stages.specialDefense.should.equal 1 it "doubles the base power of the user's next move", -> shared.create.call(this) move = @battle.getMove("Thunderbolt") move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 @battle.performMove(@p1, @battle.getMove("Charge")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x2000 it "doesn't double the next move if it is non-electric type", -> shared.create.call(this) move = @battle.getMove("Flamethrower") move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 @battle.performMove(@p1, @battle.getMove("Charge")) move.modifyAttack(@battle, @p1, @p2).should.equal 0x1000 it "can be used twice in a row", -> shared.create.call(this) move = @battle.getMove("Charge") mock = @sandbox.mock(move).expects('fail').never() @battle.performMove(@p1, move) @battle.endTurn() @battle.performMove(@p1, move) @battle.endTurn() @p1.has(Attachment.Charge).should.be.true mock.verify() describe "Tri Attack", -> it "has a 20% chance to activate its secondary effect", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.hasStatus().should.be.true it "has a 1/3 chance for the secondary effect to be paralysis", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 0) # par @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Paralyze).should.be.true it "has a 1/3 chance for the secondary effect to be burn", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 1) # brn @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Burn).should.be.true it "has a 1/3 chance for the secondary effect to be freeze", -> shared.create.call(this) shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance shared.biasRNG.call(this, "randInt", 'tri attack effect', 2) # frz @battle.performMove(@p1, @battle.getMove("Tri Attack")) @p2.has(Status.Freeze).should.be.true describe "Mirror Move", -> it "copies the opponent's last move", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('execute').once() @p2.lastMove = move @battle.performMove(@p1, @battle.getMove("Mirror Move")) mock.verify() it "fails if the opponent has not moved the past turn", -> shared.create.call(this) move = @battle.getMove("Mirror Move") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() it "fails if the move does not have a `mirror` flag", -> shared.create.call(this) @p2.lastMove = @battle.getMove("Dragon Dance") move = @battle.getMove("Mirror Move") mock = @sandbox.mock(move).expects('fail').once() @battle.performMove(@p1, move) mock.verify() # TODO: Find out if this is true: when is lastMove nullified? it "fails if the pokemon was unable to move the previous turn" describe "Leech Seed", -> shared.shouldFailIfUsedTwice("Leech Seed") it "saps 1/8 of the target's max HP each turn", -> shared.create.call(this) move = @battle.getMove("Leech Seed") @p1.currentHP = 1 @battle.performMove(@p1, move) @battle.endTurn() p = @p2 fullHP = p.stat('hp') (fullHP - p.currentHP).should.equal Math.floor(fullHP / 8) @p1.currentHP.should.equal(fullHP - p.currentHP + 1) it "saps up to 1/8 HP", -> shared.create.call(this) move = @battle.getMove("Leech Seed") @p1.currentHP = 1 @p2.currentHP = 1 @battle.performMove(@p1, move) @battle.endTurn() @p1.currentHP.should.equal 2 it "saps a minimum of 1 damage", -> shared.create.call(this, team2: [Factory("Shedinja")]) move = @battle.getMove("Leech Seed") @battle.performMove(@p1, move) @battle.endTurn() @p2.currentHP.should.equal(0) it "always misses on Grass type Pokemon", -> shared.create.call(this) move = @battle.getMove("Leech Seed") mock = @sandbox.mock(move).expects('afterMiss').once() @p2.types = [ "Water", "Grass"] @battle.performMove(@p1, move) mock.verify() it "does not trigger if the user has fainted", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p1.faint() @battle.endTurn() @p2.currentHP.should.equal @p2.stat('hp') it "leeches next pokemon to switch in at that slot", -> shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p1.faint() @battle.endTurn() @battle.performSwitch(@team1.first(), 1) @p2.currentHP.should.equal @p2.stat('hp') newFirst = @team1.first() newFirst.currentHP = 1 @battle.endTurn() hp = @p2.stat('hp') - @p2.currentHP hp.should.be.greaterThan(0) newFirst.currentHP.should.equal(hp + 1) it "stops if the target has fainted", -> shared.create.call(this, team2: (Factory("Magikarp") for x in [1..2])) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Leech Seed")) @p2.faint() @battle.endTurn() @battle.performSwitch(@team2.first(), 1) @team2.first().currentHP.should.equal @team2.first().stat('hp') @p1.currentHP.should.equal(1) testProtectCounterMove = (moveName) -> it "fails if the user moves last this turn", -> shared.create.call(this) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('fail').once() @battle.determineTurnOrder() @battle.performMove(@p1, move) mock.verify() it "has decreasing chances of success", -> shared.create.call(this) p = @p1 for x in [0..7] attachment = p.attach(Attachment.ProtectCounter) attachment.successChance().should.equal Math.pow(2, x) attachment = p.attach(Attachment.ProtectCounter) attachment.successChance().should.equal Math.pow(2, 32) it "fails if not successful", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 2) move = @battle.getMove(moveName) mock = @sandbox.mock(move).expects('fail').once() @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) mock.verify() it "resets to 100% chance of success if move fails", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 2) move = @battle.getMove(moveName) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) @p1.has(Attachment.ProtectCounter).should.be.false it "resets to 100% chance of success if user selects a different move", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", 'protect', 1) move = @battle.getMove(moveName) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, move) @battle.endTurn() @p1.has(Attachment.ProtectCounter).should.be.true @battle.performMove(@p1, @battle.getMove('Splash')) @battle.endTurn() @p1.has(Attachment.ProtectCounter).should.be.false testProtectMove = (moveName) -> describe moveName, -> testProtectCounterMove(moveName) it "completely protects the user from attacks", -> shared.create.call(this) move = @battle.getMove("Tackle") mock = @sandbox.mock(move).expects('hit').never() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) mock.verify() it "does not carry over to the next turn", -> shared.create.call(this) move = @battle.getMove("Tackle") @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) @battle.endTurn() mock = @sandbox.mock(move).expects('hit').once() @battle.performMove(@p2, move) mock.verify() it "does not protect the user from attacks without the protect flag", -> shared.create.call(this) move = @battle.getMove("Feint") mock = @sandbox.mock(move).expects('hit').once() @battle.recordMove(@id2, move) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove(moveName)) @battle.performMove(@p2, move) mock.verify() testProtectMove 'Protect' testProtectMove 'Detect' describe "Endure", -> testProtectCounterMove("Endure") it "always survives moves that would otherwise KO with 1 HP", -> shared.create.call(this) move = @battle.getMove("Tackle") hp = @p1.currentHP @sandbox.stub(move, 'baseDamage', -> hp) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Endure")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.currentHP.should.equal 1 it "disappears at the end of the turn", -> shared.create.call(this) @battle.recordMove(@id2, @battle.getMove("Tackle")) @battle.determineTurnOrder() @battle.performMove(@p1, @battle.getMove("Endure")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.has(Attachment.Endure).should.be.true @battle.endTurn() @p1.has(Attachment.Endure).should.be.false describe "Feint", -> it "removes the Protect attachment, if any, on the target", -> shared.create.call(this) @p1.attach(Attachment.Protect) @p1.has(Attachment.Protect).should.be.true @battle.performMove(@p2, @battle.getMove("Feint")) @p1.has(Attachment.Protect).should.be.false it "removes the Wide Guard attachment, if any, on the target" it "removes the Quick Guard attachment, if any, on the target" describe "Payback", -> it "doubles base power if target has made a move this turn", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.performMove(@p2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(2 * move.power).should.be.true it "doesn't double base power otherwise", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(move.power).should.be.true it "doesn't double BP if target moved last turn, but not this turn", -> shared.create.call(this) move = @battle.getMove("Payback") spy = @sandbox.spy(move, 'basePower') @battle.performMove(@p2, @battle.getMove("Splash")) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.performMove(@p1, move) spy.returned(move.power).should.be.true describe "Curse", -> it "silently chooses a random enemy as the target", -> shared.create.call(this) move = @battle.getMove("Curse") targets = move.getTargets(@battle, @p1) should.exist targets targets.should.eql [ @p2 ] describe "for Ghost types", -> it "curses the opponent", -> shared.create.call(this) @p1.types = [ "Ghost" ] @battle.performMove(@p1, @battle.getMove("Curse")) @p2.has(Attachment.Curse).should.be.true it "damages the user for half of its HP, rounded down", -> shared.create.call(this) p = @p1 p.types = [ "Ghost" ] maxHP = p.stat('hp') @battle.performMove(@p1, @battle.getMove("Curse")) p.currentHP.should.equal(maxHP - Math.floor(maxHP / 2)) it "causes the opponent to lose 25% of their HP at end of turns", -> shared.create.call(this) @p1.types = [ "Ghost" ] p = @p2 maxHP = p.stat('hp') quarterHP = Math.floor(maxHP / 4) @battle.performMove(@p1, @battle.getMove("Curse")) p.currentHP.should.equal(maxHP) @battle.endTurn() p.currentHP.should.equal(maxHP - quarterHP) @battle.endTurn() p.currentHP.should.equal(maxHP - 2 * quarterHP) it "causes the opponent to lose a minimum of 1 HP per turn", -> shared.create.call(this, team2: [Factory("Shedinja"), Factory("Magikarp")]) @p1.types = [ "Ghost" ] @battle.performMove(@p1, @battle.getMove("Curse")) @battle.endTurn() @p2.currentHP.should.equal(0) it "can faint the user", -> shared.create.call(this) p = @p1 p.types = [ "Ghost" ] p.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Curse")) p.isFainted().should.be.true describe "for non-Ghost types", -> it "raises Attack and Defense and lowers Speed", -> shared.create.call(this) p = @p1 p.types = [ "Normal" ] @battle.performMove(@p1, @battle.getMove("Curse")) p.stages.should.containEql attack: 1, defense: 1, speed: -1 testBasePowerBoostMove = (moveName, rawBasePower, maxBasePower, which) -> describe moveName, -> it "increases base power by 20 for each positive stat boost on #{which}", -> shared.create.call(this) move = @battle.getMove(moveName) poke = { user: @p1, target: @p2 } {user, target} = poke move.basePower(@battle, user, target).should.equal rawBasePower poke[which].boost(attack: 1) move.basePower(@battle, user, target).should.equal rawBasePower + 20 poke[which].boost(defense: 1) move.basePower(@battle, user, target).should.equal rawBasePower + 40 poke[which].boost(speed: 2, specialAttack: -1) move.basePower(@battle, user, target).should.equal rawBasePower + 80 it "has a maximum of #{maxBasePower} base power", -> shared.create.call(this) move = @battle.getMove(moveName) poke = { user: @p1, target: @p2 } {user, target} = poke # Total base power would theoretically be rawBasePower + 840 stats = { speed: 6, specialAttack: 6, attack: 6, defense: 6, specialDefense: 6, evasion: 6, accuracy: 6 } poke[which].boost(stats) move.basePower(@battle, user, target).should.equal maxBasePower testBasePowerBoostMove("Stored Power", 20, 860, "user") testBasePowerBoostMove("Punishment", 60, 200, "target") describe "Destiny Bond", -> it "causes the attacker to faint the turn of use if the user faints", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.true it "causes the attacker to faint any time before the user moves again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.endTurn() @battle.beginTurn() @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.true it "does not cause attacker to faint after user moves again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p1, @battle.getMove("Splash")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.false it "does not cause attacker to faint after user attempts to move again", -> shared.create.call(this) @p1.currentHP = 1 @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.endTurn() @battle.beginTurn() @p1.attach(Status.Sleep) @battle.performMove(@p1, @battle.getMove("Tackle")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p2.isFainted().should.be.false it "does not faint attacker if pokemon fainted naturally", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @p1.faint() @battle.endTurn() @p2.isFainted().should.be.false it "does not faint attacker if opponent made move, but did not faint", -> shared.create.call(this) @battle.setWeather(Weather.SAND) @battle.performMove(@p2, @battle.getMove("Tackle")) @battle.performMove(@p1, @battle.getMove("Destiny Bond")) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.currentHP = 1 @battle.endTurn() @p1.isFainted().should.be.true @p2.isFainted().should.be.false it "does not cause a party member to faint" it "handles 2+ pokemon destiny-bonding and all fainting at once" describe "Pursuit", -> it "doubles base power if the target switches", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() spy.alwaysReturned(2 * pursuit.power).should.be.true it "doubles BP if a faster target uses a damaging switch move", -> shared.create.call this, team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id2, @battle.getMove("U-turn")) @battle.recordMove(@id1, pursuit) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(2 * pursuit.power).should.be.true it "doesn't double BP if a slower target uses a damaging switch move", -> shared.create.call this, team1: [ Factory("Magikarp", evs: {speed: 4}) ] team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id1, pursuit) @battle.recordMove(@id2, @battle.getMove("U-turn")) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(pursuit.power).should.be.true it "has perfect accuracy if target is switching", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'chanceToHit') pursuit = @battle.getMove("Pursuit") @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() spy.alwaysReturned(0).should.be.true it "runs only once", -> shared.create.call this, team2: [ Factory("Magikarp"), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(pursuit).expects('execute').once() pursuit = @battle.getMove("Pursuit") @battle.recordSwitch(@id2, 1) @battle.recordMove(@id1, pursuit) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() mock.verify() it "doesn't double BP on a faster Baton Passer", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(pursuit, 'basePower') @battle.recordMove(@id1, pursuit) @battle.recordMove(@id2, @battle.getMove("Baton Pass")) @battle.continueTurn() @battle.recordSwitch(@id2, 1) # battle.forceSwitch makes a request @battle.continueTurn() spy.alwaysReturned(pursuit.power).should.be.true it "emits the move name when target switches", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") spy = @sandbox.spy(@battle, 'tell') @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() spy.calledWith(Protocol.MAKE_MOVE).should.be.true it "records the move when target switches", -> shared.create.call this, team1: [ Factory("Magikarp") ] team2: [ Factory("Magikarp", evs: {speed: 4}), Factory("Magikarp") ] pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(@p1).expects('recordMove').once() @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() mock.verify() it "does not trigger if asleep", -> shared.create.call(this) @p1.attach(Status.Sleep, turns: 4) pursuit = @battle.getMove("Pursuit") mock = @sandbox.mock(pursuit).expects('hit').never() @battle.recordMove(@id1, pursuit) @battle.recordSwitch(@id2, 1) @battle.continueTurn() mock.verify() it "does not trigger on team members" describe 'Power Swap', -> it 'swaps attack and special attack boosts with the target', -> shared.create.call(this) @p1.boost(attack: 1, specialAttack: -3, speed: 1) @p2.boost(attack: 2, specialAttack: 6, defense: -1) @battle.performMove(@p1, @battle.getMove('Power Swap')) @p1.stages.should.containEql attack: 2, specialAttack: 6, speed: 1 @p2.stages.should.containEql attack: 1, specialAttack: -3, defense: -1 describe 'Guard Swap', -> it 'swaps defense and special defense boosts with the target', -> shared.create.call(this) @p1.boost(attack: 1, specialDefense: -3, defense: 1) @p2.boost(speed: 2, specialDefense: 6, defense: -1) @battle.performMove(@p1, @battle.getMove('Guard Swap')) @p1.stages.should.containEql defense: -1, specialDefense: 6, attack: 1 @p2.stages.should.containEql defense: 1, specialDefense: -3, speed: 2 describe 'Spite', -> it 'reduces the last move used by the target by 4', -> shared.create.call(this) move = @p2.moves[0] pp = @p2.pp(move) @battle.performMove(@p2, move) @battle.performMove(@p1, @battle.getMove('Spite')) @p2.pp(move).should.equal(pp - 4 - 1) it 'fails if the target has not recorded their last move', -> shared.create.call(this) spite = @battle.getMove('Spite') mock = @sandbox.mock(spite).expects('fail').once() @battle.performMove(@p1, spite) mock.verify() it "fails if the target's move has 0 PP", -> shared.create.call(this) spite = @battle.getMove('Spite') move = @p2.moves[0] mock = @sandbox.mock(spite).expects('fail').once() @p2.setPP(move, 0) @battle.performMove(@p2, move) @battle.performMove(@p1, spite) mock.verify() it 'fails if the target no longer knows the move', -> shared.create.call(this) spite = @battle.getMove('Spite') move = @p2.moves[0] mock = @sandbox.mock(spite).expects('fail').once() @battle.performMove(@p2, move) @p2.moves.splice(@p2.moves.indexOf(move), 1) @battle.performMove(@p1, spite) mock.verify() describe 'Wring Out', -> it 'has 120 power at maximum HP', -> shared.create.call(this) move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 120 it 'has 59 power at half-of-odd HP (rounded down)', -> shared.create.call(this) @p1.currentHP >>= 1 move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 59 it 'has 1 power minimum', -> shared.create.call(this) @p1.currentHP = 1 move = @battle.getMove('Wring Out') move.basePower(@battle, @p1, @p2).should.equal 1 describe 'Assurance', -> it 'doubles base power if the user was damaged this turn', -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Tackle')) power = move.basePower(@battle, @p1, @p2) power.should.equal(2 * move.power) it "doesn't double base power if the user was damaged a different turn", -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Tackle')) @battle.endTurn() @battle.beginTurn() power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) it "doesn't double base power if the user has never used a move", -> shared.create.call(this) move = @battle.getMove('Assurance') power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) it "doesn't double base power if hit by a non-damaging move", -> shared.create.call(this) move = @battle.getMove('Assurance') @battle.performMove(@p2, @battle.getMove('Will-O-Wisp')) power = move.basePower(@battle, @p1, @p2) power.should.equal(move.power) describe "Substitute", -> shared.shouldDoNoDamage("Substitute") shared.shouldFailIfUsedTwice("Substitute") it "removes 25% of the owner's health, rounded down", -> shared.create.call(this) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') @battle.performMove(@p1, sub) @p1.currentHP.should.equal(hp - (hp >> 2)) it "fails if the pokemon has 25% HP or less", -> shared.create.call(this) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') mock = @sandbox.mock(sub).expects('fail').once() @p1.currentHP = hp >> 2 @battle.performMove(@p1, sub) mock.verify() it "fails if the pokemon does not have enough total HP", -> shared.create.call(this, team1: [Factory("Shedinja")]) sub = @battle.getMove('Substitute') hp = @p1.stat('hp') mock = @sandbox.mock(sub).expects('fail').once() @battle.performMove(@p1, sub) mock.verify() it "takes damage for the user", -> shared.create.call(this) sub = @battle.getMove('Substitute') subHP = (@p1.stat('hp') >> 2) @battle.performMove(@p1, sub) hp = @p1.currentHP attachment = @p1.get(Attachment.Substitute) attachment.hp.should.equal subHP @battle.performMove(@p2, @battle.getMove('Tackle')) attachment.hp.should.be.lessThan subHP @p1.currentHP.should.equal hp it "breaks after taking too much damage", -> shared.create.call(this) tackle = @battle.getMove('Tackle') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) hp = @p1.currentHP @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(tackle, 'baseDamage', -> 9999) @battle.performMove(@p2, tackle) @p1.has(Attachment.Substitute).should.be.false @p1.currentHP.should.equal hp it "fails most non-damaging moves", -> shared.create.call(this) hypnosis = @battle.getMove('Hypnosis') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(hypnosis).expects('fail').once() @battle.performMove(@p2, hypnosis) mock.verify() it "does not fail stat-up moves", -> shared.create.call(this) dragonDance = @battle.getMove('Dragon Dance') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(dragonDance).expects('fail').never() @battle.performMove(@p1, dragonDance) mock.verify() it "does not fail non-damaging moves with an authentic flag", -> shared.create.call(this) foresight = @battle.getMove('Foresight') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true mock = @sandbox.mock(foresight).expects('fail').never() @battle.performMove(@p2, foresight) mock.verify() it "still stores the actual damage", -> shared.create.call(this) gigaDrain = @battle.getMove('Giga Drain') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true spy = @sandbox.spy(@p2, 'drain') @battle.performMove(@p2, gigaDrain) spy.calledWith(0).should.be.false @p1.lastHitBy.damage.should.be.greaterThan 0 it "blocks secondary effects", -> shared.create.call(this) shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn flamethrower = @battle.getMove('Flamethrower') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(flamethrower, 'baseDamage', -> 1) @battle.performMove(@p2, flamethrower) @p1.has(Status.Burn).should.be.false it "blocks secondary effects even if sub fades", -> shared.create.call(this) shared.biasRNG.call(this, "next", "secondary effect", 0) # always burn flamethrower = @battle.getMove('Flamethrower') sub = @battle.getMove('Substitute') @battle.performMove(@p1, sub) @p1.has(Attachment.Substitute).should.be.true @sandbox.stub(flamethrower, 'baseDamage', -> 9999) @battle.performMove(@p2, flamethrower) @p1.has(Status.Burn).should.be.false it "does not block sandstorm damage", -> shared.create.call(this) @battle.setWeather(Weather.SAND) @battle.performMove(@p1, @battle.getMove('Substitute')) hp = @p1.currentHP @battle.endTurn() @p1.currentHP.should.be.lessThan(hp) it "does not block leech seed damage", -> shared.create.call(this) @battle.performMove(@p2, @battle.getMove('Leech Seed')) @battle.performMove(@p1, @battle.getMove('Substitute')) hp = @p1.currentHP @battle.endTurn() @p1.currentHP.should.be.lessThan(hp) it "is baton-passable" describe "Sucker Punch", -> it "fails if the target is not moving after the user", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') mock = @sandbox.mock(suckerPunch).expects('fail').once() @battle.performMove(@p1, suckerPunch) mock.verify() it "executes normally if the target is moving after the user", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') tackle = @battle.getMove('Tackle') mock = @sandbox.mock(suckerPunch).expects('afterSuccessfulHit').once() @battle.recordMove(@id2, tackle) @battle.determineTurnOrder() @battle.performMove(@p1, suckerPunch) mock.verify() it "fails if the target is using a status move", -> shared.create.call(this) suckerPunch = @battle.getMove('Sucker Punch') willOWisp = @battle.getMove('Will-O-Wisp') mock = @sandbox.mock(suckerPunch).expects('fail').once() @battle.recordMove(@id2, willOWisp) @battle.determineTurnOrder() @battle.performMove(@p1, suckerPunch) mock.verify() describe 'Grudge', -> it "causes the last move to lose all its PP if the user faints", -> shared.create.call(this) grudge = @battle.getMove("Grudge") tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p2, tackle) @battle.performFaints() @p1.isFainted().should.be.true @p2.pp(tackle).should.equal 0 it "causes the attacker to lose PP any time before the user moves again", -> shared.create.call(this) grudge = @battle.getMove("Grudge") tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.endTurn() @battle.beginTurn() @battle.performMove(@p2, tackle) @battle.performFaints() @p2.pp(tackle).should.equal 0 it "does not cause attacker to lose PP after user moves again", -> shared.create.call(this) grudge = @battle.getMove("Grudge") splash = @battle.getMove('Splash') tackle = @battle.getMove('Tackle') @p2.moves = [ tackle ] @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p1, splash) @battle.performMove(@p2, tackle) @battle.performFaints() @p2.pp(tackle).should.not.equal 0 it "does not trigger from natural causes", -> shared.create.call(this) grudge = @battle.getMove("Grudge") splash = @battle.getMove('Splash') leechSeed = @battle.getMove('Leech Seed') @p2.moves = [ leechSeed ] @p2.resetAllPP() @p1.currentHP = 1 @battle.performMove(@p1, grudge) @battle.performMove(@p2, leechSeed) @battle.endTurn() @p2.pp(leechSeed).should.equal(@p2.maxPP(leechSeed) - 1) describe "Stockpile", -> it "raises def and spdef", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, stockpile) @p1.stages.should.containEql defense: 1, specialDefense: 1 it "cannot raise if stockpile is at its limit", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") for i in [0...Attachment.Stockpile::maxLayers] @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 it "fails if stockpile is at its limit", -> shared.create.call(this) stockpile = @battle.getMove("Stockpile") mock = @sandbox.mock(stockpile).expects('fail').once() for i in [0...Attachment.Stockpile::maxLayers] @p1.attach(Attachment.Stockpile) @battle.performMove(@p1, stockpile) mock.verify() describe 'Spit Up', -> it 'fails if user has no stockpiles', -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") mock = @sandbox.mock(spitUp).expects('fail').once() @battle.performMove(@p1, spitUp) mock.verify() it "has 100 base power with 1 layer of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 100 it "has 200 base power with 2 layers of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 200 it "has 300 base power with 3 layers of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) spitUp.basePower(@battle, @p1, @p2).should.equal 300 it "resets stockpile count to 0", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.get(Attachment.Stockpile).layers.should.equal 1 @battle.performMove(@p1, spitUp) @p1.has(Attachment.Stockpile).should.be.false it "loses def/sp. def according to number of stockpiles", -> shared.create.call(this) spitUp = @battle.getMove("Spit Up") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, spitUp) @p1.stages.should.containEql defense: -2, specialDefense: -2 describe 'Swallow', -> it 'fails if user has no stockpiles', -> shared.create.call(this) swallow = @battle.getMove("Swallow") mock = @sandbox.mock(swallow).expects('fail').once() @battle.performMove(@p1, swallow) mock.verify() it "heals 25% of its HP, rounded half-down, with 1 layer of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal(1 + util.roundHalfDown(@p1.stat('hp') / 4)) it "heals 50% of its HP, rounded half-down, with 2 layers of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal(1 + util.roundHalfDown(@p1.stat('hp') / 2)) it "heals all of its HP with 3 layers of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.currentHP = 1 @battle.performMove(@p1, swallow) @p1.currentHP.should.equal @p1.stat('hp') it "resets stockpile count to 0", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.get(Attachment.Stockpile).layers.should.equal 1 @battle.performMove(@p1, swallow) @p1.has(Attachment.Stockpile).should.be.false it "loses def/sp. def according to number of stockpiles", -> shared.create.call(this) swallow = @battle.getMove("Swallow") @p1.attach(Attachment.Stockpile) @p1.attach(Attachment.Stockpile) @p1.stages.should.containEql defense: 0, specialDefense: 0 @battle.performMove(@p1, swallow) @p1.stages.should.containEql defense: -2, specialDefense: -2 describe 'Rage', -> it "raises the user's attack if hit by a move", -> shared.create.call(this) rage = @battle.getMove('Rage') tackle = @battle.getMove('Tackle') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p2, tackle) @p1.stages.attack.should.equal 1 it "doesn't raise the user's attack if user chooses another move", -> shared.create.call(this) rage = @battle.getMove('Rage') tackle = @battle.getMove('Tackle') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p1, tackle) @battle.performMove(@p2, tackle) @p1.stages.attack.should.equal 0 it "doesn't raise the user's attack if hit by a non-damaging move", -> shared.create.call(this) rage = @battle.getMove('Rage') willOWisp = @battle.getMove('Will-O-Wisp') @p1.stages.attack.should.equal 0 @battle.performMove(@p1, rage) @battle.performMove(@p2, willOWisp) @p1.stages.attack.should.equal 0 testRevengeMove = (moveName) -> describe moveName, -> it "doubles base power if hit by an attack that turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.performMove(@p2, tackle) revenge.basePower(@battle, @p1, @p2).should.equal(2 * revenge.power) it "doesn't double base power if not hit by an attack that turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) it "doesn't double base power if hit by a non-damaging move", -> shared.create.call(this) revenge = @battle.getMove(moveName) willOWisp = @battle.getMove("Will-O-Wisp") @battle.performMove(@p2, willOWisp) revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) it "doesn't double base power if hit last turn, but not this turn", -> shared.create.call(this) revenge = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.performMove(@p2, tackle) @battle.beginTurn() revenge.basePower(@battle, @p1, @p2).should.equal(revenge.power) testRevengeMove("Avalanche") testRevengeMove("Revenge") testIgnoreStagesMove = (moveName) -> describe moveName, -> it "ignores the target's defensive and evasive stat stages", -> shared.create.call(this) move = @battle.getMove(moveName) stats = [ 'defense', 'specialDefense', 'evasion' ] values = ( @p2.stat(stat) for stat in stats ) spy = @sandbox.spy(@p2, 'stat') spy.withArgs(stat) for stat in stats @p2.boost(defense: -3, specialDefense: 2, evasion: 6) @battle.performMove(@p1, move) for i in [0...stats.length] stat = stats[i] value = values[i] continue if spy.withArgs(stat).returnValues.length == 0 spy.withArgs(stat).alwaysReturned(value).should.be.true testIgnoreStagesMove("Chip Away") testIgnoreStagesMove("Sacred Sword") describe 'Captivate', -> it 'fails if the user and target are not opposite genders', -> shared.create.call this, team1: [Factory("Magikarp", gender: "M")] team2: [Factory("Magikarp", gender: "M")] captivate = @battle.getMove('Captivate') mock = @sandbox.mock(captivate).expects('fail').once() @battle.performMove(@p1, captivate) mock.verify() it "lowers the target's special attack by 2", -> shared.create.call this, team1: [Factory("Magikarp", gender: "M")] team2: [Factory("Magikarp", gender: "F")] captivate = @battle.getMove('Captivate') @p2.stages.specialAttack.should.equal 0 @battle.performMove(@p1, captivate) @p2.stages.specialAttack.should.equal -2 testStatusCureAttackMove = (moveName, status) -> describe moveName, -> it "doubles base power if the target has #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.attach(status) move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) it "doesn't double if the target doesn't have #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) move.basePower(@battle, @p1, @p2).should.equal(move.power) it "cures the target of #{status.name}", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.attach(status) @p2.has(status).should.be.true @battle.performMove(@p1, move) @p2.hasStatus().should.be.false it "does not cure #{status.name} if the user faints", -> shared.create.call(this, team2: [Factory("Magikarp", ability: "Iron Barbs")]) move = @battle.getMove(moveName) @p1.currentHP = 1 @p2.attach(status) @p2.has(status).should.be.true @battle.performMove(@p1, move) @p2.hasStatus().should.be.true testStatusCureAttackMove("Wake-Up Slap", Status.Sleep) testStatusCureAttackMove("SmellingSalt", Status.Paralyze) describe 'Aqua Ring', -> it "restores 1/16 max HP at the end of each turn", -> shared.create.call(this) aquaRing = @battle.getMove('Aqua Ring') delta = @p1.currentHP >> 4 @p1.currentHP = 1 @battle.performMove(@p1, aquaRing) @p1.currentHP.should.equal(1) @battle.endTurn() @p1.currentHP.should.equal(1 + delta) describe 'Ingrain', -> it "restores 1/16 max HP at the end of each turn", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') delta = @p1.currentHP >> 4 @p1.currentHP = 1 @battle.performMove(@p1, ingrain) @p1.currentHP.should.equal(1) @battle.endTurn() @p1.currentHP.should.equal(1 + delta) it "prevents switching", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') @battle.performMove(@p1, ingrain) @battle.beginTurn() @p1.isSwitchBlocked().should.be.true it "prevents self from being phased", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] ingrain = @battle.getMove('Ingrain') whirlwind = @battle.getMove('Whirlwind') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(@team1).expects('switch').never() @battle.performMove(@p2, whirlwind) mock.verify() it "lets self be switched out if using self-switching moves", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') uTurn = @battle.getMove('U-turn') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(@battle).expects('requestActions').once() @battle.performMove(@p1, uTurn) mock.verify() it "makes self vulnerable to Ground moves", -> shared.create.call(this, team1: [ Factory("Gyarados") ]) ingrain = @battle.getMove('Ingrain') uTurn = @battle.getMove('U-turn') @p1.isImmune('Ground').should.be.true @battle.performMove(@p1, ingrain) @p1.isImmune('Ground').should.be.false it "causes Telekinesis to fail", -> shared.create.call(this) ingrain = @battle.getMove('Ingrain') telekinesis = @battle.getMove('Telekinesis') @battle.performMove(@p1, ingrain) mock = @sandbox.mock(telekinesis).expects('fail').once() @battle.performMove(@p2, telekinesis) mock.verify() describe "Embargo", -> it "prevents the target's use of items", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) @battle.endTurn() mock.verify() it "lasts 5 turns", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) for i in [0...5] @p2.has(Attachment.Embargo).should.be.true @battle.endTurn() @p2.has(Attachment.Embargo).should.be.false it "prevents the target's use of items in subsequent turns", -> shared.create.call this, team2: [ Factory("Magikarp", item: "Leftovers") ] embargo = @battle.getMove('Embargo') mock = @sandbox.mock(@p2.get(@p2.item)).expects('endTurn').never() @battle.performMove(@p1, embargo) for i in [0...5] @battle.endTurn() @battle.beginTurn() mock.verify() testChargeMove = (moveName, vulnerable) -> describe moveName, -> it "chooses the player's next action for them", -> shared.create.call(this) move = @battle.getMove(moveName) @p1.moves = [ move ] @battle.recordMove(@id1, move) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() @battle.requests.should.not.have.property(@id1) should.exist(@battle.getAction(@p1)) it "only spends 1 PP for the entire attack", -> shared.create.call(this) move = @battle.getMove(moveName) @p1.moves = [ move ] @p1.resetAllPP() pp = @p1.pp(move) @battle.recordMove(@id1, move) @battle.continueTurn() @p1.pp(move).should.equal(pp) @battle.beginTurn() @battle.continueTurn() @p1.pp(move).should.equal(pp - 1) it "skips the charge turn if the user is holding a Power Herb", -> shared.create.call this, team1: [Factory("Magikarp", item: "Power Herb")] move = @battle.getMove(moveName) @p1.hasItem("Power Herb").should.be.true mock = @sandbox.mock(move).expects('execute').once() @battle.recordMove(@id1, move) @battle.continueTurn() mock.verify() @p1.hasItem().should.be.false if vulnerable?.length? it "makes target invulnerable to moves", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) clearSmog = @battle.getMove("Clear Smog") @battle.recordMove(@id1, move) @battle.recordMove(@id2, clearSmog) mock = @sandbox.mock(clearSmog).expects('hit').never() @battle.continueTurn() mock.verify() it "makes target invulnerable to moves *after* use", -> shared.create.call this, team2: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() it "is vulnerable to attacks from a No Guard pokemon", -> shared.create.call this, team2: [Factory("Magikarp", ability: "No Guard")] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() it "is vulnerable to attacks if locked on", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Lock-On")) @battle.performMove(@p2, @battle.getMove(moveName)) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() for vulnerableMove in vulnerable it "is vulnerable to #{vulnerableMove}", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) vulnerable = @battle.getMove(vulnerableMove) @battle.recordMove(@id1, move) @battle.recordMove(@id2, vulnerable) mock = @sandbox.mock(vulnerable).expects('hit').once() @battle.continueTurn() mock.verify() else # no vulnerable moves it "doesn't make target invulnerable to moves", -> shared.create.call this, team1: [Factory("Magikarp", evs: {speed: 4})] move = @battle.getMove(moveName) tackle = @battle.getMove("Tackle") @battle.recordMove(@id1, move) @battle.recordMove(@id2, tackle) mock = @sandbox.mock(tackle).expects('hit').once() @battle.continueTurn() mock.verify() testChargeMove('Skull Bash') testChargeMove('Razor Wind') testChargeMove('Shadow Force', []) testChargeMove('Ice Burn') testChargeMove('Freeze Shock') testChargeMove('Fly', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down"]) testChargeMove('Bounce', ["Gust", "Thunder", "Twister", "Sky Uppercut", "Hurricane", "Smack Down"]) # Additional 30% chance to par testChargeMove('Dig', ["Earthquake", "Magnitude"]) testChargeMove('Dive', ["Surf", "Whirlpool"]) testChargeMove('SolarBeam') testChargeMove('Sky Attack') describe "Skull Bash", -> it "raises defense of the user on the charge turn", -> shared.create.call(this) skullBash = @battle.getMove('Skull Bash') @p1.stages.defense.should.equal(0) @battle.performMove(@p1, skullBash) @p1.stages.defense.should.equal(1) describe "Sky Attack", -> it "has a 30% chance to flinch after execution", -> shared.create.call(this) skyAttack = @battle.getMove('Sky Attack') shared.biasRNG.call(this, "randInt", 'flinch', 0) # 100% chance @battle.recordMove(@id1, skyAttack) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.false @battle.beginTurn() @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true for moveName in [ "Gust", "Twister" ] for chargeMoveName in [ "Fly", "Bounce" ] do (moveName, chargeMoveName) -> describe moveName, -> it "deals double damage to Pokemon using #{chargeMoveName}", -> shared.create.call(this) chargeMove = @battle.getMove(chargeMoveName) move = @battle.getMove(moveName) # Make the Pokemon charge @battle.recordMove(@id2, chargeMove) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) for moveName in [ "Surf", "Whirlpool" ] do (moveName) -> describe moveName, -> it "deals double damage to Pokemon using Dive", -> shared.create.call(this) dive = @battle.getMove("Dive") move = @battle.getMove(moveName) # Make the Pokemon charge @battle.recordMove(@id2, dive) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * move.power) for moveName in [ "Earthquake", "Magnitude" ] do (moveName) -> describe moveName, -> it "deals double damage to Pokemon using Dig", -> shared.create.call(this) dig = @battle.getMove("Dig") move = @battle.getMove(moveName) power = move.power if moveName == 'Magnitude' power = 50 shared.biasRNG.call(this, 'randInt', 'magnitude', 20) # Make the Pokemon charge @battle.recordMove(@id2, dig) @battle.continueTurn() move.basePower(@battle, @p1, @p2).should.equal(2 * power) describe "SolarBeam", -> it "skips the charge turn under Sun", -> shared.create.call(this) solarBeam = @battle.getMove("SolarBeam") @battle.setWeather(Weather.SUN) mock = @sandbox.mock(solarBeam).expects('execute').once() @battle.recordMove(@id1, solarBeam) @battle.continueTurn() mock.verify() for weather in [ Weather.RAIN, Weather.SAND, Weather.HAIL ] do (weather) -> it "halves base power under #{weather}", -> shared.create.call(this) move = @battle.getMove("SolarBeam") @battle.setWeather(weather) move.basePower(@battle, @p1, @p2).should.equal(move.power >> 1) describe "Fury Cutter", -> it "doubles base power after every use, to a max of 160", -> shared.create.call(this) furyCutter = @battle.getMove("Fury Cutter") furyCutter.basePower(@battle, @p1, @p2).should.equal(20) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(40) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(80) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(160) @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(160) it "resets to normal base power if using a different move", -> shared.create.call(this) furyCutter = @battle.getMove("Fury Cutter") splash = @battle.getMove("Splash") @battle.performMove(@p1, furyCutter) furyCutter.basePower(@battle, @p1, @p2).should.equal(40) @battle.performMove(@p1, splash) furyCutter.basePower(@battle, @p1, @p2).should.equal(20) describe "Imprison", -> shared.shouldDoNoDamage("Imprison") shared.shouldFailIfUsedTwice("Imprison") it "prevents the opponent from selecting moves that the user knows", -> shared.create.call(this) imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @p2.validMoves().should.eql [ furyCutter, tackle, splash ] @battle.performMove(@p1, imprison) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter ] it "prevents the opponent from executing moves that the user knows", -> shared.create.call(this) imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @battle.performMove(@p1, imprison) mock = @sandbox.mock(tackle).expects('execute').never() @battle.performMove(@p2, tackle) mock.verify() it "lets opponents use moves again after user switches out", -> shared.create.call this, team1: [Factory("Magikarp"), Factory("Magikarp")] imprison = @battle.getMove("Imprison") furyCutter = @battle.getMove("Fury Cutter") tackle = @battle.getMove("Tackle") splash = @battle.getMove("Splash") @p1.moves = [ imprison, tackle, splash ] @p2.moves = [ furyCutter, tackle, splash ] @p1.resetAllPP() @p2.resetAllPP() @battle.performMove(@p1, imprison) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter ] @battle.performSwitch(@team1.first(), 1) @battle.beginTurn() @p2.validMoves().should.eql [ furyCutter, tackle, splash ] describe "Present", -> it "has a 40% chance for 40 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .6) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(40).should.be.true it "has a 30% chance for 80 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .3) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(80).should.be.true it "has a 10% chance for 120 base power", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", 0) present = @battle.getMove("Present") spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(120).should.be.true it "has a 20% chance to heal target by 25% HP, rounded down", -> shared.create.call(this) shared.biasRNG.call(this, "next", "present", .1) present = @battle.getMove("Present") @p2.currentHP = 1 spy = @sandbox.spy(present, 'basePower') @battle.performMove(@p1, present) spy.alwaysReturned(0).should.be.true @p2.currentHP.should.equal(1 + (@p2.stat('hp') >> 2)) describe "Final Gambit", -> it "faints the user", -> shared.create.call(this) finalGambit = @battle.getMove("Final Gambit") @battle.performMove(@p1, finalGambit) @p1.isFainted().should.be.true it "deals damage equal to the user's HP to the target", -> shared.create.call(this, team2: [Factory("Magikarp", evs: {hp: 4})]) finalGambit = @battle.getMove("Final Gambit") @battle.performMove(@p1, finalGambit) @p2.currentHP.should.equal(1) describe "Lucky Chant", -> shared.shouldDoNoDamage("Lucky Chant") shared.shouldFailIfUsedTwice("Lucky Chant") it "prevents critical hits on the defender's team", -> shared.create.call(this) luckyChant = @battle.getMove("Lucky Chant") stormThrow = @battle.getMove("Storm Throw") @battle.performMove(@p1, luckyChant) stormThrow.isCriticalHit(@battle, @p2, @p1).should.be.false it "lasts 5 turns", -> shared.create.call(this) luckyChant = @battle.getMove("Lucky Chant") @battle.performMove(@p1, luckyChant) for i in [0...5] @team1.has(Attachment.LuckyChant).should.be.true @battle.endTurn() @team1.has(Attachment.LuckyChant).should.be.false describe "Lunar Dance", -> it "faints the user", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") @battle.performMove(@p1, lunarDance) @p1.isFainted().should.be.true it "fails if the user is the last active pokemon", -> shared.create.call(this, team1: [Factory('Magikarp')]) lunarDance = @battle.getMove("Lunar Dance") mock = @sandbox.mock(lunarDance).expects('fail').once() @battle.performMove(@p1, lunarDance) mock.verify() @p1.isFainted().should.be.false it "completely restores the switchin's HP, PP, and status", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") benched = @team1.at(1) benched.attach(Status.Burn) benched.currentHP = 1 benched.setPP(benched.moves[0], 1) @battle.performMove(@p1, lunarDance) @battle.performSwitch(@team1.first(), 1) benched.currentHP.should.equal(benched.stat('hp')) benched.hasStatus().should.be.false for move in benched.moves benched.pp(move).should.equal(benched.maxPP(move)) it "disappears afterward", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lunarDance = @battle.getMove("Lunar Dance") @battle.performMove(@p1, lunarDance) @team1.has(Attachment.LunarDance).should.be.true @battle.performSwitch(@team1.first(), 1) @team1.has(Attachment.LunarDance).should.be.false it "works for 2v2" describe "Healing Wish", -> it "faints the user", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") @battle.performMove(@p1, healingWish) @p1.isFainted().should.be.true it "fails if the user is the last active pokemon", -> shared.create.call(this, team1: [Factory('Magikarp')]) healingWish = @battle.getMove("Healing Wish") mock = @sandbox.mock(healingWish).expects('fail').once() @battle.performMove(@p1, healingWish) mock.verify() @p1.isFainted().should.be.false it "completely restores the switchin's HP and status", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") benched = @team1.at(1) benched.attach(Status.Burn) benched.currentHP = 1 benched.setPP(benched.moves[0], 1) @battle.performMove(@p1, healingWish) @battle.performSwitch(@team1.first(), 1) benched.currentHP.should.equal(benched.stat('hp')) benched.hasStatus().should.be.false it "disappears afterward", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] healingWish = @battle.getMove("Healing Wish") @battle.performMove(@p1, healingWish) @team1.has(Attachment.HealingWish).should.be.true @battle.performSwitch(@team1.first(), 1) @team1.has(Attachment.HealingWish).should.be.false it "works for 2v2" describe "Last Resort", -> it "fails if the pokemon only has one move", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") @p1.moves = [ lastResort ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() it "works if the pokemon uses all other moves before Last Resort", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] @battle.performMove(@p1, splash) mock = @sandbox.mock(lastResort).expects('afterSuccessfulHit').once() @battle.performMove(@p1, lastResort) mock.verify() it "fails if using all moves, but switches out and back in", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, splash) @battle.performSwitch(@team1.first(), 1) @battle.performMove(@team1.first(), lastResort) @battle.performSwitch(@team1.first(), 1) mock.verify() it "fails if the pokemon does not know Last Resort", -> shared.create.call(this) splash = @battle.getMove("Splash") tackle = @battle.getMove("Tackle") @p1.moves = [ splash, tackle ] lastResort = @battle.getMove("Last Resort") mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() it "fails if the pokemon has not used another move since it was active", -> shared.create.call(this) lastResort = @battle.getMove("Last Resort") splash = @battle.getMove("Splash") @p1.moves = [ lastResort, splash ] mock = @sandbox.mock(lastResort).expects('fail').once() @battle.performMove(@p1, lastResort) mock.verify() describe "Assist", -> it "fails if no team member exists", -> shared.create.call this, team1: [ Factory("Magikarp") ] assist = @battle.getMove("Assist") mock = @sandbox.mock(assist).expects('fail').once() @battle.performMove(@p1, assist) mock.verify() it "chooses a team member's move at random", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] assist = @battle.getMove("Assist") move = @team1.at(1).moves[0] shared.biasRNG.call(this, "randInt", "assist", 0) mock = @sandbox.mock(move) mock.expects('execute').once().withArgs(@battle, @p1, [ @p1 ]) @battle.performMove(@p1, assist) mock.verify() it "fails if all team member moves are illegal", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Magikarp") ] assist = @battle.getMove("Assist") @team1.at(1).moves = [] @team1.at(1).moves.push @battle.getMove("Assist") @team1.at(1).moves.push @battle.getMove("Bestow") @team1.at(1).moves.push @battle.getMove("Chatter") @team1.at(1).moves.push @battle.getMove("Circle Throw") @team1.at(1).moves.push @battle.getMove("Copycat") @team1.at(1).moves.push @battle.getMove("Counter") @team1.at(1).moves.push @battle.getMove("Covet") @team1.at(1).moves.push @battle.getMove("Destiny Bond") @team1.at(1).moves.push @battle.getMove("Detect") @team1.at(1).moves.push @battle.getMove("Dragon Tail") @team1.at(1).moves.push @battle.getMove("Endure") @team1.at(1).moves.push @battle.getMove("Feint") @team1.at(1).moves.push @battle.getMove("Focus Punch") @team1.at(1).moves.push @battle.getMove("Follow Me") @team1.at(1).moves.push @battle.getMove("Helping Hand") @team1.at(1).moves.push @battle.getMove("Me First") @team1.at(1).moves.push @battle.getMove("Metronome") @team1.at(1).moves.push @battle.getMove("Mimic") @team1.at(1).moves.push @battle.getMove("Mirror Coat") @team1.at(1).moves.push @battle.getMove("Mirror Move") @team1.at(1).moves.push @battle.getMove("Nature Power") @team1.at(1).moves.push @battle.getMove("Protect") @team1.at(1).moves.push @battle.getMove("Rage Powder") @team1.at(1).moves.push @battle.getMove("Sketch") @team1.at(1).moves.push @battle.getMove("Sleep Talk") @team1.at(1).moves.push @battle.getMove("Snatch") @team1.at(1).moves.push @battle.getMove("Struggle") @team1.at(1).moves.push @battle.getMove("Switcheroo") @team1.at(1).moves.push @battle.getMove("Thief") @team1.at(1).moves.push @battle.getMove("Transform") @team1.at(1).moves.push @battle.getMove("Trick") mock = @sandbox.mock(assist).expects('fail').once() @battle.performMove(@p1, assist) mock.verify() describe "Metronome", -> it "chooses a random move to execute", -> shared.create.call(this) @p1.moves = [] metronome = @battle.getMove("Metronome") tackle = @battle.getMove("Tackle") index = @battle.MoveList.indexOf(tackle) shared.biasRNG.call(this, 'randInt', "metronome", index) mock = @sandbox.mock(tackle).expects('execute').once() @battle.performMove(@p1, metronome) mock.verify() it "reselects if chosen an illegal move", -> shared.create.call(this) @p1.moves = [ metronome ] metronome = @battle.getMove("Metronome") technoBlast = @battle.getMove("Techno Blast") tackle = @battle.getMove("Tackle") index = @battle.MoveList.indexOf(technoBlast) reselectIndex = @battle.MoveList.indexOf(tackle) shared.biasRNG.call(this, 'randInt', "metronome", index) shared.biasRNG.call(this, 'randInt', "metronome reselect", reselectIndex) mock = @sandbox.mock(tackle).expects('execute').once() @battle.performMove(@p1, metronome) mock.verify() describe "Magic Coat", -> shared.shouldDoNoDamage("Magic Coat") it "causes certain moves directed at the user to be bounced back", -> shared.create.call(this) whirlwind = @battle.getMove("Whirlwind") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(whirlwind, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, whirlwind) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.true it "bounces back spikes", -> shared.create.call(this) spikes = @battle.getMove("Spikes") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(spikes, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, spikes) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @id2 ).should.be.true @team1.has(Attachment.Spikes).should.be.false @team2.has(Attachment.Spikes).should.be.true it "cannot bounce spikes more than once", -> shared.create.call(this) spikes = @battle.getMove("Spikes") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, magicCoat) (=> @battle.performMove(@p2, spikes) ).should.not.throw(/Maximum call stack size exceeded/) it "does not bounce certain moves back", -> shared.create.call(this) tackle = @battle.getMove("Tackle") magicCoat = @battle.getMove("Magic Coat") spy = @sandbox.spy(tackle, 'execute') @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, tackle) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.false it "lasts until the end of the turn", -> shared.create.call(this) magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @p1.has(Attachment.MagicCoat).should.be.true @battle.endTurn() @p1.has(Attachment.MagicCoat).should.be.false it "cannot bounce more than once in the same turn", -> shared.create.call(this) willOWisp = @battle.getMove("Will-O-Wisp") thunderWave = @battle.getMove("Thunder Wave") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, willOWisp) spy = @sandbox.spy(thunderWave, 'execute') @battle.performMove(@p2, thunderWave) spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.false it "cannot bounce a certain move more than once in the same turn", -> shared.create.call(this) willOWisp = @battle.getMove("Will-O-Wisp") magicCoat = @battle.getMove("Magic Coat") @battle.performMove(@p1, magicCoat) @battle.performMove(@p2, magicCoat) spy = @sandbox.spy(willOWisp, 'execute') (=> @battle.performMove(@p2, willOWisp) ).should.not.throw(/Maximum call stack size exceeded/) spy.calledTwice.should.be.true spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p1 && targets[0] == @p2 ).should.be.true spy.args.some((array) => [battle, user, targets] = array battle == @battle && user == @p2 && targets[0] == @p1 ).should.be.true describe "Telekinesis", -> shared.shouldDoNoDamage("Telekinesis") shared.shouldFailIfUsedTwice("Telekinesis") it "makes the target immune to ground moves", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") @p1.isImmune('Ground').should.be.false @battle.performMove(@p2, telekinesis) @p1.isImmune('Ground').should.be.true it "lasts 3 turns", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p2, telekinesis) for x in [0...3] @p1.isImmune('Ground').should.be.true @battle.endTurn() @p1.isImmune('Ground').should.be.false it "makes the target unable to avoid attacks other than ohko moves", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") inferno = @battle.getMove("Inferno") sheerCold = @battle.getMove("Sheer Cold") inferno.chanceToHit(@battle, @p2, @p1).should.equal(50) sheerCold.chanceToHit(@battle, @p2, @p1).should.equal(30) @battle.performMove(@p2, telekinesis) inferno.chanceToHit(@battle, @p2, @p1).should.equal(0) sheerCold.chanceToHit(@battle, @p2, @p1).should.equal(30) describe "Smack Down", -> it "doesn't crash on secondary effect", -> shared.create.call(this, team2: [ Factory("Gyarados") ]) shared.biasRNG.call(this, "next", "secondary effect", 0) smackDown = @battle.getMove("Smack Down") (=> @battle.performMove(@p1, smackDown)).should.not.throw() it "removes target's Ground immunity", -> shared.create.call(this, team2: [ Factory("Gyarados") ]) smackDown = @battle.getMove("Smack Down") @p2.isImmune("Ground").should.be.true @battle.performMove(@p1, smackDown) @p2.isImmune("Ground").should.be.false it "stops Fly", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") fly = @battle.getMove("Fly") @battle.recordMove(@id1, fly) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.false it "stops Bounce", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") bounce = @battle.getMove("Bounce") @battle.recordMove(@id1, bounce) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.false it "does not stop other charge moves like Dive", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") dive = @battle.getMove("Dive") @battle.recordMove(@id1, dive) @battle.continueTurn() @p1.has(Attachment.Charging).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Charging).should.be.true it "stops Magnet Rise", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") magnetRise = @battle.getMove("Magnet Rise") @battle.performMove(@p1, magnetRise) @p1.has(Attachment.MagnetRise).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.MagnetRise).should.be.false it "stops Telekinesis", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p2, telekinesis) @p1.has(Attachment.Telekinesis).should.be.true @battle.performMove(@p2, smackDown) @p1.has(Attachment.Telekinesis).should.be.false it "makes Magnet Rise execution fail", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") magnetRise = @battle.getMove("Magnet Rise") @battle.performMove(@p1, smackDown) mock = @sandbox.mock(magnetRise).expects('fail').once() @battle.performMove(@p2, magnetRise) mock.verify() it "causes Telekinesis execution to fail", -> shared.create.call(this) smackDown = @battle.getMove("Smack Down") telekinesis = @battle.getMove("Telekinesis") @battle.performMove(@p1, smackDown) mock = @sandbox.mock(telekinesis).expects('fail').once() @battle.performMove(@p1, telekinesis) mock.verify() describe "Echoed Voice", -> it "has 80 base power the second turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) it "has 120 base power the third turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...3] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(120) it "has 160 base power the fourth turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...4] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(160) it "has 200 base power the fifth turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...5] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(200) it "has 200 base power the sixth and above turn in a row it is used", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") for i in [1...6] @battle.performMove(@p1, echoedVoice) @p2.currentHP = @p2.stat('hp') @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(200) it "resets to 40 base power if nobody uses this move the previous turn", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") splash = @battle.getMove("Splash") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) @battle.performMove(@p1, splash) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(40) it "has the same base power that turn for all users", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") splash = @battle.getMove("Splash") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) echoedVoice.basePower(@battle, @p2, @p1).should.equal(80) it "does not reset even if missing", -> shared.create.call(this) echoedVoice = @battle.getMove("Echoed Voice") @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(80) @sandbox.stub(echoedVoice, 'willMiss', -> true) @battle.performMove(@p1, echoedVoice) @battle.endTurn() echoedVoice.basePower(@battle, @p1, @p2).should.equal(120) describe "Struggle", -> it "deals typless damage", -> shared.create.call(this) struggle = @battle.getMove('Struggle') for type of util.Type util.typeEffectiveness(struggle.type, [type]).should.equal(1) it "deals 25% in recoil to the attacker, rounded down", -> shared.create.call(this) struggle = @battle.getMove('Struggle') hp = @p1.currentHP @p1.currentHP.should.equal @p1.stat('hp') @battle.performMove(@p1, struggle) (hp - @p1.currentHP).should.equal(hp >> 2) describe "Nature Power", -> it "uses Earthquake in Wi-Fi battles", -> shared.create.call(this) naturePower = @battle.getMove('Nature Power') earthquake = @battle.getMove('Earthquake') mock = @sandbox.mock(earthquake).expects('execute').once() .withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, naturePower) mock.verify() testRampageMove = (moveName) -> describe moveName, -> it "lasts 2-3 turns", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p1.has(Attachment.Rampage).should.be.true @battle.endTurn() @battle.performMove(@p1, rampageMove) @battle.endTurn() @p1.has(Attachment.Rampage).should.be.false it "locks the user into that move until execution ends", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) splash = @battle.getMove("Splash") @p1.moves = [ rampageMove, splash ] @p1.resetAllPP() @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.validMoves().should.eql [ rampageMove ] @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.validMoves().should.eql [ rampageMove, splash ] it "blocks switching until execution ends", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.true @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.isSwitchBlocked().should.be.false it "confuses the user after use", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 2) rampageMove = @battle.getMove(moveName) @battle.performMove(@p1, rampageMove) @p2.currentHP = @p2.stat('hp') @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Confusion).should.be.false @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @p1.has(Attachment.Confusion).should.be.true it "stops immediately if the user's move did not hit", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'rampage turns', 3) rampageMove = @battle.getMove(moveName) protect = @battle.getMove("Protect") @battle.performMove(@p1, rampageMove) @battle.endTurn() @battle.beginTurn() @battle.recordMove(@id2, protect) @battle.recordMove(@id1, rampageMove) @battle.continueTurn() @battle.endTurn() @p1.has(Attachment.Rampage).should.be.false testRampageMove("Outrage") testRampageMove("Petal Dance") testRampageMove("Thrash") test2To5MulthitMove = (moveName) -> describe moveName, -> it "deals 2 to 5 hits with a probability distribution of 1/3, 1/3, 1/6, 1/6", -> shared.create.call(this) move = @battle.getMove(moveName) spy = @sandbox.spy(@battle.rng, 'choice') spy = spy.withArgs([2, 2, 3, 3, 4, 5], 'num hits') @battle.performMove(@p1, move) spy.calledOnce.should.be.true it "hits 5 times if the user has Skill Link", -> shared.create.call(this, team1: [Factory('Cloyster', ability: 'Skill Link')]) # try to "trick" the system into giving an invalid result. It should always hit # 5 times regardless of the rng shared.biasRNG.call(this, "choice", 'num hits', 2) shared.biasRNG.call(this, "randInt", 'num hits', 2) move = @battle.getMove(moveName) move.calculateNumberOfHits(@battle, @p1, [ @p2 ]).should.equal(5) it "only hits up until the target Pokemon faints", -> shared.create.call(this, team1: [Factory('Cloyster', ability: 'Skill Link')]) # try to "trick" the system into giving an invalid result. It should always hit # 5 times regardless of the rng shared.biasRNG.call(this, "choice", 'num hits', 3) shared.biasRNG.call(this, "randInt", 'num hits', 3) @p2.currentHP = 1 move = @battle.getMove(moveName) spy = @sandbox.spy(move, 'hit') @battle.performMove(@p1, move) spy.calledOnce.should.be.true test2To5MulthitMove('Arm Thrust') test2To5MulthitMove('Barrage') test2To5MulthitMove('Bone Rush') test2To5MulthitMove('Bullet Seed') test2To5MulthitMove('Comet Punch') test2To5MulthitMove('DoubleSlap') test2To5MulthitMove('Fury Attack') test2To5MulthitMove('Fury Swipes') test2To5MulthitMove('Icicle Spear') test2To5MulthitMove('Pin Missile') test2To5MulthitMove('Rock Blast') test2To5MulthitMove('Spike Cannon') test2To5MulthitMove('Tail Slap') describe "Trick Room", -> it "lasts 5 turns", -> shared.create.call(this) trickRoom = @battle.getMove("Trick Room") @battle.performMove(@p1, trickRoom) for x in [0...5] @battle.has(Attachment.TrickRoom).should.be.true @battle.endTurn() @battle.has(Attachment.TrickRoom).should.be.false it "ends a previous use of Trick Room", -> shared.create.call(this) trickRoom = @battle.getMove("Trick Room") @battle.performMove(@p1, trickRoom) @battle.has(Attachment.TrickRoom).should.be.true @battle.performMove(@p1, trickRoom) @battle.has(Attachment.TrickRoom).should.be.false it "reverses the order that moves are performed in", -> shared.create.call(this, team1: [Factory("Magikarp", evs: {speed: 4})]) trickRoom = @battle.getMove("Trick Room") splash = @battle.getMove("Splash") @battle.performMove(@p1, trickRoom) @battle.recordMove(@id1, splash) @battle.recordMove(@id2, splash) @battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ] describe "Transform", -> shared.shouldDoNoDamage("Transform") shared.shouldFailIfUsedTwice("Transform") it "fails on a substitute", -> shared.create.call(this) substitute = @battle.getMove("Substitute") transform = @battle.getMove("Transform") @battle.performMove(@p2, substitute) mock = @sandbox.mock(transform).expects('fail').once() @battle.performMove(@p1, transform) mock.verify() it "changes the user's type to match the target's", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.types.should.eql @p2.types it "forces a sprite change", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") mock = @sandbox.mock(@p1).expects('changeSprite').once() @battle.performMove(@p1, transform) mock.verify() it "does not change species or forme", -> shared.create.call(this, team2: [Factory("Latias")]) transform = @battle.getMove("Transform") oldSpecies = @p1.species oldForme = @p1.forme @battle.performMove(@p1, transform) @p1.species.should.equal(oldSpecies) @p1.forme.should.equal(oldForme) it "changes the user's stats to match the target's, except HP", -> shared.create.call(this, team2: [Factory("Celebi", evs: {speed: 252})]) transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) for stat of @p2.baseStats if stat == 'hp' @p1.stat(stat).should.not.equal(@p2.stat(stat)) else @p1.stat(stat).should.equal(@p2.stat(stat)) it "copies the target's gender", -> shared.create.call this, team1: [Factory("Magikarp", gender: "F")] team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.gender.should.equal(@p2.gender) it "copies the target's moveset, setting each PP and max PP to 5", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @p2.boost(attack: 3, speed: -2, accuracy: 1) @battle.performMove(@p1, transform) @p1.moves.should.eql @p2.moves for move in @p1.moves @p1.pp(move).should.equal(5) @p1.maxPP(move).should.equal(5) it "copies the target's stat boosts", -> shared.create.call(this, team2: [Factory("Celebi")]) transform = @battle.getMove("Transform") @p2.boost(attack: 3, speed: -2, accuracy: 1) @battle.performMove(@p1, transform) @p1.stages.should.containEql(attack: 3, speed: -2, accuracy: 1) it "copies the target's ability", -> shared.create.call this, team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.hasAbility("Natural Cure").should.be.true it "copies the target's weight", -> shared.create.call this, team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.weight.should.equal(@p2.weight) it "copies the target's gender", -> shared.create.call this, team1: [Factory("Magikarp", gender: "F")] team2: [Factory("Celebi")] transform = @battle.getMove("Transform") @battle.performMove(@p1, transform) @p1.gender.should.equal(@p2.gender) it "restores the original stats after switching out", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure", evs: {speed: 252})] transform = @battle.getMove("Transform") baseStats = _.clone(@p1.baseStats) evs = _.clone(@p1.evs) stats = {} for stat of baseStats stats[stat] = @p1.stat(stat) @battle.performMove(@p1, transform) @p1.baseStats.should.not.eql(baseStats) @p1.evs.should.not.eql(evs) for stat, value of stats @p1.stat(stat).should.not.equal(value) @battle.performSwitch(@p1, 1) @p1.baseStats.should.eql(baseStats) @p1.evs.should.eql(evs) for stat, value of stats @p1.stat(stat).should.equal(value) it "restores the original species and type after switching out", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") species = @p1.species types = _.clone(@p1.types) @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.types.should.eql(types) @p1.species.should.eql(species) it "restores the original ability after switching out", -> # Ditto has a fake ability so we can test abilities being restored. shared.create.call this, team1: [Factory("Ditto", ability: "Sniper"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") ability = @p1.ability @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.ability.should.eql(ability) it "restores original moveset after switch, but Transform PP decreases", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") moves = _.clone(@p1.moves) ppHash = _.clone(@p1.ppHash) maxPPHash = _.clone(@p1.maxPPHash) @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.moves.should.eql(moves) @p1.maxPPHash.should.eql(maxPPHash) # Transform's PP should go down! ppHash[transform.name] -= 1 @p1.ppHash.should.eql(ppHash) it "restores original gender after switch", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") gender = @p1.gender @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.gender.should.eql(gender) it "restores original weight after switch", -> shared.create.call this, team1: [Factory("Ditto"), Factory("Magikarp")] team2: [Factory("Celebi", ability: "Natural Cure")] transform = @battle.getMove("Transform") weight = @p1.weight @battle.performMove(@p1, transform) @battle.performSwitch(@team1.first(), 1) @p1.weight.should.eql(weight) it "fails if the target is transformed", -> shared.create.call(this) transform = @battle.getMove("Transform") @battle.performMove(@p2, transform) mock = @sandbox.mock(transform).expects('fail').once() @battle.performMove(@p1, transform) mock.verify() it "fails if the target is under an illusion" it "fails if the user is under an illusion" it "cannot change formes if it has the ability to do so" describe "Fling", -> it "fails if the pokemon has no item", -> shared.create.call(this) fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "fails if the item is not removeable", -> shared.create.call this, team1: [Factory("Magikarp", item: "Acro Bike")] fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "fails if the user is blocked from using items", -> shared.create.call this, team1: [Factory("Magikarp", item: "Armor Fossil")] fling = @battle.getMove("Fling") @p1.blockItem() mock = @sandbox.mock(fling).expects('fail').once() @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() it "has a base power depending on the item held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Armor Fossil")] fling = @battle.getMove("Fling") fling.beforeTurn(@battle, @p1) @p1.beforeMove(fling, @p1, [@p2]) fling.basePower(@battle, @p1, @p2).should.equal(100) it "inflicts Burn on the target if Flame Orb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Flame Orb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Burn).should.be.true it "inflicts Toxic on the target if Toxic Orb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Toxic Orb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Toxic).should.be.true it "flinches the target if King's Rock is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "King's Rock")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true it "flinches the target if Razor Fang is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Razor Fang")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Flinch).should.be.true it "paralyzes the target if Light Ball is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Light Ball")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Paralyze).should.be.true it "removes negative status effects if Mental Herb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Mental Herb")] fling = @battle.getMove("Fling") @p2.attach(Attachment.Torment) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Attachment.Torment).should.be.false it "removes negative stat boosts if White Herb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "White Herb")] fling = @battle.getMove("Fling") @p2.boost(attack: 1, accuracy: -2) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.stages.should.containEql(attack: 1, accuracy: 0) it "inflicts Poison on the target if Poison Barb is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Barb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Poison).should.be.true it "causes target to eat the flung berry if a berry is held", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.stages.speed.should.equal(1) it "does not activate an item effect when hitting a substitute", -> shared.create.call this, team1: [Factory("Magikarp", item: "Toxic Orb")] fling = @battle.getMove("Fling") @p2.attach(Attachment.Substitute, hp: 1) @battle.recordMove(@id1, fling) @battle.continueTurn() @p2.has(Status.Toxic).should.be.false it "loses the user's item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Barb")] fling = @battle.getMove("Fling") @battle.recordMove(@id1, fling) @battle.continueTurn() @p1.hasItem().should.be.false it "loses the item even if execution is canceled by protect", -> shared.create.call this, team1: [Factory("Magikarp", item: "Poison Herb")] protect = @battle.getMove("Protect") fling = @battle.getMove("Fling") mock = @sandbox.mock(fling).expects('hit').never() @battle.recordMove(@id2, protect) @battle.recordMove(@id1, fling) @battle.continueTurn() mock.verify() @p1.hasItem().should.be.false describe "Bug Bite", -> it "eats the target's berry and gets its effects", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry")] bugBite = @battle.getMove("Bug Bite") @battle.performMove(@p1, bugBite) @p2.hasItem().should.be.false @p1.stages.should.containEql(speed: 1) it "does eat the target's berry if the target fainted", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry")] bugBite = @battle.getMove("Bug Bite") @p2.currentHP = 1 @battle.performMove(@p1, bugBite) @p2.isFainted().should.be.true @p1.stages.should.containEql(speed: 1) it "does not eat the target's berry if the user fainted", -> shared.create.call this, team2: [Factory("Magikarp", item: "Salac Berry", ability: "Iron Barbs")] bugBite = @battle.getMove("Bug Bite") @p1.currentHP = 1 @battle.performMove(@p1, bugBite) @p1.isFainted().should.be.true @p2.hasItem().should.be.true describe "Beat Up", -> it "deals 1 less hit for each unhealthy member in the user's party", -> shared.create.call this, team1: (Factory("Magikarp") for i in [0...6]) @team1.at(5).attach(Status.Paralyze) @team1.at(1).faint() beatUp = @battle.getMove("Beat Up") mock = @sandbox.mock(beatUp).expects('hit').exactly(4) @battle.performMove(@p1, beatUp) mock.verify() it "has 5 + X/10 base power for X in team, where X is base attack", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("PI:NAME:<NAME>END_PI"), Factory("Celebi"), Factory("Totodile"), Factory("RayPI:NAME:<NAME>END_PI"), Factory("Seedot") ] beatUp = @battle.getMove("Beat Up") spy = @sandbox.spy(beatUp, "basePower") @battle.performMove(@p1, beatUp) for pokemon in @team1.pokemon basePower = 5 + Math.floor(pokemon.baseStats.attack / 10) spy.returned(basePower).should.be.true it "works for teams smaller than 6", -> shared.create.call this, team1: (Factory("Magikarp") for i in [0...4]) beatUp = @battle.getMove("Beat Up") mock = @sandbox.mock(beatUp).expects('hit').exactly(4) @battle.performMove(@p1, beatUp) mock.verify() it "doesn't crash if all pokemon are statused or fainted", -> shared.create.call this, team1: (Factory("PI:NAME:<NAME>END_PIikPI:NAME:<NAME>END_PI") for i in [0...2]) @team1.at(1).faint() @team1.at(0).attach(Status.Burn) beatUp = @battle.getMove("Beat Up") (=> @battle.performMove(@p1, beatUp) ).should.not.throw() it "doesn't crash when used by a pokemon with technician", -> shared.create.call(this, team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Technician")]) beatUp = @battle.getMove("Beat Up") (=> @battle.performMove(@p1, beatUp) ).should.not.throw() describe "Psycho Shift", -> it "fails if the user doesn't have a status", -> shared.create.call(this) psychoShift = @battle.getMove("Psycho Shift") mock = @sandbox.mock(psychoShift).expects('fail').once() @battle.performMove(@p1, psychoShift) mock.verify() it "fails if the target already has a status", -> shared.create.call(this) @p1.attach(Status.Toxic) @p2.attach(Status.Paralyze) psychoShift = @battle.getMove("Psycho Shift") mock = @sandbox.mock(psychoShift).expects('fail').once() @battle.performMove(@p1, psychoShift) mock.verify() it "cures the user of its status", -> shared.create.call(this) @p1.attach(Status.Poison) psychoShift = @battle.getMove("Psycho Shift") @battle.performMove(@p1, psychoShift) @p1.hasStatus().should.be.false it "gives the user's former status to the target", -> shared.create.call(this) @p1.attach(Status.Burn) psychoShift = @battle.getMove("Psycho Shift") @battle.performMove(@p1, psychoShift) @p2.has(Status.Burn).should.be.true describe "Gravity", -> shared.shouldDoNoDamage("Gravity") shared.shouldFailIfUsedTwice("Gravity") it "raises accuracy of all attacks by 5/3", -> shared.create.call(this) gravity = @battle.getMove("Gravity") focusBlast = @battle.getMove("Focus Blast") @battle.performMove(@p1, gravity) accuracy = focusBlast.chanceToHit(@battle, @p1, @p2) accuracy.should.equal Math.floor(focusBlast.accuracy * 5 / 3) it "lasts 5 turns", -> shared.create.call(this) gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) for i in [0...5] @battle.has(Attachment.Gravity).should.be.true @battle.endTurn() @battle.has(Attachment.Gravity).should.be.false it "makes Flying Pokemon no longer immune to Ground", -> shared.create.call(this) @p2.types = [ "Flying" ] @p2.isImmune("Ground").should.be.true gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) @p2.isImmune("Ground").should.be.false it "makes Levitating Pokemon no longer immune to Ground", -> shared.create.call(this, team2: [Factory("Magikarp", ability: "Levitate")]) @p2.isImmune("Ground").should.be.true gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) @p2.isImmune("Ground").should.be.false it "deals damage to Flying Pokemon", -> shared.create.call(this) @p2.types = [ "Flying" ] gravity = @battle.getMove("Gravity") earthquake = @battle.getMove("Earthquake") earthquake.typeEffectiveness(@battle, @p1, @p2).should.equal(0) @battle.performMove(@p1, gravity) earthquake.typeEffectiveness(@battle, @p1, @p2).should.equal(1) # TODO: Sky Drop for moveName in [ "Bounce", "Fly" ] do (moveName) -> it "grounds pokemon using #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @battle.recordMove(@id2, move) @battle.continueTurn() @p2.has(Attachment.Charging).should.be.true @battle.recordMove(@id1, gravity) @battle.continueTurn() @p2.has(Attachment.Charging).should.be.false it "removes Telekinesis", -> shared.create.call(this) telekinesis = @battle.getMove("Telekinesis") gravity = @battle.getMove("Gravity") @battle.performMove(@p1, telekinesis) @p2.has(Attachment.Telekinesis).should.be.true @battle.performMove(@p1, gravity) @p2.has(Attachment.Telekinesis).should.be.false it "removes Magnet Rise", -> shared.create.call(this) magnetRise = @battle.getMove("Magnet Rise") gravity = @battle.getMove("Gravity") @battle.performMove(@p2, magnetRise) @p2.has(Attachment.MagnetRise).should.be.true @battle.performMove(@p1, gravity) @p2.has(Attachment.MagnetRise).should.be.false for moveName in [ "Jump Kick", "Hi Jump Kick", "Bounce", "Fly", "Sky Drop", "Splash", "Telekinesis" ] do (moveName) -> it "disables #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @p1.moves = [ move ] @p2.moves = [ move ] @battle.performMove(@p1, gravity) @battle.beginTurn() @p1.validMoves().should.not.containEql(move) @p2.validMoves().should.not.containEql(move) it "prevents the execution of #{moveName}", -> shared.create.call(this) move = @battle.getMove(moveName) gravity = @battle.getMove("Gravity") @battle.performMove(@p1, gravity) mock = @sandbox.mock(move).expects('execute').never() @battle.performMove(@p2, move) mock.verify() testDelayedAttackMove = (moveName, type) -> describe moveName, -> shared.shouldFailIfUsedTwice(moveName) it "waits three turns before attacking", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) for x in [0...3] @p2.currentHP.should.equal @p2.stat('hp') @battle.endTurn() @p2.currentHP.should.be.lessThan @p2.stat('hp') it "does not initialize and error if the target has fainted", -> shared.create.call(this) move = @battle.getMove(moveName) @p2.faint() (=> @battle.performMove(@p1, move)).should.not.throw() it "does not hit if the target has fainted", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) for x in [0...2] @battle.endTurn() @p2.faint() mock = @sandbox.mock(move).expects('hit').never() @battle.endTurn() mock.verify() it "is considered a direct attack", -> shared.create.call(this) move = @battle.getMove(moveName) @battle.performMove(@p1, move) @p2.attach(Attachment.Substitute, hp: 1) @battle.endTurn() @battle.endTurn() @p2.has(Attachment.Substitute).should.be.true @battle.endTurn() @p2.has(Attachment.Substitute).should.be.false it "can target multiple positions" testDelayedAttackMove("Future Sight") testDelayedAttackMove("Doom Desire") describe "Baton Pass", -> it "fails if there is no benched pokemon to BP to", -> shared.create.call(this, team1: [Factory('Magikarp')]) batonPass = @battle.getMove("Baton Pass") mock = @sandbox.mock(batonPass).expects('fail').once() @battle.performMove(@p1, batonPass) mock.verify() it "switches to another pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @battle.performMove(@p1, batonPass) @battle.requests.should.have.property @id1 it "passes certain attachments to the next pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @p1.attach(Attachment.Ingrain) @p1.attach(Attachment.Torment) @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().has(Attachment.Torment).should.be.false @team1.first().has(Attachment.Ingrain).should.be.true it "continues Perish Song's counter", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") perishSong = @battle.getMove("Perish Song") @battle.performMove(@p1, perishSong) for i in [0...3] @battle.endTurn() @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().isFainted().should.be.false @battle.endTurn() @team1.first().isFainted().should.be.true it "passes status boosts to the next pokemon", -> shared.create.call this, team1: [ Factory("Magikarp"), Factory("Celebi") ] batonPass = @battle.getMove("Baton Pass") @p1.boost(attack: 1, evasion: -3) @battle.performMove(@p1, batonPass) @battle.performSwitch(@team1.first(), 1) @team1.first().stages.should.containEql(attack: 1, evasion: -3) describe "Thunder Wave", -> it "is affected by immunities", -> shared.create.call(this) thunderWave = @battle.getMove("Thunder Wave") @p2.types = [ 'Ground' ] @battle.performMove(@p1, thunderWave) @p2.has(Status.Paralyze).should.be.false describe "Thunder", -> it "has 50% accuracy in Sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(50) it "has perfect accuracy in Rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) thunder = @battle.getMove("Thunder") thunder.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Hurricane", -> it "has 50% accuracy in Sun", -> shared.create.call(this) @battle.setWeather(Weather.SUN) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(50) it "has perfect accuracy in Rain", -> shared.create.call(this) @battle.setWeather(Weather.RAIN) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) hurricane = @battle.getMove("Hurricane") hurricane.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Blizzard", -> it "has perfect accuracy in Hail", -> shared.create.call(this) @battle.setWeather(Weather.HAIL) blizzard = @battle.getMove("Blizzard") blizzard.chanceToHit(@battle, @p1, @p2).should.equal(0) it "has normal accuracy otherwise", -> shared.create.call(this) blizzard = @battle.getMove("Blizzard") blizzard.chanceToHit(@battle, @p1, @p2).should.equal(70) describe "Sleep Talk", -> it "fails if the pokemon is awake", -> shared.create.call(this) sleepTalk = @battle.getMove("Sleep Talk") mock = @sandbox.mock(sleepTalk).expects('fail').once() @battle.performMove(@p1, sleepTalk) mock.verify() it "performs a random move when the pokemon is asleep", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ tackle, sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) spy = @sandbox.spy(@battle, 'executeMove') @battle.performMove(@p1, sleepTalk) spy.calledWith(tackle).should.be.true it "does not choose sleep talk or other moves", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") assist = @battle.getMove("Assist") @p1.moves = [ sleepTalk, assist, tackle ] @p1.resetAllPP() @p1.attach(Status.Sleep) spy = @sandbox.spy(@battle, 'executeMove') @battle.performMove(@p1, sleepTalk) spy.calledWith(tackle).should.be.true it "fails if there are no viable moves", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) mock = @sandbox.mock(sleepTalk).expects('fail').once() @battle.performMove(@p1, sleepTalk) mock.verify() it "changes the move's target properly", -> shared.create.call(this) shared.biasRNG.call(this, 'randInt', 'sleep talk', 0) tackle = @battle.getMove("Tackle") sleepTalk = @battle.getMove("Sleep Talk") @p1.moves = [ tackle, sleepTalk ] @p1.resetAllPP() @p1.attach(Status.Sleep) mock = @sandbox.mock(tackle) mock.expects('execute').once().withArgs(@battle, @p1, [ @p2 ]) @battle.performMove(@p1, sleepTalk) mock.verify() describe "Rest", -> it "fails if the pokemon is at full HP", -> shared.create.call(this) rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(@p1.stat('hp')) @battle.performMove(@p1, rest) mock.verify() it "restores the pokemon to full HP otherwise", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @battle.performMove(@p1, rest) @p1.currentHP.should.equal @p1.stat('hp') it "sleeps the pokemon", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @p1.has(Status.Sleep).should.be.false @battle.performMove(@p1, rest) @p1.has(Status.Sleep).should.be.true it "fails if the pokemon is already asleep", -> shared.create.call(this) rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(1) @p1.attach(Status.Sleep) # execute instead of perform to avoid beforeMove callbacks. @battle.executeMove(rest, @p1, [ @p1 ]) mock.verify() it "cures the pokemon of adverse status effects", -> shared.create.call(this) rest = @battle.getMove("Rest") @p1.setHP(1) @p1.attach(Status.Burn) @p1.has(Status.Burn).should.be.true @battle.performMove(@p1, rest) @p1.has(Status.Sleep).should.be.true @p1.has(Status.Burn).should.be.false it "always forces sleep turns to be 2", -> shared.create.call(this) shared.biasRNG.call(this, "randInt", "sleep turns", 3) rest = @battle.getMove("Rest") @p1.setHP(1) @battle.performMove(@p1, rest) attachment = @p1.get(Status.Sleep) should.exist(attachment) attachment.should.have.property("turns") attachment.turns.should.equal(2) it "fails if the Pokemon cannot be slept", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Vital Spirit")] rest = @battle.getMove("Rest") mock = @sandbox.mock(rest).expects('fail').once() @p1.setHP(1) @battle.performMove(@p1, rest) mock.verify() describe "Defog", -> it "lowers target's evasion by 1", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, defog) @p2.stages.should.containEql(evasion: -1) it "removes Reflect on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Reflect")) @p2.team.has(Attachment.Reflect).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Reflect).should.be.false it "removes Light Screen on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Light Screen")) @p2.team.has(Attachment.LightScreen).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.LightScreen).should.be.false it "removes Spikes on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Spikes")) @p2.team.has(Attachment.Spikes).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Spikes).should.be.false it "removes Stealth Rock on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Stealth Rock")) @p2.team.has(Attachment.StealthRock).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.StealthRock).should.be.false it "removes Toxic Spikes on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p1, @battle.getMove("Toxic Spikes")) @p2.team.has(Attachment.ToxicSpikes).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.ToxicSpikes).should.be.false it "removes Safeguard on target's side", -> shared.create.call(this, gen: 'bw') defog = @battle.getMove("Defog") @battle.performMove(@p2, @battle.getMove("Safeguard")) @p2.team.has(Attachment.Safeguard).should.be.true @battle.performMove(@p1, defog) @p2.team.has(Attachment.Safeguard).should.be.false it "removes Mist on target's side" describe "Refresh", -> it "fails if the Pokemon has no status", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") mock = @sandbox.mock(refresh).expects('fail').once() @battle.performMove(@p1, refresh) mock.verify() it "restores a Pokemon's status", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") @p1.attach(Status.Burn) @p1.has(Status.Burn).should.be.true @battle.performMove(@p1, refresh) @p1.has(Status.Burn).should.be.false it "sends a message about status being restored", -> shared.create.call(this, gen: 'bw') refresh = @battle.getMove("Refresh") @p1.attach(Status.Burn) spy = @sandbox.spy(@battle, 'message') @battle.performMove(@p1, refresh) spy.args.join(',').should.containEql("#{@p1.name} healed its burn!") describe "Growth", -> it "boosts the pokemon's stats", -> shared.create.call(this, gen: 'bw') @battle.setWeather(Weather.SUN) @battle.performMove(@p1, @battle.getMove('Growth')) @p1.stages.should.containEql attack: 2, specialAttack: 2 describe "Reflect Type", -> it "copies the target's types", -> shared.create.call(this, team1: [Factory("Magikarp")], team2: [Factory("Charmander")]) @battle.performMove(@p1, @battle.getMove('Reflect Type')) @p1.types.should.containEql "Fire" it "fails if the user has multitype", -> shared.create.call(this, team1: [Factory("Arceus", ability: "Multitype")], team2: [Factory("Toxicroak")]) @battle.performMove(@p1, @battle.getMove('Reflect Type')) @p1.types.should.containEql "Normal" describe "Retaliate", -> it "doubles in power if a pokemon on the user's side fainted last turn", -> shared.create.call this, team1: [Factory("Magikarp"), Factory("Slaking")] @p2.currentHP = 1 @battle.beginTurn() @battle.recordMove(@id1, @battle.getMove("Aqua Jet")) @battle.recordMove(@id2, @battle.getMove("Splash")) @battle.continueTurn() @battle.endTurn() @battle.beginTurn() retaliate = @battle.getMove("Retaliate") spy = @sandbox.spy(retaliate, 'basePower') @battle.performMove(@p2, retaliate) spy.returned(140).should.be.true it "deals normal damage otherwise", -> shared.create.call(this) retaliate = @battle.getMove("Retaliate") spy = @sandbox.spy(retaliate, 'basePower') @battle.performMove(@p1, retaliate) spy.returned(70).should.be.true describe "Role Play", -> it "copies the target's ability", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Magikarp", ability: "Levitate")] @battle.performMove(@p1, @battle.getMove('Role Play')) @p1.hasAbility("Levitate").should.be.true it "does not copy certain abilities", -> shared.create.call this, team1: [Factory("Magikarp"), ability: "Swift Swim"] team2: [Factory("Arceus", ability: "Multitype")] @battle.performMove(@p1, @battle.getMove('Role Play')) @p1.hasAbility("Multitype").should.be.false describe "Relic Song", -> it "transforms Meloetta", -> shared.create.call this, team1: [Factory("Meloetta")] team2: [Factory("Arceus")] @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("pirouette") @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("default") it "changes Meloetta to default forme after switching out", -> shared.create.call this, team1: [Factory("Meloetta"), Factory("Magikarp")] team2: [Factory("Arceus")] @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("pirouette") @battle.performSwitch(@p1, 1) @battle.performSwitch(@team1.first(), 1) @p1.forme.should.equal("default") it "does not transform Pokemon that are not Meloetta", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Magikarp")] @p1.forme.should.equal("default") @battle.performMove(@p1, @battle.getMove('Relic Song')) @p1.forme.should.equal("default") describe "Safeguard", -> it "protects the user's team from status", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Safeguard")) @battle.performMove(@p2, @battle.getMove("Thunder Wave")) @p1.has(Status.Paralyze).should.be.false it "protects the user's team from confusion", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Safeguard")) @battle.performMove(@p2, @battle.getMove("Confuse Ray")) @p1.has(Attachment.Confusion).should.be.false it "doesn't protect against status inflicted by the user", -> shared.create.call(this) @p1.team.attach(Attachment.Safeguard) @p1.setHP(1) @battle.performMove(@p1, @battle.getMove("Rest")) @p1.has(Status.Sleep).should.be.true it "protects against yawn being inflicted", -> shared.create.call(this) @p1.team.attach(Attachment.Safeguard) @battle.performMove(@p2, @battle.getMove("Yawn")) @p1.has(Attachment.Yawn).should.be.false it "doesn't prevent yawn's effect", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove('Yawn')) @battle.endTurn() @p2.has(Status.Sleep).should.be.false @p2.team.attach(Attachment.Safeguard) @battle.endTurn() @p2.has(Status.Sleep).should.be.true describe "Soak", -> it "changes the target's type to Water", -> shared.create.call this, team1: [Factory("PI:NAME:<NAME>END_PI")] team2: [Factory("Smeargle")] @p2.types.should.not.eql ['Water'] @battle.performMove(@p1, @battle.getMove('Soak')) @p2.types.should.eql ['Water'] it "does not affect pure Water type Pokemon", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("MagPI:NAME:<NAME>END_PI")] @p2.types.should.eql ['Water'] soak = @battle.getMove("Soak") mock = @sandbox.mock(soak).expects('fail').once() @battle.performMove(@p1, soak) mock.verify() it "does not affect Arceus", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus")] soak = @battle.getMove("Soak") mock = @sandbox.mock(soak).expects('fail').once() @battle.performMove(@p1, soak) mock.verify() describe 'Electro Ball', -> it 'has variable base power based on speed of user and target', -> shared.create.call this, team1: [Factory('Electrode', evs: {speed: 252}, nature: "Timid")] team2: [Factory('Smeargle')] move = @battle.getMove('Electro Ball') move.basePower(@battle, @p1, @p2).should.equal 80 describe "Snore", -> it "fails if the pokemon is awake", -> shared.create.call(this) snore = @battle.getMove("Snore") mock = @sandbox.mock(snore).expects('fail').once() @battle.performMove(@p1, snore) mock.verify() it "attacks the target when the user is asleep", -> shared.create.call this, snore = @battle.getMove("Snore") @p1.attach(Status.Sleep) mock = @sandbox.mock(snore).expects('hit').once() @battle.performMove(@p1, snore) mock.verify() describe "Worry Seed", -> it "changes the target's ability to Insomnia", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Swift Swim")] @battle.performMove(@p1, @battle.getMove('Worry Seed')) @p2.hasAbility("Insomnia").should.be.true it "does not change some abilities", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus", ability: "Multitype")] worrySeed = @battle.getMove("Worry Seed") mock = @sandbox.mock(worrySeed).expects('fail').once() @battle.performMove(@p1, worrySeed) mock.verify() describe "Simple Beam", -> it "changes the target's ability to Simple", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("PI:NAME:<NAME>END_PI", ability: "Swift Swim")] @battle.performMove(@p1, @battle.getMove('Simple Beam')) @p2.hasAbility("Simple").should.be.true it "does not change some abilities", -> shared.create.call this, team1: [Factory("Smeargle")] team2: [Factory("Arceus", ability: "Multitype")] simpleBeam = @battle.getMove("Simple Beam") mock = @sandbox.mock(simpleBeam).expects('fail').once() @battle.performMove(@p1, simpleBeam) mock.verify() describe "Entrainment", -> it "copies the user's ability to the target", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Smeargle", ability: "Own Tempo")] @battle.performMove(@p1, @battle.getMove('Entrainment')) @p2.hasAbility("Swift Swim").should.be.true it "does not copy some abilities", -> shared.create.call this, team1: [Factory("Arceus", ability: "Multitype")] team2: [Factory("Magikarp", ability: "Swift Swim")] entrainment = @battle.getMove("Entrainment") mock = @sandbox.mock(entrainment).expects('fail').once() @battle.performMove(@p1, entrainment) mock.verify() describe "Natural Gift", -> it "changes power and type depending on the berry held by the user", -> shared.create.call this, team1: [Factory("Smeargle", item: 'Liechi Berry')] team2: [Factory("Magikarp")] move = @battle.getMove('Natural Gift') basePower = move.basePower(@battle, @p1, @p2) basePower.should.equal(80) move.typeEffectiveness(@battle, @p1, @p2).should.equal(2) it "only works with certain items", -> shared.create.call this, team1: [Factory("Smeargle", item: 'Leftovers')] naturalGift = @battle.getMove('Natural Gift') mock = @sandbox.mock(naturalGift).expects('fail').once() @battle.performMove(@p1, naturalGift) mock.verify() it "should remove the item even if missing" describe "False Swipe", -> it "leaves the target with at least 1 HP", -> shared.create.call(this) @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove("False Swipe")) @p2.currentHP.should.equal 1 it "does normal damage if the target has a substitute", -> shared.create.call(this) @p2.currentHP = 1 @p2.attach(Attachment.Substitute) falseSwipe = @battle.getMove("False Swipe") spy = @sandbox.spy(falseSwipe, 'calculateDamage') @battle.performMove(@p1, falseSwipe) spy.returned(0).should.be.false describe "Gastro Acid", -> it "suppresses the target's ability", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Gastro Acid")) @p2.has(Attachment.AbilitySuppress).should.be.true @p2.isAbilityBlocked().should.be.true it "continues turn by turn", -> shared.create.call(this) @battle.performMove(@p1, @battle.getMove("Gastro Acid")) @battle.endTurn() @battle.beginTurn() @p2.has(Attachment.AbilitySuppress).should.be.true @p2.isAbilityBlocked().should.be.true it "fails against some abilities", -> shared.create.call(this, team2: [Factory("Arceus", ability: "Multitype")]) gastroAcid = @battle.getMove("Gastro Acid") mock = @sandbox.mock(gastroAcid).expects('fail').once() @battle.performMove(@p1, gastroAcid) mock.verify() describe "Helping Hand", -> it "fails if there is no target", -> shared.create.call(this) helpingHand = @battle.getMove("Helping Hand") mock = @sandbox.mock(helpingHand).expects('fail').once() @battle.performMove(@p1, helpingHand) mock.verify() describe "Skill Swap", -> it "swaps the user's ability with the target's", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Swift Swim")] team2: [Factory("Smeargle", ability: "Own Tempo")] @battle.performMove(@p1, @battle.getMove('Skill Swap')) @p1.hasAbility("Own Tempo").should.be.true @p2.hasAbility("Swift Swim").should.be.true it "cannot swap some abilities", -> shared.create.call this, team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Swift Swim")] team2: [Factory("PI:NAME:<NAME>END_PI", ability: "Wonder Guard")] skillSwap = @battle.getMove("Skill Swap") mock = @sandbox.mock(skillSwap).expects('fail').once() @battle.performMove(@p1, skillSwap) mock.verify() it "cannot swap the abilities if they are the same", -> shared.create.call this, team1: [Factory("MagPI:NAME:<NAME>END_PI", ability: "Swift Swim")] team2: [Factory("Magikarp", ability: "Swift Swim")] skillSwap = @battle.getMove("Skill Swap") mock = @sandbox.mock(skillSwap).expects('fail').once() @battle.performMove(@p1, skillSwap) mock.verify() it "activates abilities after swapping", -> shared.create.call this, team1: [Factory("PI:NAME:<NAME>END_PI", ability: "Swift Swim")] team2: [Factory("PI:NAME:<NAME>END_PI", ability: "Intimidate")] @battle.performMove(@p1, @battle.getMove('Skill Swap')) @p1.hasAbility("Intimidate").should.be.true @p2.hasAbility("Swift Swim").should.be.true @p2.stages.should.containEql(attack: -1) describe "Heal Block", -> it "lasts 5 turns", -> shared.create.call(this) healBlock = @battle.getMove("Heal Block") @battle.performMove(@p1, healBlock) for x in [0...5] @p2.has(Attachment.HealBlock).should.be.true @battle.endTurn() @p2.has(Attachment.HealBlock).should.be.false it 'prevents the target from executing a healing move', -> shared.create.call(this, team1: [ Factory('Magikarp', evs: {speed: 4}) ]) move = @battle.getMove('Recover') healBlock = @battle.getMove('Heal Block') mock = @sandbox.mock(move) mock.expects('execute').never() @battle.performMove(@p1, healBlock) @battle.performMove(@p2, move) mock.verify() it 'prevents the target from selecting a healing move', -> shared.create.call this, team2: [Factory("Magikarp", moves: [ "Splash", "Recover" ])] @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.beginTurn() requestedMoves = @battle.requestFor(@p2).moves requestedMoves.should.not.containEql 'Recover' it "prevents Abilities that heal from healing", -> shared.create.call this, team2: [Factory("Magikarp", ability: "Water Absorb")] @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @battle.performMove(@p1, @battle.getMove('Water Gun')) @p2.currentHP.should.equal 1 it "does not prevent Regenerator from healing", -> shared.create.call this, team1: [Factory("Magikarp", ability: "Regenerator")] @p1.currentHP = 1 @battle.performMove(@p2, @battle.getMove('Heal Block')) @p1.switchOut(@battle) hp = Math.floor(@p1.stat('hp') / 3) @p1.currentHP.should.equal(1 + hp) it "prevents items that heal from healing", -> shared.create.call this, team2: [Factory("Magikarp", item: "Leftovers")] @p2.currentHP = 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @p2.currentHP.should.equal 1 it "prevents Berries that heal from attempting to activate", -> shared.create.call this, team2: [Factory("Magikarp", item: "Sitrus Berry")] item = @p2.item hp = @p2.currentHP @p2.currentHP >>= 1 @battle.performMove(@p1, @battle.getMove('Heal Block')) @battle.endTurn() @battle.performMove(@p1, @battle.getMove('Tackle')) @p2.currentHP.should.be.lessThan hp >> 1 @p2.item.should.equal item describe "Recycle", -> it "restores the user's last used item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] @p1.useItem() @battle.performMove(@p1, @battle.getMove("Recycle")) @p1.hasItem("Salac Berry").should.be.true it "fails if the user has an item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Salac Berry")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p1, recycle) @p1.hasItem("Salac Berry").should.be.true mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "fails if the user has no last used item", -> shared.create.call this, team1: [Factory("Magikarp", item: "Air Balloon")] recycle = @battle.getMove("Recycle") @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.hasItem("Air Balloon").should.be.false mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "cannot restore an item that was forcefully removed", -> shared.create.call this, team1: [Factory("MagikPI:NAME:<NAME>END_PI", item: "PI:NAME:<NAME>END_PIerry")] recycle = @battle.getMove("Recycle") @battle.performMove(@p2, @battle.getMove("Covet")) @p1.hasItem("PI:NAME:<NAME>END_PI Berry").should.be.false @p2.hasItem("PI:NAME:<NAME>END_PI Berry").should.be.true mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify() it "can restore the last used item if the current item is forcefully removed", -> shared.create.call this, team1: [Factory("Magikarp", item: "PI:NAME:<NAME>END_PI")] team2: [Factory("Magikarp", item: "PI:NAME:<NAME>END_PI")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p2, @battle.getMove("Trick")) @p1.hasItem("PI:NAME:<NAME>END_PI").should.be.true @battle.performMove(@p2, @battle.getMove("Knock Off")) @battle.performMove(@p1, recycle) @p1.hasItem("PI:NAME:<NAME>END_PI Berry").should.be.true it "cannot restore the last used item if it was restored and forcefully removed", -> shared.create.call this, team1: [Factory("Magikarp", item: "PI:NAME:<NAME>END_PI")] recycle = @battle.getMove("Recycle") @p1.useItem() @battle.performMove(@p1, recycle) @p1.hasItem("PI:NAME:<NAME>END_PI").should.be.true @battle.performMove(@p2, @battle.getMove("Knock Off")) mock = @sandbox.mock(recycle).expects('fail').once() @battle.performMove(@p1, recycle) mock.verify()
[ { "context": "####################################\n\nVaultKey = \"hubot-deploy-github-secret\"\n\nclass ApiTokenVerifier\n constructor: (token) -", "end": 341, "score": 0.9991041421890259, "start": 315, "tag": "KEY", "value": "hubot-deploy-github-secret" }, { "context": "ets = process.env.HUBOT_DEPLOY_GITHUB_SUBNETS || \"192.30.252.0/22\"\n @subnets = (new Address4(subnet.trim()) f", "end": 960, "score": 0.9996963143348694, "start": 948, "tag": "IP_ADDRESS", "value": "192.30.252.0" } ]
src/models/verifiers.coffee
alvinvogelzang/hubot-deploy
310
Path = require "path" Octonode = require "octonode" Address4 = require("ip-address").Address4 GitHubApi = require(Path.join(__dirname, "..", "github", "api")).Api ScopedClient = require "scoped-http-client" ########################################################################### VaultKey = "hubot-deploy-github-secret" class ApiTokenVerifier constructor: (token) -> @token = token?.trim() @config = new GitHubApi(@token, null) hostname = @config.hostname path = @config.path() if path isnt "/" hostname += path @api = Octonode.client(@config.token, {hostname: hostname}) valid: (cb) -> @api.get "/user", (err, status, data, headers) -> scopes = headers?['x-oauth-scopes'] if scopes?.indexOf('repo') >= 0 cb(true) else cb(false) class GitHubWebHookIpVerifier constructor: () -> gitHubSubnets = process.env.HUBOT_DEPLOY_GITHUB_SUBNETS || "192.30.252.0/22" @subnets = (new Address4(subnet.trim()) for subnet in gitHubSubnets.split(',')) ipIsValid: (ipAddress) -> address = new Address4("#{ipAddress}/24") for subnet in @subnets return true if address.isInSubnet(subnet) false class GitHubTokenVerifier constructor: (token) -> @token = token?.trim() valid: (cb) -> return cb(false) unless token? ScopedClient.create("https://api.github.com"). header("User-Agent", "hubot-deploy/0.13.1"). header("Authorization", "token #{@token}"). path("/user"). get() (err, res, body) -> scopes = res.headers?['x-oauth-scopes'] if err cb(false) else if res.statusCode isnt 200 cb(false) else if scopes?.indexOf("repo") < 0 cb(false) else user = JSON.parse(body) cb(user) class HerokuTokenVerifier constructor: (token) -> @token = token?.trim() valid: (cb) -> return cb(false) unless token? ScopedClient.create("https://api.heroku.com"). header("Accept", "application/vnd.heroku+json; version=3"). header("Authorization", "Bearer #{@token}"). path("/account"). get() (err, res, body) -> if err cb(false) else if res.statusCode isnt 200 cb(false) else user = JSON.parse(body) cb(user) exports.VaultKey = VaultKey exports.ApiTokenVerifier = ApiTokenVerifier exports.GitHubTokenVerifier = GitHubTokenVerifier exports.HerokuTokenVerifier = HerokuTokenVerifier exports.GitHubWebHookIpVerifier = GitHubWebHookIpVerifier
182515
Path = require "path" Octonode = require "octonode" Address4 = require("ip-address").Address4 GitHubApi = require(Path.join(__dirname, "..", "github", "api")).Api ScopedClient = require "scoped-http-client" ########################################################################### VaultKey = "<KEY>" class ApiTokenVerifier constructor: (token) -> @token = token?.trim() @config = new GitHubApi(@token, null) hostname = @config.hostname path = @config.path() if path isnt "/" hostname += path @api = Octonode.client(@config.token, {hostname: hostname}) valid: (cb) -> @api.get "/user", (err, status, data, headers) -> scopes = headers?['x-oauth-scopes'] if scopes?.indexOf('repo') >= 0 cb(true) else cb(false) class GitHubWebHookIpVerifier constructor: () -> gitHubSubnets = process.env.HUBOT_DEPLOY_GITHUB_SUBNETS || "172.16.31.10/22" @subnets = (new Address4(subnet.trim()) for subnet in gitHubSubnets.split(',')) ipIsValid: (ipAddress) -> address = new Address4("#{ipAddress}/24") for subnet in @subnets return true if address.isInSubnet(subnet) false class GitHubTokenVerifier constructor: (token) -> @token = token?.trim() valid: (cb) -> return cb(false) unless token? ScopedClient.create("https://api.github.com"). header("User-Agent", "hubot-deploy/0.13.1"). header("Authorization", "token #{@token}"). path("/user"). get() (err, res, body) -> scopes = res.headers?['x-oauth-scopes'] if err cb(false) else if res.statusCode isnt 200 cb(false) else if scopes?.indexOf("repo") < 0 cb(false) else user = JSON.parse(body) cb(user) class HerokuTokenVerifier constructor: (token) -> @token = token?.trim() valid: (cb) -> return cb(false) unless token? ScopedClient.create("https://api.heroku.com"). header("Accept", "application/vnd.heroku+json; version=3"). header("Authorization", "Bearer #{@token}"). path("/account"). get() (err, res, body) -> if err cb(false) else if res.statusCode isnt 200 cb(false) else user = JSON.parse(body) cb(user) exports.VaultKey = VaultKey exports.ApiTokenVerifier = ApiTokenVerifier exports.GitHubTokenVerifier = GitHubTokenVerifier exports.HerokuTokenVerifier = HerokuTokenVerifier exports.GitHubWebHookIpVerifier = GitHubWebHookIpVerifier
true
Path = require "path" Octonode = require "octonode" Address4 = require("ip-address").Address4 GitHubApi = require(Path.join(__dirname, "..", "github", "api")).Api ScopedClient = require "scoped-http-client" ########################################################################### VaultKey = "PI:KEY:<KEY>END_PI" class ApiTokenVerifier constructor: (token) -> @token = token?.trim() @config = new GitHubApi(@token, null) hostname = @config.hostname path = @config.path() if path isnt "/" hostname += path @api = Octonode.client(@config.token, {hostname: hostname}) valid: (cb) -> @api.get "/user", (err, status, data, headers) -> scopes = headers?['x-oauth-scopes'] if scopes?.indexOf('repo') >= 0 cb(true) else cb(false) class GitHubWebHookIpVerifier constructor: () -> gitHubSubnets = process.env.HUBOT_DEPLOY_GITHUB_SUBNETS || "PI:IP_ADDRESS:172.16.31.10END_PI/22" @subnets = (new Address4(subnet.trim()) for subnet in gitHubSubnets.split(',')) ipIsValid: (ipAddress) -> address = new Address4("#{ipAddress}/24") for subnet in @subnets return true if address.isInSubnet(subnet) false class GitHubTokenVerifier constructor: (token) -> @token = token?.trim() valid: (cb) -> return cb(false) unless token? ScopedClient.create("https://api.github.com"). header("User-Agent", "hubot-deploy/0.13.1"). header("Authorization", "token #{@token}"). path("/user"). get() (err, res, body) -> scopes = res.headers?['x-oauth-scopes'] if err cb(false) else if res.statusCode isnt 200 cb(false) else if scopes?.indexOf("repo") < 0 cb(false) else user = JSON.parse(body) cb(user) class HerokuTokenVerifier constructor: (token) -> @token = token?.trim() valid: (cb) -> return cb(false) unless token? ScopedClient.create("https://api.heroku.com"). header("Accept", "application/vnd.heroku+json; version=3"). header("Authorization", "Bearer #{@token}"). path("/account"). get() (err, res, body) -> if err cb(false) else if res.statusCode isnt 200 cb(false) else user = JSON.parse(body) cb(user) exports.VaultKey = VaultKey exports.ApiTokenVerifier = ApiTokenVerifier exports.GitHubTokenVerifier = GitHubTokenVerifier exports.HerokuTokenVerifier = HerokuTokenVerifier exports.GitHubWebHookIpVerifier = GitHubWebHookIpVerifier
[ { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof", "end": 23, "score": 0.9998920559883118, "start": 13, "tag": "NAME", "value": "Mat Groves" }, { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/filters/M", "end": 37, "score": 0.8062465190887451, "start": 34, "tag": "USERNAME", "value": "gro" }, { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/filters/MaskFilter', ->\n \n ", "end": 56, "score": 0.9995217323303223, "start": 46, "tag": "USERNAME", "value": "@Doormat23" } ]
src/Coffixi/filters/MaskFilter.coffee
namuol/Coffixi
1
###* @author Mat Groves http://matgroves.com/ @Doormat23 ### define 'Coffixi/filters/MaskFilter', -> class MaskFilter constructor: (graphics) -> # the graphics data that will be used for filtering @graphics
59620
###* @author <NAME> http://matgroves.com/ @Doormat23 ### define 'Coffixi/filters/MaskFilter', -> class MaskFilter constructor: (graphics) -> # the graphics data that will be used for filtering @graphics
true
###* @author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23 ### define 'Coffixi/filters/MaskFilter', -> class MaskFilter constructor: (graphics) -> # the graphics data that will be used for filtering @graphics
[ { "context": "ard highlight visual effect\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\nclass Fx.Highlight extends Fx.Style\n extend:\n ", "end": 81, "score": 0.9998824596405029, "start": 64, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/fx/src/fx/highlight.coffee
lovely-io/lovely.io-stl
2
# # The standard highlight visual effect # # Copyright (C) 2011 Nikolay Nemshilov # class Fx.Highlight extends Fx.Style extend: # additional options Options: Hash.merge(Fx.Options, { color: '#FF8' transition: 'ease-out' }) # protected # # Prepares the transition # # @param {String} start color # @param {String} optional end color # @return {Fx.Highlight} this # prepare: (start, end)-> element = @element element_style = element._.style style_name = 'backgroundColor' end_color = end || element.style(style_name) if is_transparent(end_color) @on 'finish', -> element_style[style_name] = 'transparent' # trying to find the end color end_color = new List([element]) .concat(element.parents()) .map('style', style_name) .reject((v) -> !v || is_transparent(v)) end_color = end_color[0] || '#FFF' element_style[style_name] = start || @options.color super backgroundColor: end_color
171982
# # The standard highlight visual effect # # Copyright (C) 2011 <NAME> # class Fx.Highlight extends Fx.Style extend: # additional options Options: Hash.merge(Fx.Options, { color: '#FF8' transition: 'ease-out' }) # protected # # Prepares the transition # # @param {String} start color # @param {String} optional end color # @return {Fx.Highlight} this # prepare: (start, end)-> element = @element element_style = element._.style style_name = 'backgroundColor' end_color = end || element.style(style_name) if is_transparent(end_color) @on 'finish', -> element_style[style_name] = 'transparent' # trying to find the end color end_color = new List([element]) .concat(element.parents()) .map('style', style_name) .reject((v) -> !v || is_transparent(v)) end_color = end_color[0] || '#FFF' element_style[style_name] = start || @options.color super backgroundColor: end_color
true
# # The standard highlight visual effect # # Copyright (C) 2011 PI:NAME:<NAME>END_PI # class Fx.Highlight extends Fx.Style extend: # additional options Options: Hash.merge(Fx.Options, { color: '#FF8' transition: 'ease-out' }) # protected # # Prepares the transition # # @param {String} start color # @param {String} optional end color # @return {Fx.Highlight} this # prepare: (start, end)-> element = @element element_style = element._.style style_name = 'backgroundColor' end_color = end || element.style(style_name) if is_transparent(end_color) @on 'finish', -> element_style[style_name] = 'transparent' # trying to find the end color end_color = new List([element]) .concat(element.parents()) .map('style', style_name) .reject((v) -> !v || is_transparent(v)) end_color = end_color[0] || '#FFF' element_style[style_name] = start || @options.color super backgroundColor: end_color
[ { "context": "Bittorrent Instance'\n\n @username = properties['username'] or 'admin'\n @password = properties['passwor", "end": 302, "score": 0.6775888800621033, "start": 294, "tag": "USERNAME", "value": "username" }, { "context": "ance'\n\n @username = properties['username'] or 'admin'\n @password = properties['password'] or 'admi", "end": 314, "score": 0.9350256323814392, "start": 309, "tag": "USERNAME", "value": "admin" }, { "context": "dmin'\n @password = properties['password'] or 'adminadmin'\n @host = properties['host'] or 'localhost'\n ", "end": 370, "score": 0.9993926286697388, "start": 360, "tag": "PASSWORD", "value": "adminadmin" }, { "context": "ed'\n json: true\n form:\n username: @username\n password: @password\n\n request options,", "end": 8294, "score": 0.9994980096817017, "start": 8285, "tag": "USERNAME", "value": "@username" }, { "context": "orm:\n username: @username\n password: @password\n\n request options, (err, res, body) ->\n ", "end": 8322, "score": 0.9916818141937256, "start": 8313, "tag": "PASSWORD", "value": "@password" } ]
src/qBittorrent.coffee
makeran218/node-qbittorrent-client
3
request = require 'request' md5 = require 'md5' async = require 'async' semver = require 'semver' log = require('debug-logger')('qBittorrent') class qBittorrent constructor: (properties) -> log.debug 'Instantiating qBittorrent Instance' @username = properties['username'] or 'admin' @password = properties['password'] or 'adminadmin' @host = properties['host'] or 'localhost' @port = properties['port'] or 8080 @version = properties['version'] or '3.1.8' @ssl = properties['ssl'] or false @nonce = properties['nonce'] or null @authenticated = false if semver.lt '3.1.8', @version @apiVersion = 'API2' else @apiVersion = 'API1' _makeRequest: (method = 'GET', api = '', form = null, callback) -> if typeof form == 'function' callback = form form = null log.debug "#{method} http://#{@host}:#{@port}#{api} #{form or ''}" client = this async.waterfall [ # Authenticate (wcb) -> return wcb() if client.authenticated client.login wcb # Prepare Request (wcb) -> options = method: method url: "http://#{client.host}:#{client.port}#{api}" headers: 'content-type': 'application/json' cookie: client.cookie or null options.headers['content-type'] = 'multipart/form-data' if method == 'POST' options.formData = form if form if client.apiVersion == 'API1' auth = realm: 'Web UI Access' username: client.username nonce: client.nonce or null uri: api options.headers.authorization = 'Digest ' auth.response = md5( md5(client.username + ':' + auth.realm + ':' + client.password) + ':' + client.nonce + ':' + md5(method + ':' + api) ) if client.nonce for key, val of auth options.headers.authorization += "#{key}=\"#{val}\", " options.headers.authorization = options.headers.authorization.replace(/, $/,'') wcb null, options # Perform request (options, wcb) -> log options request options, (err, res, body) -> log.debug 'REQUEST ERROR: ' + err if err wcb err, res, body ], (err, res, body) -> callback err, body _functionName = (fn) -> ret = fn.toString() ret = ret.substr('function '.length) return ret.substr(0, ret.indexOf('(')) shutdown: (callback) -> log.debug 'Executing shutdown' @_makeRequest 'GET', "/command/shutdown", callback class API1 extends qBittorrent login: (cb) -> log.debug 'Authenticating via API1' client = this options = method: 'GET' url: "http://#{@host}:#{@port}" headers: 'content-type': 'application/json' json: true request options, (err, res, body) -> if res.headers['www-authenticate'] auth = {} res.headers['www-authenticate'].split(',').map((x)-> opts = x.split('=').map (x)-> x.replace(/"/g,'').replace(/\s/g,'') auth[opts[0]] = opts[1] )[0] client.nonce = auth.nonce if auth.nonce client.authenticated = true return cb() if cb else return cb() if cb getTorrents: (callback) -> log.debug 'Executing getTorrents' @_makeRequest 'GET', "/json/torrents", callback getTorrent: (hash, callback) -> log.debug 'Executing getTorrent' @_makeRequest 'GET', "/json/propertiesGeneral/#{hash}", callback getTorrentTrackers: (hash, callback) -> log.debug 'Executing getTorrentTrackers' @_makeRequest 'GET', "/json/propertiesTrackers/#{hash}", callback getTorrentContents: (hash, callback) -> log.debug 'Executing getTorrentContents. : ' + hash @_makeRequest 'GET', "/json/propertiesFiles/#{hash}", callback getGlobalTransferInfo: (callback) -> log.debug 'Executing getGlobalTransferInfo' @_makeRequest 'GET', "/json/transferInfo", callback getPreferences: (callback) -> log.debug 'Executing getPreferences' @_makeRequest 'GET', "/json/preferences", callback uploadFromDisk: (callback) -> log.debug 'Executing uploadFromDisk' #TODO: uploadFromDisk support callback 'This feature is not yet supported' addTrackers: (hash, urls, callback) -> log.debug 'Executing addTrackers' #@_makeRequest 'POST', "/command/addTrackers", callback callback 'This feature is not yet supported' pauseTorrent: (hash, callback) -> log.debug 'Executing pauseTorrent' @_makeRequest 'POST', "/command/pause", hash: hash, callback pauseAllTorrents: (callback) -> log.debug 'Executing pauseAllTorrents' @_makeRequest 'POST', "/command/pauseall", callback resumeTorrent: (hash, callback) -> log.debug 'Executing resumeTorrent' @_makeRequest 'POST', "/command/resume", hash: hash , callback resumeAllTorrents: (callback) -> log.debug 'Executing resumeAllTorrents' @_makeRequest 'POST', "/command/resumeall", callback deleteTorrent: (hash, callback) -> log.debug 'Executing deleteTorrent' @_makeRequest 'POST', "/command/delete", hash: hash, callback deleteTorrentAndData: (hashes, callback) -> log.debug 'Executing deleteTorrentAndData' @_makeRequest 'POST', "/command/deletePerm", hashes: hash, callback recheckTorrent: (hash, callback) -> log.debug 'Executing recheckTorrent' @_makeRequest 'POST', "/command/recheck", hash: hash, callback increaseTorrentPriority: (hashes, callback) -> log.debug 'Executing increaseTorrentPriority' @_makeRequest 'POST', "/command/increasePrio", hashes: hash, callback decreaseTorrentPriority: (hashes, callback) -> log.debug 'Executing decreaseTorrentPriority' @_makeRequest 'POST', "/command/decreasePrio", hashes: hash, callback maximalTorrentPriority: (hashes, callback) -> log.debug 'Executing maximalTorrentPriority' @_makeRequest 'POST', "/command/topPrio", hashes: hash, callback manimalTorrentPriority: (hashes, callback) -> log.debug 'Executing manimalTorrentPriority' @_makeRequest 'POST', "/command/bottomPrio", hashes: hash, callback setFilePriority: (hash, id, priority, callback) -> log.debug 'Executing setFilePriority' @_makeRequest 'POST', "/command/bottomPrio", { hash: hash, id: id, priority: priority }, callback getGlobalDownloadLimit: (callback) -> log.debug 'Executing getGlobalDownloadLimit' @_makeRequest 'POST', "/command/getGlobalDlLimit", callback setGlobalDownloadLimit: (limit, callback) -> log.debug 'Executing setGlobalDownloadLimit' @_makeRequest 'POST', "/command/setGlobalDlLimit", limit: limit, callback getGlobalUploadLimit: (callback) -> log.debug 'Executing getGlobalUploadLimit' @_makeRequest 'POST', "/command/getGlobalUpLimit", callback setGlobalUploadLimit: (limit, callback) -> log.debug 'Executing setGlobalUploadLimit' @_makeRequest 'POST', "/command/setGlobalUpLimit", limit: limit, callback getTorrentDownloadLimit: (hash, callback) -> log.debug 'Executing getTorrentDownloadLimit' @_makeRequest 'POST', "/command/getTorrentDlLimit", hash: hash, callback setTorrentDownloadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentDownloadLimit' @_makeRequest 'POST', "/command/setTorrentDlLimit", { hash: hash, limit: limit }, callback getTorrentUploadLimit: (hash, callback) -> log.debug 'Executing getTorrentUploadLimit' @_makeRequest 'POST', "/command/getTorrentUpLimit", hash: hash, callback setTorrentUploadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentUploadLimit' @_makeRequest 'POST', "/command/setTorrentUpLimit", { hash: hash, limit: limit }, callback setPreferences: (preferences = {}, callback) -> log.debug 'Executing setPreferences' @_makeRequest 'POST', "/command/setTorrentUpLimit", json: JSON.stringify(preferences), callback class API2 extends API1 login: (cb) -> log.debug 'Authenticating via API2 (Using Cookies)' client = this options = method: 'POST' url: "http://#{@host}:#{@port}/login" headers: 'content-type': 'application/x-www-form-urlencoded' json: true form: username: @username password: @password request options, (err, res, body) -> if body == 'Ok.' && res.headers['set-cookie'] client.authenticated = true client.cookie = res.headers['set-cookie'][0]?.match(/.*; /)[0]?.replace(/; $/,'') return cb err logout: (callback) -> @_makeRequest 'POST', "/logout", callback getMinimumApiVersion: (callback) -> log.debug 'Executing getMinimumApiVersion' @_makeRequest 'GET', "/version/api_min", callback getqBittorrentVersion: (callback) -> log.debug 'Executing getqBittorrentVersion' @_makeRequest 'GET', "/version/qbittorrent", callback getTorrents: (params, callback) -> log.debug 'Executing getTorrents' if typeof params == 'function' callback = params params = null @_makeRequest 'GET', "/query/torrents", params, callback getTorrent: (hash, callback) -> log.debug 'Executing getTorrent' @_makeRequest 'GET', "/query/propertiesGeneral/#{hash}", callback getTorrentTrackers: (hash, callback) -> log.debug 'Executing getTorrentTrackers' @_makeRequest 'GET', "/query/propertiesTrackers/#{hash}", callback getTorrentContents: (hash, callback) -> log.debug 'Executing getTorrentContents. : ' + hash @_makeRequest 'GET', "/query/propertiesFiles/#{hash}", callback getGlobalTransferInfo: (callback) -> log.debug 'Executing getGlobalTransferInfo' @_makeRequest 'GET', "/query/transferInfo", callback getPreferences: (callback) -> log.debug 'Executing getPreferences' @_makeRequest 'GET', "/query/preferences", callback addTorrentFromURL: (options, callback) -> log.debug 'Executing addTorrentFromURL' @_makeRequest 'POST', "/command/download", options, callback uploadFromDisk: (callback) -> log.debug 'Executing uploadFromDisk' #TODO: uploadFromDisk support callback 'This feature is not yet supported' addTrackers: (hash, urls, callback) -> log.debug 'Executing addTrackers' #@_makeRequest 'POST', "/command/addTrackers", callback callback 'This feature is not yet supported' pauseTorrent: (hash, callback) -> log.debug 'Executing pauseTorrent' @_makeRequest 'POST', "/command/pause", hash: hash, callback pauseAllTorrents: (callback) -> log.debug 'Executing pauseAllTorrents' @_makeRequest 'POST', "/command/pauseall", callback resumeTorrent: (hash, callback) -> log.debug 'Executing resumeTorrent' @_makeRequest 'POST', "/command/resume", hash: hash , callback resumeAllTorrents: (callback) -> log.debug 'Executing resumeAllTorrents' @_makeRequest 'POST', "/command/resumeall", callback deleteTorrent: (hash, callback) -> log.debug 'Executing deleteTorrent' @_makeRequest 'POST', "/command/delete", hash: hash, callback deleteTorrentAndData: (hashes, callback) -> log.debug 'Executing deleteTorrentAndData' @_makeRequest 'POST', "/command/deletePerm", hashes: hash, callback recheckTorrent: (hash, callback) -> log.debug 'Executing recheckTorrent' @_makeRequest 'POST', "/command/recheck", hash: hash, callback increaseTorrentPriority: (hashes, callback) -> log.debug 'Executing increaseTorrentPriority' @_makeRequest 'POST', "/command/increasePrio", hashes: hash, callback decreaseTorrentPriority: (hashes, callback) -> log.debug 'Executing decreaseTorrentPriority' @_makeRequest 'POST', "/command/decreasePrio", hashes: hash, callback maximalTorrentPriority: (hashes, callback) -> log.debug 'Executing maximalTorrentPriority' @_makeRequest 'POST', "/command/topPrio", hashes: hash, callback manimalTorrentPriority: (hashes, callback) -> log.debug 'Executing manimalTorrentPriority' @_makeRequest 'POST', "/command/bottomPrio", hashes: hash, callback setFilePriority: (hash, id, priority, callback) -> log.debug 'Executing setFilePriority' @_makeRequest 'POST', "/command/bottomPrio", { hash: hash, id: id, priority: priority }, callback getGlobalDownloadLimit: (callback) -> log.debug 'Executing getGlobalDownloadLimit' @_makeRequest 'POST', "/command/getGlobalDlLimit", callback setGlobalDownloadLimit: (limit, callback) -> log.debug 'Executing setGlobalDownloadLimit' @_makeRequest 'POST', "/command/setGlobalDlLimit", limit: limit, callback getGlobalUploadLimit: (callback) -> log.debug 'Executing getGlobalUploadLimit' @_makeRequest 'POST', "/command/getGlobalUpLimit", callback setGlobalUploadLimit: (limit, callback) -> log.debug 'Executing setGlobalUploadLimit' @_makeRequest 'POST', "/command/setGlobalUpLimit", limit: limit, callback getTorrentDownloadLimit: (hash, callback) -> log.debug 'Executing getTorrentDownloadLimit' @_makeRequest 'POST', "/command/getTorrentsDlLimit", hashes: hash, callback setTorrentDownloadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentDownloadLimit' @_makeRequest 'POST', "/command/setTorrentsDlLimit", { hashes: hash, limit: limit }, callback getTorrentUploadLimit: (hash, callback) -> log.debug 'Executing getTorrentUploadLimit' @_makeRequest 'POST', "/command/getTorrentsUpLimit", hashes: hash, callback setTorrentUploadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentUploadLimit' @_makeRequest 'POST', "/command/setTorrentsUpLimit", { hash: hash, limit: limit }, callback setPreferences: (preferences = {}, callback) -> log.debug 'Executing setPreferences' @_makeRequest 'POST', "/command/setTorrentUpLimit", json: JSON.stringify(preferences), callback class API3 extends API2 getTorrentWebSeeds: (hash, callback) -> log.debug 'Executing getTorrentWebSeeds' @_makeRequest 'GET', "/query/propertiesWebSeeds/#{hash}", callback module.exports = API1: API1 API2: API2 API3: API3
58046
request = require 'request' md5 = require 'md5' async = require 'async' semver = require 'semver' log = require('debug-logger')('qBittorrent') class qBittorrent constructor: (properties) -> log.debug 'Instantiating qBittorrent Instance' @username = properties['username'] or 'admin' @password = properties['password'] or '<PASSWORD>' @host = properties['host'] or 'localhost' @port = properties['port'] or 8080 @version = properties['version'] or '3.1.8' @ssl = properties['ssl'] or false @nonce = properties['nonce'] or null @authenticated = false if semver.lt '3.1.8', @version @apiVersion = 'API2' else @apiVersion = 'API1' _makeRequest: (method = 'GET', api = '', form = null, callback) -> if typeof form == 'function' callback = form form = null log.debug "#{method} http://#{@host}:#{@port}#{api} #{form or ''}" client = this async.waterfall [ # Authenticate (wcb) -> return wcb() if client.authenticated client.login wcb # Prepare Request (wcb) -> options = method: method url: "http://#{client.host}:#{client.port}#{api}" headers: 'content-type': 'application/json' cookie: client.cookie or null options.headers['content-type'] = 'multipart/form-data' if method == 'POST' options.formData = form if form if client.apiVersion == 'API1' auth = realm: 'Web UI Access' username: client.username nonce: client.nonce or null uri: api options.headers.authorization = 'Digest ' auth.response = md5( md5(client.username + ':' + auth.realm + ':' + client.password) + ':' + client.nonce + ':' + md5(method + ':' + api) ) if client.nonce for key, val of auth options.headers.authorization += "#{key}=\"#{val}\", " options.headers.authorization = options.headers.authorization.replace(/, $/,'') wcb null, options # Perform request (options, wcb) -> log options request options, (err, res, body) -> log.debug 'REQUEST ERROR: ' + err if err wcb err, res, body ], (err, res, body) -> callback err, body _functionName = (fn) -> ret = fn.toString() ret = ret.substr('function '.length) return ret.substr(0, ret.indexOf('(')) shutdown: (callback) -> log.debug 'Executing shutdown' @_makeRequest 'GET', "/command/shutdown", callback class API1 extends qBittorrent login: (cb) -> log.debug 'Authenticating via API1' client = this options = method: 'GET' url: "http://#{@host}:#{@port}" headers: 'content-type': 'application/json' json: true request options, (err, res, body) -> if res.headers['www-authenticate'] auth = {} res.headers['www-authenticate'].split(',').map((x)-> opts = x.split('=').map (x)-> x.replace(/"/g,'').replace(/\s/g,'') auth[opts[0]] = opts[1] )[0] client.nonce = auth.nonce if auth.nonce client.authenticated = true return cb() if cb else return cb() if cb getTorrents: (callback) -> log.debug 'Executing getTorrents' @_makeRequest 'GET', "/json/torrents", callback getTorrent: (hash, callback) -> log.debug 'Executing getTorrent' @_makeRequest 'GET', "/json/propertiesGeneral/#{hash}", callback getTorrentTrackers: (hash, callback) -> log.debug 'Executing getTorrentTrackers' @_makeRequest 'GET', "/json/propertiesTrackers/#{hash}", callback getTorrentContents: (hash, callback) -> log.debug 'Executing getTorrentContents. : ' + hash @_makeRequest 'GET', "/json/propertiesFiles/#{hash}", callback getGlobalTransferInfo: (callback) -> log.debug 'Executing getGlobalTransferInfo' @_makeRequest 'GET', "/json/transferInfo", callback getPreferences: (callback) -> log.debug 'Executing getPreferences' @_makeRequest 'GET', "/json/preferences", callback uploadFromDisk: (callback) -> log.debug 'Executing uploadFromDisk' #TODO: uploadFromDisk support callback 'This feature is not yet supported' addTrackers: (hash, urls, callback) -> log.debug 'Executing addTrackers' #@_makeRequest 'POST', "/command/addTrackers", callback callback 'This feature is not yet supported' pauseTorrent: (hash, callback) -> log.debug 'Executing pauseTorrent' @_makeRequest 'POST', "/command/pause", hash: hash, callback pauseAllTorrents: (callback) -> log.debug 'Executing pauseAllTorrents' @_makeRequest 'POST', "/command/pauseall", callback resumeTorrent: (hash, callback) -> log.debug 'Executing resumeTorrent' @_makeRequest 'POST', "/command/resume", hash: hash , callback resumeAllTorrents: (callback) -> log.debug 'Executing resumeAllTorrents' @_makeRequest 'POST', "/command/resumeall", callback deleteTorrent: (hash, callback) -> log.debug 'Executing deleteTorrent' @_makeRequest 'POST', "/command/delete", hash: hash, callback deleteTorrentAndData: (hashes, callback) -> log.debug 'Executing deleteTorrentAndData' @_makeRequest 'POST', "/command/deletePerm", hashes: hash, callback recheckTorrent: (hash, callback) -> log.debug 'Executing recheckTorrent' @_makeRequest 'POST', "/command/recheck", hash: hash, callback increaseTorrentPriority: (hashes, callback) -> log.debug 'Executing increaseTorrentPriority' @_makeRequest 'POST', "/command/increasePrio", hashes: hash, callback decreaseTorrentPriority: (hashes, callback) -> log.debug 'Executing decreaseTorrentPriority' @_makeRequest 'POST', "/command/decreasePrio", hashes: hash, callback maximalTorrentPriority: (hashes, callback) -> log.debug 'Executing maximalTorrentPriority' @_makeRequest 'POST', "/command/topPrio", hashes: hash, callback manimalTorrentPriority: (hashes, callback) -> log.debug 'Executing manimalTorrentPriority' @_makeRequest 'POST', "/command/bottomPrio", hashes: hash, callback setFilePriority: (hash, id, priority, callback) -> log.debug 'Executing setFilePriority' @_makeRequest 'POST', "/command/bottomPrio", { hash: hash, id: id, priority: priority }, callback getGlobalDownloadLimit: (callback) -> log.debug 'Executing getGlobalDownloadLimit' @_makeRequest 'POST', "/command/getGlobalDlLimit", callback setGlobalDownloadLimit: (limit, callback) -> log.debug 'Executing setGlobalDownloadLimit' @_makeRequest 'POST', "/command/setGlobalDlLimit", limit: limit, callback getGlobalUploadLimit: (callback) -> log.debug 'Executing getGlobalUploadLimit' @_makeRequest 'POST', "/command/getGlobalUpLimit", callback setGlobalUploadLimit: (limit, callback) -> log.debug 'Executing setGlobalUploadLimit' @_makeRequest 'POST', "/command/setGlobalUpLimit", limit: limit, callback getTorrentDownloadLimit: (hash, callback) -> log.debug 'Executing getTorrentDownloadLimit' @_makeRequest 'POST', "/command/getTorrentDlLimit", hash: hash, callback setTorrentDownloadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentDownloadLimit' @_makeRequest 'POST', "/command/setTorrentDlLimit", { hash: hash, limit: limit }, callback getTorrentUploadLimit: (hash, callback) -> log.debug 'Executing getTorrentUploadLimit' @_makeRequest 'POST', "/command/getTorrentUpLimit", hash: hash, callback setTorrentUploadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentUploadLimit' @_makeRequest 'POST', "/command/setTorrentUpLimit", { hash: hash, limit: limit }, callback setPreferences: (preferences = {}, callback) -> log.debug 'Executing setPreferences' @_makeRequest 'POST', "/command/setTorrentUpLimit", json: JSON.stringify(preferences), callback class API2 extends API1 login: (cb) -> log.debug 'Authenticating via API2 (Using Cookies)' client = this options = method: 'POST' url: "http://#{@host}:#{@port}/login" headers: 'content-type': 'application/x-www-form-urlencoded' json: true form: username: @username password: <PASSWORD> request options, (err, res, body) -> if body == 'Ok.' && res.headers['set-cookie'] client.authenticated = true client.cookie = res.headers['set-cookie'][0]?.match(/.*; /)[0]?.replace(/; $/,'') return cb err logout: (callback) -> @_makeRequest 'POST', "/logout", callback getMinimumApiVersion: (callback) -> log.debug 'Executing getMinimumApiVersion' @_makeRequest 'GET', "/version/api_min", callback getqBittorrentVersion: (callback) -> log.debug 'Executing getqBittorrentVersion' @_makeRequest 'GET', "/version/qbittorrent", callback getTorrents: (params, callback) -> log.debug 'Executing getTorrents' if typeof params == 'function' callback = params params = null @_makeRequest 'GET', "/query/torrents", params, callback getTorrent: (hash, callback) -> log.debug 'Executing getTorrent' @_makeRequest 'GET', "/query/propertiesGeneral/#{hash}", callback getTorrentTrackers: (hash, callback) -> log.debug 'Executing getTorrentTrackers' @_makeRequest 'GET', "/query/propertiesTrackers/#{hash}", callback getTorrentContents: (hash, callback) -> log.debug 'Executing getTorrentContents. : ' + hash @_makeRequest 'GET', "/query/propertiesFiles/#{hash}", callback getGlobalTransferInfo: (callback) -> log.debug 'Executing getGlobalTransferInfo' @_makeRequest 'GET', "/query/transferInfo", callback getPreferences: (callback) -> log.debug 'Executing getPreferences' @_makeRequest 'GET', "/query/preferences", callback addTorrentFromURL: (options, callback) -> log.debug 'Executing addTorrentFromURL' @_makeRequest 'POST', "/command/download", options, callback uploadFromDisk: (callback) -> log.debug 'Executing uploadFromDisk' #TODO: uploadFromDisk support callback 'This feature is not yet supported' addTrackers: (hash, urls, callback) -> log.debug 'Executing addTrackers' #@_makeRequest 'POST', "/command/addTrackers", callback callback 'This feature is not yet supported' pauseTorrent: (hash, callback) -> log.debug 'Executing pauseTorrent' @_makeRequest 'POST', "/command/pause", hash: hash, callback pauseAllTorrents: (callback) -> log.debug 'Executing pauseAllTorrents' @_makeRequest 'POST', "/command/pauseall", callback resumeTorrent: (hash, callback) -> log.debug 'Executing resumeTorrent' @_makeRequest 'POST', "/command/resume", hash: hash , callback resumeAllTorrents: (callback) -> log.debug 'Executing resumeAllTorrents' @_makeRequest 'POST', "/command/resumeall", callback deleteTorrent: (hash, callback) -> log.debug 'Executing deleteTorrent' @_makeRequest 'POST', "/command/delete", hash: hash, callback deleteTorrentAndData: (hashes, callback) -> log.debug 'Executing deleteTorrentAndData' @_makeRequest 'POST', "/command/deletePerm", hashes: hash, callback recheckTorrent: (hash, callback) -> log.debug 'Executing recheckTorrent' @_makeRequest 'POST', "/command/recheck", hash: hash, callback increaseTorrentPriority: (hashes, callback) -> log.debug 'Executing increaseTorrentPriority' @_makeRequest 'POST', "/command/increasePrio", hashes: hash, callback decreaseTorrentPriority: (hashes, callback) -> log.debug 'Executing decreaseTorrentPriority' @_makeRequest 'POST', "/command/decreasePrio", hashes: hash, callback maximalTorrentPriority: (hashes, callback) -> log.debug 'Executing maximalTorrentPriority' @_makeRequest 'POST', "/command/topPrio", hashes: hash, callback manimalTorrentPriority: (hashes, callback) -> log.debug 'Executing manimalTorrentPriority' @_makeRequest 'POST', "/command/bottomPrio", hashes: hash, callback setFilePriority: (hash, id, priority, callback) -> log.debug 'Executing setFilePriority' @_makeRequest 'POST', "/command/bottomPrio", { hash: hash, id: id, priority: priority }, callback getGlobalDownloadLimit: (callback) -> log.debug 'Executing getGlobalDownloadLimit' @_makeRequest 'POST', "/command/getGlobalDlLimit", callback setGlobalDownloadLimit: (limit, callback) -> log.debug 'Executing setGlobalDownloadLimit' @_makeRequest 'POST', "/command/setGlobalDlLimit", limit: limit, callback getGlobalUploadLimit: (callback) -> log.debug 'Executing getGlobalUploadLimit' @_makeRequest 'POST', "/command/getGlobalUpLimit", callback setGlobalUploadLimit: (limit, callback) -> log.debug 'Executing setGlobalUploadLimit' @_makeRequest 'POST', "/command/setGlobalUpLimit", limit: limit, callback getTorrentDownloadLimit: (hash, callback) -> log.debug 'Executing getTorrentDownloadLimit' @_makeRequest 'POST', "/command/getTorrentsDlLimit", hashes: hash, callback setTorrentDownloadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentDownloadLimit' @_makeRequest 'POST', "/command/setTorrentsDlLimit", { hashes: hash, limit: limit }, callback getTorrentUploadLimit: (hash, callback) -> log.debug 'Executing getTorrentUploadLimit' @_makeRequest 'POST', "/command/getTorrentsUpLimit", hashes: hash, callback setTorrentUploadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentUploadLimit' @_makeRequest 'POST', "/command/setTorrentsUpLimit", { hash: hash, limit: limit }, callback setPreferences: (preferences = {}, callback) -> log.debug 'Executing setPreferences' @_makeRequest 'POST', "/command/setTorrentUpLimit", json: JSON.stringify(preferences), callback class API3 extends API2 getTorrentWebSeeds: (hash, callback) -> log.debug 'Executing getTorrentWebSeeds' @_makeRequest 'GET', "/query/propertiesWebSeeds/#{hash}", callback module.exports = API1: API1 API2: API2 API3: API3
true
request = require 'request' md5 = require 'md5' async = require 'async' semver = require 'semver' log = require('debug-logger')('qBittorrent') class qBittorrent constructor: (properties) -> log.debug 'Instantiating qBittorrent Instance' @username = properties['username'] or 'admin' @password = properties['password'] or 'PI:PASSWORD:<PASSWORD>END_PI' @host = properties['host'] or 'localhost' @port = properties['port'] or 8080 @version = properties['version'] or '3.1.8' @ssl = properties['ssl'] or false @nonce = properties['nonce'] or null @authenticated = false if semver.lt '3.1.8', @version @apiVersion = 'API2' else @apiVersion = 'API1' _makeRequest: (method = 'GET', api = '', form = null, callback) -> if typeof form == 'function' callback = form form = null log.debug "#{method} http://#{@host}:#{@port}#{api} #{form or ''}" client = this async.waterfall [ # Authenticate (wcb) -> return wcb() if client.authenticated client.login wcb # Prepare Request (wcb) -> options = method: method url: "http://#{client.host}:#{client.port}#{api}" headers: 'content-type': 'application/json' cookie: client.cookie or null options.headers['content-type'] = 'multipart/form-data' if method == 'POST' options.formData = form if form if client.apiVersion == 'API1' auth = realm: 'Web UI Access' username: client.username nonce: client.nonce or null uri: api options.headers.authorization = 'Digest ' auth.response = md5( md5(client.username + ':' + auth.realm + ':' + client.password) + ':' + client.nonce + ':' + md5(method + ':' + api) ) if client.nonce for key, val of auth options.headers.authorization += "#{key}=\"#{val}\", " options.headers.authorization = options.headers.authorization.replace(/, $/,'') wcb null, options # Perform request (options, wcb) -> log options request options, (err, res, body) -> log.debug 'REQUEST ERROR: ' + err if err wcb err, res, body ], (err, res, body) -> callback err, body _functionName = (fn) -> ret = fn.toString() ret = ret.substr('function '.length) return ret.substr(0, ret.indexOf('(')) shutdown: (callback) -> log.debug 'Executing shutdown' @_makeRequest 'GET', "/command/shutdown", callback class API1 extends qBittorrent login: (cb) -> log.debug 'Authenticating via API1' client = this options = method: 'GET' url: "http://#{@host}:#{@port}" headers: 'content-type': 'application/json' json: true request options, (err, res, body) -> if res.headers['www-authenticate'] auth = {} res.headers['www-authenticate'].split(',').map((x)-> opts = x.split('=').map (x)-> x.replace(/"/g,'').replace(/\s/g,'') auth[opts[0]] = opts[1] )[0] client.nonce = auth.nonce if auth.nonce client.authenticated = true return cb() if cb else return cb() if cb getTorrents: (callback) -> log.debug 'Executing getTorrents' @_makeRequest 'GET', "/json/torrents", callback getTorrent: (hash, callback) -> log.debug 'Executing getTorrent' @_makeRequest 'GET', "/json/propertiesGeneral/#{hash}", callback getTorrentTrackers: (hash, callback) -> log.debug 'Executing getTorrentTrackers' @_makeRequest 'GET', "/json/propertiesTrackers/#{hash}", callback getTorrentContents: (hash, callback) -> log.debug 'Executing getTorrentContents. : ' + hash @_makeRequest 'GET', "/json/propertiesFiles/#{hash}", callback getGlobalTransferInfo: (callback) -> log.debug 'Executing getGlobalTransferInfo' @_makeRequest 'GET', "/json/transferInfo", callback getPreferences: (callback) -> log.debug 'Executing getPreferences' @_makeRequest 'GET', "/json/preferences", callback uploadFromDisk: (callback) -> log.debug 'Executing uploadFromDisk' #TODO: uploadFromDisk support callback 'This feature is not yet supported' addTrackers: (hash, urls, callback) -> log.debug 'Executing addTrackers' #@_makeRequest 'POST', "/command/addTrackers", callback callback 'This feature is not yet supported' pauseTorrent: (hash, callback) -> log.debug 'Executing pauseTorrent' @_makeRequest 'POST', "/command/pause", hash: hash, callback pauseAllTorrents: (callback) -> log.debug 'Executing pauseAllTorrents' @_makeRequest 'POST', "/command/pauseall", callback resumeTorrent: (hash, callback) -> log.debug 'Executing resumeTorrent' @_makeRequest 'POST', "/command/resume", hash: hash , callback resumeAllTorrents: (callback) -> log.debug 'Executing resumeAllTorrents' @_makeRequest 'POST', "/command/resumeall", callback deleteTorrent: (hash, callback) -> log.debug 'Executing deleteTorrent' @_makeRequest 'POST', "/command/delete", hash: hash, callback deleteTorrentAndData: (hashes, callback) -> log.debug 'Executing deleteTorrentAndData' @_makeRequest 'POST', "/command/deletePerm", hashes: hash, callback recheckTorrent: (hash, callback) -> log.debug 'Executing recheckTorrent' @_makeRequest 'POST', "/command/recheck", hash: hash, callback increaseTorrentPriority: (hashes, callback) -> log.debug 'Executing increaseTorrentPriority' @_makeRequest 'POST', "/command/increasePrio", hashes: hash, callback decreaseTorrentPriority: (hashes, callback) -> log.debug 'Executing decreaseTorrentPriority' @_makeRequest 'POST', "/command/decreasePrio", hashes: hash, callback maximalTorrentPriority: (hashes, callback) -> log.debug 'Executing maximalTorrentPriority' @_makeRequest 'POST', "/command/topPrio", hashes: hash, callback manimalTorrentPriority: (hashes, callback) -> log.debug 'Executing manimalTorrentPriority' @_makeRequest 'POST', "/command/bottomPrio", hashes: hash, callback setFilePriority: (hash, id, priority, callback) -> log.debug 'Executing setFilePriority' @_makeRequest 'POST', "/command/bottomPrio", { hash: hash, id: id, priority: priority }, callback getGlobalDownloadLimit: (callback) -> log.debug 'Executing getGlobalDownloadLimit' @_makeRequest 'POST', "/command/getGlobalDlLimit", callback setGlobalDownloadLimit: (limit, callback) -> log.debug 'Executing setGlobalDownloadLimit' @_makeRequest 'POST', "/command/setGlobalDlLimit", limit: limit, callback getGlobalUploadLimit: (callback) -> log.debug 'Executing getGlobalUploadLimit' @_makeRequest 'POST', "/command/getGlobalUpLimit", callback setGlobalUploadLimit: (limit, callback) -> log.debug 'Executing setGlobalUploadLimit' @_makeRequest 'POST', "/command/setGlobalUpLimit", limit: limit, callback getTorrentDownloadLimit: (hash, callback) -> log.debug 'Executing getTorrentDownloadLimit' @_makeRequest 'POST', "/command/getTorrentDlLimit", hash: hash, callback setTorrentDownloadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentDownloadLimit' @_makeRequest 'POST', "/command/setTorrentDlLimit", { hash: hash, limit: limit }, callback getTorrentUploadLimit: (hash, callback) -> log.debug 'Executing getTorrentUploadLimit' @_makeRequest 'POST', "/command/getTorrentUpLimit", hash: hash, callback setTorrentUploadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentUploadLimit' @_makeRequest 'POST', "/command/setTorrentUpLimit", { hash: hash, limit: limit }, callback setPreferences: (preferences = {}, callback) -> log.debug 'Executing setPreferences' @_makeRequest 'POST', "/command/setTorrentUpLimit", json: JSON.stringify(preferences), callback class API2 extends API1 login: (cb) -> log.debug 'Authenticating via API2 (Using Cookies)' client = this options = method: 'POST' url: "http://#{@host}:#{@port}/login" headers: 'content-type': 'application/x-www-form-urlencoded' json: true form: username: @username password: PI:PASSWORD:<PASSWORD>END_PI request options, (err, res, body) -> if body == 'Ok.' && res.headers['set-cookie'] client.authenticated = true client.cookie = res.headers['set-cookie'][0]?.match(/.*; /)[0]?.replace(/; $/,'') return cb err logout: (callback) -> @_makeRequest 'POST', "/logout", callback getMinimumApiVersion: (callback) -> log.debug 'Executing getMinimumApiVersion' @_makeRequest 'GET', "/version/api_min", callback getqBittorrentVersion: (callback) -> log.debug 'Executing getqBittorrentVersion' @_makeRequest 'GET', "/version/qbittorrent", callback getTorrents: (params, callback) -> log.debug 'Executing getTorrents' if typeof params == 'function' callback = params params = null @_makeRequest 'GET', "/query/torrents", params, callback getTorrent: (hash, callback) -> log.debug 'Executing getTorrent' @_makeRequest 'GET', "/query/propertiesGeneral/#{hash}", callback getTorrentTrackers: (hash, callback) -> log.debug 'Executing getTorrentTrackers' @_makeRequest 'GET', "/query/propertiesTrackers/#{hash}", callback getTorrentContents: (hash, callback) -> log.debug 'Executing getTorrentContents. : ' + hash @_makeRequest 'GET', "/query/propertiesFiles/#{hash}", callback getGlobalTransferInfo: (callback) -> log.debug 'Executing getGlobalTransferInfo' @_makeRequest 'GET', "/query/transferInfo", callback getPreferences: (callback) -> log.debug 'Executing getPreferences' @_makeRequest 'GET', "/query/preferences", callback addTorrentFromURL: (options, callback) -> log.debug 'Executing addTorrentFromURL' @_makeRequest 'POST', "/command/download", options, callback uploadFromDisk: (callback) -> log.debug 'Executing uploadFromDisk' #TODO: uploadFromDisk support callback 'This feature is not yet supported' addTrackers: (hash, urls, callback) -> log.debug 'Executing addTrackers' #@_makeRequest 'POST', "/command/addTrackers", callback callback 'This feature is not yet supported' pauseTorrent: (hash, callback) -> log.debug 'Executing pauseTorrent' @_makeRequest 'POST', "/command/pause", hash: hash, callback pauseAllTorrents: (callback) -> log.debug 'Executing pauseAllTorrents' @_makeRequest 'POST', "/command/pauseall", callback resumeTorrent: (hash, callback) -> log.debug 'Executing resumeTorrent' @_makeRequest 'POST', "/command/resume", hash: hash , callback resumeAllTorrents: (callback) -> log.debug 'Executing resumeAllTorrents' @_makeRequest 'POST', "/command/resumeall", callback deleteTorrent: (hash, callback) -> log.debug 'Executing deleteTorrent' @_makeRequest 'POST', "/command/delete", hash: hash, callback deleteTorrentAndData: (hashes, callback) -> log.debug 'Executing deleteTorrentAndData' @_makeRequest 'POST', "/command/deletePerm", hashes: hash, callback recheckTorrent: (hash, callback) -> log.debug 'Executing recheckTorrent' @_makeRequest 'POST', "/command/recheck", hash: hash, callback increaseTorrentPriority: (hashes, callback) -> log.debug 'Executing increaseTorrentPriority' @_makeRequest 'POST', "/command/increasePrio", hashes: hash, callback decreaseTorrentPriority: (hashes, callback) -> log.debug 'Executing decreaseTorrentPriority' @_makeRequest 'POST', "/command/decreasePrio", hashes: hash, callback maximalTorrentPriority: (hashes, callback) -> log.debug 'Executing maximalTorrentPriority' @_makeRequest 'POST', "/command/topPrio", hashes: hash, callback manimalTorrentPriority: (hashes, callback) -> log.debug 'Executing manimalTorrentPriority' @_makeRequest 'POST', "/command/bottomPrio", hashes: hash, callback setFilePriority: (hash, id, priority, callback) -> log.debug 'Executing setFilePriority' @_makeRequest 'POST', "/command/bottomPrio", { hash: hash, id: id, priority: priority }, callback getGlobalDownloadLimit: (callback) -> log.debug 'Executing getGlobalDownloadLimit' @_makeRequest 'POST', "/command/getGlobalDlLimit", callback setGlobalDownloadLimit: (limit, callback) -> log.debug 'Executing setGlobalDownloadLimit' @_makeRequest 'POST', "/command/setGlobalDlLimit", limit: limit, callback getGlobalUploadLimit: (callback) -> log.debug 'Executing getGlobalUploadLimit' @_makeRequest 'POST', "/command/getGlobalUpLimit", callback setGlobalUploadLimit: (limit, callback) -> log.debug 'Executing setGlobalUploadLimit' @_makeRequest 'POST', "/command/setGlobalUpLimit", limit: limit, callback getTorrentDownloadLimit: (hash, callback) -> log.debug 'Executing getTorrentDownloadLimit' @_makeRequest 'POST', "/command/getTorrentsDlLimit", hashes: hash, callback setTorrentDownloadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentDownloadLimit' @_makeRequest 'POST', "/command/setTorrentsDlLimit", { hashes: hash, limit: limit }, callback getTorrentUploadLimit: (hash, callback) -> log.debug 'Executing getTorrentUploadLimit' @_makeRequest 'POST', "/command/getTorrentsUpLimit", hashes: hash, callback setTorrentUploadLimit: (hash, limit, callback) -> log.debug 'Executing setTorrentUploadLimit' @_makeRequest 'POST', "/command/setTorrentsUpLimit", { hash: hash, limit: limit }, callback setPreferences: (preferences = {}, callback) -> log.debug 'Executing setPreferences' @_makeRequest 'POST', "/command/setTorrentUpLimit", json: JSON.stringify(preferences), callback class API3 extends API2 getTorrentWebSeeds: (hash, callback) -> log.debug 'Executing getTorrentWebSeeds' @_makeRequest 'GET', "/query/propertiesWebSeeds/#{hash}", callback module.exports = API1: API1 API2: API2 API3: API3
[ { "context": "\tlist.append(@tripTemplate(trip: item))\n\t\t\tkey = \"vehicle#{item.get('vehicleId')}\"\n\t\t\tpos = Transit.map.lat", "end": 1471, "score": 0.9844623804092407, "start": 1464, "tag": "KEY", "value": "vehicle" }, { "context": "(trip: item))\n\t\t\tkey = \"vehicle#{item.get('vehicleId')}\"\n\t\t\tpos = Transit.map.latlng item.get('positio", "end": 1492, "score": 0.6912131309509277, "start": 1490, "tag": "KEY", "value": "Id" } ]
app/scripts/transit/views/route.coffee
whichbus/whichbus-phonegap
0
class Transit.Views.Route extends Backbone.View template: JST['templates/route'] tripTemplate: JST['templates/trip'] el: '#navigation' tagName: 'div' className: 'route' initialize: => @model.fetch success: @render error: (model, message) => Transit.errorPage('Error Loading Route', message) @trips = new Transit.Collections.Trips(@model) @trips.fetch success: @showTrips @tripTimer = setInterval (=> @trips.fetch(success: @showTrips)), 30000 # Transit.events.on 'route:complete', @render favorite: -> { name: "#{@model.get('name')}" type: 'route' url: "routes/#{@model.get('oba_id')}" } render: => $(@el).html(@template(route: @model)) Transit.setTitleHTML Transit.Favorites.icon(@model.get('name')), HTML.btn('btn-route', @model.get('name')), @model.get('description') @polylines = Transit.map.create_multi_polyline(@model.get('polylines').split(','), '#025d8c') Transit.map.addLayer @polylines @stopMarkers = [] for stop in @model.get('stops') pos = new G.LatLng(stop['lat'], stop['lon']) @stopMarkers.push Transit.map.create_marker(stop['name'] + " (#{stop['direction']})", pos, Transit.GMarkers.StopDot, false, true) if bounds? then bounds.extend(pos) else bounds = new G.LatLngBounds(pos) Transit.map.map.fitBounds(bounds) Transit.map.addLayer(@stopMarkers) this showTrips: => list = $("#trips").html('') @trips.forEach (item) => list.append(@tripTemplate(trip: item)) key = "vehicle#{item.get('vehicleId')}" pos = Transit.map.latlng item.get('position') if Transit.map.hasMarker key then Transit.map.moveMarker key, pos else Transit.map.addMarker key, "Vehicle #{item.get('vehicleId')}", pos, Transit.GMarkers.Bus, false, true, G.Animation.DROP
93271
class Transit.Views.Route extends Backbone.View template: JST['templates/route'] tripTemplate: JST['templates/trip'] el: '#navigation' tagName: 'div' className: 'route' initialize: => @model.fetch success: @render error: (model, message) => Transit.errorPage('Error Loading Route', message) @trips = new Transit.Collections.Trips(@model) @trips.fetch success: @showTrips @tripTimer = setInterval (=> @trips.fetch(success: @showTrips)), 30000 # Transit.events.on 'route:complete', @render favorite: -> { name: "#{@model.get('name')}" type: 'route' url: "routes/#{@model.get('oba_id')}" } render: => $(@el).html(@template(route: @model)) Transit.setTitleHTML Transit.Favorites.icon(@model.get('name')), HTML.btn('btn-route', @model.get('name')), @model.get('description') @polylines = Transit.map.create_multi_polyline(@model.get('polylines').split(','), '#025d8c') Transit.map.addLayer @polylines @stopMarkers = [] for stop in @model.get('stops') pos = new G.LatLng(stop['lat'], stop['lon']) @stopMarkers.push Transit.map.create_marker(stop['name'] + " (#{stop['direction']})", pos, Transit.GMarkers.StopDot, false, true) if bounds? then bounds.extend(pos) else bounds = new G.LatLngBounds(pos) Transit.map.map.fitBounds(bounds) Transit.map.addLayer(@stopMarkers) this showTrips: => list = $("#trips").html('') @trips.forEach (item) => list.append(@tripTemplate(trip: item)) key = "<KEY>#{item.get('vehicle<KEY>')}" pos = Transit.map.latlng item.get('position') if Transit.map.hasMarker key then Transit.map.moveMarker key, pos else Transit.map.addMarker key, "Vehicle #{item.get('vehicleId')}", pos, Transit.GMarkers.Bus, false, true, G.Animation.DROP
true
class Transit.Views.Route extends Backbone.View template: JST['templates/route'] tripTemplate: JST['templates/trip'] el: '#navigation' tagName: 'div' className: 'route' initialize: => @model.fetch success: @render error: (model, message) => Transit.errorPage('Error Loading Route', message) @trips = new Transit.Collections.Trips(@model) @trips.fetch success: @showTrips @tripTimer = setInterval (=> @trips.fetch(success: @showTrips)), 30000 # Transit.events.on 'route:complete', @render favorite: -> { name: "#{@model.get('name')}" type: 'route' url: "routes/#{@model.get('oba_id')}" } render: => $(@el).html(@template(route: @model)) Transit.setTitleHTML Transit.Favorites.icon(@model.get('name')), HTML.btn('btn-route', @model.get('name')), @model.get('description') @polylines = Transit.map.create_multi_polyline(@model.get('polylines').split(','), '#025d8c') Transit.map.addLayer @polylines @stopMarkers = [] for stop in @model.get('stops') pos = new G.LatLng(stop['lat'], stop['lon']) @stopMarkers.push Transit.map.create_marker(stop['name'] + " (#{stop['direction']})", pos, Transit.GMarkers.StopDot, false, true) if bounds? then bounds.extend(pos) else bounds = new G.LatLngBounds(pos) Transit.map.map.fitBounds(bounds) Transit.map.addLayer(@stopMarkers) this showTrips: => list = $("#trips").html('') @trips.forEach (item) => list.append(@tripTemplate(trip: item)) key = "PI:KEY:<KEY>END_PI#{item.get('vehiclePI:KEY:<KEY>END_PI')}" pos = Transit.map.latlng item.get('position') if Transit.map.hasMarker key then Transit.map.moveMarker key, pos else Transit.map.addMarker key, "Vehicle #{item.get('vehicleId')}", pos, Transit.GMarkers.Bus, false, true, G.Animation.DROP
[ { "context": "\n options {\n dependentKeys: ['customer_id', 'job_id', 'campaign_id']\n args: ['${", "end": 3665, "score": 0.9985998272895813, "start": 3654, "tag": "KEY", "value": "customer_id" }, { "context": "ons {\n dependentKeys: ['customer_id', 'job_id', 'campaign_id']\n args: ['${campaign_i", "end": 3675, "score": 0.9733811020851135, "start": 3669, "tag": "KEY", "value": "job_id" }, { "context": " dependentKeys: ['customer_id', 'job_id', 'campaign_id']\n args: ['${campaign_id}', '${custome", "end": 3690, "score": 0.9373760223388672, "start": 3679, "tag": "KEY", "value": "campaign_id" } ]
src/controls/mixins/DataSourced.coffee
vedantchoubey098/react-form-builder
44
React = require 'react' shallowEqual = require('shallowequal') tap = require("lodash/tap") keys = require("lodash/keys") difference = require("lodash/difference") clone = require("lodash/clone") each = require("lodash/each") capitalize = require("lodash/capitalize") # # For each data source: # * sets a value on the state with "{dataSourceName}" as key # * sets a loading on the state with "{dataSourceName}Loading" as key # * loadDataSource(name, props, ) # DataSourcedMixin = propTypes: dataSources: React.PropTypes.object.isRequired getInitialState: -> tap {}, (state) => for name, dataSource of @props.dataSources state[@loadingStateKey(name)] = false state[name] = dataSource.initial if 'initial' of dataSource componentDidMount: -> for name, dataSource of @props.dataSources @loadDataSource(name, @props.dependencies) componentWillReceiveProps: (nextProps) -> for name, dataSource of @props.dataSources if dataSource.dependentKeys? && dataSource.type is 'service' && !shallowEqual(nextProps.dependencies, @props.dependencies) @loadDataSource(name, nextProps.dependencies) # # Public: Loads data for a dataSource # loadDataSource: (dataSourceName, dependencies) -> dataSource = @props.dataSources[dataSourceName] switch dataSource.type when 'service' missingDependencies = difference(dataSource.dependentKeys, keys(dependencies)) if missingDependencies.length > 0 return else @handleService dataSourceName, @tokenizeArgs(dependencies, dataSource.args ? []) when 'inline' @updateDataSource(dataSourceName, dataSource.data) else throw new Error("dataSource.type #{dataSource.type} is not a valid data source.") # # Updates data source # updateDataSource: (dataSourceName, data) -> update = {} update[dataSourceName] = @applyAdapter(@props.dataSources[dataSourceName], data) @setState(update) # # Loads a data source if all it's data dependencies have been met # handleService: (dataSourceName, args) -> dataSource = @props.dataSources[dataSourceName] @loadingDataSource dataSourceName, => options = complete: => @doneLoadingDataSource(dataSourceName) if @isMounted() success: (resp) => @updateDataSource(dataSourceName, resp) if @isMounted() if args.length > 0 dataSource.service args, options else dataSource.service options # # Each data source maps to a key and a loading key in the state # e.g.: dataSource = { name: "options" } # @state.options = [] # @state.loadingOptions = false # loadingStateKey: (dataSourceName) -> "loading" + capitalize(dataSourceName) # # Set corresponding loading state for a data source # loadingDataSource: (dataSourceName, cb) -> update = {} update[@loadingStateKey(dataSourceName)] = true @setState(update, cb) # # Unset corresponding loading state for a data source doneLoadingDataSource: (dataSourceName) -> update = {} update[@loadingStateKey(dataSourceName)] = false @setState(update) # # Applies the adapter to the dataSource if any # applyAdapter: (dataSource, data) -> if dataSource.adapter dataSource.adapter data else data ### This will loop through the service args list pulling out values that are of the form: ${dependent_key} and replacing them with the associated value for that dependent key. Ex: Data source in the form defintion: dataSources: { options { dependentKeys: ['customer_id', 'job_id', 'campaign_id'] args: ['${campaign_id}', '${customer_id}', '${job_id}', 66] ... } } Dependencies hash passed into the component: { customer_id: 44, job_id: 123, campaign_id: 99 } Results in the following args list: [99, 44, 123, 66] ### tokenizeArgs: (dependencies, args) -> tokenizedArgs = clone args each args, (argument, index) => if typeof argument is 'string' and argument.substr(0, 2) == '${' key = argument.substr(2, argument.length - 3) tokenizedArgs[index] = dependencies[key] else tokenizedArgs[index] = argument tokenizedArgs module.exports = DataSourcedMixin
65821
React = require 'react' shallowEqual = require('shallowequal') tap = require("lodash/tap") keys = require("lodash/keys") difference = require("lodash/difference") clone = require("lodash/clone") each = require("lodash/each") capitalize = require("lodash/capitalize") # # For each data source: # * sets a value on the state with "{dataSourceName}" as key # * sets a loading on the state with "{dataSourceName}Loading" as key # * loadDataSource(name, props, ) # DataSourcedMixin = propTypes: dataSources: React.PropTypes.object.isRequired getInitialState: -> tap {}, (state) => for name, dataSource of @props.dataSources state[@loadingStateKey(name)] = false state[name] = dataSource.initial if 'initial' of dataSource componentDidMount: -> for name, dataSource of @props.dataSources @loadDataSource(name, @props.dependencies) componentWillReceiveProps: (nextProps) -> for name, dataSource of @props.dataSources if dataSource.dependentKeys? && dataSource.type is 'service' && !shallowEqual(nextProps.dependencies, @props.dependencies) @loadDataSource(name, nextProps.dependencies) # # Public: Loads data for a dataSource # loadDataSource: (dataSourceName, dependencies) -> dataSource = @props.dataSources[dataSourceName] switch dataSource.type when 'service' missingDependencies = difference(dataSource.dependentKeys, keys(dependencies)) if missingDependencies.length > 0 return else @handleService dataSourceName, @tokenizeArgs(dependencies, dataSource.args ? []) when 'inline' @updateDataSource(dataSourceName, dataSource.data) else throw new Error("dataSource.type #{dataSource.type} is not a valid data source.") # # Updates data source # updateDataSource: (dataSourceName, data) -> update = {} update[dataSourceName] = @applyAdapter(@props.dataSources[dataSourceName], data) @setState(update) # # Loads a data source if all it's data dependencies have been met # handleService: (dataSourceName, args) -> dataSource = @props.dataSources[dataSourceName] @loadingDataSource dataSourceName, => options = complete: => @doneLoadingDataSource(dataSourceName) if @isMounted() success: (resp) => @updateDataSource(dataSourceName, resp) if @isMounted() if args.length > 0 dataSource.service args, options else dataSource.service options # # Each data source maps to a key and a loading key in the state # e.g.: dataSource = { name: "options" } # @state.options = [] # @state.loadingOptions = false # loadingStateKey: (dataSourceName) -> "loading" + capitalize(dataSourceName) # # Set corresponding loading state for a data source # loadingDataSource: (dataSourceName, cb) -> update = {} update[@loadingStateKey(dataSourceName)] = true @setState(update, cb) # # Unset corresponding loading state for a data source doneLoadingDataSource: (dataSourceName) -> update = {} update[@loadingStateKey(dataSourceName)] = false @setState(update) # # Applies the adapter to the dataSource if any # applyAdapter: (dataSource, data) -> if dataSource.adapter dataSource.adapter data else data ### This will loop through the service args list pulling out values that are of the form: ${dependent_key} and replacing them with the associated value for that dependent key. Ex: Data source in the form defintion: dataSources: { options { dependentKeys: ['<KEY>', '<KEY>', '<KEY>'] args: ['${campaign_id}', '${customer_id}', '${job_id}', 66] ... } } Dependencies hash passed into the component: { customer_id: 44, job_id: 123, campaign_id: 99 } Results in the following args list: [99, 44, 123, 66] ### tokenizeArgs: (dependencies, args) -> tokenizedArgs = clone args each args, (argument, index) => if typeof argument is 'string' and argument.substr(0, 2) == '${' key = argument.substr(2, argument.length - 3) tokenizedArgs[index] = dependencies[key] else tokenizedArgs[index] = argument tokenizedArgs module.exports = DataSourcedMixin
true
React = require 'react' shallowEqual = require('shallowequal') tap = require("lodash/tap") keys = require("lodash/keys") difference = require("lodash/difference") clone = require("lodash/clone") each = require("lodash/each") capitalize = require("lodash/capitalize") # # For each data source: # * sets a value on the state with "{dataSourceName}" as key # * sets a loading on the state with "{dataSourceName}Loading" as key # * loadDataSource(name, props, ) # DataSourcedMixin = propTypes: dataSources: React.PropTypes.object.isRequired getInitialState: -> tap {}, (state) => for name, dataSource of @props.dataSources state[@loadingStateKey(name)] = false state[name] = dataSource.initial if 'initial' of dataSource componentDidMount: -> for name, dataSource of @props.dataSources @loadDataSource(name, @props.dependencies) componentWillReceiveProps: (nextProps) -> for name, dataSource of @props.dataSources if dataSource.dependentKeys? && dataSource.type is 'service' && !shallowEqual(nextProps.dependencies, @props.dependencies) @loadDataSource(name, nextProps.dependencies) # # Public: Loads data for a dataSource # loadDataSource: (dataSourceName, dependencies) -> dataSource = @props.dataSources[dataSourceName] switch dataSource.type when 'service' missingDependencies = difference(dataSource.dependentKeys, keys(dependencies)) if missingDependencies.length > 0 return else @handleService dataSourceName, @tokenizeArgs(dependencies, dataSource.args ? []) when 'inline' @updateDataSource(dataSourceName, dataSource.data) else throw new Error("dataSource.type #{dataSource.type} is not a valid data source.") # # Updates data source # updateDataSource: (dataSourceName, data) -> update = {} update[dataSourceName] = @applyAdapter(@props.dataSources[dataSourceName], data) @setState(update) # # Loads a data source if all it's data dependencies have been met # handleService: (dataSourceName, args) -> dataSource = @props.dataSources[dataSourceName] @loadingDataSource dataSourceName, => options = complete: => @doneLoadingDataSource(dataSourceName) if @isMounted() success: (resp) => @updateDataSource(dataSourceName, resp) if @isMounted() if args.length > 0 dataSource.service args, options else dataSource.service options # # Each data source maps to a key and a loading key in the state # e.g.: dataSource = { name: "options" } # @state.options = [] # @state.loadingOptions = false # loadingStateKey: (dataSourceName) -> "loading" + capitalize(dataSourceName) # # Set corresponding loading state for a data source # loadingDataSource: (dataSourceName, cb) -> update = {} update[@loadingStateKey(dataSourceName)] = true @setState(update, cb) # # Unset corresponding loading state for a data source doneLoadingDataSource: (dataSourceName) -> update = {} update[@loadingStateKey(dataSourceName)] = false @setState(update) # # Applies the adapter to the dataSource if any # applyAdapter: (dataSource, data) -> if dataSource.adapter dataSource.adapter data else data ### This will loop through the service args list pulling out values that are of the form: ${dependent_key} and replacing them with the associated value for that dependent key. Ex: Data source in the form defintion: dataSources: { options { dependentKeys: ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'] args: ['${campaign_id}', '${customer_id}', '${job_id}', 66] ... } } Dependencies hash passed into the component: { customer_id: 44, job_id: 123, campaign_id: 99 } Results in the following args list: [99, 44, 123, 66] ### tokenizeArgs: (dependencies, args) -> tokenizedArgs = clone args each args, (argument, index) => if typeof argument is 'string' and argument.substr(0, 2) == '${' key = argument.substr(2, argument.length - 3) tokenizedArgs[index] = dependencies[key] else tokenizedArgs[index] = argument tokenizedArgs module.exports = DataSourcedMixin
[ { "context": "# name: coffeelint.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈", "end": 37, "score": 0.9998903870582581, "start": 34, "tag": "NAME", "value": "沈维忠" }, { "context": "# name: coffeelint.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizho", "end": 53, "score": 0.9998326301574707, "start": 40, "tag": "NAME", "value": "Shen Weizhong" }, { "context": "e: coffeelint.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizhong / Tony Sta", "end": 66, "score": 0.9992896318435669, "start": 56, "tag": "NAME", "value": "Tony Stark" }, { "context": "维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizhong / Tony Stark )\n\n\n\n'use strict'\n\n\n", "end": 89, "score": 0.998647153377533, "start": 86, "tag": "NAME", "value": "沈维忠" }, { "context": "hen Weizhong / Tony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizhong / Tony Stark )\n\n\n\n'use strict'\n\n\n\ncfg = requ", "end": 105, "score": 0.9998404383659363, "start": 92, "tag": "NAME", "value": "Shen Weizhong" }, { "context": "ony Stark )\n#\n# Last Update: 沈维忠 ( Shen Weizhong / Tony Stark )\n\n\n\n'use strict'\n\n\n\ncfg = require '../confi", "end": 118, "score": 0.9979104399681091, "start": 108, "tag": "NAME", "value": "Tony Stark" } ]
dev/splited_tasks_for_gulp/coffeelint.coffee
gitter-badger/is-object-brace
0
# name: coffeelint.js # # author: 沈维忠 ( Shen Weizhong / Tony Stark ) # # Last Update: 沈维忠 ( Shen Weizhong / Tony Stark ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'coffeelint', -> gulp.src cfg.path.dev + 'is.object.brace.coffee' .pipe $.coffeelint 'coffeelint.json' .pipe $.coffeelint.reporter() .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'CoffeeScript' message: cfg.message.coffeelint
130616
# name: coffeelint.js # # author: <NAME> ( <NAME> / <NAME> ) # # Last Update: <NAME> ( <NAME> / <NAME> ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'coffeelint', -> gulp.src cfg.path.dev + 'is.object.brace.coffee' .pipe $.coffeelint 'coffeelint.json' .pipe $.coffeelint.reporter() .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'CoffeeScript' message: cfg.message.coffeelint
true
# name: coffeelint.js # # author: PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) # # Last Update: PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'coffeelint', -> gulp.src cfg.path.dev + 'is.object.brace.coffee' .pipe $.coffeelint 'coffeelint.json' .pipe $.coffeelint.reporter() .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'CoffeeScript' message: cfg.message.coffeelint
[ { "context": "se it's been minified to \"n\"\n foreign_key = \"#{_.singularize(@constructor.to_s().toLowerCase())}_id\"\n if @constructor._object_id\n selecto", "end": 2728, "score": 0.8920518159866333, "start": 2673, "tag": "KEY", "value": "\"#{_.singularize(@constructor.to_s().toLowerCase())}_id" }, { "context": "gn_key = has_one.foreign_key\n foreign_key = \"#{_.singularize(@constructor.to_s().toLowerCase())}_id\"\n if @constructor._object_id\n selecto", "end": 3685, "score": 0.8533958196640015, "start": 3630, "tag": "KEY", "value": "\"#{_.singularize(@constructor.to_s().toLowerCase())}_id" }, { "context": "ified to \"n\"\n foreign_key = \"#{_.singularize(@constructor.to_s().toLowerCase())}_id\"\n i", "end": 6720, "score": 0.5277964472770691, "start": 6717, "tag": "KEY", "value": "ize" }, { "context": "#{_.singularize(@constructor.to_s().toLowerCase())}_id\"\n if @constructor._object_id\n sel", "end": 6759, "score": 0.8702145218849182, "start": 6757, "tag": "KEY", "value": "id" } ]
lib/minimongoid.coffee
tianfranco/uno
50
global = @ class @Minimongoid # --- instance vars id: undefined errors: false # attr: {} # --- instance methods constructor: (attr = {}, parent = null, is_new = true) -> @__is_new = !!is_new if attr._id if @constructor._object_id @id = attr._id._str else @id = attr._id @_id = @id @initAttrsAndRelations(attr, parent) # this function sets up all of the attributes to be stored on the model as well as # setting up the relation methods initAttrsAndRelations: (attr = {}, parent = null) -> # initialize relation arrays to be an empty array, if they don't exist for habtm in @constructor.has_and_belongs_to_many # e.g. matchup.game_ids = [] identifier = "#{_.singularize(habtm.name)}_ids" @[identifier] ||= [] # initialize relation arrays to be an empty array, if they don't exist for embeds_many in @constructor.embeds_many @[embeds_many.name] ||= [] if @constructor.embedded_in and parent @[@constructor.embedded_in] = parent # load in all the passed attrs for name, value of attr continue if name.match(/^_id/) if name.match(/_id$/) and (value instanceof Meteor.Collection.ObjectID) @[name] = value._str else if (embeds_many = _.findWhere(@constructor.embeds_many, {name: name})) # initialize a model with the appropriate attributes # also pass "self" along as the parent model class_name = embeds_many.class_name || _.classify(_.singularize(name)) @[name] = global[class_name].modelize(value, @) else @[name] = value # load in defaults for own attr, val of @constructor.defaults @[attr] = val if typeof @[attr] is 'undefined' self = @ # set up belongs_to methods, e.g. recipe.user() for belongs_to in @constructor.belongs_to relation = belongs_to.name identifier = belongs_to.identifier || "#{relation}_id" # set up default class name, e.g. "belongs_to: user" ==> 'User' class_name = belongs_to.class_name || _.titleize(relation) @[relation] = do(relation, identifier, class_name) -> (options = {}) -> # if we have a relation_id if global[class_name] and self[identifier] return global[class_name].find self[identifier], options else return false # set up has_many methods, e.g. user.recipes() for has_many in @constructor.has_many relation = has_many.name selector = {} unless foreign_key = has_many.foreign_key # can't use @constructor.name in production because it's been minified to "n" foreign_key = "#{_.singularize(@constructor.to_s().toLowerCase())}_id" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_many: users" ==> 'User' class_name = has_many.class_name || _.titleize(_.singularize(relation)) @[relation] = do(relation, selector, class_name) -> (mod_selector = {}, options = {}) -> # first consider any passed in selector options mod_selector = _.extend mod_selector, selector # e.g. where {user_id: @id} if global[class_name] HasManyRelation.fromRelation(global[class_name].where(mod_selector, options), foreign_key, @id) # set up has_one methods, e.g. user.recipes() for has_one in @constructor.has_one relation = has_one.name selector = {} unless foreign_key = has_one.foreign_key foreign_key = "#{_.singularize(@constructor.to_s().toLowerCase())}_id" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_one: user" ==> 'User' class_name = has_one.class_name || _.titleize(relation) @[relation] = do(relation, selector, class_name) -> (mod_selector = {}, options = {}) -> # first consider any passed in selector options mod_selector = _.extend mod_selector, selector # e.g. where {user_id: @id} if global[class_name] global[class_name].first(mod_selector, options) # set up HABTM methods, e.g. user.friends() for habtm in @constructor.has_and_belongs_to_many relation = habtm.name identifier = "#{_.singularize(relation)}_ids" # set up default class name, e.g. "habtm: users" ==> 'User' class_name = habtm.class_name || _.titleize(_.singularize(relation)) @[relation] = do(relation, identifier, class_name) -> (mod_selector = {}, options = {}) -> selector = {_id: {$in: self[identifier]}} # first consider any passed in selector options mod_selector = _.extend mod_selector, selector instance = global[class_name].init() filter = (r) -> name = r.class_name || _.titleize(_.singularize(r.name)) global[name] == this.constructor inverse = _.find instance.constructor.has_and_belongs_to_many, filter, @ inverse_identifier = "#{_.singularize(inverse.name)}_ids" if global[class_name] and self[identifier] and self[identifier].length relation = global[class_name].where mod_selector, options return HasAndBelongsToManyRelation.fromRelation(relation, @, inverse_identifier, identifier, @id) else return HasAndBelongsToManyRelation.new(@, global[class_name], inverse_identifier, identifier, @id) # /-------------------- # DEPRECATED: r() and related() methods # Also does not support has_one. # -------------------- # alias to @related r: (relation) -> @related(relation) # look up related models related: (relation, options = {}) -> # self = @ # is it a belongs_to? for belongs_to in @constructor.belongs_to if relation == belongs_to.name identifier = "#{belongs_to.name}_id" # set up default class name, e.g. "belongs_to: user" ==> 'User' unless belongs_to.class_name belongs_to.class_name = _.titleize belongs_to.name # if we have a relation_id if @[identifier] return global[belongs_to.class_name].find @[identifier], options else return false # is it a has many? for has_many in @constructor.has_many if relation == has_many.name selector = {} unless foreign_key = has_many.foreign_key # can't use @constructor.name in production because it's been minified to "n" foreign_key = "#{_.singularize(@constructor.to_s().toLowerCase())}_id" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_many: users" ==> 'User' unless has_many.class_name has_many.class_name = _.titleize _.singularize(has_many.name) # e.g. where {user_id: @id} return global[has_many.class_name].where selector, options # is it a has many? (same as HABTM) for habtm in @constructor.has_and_belongs_to_many if relation == habtm.name identifier = "#{_.singularize(habtm.name)}_ids" # set up default class name, e.g. "habtm: users" ==> 'User' unless habtm.class_name habtm.class_name = _.titleize _.singularize(habtm.name) if @[identifier] and @[identifier].length return global[habtm.class_name].where {_id: {$in: @[identifier]}}, options else return [] # if we get here, means method not found console.warn "Method #{relation} does not exist for #{@constructor.to_s()}." # isPersisted: -> @id? # ------------------- # --------------------/ error: (field, message) -> @errors ||= [] obj = {} obj[field] = message @errors.push obj isValid: (attr = {}) -> @validate() not @errors # nothing by default validate: -> # if blah then @errors.blah = 'no, bad!' else @errors = false true is_new: () -> @isNew() isNew: () -> @__is_new save: (attr = {}, callback = undefined) -> # reset errors before running isValid() @errors = false for k,v of attr @[k] = v attr = @constructor.before_save(attr) if @constructor.before_save return @ if not @isValid() # attr['_type'] = @constructor._type if @constructor._type? if callback? if @isNew() @constructor._collection.insert( attr, ((error, result) => unless error? @id = @_id = result @__is_new = false if @constructor.after_save @constructor.after_save(@) callback(error, result) )) else @constructor._collection.update( @id, { $set: attr }, ((error, result) => unless error? if @constructor.after_save @constructor.after_save(@) callback(error, result) )) return null else if @isNew() @id = @_id = @constructor._collection.insert( attr ) @__is_new = false else @constructor._collection.update( @id, { $set: attr } ) if @constructor.after_save @constructor.after_save(@) return @ update: (attr, callback = undefined) -> @save(attr, callback) # push to mongo array field push: (data) -> # TODO: should maybe do something like this; but it should know if we're pushing an embedded model and instantiate it... # for name, value of data # # update locally # @[name].push value # addToSet to ensure uniqueness -- can't think of if/when we WOULDN'T want that?? @constructor._collection.update @id, {$addToSet: data} # pull from mongo array field pull: (data) -> @constructor._collection.update @id, {$pull: data} del: (field) -> unset = {} unset[field] = "" @constructor._collection.update @id, {$unset: unset} destroy: (callback = undefined) -> if @id? @constructor._collection.remove( @id, callback ) @id = @_id = null reload: -> if @id? @constructor.find(@id) # --- class variables @_object_id: false @_collection: undefined @_type: undefined @_debug: false @defaults: [] @belongs_to: [] @has_many: [] @has_one: [] @has_and_belongs_to_many: [] @embedded_in: null @embeds_many: [] # @after_save: null # @before_save: null # @before_create: null # @after_create: null # --- class methods @init: (attr, parent = null, is_new = false) -> new @(attr, parent, is_new) @to_s: -> if @_collection then @_collection._name else "embedded" @create: (attr, callback = undefined) -> attr.createdAt ||= new Date() attr = @before_create(attr) if @before_create doc = @init(attr, null, true) if callback? doc.save(attr, callback) null else doc = doc.save(attr) doc.initAttrsAndRelations(attr) if doc and @after_create @after_create(doc) else doc # find + modelize @where: (selector = {}, options = {}) -> self = @ if @_debug console.info " --- WHERE ---" console.info " #{_.singularize _.classify @to_s()}.where(#{JSON.stringify selector}#{if not _.isEmpty options then ','+JSON.stringify options else ''})" result = @find(selector, options).fetch() result = Relation.new self, result... result.setQuery selector console.info " > found #{result.length}" if @_debug and result result @first: (selector = {}, options = {}) -> if @_debug console.info " --- FIRST ---" console.info " #{_.singularize _.classify @to_s()}.first(#{JSON.stringify selector}#{if not _.isEmpty options then ','+JSON.stringify options else ''})" if doc = @_collection.findOne(selector, options) @init doc # kind of a silly method, just does a findOne with reverse sort on createdAt @last: (selector = {}, options = {}) -> options.sort = createdAt: -1 if doc = @_collection.findOne(selector, options) @init doc @all: (options = {}) -> @where({}, options) # this doesn't perform a fetch, just generates a collection cursor @find: (selector = {}, options = {}) -> self = @ # ***Important!*** Transform all docs in the collection to be an instance of our model unless options.transform options.transform = (doc) -> self.init(doc) # unless you just pass an id, in which case it *does* fetch the first unless typeof selector == 'object' if @_object_id selector = new Meteor.Collection.ObjectID selector @first {_id: selector}, options else if selector instanceof Meteor.Collection.ObjectID @first {_id: selector}, options else # handle objectIDs -- these would come from an external database entry e.g. Rails if @_object_id if selector and selector._id if typeof selector._id is 'string' selector._id = new Meteor.Collection.ObjectID selector._id else if selector._id['$in'] # _.map(game_ids, function(x) { return new Meteor.Collection.ObjectID(x) }) selector._id['$in'] = _.map_object_id selector._id['$in'] if selector and selector._ids selector._ids = _.map(selector._ids, (id) -> new Meteor.Collection.ObjectID id) @_collection.find selector, options @count: (selector = {}, options = {}) -> @find(selector, options).count() @destroyAll: (selector = {}) -> @_collection.remove(selector) # run a model init on all items in the collection # -- somewhat deprecated -- used to be used in @where function, which is replaced by the transform inside of @find @modelize: (cursor, parent = null) -> self = @ models = cursor.map (i) -> self.init(i, parent) Relation.new self, models... # for some reason underscore.inflection stopped working with Meteor 0.6.5. # so for now we just use this simple singularize method instead of including the library _.singularize = (s) -> s = s.replace /s$/, ""
135203
global = @ class @Minimongoid # --- instance vars id: undefined errors: false # attr: {} # --- instance methods constructor: (attr = {}, parent = null, is_new = true) -> @__is_new = !!is_new if attr._id if @constructor._object_id @id = attr._id._str else @id = attr._id @_id = @id @initAttrsAndRelations(attr, parent) # this function sets up all of the attributes to be stored on the model as well as # setting up the relation methods initAttrsAndRelations: (attr = {}, parent = null) -> # initialize relation arrays to be an empty array, if they don't exist for habtm in @constructor.has_and_belongs_to_many # e.g. matchup.game_ids = [] identifier = "#{_.singularize(habtm.name)}_ids" @[identifier] ||= [] # initialize relation arrays to be an empty array, if they don't exist for embeds_many in @constructor.embeds_many @[embeds_many.name] ||= [] if @constructor.embedded_in and parent @[@constructor.embedded_in] = parent # load in all the passed attrs for name, value of attr continue if name.match(/^_id/) if name.match(/_id$/) and (value instanceof Meteor.Collection.ObjectID) @[name] = value._str else if (embeds_many = _.findWhere(@constructor.embeds_many, {name: name})) # initialize a model with the appropriate attributes # also pass "self" along as the parent model class_name = embeds_many.class_name || _.classify(_.singularize(name)) @[name] = global[class_name].modelize(value, @) else @[name] = value # load in defaults for own attr, val of @constructor.defaults @[attr] = val if typeof @[attr] is 'undefined' self = @ # set up belongs_to methods, e.g. recipe.user() for belongs_to in @constructor.belongs_to relation = belongs_to.name identifier = belongs_to.identifier || "#{relation}_id" # set up default class name, e.g. "belongs_to: user" ==> 'User' class_name = belongs_to.class_name || _.titleize(relation) @[relation] = do(relation, identifier, class_name) -> (options = {}) -> # if we have a relation_id if global[class_name] and self[identifier] return global[class_name].find self[identifier], options else return false # set up has_many methods, e.g. user.recipes() for has_many in @constructor.has_many relation = has_many.name selector = {} unless foreign_key = has_many.foreign_key # can't use @constructor.name in production because it's been minified to "n" foreign_key = <KEY>" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_many: users" ==> 'User' class_name = has_many.class_name || _.titleize(_.singularize(relation)) @[relation] = do(relation, selector, class_name) -> (mod_selector = {}, options = {}) -> # first consider any passed in selector options mod_selector = _.extend mod_selector, selector # e.g. where {user_id: @id} if global[class_name] HasManyRelation.fromRelation(global[class_name].where(mod_selector, options), foreign_key, @id) # set up has_one methods, e.g. user.recipes() for has_one in @constructor.has_one relation = has_one.name selector = {} unless foreign_key = has_one.foreign_key foreign_key = <KEY>" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_one: user" ==> 'User' class_name = has_one.class_name || _.titleize(relation) @[relation] = do(relation, selector, class_name) -> (mod_selector = {}, options = {}) -> # first consider any passed in selector options mod_selector = _.extend mod_selector, selector # e.g. where {user_id: @id} if global[class_name] global[class_name].first(mod_selector, options) # set up HABTM methods, e.g. user.friends() for habtm in @constructor.has_and_belongs_to_many relation = habtm.name identifier = "#{_.singularize(relation)}_ids" # set up default class name, e.g. "habtm: users" ==> 'User' class_name = habtm.class_name || _.titleize(_.singularize(relation)) @[relation] = do(relation, identifier, class_name) -> (mod_selector = {}, options = {}) -> selector = {_id: {$in: self[identifier]}} # first consider any passed in selector options mod_selector = _.extend mod_selector, selector instance = global[class_name].init() filter = (r) -> name = r.class_name || _.titleize(_.singularize(r.name)) global[name] == this.constructor inverse = _.find instance.constructor.has_and_belongs_to_many, filter, @ inverse_identifier = "#{_.singularize(inverse.name)}_ids" if global[class_name] and self[identifier] and self[identifier].length relation = global[class_name].where mod_selector, options return HasAndBelongsToManyRelation.fromRelation(relation, @, inverse_identifier, identifier, @id) else return HasAndBelongsToManyRelation.new(@, global[class_name], inverse_identifier, identifier, @id) # /-------------------- # DEPRECATED: r() and related() methods # Also does not support has_one. # -------------------- # alias to @related r: (relation) -> @related(relation) # look up related models related: (relation, options = {}) -> # self = @ # is it a belongs_to? for belongs_to in @constructor.belongs_to if relation == belongs_to.name identifier = "#{belongs_to.name}_id" # set up default class name, e.g. "belongs_to: user" ==> 'User' unless belongs_to.class_name belongs_to.class_name = _.titleize belongs_to.name # if we have a relation_id if @[identifier] return global[belongs_to.class_name].find @[identifier], options else return false # is it a has many? for has_many in @constructor.has_many if relation == has_many.name selector = {} unless foreign_key = has_many.foreign_key # can't use @constructor.name in production because it's been minified to "n" foreign_key = "#{_.singular<KEY>(@constructor.to_s().toLowerCase())}_<KEY>" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_many: users" ==> 'User' unless has_many.class_name has_many.class_name = _.titleize _.singularize(has_many.name) # e.g. where {user_id: @id} return global[has_many.class_name].where selector, options # is it a has many? (same as HABTM) for habtm in @constructor.has_and_belongs_to_many if relation == habtm.name identifier = "#{_.singularize(habtm.name)}_ids" # set up default class name, e.g. "habtm: users" ==> 'User' unless habtm.class_name habtm.class_name = _.titleize _.singularize(habtm.name) if @[identifier] and @[identifier].length return global[habtm.class_name].where {_id: {$in: @[identifier]}}, options else return [] # if we get here, means method not found console.warn "Method #{relation} does not exist for #{@constructor.to_s()}." # isPersisted: -> @id? # ------------------- # --------------------/ error: (field, message) -> @errors ||= [] obj = {} obj[field] = message @errors.push obj isValid: (attr = {}) -> @validate() not @errors # nothing by default validate: -> # if blah then @errors.blah = 'no, bad!' else @errors = false true is_new: () -> @isNew() isNew: () -> @__is_new save: (attr = {}, callback = undefined) -> # reset errors before running isValid() @errors = false for k,v of attr @[k] = v attr = @constructor.before_save(attr) if @constructor.before_save return @ if not @isValid() # attr['_type'] = @constructor._type if @constructor._type? if callback? if @isNew() @constructor._collection.insert( attr, ((error, result) => unless error? @id = @_id = result @__is_new = false if @constructor.after_save @constructor.after_save(@) callback(error, result) )) else @constructor._collection.update( @id, { $set: attr }, ((error, result) => unless error? if @constructor.after_save @constructor.after_save(@) callback(error, result) )) return null else if @isNew() @id = @_id = @constructor._collection.insert( attr ) @__is_new = false else @constructor._collection.update( @id, { $set: attr } ) if @constructor.after_save @constructor.after_save(@) return @ update: (attr, callback = undefined) -> @save(attr, callback) # push to mongo array field push: (data) -> # TODO: should maybe do something like this; but it should know if we're pushing an embedded model and instantiate it... # for name, value of data # # update locally # @[name].push value # addToSet to ensure uniqueness -- can't think of if/when we WOULDN'T want that?? @constructor._collection.update @id, {$addToSet: data} # pull from mongo array field pull: (data) -> @constructor._collection.update @id, {$pull: data} del: (field) -> unset = {} unset[field] = "" @constructor._collection.update @id, {$unset: unset} destroy: (callback = undefined) -> if @id? @constructor._collection.remove( @id, callback ) @id = @_id = null reload: -> if @id? @constructor.find(@id) # --- class variables @_object_id: false @_collection: undefined @_type: undefined @_debug: false @defaults: [] @belongs_to: [] @has_many: [] @has_one: [] @has_and_belongs_to_many: [] @embedded_in: null @embeds_many: [] # @after_save: null # @before_save: null # @before_create: null # @after_create: null # --- class methods @init: (attr, parent = null, is_new = false) -> new @(attr, parent, is_new) @to_s: -> if @_collection then @_collection._name else "embedded" @create: (attr, callback = undefined) -> attr.createdAt ||= new Date() attr = @before_create(attr) if @before_create doc = @init(attr, null, true) if callback? doc.save(attr, callback) null else doc = doc.save(attr) doc.initAttrsAndRelations(attr) if doc and @after_create @after_create(doc) else doc # find + modelize @where: (selector = {}, options = {}) -> self = @ if @_debug console.info " --- WHERE ---" console.info " #{_.singularize _.classify @to_s()}.where(#{JSON.stringify selector}#{if not _.isEmpty options then ','+JSON.stringify options else ''})" result = @find(selector, options).fetch() result = Relation.new self, result... result.setQuery selector console.info " > found #{result.length}" if @_debug and result result @first: (selector = {}, options = {}) -> if @_debug console.info " --- FIRST ---" console.info " #{_.singularize _.classify @to_s()}.first(#{JSON.stringify selector}#{if not _.isEmpty options then ','+JSON.stringify options else ''})" if doc = @_collection.findOne(selector, options) @init doc # kind of a silly method, just does a findOne with reverse sort on createdAt @last: (selector = {}, options = {}) -> options.sort = createdAt: -1 if doc = @_collection.findOne(selector, options) @init doc @all: (options = {}) -> @where({}, options) # this doesn't perform a fetch, just generates a collection cursor @find: (selector = {}, options = {}) -> self = @ # ***Important!*** Transform all docs in the collection to be an instance of our model unless options.transform options.transform = (doc) -> self.init(doc) # unless you just pass an id, in which case it *does* fetch the first unless typeof selector == 'object' if @_object_id selector = new Meteor.Collection.ObjectID selector @first {_id: selector}, options else if selector instanceof Meteor.Collection.ObjectID @first {_id: selector}, options else # handle objectIDs -- these would come from an external database entry e.g. Rails if @_object_id if selector and selector._id if typeof selector._id is 'string' selector._id = new Meteor.Collection.ObjectID selector._id else if selector._id['$in'] # _.map(game_ids, function(x) { return new Meteor.Collection.ObjectID(x) }) selector._id['$in'] = _.map_object_id selector._id['$in'] if selector and selector._ids selector._ids = _.map(selector._ids, (id) -> new Meteor.Collection.ObjectID id) @_collection.find selector, options @count: (selector = {}, options = {}) -> @find(selector, options).count() @destroyAll: (selector = {}) -> @_collection.remove(selector) # run a model init on all items in the collection # -- somewhat deprecated -- used to be used in @where function, which is replaced by the transform inside of @find @modelize: (cursor, parent = null) -> self = @ models = cursor.map (i) -> self.init(i, parent) Relation.new self, models... # for some reason underscore.inflection stopped working with Meteor 0.6.5. # so for now we just use this simple singularize method instead of including the library _.singularize = (s) -> s = s.replace /s$/, ""
true
global = @ class @Minimongoid # --- instance vars id: undefined errors: false # attr: {} # --- instance methods constructor: (attr = {}, parent = null, is_new = true) -> @__is_new = !!is_new if attr._id if @constructor._object_id @id = attr._id._str else @id = attr._id @_id = @id @initAttrsAndRelations(attr, parent) # this function sets up all of the attributes to be stored on the model as well as # setting up the relation methods initAttrsAndRelations: (attr = {}, parent = null) -> # initialize relation arrays to be an empty array, if they don't exist for habtm in @constructor.has_and_belongs_to_many # e.g. matchup.game_ids = [] identifier = "#{_.singularize(habtm.name)}_ids" @[identifier] ||= [] # initialize relation arrays to be an empty array, if they don't exist for embeds_many in @constructor.embeds_many @[embeds_many.name] ||= [] if @constructor.embedded_in and parent @[@constructor.embedded_in] = parent # load in all the passed attrs for name, value of attr continue if name.match(/^_id/) if name.match(/_id$/) and (value instanceof Meteor.Collection.ObjectID) @[name] = value._str else if (embeds_many = _.findWhere(@constructor.embeds_many, {name: name})) # initialize a model with the appropriate attributes # also pass "self" along as the parent model class_name = embeds_many.class_name || _.classify(_.singularize(name)) @[name] = global[class_name].modelize(value, @) else @[name] = value # load in defaults for own attr, val of @constructor.defaults @[attr] = val if typeof @[attr] is 'undefined' self = @ # set up belongs_to methods, e.g. recipe.user() for belongs_to in @constructor.belongs_to relation = belongs_to.name identifier = belongs_to.identifier || "#{relation}_id" # set up default class name, e.g. "belongs_to: user" ==> 'User' class_name = belongs_to.class_name || _.titleize(relation) @[relation] = do(relation, identifier, class_name) -> (options = {}) -> # if we have a relation_id if global[class_name] and self[identifier] return global[class_name].find self[identifier], options else return false # set up has_many methods, e.g. user.recipes() for has_many in @constructor.has_many relation = has_many.name selector = {} unless foreign_key = has_many.foreign_key # can't use @constructor.name in production because it's been minified to "n" foreign_key = PI:KEY:<KEY>END_PI" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_many: users" ==> 'User' class_name = has_many.class_name || _.titleize(_.singularize(relation)) @[relation] = do(relation, selector, class_name) -> (mod_selector = {}, options = {}) -> # first consider any passed in selector options mod_selector = _.extend mod_selector, selector # e.g. where {user_id: @id} if global[class_name] HasManyRelation.fromRelation(global[class_name].where(mod_selector, options), foreign_key, @id) # set up has_one methods, e.g. user.recipes() for has_one in @constructor.has_one relation = has_one.name selector = {} unless foreign_key = has_one.foreign_key foreign_key = PI:KEY:<KEY>END_PI" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_one: user" ==> 'User' class_name = has_one.class_name || _.titleize(relation) @[relation] = do(relation, selector, class_name) -> (mod_selector = {}, options = {}) -> # first consider any passed in selector options mod_selector = _.extend mod_selector, selector # e.g. where {user_id: @id} if global[class_name] global[class_name].first(mod_selector, options) # set up HABTM methods, e.g. user.friends() for habtm in @constructor.has_and_belongs_to_many relation = habtm.name identifier = "#{_.singularize(relation)}_ids" # set up default class name, e.g. "habtm: users" ==> 'User' class_name = habtm.class_name || _.titleize(_.singularize(relation)) @[relation] = do(relation, identifier, class_name) -> (mod_selector = {}, options = {}) -> selector = {_id: {$in: self[identifier]}} # first consider any passed in selector options mod_selector = _.extend mod_selector, selector instance = global[class_name].init() filter = (r) -> name = r.class_name || _.titleize(_.singularize(r.name)) global[name] == this.constructor inverse = _.find instance.constructor.has_and_belongs_to_many, filter, @ inverse_identifier = "#{_.singularize(inverse.name)}_ids" if global[class_name] and self[identifier] and self[identifier].length relation = global[class_name].where mod_selector, options return HasAndBelongsToManyRelation.fromRelation(relation, @, inverse_identifier, identifier, @id) else return HasAndBelongsToManyRelation.new(@, global[class_name], inverse_identifier, identifier, @id) # /-------------------- # DEPRECATED: r() and related() methods # Also does not support has_one. # -------------------- # alias to @related r: (relation) -> @related(relation) # look up related models related: (relation, options = {}) -> # self = @ # is it a belongs_to? for belongs_to in @constructor.belongs_to if relation == belongs_to.name identifier = "#{belongs_to.name}_id" # set up default class name, e.g. "belongs_to: user" ==> 'User' unless belongs_to.class_name belongs_to.class_name = _.titleize belongs_to.name # if we have a relation_id if @[identifier] return global[belongs_to.class_name].find @[identifier], options else return false # is it a has many? for has_many in @constructor.has_many if relation == has_many.name selector = {} unless foreign_key = has_many.foreign_key # can't use @constructor.name in production because it's been minified to "n" foreign_key = "#{_.singularPI:KEY:<KEY>END_PI(@constructor.to_s().toLowerCase())}_PI:KEY:<KEY>END_PI" if @constructor._object_id selector[foreign_key] = new Meteor.Collection.ObjectID @id else selector[foreign_key] = @id # set up default class name, e.g. "has_many: users" ==> 'User' unless has_many.class_name has_many.class_name = _.titleize _.singularize(has_many.name) # e.g. where {user_id: @id} return global[has_many.class_name].where selector, options # is it a has many? (same as HABTM) for habtm in @constructor.has_and_belongs_to_many if relation == habtm.name identifier = "#{_.singularize(habtm.name)}_ids" # set up default class name, e.g. "habtm: users" ==> 'User' unless habtm.class_name habtm.class_name = _.titleize _.singularize(habtm.name) if @[identifier] and @[identifier].length return global[habtm.class_name].where {_id: {$in: @[identifier]}}, options else return [] # if we get here, means method not found console.warn "Method #{relation} does not exist for #{@constructor.to_s()}." # isPersisted: -> @id? # ------------------- # --------------------/ error: (field, message) -> @errors ||= [] obj = {} obj[field] = message @errors.push obj isValid: (attr = {}) -> @validate() not @errors # nothing by default validate: -> # if blah then @errors.blah = 'no, bad!' else @errors = false true is_new: () -> @isNew() isNew: () -> @__is_new save: (attr = {}, callback = undefined) -> # reset errors before running isValid() @errors = false for k,v of attr @[k] = v attr = @constructor.before_save(attr) if @constructor.before_save return @ if not @isValid() # attr['_type'] = @constructor._type if @constructor._type? if callback? if @isNew() @constructor._collection.insert( attr, ((error, result) => unless error? @id = @_id = result @__is_new = false if @constructor.after_save @constructor.after_save(@) callback(error, result) )) else @constructor._collection.update( @id, { $set: attr }, ((error, result) => unless error? if @constructor.after_save @constructor.after_save(@) callback(error, result) )) return null else if @isNew() @id = @_id = @constructor._collection.insert( attr ) @__is_new = false else @constructor._collection.update( @id, { $set: attr } ) if @constructor.after_save @constructor.after_save(@) return @ update: (attr, callback = undefined) -> @save(attr, callback) # push to mongo array field push: (data) -> # TODO: should maybe do something like this; but it should know if we're pushing an embedded model and instantiate it... # for name, value of data # # update locally # @[name].push value # addToSet to ensure uniqueness -- can't think of if/when we WOULDN'T want that?? @constructor._collection.update @id, {$addToSet: data} # pull from mongo array field pull: (data) -> @constructor._collection.update @id, {$pull: data} del: (field) -> unset = {} unset[field] = "" @constructor._collection.update @id, {$unset: unset} destroy: (callback = undefined) -> if @id? @constructor._collection.remove( @id, callback ) @id = @_id = null reload: -> if @id? @constructor.find(@id) # --- class variables @_object_id: false @_collection: undefined @_type: undefined @_debug: false @defaults: [] @belongs_to: [] @has_many: [] @has_one: [] @has_and_belongs_to_many: [] @embedded_in: null @embeds_many: [] # @after_save: null # @before_save: null # @before_create: null # @after_create: null # --- class methods @init: (attr, parent = null, is_new = false) -> new @(attr, parent, is_new) @to_s: -> if @_collection then @_collection._name else "embedded" @create: (attr, callback = undefined) -> attr.createdAt ||= new Date() attr = @before_create(attr) if @before_create doc = @init(attr, null, true) if callback? doc.save(attr, callback) null else doc = doc.save(attr) doc.initAttrsAndRelations(attr) if doc and @after_create @after_create(doc) else doc # find + modelize @where: (selector = {}, options = {}) -> self = @ if @_debug console.info " --- WHERE ---" console.info " #{_.singularize _.classify @to_s()}.where(#{JSON.stringify selector}#{if not _.isEmpty options then ','+JSON.stringify options else ''})" result = @find(selector, options).fetch() result = Relation.new self, result... result.setQuery selector console.info " > found #{result.length}" if @_debug and result result @first: (selector = {}, options = {}) -> if @_debug console.info " --- FIRST ---" console.info " #{_.singularize _.classify @to_s()}.first(#{JSON.stringify selector}#{if not _.isEmpty options then ','+JSON.stringify options else ''})" if doc = @_collection.findOne(selector, options) @init doc # kind of a silly method, just does a findOne with reverse sort on createdAt @last: (selector = {}, options = {}) -> options.sort = createdAt: -1 if doc = @_collection.findOne(selector, options) @init doc @all: (options = {}) -> @where({}, options) # this doesn't perform a fetch, just generates a collection cursor @find: (selector = {}, options = {}) -> self = @ # ***Important!*** Transform all docs in the collection to be an instance of our model unless options.transform options.transform = (doc) -> self.init(doc) # unless you just pass an id, in which case it *does* fetch the first unless typeof selector == 'object' if @_object_id selector = new Meteor.Collection.ObjectID selector @first {_id: selector}, options else if selector instanceof Meteor.Collection.ObjectID @first {_id: selector}, options else # handle objectIDs -- these would come from an external database entry e.g. Rails if @_object_id if selector and selector._id if typeof selector._id is 'string' selector._id = new Meteor.Collection.ObjectID selector._id else if selector._id['$in'] # _.map(game_ids, function(x) { return new Meteor.Collection.ObjectID(x) }) selector._id['$in'] = _.map_object_id selector._id['$in'] if selector and selector._ids selector._ids = _.map(selector._ids, (id) -> new Meteor.Collection.ObjectID id) @_collection.find selector, options @count: (selector = {}, options = {}) -> @find(selector, options).count() @destroyAll: (selector = {}) -> @_collection.remove(selector) # run a model init on all items in the collection # -- somewhat deprecated -- used to be used in @where function, which is replaced by the transform inside of @find @modelize: (cursor, parent = null) -> self = @ models = cursor.map (i) -> self.init(i, parent) Relation.new self, models... # for some reason underscore.inflection stopped working with Meteor 0.6.5. # so for now we just use this simple singularize method instead of including the library _.singularize = (s) -> s = s.replace /s$/, ""
[ { "context": "/cryptotrader.org/strategies/peKY35zY2Z2G56rLi\r\nby aspiramedia (https://cryptotrader.org/aspiramedia)\r\n\r\nPlease ", "end": 157, "score": 0.9034062027931213, "start": 146, "tag": "USERNAME", "value": "aspiramedia" }, { "context": " and Swing indicators used here were originally by Chris Moody at TradingView.\r\nTrading logic is my own.\r\nThanks", "end": 955, "score": 0.9997210502624512, "start": 944, "tag": "NAME", "value": "Chris Moody" } ]
test.coffee
urbantumbleweed/charlie-tango-bravo
1
####################### ### TRENDATRON 5000 ### ####################### ### INTRO https://cryptotrader.org/strategies/peKY35zY2Z2G56rLi by aspiramedia (https://cryptotrader.org/aspiramedia) Please PM me with any updates, feedback, bugs, suggestions, criticism etc. Please leave this header intact, adding your own comments in EDITOR'S COMMENTS. Edited bots are NOT for submission into the CryptoTrader.org Strategies section. ### ### EDITOR'S COMMENTS Made any edits? Why not explain here. ### ### DONATIONS I am releasing this as a donation based bot. I am releasing this in hope of obtaining some donations from users here. Please donate BTC to: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74 ### ### DISCLAIMER As usual with all trading, only trade with what you are able to lose. Start small. I am NOT responsible for your losses if any occur. ### ### CREDITS The VIX and Swing indicators used here were originally by Chris Moody at TradingView. Trading logic is my own. Thanks to all at Cryptotrader.org that helped me along the way. ### ### ADVICE Rather than just trading with this, perhaps make this bot your own. Use it as a learning tool. Edit it to trade as you like to match your strategy. View this as a template for a long term trend trader with added scalping. Backtesting is your friend. Backtest over long periods to identify strengths and weaknesses. ### ############ ### CODE ### ############ talib = require 'talib' trading = require 'trading' params = require 'params' STOP_LOSS = params.add 'Use a Stop Loss?', false STOP_LOSS_PERCENTAGE = params.add 'If so, Stop Loss Percentage?', 5 SCALP = params.add 'Use Scalping?', true SPLIT = params.add 'Split orders up?', false SPLIT_AMOUNT = params.add 'If so, split into how many?', 4 PERIOD = params.add 'Trend reaction time (Max = 250 | Min = 50 | Default = 250 )', 250 SNIPE = params.add 'Use Fat Finger Sniping?', false CODE = params.add 'Code to remove donation requests', 0 class VIX constructor: (@period) -> @close = [] @wvf = [] @trade = [] @count = 0 # INITIALIZE ARRAYS for [@close.length..22] @close.push 0 for [@wvf.length..@period] @wvf.push 0 for [@trade.length..10] @trade.push 0 calculate: (instrument) -> close = instrument.close[instrument.close.length-1] high = instrument.high[instrument.high.length-1] low = instrument.low[instrument.low.length-1] # INCREASE DATA COUNT @count++ # REMOVE OLD DATA @close.pop() @wvf.pop() @trade.pop() # ADD NEW DATA @close.unshift(0) @wvf.unshift(0) @trade.unshift(0) # CALCULATE @close[0] = close highest = (@close.reduce (a,b) -> Math.max a, b) @wvf[0] = ((highest - low) / (highest)) * 100 sdev = talib.STDDEV inReal: @wvf startIdx: 0 endIdx: @wvf.length-1 optInTimePeriod: @period optInNbDev: 1 sdev = sdev[sdev.length-1] midline = talib.SMA inReal: @wvf startIdx: 0 endIdx: @wvf.length-1 optInTimePeriod: @period midline = midline[midline.length-1] lowerband = midline - sdev upperband = midline + sdev rangehigh = (@wvf.reduce (a,b) -> Math.max a, b) * 0.85 rangelow = (@wvf.reduce (a,b) -> Math.min a, b) * 1.01 if @wvf[0] >= upperband or @wvf[0] >= rangehigh @trade[0] = 0 plotMark "wvf1": @wvf[0] else @trade[0] = 1 plotMark "wvf2": @wvf[0] # RETURN DATA result = wvf: @wvf[0] rangehigh: rangehigh rangelow: rangelow trade: @trade return result class GANNSWING constructor: (@period) -> @count = 0 @buycount = 0 @sellcount = 0 @lowma = [] @highma = [] @fastlowma = [] @fasthighma = [] # INITIALIZE ARRAYS for [@lowma.length..5] @lowma.push 0 for [@highma.length..5] @highma.push 0 for [@fastlowma.length..5] @fastlowma.push 0 for [@fasthighma.length..5] @fasthighma.push 0 calculate: (instrument) -> close = instrument.close[instrument.close.length-1] high = instrument.high[instrument.high.length-1] low = instrument.low[instrument.low.length-1] # REMOVE OLD DATA @lowma.pop() @highma.pop() @fastlowma.pop() @fasthighma.pop() # ADD NEW DATA @lowma.unshift(0) @highma.unshift(0) @fastlowma.unshift(0) @fasthighma.unshift(0) # CALCULATE highma = talib.SMA inReal: instrument.high startIdx: 0 endIdx: instrument.high.length-1 optInTimePeriod: @period @highma[0] = highma[highma.length-1] lowma = talib.SMA inReal: instrument.low startIdx: 0 endIdx: instrument.low.length-1 optInTimePeriod: @period @lowma[0] = lowma[lowma.length-1] fasthighma = talib.SMA inReal: instrument.high startIdx: 0 endIdx: instrument.high.length-1 optInTimePeriod: @period / 5 @fasthighma[0] = fasthighma[fasthighma.length-1] fastlowma = talib.SMA inReal: instrument.low startIdx: 0 endIdx: instrument.low.length-1 optInTimePeriod: @period / 5 @fastlowma[0] = fastlowma[fastlowma.length-1] if close > @highma[1] * 0.998 or (close > @fasthighma[1] and close > @fastlowma[1] * 1.01 and @fasthighma[1] > @highma[1]) hld = 1 else if close < @lowma[1] / 0.998 or (close < @fastlowma[1] and close < @fasthighma[1] / 1.01 and @fastlowma[1] < @lowma[1]) hld = -1 else hld = 0 if hld != 0 @count++ if hld != 0 && @count == 1 hlv = hld @count = 0 else hlv = 0 if hlv == -1 hi = @highma[0] plotMark "hi": 50 @sellcount++ @buycount = 0 if hlv == 1 lo = @lowma[0] plotMark "lo": -5 @buycount++ @sellcount = 0 if @buycount == 3 tradebuy = true @buycount = 0 else tradebuy = false if @sellcount == 3 tradesell = true @sellcount = 0 else tradesell = false # RETURN DATA result = tradesell: tradesell tradebuy: tradebuy return result class FUNCTIONS @ROUND_DOWN: (value, places) -> offset = Math.pow(10, places) return Math.floor(value*offset)/offset class TRADE @BUY: (instrument, amount, split, timeout) -> price = instrument.price trading = require 'trading' amount = FUNCTIONS.ROUND_DOWN((portfolio.positions[instrument.curr()].amount)/price, 8) trading.buy instrument, 'limit', amount, price, timeout @SELL: (instrument, amount, split, timeout) -> price = instrument.price trading = require 'trading' amount = FUNCTIONS.ROUND_DOWN(portfolio.positions[instrument.asset()].amount, 8) trading.sell instrument, 'limit', amount, price, timeout init: -> context.vix = new VIX(20) # Period of stddev and midline context.swing = new GANNSWING(PERIOD) # Period of highma and lowma # FOR FINALISE STATS context.balance_curr = 0 context.balance_btc = 0 context.price = 0 # TRADING if SPLIT context.trade_split = SPLIT_AMOUNT else context.trade_split = 0 context.trade_timeout = 3000 handle: -> instrument = data.instruments[0] price = instrument.close[instrument.close.length - 1] storage.lastBuyPrice ?= 0 storage.TICK ?= 0 storage.NAG ?= 1 storage.coolOff ?= 0 tradingblock = 0 # FOR FINALISE STATS context.price = instrument.close[instrument.close.length - 1] context.balance_curr = portfolio.positions[instrument.curr()].amount context.balance_btc = portfolio.positions[instrument.asset()].amount # CALLING INDICATORS vix = context.vix.calculate(instrument) wvf = vix.wvf rangehigh = vix.rangehigh rangelow = vix.rangelow trade = vix.trade swing = context.swing.calculate(instrument) tradesell = swing.tradesell tradebuy = swing.tradebuy # LOGGING today = new Date day = today.getDate() month = today.getMonth() combo = day + month + 1 if storage.TICK == 0 storage.balance_curr_start = portfolio.positions[instrument.curr()].amount storage.balance_btc_start = portfolio.positions[instrument.asset()].amount storage.price_start = price if combo == CODE storage.NAG = 0 # WELCOME info "###" info "Welcome to the Trendatron Bot." if storage.NAG == 1 info "Thanks for choosing this free bot. As many hours have gone into its creation, please consider a donation to:" info "BTC: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74" info "(The bot carries on regardless of donations - don't worry.)" info "If you have donated PM me for a code to make donation requests disappear." else info "Thanks for choosing to donate. Appreciated." if STOP_LOSS == true info "You chose to use a Stop Loss, with a cutoff of " + STOP_LOSS_PERCENTAGE + " percent." if SCALP == true info "You chose to use scalping (default bot behaviour)" if SPLIT == true info "You chose to split orders up into " + SPLIT_AMOUNT + " orders." if SNIPE == true info "You chose to enable sniping." info "###" starting_btc_equiv = storage.balance_btc_start + storage.balance_curr_start / storage.price_start current_btc_equiv = context.balance_btc + context.balance_curr / price starting_fiat_equiv = storage.balance_curr_start + storage.balance_btc_start * storage.price_start current_fiat_equiv = context.balance_curr + context.balance_btc * price efficiency = Math.round((current_btc_equiv / starting_btc_equiv) * 1000) / 1000 efficiency_percent = Math.round((((current_btc_equiv / starting_btc_equiv) - 1) * 100) * 10) / 10 market_efficiency = Math.round((((context.price / storage.price_start) - 1) * 100) * 10) / 10 bot_efficiency = Math.round((((current_fiat_equiv / starting_fiat_equiv) - 1) * 100) * 10) / 10 storage.TICK++ if Math.round(storage.TICK/24) == (storage.TICK/24) warn "### Day " + storage.TICK/24 + " Log" debug "Current Fiat (USD): " + Math.round(context.balance_curr*100)/100 + " | Current Crypto (BTC): " + Math.round(context.balance_btc*100)/100 debug "Starting Fiat (USD): " + Math.round(storage.balance_curr_start*100)/100 + " | Starting Crypto (BTC): " + Math.round(storage.balance_btc_start*100)/100 debug "Current Portfolio Worth: " + Math.round(((context.balance_btc * price) + context.balance_curr)*100)/100 debug "Starting Portfolio Worth: " + Math.round(((storage.balance_btc_start * storage.price_start) + storage.balance_curr_start)*100)/100 debug "Efficiency of Buy and Hold: " + market_efficiency + "%" debug "Efficiency of Bot: " + bot_efficiency + "%" debug "Efficiency Vs Buy and Hold: " + efficiency + " which equals " + efficiency_percent + "%" warn "###" if Math.round(storage.TICK/48) == (storage.TICK/48) && storage.NAG == 1 info "###" info "Thanks for using this bot. Please consider a donation to:" info "BTC: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74" info "(The bot carries on regardless of donations - don't worry.)" info "If you have donated PM me for a code to make donation requests disappear." info "###" # TRADING if context.balance_curr/price > 0.01 if tradebuy == true && storage.coolOff <= 0 if TRADE.BUY(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = price storage.stop = true info "#########" info "Trend Buy" info "#########" tradingblock = 1 sendEmail "Trendatron TREND BUY" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if context.balance_curr/price > 0.01 && SCALP == true && storage.coolOff <= 0 if trade[0] == 1 && trade[1] == 1 && trade[2] == 0 && trade[3] == 0 && trade[4] == 0 && trade[5] == 0 && wvf > 8.5 if TRADE.BUY(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = price storage.stop = true info "#########" info "Scalp Buy" info "#########" tradingblock = 1 sendEmail "Trendatron SCALP BUY" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if context.balance_btc > 0.01 if (tradesell == true && wvf < 2.85) or (tradebuy == true && wvf > 8.5 && trade[0] == 1 && trade[1] == 0) if TRADE.SELL(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = 0 storage.lastSellPrice = price storage.stop = false warn "##########" warn "Trend Sell" warn "##########" tradingblock = 1 sendEmail "Trendatron TREND SELL" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if STOP_LOSS if storage.stop == true && price < storage.lastBuyPrice * (1 - (STOP_LOSS_PERCENTAGE / 100)) if TRADE.SELL(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = 0 storage.lastSellPrice = price storage.stop = false storage.coolOff = 30 warn "##############" warn "Stop Loss Sell" warn "##############" tradingblock = 1 sendEmail "Trendatron STOP LOSS SELL" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if SNIPE && tradingblock == 0 if context.balance_btc > 0.05 trading = require 'trading' if trading.sell instrument, 'limit', null, instrument.price * 1.1, 3530 warn "##########" warn "Snipe Sell" warn "##########" if context.balance_curr > 10 trading = require 'trading' if trading.buy instrument, 'limit', null, instrument.price * 0.9, 3530 info "#########" info "Snipe Buy" info "#########" storage.coolOff-- # PLOTTING / DEBUG plot wvf: wvf rangehigh: rangehigh rangelow: rangelow setPlotOptions wvf: secondary: true rangehigh: secondary: true rangelow: secondary: true wvf1: secondary: true color: 'blue' size: 1 wvf2: secondary: true color: 'black' size: 1 lo: color: 'green' secondary: true size: 4 hi: color: 'red' secondary: true size: 4 onStop: -> # DISPLAY FINALISE STATS if context.balance_curr > 10 info "Final BTC Equiv: " + Math.round(context.balance_curr/context.price*100)/100 if context.balance_btc > 0.05 info "Final BTC Value: " + Math.round(context.balance_btc*100)/100
57023
####################### ### TRENDATRON 5000 ### ####################### ### INTRO https://cryptotrader.org/strategies/peKY35zY2Z2G56rLi by aspiramedia (https://cryptotrader.org/aspiramedia) Please PM me with any updates, feedback, bugs, suggestions, criticism etc. Please leave this header intact, adding your own comments in EDITOR'S COMMENTS. Edited bots are NOT for submission into the CryptoTrader.org Strategies section. ### ### EDITOR'S COMMENTS Made any edits? Why not explain here. ### ### DONATIONS I am releasing this as a donation based bot. I am releasing this in hope of obtaining some donations from users here. Please donate BTC to: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74 ### ### DISCLAIMER As usual with all trading, only trade with what you are able to lose. Start small. I am NOT responsible for your losses if any occur. ### ### CREDITS The VIX and Swing indicators used here were originally by <NAME> at TradingView. Trading logic is my own. Thanks to all at Cryptotrader.org that helped me along the way. ### ### ADVICE Rather than just trading with this, perhaps make this bot your own. Use it as a learning tool. Edit it to trade as you like to match your strategy. View this as a template for a long term trend trader with added scalping. Backtesting is your friend. Backtest over long periods to identify strengths and weaknesses. ### ############ ### CODE ### ############ talib = require 'talib' trading = require 'trading' params = require 'params' STOP_LOSS = params.add 'Use a Stop Loss?', false STOP_LOSS_PERCENTAGE = params.add 'If so, Stop Loss Percentage?', 5 SCALP = params.add 'Use Scalping?', true SPLIT = params.add 'Split orders up?', false SPLIT_AMOUNT = params.add 'If so, split into how many?', 4 PERIOD = params.add 'Trend reaction time (Max = 250 | Min = 50 | Default = 250 )', 250 SNIPE = params.add 'Use Fat Finger Sniping?', false CODE = params.add 'Code to remove donation requests', 0 class VIX constructor: (@period) -> @close = [] @wvf = [] @trade = [] @count = 0 # INITIALIZE ARRAYS for [@close.length..22] @close.push 0 for [@wvf.length..@period] @wvf.push 0 for [@trade.length..10] @trade.push 0 calculate: (instrument) -> close = instrument.close[instrument.close.length-1] high = instrument.high[instrument.high.length-1] low = instrument.low[instrument.low.length-1] # INCREASE DATA COUNT @count++ # REMOVE OLD DATA @close.pop() @wvf.pop() @trade.pop() # ADD NEW DATA @close.unshift(0) @wvf.unshift(0) @trade.unshift(0) # CALCULATE @close[0] = close highest = (@close.reduce (a,b) -> Math.max a, b) @wvf[0] = ((highest - low) / (highest)) * 100 sdev = talib.STDDEV inReal: @wvf startIdx: 0 endIdx: @wvf.length-1 optInTimePeriod: @period optInNbDev: 1 sdev = sdev[sdev.length-1] midline = talib.SMA inReal: @wvf startIdx: 0 endIdx: @wvf.length-1 optInTimePeriod: @period midline = midline[midline.length-1] lowerband = midline - sdev upperband = midline + sdev rangehigh = (@wvf.reduce (a,b) -> Math.max a, b) * 0.85 rangelow = (@wvf.reduce (a,b) -> Math.min a, b) * 1.01 if @wvf[0] >= upperband or @wvf[0] >= rangehigh @trade[0] = 0 plotMark "wvf1": @wvf[0] else @trade[0] = 1 plotMark "wvf2": @wvf[0] # RETURN DATA result = wvf: @wvf[0] rangehigh: rangehigh rangelow: rangelow trade: @trade return result class GANNSWING constructor: (@period) -> @count = 0 @buycount = 0 @sellcount = 0 @lowma = [] @highma = [] @fastlowma = [] @fasthighma = [] # INITIALIZE ARRAYS for [@lowma.length..5] @lowma.push 0 for [@highma.length..5] @highma.push 0 for [@fastlowma.length..5] @fastlowma.push 0 for [@fasthighma.length..5] @fasthighma.push 0 calculate: (instrument) -> close = instrument.close[instrument.close.length-1] high = instrument.high[instrument.high.length-1] low = instrument.low[instrument.low.length-1] # REMOVE OLD DATA @lowma.pop() @highma.pop() @fastlowma.pop() @fasthighma.pop() # ADD NEW DATA @lowma.unshift(0) @highma.unshift(0) @fastlowma.unshift(0) @fasthighma.unshift(0) # CALCULATE highma = talib.SMA inReal: instrument.high startIdx: 0 endIdx: instrument.high.length-1 optInTimePeriod: @period @highma[0] = highma[highma.length-1] lowma = talib.SMA inReal: instrument.low startIdx: 0 endIdx: instrument.low.length-1 optInTimePeriod: @period @lowma[0] = lowma[lowma.length-1] fasthighma = talib.SMA inReal: instrument.high startIdx: 0 endIdx: instrument.high.length-1 optInTimePeriod: @period / 5 @fasthighma[0] = fasthighma[fasthighma.length-1] fastlowma = talib.SMA inReal: instrument.low startIdx: 0 endIdx: instrument.low.length-1 optInTimePeriod: @period / 5 @fastlowma[0] = fastlowma[fastlowma.length-1] if close > @highma[1] * 0.998 or (close > @fasthighma[1] and close > @fastlowma[1] * 1.01 and @fasthighma[1] > @highma[1]) hld = 1 else if close < @lowma[1] / 0.998 or (close < @fastlowma[1] and close < @fasthighma[1] / 1.01 and @fastlowma[1] < @lowma[1]) hld = -1 else hld = 0 if hld != 0 @count++ if hld != 0 && @count == 1 hlv = hld @count = 0 else hlv = 0 if hlv == -1 hi = @highma[0] plotMark "hi": 50 @sellcount++ @buycount = 0 if hlv == 1 lo = @lowma[0] plotMark "lo": -5 @buycount++ @sellcount = 0 if @buycount == 3 tradebuy = true @buycount = 0 else tradebuy = false if @sellcount == 3 tradesell = true @sellcount = 0 else tradesell = false # RETURN DATA result = tradesell: tradesell tradebuy: tradebuy return result class FUNCTIONS @ROUND_DOWN: (value, places) -> offset = Math.pow(10, places) return Math.floor(value*offset)/offset class TRADE @BUY: (instrument, amount, split, timeout) -> price = instrument.price trading = require 'trading' amount = FUNCTIONS.ROUND_DOWN((portfolio.positions[instrument.curr()].amount)/price, 8) trading.buy instrument, 'limit', amount, price, timeout @SELL: (instrument, amount, split, timeout) -> price = instrument.price trading = require 'trading' amount = FUNCTIONS.ROUND_DOWN(portfolio.positions[instrument.asset()].amount, 8) trading.sell instrument, 'limit', amount, price, timeout init: -> context.vix = new VIX(20) # Period of stddev and midline context.swing = new GANNSWING(PERIOD) # Period of highma and lowma # FOR FINALISE STATS context.balance_curr = 0 context.balance_btc = 0 context.price = 0 # TRADING if SPLIT context.trade_split = SPLIT_AMOUNT else context.trade_split = 0 context.trade_timeout = 3000 handle: -> instrument = data.instruments[0] price = instrument.close[instrument.close.length - 1] storage.lastBuyPrice ?= 0 storage.TICK ?= 0 storage.NAG ?= 1 storage.coolOff ?= 0 tradingblock = 0 # FOR FINALISE STATS context.price = instrument.close[instrument.close.length - 1] context.balance_curr = portfolio.positions[instrument.curr()].amount context.balance_btc = portfolio.positions[instrument.asset()].amount # CALLING INDICATORS vix = context.vix.calculate(instrument) wvf = vix.wvf rangehigh = vix.rangehigh rangelow = vix.rangelow trade = vix.trade swing = context.swing.calculate(instrument) tradesell = swing.tradesell tradebuy = swing.tradebuy # LOGGING today = new Date day = today.getDate() month = today.getMonth() combo = day + month + 1 if storage.TICK == 0 storage.balance_curr_start = portfolio.positions[instrument.curr()].amount storage.balance_btc_start = portfolio.positions[instrument.asset()].amount storage.price_start = price if combo == CODE storage.NAG = 0 # WELCOME info "###" info "Welcome to the Trendatron Bot." if storage.NAG == 1 info "Thanks for choosing this free bot. As many hours have gone into its creation, please consider a donation to:" info "BTC: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74" info "(The bot carries on regardless of donations - don't worry.)" info "If you have donated PM me for a code to make donation requests disappear." else info "Thanks for choosing to donate. Appreciated." if STOP_LOSS == true info "You chose to use a Stop Loss, with a cutoff of " + STOP_LOSS_PERCENTAGE + " percent." if SCALP == true info "You chose to use scalping (default bot behaviour)" if SPLIT == true info "You chose to split orders up into " + SPLIT_AMOUNT + " orders." if SNIPE == true info "You chose to enable sniping." info "###" starting_btc_equiv = storage.balance_btc_start + storage.balance_curr_start / storage.price_start current_btc_equiv = context.balance_btc + context.balance_curr / price starting_fiat_equiv = storage.balance_curr_start + storage.balance_btc_start * storage.price_start current_fiat_equiv = context.balance_curr + context.balance_btc * price efficiency = Math.round((current_btc_equiv / starting_btc_equiv) * 1000) / 1000 efficiency_percent = Math.round((((current_btc_equiv / starting_btc_equiv) - 1) * 100) * 10) / 10 market_efficiency = Math.round((((context.price / storage.price_start) - 1) * 100) * 10) / 10 bot_efficiency = Math.round((((current_fiat_equiv / starting_fiat_equiv) - 1) * 100) * 10) / 10 storage.TICK++ if Math.round(storage.TICK/24) == (storage.TICK/24) warn "### Day " + storage.TICK/24 + " Log" debug "Current Fiat (USD): " + Math.round(context.balance_curr*100)/100 + " | Current Crypto (BTC): " + Math.round(context.balance_btc*100)/100 debug "Starting Fiat (USD): " + Math.round(storage.balance_curr_start*100)/100 + " | Starting Crypto (BTC): " + Math.round(storage.balance_btc_start*100)/100 debug "Current Portfolio Worth: " + Math.round(((context.balance_btc * price) + context.balance_curr)*100)/100 debug "Starting Portfolio Worth: " + Math.round(((storage.balance_btc_start * storage.price_start) + storage.balance_curr_start)*100)/100 debug "Efficiency of Buy and Hold: " + market_efficiency + "%" debug "Efficiency of Bot: " + bot_efficiency + "%" debug "Efficiency Vs Buy and Hold: " + efficiency + " which equals " + efficiency_percent + "%" warn "###" if Math.round(storage.TICK/48) == (storage.TICK/48) && storage.NAG == 1 info "###" info "Thanks for using this bot. Please consider a donation to:" info "BTC: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74" info "(The bot carries on regardless of donations - don't worry.)" info "If you have donated PM me for a code to make donation requests disappear." info "###" # TRADING if context.balance_curr/price > 0.01 if tradebuy == true && storage.coolOff <= 0 if TRADE.BUY(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = price storage.stop = true info "#########" info "Trend Buy" info "#########" tradingblock = 1 sendEmail "Trendatron TREND BUY" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if context.balance_curr/price > 0.01 && SCALP == true && storage.coolOff <= 0 if trade[0] == 1 && trade[1] == 1 && trade[2] == 0 && trade[3] == 0 && trade[4] == 0 && trade[5] == 0 && wvf > 8.5 if TRADE.BUY(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = price storage.stop = true info "#########" info "Scalp Buy" info "#########" tradingblock = 1 sendEmail "Trendatron SCALP BUY" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if context.balance_btc > 0.01 if (tradesell == true && wvf < 2.85) or (tradebuy == true && wvf > 8.5 && trade[0] == 1 && trade[1] == 0) if TRADE.SELL(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = 0 storage.lastSellPrice = price storage.stop = false warn "##########" warn "Trend Sell" warn "##########" tradingblock = 1 sendEmail "Trendatron TREND SELL" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if STOP_LOSS if storage.stop == true && price < storage.lastBuyPrice * (1 - (STOP_LOSS_PERCENTAGE / 100)) if TRADE.SELL(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = 0 storage.lastSellPrice = price storage.stop = false storage.coolOff = 30 warn "##############" warn "Stop Loss Sell" warn "##############" tradingblock = 1 sendEmail "Trendatron STOP LOSS SELL" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if SNIPE && tradingblock == 0 if context.balance_btc > 0.05 trading = require 'trading' if trading.sell instrument, 'limit', null, instrument.price * 1.1, 3530 warn "##########" warn "Snipe Sell" warn "##########" if context.balance_curr > 10 trading = require 'trading' if trading.buy instrument, 'limit', null, instrument.price * 0.9, 3530 info "#########" info "Snipe Buy" info "#########" storage.coolOff-- # PLOTTING / DEBUG plot wvf: wvf rangehigh: rangehigh rangelow: rangelow setPlotOptions wvf: secondary: true rangehigh: secondary: true rangelow: secondary: true wvf1: secondary: true color: 'blue' size: 1 wvf2: secondary: true color: 'black' size: 1 lo: color: 'green' secondary: true size: 4 hi: color: 'red' secondary: true size: 4 onStop: -> # DISPLAY FINALISE STATS if context.balance_curr > 10 info "Final BTC Equiv: " + Math.round(context.balance_curr/context.price*100)/100 if context.balance_btc > 0.05 info "Final BTC Value: " + Math.round(context.balance_btc*100)/100
true
####################### ### TRENDATRON 5000 ### ####################### ### INTRO https://cryptotrader.org/strategies/peKY35zY2Z2G56rLi by aspiramedia (https://cryptotrader.org/aspiramedia) Please PM me with any updates, feedback, bugs, suggestions, criticism etc. Please leave this header intact, adding your own comments in EDITOR'S COMMENTS. Edited bots are NOT for submission into the CryptoTrader.org Strategies section. ### ### EDITOR'S COMMENTS Made any edits? Why not explain here. ### ### DONATIONS I am releasing this as a donation based bot. I am releasing this in hope of obtaining some donations from users here. Please donate BTC to: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74 ### ### DISCLAIMER As usual with all trading, only trade with what you are able to lose. Start small. I am NOT responsible for your losses if any occur. ### ### CREDITS The VIX and Swing indicators used here were originally by PI:NAME:<NAME>END_PI at TradingView. Trading logic is my own. Thanks to all at Cryptotrader.org that helped me along the way. ### ### ADVICE Rather than just trading with this, perhaps make this bot your own. Use it as a learning tool. Edit it to trade as you like to match your strategy. View this as a template for a long term trend trader with added scalping. Backtesting is your friend. Backtest over long periods to identify strengths and weaknesses. ### ############ ### CODE ### ############ talib = require 'talib' trading = require 'trading' params = require 'params' STOP_LOSS = params.add 'Use a Stop Loss?', false STOP_LOSS_PERCENTAGE = params.add 'If so, Stop Loss Percentage?', 5 SCALP = params.add 'Use Scalping?', true SPLIT = params.add 'Split orders up?', false SPLIT_AMOUNT = params.add 'If so, split into how many?', 4 PERIOD = params.add 'Trend reaction time (Max = 250 | Min = 50 | Default = 250 )', 250 SNIPE = params.add 'Use Fat Finger Sniping?', false CODE = params.add 'Code to remove donation requests', 0 class VIX constructor: (@period) -> @close = [] @wvf = [] @trade = [] @count = 0 # INITIALIZE ARRAYS for [@close.length..22] @close.push 0 for [@wvf.length..@period] @wvf.push 0 for [@trade.length..10] @trade.push 0 calculate: (instrument) -> close = instrument.close[instrument.close.length-1] high = instrument.high[instrument.high.length-1] low = instrument.low[instrument.low.length-1] # INCREASE DATA COUNT @count++ # REMOVE OLD DATA @close.pop() @wvf.pop() @trade.pop() # ADD NEW DATA @close.unshift(0) @wvf.unshift(0) @trade.unshift(0) # CALCULATE @close[0] = close highest = (@close.reduce (a,b) -> Math.max a, b) @wvf[0] = ((highest - low) / (highest)) * 100 sdev = talib.STDDEV inReal: @wvf startIdx: 0 endIdx: @wvf.length-1 optInTimePeriod: @period optInNbDev: 1 sdev = sdev[sdev.length-1] midline = talib.SMA inReal: @wvf startIdx: 0 endIdx: @wvf.length-1 optInTimePeriod: @period midline = midline[midline.length-1] lowerband = midline - sdev upperband = midline + sdev rangehigh = (@wvf.reduce (a,b) -> Math.max a, b) * 0.85 rangelow = (@wvf.reduce (a,b) -> Math.min a, b) * 1.01 if @wvf[0] >= upperband or @wvf[0] >= rangehigh @trade[0] = 0 plotMark "wvf1": @wvf[0] else @trade[0] = 1 plotMark "wvf2": @wvf[0] # RETURN DATA result = wvf: @wvf[0] rangehigh: rangehigh rangelow: rangelow trade: @trade return result class GANNSWING constructor: (@period) -> @count = 0 @buycount = 0 @sellcount = 0 @lowma = [] @highma = [] @fastlowma = [] @fasthighma = [] # INITIALIZE ARRAYS for [@lowma.length..5] @lowma.push 0 for [@highma.length..5] @highma.push 0 for [@fastlowma.length..5] @fastlowma.push 0 for [@fasthighma.length..5] @fasthighma.push 0 calculate: (instrument) -> close = instrument.close[instrument.close.length-1] high = instrument.high[instrument.high.length-1] low = instrument.low[instrument.low.length-1] # REMOVE OLD DATA @lowma.pop() @highma.pop() @fastlowma.pop() @fasthighma.pop() # ADD NEW DATA @lowma.unshift(0) @highma.unshift(0) @fastlowma.unshift(0) @fasthighma.unshift(0) # CALCULATE highma = talib.SMA inReal: instrument.high startIdx: 0 endIdx: instrument.high.length-1 optInTimePeriod: @period @highma[0] = highma[highma.length-1] lowma = talib.SMA inReal: instrument.low startIdx: 0 endIdx: instrument.low.length-1 optInTimePeriod: @period @lowma[0] = lowma[lowma.length-1] fasthighma = talib.SMA inReal: instrument.high startIdx: 0 endIdx: instrument.high.length-1 optInTimePeriod: @period / 5 @fasthighma[0] = fasthighma[fasthighma.length-1] fastlowma = talib.SMA inReal: instrument.low startIdx: 0 endIdx: instrument.low.length-1 optInTimePeriod: @period / 5 @fastlowma[0] = fastlowma[fastlowma.length-1] if close > @highma[1] * 0.998 or (close > @fasthighma[1] and close > @fastlowma[1] * 1.01 and @fasthighma[1] > @highma[1]) hld = 1 else if close < @lowma[1] / 0.998 or (close < @fastlowma[1] and close < @fasthighma[1] / 1.01 and @fastlowma[1] < @lowma[1]) hld = -1 else hld = 0 if hld != 0 @count++ if hld != 0 && @count == 1 hlv = hld @count = 0 else hlv = 0 if hlv == -1 hi = @highma[0] plotMark "hi": 50 @sellcount++ @buycount = 0 if hlv == 1 lo = @lowma[0] plotMark "lo": -5 @buycount++ @sellcount = 0 if @buycount == 3 tradebuy = true @buycount = 0 else tradebuy = false if @sellcount == 3 tradesell = true @sellcount = 0 else tradesell = false # RETURN DATA result = tradesell: tradesell tradebuy: tradebuy return result class FUNCTIONS @ROUND_DOWN: (value, places) -> offset = Math.pow(10, places) return Math.floor(value*offset)/offset class TRADE @BUY: (instrument, amount, split, timeout) -> price = instrument.price trading = require 'trading' amount = FUNCTIONS.ROUND_DOWN((portfolio.positions[instrument.curr()].amount)/price, 8) trading.buy instrument, 'limit', amount, price, timeout @SELL: (instrument, amount, split, timeout) -> price = instrument.price trading = require 'trading' amount = FUNCTIONS.ROUND_DOWN(portfolio.positions[instrument.asset()].amount, 8) trading.sell instrument, 'limit', amount, price, timeout init: -> context.vix = new VIX(20) # Period of stddev and midline context.swing = new GANNSWING(PERIOD) # Period of highma and lowma # FOR FINALISE STATS context.balance_curr = 0 context.balance_btc = 0 context.price = 0 # TRADING if SPLIT context.trade_split = SPLIT_AMOUNT else context.trade_split = 0 context.trade_timeout = 3000 handle: -> instrument = data.instruments[0] price = instrument.close[instrument.close.length - 1] storage.lastBuyPrice ?= 0 storage.TICK ?= 0 storage.NAG ?= 1 storage.coolOff ?= 0 tradingblock = 0 # FOR FINALISE STATS context.price = instrument.close[instrument.close.length - 1] context.balance_curr = portfolio.positions[instrument.curr()].amount context.balance_btc = portfolio.positions[instrument.asset()].amount # CALLING INDICATORS vix = context.vix.calculate(instrument) wvf = vix.wvf rangehigh = vix.rangehigh rangelow = vix.rangelow trade = vix.trade swing = context.swing.calculate(instrument) tradesell = swing.tradesell tradebuy = swing.tradebuy # LOGGING today = new Date day = today.getDate() month = today.getMonth() combo = day + month + 1 if storage.TICK == 0 storage.balance_curr_start = portfolio.positions[instrument.curr()].amount storage.balance_btc_start = portfolio.positions[instrument.asset()].amount storage.price_start = price if combo == CODE storage.NAG = 0 # WELCOME info "###" info "Welcome to the Trendatron Bot." if storage.NAG == 1 info "Thanks for choosing this free bot. As many hours have gone into its creation, please consider a donation to:" info "BTC: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74" info "(The bot carries on regardless of donations - don't worry.)" info "If you have donated PM me for a code to make donation requests disappear." else info "Thanks for choosing to donate. Appreciated." if STOP_LOSS == true info "You chose to use a Stop Loss, with a cutoff of " + STOP_LOSS_PERCENTAGE + " percent." if SCALP == true info "You chose to use scalping (default bot behaviour)" if SPLIT == true info "You chose to split orders up into " + SPLIT_AMOUNT + " orders." if SNIPE == true info "You chose to enable sniping." info "###" starting_btc_equiv = storage.balance_btc_start + storage.balance_curr_start / storage.price_start current_btc_equiv = context.balance_btc + context.balance_curr / price starting_fiat_equiv = storage.balance_curr_start + storage.balance_btc_start * storage.price_start current_fiat_equiv = context.balance_curr + context.balance_btc * price efficiency = Math.round((current_btc_equiv / starting_btc_equiv) * 1000) / 1000 efficiency_percent = Math.round((((current_btc_equiv / starting_btc_equiv) - 1) * 100) * 10) / 10 market_efficiency = Math.round((((context.price / storage.price_start) - 1) * 100) * 10) / 10 bot_efficiency = Math.round((((current_fiat_equiv / starting_fiat_equiv) - 1) * 100) * 10) / 10 storage.TICK++ if Math.round(storage.TICK/24) == (storage.TICK/24) warn "### Day " + storage.TICK/24 + " Log" debug "Current Fiat (USD): " + Math.round(context.balance_curr*100)/100 + " | Current Crypto (BTC): " + Math.round(context.balance_btc*100)/100 debug "Starting Fiat (USD): " + Math.round(storage.balance_curr_start*100)/100 + " | Starting Crypto (BTC): " + Math.round(storage.balance_btc_start*100)/100 debug "Current Portfolio Worth: " + Math.round(((context.balance_btc * price) + context.balance_curr)*100)/100 debug "Starting Portfolio Worth: " + Math.round(((storage.balance_btc_start * storage.price_start) + storage.balance_curr_start)*100)/100 debug "Efficiency of Buy and Hold: " + market_efficiency + "%" debug "Efficiency of Bot: " + bot_efficiency + "%" debug "Efficiency Vs Buy and Hold: " + efficiency + " which equals " + efficiency_percent + "%" warn "###" if Math.round(storage.TICK/48) == (storage.TICK/48) && storage.NAG == 1 info "###" info "Thanks for using this bot. Please consider a donation to:" info "BTC: 1GGZU5mAUSLxVDegdxjakTLqZy7zizRH74" info "(The bot carries on regardless of donations - don't worry.)" info "If you have donated PM me for a code to make donation requests disappear." info "###" # TRADING if context.balance_curr/price > 0.01 if tradebuy == true && storage.coolOff <= 0 if TRADE.BUY(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = price storage.stop = true info "#########" info "Trend Buy" info "#########" tradingblock = 1 sendEmail "Trendatron TREND BUY" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if context.balance_curr/price > 0.01 && SCALP == true && storage.coolOff <= 0 if trade[0] == 1 && trade[1] == 1 && trade[2] == 0 && trade[3] == 0 && trade[4] == 0 && trade[5] == 0 && wvf > 8.5 if TRADE.BUY(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = price storage.stop = true info "#########" info "Scalp Buy" info "#########" tradingblock = 1 sendEmail "Trendatron SCALP BUY" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if context.balance_btc > 0.01 if (tradesell == true && wvf < 2.85) or (tradebuy == true && wvf > 8.5 && trade[0] == 1 && trade[1] == 0) if TRADE.SELL(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = 0 storage.lastSellPrice = price storage.stop = false warn "##########" warn "Trend Sell" warn "##########" tradingblock = 1 sendEmail "Trendatron TREND SELL" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if STOP_LOSS if storage.stop == true && price < storage.lastBuyPrice * (1 - (STOP_LOSS_PERCENTAGE / 100)) if TRADE.SELL(instrument, null, context.trade_split, context.trade_timeout) storage.lastBuyPrice = 0 storage.lastSellPrice = price storage.stop = false storage.coolOff = 30 warn "##############" warn "Stop Loss Sell" warn "##############" tradingblock = 1 sendEmail "Trendatron STOP LOSS SELL" + " - Current Fiat: " + Math.round(context.balance_curr*100)/100 + " | Current BTC: " + Math.round(context.balance_btc*100)/100 if SNIPE && tradingblock == 0 if context.balance_btc > 0.05 trading = require 'trading' if trading.sell instrument, 'limit', null, instrument.price * 1.1, 3530 warn "##########" warn "Snipe Sell" warn "##########" if context.balance_curr > 10 trading = require 'trading' if trading.buy instrument, 'limit', null, instrument.price * 0.9, 3530 info "#########" info "Snipe Buy" info "#########" storage.coolOff-- # PLOTTING / DEBUG plot wvf: wvf rangehigh: rangehigh rangelow: rangelow setPlotOptions wvf: secondary: true rangehigh: secondary: true rangelow: secondary: true wvf1: secondary: true color: 'blue' size: 1 wvf2: secondary: true color: 'black' size: 1 lo: color: 'green' secondary: true size: 4 hi: color: 'red' secondary: true size: 4 onStop: -> # DISPLAY FINALISE STATS if context.balance_curr > 10 info "Final BTC Equiv: " + Math.round(context.balance_curr/context.price*100)/100 if context.balance_btc > 0.05 info "Final BTC Value: " + Math.round(context.balance_btc*100)/100
[ { "context": "= ()->\n#Аа Aа \n equalLat(\"Алушта Андрій\", \"Alushta Andrii\");\n#Бб Bb \n equalLat(\"Борщагівка Борисенко", "end": 1082, "score": 0.9817265272140503, "start": 1068, "tag": "NAME", "value": "Alushta Andrii" }, { "context": "#Бб Bb \n equalLat(\"Борщагівка Борисенко\", \"Borshchahivka Borysenko\");\n#Вв Vv \n equalLat(\"Вінниця Володимир\", ", "end": 1159, "score": 0.9963812828063965, "start": 1136, "tag": "NAME", "value": "Borshchahivka Borysenko" }, { "context": ");\n#Вв Vv \n equalLat(\"Вінниця Володимир\", \"Vinnytsia Volodymyr\");\n#Гг Hh \n equalLat(\"Гадяч Богдан Згурськ", "end": 1229, "score": 0.9944584965705872, "start": 1210, "tag": "NAME", "value": "Vinnytsia Volodymyr" }, { "context": "г Hh \n equalLat(\"Гадяч Богдан Згурський\", \"Hadiach Bohdan Zghurskyi\");\n#Ґґ Gg \n equalLat(\"Ґалаґан Ґорґани\", \"G", "end": 1309, "score": 0.9990053772926331, "start": 1285, "tag": "NAME", "value": "Hadiach Bohdan Zghurskyi" }, { "context": "i\");\n#Ґґ Gg \n equalLat(\"Ґалаґан Ґорґани\", \"Galagan Gorgany\");\n#Дд Dd \n equalLat(\"Донецьк Дмитро\", \"Do", "end": 1373, "score": 0.9988539218902588, "start": 1358, "tag": "NAME", "value": "Galagan Gorgany" }, { "context": "gan Gorgany\");\n#Дд Dd \n equalLat(\"Донецьк Дмитро\", \"Donetsk Dmytro\");\n#Ее Eе \n equalLat", "end": 1413, "score": 0.6840795278549194, "start": 1412, "tag": "NAME", "value": "м" }, { "context": "ny\");\n#Дд Dd \n equalLat(\"Донецьк Дмитро\", \"Donetsk Dmytro\");\n#Ее Eе \n equalLat(\"Рівне Олег Есмань\", ", "end": 1435, "score": 0.9956088066101074, "start": 1421, "tag": "NAME", "value": "Donetsk Dmytro" }, { "context": ");\n#Ее Eе \n equalLat(\"Рівне Олег Есмань\", \"Rivne Oleh Esman\");\n#Єє Ye ie на початку слова в інших позиціях \n ", "end": 1502, "score": 0.9974561929702759, "start": 1486, "tag": "NAME", "value": "Rivne Oleh Esman" }, { "context": "іях \n equalLat(\"Єнакієве Гаєвич Короп’є\", \"Yenakiieve Haievych Koropie\");\n#Жж Zh zh \n equalLat(\"Житомир Жанна Жеж", "end": 1623, "score": 0.8188996315002441, "start": 1596, "tag": "NAME", "value": "Yenakiieve Haievych Koropie" }, { "context": "Zh zh \n equalLat(\"Житомир Жанна Жежелів\", \"Zhytomyr Zhanna Zhezheliv\");\n#Зз Zz \n equalLat(\"Закарпаття Казимирчу", "end": 1706, "score": 0.9729613661766052, "start": 1681, "tag": "NAME", "value": "Zhytomyr Zhanna Zhezheliv" }, { "context": "Зз Zz \n equalLat(\"Закарпаття Казимирчук\", \"Zakarpattia Kazymyrchuk\");\n#Ии Yy \n equalLat(\"Медвин Михайленко\", ", "end": 1784, "score": 0.94585782289505, "start": 1761, "tag": "NAME", "value": "Zakarpattia Kazymyrchuk" }, { "context": "ttia Kazymyrchuk\");\n#Ии Yy \n equalLat(\"Медвин Михайленко\", \"Medvyn Mykhailenko\");\n#Іі Ii \n equalLat", "end": 1831, "score": 0.8087376952171326, "start": 1818, "tag": "NAME", "value": "ин Михайленко" }, { "context": ");\n#Ии Yy \n equalLat(\"Медвин Михайленко\", \"Medvyn Mykhailenko\");\n#Іі Ii \n equalLat(\"Іванків Іващенко\", \"", "end": 1853, "score": 0.9942730069160461, "start": 1835, "tag": "NAME", "value": "Medvyn Mykhailenko" }, { "context": "\");\n#Іі Ii \n equalLat(\"Іванків Іващенко\", \"Ivankiv Ivashchenko\");\n#Її Yi i на початку слова в інших позиціях \n ", "end": 1922, "score": 0.9844180345535278, "start": 1903, "tag": "NAME", "value": "Ivankiv Ivashchenko" }, { "context": "t(\"Їжакевич Кадиївка Мар’їне\", \"Yizhakevych Kadyivka Marine\");\n#Йй Y i на початку слова в інших позиці", "end": 2037, "score": 0.6354727745056152, "start": 2035, "tag": "NAME", "value": "ka" }, { "context": "кевич Кадиївка Мар’їне\", \"Yizhakevych Kadyivka Marine\");\n#Йй Y i на початку слова в інших позиціях \n ", "end": 2044, "score": 0.83400559425354, "start": 2041, "tag": "NAME", "value": "ine" }, { "context": "ii\");\n#Кк Kk \n equalLat(\"Київ Коваленко\", \"Kyiv Kovalenko\");\n#Лл Ll \n equalLat(\"Лебедин Леонід\", \"Le", "end": 2221, "score": 0.9520142674446106, "start": 2207, "tag": "NAME", "value": "Kyiv Kovalenko" }, { "context": "ko\");\n#Лл Ll \n equalLat(\"Лебедин Леонід\", \"Lebedyn Leonid\");\n#Мм Mm \n equalLat(\"Миколаїв Мари", "end": 2276, "score": 0.717772364616394, "start": 2269, "tag": "NAME", "value": "Lebedyn" }, { "context": "Ll \n equalLat(\"Лебедин Леонід\", \"Lebedyn Leonid\");\n#Мм Mm \n equalLat(\"Миколаїв Маринич\", \"", "end": 2283, "score": 0.8318785429000854, "start": 2279, "tag": "NAME", "value": "onid" }, { "context": "dyn Leonid\");\n#Мм Mm \n equalLat(\"Миколаїв Маринич\", \"Mykolaiv Marynych\");\n#Нн Nn \n equalLat(", "end": 2329, "score": 0.7988502383232117, "start": 2323, "tag": "NAME", "value": "аринич" }, { "context": "\");\n#Мм Mm \n equalLat(\"Миколаїв Маринич\", \"Mykolaiv Marynych\");\n#Нн Nn \n equalLat(\"Ніжин Наталія\", \"Niz", "end": 2350, "score": 0.9979048371315002, "start": 2333, "tag": "NAME", "value": "Mykolaiv Marynych" }, { "context": "ych\");\n#Нн Nn \n equalLat(\"Ніжин Наталія\", \"Nizhyn Nataliia\");\n#Оо Oo \n equalLat(\"Одеса Онищенко\", \"Od", "end": 2412, "score": 0.9985107779502869, "start": 2397, "tag": "NAME", "value": "Nizhyn Nataliia" }, { "context": "ia\");\n#Оо Oo \n equalLat(\"Одеса Онищенко\", \"Odesa Onyshchenko\");\n#Пп Pp \n equalLat(\"Полтава Петро\", \"Pol", "end": 2477, "score": 0.9653029441833496, "start": 2460, "tag": "NAME", "value": "Odesa Onyshchenko" }, { "context": ", \"Odesa Onyshchenko\");\n#Пп Pp \n equalLat(\"Полтава Петро\", \"Poltava Petro\");\n#Рр Rr \n equalLat(\"Реш", "end": 2520, "score": 0.9301679134368896, "start": 2507, "tag": "NAME", "value": "Полтава Петро" }, { "context": "nko\");\n#Пп Pp \n equalLat(\"Полтава Петро\", \"Poltava Petro\");\n#Рр Rr \n equalLat(\"Решетилівка Рибчинсь", "end": 2537, "score": 0.9919716119766235, "start": 2524, "tag": "NAME", "value": "Poltava Petro" }, { "context": " Rr \n equalLat(\"Решетилівка Рибчинський\", \"Reshetylivka Rybchynskyi\");\n#Сс Ss \n equalLat(\"Суми Соломія\", \"Sumy", "end": 2618, "score": 0.9441753625869751, "start": 2594, "tag": "NAME", "value": "Reshetylivka Rybchynskyi" }, { "context": "skyi\");\n#Сс Ss \n equalLat(\"Суми Соломія\", \"Sumy Solomiia\");\n#Тт Tt \n equalLat(\"Тернопіль Троц", "end": 2671, "score": 0.6607028245925903, "start": 2664, "tag": "NAME", "value": "Sumy So" }, { "context": "\");\n#Тт Tt \n equalLat(\"Тернопіль Троць\", \"Ternopil Trots\");\n#Уу Uu \n equalLat(\"Ужгород Уляна\", \"Uzh", "end": 2740, "score": 0.7458456754684448, "start": 2727, "tag": "NAME", "value": "ernopil Trots" }, { "context": "a\");\n#Фф Ff \n equalLat(\"Фастів Філіпчук\", \"Fastiv Filipchuk\");\n#Хх Kh kh \n equalLat(\"Харків Христина", "end": 2865, "score": 0.7238187789916992, "start": 2851, "tag": "NAME", "value": "Fastiv Filipch" }, { "context": " Ts ts \n equalLat(\"Біла Церква Стеценко\", \"Bila Tserkva Stetsenko\");\n#Чч Ch ch \n equalLat(\"Чернівці Шевченко", "end": 3015, "score": 0.9616019129753113, "start": 2993, "tag": "NAME", "value": "Bila Tserkva Stetsenko" }, { "context": "#Чч Ch ch \n equalLat(\"Чернівці Шевченко\", \"Chernivtsi Shevchenko\");\n#Шш Sh sh \n equalLat(\"Шостка Кишеньки\",", "end": 3090, "score": 0.9464852213859558, "start": 3069, "tag": "NAME", "value": "Chernivtsi Shevchenko" }, { "context": "shch \n equalLat(\"Щербухи Гоща Гаращенко\", \"Shcherbukhy Hoshcha Harashchenko\");\n#Юю Yu іu на початку слова в інших позиціях \n ", "end": 3253, "score": 0.8576577305793762, "start": 3221, "tag": "NAME", "value": "Shcherbukhy Hoshcha Harashchenko" }, { "context": "початку слова в інших позиціях \n equalLat(\"Яготин Ярошенко Костянтин Знам’янка Феодосія\", \"Yahotyn Yaroshenko Kostiantyn Znamianka Fe", "end": 3461, "score": 0.9503079652786255, "start": 3421, "tag": "NAME", "value": "Яготин Ярошенко Костянтин Знам’янка Феод" }, { "context": "(\"Яготин Ярошенко Костянтин Знам’янка Феодосія\", \"Yahotyn Yaroshenko Kostiantyn Znamianka Feodosiia\");\n\ntest_generateLat()\ntest_ukrainianToLatin()\nco", "end": 3518, "score": 0.9997081756591797, "start": 3469, "tag": "NAME", "value": "Yahotyn Yaroshenko Kostiantyn Znamianka Feodosiia" } ]
src/test/coffee/ukrainiantolatin.test.coffee
HappyFacade/ukrainiantolatin
4
# ukrainiantolatin.test.coffee conv = require '../../main/coffee/ukrainiantolatin.coffee' equal = (expected, actual) -> throw new Error(expected + " != " + actual) if expected != actual test_generateLat = ()-> equal("", conv.UkrainianToLatin.generateLat("")); equal("abvhd", conv.UkrainianToLatin.generateLat("абвгд")); equal("abvhd kh", conv.UkrainianToLatin.generateLat("абвгд х")); equal("abvhd kh yulia", conv.UkrainianToLatin.generateLat("абвгд х юля")); equal("yizhak", conv.UkrainianToLatin.generateLat("їжак")); equal("yizhaksiryi", conv.UkrainianToLatin.generateLat("їжак-сірий")); equal("Rozghon", conv.UkrainianToLatin.generateLat("Розгон")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани'")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани’")); equalLat = (expected, actual) -> equal(actual, conv.UkrainianToLatin.generateLat(expected)) test_ukrainianToLatin = ()-> #Аа Aа equalLat("Алушта Андрій", "Alushta Andrii"); #Бб Bb equalLat("Борщагівка Борисенко", "Borshchahivka Borysenko"); #Вв Vv equalLat("Вінниця Володимир", "Vinnytsia Volodymyr"); #Гг Hh equalLat("Гадяч Богдан Згурський", "Hadiach Bohdan Zghurskyi"); #Ґґ Gg equalLat("Ґалаґан Ґорґани", "Galagan Gorgany"); #Дд Dd equalLat("Донецьк Дмитро", "Donetsk Dmytro"); #Ее Eе equalLat("Рівне Олег Есмань", "Rivne Oleh Esman"); #Єє Ye ie на початку слова в інших позиціях equalLat("Єнакієве Гаєвич Короп’є", "Yenakiieve Haievych Koropie"); #Жж Zh zh equalLat("Житомир Жанна Жежелів", "Zhytomyr Zhanna Zhezheliv"); #Зз Zz equalLat("Закарпаття Казимирчук", "Zakarpattia Kazymyrchuk"); #Ии Yy equalLat("Медвин Михайленко", "Medvyn Mykhailenko"); #Іі Ii equalLat("Іванків Іващенко", "Ivankiv Ivashchenko"); #Її Yi i на початку слова в інших позиціях equalLat("Їжакевич Кадиївка Мар’їне", "Yizhakevych Kadyivka Marine"); #Йй Y i на початку слова в інших позиціях equalLat("Йосипівка Стрий Олексій", "Yosypivka Stryi Oleksii"); #Кк Kk equalLat("Київ Коваленко", "Kyiv Kovalenko"); #Лл Ll equalLat("Лебедин Леонід", "Lebedyn Leonid"); #Мм Mm equalLat("Миколаїв Маринич", "Mykolaiv Marynych"); #Нн Nn equalLat("Ніжин Наталія", "Nizhyn Nataliia"); #Оо Oo equalLat("Одеса Онищенко", "Odesa Onyshchenko"); #Пп Pp equalLat("Полтава Петро", "Poltava Petro"); #Рр Rr equalLat("Решетилівка Рибчинський", "Reshetylivka Rybchynskyi"); #Сс Ss equalLat("Суми Соломія", "Sumy Solomiia"); #Тт Tt equalLat("Тернопіль Троць", "Ternopil Trots"); #Уу Uu equalLat("Ужгород Уляна", "Uzhhorod Uliana"); #Фф Ff equalLat("Фастів Філіпчук", "Fastiv Filipchuk"); #Хх Kh kh equalLat("Харків Христина", "Kharkiv Khrystyna"); #Цц Ts ts equalLat("Біла Церква Стеценко", "Bila Tserkva Stetsenko"); #Чч Ch ch equalLat("Чернівці Шевченко", "Chernivtsi Shevchenko"); #Шш Sh sh equalLat("Шостка Кишеньки", "Shostka Kyshenky"); #Щщ Shch shch equalLat("Щербухи Гоща Гаращенко", "Shcherbukhy Hoshcha Harashchenko"); #Юю Yu іu на початку слова в інших позиціях equalLat("Юрій Корюківка", "Yurii Koriukivka"); #Яя Ya ia на початку слова в інших позиціях equalLat("Яготин Ярошенко Костянтин Знам’янка Феодосія", "Yahotyn Yaroshenko Kostiantyn Znamianka Feodosiia"); test_generateLat() test_ukrainianToLatin() console.log "Tests were run test_generateLat(), test_ukrainianToLatin()"
207736
# ukrainiantolatin.test.coffee conv = require '../../main/coffee/ukrainiantolatin.coffee' equal = (expected, actual) -> throw new Error(expected + " != " + actual) if expected != actual test_generateLat = ()-> equal("", conv.UkrainianToLatin.generateLat("")); equal("abvhd", conv.UkrainianToLatin.generateLat("абвгд")); equal("abvhd kh", conv.UkrainianToLatin.generateLat("абвгд х")); equal("abvhd kh yulia", conv.UkrainianToLatin.generateLat("абвгд х юля")); equal("yizhak", conv.UkrainianToLatin.generateLat("їжак")); equal("yizhaksiryi", conv.UkrainianToLatin.generateLat("їжак-сірий")); equal("Rozghon", conv.UkrainianToLatin.generateLat("Розгон")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани'")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани’")); equalLat = (expected, actual) -> equal(actual, conv.UkrainianToLatin.generateLat(expected)) test_ukrainianToLatin = ()-> #Аа Aа equalLat("Алушта Андрій", "<NAME>"); #Бб Bb equalLat("Борщагівка Борисенко", "<NAME>"); #Вв Vv equalLat("Вінниця Володимир", "<NAME>"); #Гг Hh equalLat("Гадяч Богдан Згурський", "<NAME>"); #Ґґ Gg equalLat("Ґалаґан Ґорґани", "<NAME>"); #Дд Dd equalLat("Донецьк Д<NAME>итро", "<NAME>"); #Ее Eе equalLat("Рівне Олег Есмань", "<NAME>"); #Єє Ye ie на початку слова в інших позиціях equalLat("Єнакієве Гаєвич Короп’є", "<NAME>"); #Жж Zh zh equalLat("Житомир Жанна Жежелів", "<NAME>"); #Зз Zz equalLat("Закарпаття Казимирчук", "<NAME>"); #Ии Yy equalLat("Медв<NAME>", "<NAME>"); #Іі Ii equalLat("Іванків Іващенко", "<NAME>"); #Її Yi i на початку слова в інших позиціях equalLat("Їжакевич Кадиївка Мар’їне", "Yizhakevych Kadyiv<NAME> Mar<NAME>"); #Йй Y i на початку слова в інших позиціях equalLat("Йосипівка Стрий Олексій", "Yosypivka Stryi Oleksii"); #Кк Kk equalLat("Київ Коваленко", "<NAME>"); #Лл Ll equalLat("Лебедин Леонід", "<NAME> Le<NAME>"); #Мм Mm equalLat("Миколаїв М<NAME>", "<NAME>"); #Нн Nn equalLat("Ніжин Наталія", "<NAME>"); #Оо Oo equalLat("Одеса Онищенко", "<NAME>"); #Пп Pp equalLat("<NAME>", "<NAME>"); #Рр Rr equalLat("Решетилівка Рибчинський", "<NAME>"); #Сс Ss equalLat("Суми Соломія", "<NAME>lomiia"); #Тт Tt equalLat("Тернопіль Троць", "T<NAME>"); #Уу Uu equalLat("Ужгород Уляна", "Uzhhorod Uliana"); #Фф Ff equalLat("Фастів Філіпчук", "<NAME>uk"); #Хх Kh kh equalLat("Харків Христина", "Kharkiv Khrystyna"); #Цц Ts ts equalLat("Біла Церква Стеценко", "<NAME>"); #Чч Ch ch equalLat("Чернівці Шевченко", "<NAME>"); #Шш Sh sh equalLat("Шостка Кишеньки", "Shostka Kyshenky"); #Щщ Shch shch equalLat("Щербухи Гоща Гаращенко", "<NAME>"); #Юю Yu іu на початку слова в інших позиціях equalLat("Юрій Корюківка", "Yurii Koriukivka"); #Яя Ya ia на початку слова в інших позиціях equalLat("<NAME>осія", "<NAME>"); test_generateLat() test_ukrainianToLatin() console.log "Tests were run test_generateLat(), test_ukrainianToLatin()"
true
# ukrainiantolatin.test.coffee conv = require '../../main/coffee/ukrainiantolatin.coffee' equal = (expected, actual) -> throw new Error(expected + " != " + actual) if expected != actual test_generateLat = ()-> equal("", conv.UkrainianToLatin.generateLat("")); equal("abvhd", conv.UkrainianToLatin.generateLat("абвгд")); equal("abvhd kh", conv.UkrainianToLatin.generateLat("абвгд х")); equal("abvhd kh yulia", conv.UkrainianToLatin.generateLat("абвгд х юля")); equal("yizhak", conv.UkrainianToLatin.generateLat("їжак")); equal("yizhaksiryi", conv.UkrainianToLatin.generateLat("їжак-сірий")); equal("Rozghon", conv.UkrainianToLatin.generateLat("Розгон")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани'")); equal("Zghorany", conv.UkrainianToLatin.generateLat("Згорани’")); equalLat = (expected, actual) -> equal(actual, conv.UkrainianToLatin.generateLat(expected)) test_ukrainianToLatin = ()-> #Аа Aа equalLat("Алушта Андрій", "PI:NAME:<NAME>END_PI"); #Бб Bb equalLat("Борщагівка Борисенко", "PI:NAME:<NAME>END_PI"); #Вв Vv equalLat("Вінниця Володимир", "PI:NAME:<NAME>END_PI"); #Гг Hh equalLat("Гадяч Богдан Згурський", "PI:NAME:<NAME>END_PI"); #Ґґ Gg equalLat("Ґалаґан Ґорґани", "PI:NAME:<NAME>END_PI"); #Дд Dd equalLat("Донецьк ДPI:NAME:<NAME>END_PIитро", "PI:NAME:<NAME>END_PI"); #Ее Eе equalLat("Рівне Олег Есмань", "PI:NAME:<NAME>END_PI"); #Єє Ye ie на початку слова в інших позиціях equalLat("Єнакієве Гаєвич Короп’є", "PI:NAME:<NAME>END_PI"); #Жж Zh zh equalLat("Житомир Жанна Жежелів", "PI:NAME:<NAME>END_PI"); #Зз Zz equalLat("Закарпаття Казимирчук", "PI:NAME:<NAME>END_PI"); #Ии Yy equalLat("МедвPI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"); #Іі Ii equalLat("Іванків Іващенко", "PI:NAME:<NAME>END_PI"); #Її Yi i на початку слова в інших позиціях equalLat("Їжакевич Кадиївка Мар’їне", "Yizhakevych KadyivPI:NAME:<NAME>END_PI MarPI:NAME:<NAME>END_PI"); #Йй Y i на початку слова в інших позиціях equalLat("Йосипівка Стрий Олексій", "Yosypivka Stryi Oleksii"); #Кк Kk equalLat("Київ Коваленко", "PI:NAME:<NAME>END_PI"); #Лл Ll equalLat("Лебедин Леонід", "PI:NAME:<NAME>END_PI LePI:NAME:<NAME>END_PI"); #Мм Mm equalLat("Миколаїв МPI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"); #Нн Nn equalLat("Ніжин Наталія", "PI:NAME:<NAME>END_PI"); #Оо Oo equalLat("Одеса Онищенко", "PI:NAME:<NAME>END_PI"); #Пп Pp equalLat("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"); #Рр Rr equalLat("Решетилівка Рибчинський", "PI:NAME:<NAME>END_PI"); #Сс Ss equalLat("Суми Соломія", "PI:NAME:<NAME>END_PIlomiia"); #Тт Tt equalLat("Тернопіль Троць", "TPI:NAME:<NAME>END_PI"); #Уу Uu equalLat("Ужгород Уляна", "Uzhhorod Uliana"); #Фф Ff equalLat("Фастів Філіпчук", "PI:NAME:<NAME>END_PIuk"); #Хх Kh kh equalLat("Харків Христина", "Kharkiv Khrystyna"); #Цц Ts ts equalLat("Біла Церква Стеценко", "PI:NAME:<NAME>END_PI"); #Чч Ch ch equalLat("Чернівці Шевченко", "PI:NAME:<NAME>END_PI"); #Шш Sh sh equalLat("Шостка Кишеньки", "Shostka Kyshenky"); #Щщ Shch shch equalLat("Щербухи Гоща Гаращенко", "PI:NAME:<NAME>END_PI"); #Юю Yu іu на початку слова в інших позиціях equalLat("Юрій Корюківка", "Yurii Koriukivka"); #Яя Ya ia на початку слова в інших позиціях equalLat("PI:NAME:<NAME>END_PIосія", "PI:NAME:<NAME>END_PI"); test_generateLat() test_ukrainianToLatin() console.log "Tests were run test_generateLat(), test_ukrainianToLatin()"
[ { "context": "rune/\n# JSON.prune on github : https://github.com/Canop/JSON.prune\n# This was discussed here : http://sta", "end": 522, "score": 0.9990884065628052, "start": 517, "tag": "USERNAME", "value": "Canop" }, { "context": "rflow.com/q/13861254/263525\n# The code is based on Douglas Crockford's code : https://github.com/dougl", "end": 629, "score": 0.6281924843788147, "start": 628, "tag": "NAME", "value": "D" }, { "context": "w.com/q/13861254/263525\n# The code is based on Douglas Crockford's code : https://github.com/douglascroc", "end": 635, "score": 0.6266035437583923, "start": 631, "tag": "NAME", "value": "glas" }, { "context": " on Douglas Crockford's code : https://github.com/douglascrockford/JSON-js/blob/master/json2.js\n# No effort was done", "end": 690, "score": 0.9995362162590027, "start": 674, "tag": "USERNAME", "value": "douglascrockford" } ]
GOTHAM/Backend/src/Tools/JSON.coffee
perara/gotham
0
# JSON.prune : a function to stringify any object without overflow # two additional optional parameters : # - the maximal depth (default : 6) # - the maximal length of arrays (default : 50) # You can also pass an "options" object. # examples : # var json = JSON.prune(window) # var arr = Array.apply(0,Array(1000)); var json = JSON.prune(arr, 4, 20) # var json = JSON.prune(window.location, {inheritedProperties:true}) # Web site : http://dystroy.org/JSON.prune/ # JSON.prune on github : https://github.com/Canop/JSON.prune # This was discussed here : http://stackoverflow.com/q/13861254/263525 # The code is based on Douglas Crockford's code : https://github.com/douglascrockford/JSON-js/blob/master/json2.js # No effort was done to support old browsers. JSON.prune will fail on IE8. do -> quote = (string) -> escapable.lastIndex = 0 if escapable.test(string) then '"' + string.replace(escapable, ((a) -> c = meta[a] if typeof c == 'string' then c else '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4) )) + '"' else '"' + string + '"' str = (key, holder, depthDecr, arrayMaxLength) -> i = undefined k = undefined v = undefined length = undefined partial = undefined value = holder[key] if value and typeof value == 'object' and typeof value.toPrunedJSON == 'function' value = value.toPrunedJSON(key) switch typeof value when 'string' return quote(value) when 'number' return if isFinite(value) then String(value) else 'null' when 'boolean', 'null' return String(value) when 'object' if !value return 'null' if depthDecr <= 0 or seen.indexOf(value) != -1 return '"-pruned-"' seen.push value partial = [] if Object::toString.apply(value) == '[object Array]' length = Math.min(value.length, arrayMaxLength) i = 0 while i < length partial[i] = str(i, value, depthDecr - 1, arrayMaxLength) or 'null' i += 1 return '[' + partial.join(',') + ']' iterator value, (k) -> try v = str(k, value, depthDecr - 1, arrayMaxLength) if v partial.push quote(k) + ':' + v catch e # this try/catch due to forbidden accessors on some objects return return '{' + partial.join(',') + '}' return 'use strict' DEFAULT_MAX_DEPTH = 6 DEFAULT_ARRAY_MAX_LENGTH = 50 seen = undefined # Same variable used for all stringifications iterator = undefined # either forEachEnumerableOwnProperty, forEachEnumerableProperty or forEachProperty # iterates on enumerable own properties (default behavior) forEachEnumerableOwnProperty = (obj, callback) -> for k of obj if Object::hasOwnProperty.call(obj, k) callback k return # iterates on enumerable properties forEachEnumerableProperty = (obj, callback) -> for k of obj callback k return # iterates on properties, even non enumerable and inherited ones # This is dangerous forEachProperty = (obj, callback, excluded) -> if obj == null return excluded = excluded or {} Object.getOwnPropertyNames(obj).forEach (k) -> if !excluded[k] callback k excluded[k] = true return forEachProperty Object.getPrototypeOf(obj), callback, excluded return Date::toPrunedJSON = Date::toJSON String::toPrunedJSON = String::toJSON cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g meta = '\\u8': '\\b' '\\u9': '\\t' '\\n': '\\n' '\\uc': '\\f' '\\ud': '\\r' '"': '\"' '\\': '\\\\' JSON.prune = (value, depthDecr, arrayMaxLength) -> if typeof depthDecr == 'object' options = depthDecr depthDecr = options.depthDecr arrayMaxLength = options.arrayMaxLength iterator = options.iterator or forEachEnumerableOwnProperty if options.allProperties iterator = forEachProperty else if options.inheritedProperties iterator = forEachEnumerableProperty else iterator = forEachEnumerableOwnProperty seen = [] depthDecr = depthDecr or DEFAULT_MAX_DEPTH arrayMaxLength = arrayMaxLength or DEFAULT_ARRAY_MAX_LENGTH str '', { '': value }, depthDecr, arrayMaxLength JSON.prune.log = -> console.log.apply console, Array::slice.call(arguments).map((v) -> JSON.parse JSON.prune(v) ) return JSON.prune.forEachProperty = forEachProperty # you might want to also assign it to Object.forEachProperty return # --- # generated by js2coffee 2.0.3
116621
# JSON.prune : a function to stringify any object without overflow # two additional optional parameters : # - the maximal depth (default : 6) # - the maximal length of arrays (default : 50) # You can also pass an "options" object. # examples : # var json = JSON.prune(window) # var arr = Array.apply(0,Array(1000)); var json = JSON.prune(arr, 4, 20) # var json = JSON.prune(window.location, {inheritedProperties:true}) # Web site : http://dystroy.org/JSON.prune/ # JSON.prune on github : https://github.com/Canop/JSON.prune # This was discussed here : http://stackoverflow.com/q/13861254/263525 # The code is based on <NAME>ou<NAME> Crockford's code : https://github.com/douglascrockford/JSON-js/blob/master/json2.js # No effort was done to support old browsers. JSON.prune will fail on IE8. do -> quote = (string) -> escapable.lastIndex = 0 if escapable.test(string) then '"' + string.replace(escapable, ((a) -> c = meta[a] if typeof c == 'string' then c else '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4) )) + '"' else '"' + string + '"' str = (key, holder, depthDecr, arrayMaxLength) -> i = undefined k = undefined v = undefined length = undefined partial = undefined value = holder[key] if value and typeof value == 'object' and typeof value.toPrunedJSON == 'function' value = value.toPrunedJSON(key) switch typeof value when 'string' return quote(value) when 'number' return if isFinite(value) then String(value) else 'null' when 'boolean', 'null' return String(value) when 'object' if !value return 'null' if depthDecr <= 0 or seen.indexOf(value) != -1 return '"-pruned-"' seen.push value partial = [] if Object::toString.apply(value) == '[object Array]' length = Math.min(value.length, arrayMaxLength) i = 0 while i < length partial[i] = str(i, value, depthDecr - 1, arrayMaxLength) or 'null' i += 1 return '[' + partial.join(',') + ']' iterator value, (k) -> try v = str(k, value, depthDecr - 1, arrayMaxLength) if v partial.push quote(k) + ':' + v catch e # this try/catch due to forbidden accessors on some objects return return '{' + partial.join(',') + '}' return 'use strict' DEFAULT_MAX_DEPTH = 6 DEFAULT_ARRAY_MAX_LENGTH = 50 seen = undefined # Same variable used for all stringifications iterator = undefined # either forEachEnumerableOwnProperty, forEachEnumerableProperty or forEachProperty # iterates on enumerable own properties (default behavior) forEachEnumerableOwnProperty = (obj, callback) -> for k of obj if Object::hasOwnProperty.call(obj, k) callback k return # iterates on enumerable properties forEachEnumerableProperty = (obj, callback) -> for k of obj callback k return # iterates on properties, even non enumerable and inherited ones # This is dangerous forEachProperty = (obj, callback, excluded) -> if obj == null return excluded = excluded or {} Object.getOwnPropertyNames(obj).forEach (k) -> if !excluded[k] callback k excluded[k] = true return forEachProperty Object.getPrototypeOf(obj), callback, excluded return Date::toPrunedJSON = Date::toJSON String::toPrunedJSON = String::toJSON cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g meta = '\\u8': '\\b' '\\u9': '\\t' '\\n': '\\n' '\\uc': '\\f' '\\ud': '\\r' '"': '\"' '\\': '\\\\' JSON.prune = (value, depthDecr, arrayMaxLength) -> if typeof depthDecr == 'object' options = depthDecr depthDecr = options.depthDecr arrayMaxLength = options.arrayMaxLength iterator = options.iterator or forEachEnumerableOwnProperty if options.allProperties iterator = forEachProperty else if options.inheritedProperties iterator = forEachEnumerableProperty else iterator = forEachEnumerableOwnProperty seen = [] depthDecr = depthDecr or DEFAULT_MAX_DEPTH arrayMaxLength = arrayMaxLength or DEFAULT_ARRAY_MAX_LENGTH str '', { '': value }, depthDecr, arrayMaxLength JSON.prune.log = -> console.log.apply console, Array::slice.call(arguments).map((v) -> JSON.parse JSON.prune(v) ) return JSON.prune.forEachProperty = forEachProperty # you might want to also assign it to Object.forEachProperty return # --- # generated by js2coffee 2.0.3
true
# JSON.prune : a function to stringify any object without overflow # two additional optional parameters : # - the maximal depth (default : 6) # - the maximal length of arrays (default : 50) # You can also pass an "options" object. # examples : # var json = JSON.prune(window) # var arr = Array.apply(0,Array(1000)); var json = JSON.prune(arr, 4, 20) # var json = JSON.prune(window.location, {inheritedProperties:true}) # Web site : http://dystroy.org/JSON.prune/ # JSON.prune on github : https://github.com/Canop/JSON.prune # This was discussed here : http://stackoverflow.com/q/13861254/263525 # The code is based on PI:NAME:<NAME>END_PIouPI:NAME:<NAME>END_PI Crockford's code : https://github.com/douglascrockford/JSON-js/blob/master/json2.js # No effort was done to support old browsers. JSON.prune will fail on IE8. do -> quote = (string) -> escapable.lastIndex = 0 if escapable.test(string) then '"' + string.replace(escapable, ((a) -> c = meta[a] if typeof c == 'string' then c else '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4) )) + '"' else '"' + string + '"' str = (key, holder, depthDecr, arrayMaxLength) -> i = undefined k = undefined v = undefined length = undefined partial = undefined value = holder[key] if value and typeof value == 'object' and typeof value.toPrunedJSON == 'function' value = value.toPrunedJSON(key) switch typeof value when 'string' return quote(value) when 'number' return if isFinite(value) then String(value) else 'null' when 'boolean', 'null' return String(value) when 'object' if !value return 'null' if depthDecr <= 0 or seen.indexOf(value) != -1 return '"-pruned-"' seen.push value partial = [] if Object::toString.apply(value) == '[object Array]' length = Math.min(value.length, arrayMaxLength) i = 0 while i < length partial[i] = str(i, value, depthDecr - 1, arrayMaxLength) or 'null' i += 1 return '[' + partial.join(',') + ']' iterator value, (k) -> try v = str(k, value, depthDecr - 1, arrayMaxLength) if v partial.push quote(k) + ':' + v catch e # this try/catch due to forbidden accessors on some objects return return '{' + partial.join(',') + '}' return 'use strict' DEFAULT_MAX_DEPTH = 6 DEFAULT_ARRAY_MAX_LENGTH = 50 seen = undefined # Same variable used for all stringifications iterator = undefined # either forEachEnumerableOwnProperty, forEachEnumerableProperty or forEachProperty # iterates on enumerable own properties (default behavior) forEachEnumerableOwnProperty = (obj, callback) -> for k of obj if Object::hasOwnProperty.call(obj, k) callback k return # iterates on enumerable properties forEachEnumerableProperty = (obj, callback) -> for k of obj callback k return # iterates on properties, even non enumerable and inherited ones # This is dangerous forEachProperty = (obj, callback, excluded) -> if obj == null return excluded = excluded or {} Object.getOwnPropertyNames(obj).forEach (k) -> if !excluded[k] callback k excluded[k] = true return forEachProperty Object.getPrototypeOf(obj), callback, excluded return Date::toPrunedJSON = Date::toJSON String::toPrunedJSON = String::toJSON cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g meta = '\\u8': '\\b' '\\u9': '\\t' '\\n': '\\n' '\\uc': '\\f' '\\ud': '\\r' '"': '\"' '\\': '\\\\' JSON.prune = (value, depthDecr, arrayMaxLength) -> if typeof depthDecr == 'object' options = depthDecr depthDecr = options.depthDecr arrayMaxLength = options.arrayMaxLength iterator = options.iterator or forEachEnumerableOwnProperty if options.allProperties iterator = forEachProperty else if options.inheritedProperties iterator = forEachEnumerableProperty else iterator = forEachEnumerableOwnProperty seen = [] depthDecr = depthDecr or DEFAULT_MAX_DEPTH arrayMaxLength = arrayMaxLength or DEFAULT_ARRAY_MAX_LENGTH str '', { '': value }, depthDecr, arrayMaxLength JSON.prune.log = -> console.log.apply console, Array::slice.call(arguments).map((v) -> JSON.parse JSON.prune(v) ) return JSON.prune.forEachProperty = forEachProperty # you might want to also assign it to Object.forEachProperty return # --- # generated by js2coffee 2.0.3
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999122619628906, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/_classes/forum-post-preview.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @ForumPostPreview constructor: -> $(document).on 'click', '.js-forum-post-preview--show', @fetchPreview $(document).on 'click', '.js-forum-post-preview--hide', @hidePreview fetchPreview: (e) => $form = $(e.target).parents('.js-forum-post-preview--form') $preview = $form.find('.js-forum-post-preview--preview') $body = $form.find('.js-forum-post-preview--body') text = $body.val() lastText = $body.attr('data-last-text') return if $form.attr('data-state') == 'preview' return unless osu.present(text) if text == $body.attr('data-last-text') @showPreview(e) return $form.attr('data-state', 'loading-preview') $.ajax url: laroute.route 'bbcode-preview' method: 'POST' data: { text } .done (data) => $body.attr('data-last-text', text) $preview.html(data) osu.pageChange() @showPreview(e) showPreview: (e) => $(e.target).parents('.js-forum-post-preview--form').attr('data-state', 'preview') osu.pageChange() # sync height of reply box hidePreview: (e) => $form = $(e.target).parents('.js-forum-post-preview--form') $form.attr('data-state', 'write') osu.pageChange() # sync height of reply box $form.find('.js-forum-post-preview--body').focus()
180483
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @ForumPostPreview constructor: -> $(document).on 'click', '.js-forum-post-preview--show', @fetchPreview $(document).on 'click', '.js-forum-post-preview--hide', @hidePreview fetchPreview: (e) => $form = $(e.target).parents('.js-forum-post-preview--form') $preview = $form.find('.js-forum-post-preview--preview') $body = $form.find('.js-forum-post-preview--body') text = $body.val() lastText = $body.attr('data-last-text') return if $form.attr('data-state') == 'preview' return unless osu.present(text) if text == $body.attr('data-last-text') @showPreview(e) return $form.attr('data-state', 'loading-preview') $.ajax url: laroute.route 'bbcode-preview' method: 'POST' data: { text } .done (data) => $body.attr('data-last-text', text) $preview.html(data) osu.pageChange() @showPreview(e) showPreview: (e) => $(e.target).parents('.js-forum-post-preview--form').attr('data-state', 'preview') osu.pageChange() # sync height of reply box hidePreview: (e) => $form = $(e.target).parents('.js-forum-post-preview--form') $form.attr('data-state', 'write') osu.pageChange() # sync height of reply box $form.find('.js-forum-post-preview--body').focus()
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. class @ForumPostPreview constructor: -> $(document).on 'click', '.js-forum-post-preview--show', @fetchPreview $(document).on 'click', '.js-forum-post-preview--hide', @hidePreview fetchPreview: (e) => $form = $(e.target).parents('.js-forum-post-preview--form') $preview = $form.find('.js-forum-post-preview--preview') $body = $form.find('.js-forum-post-preview--body') text = $body.val() lastText = $body.attr('data-last-text') return if $form.attr('data-state') == 'preview' return unless osu.present(text) if text == $body.attr('data-last-text') @showPreview(e) return $form.attr('data-state', 'loading-preview') $.ajax url: laroute.route 'bbcode-preview' method: 'POST' data: { text } .done (data) => $body.attr('data-last-text', text) $preview.html(data) osu.pageChange() @showPreview(e) showPreview: (e) => $(e.target).parents('.js-forum-post-preview--form').attr('data-state', 'preview') osu.pageChange() # sync height of reply box hidePreview: (e) => $form = $(e.target).parents('.js-forum-post-preview--form') $form.attr('data-state', 'write') osu.pageChange() # sync height of reply box $form.find('.js-forum-post-preview--body').focus()
[ { "context": "ction View\nContains buttons that do stuff\n\n@author Roelof Roos (https://github.com/roelofr)\n###\n\n{View} = requir", "end": 78, "score": 0.9998788237571716, "start": 67, "tag": "NAME", "value": "Roelof Roos" }, { "context": "do stuff\n\n@author Roelof Roos (https://github.com/roelofr)\n###\n\n{View} = require 'space-pen'\n\nmodule.export", "end": 106, "score": 0.9996383190155029, "start": 99, "tag": "USERNAME", "value": "roelofr" } ]
lib/views/action-view.coffee
roelofr/php-report
0
### PHP Report Action View Contains buttons that do stuff @author Roelof Roos (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class ActionView extends View @buttons: btn_run: ['run', 'primary', 'playback-play', 'Start'], btn_kill: ['kill', 'default', 'flame', 'Abort'], btn_clear: ['clear', 'default', 'trashcan', null] @content: -> @div class: 'php-report__actions', outlet: 'elem_actions', => @div class: 'block pull-right', => for outlet, data of @buttons config = 'data-click': data[0], outlet: outlet, class: "btn btn-#{data[1]} icon icon-#{data[2]} inline-block" if data[3] @button config, data[3] else @button config reporter: null initialize: (phpReport) -> @reporter = phpReport @btn_run.on 'click', -> phpReport.runnerStart() @btn_kill.on 'click', -> phpReport.runnerStop() @btn_clear.on 'click', -> phpReport.trigger 'clean' phpReport.on 'start', => @changeButtons yes phpReport.on 'stop', => @changeButtons no @changeButtons no clear: -> @reporter.clear() changeButtons: (active) -> unless active @btn_run.removeAttr('disabled') @btn_clear.removeAttr('disabled') @btn_kill.attr('disabled', 'disabled') else @btn_run.attr('disabled', 'disabled') @btn_clear.attr('disabled', 'disabled') @btn_kill.removeAttr('disabled')
124630
### PHP Report Action View Contains buttons that do stuff @author <NAME> (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class ActionView extends View @buttons: btn_run: ['run', 'primary', 'playback-play', 'Start'], btn_kill: ['kill', 'default', 'flame', 'Abort'], btn_clear: ['clear', 'default', 'trashcan', null] @content: -> @div class: 'php-report__actions', outlet: 'elem_actions', => @div class: 'block pull-right', => for outlet, data of @buttons config = 'data-click': data[0], outlet: outlet, class: "btn btn-#{data[1]} icon icon-#{data[2]} inline-block" if data[3] @button config, data[3] else @button config reporter: null initialize: (phpReport) -> @reporter = phpReport @btn_run.on 'click', -> phpReport.runnerStart() @btn_kill.on 'click', -> phpReport.runnerStop() @btn_clear.on 'click', -> phpReport.trigger 'clean' phpReport.on 'start', => @changeButtons yes phpReport.on 'stop', => @changeButtons no @changeButtons no clear: -> @reporter.clear() changeButtons: (active) -> unless active @btn_run.removeAttr('disabled') @btn_clear.removeAttr('disabled') @btn_kill.attr('disabled', 'disabled') else @btn_run.attr('disabled', 'disabled') @btn_clear.attr('disabled', 'disabled') @btn_kill.removeAttr('disabled')
true
### PHP Report Action View Contains buttons that do stuff @author PI:NAME:<NAME>END_PI (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class ActionView extends View @buttons: btn_run: ['run', 'primary', 'playback-play', 'Start'], btn_kill: ['kill', 'default', 'flame', 'Abort'], btn_clear: ['clear', 'default', 'trashcan', null] @content: -> @div class: 'php-report__actions', outlet: 'elem_actions', => @div class: 'block pull-right', => for outlet, data of @buttons config = 'data-click': data[0], outlet: outlet, class: "btn btn-#{data[1]} icon icon-#{data[2]} inline-block" if data[3] @button config, data[3] else @button config reporter: null initialize: (phpReport) -> @reporter = phpReport @btn_run.on 'click', -> phpReport.runnerStart() @btn_kill.on 'click', -> phpReport.runnerStop() @btn_clear.on 'click', -> phpReport.trigger 'clean' phpReport.on 'start', => @changeButtons yes phpReport.on 'stop', => @changeButtons no @changeButtons no clear: -> @reporter.clear() changeButtons: (active) -> unless active @btn_run.removeAttr('disabled') @btn_clear.removeAttr('disabled') @btn_kill.attr('disabled', 'disabled') else @btn_run.attr('disabled', 'disabled') @btn_clear.attr('disabled', 'disabled') @btn_kill.removeAttr('disabled')
[ { "context": "dify_footer() {\n\techo 'Created by <a href=\"mailto:you@example.com\">you</a>.';\n}\nadd_filter( 'admin_footer_text', 'm", "end": 2746, "score": 0.999843955039978, "start": 2731, "tag": "EMAIL", "value": "you@example.com" }, { "context": " $excerpt_more;\n\t\t?>\n<meta name=\"author\" content=\"Your Name\">\n<meta name=\"description\" content=\"<?php echo $e", "end": 11415, "score": 0.9605134725570679, "start": 11406, "tag": "NAME", "value": "Your Name" } ]
snippets/wp-functions.cson
Alicannklc/wp-functions-snippets
1
".text.html.php": "Hide WordPress Update Nag to All But Admins": "prefix": "hidea" "body": """ /** * Hide WordPress Update Nag to All But Admins */ function hide_update_notice_to_all_but_admin() { if ( !current_user_can( 'update_core' ) ) { remove_action( 'admin_notices', 'update_nag', 3 ); } } add_action( 'admin_head', 'hide_update_notice_to_all_but_admin', 1 ); """ "Create Proper WordPress Titles": "prefix": "tt" "body": """ /** * Create Proper WordPress Titles */ add_theme_support( 'title-tag' ); """ "Create Custom WordPress Dashboard Widget": "prefix": "cwdw" "body": """ /** * Create Custom WordPress Dashboard Widget */ function dashboard_widget_function() { echo ' <h2>Custom Dashboard Widget</h2> <p>Custom content here</p> '; } function add_dashboard_widgets() { wp_add_dashboard_widget( 'custom_dashboard_widget', 'Custom Dashoard Widget', 'dashboard_widget_function' ); } add_action( 'wp_dashboard_setup', 'add_dashboard_widgets' ); """ "Remove All Dashboard Widgets": "prefix": "rdw" "body": """ /** * Remove All Dashboard Widgets */ function remove_dashboard_widgets() { global $wp_meta_boxes; unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments'] ); unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'] ); unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary'] ); remove_meta_box( 'dashboard_activity', 'dashboard', 'normal' ); } add_action( 'wp_dashboard_setup', 'remove_dashboard_widgets' ); """ "Include Navigation Menus": "prefix": "inm" "body": """ /** * Include navigation menu */ function register_my_menu() { register_nav_menu('nav-menu',__( 'Navigation Menu' )); } add_action( 'init', 'register_my_menu' ); """ "Insert Custom Login Logo": "prefix": "icll" "body": """ /** * Insert Custom Login Logo */ function custom_login_logo() { echo ' <style> .login h1 a { background-image: url(image.jpg) !important; background-size: 234px 67px; width:234px; height:67px; display:block; } </style> '; } add_action( 'login_head', 'custom_login_logo' ); """ "Modify Admin Footer Text": "prefix": "maft" "body": """ /** * Modify Admin Footer Text */ function modify_footer() { echo 'Created by <a href="mailto:you@example.com">you</a>.'; } add_filter( 'admin_footer_text', 'modify_footer' ); """ "Enqueue Styles and Scripts": "prefix": "esas" "body": """ /** * Enqueue Styles and Scripts */ function custom_scripts() { wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6' ); wp_enqueue_style( 'style', get_template_directory_uri() . '/css/style.css' ); wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '3.3.6', true ); wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js' ); } add_action( 'wp_enqueue_scripts', 'custom_scripts' ); """ "Enqueue Google Fonts": "prefix": "egf" "body": """ /** * Enqueue Google Fonts */ function google_fonts() { wp_register_style( 'OpenSans', '//fonts.googleapis.com/css?family=Open+Sans:400,600,700,800' ); wp_enqueue_style( 'OpenSans' ); } add_action( 'wp_print_styles', 'google_fonts' ); """ "Modify Excerpt Length": "prefix": "mel" "body": """ /** * Modify Excerpt Length */ function custom_excerpt_length( $length ) { return 25; } add_filter( 'excerpt_length', 'custom_excerpt_length', 999 ); """ "Change Read More Link": "prefix": "crml" "body": """ /** * Change Read More Link */ function custom_read_more_link() { return '<a href="' . get_permalink() . '">Read More</a>'; } add_filter( 'the_content_more_link', 'custom_read_more_link' ); """ "Change More Excerpt": "prefix": "cme" "body": """ /** * Change More Excerpt */ function custom_more_excerpt( $more ) { return '...'; } add_filter( 'excerpt_more', 'custom_more_excerpt' ); """ "Disable Emoji Mess": "prefix": "dem" "body": """ /** * Disable Emoji Mess */ function disable_wp_emojicons() { remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' ); add_filter( 'emoji_svg_url', '__return_false' ); } add_action( 'init', 'disable_wp_emojicons' ); function disable_emojicons_tinymce( $plugins ) { return is_array( $plugins ) ? array_diff( $plugins, array( 'wpemoji' ) ) : array(); } """ "Remove Comments": "prefix": "rc" "body": """ /** * Remove Comments */ // Removes from admin menu add_action( 'admin_menu', 'my_remove_admin_menus' ); function my_remove_admin_menus() { remove_menu_page( 'edit-comments.php' ); } // Removes from post and pages add_action( 'init', 'remove_comment_support', 100 ); function remove_comment_support() { remove_post_type_support( 'post', 'comments' ); remove_post_type_support( 'page', 'comments' ); } // Removes from admin bar function mytheme_admin_bar_render() { global $wp_admin_bar; $wp_admin_bar->remove_menu( 'comments' ); } add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' ); """ "Change Media Gallery URL": "prefix": "cmgl" "body": """ /** * Change Media Gallery URL */ if ( empty( get_option( 'upload_url_path' ) ) ) { update_option( 'upload_url_path', 'http://assets.website.com/wp-content/uploads' ); } """ "Create Custom Thumbnail Size": "prefix": "ccts" "body": """ /** * Create Custom Thumbnail Size */ add_image_size( 'custom-thumbnail', 250, 250, true ); """ "Retrieve Thumbnail": "prefix": "rt" "body": """ <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'custom-thumbnail' ); echo $thumb[0]; ?> """ "Add Categories for Attachments": "prefix": "acfa" "body": """ /** * Add Categories for Attachments */ function add_categories_for_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'add_categories_for_attachments' ); """ "Add Custom Excerpt to Pages": "prefix": "acetp" "body": """ /** * Add Custom Excerpt to Pages */ function add_page_excerpt() { add_post_type_support( 'page', array( 'excerpt' ) ); } add_action( 'init', 'add_page_excerpt' ); """ "Create a Global String": "prefix": "cgs" "body": """ /** * Create a Global String */ function global_string() { return 'String'; } //<?php echo global_string(); ?> """ "Support Featured Images": "prefix": "sfı" "body": """ /** * Support Featured Images */ add_theme_support( 'post-thumbnails' ); """ "Support Search Form": "prefix": "ssf" "body": """ /** * Support Search Form */ add_theme_support( 'html5', array( 'search-form' ) ); """ "Excluding pages from search": "prefix": "epfs" "body": """ /** * Excluding pages from search */ function exclude_pages_from_search() { global $wp_post_types; $wp_post_types['page']->exclude_from_search = true; } add_action( 'init', 'exclude_pages_from_search' ); """ "Disable xmlrpc.php": "prefix": "dx" "body": """ /** * Disable xmlrpc.php */ add_filter( 'xmlrpc_enabled', '__return_false' ); remove_action( 'wp_head', 'rsd_link' ); remove_action( 'wp_head', 'wlwmanifest_link' ); """ "Escape HTML in Posts": "prefix": "ehip" "body": """ /** * Escape HTML in <code> or <pre><code> tags. */ function escapeHTML($arr) { if (version_compare(PHP_VERSION, '5.2.3') >= 0) { $output = htmlspecialchars($arr[2], ENT_NOQUOTES, get_bloginfo('charset'), false); } else { $specialChars = array( '&' => '&amp;', '<' => '&lt;', '>' => '&gt;' ); // decode already converted data $data = htmlspecialchars_decode( $arr[2] ); // escapse all data inside <pre> $output = strtr( $data, $specialChars ); } if (! empty($output)) { return $arr[1] . $output . $arr[3]; } else { return $arr[1] . $arr[2] . $arr[3]; } } function filterCode($data) { // Uncomment if you want to escape anything within a <pre> tag //$modifiedData = preg_replace_callback( '@(<pre.*>)(.*)(<\/pre>)@isU', 'escapeHTML', $data ); $modifiedData = preg_replace_callback( '@(<code.*>)(.*)(<\/code>)@isU', 'escapeHTML', $data ); $modifiedData = preg_replace_callback( '@(<tt.*>)(.*)(<\/tt>)@isU', 'escapeHTML', $modifiedData ); return $modifiedData; } add_filter( 'content_save_pre', 'filterCode', 9 ); add_filter( 'excerpt_save_pre', 'filterCode', 9 ); """ "Create Custom Global Settings": "prefix": "ccgs" "body": """ /** * Create Custom Global Settings */ function custom_settings_page() { ?> <div class="wrap"> <h1>Custom Settings</h1> <form method="post" action="options.php"> <?php settings_fields( 'section' ); do_settings_sections( 'theme-options' ); submit_button(); ?> </form> </div> <?php } function custom_settings_add_menu() { add_theme_page( 'Custom Settings', 'Custom Settings', 'manage_options', 'custom-settings', 'custom_settings_page', null, 99 ); } add_action( 'admin_menu', 'custom_settings_add_menu' ); // Example setting function setting_twitter() { ?> <input type="text" name="twitter" id="twitter" value="<?php echo get_option('twitter'); ?>" /> <?php } function custom_settings_page_setup() { add_settings_section( 'section', 'All Settings', null, 'theme-options' ); add_settings_field( 'twitter', 'Twitter Username', 'setting_twitter', 'theme-options', 'section' ); register_setting( 'section', 'twitter' ); } add_action( 'admin_init', 'custom_settings_page_setup' ); """ "Remove WordPress Admin Bar": "prefix": "rwab" "body": """ /** * Remove WordPress Admin Bar */ function remove_admin_bar() { remove_action( 'wp_head', '_admin_bar_bump_cb' ); } add_action( 'get_header', 'remove_admin_bar' ); """ "Add Open Graph Meta Tags": "prefix": "ogmt" "body": """ /** * Add Open Graph Meta Tags */ function meta_og() { global $post; if ( is_single() ) { if( has_post_thumbnail( $post->ID ) ) { $img_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' ); } $excerpt = strip_tags($post->post_content); $excerpt_more = ''; if ( strlen($excerpt ) > 155) { $excerpt = substr($excerpt,0,155); $excerpt_more = ' ...'; } $excerpt = str_replace( '"', '', $excerpt ); $excerpt = str_replace( "'", '', $excerpt ); $excerptwords = preg_split( '/[\n\r\t ]+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY ); array_pop( $excerptwords ); $excerpt = implode( ' ', $excerptwords ) . $excerpt_more; ?> <meta name="author" content="Your Name"> <meta name="description" content="<?php echo $excerpt; ?>"> <meta property="og:title" content="<?php echo the_title(); ?>"> <meta property="og:description" content="<?php echo $excerpt; ?>"> <meta property="og:type" content="article"> <meta property="og:url" content="<?php echo the_permalink(); ?>"> <meta property="og:site_name" content="Your Site Name"> <meta property="og:image" content="<?php echo $img_src[0]; ?>"> <?php } else { return; } } add_action('wp_head', 'meta_og', 5); """ "Add Custom Post Type": "prefix": "cpt" "body": """ /** * Add Custom Post Type */ function create_custom_post() { register_post_type( 'custom-post', // slug for custom post type array( 'labels' => array( 'name' => __( 'Custom Post' ), ), 'public' => true, 'hierarchical' => true, 'has_archive' => true, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail' ), 'can_export' => true, 'taxonomies' => array( 'post_tag', 'category' ) )); } add_action('init', 'create_custom_post'); """ "Implement Preconnect to Google Fonts in Themes": "prefix": "ipgft" "body": """ /** * Implement Preconnect to Google Fonts in Themes */ function twentyfifteen_resource_hints( $urls, $relation_type ) { // Checks whether the subject is carrying the source of fonts google and the `$relation_type` equals preconnect. // Replace `enqueue_font_id` the `ID` used in loading the source. if ( wp_style_is( 'enqueue_font_id', 'queue' ) && 'preconnect' === $relation_type ) { // Checks whether the version of WordPress is greater than or equal to 4.7 // to ensure conmpatibilidade with older versions // because the 4.7 has become necessary to return an array instead of string if ( version_compare( $GLOBALS['wp_version'], '4.7-alpha', '>=' ) ) { // Array with url google fonts and crossorigin $urls[] = array( 'href' => 'https://fonts.gstatic.com', 'crossorigin', ); } else { // String with url google fonts $urls[] = 'https://fonts.gstatic.com'; } } return $urls; } add_filter( 'wp_resource_hints', 'twentyfifteen_resource_hints', 10, 2 ); """ "Add Thumbnail Column to Post Listing": "prefix": "tctpl" "body": """ /** * Add Thumbnail Column to Post Listing */ add_image_size( 'admin-list-thumb', 80, 80, false ); function wpcs_add_thumbnail_columns( $columns ) { if ( !is_array( $columns ) ) $columns = array(); $new = array(); foreach( $columns as $key => $title ) { if ( $key == 'title' ) // Put the Thumbnail column before the Title column $new['featured_thumb'] = __( 'Image'); $new[$key] = $title; } return $new; } function wpcs_add_thumbnail_columns_data( $column, $post_id ) { switch ( $column ) { case 'featured_thumb': echo '<a href="' . $post_id . '">'; echo the_post_thumbnail( 'admin-list-thumb' ); echo '</a>'; break; } } if ( function_exists( 'add_theme_support' ) ) { add_filter( 'manage_posts_columns' , 'wpcs_add_thumbnail_columns' ); add_action( 'manage_posts_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 ); } """ "Add Lead Class to First Paragraph": "prefix": "lcfp" "body": """ /** * Add Lead Class to First Paragraph */ function first_paragraph( $content ) { return preg_replace( '/<p([^>]+)?>/', '<p$1 class="lead">', $content, 1 ); } add_filter( 'the_content', 'first_paragraph' ); """ "Exclude Custom Post Type from Search": "prefix": "ecptfs" "body": """ /** * Exclude Custom Post Type from Search */ function excludePages( $query ) { if ( $query->is_search ) { $query->set( 'post_type', 'post' ); } return $query; } add_filter( 'pre_get_posts','excludePages' ); """ "Remove Query String from Static Resources": "prefix": "rqsfsr" "body": """ /** * Remove Query String from Static Resources */ function remove_cssjs_ver( $src ) { if( strpos( $src, '?ver=' ) ) $src = remove_query_arg( 'ver', $src ); return $src; } add_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 ); add_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 ); """ "Modify jQuery": "prefix": "mj" "body": """ /** * modify jquery */ function modify_jquery() { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', false, '3.2.1'); wp_enqueue_script('jquery'); } if (!is_admin()) add_action('wp_enqueue_scripts', 'modify_jquery'); """ "Disable Website Field From Comment Form": "prefix": "dwffcf" "body": """ /** * Disable Website Field From Comment Form */ function disable_website_field( $field ) { if( isset($field['url']) ) { unset( $field['url'] ); } return $field; } add_filter('comment_form_default_fields', 'disable_website_field'); """ "Disable JSON Rest API": "prefix": "djra" "body": """ /** * Disable JSON Rest API */ add_filter('json_enabled', '__return_false'); add_filter('json_jsonp_enabled', '__return_false'); """ "Switch post type": "prefix": "spt" "body": """ /** * Switch post type */ function switch_post_type ( $old_post_type, $new_post_type ){ global $wpdb; // Run the update query $wpdb->update( $wpdb->posts, // Set array( 'post_type' => $new_post_type), // Where array( 'post_type' => $old_post_type ) ); } """ "PHP Logger": "prefix": "pl" "body": """ /** * PHP Logger */ function php_logger( $data ) { $output = $data; if ( is_array( $output ) ) $output = implode( ',', $output); // print the result into the JavaScript console echo "<script>console.log( 'PHP LOG: " . $output . "' );</script>"; } """ "Always show second bar in TinyMCE": "prefix": "assbt" "body": """ /** * Always show second bar in TinyMCE */ function show_tinymce_toolbar( $in ) { $in['wordpress_adv_hidden'] = false; return $in; } add_filter( 'tiny_mce_before_init', 'show_tinymce_toolbar' ); """ "Remove Admin Menu Items Depending on User Role": "prefix": "ramıdur" "body": """ /** * Clone the administrator user role */ function clone_admin_role() { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $adm = $wp_roles->get_role( 'administrator' ); // Add new "Client" role with all admin capabilities $wp_roles->add_role( 'client', 'Client', $adm->capabilities ); } add_action('init', 'clone_admin_role'); /** * Specify which admin menu items are visible for users with role "Client" */ function remove_dashboard_menus() { if ( current_user_can( 'client' ) ) { // Hide Updates under Dashboard menu remove_submenu_page( 'index.php', 'update-core.php' ); // Hide Comments remove_menu_page( 'edit-comments.php' ); // Hide Plugins remove_menu_page( 'plugins.php' ); // Hide Themes, Customizer and Widgets under Appearance menu remove_submenu_page( 'themes.php', 'themes.php' ); remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) ); remove_submenu_page( 'themes.php', 'widgets.php' ); // Hide Tools remove_menu_page( 'tools.php' ); // Hide General Settings remove_menu_page( 'options-general.php' ); } } add_action( 'admin_menu', 'remove_dashboard_menus' ); """ "Remove Admin Menu Items Depending on Email Address (domain)": "prefix": "ramıdoea" "body": """ /** * Specify which users can see admin menu items based on their email address */ function remove_dashboard_menus() { $user_data = get_userdata( get_current_user_id() ); $user_email = isset( $user_data->user_email ) ? $user_data->user_email : ''; if ( ! strpos( $user_email, '@yourcompany.com' ) ) { // Hide Updates under Dashboard menu remove_submenu_page( 'index.php', 'update-core.php' ); // Hide Comments remove_menu_page( 'edit-comments.php' ); // Hide Plugins remove_menu_page( 'plugins.php' ); // Hide Themes, Customizer and Widgets under Appearance menu remove_submenu_page( 'themes.php', 'themes.php' ); remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) ); remove_submenu_page( 'themes.php', 'widgets.php' ); // Hide Tools remove_menu_page( 'tools.php' ); // Hide General Settings remove_menu_page( 'options-general.php' ); } } add_action( 'admin_menu', 'remove_dashboard_menus' ); """ "Reorder Admin Menu Items": "prefix": "ramı" "body": """ /** * Reorder admin menu */ function custom_menu_order( $menu_ord ) { if ( ! $menu_ord ) { return true; } return array( 'index.php', 'separator1', 'edit.php?post_type=page', 'edit.php', 'edit.php?post_type=[your_post_type_slug]', 'upload.php', 'edit-comments.php', 'separator2', 'themes.php', 'plugins.php', 'users.php', 'tools.php', 'options-general.php' ); } } add_filter( 'custom_menu_order', 'custom_menu_order' ); add_filter( 'menu_order', 'custom_menu_order' ); """
34225
".text.html.php": "Hide WordPress Update Nag to All But Admins": "prefix": "hidea" "body": """ /** * Hide WordPress Update Nag to All But Admins */ function hide_update_notice_to_all_but_admin() { if ( !current_user_can( 'update_core' ) ) { remove_action( 'admin_notices', 'update_nag', 3 ); } } add_action( 'admin_head', 'hide_update_notice_to_all_but_admin', 1 ); """ "Create Proper WordPress Titles": "prefix": "tt" "body": """ /** * Create Proper WordPress Titles */ add_theme_support( 'title-tag' ); """ "Create Custom WordPress Dashboard Widget": "prefix": "cwdw" "body": """ /** * Create Custom WordPress Dashboard Widget */ function dashboard_widget_function() { echo ' <h2>Custom Dashboard Widget</h2> <p>Custom content here</p> '; } function add_dashboard_widgets() { wp_add_dashboard_widget( 'custom_dashboard_widget', 'Custom Dashoard Widget', 'dashboard_widget_function' ); } add_action( 'wp_dashboard_setup', 'add_dashboard_widgets' ); """ "Remove All Dashboard Widgets": "prefix": "rdw" "body": """ /** * Remove All Dashboard Widgets */ function remove_dashboard_widgets() { global $wp_meta_boxes; unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments'] ); unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'] ); unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary'] ); remove_meta_box( 'dashboard_activity', 'dashboard', 'normal' ); } add_action( 'wp_dashboard_setup', 'remove_dashboard_widgets' ); """ "Include Navigation Menus": "prefix": "inm" "body": """ /** * Include navigation menu */ function register_my_menu() { register_nav_menu('nav-menu',__( 'Navigation Menu' )); } add_action( 'init', 'register_my_menu' ); """ "Insert Custom Login Logo": "prefix": "icll" "body": """ /** * Insert Custom Login Logo */ function custom_login_logo() { echo ' <style> .login h1 a { background-image: url(image.jpg) !important; background-size: 234px 67px; width:234px; height:67px; display:block; } </style> '; } add_action( 'login_head', 'custom_login_logo' ); """ "Modify Admin Footer Text": "prefix": "maft" "body": """ /** * Modify Admin Footer Text */ function modify_footer() { echo 'Created by <a href="mailto:<EMAIL>">you</a>.'; } add_filter( 'admin_footer_text', 'modify_footer' ); """ "Enqueue Styles and Scripts": "prefix": "esas" "body": """ /** * Enqueue Styles and Scripts */ function custom_scripts() { wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6' ); wp_enqueue_style( 'style', get_template_directory_uri() . '/css/style.css' ); wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '3.3.6', true ); wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js' ); } add_action( 'wp_enqueue_scripts', 'custom_scripts' ); """ "Enqueue Google Fonts": "prefix": "egf" "body": """ /** * Enqueue Google Fonts */ function google_fonts() { wp_register_style( 'OpenSans', '//fonts.googleapis.com/css?family=Open+Sans:400,600,700,800' ); wp_enqueue_style( 'OpenSans' ); } add_action( 'wp_print_styles', 'google_fonts' ); """ "Modify Excerpt Length": "prefix": "mel" "body": """ /** * Modify Excerpt Length */ function custom_excerpt_length( $length ) { return 25; } add_filter( 'excerpt_length', 'custom_excerpt_length', 999 ); """ "Change Read More Link": "prefix": "crml" "body": """ /** * Change Read More Link */ function custom_read_more_link() { return '<a href="' . get_permalink() . '">Read More</a>'; } add_filter( 'the_content_more_link', 'custom_read_more_link' ); """ "Change More Excerpt": "prefix": "cme" "body": """ /** * Change More Excerpt */ function custom_more_excerpt( $more ) { return '...'; } add_filter( 'excerpt_more', 'custom_more_excerpt' ); """ "Disable Emoji Mess": "prefix": "dem" "body": """ /** * Disable Emoji Mess */ function disable_wp_emojicons() { remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' ); add_filter( 'emoji_svg_url', '__return_false' ); } add_action( 'init', 'disable_wp_emojicons' ); function disable_emojicons_tinymce( $plugins ) { return is_array( $plugins ) ? array_diff( $plugins, array( 'wpemoji' ) ) : array(); } """ "Remove Comments": "prefix": "rc" "body": """ /** * Remove Comments */ // Removes from admin menu add_action( 'admin_menu', 'my_remove_admin_menus' ); function my_remove_admin_menus() { remove_menu_page( 'edit-comments.php' ); } // Removes from post and pages add_action( 'init', 'remove_comment_support', 100 ); function remove_comment_support() { remove_post_type_support( 'post', 'comments' ); remove_post_type_support( 'page', 'comments' ); } // Removes from admin bar function mytheme_admin_bar_render() { global $wp_admin_bar; $wp_admin_bar->remove_menu( 'comments' ); } add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' ); """ "Change Media Gallery URL": "prefix": "cmgl" "body": """ /** * Change Media Gallery URL */ if ( empty( get_option( 'upload_url_path' ) ) ) { update_option( 'upload_url_path', 'http://assets.website.com/wp-content/uploads' ); } """ "Create Custom Thumbnail Size": "prefix": "ccts" "body": """ /** * Create Custom Thumbnail Size */ add_image_size( 'custom-thumbnail', 250, 250, true ); """ "Retrieve Thumbnail": "prefix": "rt" "body": """ <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'custom-thumbnail' ); echo $thumb[0]; ?> """ "Add Categories for Attachments": "prefix": "acfa" "body": """ /** * Add Categories for Attachments */ function add_categories_for_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'add_categories_for_attachments' ); """ "Add Custom Excerpt to Pages": "prefix": "acetp" "body": """ /** * Add Custom Excerpt to Pages */ function add_page_excerpt() { add_post_type_support( 'page', array( 'excerpt' ) ); } add_action( 'init', 'add_page_excerpt' ); """ "Create a Global String": "prefix": "cgs" "body": """ /** * Create a Global String */ function global_string() { return 'String'; } //<?php echo global_string(); ?> """ "Support Featured Images": "prefix": "sfı" "body": """ /** * Support Featured Images */ add_theme_support( 'post-thumbnails' ); """ "Support Search Form": "prefix": "ssf" "body": """ /** * Support Search Form */ add_theme_support( 'html5', array( 'search-form' ) ); """ "Excluding pages from search": "prefix": "epfs" "body": """ /** * Excluding pages from search */ function exclude_pages_from_search() { global $wp_post_types; $wp_post_types['page']->exclude_from_search = true; } add_action( 'init', 'exclude_pages_from_search' ); """ "Disable xmlrpc.php": "prefix": "dx" "body": """ /** * Disable xmlrpc.php */ add_filter( 'xmlrpc_enabled', '__return_false' ); remove_action( 'wp_head', 'rsd_link' ); remove_action( 'wp_head', 'wlwmanifest_link' ); """ "Escape HTML in Posts": "prefix": "ehip" "body": """ /** * Escape HTML in <code> or <pre><code> tags. */ function escapeHTML($arr) { if (version_compare(PHP_VERSION, '5.2.3') >= 0) { $output = htmlspecialchars($arr[2], ENT_NOQUOTES, get_bloginfo('charset'), false); } else { $specialChars = array( '&' => '&amp;', '<' => '&lt;', '>' => '&gt;' ); // decode already converted data $data = htmlspecialchars_decode( $arr[2] ); // escapse all data inside <pre> $output = strtr( $data, $specialChars ); } if (! empty($output)) { return $arr[1] . $output . $arr[3]; } else { return $arr[1] . $arr[2] . $arr[3]; } } function filterCode($data) { // Uncomment if you want to escape anything within a <pre> tag //$modifiedData = preg_replace_callback( '@(<pre.*>)(.*)(<\/pre>)@isU', 'escapeHTML', $data ); $modifiedData = preg_replace_callback( '@(<code.*>)(.*)(<\/code>)@isU', 'escapeHTML', $data ); $modifiedData = preg_replace_callback( '@(<tt.*>)(.*)(<\/tt>)@isU', 'escapeHTML', $modifiedData ); return $modifiedData; } add_filter( 'content_save_pre', 'filterCode', 9 ); add_filter( 'excerpt_save_pre', 'filterCode', 9 ); """ "Create Custom Global Settings": "prefix": "ccgs" "body": """ /** * Create Custom Global Settings */ function custom_settings_page() { ?> <div class="wrap"> <h1>Custom Settings</h1> <form method="post" action="options.php"> <?php settings_fields( 'section' ); do_settings_sections( 'theme-options' ); submit_button(); ?> </form> </div> <?php } function custom_settings_add_menu() { add_theme_page( 'Custom Settings', 'Custom Settings', 'manage_options', 'custom-settings', 'custom_settings_page', null, 99 ); } add_action( 'admin_menu', 'custom_settings_add_menu' ); // Example setting function setting_twitter() { ?> <input type="text" name="twitter" id="twitter" value="<?php echo get_option('twitter'); ?>" /> <?php } function custom_settings_page_setup() { add_settings_section( 'section', 'All Settings', null, 'theme-options' ); add_settings_field( 'twitter', 'Twitter Username', 'setting_twitter', 'theme-options', 'section' ); register_setting( 'section', 'twitter' ); } add_action( 'admin_init', 'custom_settings_page_setup' ); """ "Remove WordPress Admin Bar": "prefix": "rwab" "body": """ /** * Remove WordPress Admin Bar */ function remove_admin_bar() { remove_action( 'wp_head', '_admin_bar_bump_cb' ); } add_action( 'get_header', 'remove_admin_bar' ); """ "Add Open Graph Meta Tags": "prefix": "ogmt" "body": """ /** * Add Open Graph Meta Tags */ function meta_og() { global $post; if ( is_single() ) { if( has_post_thumbnail( $post->ID ) ) { $img_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' ); } $excerpt = strip_tags($post->post_content); $excerpt_more = ''; if ( strlen($excerpt ) > 155) { $excerpt = substr($excerpt,0,155); $excerpt_more = ' ...'; } $excerpt = str_replace( '"', '', $excerpt ); $excerpt = str_replace( "'", '', $excerpt ); $excerptwords = preg_split( '/[\n\r\t ]+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY ); array_pop( $excerptwords ); $excerpt = implode( ' ', $excerptwords ) . $excerpt_more; ?> <meta name="author" content="<NAME>"> <meta name="description" content="<?php echo $excerpt; ?>"> <meta property="og:title" content="<?php echo the_title(); ?>"> <meta property="og:description" content="<?php echo $excerpt; ?>"> <meta property="og:type" content="article"> <meta property="og:url" content="<?php echo the_permalink(); ?>"> <meta property="og:site_name" content="Your Site Name"> <meta property="og:image" content="<?php echo $img_src[0]; ?>"> <?php } else { return; } } add_action('wp_head', 'meta_og', 5); """ "Add Custom Post Type": "prefix": "cpt" "body": """ /** * Add Custom Post Type */ function create_custom_post() { register_post_type( 'custom-post', // slug for custom post type array( 'labels' => array( 'name' => __( 'Custom Post' ), ), 'public' => true, 'hierarchical' => true, 'has_archive' => true, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail' ), 'can_export' => true, 'taxonomies' => array( 'post_tag', 'category' ) )); } add_action('init', 'create_custom_post'); """ "Implement Preconnect to Google Fonts in Themes": "prefix": "ipgft" "body": """ /** * Implement Preconnect to Google Fonts in Themes */ function twentyfifteen_resource_hints( $urls, $relation_type ) { // Checks whether the subject is carrying the source of fonts google and the `$relation_type` equals preconnect. // Replace `enqueue_font_id` the `ID` used in loading the source. if ( wp_style_is( 'enqueue_font_id', 'queue' ) && 'preconnect' === $relation_type ) { // Checks whether the version of WordPress is greater than or equal to 4.7 // to ensure conmpatibilidade with older versions // because the 4.7 has become necessary to return an array instead of string if ( version_compare( $GLOBALS['wp_version'], '4.7-alpha', '>=' ) ) { // Array with url google fonts and crossorigin $urls[] = array( 'href' => 'https://fonts.gstatic.com', 'crossorigin', ); } else { // String with url google fonts $urls[] = 'https://fonts.gstatic.com'; } } return $urls; } add_filter( 'wp_resource_hints', 'twentyfifteen_resource_hints', 10, 2 ); """ "Add Thumbnail Column to Post Listing": "prefix": "tctpl" "body": """ /** * Add Thumbnail Column to Post Listing */ add_image_size( 'admin-list-thumb', 80, 80, false ); function wpcs_add_thumbnail_columns( $columns ) { if ( !is_array( $columns ) ) $columns = array(); $new = array(); foreach( $columns as $key => $title ) { if ( $key == 'title' ) // Put the Thumbnail column before the Title column $new['featured_thumb'] = __( 'Image'); $new[$key] = $title; } return $new; } function wpcs_add_thumbnail_columns_data( $column, $post_id ) { switch ( $column ) { case 'featured_thumb': echo '<a href="' . $post_id . '">'; echo the_post_thumbnail( 'admin-list-thumb' ); echo '</a>'; break; } } if ( function_exists( 'add_theme_support' ) ) { add_filter( 'manage_posts_columns' , 'wpcs_add_thumbnail_columns' ); add_action( 'manage_posts_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 ); } """ "Add Lead Class to First Paragraph": "prefix": "lcfp" "body": """ /** * Add Lead Class to First Paragraph */ function first_paragraph( $content ) { return preg_replace( '/<p([^>]+)?>/', '<p$1 class="lead">', $content, 1 ); } add_filter( 'the_content', 'first_paragraph' ); """ "Exclude Custom Post Type from Search": "prefix": "ecptfs" "body": """ /** * Exclude Custom Post Type from Search */ function excludePages( $query ) { if ( $query->is_search ) { $query->set( 'post_type', 'post' ); } return $query; } add_filter( 'pre_get_posts','excludePages' ); """ "Remove Query String from Static Resources": "prefix": "rqsfsr" "body": """ /** * Remove Query String from Static Resources */ function remove_cssjs_ver( $src ) { if( strpos( $src, '?ver=' ) ) $src = remove_query_arg( 'ver', $src ); return $src; } add_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 ); add_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 ); """ "Modify jQuery": "prefix": "mj" "body": """ /** * modify jquery */ function modify_jquery() { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', false, '3.2.1'); wp_enqueue_script('jquery'); } if (!is_admin()) add_action('wp_enqueue_scripts', 'modify_jquery'); """ "Disable Website Field From Comment Form": "prefix": "dwffcf" "body": """ /** * Disable Website Field From Comment Form */ function disable_website_field( $field ) { if( isset($field['url']) ) { unset( $field['url'] ); } return $field; } add_filter('comment_form_default_fields', 'disable_website_field'); """ "Disable JSON Rest API": "prefix": "djra" "body": """ /** * Disable JSON Rest API */ add_filter('json_enabled', '__return_false'); add_filter('json_jsonp_enabled', '__return_false'); """ "Switch post type": "prefix": "spt" "body": """ /** * Switch post type */ function switch_post_type ( $old_post_type, $new_post_type ){ global $wpdb; // Run the update query $wpdb->update( $wpdb->posts, // Set array( 'post_type' => $new_post_type), // Where array( 'post_type' => $old_post_type ) ); } """ "PHP Logger": "prefix": "pl" "body": """ /** * PHP Logger */ function php_logger( $data ) { $output = $data; if ( is_array( $output ) ) $output = implode( ',', $output); // print the result into the JavaScript console echo "<script>console.log( 'PHP LOG: " . $output . "' );</script>"; } """ "Always show second bar in TinyMCE": "prefix": "assbt" "body": """ /** * Always show second bar in TinyMCE */ function show_tinymce_toolbar( $in ) { $in['wordpress_adv_hidden'] = false; return $in; } add_filter( 'tiny_mce_before_init', 'show_tinymce_toolbar' ); """ "Remove Admin Menu Items Depending on User Role": "prefix": "ramıdur" "body": """ /** * Clone the administrator user role */ function clone_admin_role() { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $adm = $wp_roles->get_role( 'administrator' ); // Add new "Client" role with all admin capabilities $wp_roles->add_role( 'client', 'Client', $adm->capabilities ); } add_action('init', 'clone_admin_role'); /** * Specify which admin menu items are visible for users with role "Client" */ function remove_dashboard_menus() { if ( current_user_can( 'client' ) ) { // Hide Updates under Dashboard menu remove_submenu_page( 'index.php', 'update-core.php' ); // Hide Comments remove_menu_page( 'edit-comments.php' ); // Hide Plugins remove_menu_page( 'plugins.php' ); // Hide Themes, Customizer and Widgets under Appearance menu remove_submenu_page( 'themes.php', 'themes.php' ); remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) ); remove_submenu_page( 'themes.php', 'widgets.php' ); // Hide Tools remove_menu_page( 'tools.php' ); // Hide General Settings remove_menu_page( 'options-general.php' ); } } add_action( 'admin_menu', 'remove_dashboard_menus' ); """ "Remove Admin Menu Items Depending on Email Address (domain)": "prefix": "ramıdoea" "body": """ /** * Specify which users can see admin menu items based on their email address */ function remove_dashboard_menus() { $user_data = get_userdata( get_current_user_id() ); $user_email = isset( $user_data->user_email ) ? $user_data->user_email : ''; if ( ! strpos( $user_email, '@yourcompany.com' ) ) { // Hide Updates under Dashboard menu remove_submenu_page( 'index.php', 'update-core.php' ); // Hide Comments remove_menu_page( 'edit-comments.php' ); // Hide Plugins remove_menu_page( 'plugins.php' ); // Hide Themes, Customizer and Widgets under Appearance menu remove_submenu_page( 'themes.php', 'themes.php' ); remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) ); remove_submenu_page( 'themes.php', 'widgets.php' ); // Hide Tools remove_menu_page( 'tools.php' ); // Hide General Settings remove_menu_page( 'options-general.php' ); } } add_action( 'admin_menu', 'remove_dashboard_menus' ); """ "Reorder Admin Menu Items": "prefix": "ramı" "body": """ /** * Reorder admin menu */ function custom_menu_order( $menu_ord ) { if ( ! $menu_ord ) { return true; } return array( 'index.php', 'separator1', 'edit.php?post_type=page', 'edit.php', 'edit.php?post_type=[your_post_type_slug]', 'upload.php', 'edit-comments.php', 'separator2', 'themes.php', 'plugins.php', 'users.php', 'tools.php', 'options-general.php' ); } } add_filter( 'custom_menu_order', 'custom_menu_order' ); add_filter( 'menu_order', 'custom_menu_order' ); """
true
".text.html.php": "Hide WordPress Update Nag to All But Admins": "prefix": "hidea" "body": """ /** * Hide WordPress Update Nag to All But Admins */ function hide_update_notice_to_all_but_admin() { if ( !current_user_can( 'update_core' ) ) { remove_action( 'admin_notices', 'update_nag', 3 ); } } add_action( 'admin_head', 'hide_update_notice_to_all_but_admin', 1 ); """ "Create Proper WordPress Titles": "prefix": "tt" "body": """ /** * Create Proper WordPress Titles */ add_theme_support( 'title-tag' ); """ "Create Custom WordPress Dashboard Widget": "prefix": "cwdw" "body": """ /** * Create Custom WordPress Dashboard Widget */ function dashboard_widget_function() { echo ' <h2>Custom Dashboard Widget</h2> <p>Custom content here</p> '; } function add_dashboard_widgets() { wp_add_dashboard_widget( 'custom_dashboard_widget', 'Custom Dashoard Widget', 'dashboard_widget_function' ); } add_action( 'wp_dashboard_setup', 'add_dashboard_widgets' ); """ "Remove All Dashboard Widgets": "prefix": "rdw" "body": """ /** * Remove All Dashboard Widgets */ function remove_dashboard_widgets() { global $wp_meta_boxes; unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts'] ); unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments'] ); unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'] ); unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary'] ); remove_meta_box( 'dashboard_activity', 'dashboard', 'normal' ); } add_action( 'wp_dashboard_setup', 'remove_dashboard_widgets' ); """ "Include Navigation Menus": "prefix": "inm" "body": """ /** * Include navigation menu */ function register_my_menu() { register_nav_menu('nav-menu',__( 'Navigation Menu' )); } add_action( 'init', 'register_my_menu' ); """ "Insert Custom Login Logo": "prefix": "icll" "body": """ /** * Insert Custom Login Logo */ function custom_login_logo() { echo ' <style> .login h1 a { background-image: url(image.jpg) !important; background-size: 234px 67px; width:234px; height:67px; display:block; } </style> '; } add_action( 'login_head', 'custom_login_logo' ); """ "Modify Admin Footer Text": "prefix": "maft" "body": """ /** * Modify Admin Footer Text */ function modify_footer() { echo 'Created by <a href="mailto:PI:EMAIL:<EMAIL>END_PI">you</a>.'; } add_filter( 'admin_footer_text', 'modify_footer' ); """ "Enqueue Styles and Scripts": "prefix": "esas" "body": """ /** * Enqueue Styles and Scripts */ function custom_scripts() { wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6' ); wp_enqueue_style( 'style', get_template_directory_uri() . '/css/style.css' ); wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '3.3.6', true ); wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js' ); } add_action( 'wp_enqueue_scripts', 'custom_scripts' ); """ "Enqueue Google Fonts": "prefix": "egf" "body": """ /** * Enqueue Google Fonts */ function google_fonts() { wp_register_style( 'OpenSans', '//fonts.googleapis.com/css?family=Open+Sans:400,600,700,800' ); wp_enqueue_style( 'OpenSans' ); } add_action( 'wp_print_styles', 'google_fonts' ); """ "Modify Excerpt Length": "prefix": "mel" "body": """ /** * Modify Excerpt Length */ function custom_excerpt_length( $length ) { return 25; } add_filter( 'excerpt_length', 'custom_excerpt_length', 999 ); """ "Change Read More Link": "prefix": "crml" "body": """ /** * Change Read More Link */ function custom_read_more_link() { return '<a href="' . get_permalink() . '">Read More</a>'; } add_filter( 'the_content_more_link', 'custom_read_more_link' ); """ "Change More Excerpt": "prefix": "cme" "body": """ /** * Change More Excerpt */ function custom_more_excerpt( $more ) { return '...'; } add_filter( 'excerpt_more', 'custom_more_excerpt' ); """ "Disable Emoji Mess": "prefix": "dem" "body": """ /** * Disable Emoji Mess */ function disable_wp_emojicons() { remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' ); add_filter( 'emoji_svg_url', '__return_false' ); } add_action( 'init', 'disable_wp_emojicons' ); function disable_emojicons_tinymce( $plugins ) { return is_array( $plugins ) ? array_diff( $plugins, array( 'wpemoji' ) ) : array(); } """ "Remove Comments": "prefix": "rc" "body": """ /** * Remove Comments */ // Removes from admin menu add_action( 'admin_menu', 'my_remove_admin_menus' ); function my_remove_admin_menus() { remove_menu_page( 'edit-comments.php' ); } // Removes from post and pages add_action( 'init', 'remove_comment_support', 100 ); function remove_comment_support() { remove_post_type_support( 'post', 'comments' ); remove_post_type_support( 'page', 'comments' ); } // Removes from admin bar function mytheme_admin_bar_render() { global $wp_admin_bar; $wp_admin_bar->remove_menu( 'comments' ); } add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' ); """ "Change Media Gallery URL": "prefix": "cmgl" "body": """ /** * Change Media Gallery URL */ if ( empty( get_option( 'upload_url_path' ) ) ) { update_option( 'upload_url_path', 'http://assets.website.com/wp-content/uploads' ); } """ "Create Custom Thumbnail Size": "prefix": "ccts" "body": """ /** * Create Custom Thumbnail Size */ add_image_size( 'custom-thumbnail', 250, 250, true ); """ "Retrieve Thumbnail": "prefix": "rt" "body": """ <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'custom-thumbnail' ); echo $thumb[0]; ?> """ "Add Categories for Attachments": "prefix": "acfa" "body": """ /** * Add Categories for Attachments */ function add_categories_for_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'add_categories_for_attachments' ); """ "Add Custom Excerpt to Pages": "prefix": "acetp" "body": """ /** * Add Custom Excerpt to Pages */ function add_page_excerpt() { add_post_type_support( 'page', array( 'excerpt' ) ); } add_action( 'init', 'add_page_excerpt' ); """ "Create a Global String": "prefix": "cgs" "body": """ /** * Create a Global String */ function global_string() { return 'String'; } //<?php echo global_string(); ?> """ "Support Featured Images": "prefix": "sfı" "body": """ /** * Support Featured Images */ add_theme_support( 'post-thumbnails' ); """ "Support Search Form": "prefix": "ssf" "body": """ /** * Support Search Form */ add_theme_support( 'html5', array( 'search-form' ) ); """ "Excluding pages from search": "prefix": "epfs" "body": """ /** * Excluding pages from search */ function exclude_pages_from_search() { global $wp_post_types; $wp_post_types['page']->exclude_from_search = true; } add_action( 'init', 'exclude_pages_from_search' ); """ "Disable xmlrpc.php": "prefix": "dx" "body": """ /** * Disable xmlrpc.php */ add_filter( 'xmlrpc_enabled', '__return_false' ); remove_action( 'wp_head', 'rsd_link' ); remove_action( 'wp_head', 'wlwmanifest_link' ); """ "Escape HTML in Posts": "prefix": "ehip" "body": """ /** * Escape HTML in <code> or <pre><code> tags. */ function escapeHTML($arr) { if (version_compare(PHP_VERSION, '5.2.3') >= 0) { $output = htmlspecialchars($arr[2], ENT_NOQUOTES, get_bloginfo('charset'), false); } else { $specialChars = array( '&' => '&amp;', '<' => '&lt;', '>' => '&gt;' ); // decode already converted data $data = htmlspecialchars_decode( $arr[2] ); // escapse all data inside <pre> $output = strtr( $data, $specialChars ); } if (! empty($output)) { return $arr[1] . $output . $arr[3]; } else { return $arr[1] . $arr[2] . $arr[3]; } } function filterCode($data) { // Uncomment if you want to escape anything within a <pre> tag //$modifiedData = preg_replace_callback( '@(<pre.*>)(.*)(<\/pre>)@isU', 'escapeHTML', $data ); $modifiedData = preg_replace_callback( '@(<code.*>)(.*)(<\/code>)@isU', 'escapeHTML', $data ); $modifiedData = preg_replace_callback( '@(<tt.*>)(.*)(<\/tt>)@isU', 'escapeHTML', $modifiedData ); return $modifiedData; } add_filter( 'content_save_pre', 'filterCode', 9 ); add_filter( 'excerpt_save_pre', 'filterCode', 9 ); """ "Create Custom Global Settings": "prefix": "ccgs" "body": """ /** * Create Custom Global Settings */ function custom_settings_page() { ?> <div class="wrap"> <h1>Custom Settings</h1> <form method="post" action="options.php"> <?php settings_fields( 'section' ); do_settings_sections( 'theme-options' ); submit_button(); ?> </form> </div> <?php } function custom_settings_add_menu() { add_theme_page( 'Custom Settings', 'Custom Settings', 'manage_options', 'custom-settings', 'custom_settings_page', null, 99 ); } add_action( 'admin_menu', 'custom_settings_add_menu' ); // Example setting function setting_twitter() { ?> <input type="text" name="twitter" id="twitter" value="<?php echo get_option('twitter'); ?>" /> <?php } function custom_settings_page_setup() { add_settings_section( 'section', 'All Settings', null, 'theme-options' ); add_settings_field( 'twitter', 'Twitter Username', 'setting_twitter', 'theme-options', 'section' ); register_setting( 'section', 'twitter' ); } add_action( 'admin_init', 'custom_settings_page_setup' ); """ "Remove WordPress Admin Bar": "prefix": "rwab" "body": """ /** * Remove WordPress Admin Bar */ function remove_admin_bar() { remove_action( 'wp_head', '_admin_bar_bump_cb' ); } add_action( 'get_header', 'remove_admin_bar' ); """ "Add Open Graph Meta Tags": "prefix": "ogmt" "body": """ /** * Add Open Graph Meta Tags */ function meta_og() { global $post; if ( is_single() ) { if( has_post_thumbnail( $post->ID ) ) { $img_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' ); } $excerpt = strip_tags($post->post_content); $excerpt_more = ''; if ( strlen($excerpt ) > 155) { $excerpt = substr($excerpt,0,155); $excerpt_more = ' ...'; } $excerpt = str_replace( '"', '', $excerpt ); $excerpt = str_replace( "'", '', $excerpt ); $excerptwords = preg_split( '/[\n\r\t ]+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY ); array_pop( $excerptwords ); $excerpt = implode( ' ', $excerptwords ) . $excerpt_more; ?> <meta name="author" content="PI:NAME:<NAME>END_PI"> <meta name="description" content="<?php echo $excerpt; ?>"> <meta property="og:title" content="<?php echo the_title(); ?>"> <meta property="og:description" content="<?php echo $excerpt; ?>"> <meta property="og:type" content="article"> <meta property="og:url" content="<?php echo the_permalink(); ?>"> <meta property="og:site_name" content="Your Site Name"> <meta property="og:image" content="<?php echo $img_src[0]; ?>"> <?php } else { return; } } add_action('wp_head', 'meta_og', 5); """ "Add Custom Post Type": "prefix": "cpt" "body": """ /** * Add Custom Post Type */ function create_custom_post() { register_post_type( 'custom-post', // slug for custom post type array( 'labels' => array( 'name' => __( 'Custom Post' ), ), 'public' => true, 'hierarchical' => true, 'has_archive' => true, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail' ), 'can_export' => true, 'taxonomies' => array( 'post_tag', 'category' ) )); } add_action('init', 'create_custom_post'); """ "Implement Preconnect to Google Fonts in Themes": "prefix": "ipgft" "body": """ /** * Implement Preconnect to Google Fonts in Themes */ function twentyfifteen_resource_hints( $urls, $relation_type ) { // Checks whether the subject is carrying the source of fonts google and the `$relation_type` equals preconnect. // Replace `enqueue_font_id` the `ID` used in loading the source. if ( wp_style_is( 'enqueue_font_id', 'queue' ) && 'preconnect' === $relation_type ) { // Checks whether the version of WordPress is greater than or equal to 4.7 // to ensure conmpatibilidade with older versions // because the 4.7 has become necessary to return an array instead of string if ( version_compare( $GLOBALS['wp_version'], '4.7-alpha', '>=' ) ) { // Array with url google fonts and crossorigin $urls[] = array( 'href' => 'https://fonts.gstatic.com', 'crossorigin', ); } else { // String with url google fonts $urls[] = 'https://fonts.gstatic.com'; } } return $urls; } add_filter( 'wp_resource_hints', 'twentyfifteen_resource_hints', 10, 2 ); """ "Add Thumbnail Column to Post Listing": "prefix": "tctpl" "body": """ /** * Add Thumbnail Column to Post Listing */ add_image_size( 'admin-list-thumb', 80, 80, false ); function wpcs_add_thumbnail_columns( $columns ) { if ( !is_array( $columns ) ) $columns = array(); $new = array(); foreach( $columns as $key => $title ) { if ( $key == 'title' ) // Put the Thumbnail column before the Title column $new['featured_thumb'] = __( 'Image'); $new[$key] = $title; } return $new; } function wpcs_add_thumbnail_columns_data( $column, $post_id ) { switch ( $column ) { case 'featured_thumb': echo '<a href="' . $post_id . '">'; echo the_post_thumbnail( 'admin-list-thumb' ); echo '</a>'; break; } } if ( function_exists( 'add_theme_support' ) ) { add_filter( 'manage_posts_columns' , 'wpcs_add_thumbnail_columns' ); add_action( 'manage_posts_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 ); } """ "Add Lead Class to First Paragraph": "prefix": "lcfp" "body": """ /** * Add Lead Class to First Paragraph */ function first_paragraph( $content ) { return preg_replace( '/<p([^>]+)?>/', '<p$1 class="lead">', $content, 1 ); } add_filter( 'the_content', 'first_paragraph' ); """ "Exclude Custom Post Type from Search": "prefix": "ecptfs" "body": """ /** * Exclude Custom Post Type from Search */ function excludePages( $query ) { if ( $query->is_search ) { $query->set( 'post_type', 'post' ); } return $query; } add_filter( 'pre_get_posts','excludePages' ); """ "Remove Query String from Static Resources": "prefix": "rqsfsr" "body": """ /** * Remove Query String from Static Resources */ function remove_cssjs_ver( $src ) { if( strpos( $src, '?ver=' ) ) $src = remove_query_arg( 'ver', $src ); return $src; } add_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 ); add_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 ); """ "Modify jQuery": "prefix": "mj" "body": """ /** * modify jquery */ function modify_jquery() { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', false, '3.2.1'); wp_enqueue_script('jquery'); } if (!is_admin()) add_action('wp_enqueue_scripts', 'modify_jquery'); """ "Disable Website Field From Comment Form": "prefix": "dwffcf" "body": """ /** * Disable Website Field From Comment Form */ function disable_website_field( $field ) { if( isset($field['url']) ) { unset( $field['url'] ); } return $field; } add_filter('comment_form_default_fields', 'disable_website_field'); """ "Disable JSON Rest API": "prefix": "djra" "body": """ /** * Disable JSON Rest API */ add_filter('json_enabled', '__return_false'); add_filter('json_jsonp_enabled', '__return_false'); """ "Switch post type": "prefix": "spt" "body": """ /** * Switch post type */ function switch_post_type ( $old_post_type, $new_post_type ){ global $wpdb; // Run the update query $wpdb->update( $wpdb->posts, // Set array( 'post_type' => $new_post_type), // Where array( 'post_type' => $old_post_type ) ); } """ "PHP Logger": "prefix": "pl" "body": """ /** * PHP Logger */ function php_logger( $data ) { $output = $data; if ( is_array( $output ) ) $output = implode( ',', $output); // print the result into the JavaScript console echo "<script>console.log( 'PHP LOG: " . $output . "' );</script>"; } """ "Always show second bar in TinyMCE": "prefix": "assbt" "body": """ /** * Always show second bar in TinyMCE */ function show_tinymce_toolbar( $in ) { $in['wordpress_adv_hidden'] = false; return $in; } add_filter( 'tiny_mce_before_init', 'show_tinymce_toolbar' ); """ "Remove Admin Menu Items Depending on User Role": "prefix": "ramıdur" "body": """ /** * Clone the administrator user role */ function clone_admin_role() { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $adm = $wp_roles->get_role( 'administrator' ); // Add new "Client" role with all admin capabilities $wp_roles->add_role( 'client', 'Client', $adm->capabilities ); } add_action('init', 'clone_admin_role'); /** * Specify which admin menu items are visible for users with role "Client" */ function remove_dashboard_menus() { if ( current_user_can( 'client' ) ) { // Hide Updates under Dashboard menu remove_submenu_page( 'index.php', 'update-core.php' ); // Hide Comments remove_menu_page( 'edit-comments.php' ); // Hide Plugins remove_menu_page( 'plugins.php' ); // Hide Themes, Customizer and Widgets under Appearance menu remove_submenu_page( 'themes.php', 'themes.php' ); remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) ); remove_submenu_page( 'themes.php', 'widgets.php' ); // Hide Tools remove_menu_page( 'tools.php' ); // Hide General Settings remove_menu_page( 'options-general.php' ); } } add_action( 'admin_menu', 'remove_dashboard_menus' ); """ "Remove Admin Menu Items Depending on Email Address (domain)": "prefix": "ramıdoea" "body": """ /** * Specify which users can see admin menu items based on their email address */ function remove_dashboard_menus() { $user_data = get_userdata( get_current_user_id() ); $user_email = isset( $user_data->user_email ) ? $user_data->user_email : ''; if ( ! strpos( $user_email, '@yourcompany.com' ) ) { // Hide Updates under Dashboard menu remove_submenu_page( 'index.php', 'update-core.php' ); // Hide Comments remove_menu_page( 'edit-comments.php' ); // Hide Plugins remove_menu_page( 'plugins.php' ); // Hide Themes, Customizer and Widgets under Appearance menu remove_submenu_page( 'themes.php', 'themes.php' ); remove_submenu_page( 'themes.php', 'customize.php?return=' . urlencode( $_SERVER['REQUEST_URI'] ) ); remove_submenu_page( 'themes.php', 'widgets.php' ); // Hide Tools remove_menu_page( 'tools.php' ); // Hide General Settings remove_menu_page( 'options-general.php' ); } } add_action( 'admin_menu', 'remove_dashboard_menus' ); """ "Reorder Admin Menu Items": "prefix": "ramı" "body": """ /** * Reorder admin menu */ function custom_menu_order( $menu_ord ) { if ( ! $menu_ord ) { return true; } return array( 'index.php', 'separator1', 'edit.php?post_type=page', 'edit.php', 'edit.php?post_type=[your_post_type_slug]', 'upload.php', 'edit-comments.php', 'separator2', 'themes.php', 'plugins.php', 'users.php', 'tools.php', 'options-general.php' ); } } add_filter( 'custom_menu_order', 'custom_menu_order' ); add_filter( 'menu_order', 'custom_menu_order' ); """
[ { "context": " {\n field: 'prices.all.mode'\n key: 'maxPrice'\n type: 'maxIntCustom'\n inputPrefix", "end": 7515, "score": 0.8947764039039612, "start": 7507, "tag": "KEY", "value": "maxPrice" }, { "context": "roam-na-contours.json?2'\n # url: 'http://142.93.240.113:8080/data/v2.json'\n layers: [\n {\n", "end": 18692, "score": 0.9955946803092957, "start": 18678, "tag": "IP_ADDRESS", "value": "142.93.240.113" }, { "context": "ementation in Project-OSRM\n # https://github.com/DennisOSRM/Project-OSRM-Web/blob/master/WebContent/routing/O", "end": 27810, "score": 0.999612033367157, "start": 27800, "tag": "USERNAME", "value": "DennisOSRM" } ]
src/services/map.coffee
FreeRoamApp/free-roam
14
_clone = require 'lodash/clone' _map = require 'lodash/map' _filter = require 'lodash/filter' _groupBy = require 'lodash/groupBy' _orderBy = require 'lodash/orderBy' _some = require 'lodash/some' _startCase = require 'lodash/startCase' _snakeCase = require 'lodash/snakeCase' _uniq = require 'lodash/uniq' _last = require 'lodash/last' Environment = require './environment' DateService = require './date' colors = require '../colors' config = require '../config' class MapService hasLocationPermission: ({model} = {}) -> unless navigator? return Promise.resolve false # not available in native apps # https://stackoverflow.com/questions/52784495/is-there-any-alternative-to-navigator-permissions-query-permissions-api if model and Environment.isNativeApp('freeroam') and Environment.isAndroid() model.portal.call 'permissions.check', { permissions: [ 'android.permission.ACCESS_FINE_LOCATION' 'android.permission.ACCESS_COARSE_LOCATION' ] } .then (results) -> results?['android.permission.ACCESS_FINE_LOCATION'] else if navigator.permissions navigator.permissions.query {name: 'geolocation'} .then (permissionStatus) -> return permissionStatus.state is 'granted' else return Promise.resolve localStorage?.geolocationEnabled getLocation: ({model, timeout} = {}) -> timeout ?= 10000 get = => new Promise (resolve, reject) => if navigator? navigator.geolocation.getCurrentPosition (pos) -> localStorage?.geolocationEnabled = '1' lat = Math.round(10000 * pos.coords.latitude) / 10000 lon = Math.round(10000 * pos.coords.longitude) / 10000 resolve {lat, lon} , reject, {enableHighAccuracy: true, timeout: timeout} else resolve null isNativeApp = Environment.isNativeApp 'freeroam' isIos = Environment.isIos() isNativeIos = isNativeApp and isIos if model?.portal and not isNativeIos @hasLocationPermission {model} .then (hasPermission) -> if hasPermission get() else model.portal.call 'permissions.request', { permissions: [ 'android.permission.ACCESS_FINE_LOCATION' 'android.permission.ACCESS_COARSE_LOCATION' ] } .catch (err) -> console.log 'perm req err', err .then get else get() getDirectionsBetweenPlaces: (places, {model}) -> places = _clone places target = '_system' baseUrl = 'https://google.com/maps/dir/?api=1' origin = places[0].location?.lat + ',' + places[0].location?.lon destination = _last(places).location?.lat + ',' + _last(places).location?.lon places.shift() places.pop() waypoints = _map(places, (place) -> "#{place.lat},#{place.lon}" ).join '|' url = "#{baseUrl}&origin=#{origin}&destination=#{destination}" if waypoints url += "&waypoints=#{waypoints}" model.portal.call 'browser.openWindow', {url, target} getDirections: (place, {model}) -> target = '_system' baseUrl = 'https://www.google.com/maps/dir/?api=1' destination = place?.location?.lat + ',' + place?.location?.lon isIos = Environment.isIos() onError = => if isIos url = "#{baseUrl}&destination=#{destination}" else url = "#{baseUrl}&origin=My+Location&destination=#{destination}" model.portal.call 'browser.openWindow', {url, target} # FIXME takes like a minute to load? if Environment.isNativeApp 'freeroam' (if isIos # for some reason hasLocationPermission check not working on ios Promise.resolve true else @hasLocationPermission {model} ).then (hasLocationPermission) => if hasLocationPermission @getLocation {model, timeout: 5000} .catch (err) -> console.log 'caught', err onError() .then ({lat, lon} = {}) -> if lat and lon origin = lat + ',' + lon url = "#{baseUrl}&origin=#{origin}&destination=#{destination}" model.portal.call 'browser.openWindow', {url, target} else onError() else console.log 'call onError' # just use the "my location" version, to avoid popup blocker onError() getAmenityFilters: ({model}) -> [ { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'dump' name: model.l.get 'amenities.dump' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'water' name: model.l.get 'amenities.water' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'restArea' name: model.l.get 'overnight.restArea' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'groceries' name: model.l.get 'amenities.groceries' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'propane' name: model.l.get 'amenities.propane' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'trash' name: model.l.get 'amenities.trash' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'recycle' name: model.l.get 'amenities.recycle' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArraySubTypes' items: [ {key: 'anytime', label: model.l.get 'gyms.anytime'} {key: 'planet', label: model.l.get 'gyms.planet'} {key: '24Hour', label: model.l.get 'gyms.24Hour'} ] arrayValue: 'shower' name: model.l.get 'amenities.shower' filterOverlayGroup: 'amenities' valueFn: (value) -> _filter _map value, (subTypeValue, subTypeKey) -> if subTypeValue {match: subType: subTypeKey} } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'laundry' name: model.l.get 'amenities.laundry' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'gas' name: model.l.get 'amenities.gas' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'water' name: model.l.get 'amenities.npwater' filterOverlayGroup: 'amenities' } ] getCampgroundFilters: ({model}) -> [ { field: 'subType' type: 'fieldList' items: [ {key: 'public', label: model.l.get 'placeInfo.landTypePublic'} {key: 'private', label: model.l.get 'placeInfo.landTypePrivate'} ] name: model.l.get 'placeInfo.landType' } { field: 'prices.all.mode' key: 'maxPrice' type: 'maxIntCustom' inputPrefix: '$' name: model.l.get 'campground.maxPrice' title: model.l.get 'filterContent.title.maxPrice' } { field: 'cellSignal' type: 'cellSignal' name: model.l.get 'campground.cellSignal' } { field: 'fullness' type: 'maxIntSeasonal' name: model.l.get 'campground.fullness' filterOverlayGroup: 'sliders' } { field: 'weather' type: 'weather' name: model.l.get 'general.weather' } { field: 'elevation' type: 'gtlt' name: model.l.get 'general.elevation' } { field: 'distanceTo' type: 'distanceTo' name: model.l.get 'filterSheet.facilitiesNearby' } { field: 'features' type: 'iconListBooleanAnd' items: [ {key: 'waterHookup', label: model.l.get 'feature.waterHookup'} {key: 'sewerHookup', label: model.l.get 'feature.sewerHookup'} {key: '30amp', label: model.l.get 'feature.30amp'} {key: '50amp', label: model.l.get 'feature.50amp'} {key: 'petsAllowed', label: model.l.get 'feature.petsAllowed'} ] name: model.l.get 'filterSheet.features' } # { # field: 'nearbyActivities' # type: 'iconListBooleanAnd' # items: [ # {key: 'horseBackRiding', label: model.l.get 'feature.horseBackRiding'} # ] # name: model.l.get 'filterSheet.features' # } { field: 'rating' type: 'reviews' name: model.l.get 'general.reviews' } { field: 'affiliations' type: 'listBooleanOr' items: [ {key: 'escapees', label: model.l.get 'affiliation.escapees'} {key: 'goodSam', label: model.l.get 'affiliation.goodSam'} { key: 'passportAmerica' label: model.l.get 'affiliation.passportAmerica' } ] name: model.l.get 'general.affiliations' } { field: 'maxLength' key: 'minLength' type: 'minIntCustom' inputPostfix: 'ft' name: model.l.get 'campground.minLength' } { field: 'crowds' type: 'maxIntSeasonal' name: model.l.get 'campground.crowds' filterOverlayGroup: 'sliders' } { field: 'roadDifficulty' type: 'maxInt' name: model.l.get 'campground.roadDifficulty' filterOverlayGroup: 'sliders' } { field: 'shade' type: 'maxInt' name: model.l.get 'campground.shade' filterOverlayGroup: 'sliders' } { field: 'safety' type: 'minInt' name: model.l.get 'campground.safety' filterOverlayGroup: 'sliders' } { field: 'noise' type: 'maxIntDayNight' name: model.l.get 'campground.noise' filterOverlayGroup: 'sliders' } ] getHazardFilters: ({model}) -> [ { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'wildfire' name: model.l.get 'hazard.wildfire' filterOverlayGroup: 'subType' } { field: 'subType' type: 'maxClearance' name: model.l.get 'hazard.lowClearance' arrayValue: 'lowClearance' valueFn: (value) -> if value feet = parseInt value.feet if isNaN feet feet = 0 inches = parseInt value.inches if isNaN inches feet = 0 inches = feet * 12 + inches {range: 'data.heightInches': lte: inches} filterOverlayGroup: 'lowClearance' } ] getOvernightFilters: ({model}) -> [ { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'walmart' name: model.l.get 'overnight.walmart' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'truckStop' name: model.l.get 'overnight.truckStop' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'restArea' name: model.l.get 'overnight.restArea' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'casino' name: model.l.get 'overnight.casino' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'crackerBarrel' name: model.l.get 'overnight.crackerBarrel' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'cabelas' name: model.l.get 'overnight.cabelas' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'other' name: model.l.get 'overnight.other' filterOverlayGroup: 'overnights' } ] getOptionalLayers: ({model, place, placePosition}) -> date = DateService.format new Date(), 'yyyy-mm-dd' layerSettings = JSON.parse localStorage?.layerSettings or '{}' { 'us-blm': { name: model.l.get 'placesMapContainer.layerBlm' thumb: "#{config.CDN_URL}/maps/blm_overlay.png" defaultOpacity: 0.5 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-blm.json' layer: id: 'us-blm' type: 'fill' source: 'us-blm' 'source-layer': 'us_pad' layout: {} paint: # 'fill-color': colors.$mapLayerBlm 'fill-pattern': 'blm_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-usfs': { name: model.l.get 'placesMapContainer.layerUsfs' thumb: "#{config.CDN_URL}/maps/usfs_overlay.png" defaultOpacity: 0.5 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-usfs.json' layer: id: 'us-usfs' type: 'fill' source: 'us-usfs' 'source-layer': 'us_pad' layout: {} paint: # 'fill-color': colors.$mapLayerUsfs 'fill-pattern': 'usfs_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-verizon': { name: model.l.get 'placesMapContainer.layerVerizonLte' thumb: "#{config.CDN_URL}/maps/verizon_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-verizon.json' layer: id: 'us-cell-verizon' type: 'fill' source: 'us-cell-verizon' 'source-layer': 'us_cell_verizon' layout: {} paint: # 'fill-color': colors.$verizon 'fill-pattern': 'verizon_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-att': { name: model.l.get 'placesMapContainer.layerAttLte' thumb: "#{config.CDN_URL}/maps/att_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-att.json' layer: id: 'us-cell-att' type: 'fill' source: 'us-cell-att' 'source-layer': 'us_cell_att' layout: {} paint: # 'fill-color': colors.$att 'fill-pattern': 'att_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-tmobile': { name: model.l.get 'placesMapContainer.layerTmobileLte' thumb: "#{config.CDN_URL}/maps/tmobile_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-tmobile.json' layer: id: 'us-cell-tmobile' type: 'fill' source: 'us-cell-tmobile' 'source-layer': 'us_cell_tmobile' layout: {} paint: # 'fill-color': colors.$tmobile 'fill-pattern': 'tmobile_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-sprint': { name: model.l.get 'placesMapContainer.layerSprintLte' thumb: "#{config.CDN_URL}/maps/sprint_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-sprint.json' layer: id: 'us-cell-sprint' type: 'fill' source: 'us-cell-sprint' 'source-layer': 'us_cell_sprint' layout: {} paint: # 'fill-color': colors.$sprint 'fill-pattern': 'sprint_bg' metadata: zIndex: 2 insertBeneathLabels: true } smoke: { name: model.l.get 'placesMapContainer.layerSmoke' thumb: "#{config.CDN_URL}/maps/smoke_overlay.png" source: type: 'geojson' data: "#{config.MAPS_CDN_URL}/smoke.json?#{date}" layer: id: 'smoke' type: 'fill' source: 'smoke' layout: {} paint: 'fill-opacity': property: 'Density', stops: [[0, 0], [100, 0.8]] 'fill-color': colors.$grey700 metadata: zIndex: 2 insertBeneathLabels: true } 'fire-weather': { name: model.l.get 'placesMapContainer.layerFireWeather' thumb: "#{config.CDN_URL}/maps/fire_weather_overlay.png" defaultOpacity: 0.5 source: type: 'geojson' data: "#{config.MAPS_CDN_URL}/fire_weather.json?#{date}" layer: id: 'fire-weather' type: 'fill' source: 'fire-weather' layout: {} paint: 'fill-color': [ 'match' ['get', 'name'] 'Red Flag Warning', colors.$red500 colors.$yellow500 # other ] metadata: zIndex: 2 insertBeneathLabels: true onclick: (e, properties) -> place.next { name: properties.name description: properties.description } placePosition.next e.point } 'na-contours': { name: model.l.get 'placesMapContainer.layerElevation' thumb: "#{config.CDN_URL}/maps/elevation_overlay.png" defaultOpacity: 1#0.4 sourceId: 'na-contours' source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-na-contours.json?2' # url: 'http://142.93.240.113:8080/data/v2.json' layers: [ { id: 'na-contours' type: 'line' source: 'na-contours' 'source-layer': 'contour' # minzoom: 9 # layout: paint: 'line-color': '#000000' 'line-opacity': 0.5 'line-opacity': stops: [ [0, 0.3] [14, 1] ] 'line-width': 1 metadata: zIndex: 2 } { id: 'na-contours-labels' type: 'symbol' source: 'na-contours' 'source-layer': 'contour' minzoom: 10 layout: 'symbol-placement': 'line' # 'text-field': ['concat', ['to-string', ['round', ['*', ['get', 'ele'], 3.2808399]]], "'"] 'text-field': ['concat', ['to-string', ['get', 'ele']], "'"] 'text-font': ['Open Sans Regular'] 'text-size': 14 paint: 'text-color': '#000000', 'text-halo-width': 0 metadata: zIndex: 2 } ] insertBeneathLabels: true } satellite: { name: model.l.get 'placesMapContainer.layerSatellite' thumb: "#{config.CDN_URL}/maps/satellite_overlay.png" defaultOpacity: 1 sourceId: 'mapbox' source: type: 'raster' url: 'mapbox://mapbox.satellite' tileSize: 256 layer: id: 'satellite' type: 'raster' source: 'mapbox' 'source-layer': 'mapbox_satellite_full' paint: {} # necessary to add opacity metadata: zIndex: 1 insertBeneathLabels: true } } getESQueryFromFilters: (filters, currentMapBounds) => groupedFilters = _groupBy filters, 'field' filter = _filter _map groupedFilters, (fieldFilters, field) => unless _some fieldFilters, 'value' return filter = fieldFilters[0] switch filter.type when 'maxInt', 'maxIntCustom' { range: "#{field}": lte: filter.value } when 'minInt', 'minIntCustom' { range: "#{field}": gte: filter.value } when 'gtlt' if filter.value.operator and filter.value.value { range: "#{field}": "#{filter.value.operator}": filter.value.value } when 'maxIntSeasonal' { range: "#{field}.#{filter.value.season}": lte: filter.value.value } # when 'maxClearance' # feet = parseInt filter.value.feet # if isNaN feet # feet = 0 # inches = parseInt filter.value.inches # if isNaN inches # feet = 0 # inches = feet * 12 + inches # { # range: # 'data.heightInches': # lt: inches # } when 'maxIntDayNight' { range: "#{field}.#{filter.value.dayNight}": lte: filter.value.value } when 'gtZero' { range: "#{field}": gt: 0 } when 'list' { bool: must: _filter _map filter.value, (value, key) -> if value match: "#{key}": value } when 'listBooleanAnd', 'iconListBooleanAnd' { bool: must: _filter _map filter.value, (value, key) -> if value match: "#{field}.#{key}": true } when 'listBooleanOr' { bool: should: _filter _map filter.value, (value, key) -> if value match: "#{field}.#{key}": true } when 'fieldList' { bool: should: _filter _map filter.value, (value, key) -> if value match: "#{field}": key } when 'reviews' { bool: must: _filter [ if filter.value.rating {range: {rating: {gte: filter.value.rating}}} if filter.value.hasPhotos {range: {attachmentCount: {gt: 0}}} ] } # { # field: 'attachmentCount' # type: 'gtZero' # isBoolean: true # name: model.l.get 'campground.hasPhoto' # } when 'cellSignal' { bool: should: _map filter.value, (value, carrier) -> if carrier.indexOf('_lte') isnt -1 { range: "#{field}.#{carrier}.signal": gte: value } else # check for lte and non lte bool: should: [ { range: "#{field}.#{carrier}.signal": gte: value } { range: "#{field}.#{carrier}_lte.signal": gte: value } ] } when 'weather' if filter.value.month is 'forecast' bool: must: _map filter.value.metrics, ({operator, value}, metric) -> { range: "forecast.#{metric}": "#{operator}": parseFloat(value) } else month = config.MONTHS[filter.value.month] bool: must: _map filter.value.metrics, ({operator, value}, metric) -> range: "#{field}.months.#{month}.#{metric}": "#{operator}": parseFloat(value) when 'distanceTo' bool: must: _map filter.value.facilities, (facility) -> { range: "#{field}.#{facility}.time": lte: parseInt(filter.value.time) } when 'booleanArray' withValues = _filter(fieldFilters, 'value') { # there's potentially a cleaner way to do this? bool: should: _map withValues, ({value, arrayValue, valueFn}) -> # if subtypes are specified if typeof value is 'object' bool: must: [ {match: "#{field}": arrayValue} bool: should: valueFn value ] else {match: "#{field}": arrayValue} } console.log 'fff', filter filter.push { geo_bounding_box: location: top_left: lat: @formatLatitude currentMapBounds._ne.lat lon: @formatLongitude currentMapBounds._sw.lng bottom_right: lat: @formatLatitude currentMapBounds._sw.lat lon: @formatLongitude currentMapBounds._ne.lng } filter getIconByPlace: (place) => switch place.type when 'overnight' @overnightIconGetFn(null) place when 'amenity' @amenityIconGetFn(null) place when 'hazard' @hazardIconGetFn(null) place when 'coordinate' 'empty' else @campgroundIconGetFn(null) place campgroundIconGetFn: (filters) -> (campground) -> if campground?.prices?.all?.mode is 0 and campground?.ratingCount > 0 then 'free' else if campground?.prices?.all?.mode is 0 then 'free_reviewless' else if campground?.ratingCount > 0 then 'paid' else 'paid_reviewless' overnightIconGetFn: (filters) -> (overnight) -> if overnight.subType in ['walmart', 'restArea', 'casino', 'truckStop', 'crackerBarrel', 'cabelas'] \ then _snakeCase overnight.subType else 'default' amenityIconGetFn: (filters) -> filterValues = _map _filter(filters, 'value'), 'arrayValue' (amenity) -> icon = _orderBy(amenity.amenities, (amenity) -> filterValues.indexOf(amenity) isnt -1 and config.AMENITY_ICON_ORDER.indexOf(amenity) , ['desc'])[0] if icon is 'gym' icon = 'shower' # TODO: add gym icon, rm _snakeCase icon hazardIconGetFn: (filters) -> (hazard) -> _snakeCase hazard.subType formatLatitude: (lat) -> lat = Math.round(1000 * lat) / 1000 lat = Math.max -90, lat Math.min 90, lat formatLongitude: (lon) -> lon = Math.round(1000 * lon) / 1000 lon = Math.max -180, lon Math.min 180, lon # This is adapted from the implementation in Project-OSRM # https://github.com/DennisOSRM/Project-OSRM-Web/blob/master/WebContent/routing/OSRM.RoutingGeometry.js decodePolyline: (str, precision = 6) -> index = 0 lat = 0 lng = 0 coordinates = [] shift = 0 result = 0 byte = null latitude_change = undefined longitude_change = undefined factor = 10 ** (precision) # Coordinates have variable length when encoded, so just keep # track of whether we've hit the end of the string. In each # loop iteration, a single coordinate is decoded. while index < str.length # Reset shift, result, and byte byte = null shift = 0 result = 0 loop byte = str.charCodeAt(index++) - 63 result |= (byte & 0x1f) << shift shift += 5 unless byte >= 0x20 break latitude_change = if result & 1 then ~(result >> 1) else result >> 1 shift = result = 0 loop byte = str.charCodeAt(index++) - 63 result |= (byte & 0x1f) << shift shift += 5 unless byte >= 0x20 break longitude_change = if result & 1 then ~(result >> 1) else result >> 1 lat += latitude_change lng += longitude_change # mapbox likes these backwards coordinates.push [ lng / factor lat / factor ] coordinates module.exports = new MapService()
201653
_clone = require 'lodash/clone' _map = require 'lodash/map' _filter = require 'lodash/filter' _groupBy = require 'lodash/groupBy' _orderBy = require 'lodash/orderBy' _some = require 'lodash/some' _startCase = require 'lodash/startCase' _snakeCase = require 'lodash/snakeCase' _uniq = require 'lodash/uniq' _last = require 'lodash/last' Environment = require './environment' DateService = require './date' colors = require '../colors' config = require '../config' class MapService hasLocationPermission: ({model} = {}) -> unless navigator? return Promise.resolve false # not available in native apps # https://stackoverflow.com/questions/52784495/is-there-any-alternative-to-navigator-permissions-query-permissions-api if model and Environment.isNativeApp('freeroam') and Environment.isAndroid() model.portal.call 'permissions.check', { permissions: [ 'android.permission.ACCESS_FINE_LOCATION' 'android.permission.ACCESS_COARSE_LOCATION' ] } .then (results) -> results?['android.permission.ACCESS_FINE_LOCATION'] else if navigator.permissions navigator.permissions.query {name: 'geolocation'} .then (permissionStatus) -> return permissionStatus.state is 'granted' else return Promise.resolve localStorage?.geolocationEnabled getLocation: ({model, timeout} = {}) -> timeout ?= 10000 get = => new Promise (resolve, reject) => if navigator? navigator.geolocation.getCurrentPosition (pos) -> localStorage?.geolocationEnabled = '1' lat = Math.round(10000 * pos.coords.latitude) / 10000 lon = Math.round(10000 * pos.coords.longitude) / 10000 resolve {lat, lon} , reject, {enableHighAccuracy: true, timeout: timeout} else resolve null isNativeApp = Environment.isNativeApp 'freeroam' isIos = Environment.isIos() isNativeIos = isNativeApp and isIos if model?.portal and not isNativeIos @hasLocationPermission {model} .then (hasPermission) -> if hasPermission get() else model.portal.call 'permissions.request', { permissions: [ 'android.permission.ACCESS_FINE_LOCATION' 'android.permission.ACCESS_COARSE_LOCATION' ] } .catch (err) -> console.log 'perm req err', err .then get else get() getDirectionsBetweenPlaces: (places, {model}) -> places = _clone places target = '_system' baseUrl = 'https://google.com/maps/dir/?api=1' origin = places[0].location?.lat + ',' + places[0].location?.lon destination = _last(places).location?.lat + ',' + _last(places).location?.lon places.shift() places.pop() waypoints = _map(places, (place) -> "#{place.lat},#{place.lon}" ).join '|' url = "#{baseUrl}&origin=#{origin}&destination=#{destination}" if waypoints url += "&waypoints=#{waypoints}" model.portal.call 'browser.openWindow', {url, target} getDirections: (place, {model}) -> target = '_system' baseUrl = 'https://www.google.com/maps/dir/?api=1' destination = place?.location?.lat + ',' + place?.location?.lon isIos = Environment.isIos() onError = => if isIos url = "#{baseUrl}&destination=#{destination}" else url = "#{baseUrl}&origin=My+Location&destination=#{destination}" model.portal.call 'browser.openWindow', {url, target} # FIXME takes like a minute to load? if Environment.isNativeApp 'freeroam' (if isIos # for some reason hasLocationPermission check not working on ios Promise.resolve true else @hasLocationPermission {model} ).then (hasLocationPermission) => if hasLocationPermission @getLocation {model, timeout: 5000} .catch (err) -> console.log 'caught', err onError() .then ({lat, lon} = {}) -> if lat and lon origin = lat + ',' + lon url = "#{baseUrl}&origin=#{origin}&destination=#{destination}" model.portal.call 'browser.openWindow', {url, target} else onError() else console.log 'call onError' # just use the "my location" version, to avoid popup blocker onError() getAmenityFilters: ({model}) -> [ { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'dump' name: model.l.get 'amenities.dump' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'water' name: model.l.get 'amenities.water' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'restArea' name: model.l.get 'overnight.restArea' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'groceries' name: model.l.get 'amenities.groceries' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'propane' name: model.l.get 'amenities.propane' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'trash' name: model.l.get 'amenities.trash' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'recycle' name: model.l.get 'amenities.recycle' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArraySubTypes' items: [ {key: 'anytime', label: model.l.get 'gyms.anytime'} {key: 'planet', label: model.l.get 'gyms.planet'} {key: '24Hour', label: model.l.get 'gyms.24Hour'} ] arrayValue: 'shower' name: model.l.get 'amenities.shower' filterOverlayGroup: 'amenities' valueFn: (value) -> _filter _map value, (subTypeValue, subTypeKey) -> if subTypeValue {match: subType: subTypeKey} } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'laundry' name: model.l.get 'amenities.laundry' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'gas' name: model.l.get 'amenities.gas' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'water' name: model.l.get 'amenities.npwater' filterOverlayGroup: 'amenities' } ] getCampgroundFilters: ({model}) -> [ { field: 'subType' type: 'fieldList' items: [ {key: 'public', label: model.l.get 'placeInfo.landTypePublic'} {key: 'private', label: model.l.get 'placeInfo.landTypePrivate'} ] name: model.l.get 'placeInfo.landType' } { field: 'prices.all.mode' key: '<KEY>' type: 'maxIntCustom' inputPrefix: '$' name: model.l.get 'campground.maxPrice' title: model.l.get 'filterContent.title.maxPrice' } { field: 'cellSignal' type: 'cellSignal' name: model.l.get 'campground.cellSignal' } { field: 'fullness' type: 'maxIntSeasonal' name: model.l.get 'campground.fullness' filterOverlayGroup: 'sliders' } { field: 'weather' type: 'weather' name: model.l.get 'general.weather' } { field: 'elevation' type: 'gtlt' name: model.l.get 'general.elevation' } { field: 'distanceTo' type: 'distanceTo' name: model.l.get 'filterSheet.facilitiesNearby' } { field: 'features' type: 'iconListBooleanAnd' items: [ {key: 'waterHookup', label: model.l.get 'feature.waterHookup'} {key: 'sewerHookup', label: model.l.get 'feature.sewerHookup'} {key: '30amp', label: model.l.get 'feature.30amp'} {key: '50amp', label: model.l.get 'feature.50amp'} {key: 'petsAllowed', label: model.l.get 'feature.petsAllowed'} ] name: model.l.get 'filterSheet.features' } # { # field: 'nearbyActivities' # type: 'iconListBooleanAnd' # items: [ # {key: 'horseBackRiding', label: model.l.get 'feature.horseBackRiding'} # ] # name: model.l.get 'filterSheet.features' # } { field: 'rating' type: 'reviews' name: model.l.get 'general.reviews' } { field: 'affiliations' type: 'listBooleanOr' items: [ {key: 'escapees', label: model.l.get 'affiliation.escapees'} {key: 'goodSam', label: model.l.get 'affiliation.goodSam'} { key: 'passportAmerica' label: model.l.get 'affiliation.passportAmerica' } ] name: model.l.get 'general.affiliations' } { field: 'maxLength' key: 'minLength' type: 'minIntCustom' inputPostfix: 'ft' name: model.l.get 'campground.minLength' } { field: 'crowds' type: 'maxIntSeasonal' name: model.l.get 'campground.crowds' filterOverlayGroup: 'sliders' } { field: 'roadDifficulty' type: 'maxInt' name: model.l.get 'campground.roadDifficulty' filterOverlayGroup: 'sliders' } { field: 'shade' type: 'maxInt' name: model.l.get 'campground.shade' filterOverlayGroup: 'sliders' } { field: 'safety' type: 'minInt' name: model.l.get 'campground.safety' filterOverlayGroup: 'sliders' } { field: 'noise' type: 'maxIntDayNight' name: model.l.get 'campground.noise' filterOverlayGroup: 'sliders' } ] getHazardFilters: ({model}) -> [ { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'wildfire' name: model.l.get 'hazard.wildfire' filterOverlayGroup: 'subType' } { field: 'subType' type: 'maxClearance' name: model.l.get 'hazard.lowClearance' arrayValue: 'lowClearance' valueFn: (value) -> if value feet = parseInt value.feet if isNaN feet feet = 0 inches = parseInt value.inches if isNaN inches feet = 0 inches = feet * 12 + inches {range: 'data.heightInches': lte: inches} filterOverlayGroup: 'lowClearance' } ] getOvernightFilters: ({model}) -> [ { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'walmart' name: model.l.get 'overnight.walmart' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'truckStop' name: model.l.get 'overnight.truckStop' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'restArea' name: model.l.get 'overnight.restArea' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'casino' name: model.l.get 'overnight.casino' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'crackerBarrel' name: model.l.get 'overnight.crackerBarrel' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'cabelas' name: model.l.get 'overnight.cabelas' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'other' name: model.l.get 'overnight.other' filterOverlayGroup: 'overnights' } ] getOptionalLayers: ({model, place, placePosition}) -> date = DateService.format new Date(), 'yyyy-mm-dd' layerSettings = JSON.parse localStorage?.layerSettings or '{}' { 'us-blm': { name: model.l.get 'placesMapContainer.layerBlm' thumb: "#{config.CDN_URL}/maps/blm_overlay.png" defaultOpacity: 0.5 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-blm.json' layer: id: 'us-blm' type: 'fill' source: 'us-blm' 'source-layer': 'us_pad' layout: {} paint: # 'fill-color': colors.$mapLayerBlm 'fill-pattern': 'blm_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-usfs': { name: model.l.get 'placesMapContainer.layerUsfs' thumb: "#{config.CDN_URL}/maps/usfs_overlay.png" defaultOpacity: 0.5 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-usfs.json' layer: id: 'us-usfs' type: 'fill' source: 'us-usfs' 'source-layer': 'us_pad' layout: {} paint: # 'fill-color': colors.$mapLayerUsfs 'fill-pattern': 'usfs_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-verizon': { name: model.l.get 'placesMapContainer.layerVerizonLte' thumb: "#{config.CDN_URL}/maps/verizon_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-verizon.json' layer: id: 'us-cell-verizon' type: 'fill' source: 'us-cell-verizon' 'source-layer': 'us_cell_verizon' layout: {} paint: # 'fill-color': colors.$verizon 'fill-pattern': 'verizon_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-att': { name: model.l.get 'placesMapContainer.layerAttLte' thumb: "#{config.CDN_URL}/maps/att_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-att.json' layer: id: 'us-cell-att' type: 'fill' source: 'us-cell-att' 'source-layer': 'us_cell_att' layout: {} paint: # 'fill-color': colors.$att 'fill-pattern': 'att_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-tmobile': { name: model.l.get 'placesMapContainer.layerTmobileLte' thumb: "#{config.CDN_URL}/maps/tmobile_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-tmobile.json' layer: id: 'us-cell-tmobile' type: 'fill' source: 'us-cell-tmobile' 'source-layer': 'us_cell_tmobile' layout: {} paint: # 'fill-color': colors.$tmobile 'fill-pattern': 'tmobile_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-sprint': { name: model.l.get 'placesMapContainer.layerSprintLte' thumb: "#{config.CDN_URL}/maps/sprint_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-sprint.json' layer: id: 'us-cell-sprint' type: 'fill' source: 'us-cell-sprint' 'source-layer': 'us_cell_sprint' layout: {} paint: # 'fill-color': colors.$sprint 'fill-pattern': 'sprint_bg' metadata: zIndex: 2 insertBeneathLabels: true } smoke: { name: model.l.get 'placesMapContainer.layerSmoke' thumb: "#{config.CDN_URL}/maps/smoke_overlay.png" source: type: 'geojson' data: "#{config.MAPS_CDN_URL}/smoke.json?#{date}" layer: id: 'smoke' type: 'fill' source: 'smoke' layout: {} paint: 'fill-opacity': property: 'Density', stops: [[0, 0], [100, 0.8]] 'fill-color': colors.$grey700 metadata: zIndex: 2 insertBeneathLabels: true } 'fire-weather': { name: model.l.get 'placesMapContainer.layerFireWeather' thumb: "#{config.CDN_URL}/maps/fire_weather_overlay.png" defaultOpacity: 0.5 source: type: 'geojson' data: "#{config.MAPS_CDN_URL}/fire_weather.json?#{date}" layer: id: 'fire-weather' type: 'fill' source: 'fire-weather' layout: {} paint: 'fill-color': [ 'match' ['get', 'name'] 'Red Flag Warning', colors.$red500 colors.$yellow500 # other ] metadata: zIndex: 2 insertBeneathLabels: true onclick: (e, properties) -> place.next { name: properties.name description: properties.description } placePosition.next e.point } 'na-contours': { name: model.l.get 'placesMapContainer.layerElevation' thumb: "#{config.CDN_URL}/maps/elevation_overlay.png" defaultOpacity: 1#0.4 sourceId: 'na-contours' source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-na-contours.json?2' # url: 'http://172.16.17.32:8080/data/v2.json' layers: [ { id: 'na-contours' type: 'line' source: 'na-contours' 'source-layer': 'contour' # minzoom: 9 # layout: paint: 'line-color': '#000000' 'line-opacity': 0.5 'line-opacity': stops: [ [0, 0.3] [14, 1] ] 'line-width': 1 metadata: zIndex: 2 } { id: 'na-contours-labels' type: 'symbol' source: 'na-contours' 'source-layer': 'contour' minzoom: 10 layout: 'symbol-placement': 'line' # 'text-field': ['concat', ['to-string', ['round', ['*', ['get', 'ele'], 3.2808399]]], "'"] 'text-field': ['concat', ['to-string', ['get', 'ele']], "'"] 'text-font': ['Open Sans Regular'] 'text-size': 14 paint: 'text-color': '#000000', 'text-halo-width': 0 metadata: zIndex: 2 } ] insertBeneathLabels: true } satellite: { name: model.l.get 'placesMapContainer.layerSatellite' thumb: "#{config.CDN_URL}/maps/satellite_overlay.png" defaultOpacity: 1 sourceId: 'mapbox' source: type: 'raster' url: 'mapbox://mapbox.satellite' tileSize: 256 layer: id: 'satellite' type: 'raster' source: 'mapbox' 'source-layer': 'mapbox_satellite_full' paint: {} # necessary to add opacity metadata: zIndex: 1 insertBeneathLabels: true } } getESQueryFromFilters: (filters, currentMapBounds) => groupedFilters = _groupBy filters, 'field' filter = _filter _map groupedFilters, (fieldFilters, field) => unless _some fieldFilters, 'value' return filter = fieldFilters[0] switch filter.type when 'maxInt', 'maxIntCustom' { range: "#{field}": lte: filter.value } when 'minInt', 'minIntCustom' { range: "#{field}": gte: filter.value } when 'gtlt' if filter.value.operator and filter.value.value { range: "#{field}": "#{filter.value.operator}": filter.value.value } when 'maxIntSeasonal' { range: "#{field}.#{filter.value.season}": lte: filter.value.value } # when 'maxClearance' # feet = parseInt filter.value.feet # if isNaN feet # feet = 0 # inches = parseInt filter.value.inches # if isNaN inches # feet = 0 # inches = feet * 12 + inches # { # range: # 'data.heightInches': # lt: inches # } when 'maxIntDayNight' { range: "#{field}.#{filter.value.dayNight}": lte: filter.value.value } when 'gtZero' { range: "#{field}": gt: 0 } when 'list' { bool: must: _filter _map filter.value, (value, key) -> if value match: "#{key}": value } when 'listBooleanAnd', 'iconListBooleanAnd' { bool: must: _filter _map filter.value, (value, key) -> if value match: "#{field}.#{key}": true } when 'listBooleanOr' { bool: should: _filter _map filter.value, (value, key) -> if value match: "#{field}.#{key}": true } when 'fieldList' { bool: should: _filter _map filter.value, (value, key) -> if value match: "#{field}": key } when 'reviews' { bool: must: _filter [ if filter.value.rating {range: {rating: {gte: filter.value.rating}}} if filter.value.hasPhotos {range: {attachmentCount: {gt: 0}}} ] } # { # field: 'attachmentCount' # type: 'gtZero' # isBoolean: true # name: model.l.get 'campground.hasPhoto' # } when 'cellSignal' { bool: should: _map filter.value, (value, carrier) -> if carrier.indexOf('_lte') isnt -1 { range: "#{field}.#{carrier}.signal": gte: value } else # check for lte and non lte bool: should: [ { range: "#{field}.#{carrier}.signal": gte: value } { range: "#{field}.#{carrier}_lte.signal": gte: value } ] } when 'weather' if filter.value.month is 'forecast' bool: must: _map filter.value.metrics, ({operator, value}, metric) -> { range: "forecast.#{metric}": "#{operator}": parseFloat(value) } else month = config.MONTHS[filter.value.month] bool: must: _map filter.value.metrics, ({operator, value}, metric) -> range: "#{field}.months.#{month}.#{metric}": "#{operator}": parseFloat(value) when 'distanceTo' bool: must: _map filter.value.facilities, (facility) -> { range: "#{field}.#{facility}.time": lte: parseInt(filter.value.time) } when 'booleanArray' withValues = _filter(fieldFilters, 'value') { # there's potentially a cleaner way to do this? bool: should: _map withValues, ({value, arrayValue, valueFn}) -> # if subtypes are specified if typeof value is 'object' bool: must: [ {match: "#{field}": arrayValue} bool: should: valueFn value ] else {match: "#{field}": arrayValue} } console.log 'fff', filter filter.push { geo_bounding_box: location: top_left: lat: @formatLatitude currentMapBounds._ne.lat lon: @formatLongitude currentMapBounds._sw.lng bottom_right: lat: @formatLatitude currentMapBounds._sw.lat lon: @formatLongitude currentMapBounds._ne.lng } filter getIconByPlace: (place) => switch place.type when 'overnight' @overnightIconGetFn(null) place when 'amenity' @amenityIconGetFn(null) place when 'hazard' @hazardIconGetFn(null) place when 'coordinate' 'empty' else @campgroundIconGetFn(null) place campgroundIconGetFn: (filters) -> (campground) -> if campground?.prices?.all?.mode is 0 and campground?.ratingCount > 0 then 'free' else if campground?.prices?.all?.mode is 0 then 'free_reviewless' else if campground?.ratingCount > 0 then 'paid' else 'paid_reviewless' overnightIconGetFn: (filters) -> (overnight) -> if overnight.subType in ['walmart', 'restArea', 'casino', 'truckStop', 'crackerBarrel', 'cabelas'] \ then _snakeCase overnight.subType else 'default' amenityIconGetFn: (filters) -> filterValues = _map _filter(filters, 'value'), 'arrayValue' (amenity) -> icon = _orderBy(amenity.amenities, (amenity) -> filterValues.indexOf(amenity) isnt -1 and config.AMENITY_ICON_ORDER.indexOf(amenity) , ['desc'])[0] if icon is 'gym' icon = 'shower' # TODO: add gym icon, rm _snakeCase icon hazardIconGetFn: (filters) -> (hazard) -> _snakeCase hazard.subType formatLatitude: (lat) -> lat = Math.round(1000 * lat) / 1000 lat = Math.max -90, lat Math.min 90, lat formatLongitude: (lon) -> lon = Math.round(1000 * lon) / 1000 lon = Math.max -180, lon Math.min 180, lon # This is adapted from the implementation in Project-OSRM # https://github.com/DennisOSRM/Project-OSRM-Web/blob/master/WebContent/routing/OSRM.RoutingGeometry.js decodePolyline: (str, precision = 6) -> index = 0 lat = 0 lng = 0 coordinates = [] shift = 0 result = 0 byte = null latitude_change = undefined longitude_change = undefined factor = 10 ** (precision) # Coordinates have variable length when encoded, so just keep # track of whether we've hit the end of the string. In each # loop iteration, a single coordinate is decoded. while index < str.length # Reset shift, result, and byte byte = null shift = 0 result = 0 loop byte = str.charCodeAt(index++) - 63 result |= (byte & 0x1f) << shift shift += 5 unless byte >= 0x20 break latitude_change = if result & 1 then ~(result >> 1) else result >> 1 shift = result = 0 loop byte = str.charCodeAt(index++) - 63 result |= (byte & 0x1f) << shift shift += 5 unless byte >= 0x20 break longitude_change = if result & 1 then ~(result >> 1) else result >> 1 lat += latitude_change lng += longitude_change # mapbox likes these backwards coordinates.push [ lng / factor lat / factor ] coordinates module.exports = new MapService()
true
_clone = require 'lodash/clone' _map = require 'lodash/map' _filter = require 'lodash/filter' _groupBy = require 'lodash/groupBy' _orderBy = require 'lodash/orderBy' _some = require 'lodash/some' _startCase = require 'lodash/startCase' _snakeCase = require 'lodash/snakeCase' _uniq = require 'lodash/uniq' _last = require 'lodash/last' Environment = require './environment' DateService = require './date' colors = require '../colors' config = require '../config' class MapService hasLocationPermission: ({model} = {}) -> unless navigator? return Promise.resolve false # not available in native apps # https://stackoverflow.com/questions/52784495/is-there-any-alternative-to-navigator-permissions-query-permissions-api if model and Environment.isNativeApp('freeroam') and Environment.isAndroid() model.portal.call 'permissions.check', { permissions: [ 'android.permission.ACCESS_FINE_LOCATION' 'android.permission.ACCESS_COARSE_LOCATION' ] } .then (results) -> results?['android.permission.ACCESS_FINE_LOCATION'] else if navigator.permissions navigator.permissions.query {name: 'geolocation'} .then (permissionStatus) -> return permissionStatus.state is 'granted' else return Promise.resolve localStorage?.geolocationEnabled getLocation: ({model, timeout} = {}) -> timeout ?= 10000 get = => new Promise (resolve, reject) => if navigator? navigator.geolocation.getCurrentPosition (pos) -> localStorage?.geolocationEnabled = '1' lat = Math.round(10000 * pos.coords.latitude) / 10000 lon = Math.round(10000 * pos.coords.longitude) / 10000 resolve {lat, lon} , reject, {enableHighAccuracy: true, timeout: timeout} else resolve null isNativeApp = Environment.isNativeApp 'freeroam' isIos = Environment.isIos() isNativeIos = isNativeApp and isIos if model?.portal and not isNativeIos @hasLocationPermission {model} .then (hasPermission) -> if hasPermission get() else model.portal.call 'permissions.request', { permissions: [ 'android.permission.ACCESS_FINE_LOCATION' 'android.permission.ACCESS_COARSE_LOCATION' ] } .catch (err) -> console.log 'perm req err', err .then get else get() getDirectionsBetweenPlaces: (places, {model}) -> places = _clone places target = '_system' baseUrl = 'https://google.com/maps/dir/?api=1' origin = places[0].location?.lat + ',' + places[0].location?.lon destination = _last(places).location?.lat + ',' + _last(places).location?.lon places.shift() places.pop() waypoints = _map(places, (place) -> "#{place.lat},#{place.lon}" ).join '|' url = "#{baseUrl}&origin=#{origin}&destination=#{destination}" if waypoints url += "&waypoints=#{waypoints}" model.portal.call 'browser.openWindow', {url, target} getDirections: (place, {model}) -> target = '_system' baseUrl = 'https://www.google.com/maps/dir/?api=1' destination = place?.location?.lat + ',' + place?.location?.lon isIos = Environment.isIos() onError = => if isIos url = "#{baseUrl}&destination=#{destination}" else url = "#{baseUrl}&origin=My+Location&destination=#{destination}" model.portal.call 'browser.openWindow', {url, target} # FIXME takes like a minute to load? if Environment.isNativeApp 'freeroam' (if isIos # for some reason hasLocationPermission check not working on ios Promise.resolve true else @hasLocationPermission {model} ).then (hasLocationPermission) => if hasLocationPermission @getLocation {model, timeout: 5000} .catch (err) -> console.log 'caught', err onError() .then ({lat, lon} = {}) -> if lat and lon origin = lat + ',' + lon url = "#{baseUrl}&origin=#{origin}&destination=#{destination}" model.portal.call 'browser.openWindow', {url, target} else onError() else console.log 'call onError' # just use the "my location" version, to avoid popup blocker onError() getAmenityFilters: ({model}) -> [ { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'dump' name: model.l.get 'amenities.dump' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'water' name: model.l.get 'amenities.water' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'restArea' name: model.l.get 'overnight.restArea' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'groceries' name: model.l.get 'amenities.groceries' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'propane' name: model.l.get 'amenities.propane' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'trash' name: model.l.get 'amenities.trash' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'recycle' name: model.l.get 'amenities.recycle' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArraySubTypes' items: [ {key: 'anytime', label: model.l.get 'gyms.anytime'} {key: 'planet', label: model.l.get 'gyms.planet'} {key: '24Hour', label: model.l.get 'gyms.24Hour'} ] arrayValue: 'shower' name: model.l.get 'amenities.shower' filterOverlayGroup: 'amenities' valueFn: (value) -> _filter _map value, (subTypeValue, subTypeKey) -> if subTypeValue {match: subType: subTypeKey} } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'laundry' name: model.l.get 'amenities.laundry' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'gas' name: model.l.get 'amenities.gas' filterOverlayGroup: 'amenities' } { field: 'amenities' type: 'booleanArray' isBoolean: true arrayValue: 'water' name: model.l.get 'amenities.npwater' filterOverlayGroup: 'amenities' } ] getCampgroundFilters: ({model}) -> [ { field: 'subType' type: 'fieldList' items: [ {key: 'public', label: model.l.get 'placeInfo.landTypePublic'} {key: 'private', label: model.l.get 'placeInfo.landTypePrivate'} ] name: model.l.get 'placeInfo.landType' } { field: 'prices.all.mode' key: 'PI:KEY:<KEY>END_PI' type: 'maxIntCustom' inputPrefix: '$' name: model.l.get 'campground.maxPrice' title: model.l.get 'filterContent.title.maxPrice' } { field: 'cellSignal' type: 'cellSignal' name: model.l.get 'campground.cellSignal' } { field: 'fullness' type: 'maxIntSeasonal' name: model.l.get 'campground.fullness' filterOverlayGroup: 'sliders' } { field: 'weather' type: 'weather' name: model.l.get 'general.weather' } { field: 'elevation' type: 'gtlt' name: model.l.get 'general.elevation' } { field: 'distanceTo' type: 'distanceTo' name: model.l.get 'filterSheet.facilitiesNearby' } { field: 'features' type: 'iconListBooleanAnd' items: [ {key: 'waterHookup', label: model.l.get 'feature.waterHookup'} {key: 'sewerHookup', label: model.l.get 'feature.sewerHookup'} {key: '30amp', label: model.l.get 'feature.30amp'} {key: '50amp', label: model.l.get 'feature.50amp'} {key: 'petsAllowed', label: model.l.get 'feature.petsAllowed'} ] name: model.l.get 'filterSheet.features' } # { # field: 'nearbyActivities' # type: 'iconListBooleanAnd' # items: [ # {key: 'horseBackRiding', label: model.l.get 'feature.horseBackRiding'} # ] # name: model.l.get 'filterSheet.features' # } { field: 'rating' type: 'reviews' name: model.l.get 'general.reviews' } { field: 'affiliations' type: 'listBooleanOr' items: [ {key: 'escapees', label: model.l.get 'affiliation.escapees'} {key: 'goodSam', label: model.l.get 'affiliation.goodSam'} { key: 'passportAmerica' label: model.l.get 'affiliation.passportAmerica' } ] name: model.l.get 'general.affiliations' } { field: 'maxLength' key: 'minLength' type: 'minIntCustom' inputPostfix: 'ft' name: model.l.get 'campground.minLength' } { field: 'crowds' type: 'maxIntSeasonal' name: model.l.get 'campground.crowds' filterOverlayGroup: 'sliders' } { field: 'roadDifficulty' type: 'maxInt' name: model.l.get 'campground.roadDifficulty' filterOverlayGroup: 'sliders' } { field: 'shade' type: 'maxInt' name: model.l.get 'campground.shade' filterOverlayGroup: 'sliders' } { field: 'safety' type: 'minInt' name: model.l.get 'campground.safety' filterOverlayGroup: 'sliders' } { field: 'noise' type: 'maxIntDayNight' name: model.l.get 'campground.noise' filterOverlayGroup: 'sliders' } ] getHazardFilters: ({model}) -> [ { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'wildfire' name: model.l.get 'hazard.wildfire' filterOverlayGroup: 'subType' } { field: 'subType' type: 'maxClearance' name: model.l.get 'hazard.lowClearance' arrayValue: 'lowClearance' valueFn: (value) -> if value feet = parseInt value.feet if isNaN feet feet = 0 inches = parseInt value.inches if isNaN inches feet = 0 inches = feet * 12 + inches {range: 'data.heightInches': lte: inches} filterOverlayGroup: 'lowClearance' } ] getOvernightFilters: ({model}) -> [ { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'walmart' name: model.l.get 'overnight.walmart' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'truckStop' name: model.l.get 'overnight.truckStop' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'restArea' name: model.l.get 'overnight.restArea' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'casino' name: model.l.get 'overnight.casino' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'crackerBarrel' name: model.l.get 'overnight.crackerBarrel' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'cabelas' name: model.l.get 'overnight.cabelas' filterOverlayGroup: 'overnights' } { field: 'subType' type: 'booleanArray' isBoolean: true arrayValue: 'other' name: model.l.get 'overnight.other' filterOverlayGroup: 'overnights' } ] getOptionalLayers: ({model, place, placePosition}) -> date = DateService.format new Date(), 'yyyy-mm-dd' layerSettings = JSON.parse localStorage?.layerSettings or '{}' { 'us-blm': { name: model.l.get 'placesMapContainer.layerBlm' thumb: "#{config.CDN_URL}/maps/blm_overlay.png" defaultOpacity: 0.5 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-blm.json' layer: id: 'us-blm' type: 'fill' source: 'us-blm' 'source-layer': 'us_pad' layout: {} paint: # 'fill-color': colors.$mapLayerBlm 'fill-pattern': 'blm_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-usfs': { name: model.l.get 'placesMapContainer.layerUsfs' thumb: "#{config.CDN_URL}/maps/usfs_overlay.png" defaultOpacity: 0.5 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-usfs.json' layer: id: 'us-usfs' type: 'fill' source: 'us-usfs' 'source-layer': 'us_pad' layout: {} paint: # 'fill-color': colors.$mapLayerUsfs 'fill-pattern': 'usfs_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-verizon': { name: model.l.get 'placesMapContainer.layerVerizonLte' thumb: "#{config.CDN_URL}/maps/verizon_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-verizon.json' layer: id: 'us-cell-verizon' type: 'fill' source: 'us-cell-verizon' 'source-layer': 'us_cell_verizon' layout: {} paint: # 'fill-color': colors.$verizon 'fill-pattern': 'verizon_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-att': { name: model.l.get 'placesMapContainer.layerAttLte' thumb: "#{config.CDN_URL}/maps/att_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-att.json' layer: id: 'us-cell-att' type: 'fill' source: 'us-cell-att' 'source-layer': 'us_cell_att' layout: {} paint: # 'fill-color': colors.$att 'fill-pattern': 'att_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-tmobile': { name: model.l.get 'placesMapContainer.layerTmobileLte' thumb: "#{config.CDN_URL}/maps/tmobile_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-tmobile.json' layer: id: 'us-cell-tmobile' type: 'fill' source: 'us-cell-tmobile' 'source-layer': 'us_cell_tmobile' layout: {} paint: # 'fill-color': colors.$tmobile 'fill-pattern': 'tmobile_bg' metadata: zIndex: 2 insertBeneathLabels: true } 'us-cell-sprint': { name: model.l.get 'placesMapContainer.layerSprintLte' thumb: "#{config.CDN_URL}/maps/sprint_overlay.png" defaultOpacity: 0.4 source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-us-cell-sprint.json' layer: id: 'us-cell-sprint' type: 'fill' source: 'us-cell-sprint' 'source-layer': 'us_cell_sprint' layout: {} paint: # 'fill-color': colors.$sprint 'fill-pattern': 'sprint_bg' metadata: zIndex: 2 insertBeneathLabels: true } smoke: { name: model.l.get 'placesMapContainer.layerSmoke' thumb: "#{config.CDN_URL}/maps/smoke_overlay.png" source: type: 'geojson' data: "#{config.MAPS_CDN_URL}/smoke.json?#{date}" layer: id: 'smoke' type: 'fill' source: 'smoke' layout: {} paint: 'fill-opacity': property: 'Density', stops: [[0, 0], [100, 0.8]] 'fill-color': colors.$grey700 metadata: zIndex: 2 insertBeneathLabels: true } 'fire-weather': { name: model.l.get 'placesMapContainer.layerFireWeather' thumb: "#{config.CDN_URL}/maps/fire_weather_overlay.png" defaultOpacity: 0.5 source: type: 'geojson' data: "#{config.MAPS_CDN_URL}/fire_weather.json?#{date}" layer: id: 'fire-weather' type: 'fill' source: 'fire-weather' layout: {} paint: 'fill-color': [ 'match' ['get', 'name'] 'Red Flag Warning', colors.$red500 colors.$yellow500 # other ] metadata: zIndex: 2 insertBeneathLabels: true onclick: (e, properties) -> place.next { name: properties.name description: properties.description } placePosition.next e.point } 'na-contours': { name: model.l.get 'placesMapContainer.layerElevation' thumb: "#{config.CDN_URL}/maps/elevation_overlay.png" defaultOpacity: 1#0.4 sourceId: 'na-contours' source: type: 'vector' url: 'https://tileserver.freeroam.app/data/free-roam-na-contours.json?2' # url: 'http://PI:IP_ADDRESS:172.16.17.32END_PI:8080/data/v2.json' layers: [ { id: 'na-contours' type: 'line' source: 'na-contours' 'source-layer': 'contour' # minzoom: 9 # layout: paint: 'line-color': '#000000' 'line-opacity': 0.5 'line-opacity': stops: [ [0, 0.3] [14, 1] ] 'line-width': 1 metadata: zIndex: 2 } { id: 'na-contours-labels' type: 'symbol' source: 'na-contours' 'source-layer': 'contour' minzoom: 10 layout: 'symbol-placement': 'line' # 'text-field': ['concat', ['to-string', ['round', ['*', ['get', 'ele'], 3.2808399]]], "'"] 'text-field': ['concat', ['to-string', ['get', 'ele']], "'"] 'text-font': ['Open Sans Regular'] 'text-size': 14 paint: 'text-color': '#000000', 'text-halo-width': 0 metadata: zIndex: 2 } ] insertBeneathLabels: true } satellite: { name: model.l.get 'placesMapContainer.layerSatellite' thumb: "#{config.CDN_URL}/maps/satellite_overlay.png" defaultOpacity: 1 sourceId: 'mapbox' source: type: 'raster' url: 'mapbox://mapbox.satellite' tileSize: 256 layer: id: 'satellite' type: 'raster' source: 'mapbox' 'source-layer': 'mapbox_satellite_full' paint: {} # necessary to add opacity metadata: zIndex: 1 insertBeneathLabels: true } } getESQueryFromFilters: (filters, currentMapBounds) => groupedFilters = _groupBy filters, 'field' filter = _filter _map groupedFilters, (fieldFilters, field) => unless _some fieldFilters, 'value' return filter = fieldFilters[0] switch filter.type when 'maxInt', 'maxIntCustom' { range: "#{field}": lte: filter.value } when 'minInt', 'minIntCustom' { range: "#{field}": gte: filter.value } when 'gtlt' if filter.value.operator and filter.value.value { range: "#{field}": "#{filter.value.operator}": filter.value.value } when 'maxIntSeasonal' { range: "#{field}.#{filter.value.season}": lte: filter.value.value } # when 'maxClearance' # feet = parseInt filter.value.feet # if isNaN feet # feet = 0 # inches = parseInt filter.value.inches # if isNaN inches # feet = 0 # inches = feet * 12 + inches # { # range: # 'data.heightInches': # lt: inches # } when 'maxIntDayNight' { range: "#{field}.#{filter.value.dayNight}": lte: filter.value.value } when 'gtZero' { range: "#{field}": gt: 0 } when 'list' { bool: must: _filter _map filter.value, (value, key) -> if value match: "#{key}": value } when 'listBooleanAnd', 'iconListBooleanAnd' { bool: must: _filter _map filter.value, (value, key) -> if value match: "#{field}.#{key}": true } when 'listBooleanOr' { bool: should: _filter _map filter.value, (value, key) -> if value match: "#{field}.#{key}": true } when 'fieldList' { bool: should: _filter _map filter.value, (value, key) -> if value match: "#{field}": key } when 'reviews' { bool: must: _filter [ if filter.value.rating {range: {rating: {gte: filter.value.rating}}} if filter.value.hasPhotos {range: {attachmentCount: {gt: 0}}} ] } # { # field: 'attachmentCount' # type: 'gtZero' # isBoolean: true # name: model.l.get 'campground.hasPhoto' # } when 'cellSignal' { bool: should: _map filter.value, (value, carrier) -> if carrier.indexOf('_lte') isnt -1 { range: "#{field}.#{carrier}.signal": gte: value } else # check for lte and non lte bool: should: [ { range: "#{field}.#{carrier}.signal": gte: value } { range: "#{field}.#{carrier}_lte.signal": gte: value } ] } when 'weather' if filter.value.month is 'forecast' bool: must: _map filter.value.metrics, ({operator, value}, metric) -> { range: "forecast.#{metric}": "#{operator}": parseFloat(value) } else month = config.MONTHS[filter.value.month] bool: must: _map filter.value.metrics, ({operator, value}, metric) -> range: "#{field}.months.#{month}.#{metric}": "#{operator}": parseFloat(value) when 'distanceTo' bool: must: _map filter.value.facilities, (facility) -> { range: "#{field}.#{facility}.time": lte: parseInt(filter.value.time) } when 'booleanArray' withValues = _filter(fieldFilters, 'value') { # there's potentially a cleaner way to do this? bool: should: _map withValues, ({value, arrayValue, valueFn}) -> # if subtypes are specified if typeof value is 'object' bool: must: [ {match: "#{field}": arrayValue} bool: should: valueFn value ] else {match: "#{field}": arrayValue} } console.log 'fff', filter filter.push { geo_bounding_box: location: top_left: lat: @formatLatitude currentMapBounds._ne.lat lon: @formatLongitude currentMapBounds._sw.lng bottom_right: lat: @formatLatitude currentMapBounds._sw.lat lon: @formatLongitude currentMapBounds._ne.lng } filter getIconByPlace: (place) => switch place.type when 'overnight' @overnightIconGetFn(null) place when 'amenity' @amenityIconGetFn(null) place when 'hazard' @hazardIconGetFn(null) place when 'coordinate' 'empty' else @campgroundIconGetFn(null) place campgroundIconGetFn: (filters) -> (campground) -> if campground?.prices?.all?.mode is 0 and campground?.ratingCount > 0 then 'free' else if campground?.prices?.all?.mode is 0 then 'free_reviewless' else if campground?.ratingCount > 0 then 'paid' else 'paid_reviewless' overnightIconGetFn: (filters) -> (overnight) -> if overnight.subType in ['walmart', 'restArea', 'casino', 'truckStop', 'crackerBarrel', 'cabelas'] \ then _snakeCase overnight.subType else 'default' amenityIconGetFn: (filters) -> filterValues = _map _filter(filters, 'value'), 'arrayValue' (amenity) -> icon = _orderBy(amenity.amenities, (amenity) -> filterValues.indexOf(amenity) isnt -1 and config.AMENITY_ICON_ORDER.indexOf(amenity) , ['desc'])[0] if icon is 'gym' icon = 'shower' # TODO: add gym icon, rm _snakeCase icon hazardIconGetFn: (filters) -> (hazard) -> _snakeCase hazard.subType formatLatitude: (lat) -> lat = Math.round(1000 * lat) / 1000 lat = Math.max -90, lat Math.min 90, lat formatLongitude: (lon) -> lon = Math.round(1000 * lon) / 1000 lon = Math.max -180, lon Math.min 180, lon # This is adapted from the implementation in Project-OSRM # https://github.com/DennisOSRM/Project-OSRM-Web/blob/master/WebContent/routing/OSRM.RoutingGeometry.js decodePolyline: (str, precision = 6) -> index = 0 lat = 0 lng = 0 coordinates = [] shift = 0 result = 0 byte = null latitude_change = undefined longitude_change = undefined factor = 10 ** (precision) # Coordinates have variable length when encoded, so just keep # track of whether we've hit the end of the string. In each # loop iteration, a single coordinate is decoded. while index < str.length # Reset shift, result, and byte byte = null shift = 0 result = 0 loop byte = str.charCodeAt(index++) - 63 result |= (byte & 0x1f) << shift shift += 5 unless byte >= 0x20 break latitude_change = if result & 1 then ~(result >> 1) else result >> 1 shift = result = 0 loop byte = str.charCodeAt(index++) - 63 result |= (byte & 0x1f) << shift shift += 5 unless byte >= 0x20 break longitude_change = if result & 1 then ~(result >> 1) else result >> 1 lat += latitude_change lng += longitude_change # mapbox likes these backwards coordinates.push [ lng / factor lat / factor ] coordinates module.exports = new MapService()