code
stringlengths
4
1.01M
run_date() { EXPECT_EQ '1136160000' "$(TZ=UTC sub::strtotime "${1}")" EXPECT_EQ '1136127600' "$(TZ=Asia/Tokyo sub::strtotime "${1}")" } run_datetime() { EXPECT_EQ '1136214245' "$(TZ=UTC sub::strtotime "${1}")" EXPECT_EQ '1136181845' "$(TZ=Asia/Tokyo sub::strtotime "${1}")" } run_fixed_datetime() { EXPECT_EQ '1136214245' "$(TZ=UTC sub::strtotime "${1}")" EXPECT_EQ '1136214245' "$(TZ=Asia/Tokyo sub::strtotime "${1}")" } test::strtotime() { # Proposed new HTTP format. run_date '02 Jan 2006' # Old RFC850 HTTP format. run_date '02-Jan-06' # Broken RFC850 HTTP format. run_date '02-Jan-2006' # Common logfile format. run_date '02/Jan/2006' # ISO 8601 compact date format. run_date '20060102' # ISO 8601 date format. run_date '2006-01-02' # UNIX ls format. run_date 'Jan 2 2006' # English date format. run_date 'Jan 2, 2006' # Japanese date format. run_date '2006/01/02' # ISO 8601 format without timezone. run_datetime '2006-01-02 15:04:05' # ISO 8601 format with a T separator. run_datetime '2006-01-02T15:04:05' # Compact datetime format. run_datetime '20060102150405' # HTTP format without timezone. run_datetime 'Mon, 02 Jan 2006 15:04:05' run_datetime '02 Jan 2006 15:04:05' # Japanese datetime format. run_datetime '2006/01/02 15:04:05' # HTTP format. run_fixed_datetime 'Mon, 02 Jan 2006 15:04:05 GMT' run_fixed_datetime 'Mon, 02 Jan 2006 15:04:05 +0000' run_fixed_datetime '02 Jan 2006 15:04:05 GMT' run_fixed_datetime 'Tue, 03 Jan 2006 00:04:05 +0900' run_fixed_datetime 'Tue, 03 Jan 2006 00:04:05 JST' # Old RFC850 HTTP format. run_fixed_datetime 'Monday, 02-Jan-06 15:04:05 GMT' run_fixed_datetime 'Monday, 02-Jan-2006 15:04:05 GMT' # Common logfile format. run_fixed_datetime '03/Jan/2006:00:04:05 +0900' # ISO 8601 format. run_fixed_datetime '2006-01-02 15:04:05 +0000' run_fixed_datetime '2006-01-03 00:04:05 +0900' run_fixed_datetime '2006-01-02T15:04:05Z' run_fixed_datetime '2006-01-03T00:04:05+0900' run_fixed_datetime '2006-01-03T00:04:05+09:00' # UNIX timestamp format. run_fixed_datetime '1136214245' run_fixed_datetime '@1136214245' }
'use strict'; /** * Email.js service * * @description: A set of functions similar to controller's actions to avoid code duplication. */ const _ = require('lodash'); const sendmail = require('sendmail')({ silent: true }); module.exports = { send: (options, cb) => { return new Promise((resolve, reject) => { // Default values. options = _.isObject(options) ? options : {}; options.from = options.from || '"Administration Panel" <no-reply@strapi.io>'; options.replyTo = options.replyTo || '"Administration Panel" <no-reply@strapi.io>'; options.text = options.text || options.html; options.html = options.html || options.text; // Send the email. sendmail({ from: options.from, to: options.to, replyTo: options.replyTo, subject: options.subject, text: options.text, html: options.html }, function (err) { if (err) { reject([{ messages: [{ id: 'Auth.form.error.email.invalid' }] }]); } else { resolve(); } }); }); } };
package se.sciion.quake2d.level; import java.io.File; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.ObjectMap; import se.sciion.quake2d.ai.behaviour.BehaviourTree; import se.sciion.quake2d.level.items.Weapon; public class Statistics { private ObjectMap<BehaviourTree,Float> totalDamageGiven; private ObjectMap<BehaviourTree,Float> totalDamageTaken; private ObjectMap<BehaviourTree,Float> armorAtEnd; private ObjectMap<BehaviourTree,Float> healthAtEnd; private ObjectMap<BehaviourTree,Boolean> survived; private ObjectMap<BehaviourTree,Integer> killcount; private ObjectMap<BehaviourTree,Integer> roundsPlayed; private ObjectMap<BehaviourTree,Integer> pickedWeapon; public Statistics() { totalDamageGiven = new ObjectMap<BehaviourTree,Float>(); totalDamageTaken = new ObjectMap<BehaviourTree,Float>(); armorAtEnd = new ObjectMap<BehaviourTree,Float>(); healthAtEnd = new ObjectMap<BehaviourTree,Float>(); survived = new ObjectMap<BehaviourTree,Boolean>(); killcount = new ObjectMap<BehaviourTree,Integer>(); roundsPlayed = new ObjectMap<BehaviourTree, Integer>(); pickedWeapon = new ObjectMap<BehaviourTree, Integer>(); } public void recordDamageTaken(BehaviourTree giver, BehaviourTree reciever, float amount) { if(giver != null) { if(!totalDamageGiven.containsKey(giver)) { totalDamageGiven.put(giver, 0.0f); } totalDamageGiven.put(giver, totalDamageGiven.get(giver) + amount); } if(reciever != null) { if(!totalDamageTaken.containsKey(reciever)) { totalDamageTaken.put(reciever, 0.0f); } totalDamageTaken.put(reciever, totalDamageTaken.get(reciever) + amount); } } public void recordHealth(float health, float armor, BehaviourTree entity) { if(entity == null) { return; } armorAtEnd.put(entity, armor); healthAtEnd.put(entity, health); } public void recordWeaponPickup(BehaviourTree tree){ if(!pickedWeapon.containsKey(tree)){ pickedWeapon.put(tree, 0); } pickedWeapon.put(tree, pickedWeapon.get(tree) + 1); } public void recordParticipant(BehaviourTree tree){ if(!roundsPlayed.containsKey(tree)){ roundsPlayed.put(tree, 0); } roundsPlayed.put(tree, roundsPlayed.get(tree) + 1); } public void recordSurvivior(BehaviourTree entity) { if(entity == null) { return; } survived.put(entity, true); } public void recordKill(BehaviourTree giver) { if(giver == null) { return; } if(!killcount.containsKey(giver)) { killcount.put(giver, 0); } killcount.put(giver, killcount.get(giver) + 1); } public float getFitness(BehaviourTree tree) { float damageGiven = totalDamageGiven.get(tree, 0.0f); float damageTaken = totalDamageTaken.get(tree, 0.0f); float armor = armorAtEnd.get(tree, 0.0f); //float health = healthAtEnd.get(tree,0.0f); int killcount = this.killcount.get(tree, 0); boolean survived = this.survived.get(tree, false); int rounds = roundsPlayed.get(tree,1); int weapon = pickedWeapon.get(tree, 0); return (5.0f * damageGiven + 2.0f * armor + (survived ? 500.0f : 0.0f) + 50.0f * weapon + 1000.0f * killcount) / (float)(rounds); } public boolean hasSurvived(BehaviourTree tree) { return survived.get(tree, false); } public int getTotalKillcount() { int total = 0; for(Integer i: killcount.values()) { total += i; } return total; } @Override public String toString() { String output = "Match statistics:\n"; for(BehaviourTree tree: totalDamageGiven.keys()) { output += "Tree: " + tree.toString() + " damage given: " + totalDamageGiven.get(tree) + "\n"; } for(BehaviourTree tree: totalDamageTaken.keys()) { output += "Tree: " + tree.toString() + " damage taken: " + totalDamageGiven.get(tree) + "\n"; } for(BehaviourTree tree: healthAtEnd.keys()) { output += "Tree: " + tree.toString() + " " + healthAtEnd.get(tree,0.0f) + " health at end\n"; } for(BehaviourTree tree: armorAtEnd.keys()) { output += "Tree: " + tree.toString() + " " + armorAtEnd.get(tree,0.0f) + " armor at end\n"; } for(BehaviourTree tree: survived.keys()) { output += "Tree: " + tree.toString() + " survived\n"; } for(BehaviourTree tree: roundsPlayed.keys()) { output += "Tree: " + tree.toString() + " played " + roundsPlayed.get(tree) + " rounds\n"; } for(BehaviourTree tree: pickedWeapon.keys()) { output += "Tree: " + tree.toString() + " picked weapon\n"; } return output; } public void clear() { armorAtEnd.clear(); healthAtEnd.clear(); killcount.clear(); survived.clear(); totalDamageGiven.clear(); totalDamageTaken.clear(); pickedWeapon.clear(); roundsPlayed.clear(); } }
USE ITIN20LAP; GO INSERT INTO Einrichtungen(Beschreibung) VALUES('Stuhl'); INSERT INTO Einrichtungen(Beschreibung) VALUES('Tisch'); INSERT INTO Einrichtungen(Beschreibung) VALUES('Monitor'); INSERT INTO Einrichtungen(Beschreibung) VALUES('Computer'); INSERT INTO Einrichtungen(Beschreibung) VALUES('Kasten'); GO INSERT INTO Gebäude(FirmenName,Plz,Stadt,Straße,Hausnummer,[order],active) VALUES('crowd-o-moto','1110','Wien','Volkstheater','17',1,'True'); INSERT INTO Gebäude(FirmenName,Plz,Stadt,Straße,Hausnummer,[order],active) VALUES('pc-web','4020','Linz','Wienerstrasse','22',2,'True'); INSERT INTO Gebäude(FirmenName,Plz,Stadt,Straße,Hausnummer,[order],active) VALUES('bundesrechenzentrum','5020','Salzburg','Hinterholz','8',3,'True'); INSERT INTO Gebäude(FirmenName,Plz,Stadt,Straße,Hausnummer,[order],active) VALUES('bbrz-Vorarlberg','6700','Bregenz','Mariahilfsstrasse','2',4,'True'); INSERT INTO Gebäude(FirmenName,Plz,Stadt,Straße,Hausnummer,[order],active) VALUES('bbrz-Schärding','4975','Schärding','Linzerstrasse','1',5,'True'); Go INSERT INTO Räume(Gebäude_Id,Bez) VALUES(1,'EntwicklerBüro'); INSERT INTO Räume(Gebäude_Id,Bez) VALUES(2,'ServerRaum'); INSERT INTO Räume(Gebäude_Id,Bez) VALUES(3,'TechnikerBüro'); INSERT INTO Räume(Gebäude_Id,Bez) VALUES(4,'LagerRaum'); INSERT INTO Räume(Gebäude_Id,Bez) VALUES(5,'Büro'); GO --1 RaumEinrichtungen id 1-5 per 5 Räume INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(1,1); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(1,2); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(1,3); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(1,4); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(1,5); --2 INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(2,1); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(2,2); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(2,3); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(2,4); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(2,5); --3 INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(3,1); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(3,2); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(3,3); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(3,4); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(3,5); --4 INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(4,1); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(4,2); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(4,3); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(4,4); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(4,5); --5 INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(5,1); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(5,2); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(5,3); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(5,4); INSERT INTO RaumEinrichtungen(Raum_Id,Einrichtung_Id) VALUES(5,5); GO INSERT INTO BenutzerRollen(Beschreibung,active) VALUES('Admin', 'true'); INSERT INTO BenutzerRollen(Beschreibung,active) VALUES('User', 'true'); INSERT INTO BenutzerRollen(Beschreibung,active) VALUES('Mitarbeiter', 'false'); GO INSERT INTO Firmen(FirmenName,Plz,Stadt,Straße,Hausnummer) VALUES('Microsoft','1120','Wien','Am Europl.','3'); INSERT INTO Firmen(FirmenName,Plz,Stadt,Straße,Hausnummer) VALUES('Apple','1110','Wien','Westbahnhof','22'); INSERT INTO Firmen(FirmenName,Plz,Stadt,Straße,Hausnummer) VALUES('Blizzard','1311','Wien','Stephansplatz','11'); INSERT INTO Firmen(FirmenName,Plz,Stadt,Straße,Hausnummer) VALUES('Westwood','1140','Wien','Rennbahnweg','2'); INSERT INTO Firmen(FirmenName,Plz,Stadt,Straße,Hausnummer) VALUES('Notch','1340','Wien','Rennbahnweg','13'); GO INSERT INTO Benutzer(BenutzerRolle_Id,Firmen_Id,email,Passwort,Vorname,Nachname,ist_Mitarbeiter, active) VALUES(2,1,'dzallinger@gmx.at',HASHBYTES('SHA2_512', '123user!'),'Daniel','Zallinger','true', 'true'); INSERT INTO Benutzer(BenutzerRolle_Id,Firmen_Id,email,Passwort,Vorname,Nachname,ist_Mitarbeiter, active) VALUES(1,2,'mbichler@gmx.at',HASHBYTES('SHA2_512', '123user!'),'Max','Bichler','false', 'true'); INSERT INTO Benutzer(BenutzerRolle_Id,Firmen_Id,email,Passwort,Vorname,Nachname,ist_Mitarbeiter, active) VALUES(2,3,'edruckner@gmx.at',HASHBYTES('SHA2_512', '123user!'),'Erwin','Druckner','false', 'false'); INSERT INTO Benutzer(BenutzerRolle_Id,Firmen_Id,email,Passwort,Vorname,Nachname,ist_Mitarbeiter, active) VALUES(3,4,'pwagner@gmx.at',HASHBYTES('SHA2_512', '123user!'),'Phillip','Wagner','false', 'false'); INSERT INTO Benutzer(BenutzerRolle_Id,Firmen_Id,email,Passwort,Vorname,Nachname,ist_Mitarbeiter, active) VALUES(3,5,'bmarkovic@gmx.at',HASHBYTES('SHA2_512', '123user!'),'Bojan','Markovic','false', 'false'); GO INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(1,1,'2016-01-09'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(2,2,'2016-13-06'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(3,3,'2016-20-06'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(4,4,'2017-01-01'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(5,5,'2017-13-01'); GO --last Month Bookings INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(1,1,'2017-20-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(4,1,'2017-23-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(3,1,'2017-27-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(2,2,'2017-12-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(1,2,'2017-13-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(5,2,'2017-11-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(1,3,'2017-10-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(2,3,'2017-13-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(5,3,'2017-20-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(4,4,'2017-12-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(1,4,'2017-08-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(2,4,'2017-09-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(5,5,'2017-07-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(3,5,'2017-15-02'); INSERT INTO Buchungen(Raum_Id,Benutzer_Id,Datum) VALUES(4,5,'2017-19-02'); GO INSERT INTO Rechnungen(Datum,Benutzer_Id) VALUES('2016-08-09',1); INSERT INTO Rechnungen(Datum,Benutzer_Id) VALUES('2016-20-06',1); INSERT INTO Rechnungen(Datum,Benutzer_Id) VALUES('2016-27-06',1); INSERT INTO Rechnungen(Datum,Benutzer_Id) VALUES('2017-08-01',1); INSERT INTO Rechnungen(Datum,Benutzer_Id) VALUES('2017-20-01',1); Go INSERT INTO RechnungsDetails(Rechnung_Id,Datum,Buchung_Id) VALUES(1,'2016-08-01',1); INSERT INTO RechnungsDetails(Rechnung_Id,Datum,Buchung_Id) VALUES(2,'2016-20-06',2); INSERT INTO RechnungsDetails(Rechnung_Id,Datum,Buchung_Id) VALUES(3,'2016-27-06',3); INSERT INTO RechnungsDetails(Rechnung_Id,Datum,Buchung_Id) VALUES(4,'2017-08-01',4); INSERT INTO RechnungsDetails(Rechnung_Id,Datum,Buchung_Id) VALUES(5,'2017-20-01',5); GO INSERT INTO Kontakte(Benutzer_Id,Firmen_Id) VALUES(1,1); INSERT INTO Kontakte(Benutzer_Id,Firmen_Id) VALUES(2,2); INSERT INTO Kontakte(Benutzer_Id,Firmen_Id) VALUES(3,3); INSERT INTO Kontakte(Benutzer_Id,Firmen_Id) VALUES(4,4); INSERT INTO Kontakte(Benutzer_Id,Firmen_Id) VALUES(5,5); GO INSERT INTO Stornierungen(Buchung_Id,Benutzer_Id,Grund) VALUES(1,1,'Langweilig'); INSERT INTO Stornierungen(Buchung_Id,Benutzer_Id,Grund) VALUES(2,2,'Nicht Gut'); INSERT INTO Stornierungen(Buchung_Id,Benutzer_Id,Grund) VALUES(3,3,'Nicht Schön'); INSERT INTO Stornierungen(Buchung_Id,Benutzer_Id,Grund) VALUES(4,4,'Raum zu Gros'); INSERT INTO Stornierungen(Buchung_Id,Benutzer_Id,Grund) VALUES(5,5,'raum zu klein'); GO
<!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title> Dados </title> </head> <body> <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> Lanzamiento de dados del jugador 1:<input type="checkbox" name="dado1" required> Lanzamiento de dados del jugador 2:<input type="checkbox" name="dado2" required><br> <input type="submit" value="Enviar"><br> <?php $dado1 = $_POST['dado1']; $dado2 = $_POST['dado2']; if (isset($dado1)&& isset($dado2)) { $tirada1 = mt_rand(1,6) + mt_rand(1,6); echo "La tirada del jugador 1 es $tirada1 </br>"; $tirada2 = mt_rand(1,6) + mt_rand(1,6); echo "La tirada del jugador 2 es $tirada2 </br>"; if ($tirada1 < $tirada2) { echo "El jugador 2 gana"; } elseif ($tirada1 == $tirada2) { echo"Empate"; } else { echo "El jugador 1 gana"; } } else { die("Ambos judadores deben lanzar dados"); } ?> </body> </html>
callback_functions = ["collision_enter", "collision_stay", "collision_exit"] length_area_world = 75 raise_exception = False # import all required modules from game import * from gameobject import * from contracts import * from configuration import * from component import * from loader import * from physics import * from scene import * from timeutils import * from builtincomponents import * from builtincomponents.camera import * from builtincomponents.collider import * from builtincomponents.sprite_renderer import * from builtincomponents.transform import *
/** * The MIT License * Copyright (c) 2011 Kuali Mobility Team * * 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. */ div#directory input#searchText{ width: 100%; } div#directory { /*height: 100%;*/ padding: 0; } div.ui-content { /*height: 100%;*/ padding: 0; } form#search { padding: 10px 10px 10px 10px; } ul#peopleList { margin: 0; }
--- title: "Yesus, Saudara Setia Kita" date: 15/01/2022 --- ### Bacalah untuk Pelajaran Pekan Ini Im. 25: 25-27; Ibr. 2: 14-16; Ibr. 11: 24-26; 1 Kor 15: 50; Ibr. 5: 8, 9; Ibr. 12: 1-4. > <p>Ayat Hafalan</p> > "Karena anak-anak itu adalah anak-anak dari darah dan daging, maka la juga menjadi sama dengan mereka dan mendapat bagian dalam keadaan mereka, supaya oleh kematian-Nya Ia memusnahkan dia, yaitu Iblis, yang berkuasa atas maut" (Ibrani 2: 14). Ibrani 1 berbicara tentang Yesus sebagai Anak Allah, penguasa atas para malaikat, dan "cahaya kemuliaan Allah dan gambar wujud Allah" _(Ibr. 1: 3)_. Dalam Ibrani 2, Yesus adalah Anak Manusia, yang dibuat lebih rendah dari para malaikat dan yang mengadopsi sifat manusia dengan segala kelemahannya, bahkan sampai pada titik kematian _(Ibr. 2: 7)_. Dalam Ibraní 1, Allah berkata tentang Yesus: "Anak-Ku Engkau" _(Ibr. 1: 5)_. Dalam Ibrani 2, Yesus menyebut anak-anak manusia sebagai "saudara" _(Ibr. 2: 12)_. Dalam Ibrani 1, Bapa menyatakan kedaulatan Ilahi Anak _(Ibr. 1: 8-12)_. Dalam Ibrani 2, Anak menegaskan kesetiaan-Nya kepada Bapa _(Ibr. 2: 13a)_. Dalam Ibrani 1, Yesus adalah Tuhan, Pencipta, Pemelihara, dan Penguasa Ilahi. Dalam Ibrani 2, Yesus adalah Imam Besar manusia, penyayang dan setia. Singkatnya, gambaran Yesus sebagai saudara yang setia dan penuh belas kasihan digambarkan dalam gambaran tentang Anak sebagai perwujudan akhir dari Allah pencipta yang kekal _(Ibr. 1: 1-4)_. _\*Pelajari pelajaran pekan ini untuk persiapan Sabat, 22 Januari_.
using System.Threading.Tasks; using BattleMech.WebAPI.PCL.Transports.CharacterProfile; using BattleMech.WebAPI.PCL.Transports.Common; using BattleMech.WebAPI.PCL.Transports.Internal; namespace BattleMech.WebAPI.PCL.Handlers { public class CharacterProfileHandler : BaseHandler { public CharacterProfileHandler(HandlerItem handlerItem) : base(handlerItem, "CharacterProfile") { } public async Task<CTI<CharacterProfileResponseItem>> GET() { return await GET<CTI<CharacterProfileResponseItem>>(string.Empty); } } }
# Data com mês por extenso. Construa uma função que receba uma data # no formato DD/MM/AAAA e devolva uma string no formato D de mesPorExtenso de AAAA. # Opcionalmente, valide a data e retorne NULL caso a data seja inválida. require 'test/unit' require_relative 'date_format' class TestDateFormat < Test::Unit::TestCase def test_to_br_convertion @date_format = DateFormat.new('12/03/1991') assert_equal(@date_format.to_br, '12 de Mar de 1991') end def test_to_br_detects_invalid_date_format @date_format = DateFormat.new('1991/03/12') assert_equal(@date_format.to_br, 'Invalid Date Format') end end
DS.classes.Message = function(create){ var relations = []; //check check(create, { time: DS.classes.Time, data: Match.Optional(Object) }); //create _.extend(this, create); //add relations this.addRelation = function(relation, reversed){ check(relation, DS.classes.Relation); check(reversed, Boolean); relations.push({ 'relation': relation, 'reversed': reversed }); }; this.getRelations = function(){ return relations; } };
{template '_header'} {template 'diypage/_common'} <div class="page-heading"> <span class='pull-right' style="padding: 15px 10px;"> <strong>左侧跟随</strong> <input class="js-switch small" id="phoneposition" type="checkbox" value="1" checked /> </span> <h2>{if !empty($menu)}编辑{else}新建{/if}自定义菜单 {if !empty($menu)}<small>(菜单名称: {$menu['name']})</small>{/if}</h2> </div> <div class="diy-phone" style="position: fixed;" data-merch="{php echo intval($_W['merchid'])}"> <div class="phone-head"></div> <div class="phone-body"> <div class="phone-title" id="page">自定义菜单</div> <div class="phone-main" id="phone" style="position: relative; overflow: hidden"> <p style="text-align: center; line-height: 400px">loading...</p> </div> </div> <div class="phone-foot"></div> </div> <div class="diy-editor form-horizontal" id="diy-editor" style="float: right;"> <div class="editor-arrow"></div> <div class="inner"></div> </div> <div class="diy-menu"> <div class="action"> <nav class="btn btn-default btn-sm" style="float: left; display: none" id="gotop"><i class="icon icon-top" style="font-size: 12px"></i> 返回顶部</nav> <nav class="btn btn-primary btn-sm btn-save" data-type="save">保存菜单</nav> </div> </div> {template 'diypage/_template_menu'} <script language="javascript"> var path = '../../plugin/diypage/static/js/diy.menu'; myrequire([path,'tpl','web/biz'],function(modal,tpl){ modal.init({ tpl: tpl, attachurl: "{$_W['attachurl']}", id: '{php echo intval($_GPC["id"])}', menu: {if !empty($menu['data'])}{php echo json_encode($menu['data'])}{else}null{/if}, merch: {if $_W['plugin']=='merch' && !empty($_W['merchid'])}1{else}0{/if} }); }); function showSubMenu(obj) { $(obj).toggleClass('on').siblings().removeClass('on'); $(obj).find('.child').toggleClass('in'); $(obj).siblings().find('.child').removeClass('in') } $(function () { $("#phoneposition").click(function () { var div = $(this).next(); if(div.hasClass('checked')){ $(".diy-phone").css({'position': 'fixed'}); }else{ $(".diy-phone").css('position', 'relative'); } }); }); </script> {template '_footer'}
#!/usr/bin/ruby require 'sinatra' require 'sinatra/json' require 'json' settings.public_folder = "client" get '/' do send_file File.join( settings.public_folder, "client.html" ) end get '/api' do fp = "#{params['file_path']}/*" files = [] folders = [] Dir.glob(fp).select do |f| if (!File.directory? f) then files.push File.basename(f) else folders.push File.basename(f) end end json ({ :files => files, :folders => folders }) end
from functools import reduce # constants used in the multGF2 function mask1 = mask2 = polyred = None def setGF2(degree, irPoly): """Define parameters of binary finite field GF(2^m)/g(x) - degree: extension degree of binary field - irPoly: coefficients of irreducible polynomial g(x) """ def i2P(sInt): """Convert an integer into a polynomial""" return [(sInt >> i) & 1 for i in reversed(range(sInt.bit_length()))] global mask1, mask2, polyred mask1 = mask2 = 1 << degree mask2 -= 1 polyred = reduce(lambda x, y: (x << 1) + y, i2P(irPoly)[1:]) def multGF2(p1, p2): """Multiply two polynomials in GF(2^m)/g(x)""" p = 0 while p2: if p2 & 1: p ^= p1 p1 <<= 1 if p1 & mask1: p1 ^= polyred p2 >>= 1 return p & mask2 if __name__ == "__main__": # Define binary field GF(2^3)/x^3 + x + 1 setGF2(127, 2**127 + 2**63 + 1) # Evaluate the product (x^2 + x + 1)(x^2 + 1) print("{:02x}".format(multGF2(0x3f7e0000000000000000000000000000L, 0x3f7e00000000000000000000L)))
# -*- coding: utf8 -*- from __future__ import unicode_literals import unittest import os import sys from flake8.api import legacy as engine if sys.version_info[0] == 3: unicode = str if sys.version_info[:2] == (2, 6): # Monkeypatch to make tests work on 2.6 def assert_less(first, second, msg=None): assert first > second unittest.TestCase.assertLess = assert_less class TestCodeComplexity(unittest.TestCase): def test_flake8_conformance(self): flake8style = engine.get_style_guide( ignore=['E501'], max_complexity=6 ) directory = 'flask_rollbar' self.assertEqual(os.path.isdir(directory), True, "Invalid test directory '%s'. You need to update test_flake8.py" % directory) # Get all the files to check files = [] for dirpath, dirnames, filenames in os.walk(directory): for filename in [f for f in filenames if f.endswith(".py")]: files += [os.path.join(dirpath, filename)] result = flake8style.check_files(files) self.assertEqual(result.total_errors, 0, "Code found to be too complex or failing PEP8") if __name__ == '__main__': unittest.main()
{% extends "base.html" %} {% block content %} <div class="row"> <div class="span12"> <div class="page-header"> <h2>File Not Found</h2> </div> <p>The file you are looking for cannot be found.</p> </div> </div> {% endblock %}
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>set_cursor_open_flags</title> <link rel="stylesheet" href="apiReference.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Berkeley DB C++ Standard Template Library API Reference" /> <link rel="up" href="db_container.html" title="Chapter 3.  Db_container" /> <link rel="prev" href="stldb_containerget_cursor_open_flags.html" title="get_cursor_open_flags" /> <link rel="next" href="stldb_containerdb_container.html" title="db_container" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 11.2.5.3</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">set_cursor_open_flags</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="stldb_containerget_cursor_open_flags.html">Prev</a> </td> <th width="60%" align="center">Chapter 3.  Db_container </th> <td width="20%" align="right"> <a accesskey="n" href="stldb_containerdb_container.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="stldb_containerset_cursor_open_flags"></a>set_cursor_open_flags</h2> </div> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="stldb_containerset_cursor_open_flags_details"></a>Function Details</h3> </div> </div> </div> <pre class="programlisting"> void set_cursor_open_flags(u_int32_t flag) </pre> <p>Set flag of Db::cursor() call. </p> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="idp50070192"></a>Parameters</h4> </div> </div> </div> <div class="sect4" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h5 class="title"><a id="idp50076720"></a>flag</h5> </div> </div> </div> <p>Flags to be set to Db::cursor(). </p> </div> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="idp50073696"></a>Group: Get and set functions for data members.</h3> </div> </div> </div> <p>Note that these functions are not thread safe, because all data members of <a class="link" href="db_container.html" title="Chapter 3.  Db_container">db_container</a> are supposed to be set on container construction and initialization, and remain read only afterwards. </p> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="idp50069592"></a>Class</h3> </div> </div> </div> <p> <a class="link" href="db_container.html" title="Chapter 3.  Db_container">db_container</a> </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="stldb_containerget_cursor_open_flags.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="db_container.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="stldb_containerdb_container.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">get_cursor_open_flags </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top">  db_container </td> </tr> </table> </div> </body> </html>
package com.cezarykluczynski.stapi.etl.template.starship_class.dto; public class StarshipClassTemplateParameter { public static final String NAME = "name"; public static final String OWNER = "owner"; public static final String OPERATOR = "operator"; public static final String AFFILIATION = "affiliation"; public static final String DECKS = "decks"; public static final String SPEED = "speed"; public static final String TYPE = "type"; public static final String ACTIVE = "active"; public static final String ARMAMENT = "armament"; }
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item name " + id, price: 100 + i }); } } addProducts(5); var order = 'desc'; export default class SortTable extends React.Component{ handleBtnClick = e => { if(order === 'desc'){ this.refs.table.handleSort('asc', 'name'); order = 'asc'; } else { this.refs.table.handleSort('desc', 'name'); order = 'desc'; } } render(){ return ( <div> <p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p> <button onClick={this.handleBtnClick}>Sort Product Name</button> <BootstrapTable ref="table" data={products}> <TableHeaderColumn dataField="id" isKey={true} dataSort={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable> </div> ); } };
--- layout: post title: 棋子翻转(美团) categories: C和C++基础 description: 编程基础。 keywords: C++,基础 --- #### 题目描述 在4x4的棋盘上摆满了黑白棋子,黑白两色的位置和数目随机,其中左上角坐标为(1,1),右下角坐标为(4,4),现在依次有一些翻转操作,要对一些给定支点坐标为中心的上下左右四个棋子的颜色进行翻转,请计算出翻转后的棋盘颜色。 给定两个数组A和f,分别为初始棋盘和翻转位置。其中翻转位置共有3个。请返回翻转后的棋盘。 测试样例: [[0,0,1,1],[1,0,1,0],[0,1,1,0],[0,0,1,0]],[[2,2],[3,3],[4,4]] 返回:[[0,1,1,1],[0,0,1,0],[0,1,1,0],[0,0,1,0]] #### 程序代码 ```cpp #include <iostream> #include <vector> using namespace std; vector<vector<int> > flipChess(vector<vector<int> > A, vector<vector<int> > f){ for(int i=0;i<f.size();i++){ int x=f[i][0]-1; int y=f[i][1]-1; if(x-1>=0){ if(A[x-1][y]==1) A[x-1][y]=0; else A[x-1][y]=1; } if(x+1<=3){ if(A[x+1][y]==1) A[x+1][y]=0; else A[x+1][y]=1; } if(y-1>=0){ if(A[x][y-1]==1) A[x][y-1]=0; else A[x][y-1]=1; } if(y+1<=3){ if(A[x][y+1]==1) A[x][y+1]=0; else A[x][y+1]=1; } } for(int i=0;i<A.size();i++){ for(int j=0;j<A[i].size();j++){ cout<<A[i][j]<<" "; } cout<<endl; } return A; } int main(){ int a1[4]={0,0,1,1}; int a2[4]={1,0,1,0}; int a3[4]={0,1,1,0}; int a4[4]={0,0,1,0}; vector<int> arr1(a1,a1+4); vector<int> arr2(a2,a2+4); vector<int> arr3(a3,a3+4); vector<int> arr4(a4,a4+4); vector<vector<int> >A; A.push_back(arr1); A.push_back(arr2); A.push_back(arr3); A.push_back(arr4); int af1[2]={2,2}; int af2[2]={3,3}; int af3[2]={4,4}; vector<int> f1(af1,af1+2); vector<int> f2(af2,af2+2); vector<int> f3(af3,af3+2); vector<vector<int> > f; f.push_back(f1); f.push_back(f2); f.push_back(f3); flipChess(A,f); system("pause"); } ```
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>pi-calc: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.14.1 / pi-calc - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> pi-calc <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-20 11:08:53 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-20 11:08:53 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.14.1 Formal proof management system dune 2.9.3 Fast, portable, and opinionated build system ocaml 4.13.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.13.1 Official release 4.13.1 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/pi-calc&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/PiCalc&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: process algebras&quot; &quot;keyword: pi-calculus&quot; &quot;keyword: concurrency&quot; &quot;keyword: higher-order syntax&quot; &quot;category: Computer Science/Concurrent Systems and Protocols/Theory of concurrent systems&quot; &quot;date: 1998-07&quot; ] authors: [ &quot;Ivan Scagnetto &lt;scagnett@dimi.uniud.it&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/pi-calc/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/pi-calc.git&quot; synopsis: &quot;Pi-calculus in Coq&quot; description: &quot;&quot;&quot; http://www.dimi.uniud.it/~scagnett/pi-calculus.html This is a HOAS-based encoding of the pi-calculus (as originally conceived by Milner, Parrow and Walker in &quot;A Calculus of Mobile Processes&quot; Parts I-II, Information and Computation n. 100) together with the formal verification of a large part of the metatheory of Strong Late Bisimilarity.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/pi-calc/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=3f2c7a1365c9a374a9e0336e03264361&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-pi-calc.8.8.0 coq.8.14.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.1). The following dependencies couldn&#39;t be met: - coq-pi-calc -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-pi-calc.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
//////////////////////////////////////////////////////////////////////////////////// ////// Events //////////////////////////////////////////////////////////////////////////////////// 'use strict'; // DI var db, responseHandler; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.findAll = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); var errors = req.validationErrors(), appid; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; db.findAllEvents({'application_id': appid}, responseHandler(res, next)); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.findById = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('eventid', '"eventid": must be a valid identifier').notNull(); var errors = req.validationErrors(), appid, eventid; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; eventid = req.params.eventid; db.findEventById({'application_id': appid, 'event_id': eventid}, responseHandler(res, next)); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.create = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('type', '"type": must be a valid identifier').notNull(); req.check('user', '"user": must be a valid identifier').notNull(); req.check('issued', '"date": must be a valid date').isDate(); var errors = req.validationErrors(), appid, type, user, issued; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; type = req.params.type; user = req.params.user; issued = req.params.issued; // or "2013-02-26"; // TODO today or specified db.createEvent( {'application_id': appid, 'type': type, 'user': user, 'issued': issued}, responseHandler(res, next) ); };
'use strict'; const path = require('path'); const request = require('supertest'); const pedding = require('pedding'); const assert = require('assert'); const sleep = require('ko-sleep'); const mm = require('..'); const fixtures = path.join(__dirname, 'fixtures'); const baseDir = path.join(fixtures, 'app-event'); describe('test/app_event.test.js', () => { afterEach(mm.restore); describe('after ready', () => { let app; before(() => { app = mm.app({ baseDir, cache: false, }); return app.ready(); }); after(() => app.close()); it('should listen by eventByRequest', done => { done = pedding(3, done); app.once('eventByRequest', done); app.on('eventByRequest', done); request(app.callback()) .get('/event') .expect(200) .expect('done', done); }); }); describe('before ready', () => { let app; beforeEach(() => { app = mm.app({ baseDir, cache: false, }); }); afterEach(() => app.ready()); afterEach(() => app.close()); it('should listen after app ready', done => { done = pedding(2, done); app.once('appReady', done); app.on('appReady', done); }); it('should listen after app instantiate', done => { done = pedding(2, done); app.once('appInstantiated', done); app.on('appInstantiated', done); }); }); describe('throw before app init', () => { let app; beforeEach(() => { const baseDir = path.join(fixtures, 'app'); const customEgg = path.join(fixtures, 'error-framework'); app = mm.app({ baseDir, customEgg, cache: false, }); }); afterEach(() => app.close()); it('should listen using app.on', done => { app.on('error', err => { assert(err.message === 'start error'); done(); }); }); it('should listen using app.once', done => { app.once('error', err => { assert(err.message === 'start error'); done(); }); }); it('should throw error from ready', function* () { try { yield app.ready(); } catch (err) { assert(err.message === 'start error'); } }); it('should close when app init failed', function* () { app.once('error', () => {}); yield sleep(1000); // app._app is undefined yield app.close(); }); }); });
/*! * Kaiseki * Copyright(c) 2012 BJ Basañes / Shiki (shikishiji@gmail.com) * MIT Licensed * * See the README.md file for documentation. */ var request = require('request'); var _ = require('underscore'); var Kaiseki = function(options) { if (!_.isObject(options)) { // Original signature this.applicationId = arguments[0]; this.restAPIKey = arguments[1]; this.masterKey = null; this.sessionToken = arguments[2] || null; this.request = request; this.baseURL = 'https://api.parse.com'; } else { // New interface to allow masterKey and custom request function options = options || {}; this.applicationId = options.applicationId; this.restAPIKey = options.restAPIKey; this.masterKey = options.masterKey || null; this.sessionToken = options.sessionToken || null; this.request = options.request || request; this.baseURL = options.serverURL; } }; Kaiseki.prototype = { applicationId: null, restAPIKey: null, masterKey: null, // required for deleting files sessionToken: null, createUser: function(data, callback) { this._jsonRequest({ method: 'POST', url: '/1/users', params: data, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback(err, res, body, success); } }); }, getUser: function(objectId, params, callback) { this._jsonRequest({ url: '/1/users/' + objectId, params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, // Also used for validating a session token // https://parse.com/docs/rest#users-validating getCurrentUser: function(sessionToken, callback) { if (_.isFunction(sessionToken)) { callback = sessionToken; sessionToken = undefined; } this._jsonRequest({ url: '/1/users/me', sessionToken: sessionToken, callback: callback }); }, loginFacebookUser: function(facebookAuthData, callback) { this._socialLogin({facebook: facebookAuthData}, callback); }, loginTwitterUser: function(twitterAuthData, callback) { this._socialLogin({twitter: twitterAuthData}, callback); }, loginUser: function(username, password, callback) { this._jsonRequest({ url: '/1/login', params: { username: username, password: password }, callback: callback }); }, updateUser: function(objectId, data, callback) { this._jsonRequest({ method: 'PUT', url: '/1/users/' + objectId, params: data, callback: callback }); }, deleteUser: function(objectId, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/users/' + objectId, callback: callback }); }, getUsers: function(params, callback) { this._jsonRequest({ url: '/1/users', params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, requestPasswordReset: function(email, callback) { this._jsonRequest({ method: 'POST', url: '/1/requestPasswordReset', params: {'email': email}, callback: callback }); }, createObjects: function(className, data, callback) { var requests = []; for (var i = 0; i < data.length; i++) { requests.push({ 'method': 'POST', 'path': '/1/classes/' + className, 'body': data[i] }); } this._jsonRequest({ method: 'POST', url: '/1/batch/', params: { requests: requests }, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback(err, res, body, success); } }); }, createObject: function(className, data, callback) { this._jsonRequest({ method: 'POST', url: '/1/classes/' + className, params: data, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback(err, res, body, success); } }); }, getObject: function(className, objectId, params, callback) { this._jsonRequest({ url: '/1/classes/' + className + '/' + objectId, params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, updateObjects: function(className, updates, callback) { var requests = [], update = null; for (var i = 0; i < updates.length; i++) { update = updates[i]; requests.push({ 'method': 'PUT', 'path': '/1/classes/' + className + '/' + update.objectId, 'body': update.data }); } this._jsonRequest({ method: 'POST', url: '/1/batch/', params: { requests: requests }, callback: callback }); }, updateObject: function(className, objectId, data, callback) { this._jsonRequest({ method: 'PUT', url: '/1/classes/' + className + '/' + objectId, params: data, callback: callback }); }, deleteObject: function(className, objectId, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/classes/' + className + '/' + objectId, callback: callback }); }, getObjects: function(className, params, callback) { this._jsonRequest({ url: '/1/classes/' + className, params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, countObjects: function(className, params, callback) { var paramsMod = params; if (_.isFunction(params)) { paramsMod = {}; paramsMod['count'] = 1; paramsMod['limit'] = 0; } else { paramsMod['count'] = 1; paramsMod['limit'] = 0; } this._jsonRequest({ url: '/1/classes/' + className, params: paramsMod, callback: _.isFunction(params) ? params : callback }); }, createRole: function(data, callback) { this._jsonRequest({ method: 'POST', url: '/1/roles', params: data, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback(err, res, body, success); } }); }, getRole: function(objectId, params, callback) { this._jsonRequest({ url: '/1/roles/' + objectId, params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, updateRole: function(objectId, data, callback) { this._jsonRequest({ method: 'PUT', url: '/1/roles/' + objectId, params: data, callback: callback }); }, deleteRole: function(objectId, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/roles/' + objectId, callback: callback }); }, getRoles: function(params, callback) { this._jsonRequest({ url: '/1/roles', params: _.isFunction(params) ? null : params, callback: _.isFunction(params) ? params : callback }); }, uploadFile: function(filePath, fileName, callback) { if (_.isFunction(fileName)) { callback = fileName; fileName = null; } var contentType = require('mime').lookup(filePath); if (!fileName) fileName = filePath.replace(/^.*[\\\/]/, ''); // http://stackoverflow.com/a/423385/246142 var buffer = require('fs').readFileSync(filePath); this.uploadFileBuffer(buffer, contentType, fileName, callback); }, uploadFileBuffer: function(buffer, contentType, fileName, callback) { this._jsonRequest({ method: 'POST', url: '/1/files/' + fileName, body: buffer, headers: { 'Content-type': contentType }, callback: callback }); }, deleteFile: function(name, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/files/' + name, callback: callback }); }, sendPushNotification: function(data, callback) { this._jsonRequest({ method: 'POST', url: '/1/push', params: data, callback: function(err, res, body, success) { if (!err && success) body = _.extend({}, data, body); callback.apply(this, arguments); } }); }, sendAnalyticsEvent: function(eventName, dimensionsOrCallback, callback) { this._jsonRequest({ method: 'POST', url: '/1/events/' + eventName, params: _.isFunction(dimensionsOrCallback) ? {} : dimensionsOrCallback, callback: _.isFunction(dimensionsOrCallback) ? dimensionsOrCallback : callback }); }, stringifyParamValues: function(params) { if (!params || _.isEmpty(params)) return null; var values = _(params).map(function(value, key) { if (_.isObject(value) || _.isArray(value)) return JSON.stringify(value); else return value; }); var keys = _(params).keys(); var ret = {}; for (var i = 0; i < keys.length; i++) ret[keys[i]] = values[i]; return ret; }, _socialLogin: function(authData, callback) { this._jsonRequest({ method: 'POST', url: '/1/users', params: { authData: authData }, callback: callback }); }, _jsonRequest: function(opts) { var sessionToken = opts.sessionToken || this.sessionToken; opts = _.omit(opts, 'sessionToken'); opts = _.extend({ method: 'GET', url: null, params: null, body: null, headers: null, callback: null }, opts); var reqOpts = { method: opts.method, headers: { 'X-Parse-Application-Id': this.applicationId, 'X-Parse-REST-API-Key': this.restAPIKey } }; if (sessionToken) reqOpts.headers['X-Parse-Session-Token'] = sessionToken; if (this.masterKey) reqOpts.headers['X-Parse-Master-Key'] = this.masterKey; if (opts.headers) _.extend(reqOpts.headers, opts.headers); if (opts.params) { if (opts.method == 'GET') opts.params = this.stringifyParamValues(opts.params); var key = 'qs'; if (opts.method === 'POST' || opts.method === 'PUT') key = 'json'; reqOpts[key] = opts.params; } else if (opts.body) { reqOpts.body = opts.body; } this.request(this.baseURL + opts.url, reqOpts, function(err, res, body) { var isCountRequest = opts.params && !_.isUndefined(opts.params['count']) && !!opts.params.count; var success = !err && res && (res.statusCode === 200 || res.statusCode === 201); if (res && res.headers['content-type'] && res.headers['content-type'].toLowerCase().indexOf('application/json') >= 0) { if (body != null && !_.isObject(body) && !_.isArray(body)) // just in case it's been parsed already body = JSON.parse(body); if (body != null) { if (body.error) { success = false; } else if (body.results && _.isArray(body.results) && !isCountRequest) { // If this is a "count" request. Don't touch the body/result. body = body.results; } } } opts.callback(err, res, body, success); }); } }; module.exports = Kaiseki;
# == Schema Information # # Table name: tags # # ID :integer not null, primary key # Name :string(100) # TagType :string(5) default("other"), not null # Uses :integer default(1), not null # class Tag < ActiveRecord::Base end
(function(app) { "use strict"; app.directive("ratingInput", [ "$rootScope", function($rootScope) { return { restrict: "A", link: function($scope, $element, $attrs) { $element.raty({ score: $attrs.cdRatingInput, half: true, halfShow: true, starHalf: "/Content/Images/star-half-big.png", starOff: "/Content/Images/star-off-big.png", starOn: "/Content/Images/star-on-big.png", hints: ["Poor", "Average", "Good", "Very Good", "Excellent"], target: "#Rating", targetKeep: true, noRatedMsg: "Not Rated yet!", scoreName: "Rating", click: function(score) { $rootScope.$broadcast("Broadcast::RatingAvailable", score); } }); } }; } ]); })(angular.module("books"));
{ "status": { "error": false, "code": 200, "type": "success", "message": "Success" }, "pagination": { "before_cursor": null, "after_cursor": null, "previous_link": null, "next_link": null }, "data": [ { "id": 1111, "name": "marketing" } ] }
var gulp = require('gulp'); var connect = require('gulp-connect'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var opn = require('opn'); var config = { rootDir: '.', servingPort: 8080, servingDir: './dist', paths: { src: { scripts: './src/**/*.js', styles: './src/**/*.css', images: '', index: './src/index.html', partials: ['./src/**/*.html', '!./index.html'], }, distDev: './dist.dev', distProd: './dist.prod' } } gulp.task('build', function() { }); gulp.task('serve', ['connect'], function() { return opn('http://localhost:' + config.servingPort); }); gulp.task('livereload', function() { console.log('reloading') gulp.src(config.filesToWatch) .pipe(connect.reload()); }); gulp.task('connect', function() { connect.server({ root: config.servingDir, port: config.servingPort, livereload: false, fallback: config.servingDir + '/index.html' }); }); gulp.task('watch', function() { gulp.watch([config.sourcePaths.css, config.sourcePaths.html, config.sourcePaths.js], ['livereload']); }); gulp.task('default', ['serve']); //default: clean-build-prod //serve dev
<?php /** * VersionControl_HG * Simple OO implementation for Mercurial. * * PHP Version 5.4 * * @copyright 2014 Siad Ardroumli * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://siad007.github.io/versioncontrol_hg */ namespace Siad007\VersionControl\HG\Command; /** * Simple OO implementation for Mercurial. * * @author Siad Ardroumli <siad.ardroumli@gmail.com> */ class TagsCommand extends BaseCommand { }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>hardware: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.12.0 / hardware - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> hardware <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-03-07 04:21:54 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-07 04:21:54 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.12.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/hardware&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Hardware&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: hardware verification&quot; &quot;keyword: comparator circuit&quot; &quot;category: Computer Science/Architecture&quot; &quot;category: Miscellaneous/Extracted Programs/Hardware&quot; ] authors: [ &quot;Solange Coupet-Grimal &amp; Line Jakubiec&quot; ] bug-reports: &quot;https://github.com/coq-contribs/hardware/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/hardware.git&quot; synopsis: &quot;Verification and synthesis of hardware linear arithmetic structures&quot; description: &quot;&quot;&quot; Verification and synthesis of hardware linear arithmetic structures. Example of a left-to-right comparator. Three approaches are tackled : - the usual verification of a circuit, consisting in proving that the description satisfies the specification, - the synthesis of a circuit from its specification using the Coq extractor, - the same approach as above but using the Program tactic.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/hardware/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=1593891a691ce5979b7a92a015c295c7&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-hardware.8.7.0 coq.8.12.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.12.0). The following dependencies couldn&#39;t be met: - coq-hardware -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hardware.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ceramist: 2 h 5 m 🏆</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.10.dev / ceramist - 1.0.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> ceramist <small> 1.0.0 <span class="label label-success">2 h 5 m 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-08-11 14:39:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-11 14:39:01 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; synopsis: &quot;Coq library for reasoning about probabilistic algorithms&quot; description: &quot;&quot;&quot; Ceramist extends coq-infotheo to support reasoning about probabilistic algorithms, and includes a collection of lemmas on random oracle based hash functions. Provides an example implementation of a bloom filter and uses the library to prove the probability of a false positive. &quot;&quot;&quot; homepage: &quot;https://github.com/certichain/ceramist&quot; dev-repo: &quot;git+https://github.com/certichain/ceramist.git&quot; bug-reports: &quot;https://github.com/certichain/ceramist/issues&quot; maintainer: &quot;kirang@comp.nus.edu.sg&quot; authors: [ &quot;Kiran Gopinathan&quot; &quot;Ilya Sergey&quot; ] license: &quot;GPL-3.0-or-later&quot; depends: [ &quot;coq&quot; {&gt;= &quot;8.10.2&quot; &amp; &lt; &quot;8.11~&quot;} &quot;coq-mathcomp-ssreflect&quot; {&gt;= &quot;1.10&quot; &amp; &lt; &quot;1.11~&quot;} &quot;coq-mathcomp-analysis&quot; { &gt;= &quot;0.2.0&quot; &amp; &lt; &quot;0.3~&quot; } &quot;coq-infotheo&quot; { &gt;= &quot;0.0.6&quot; &amp; &lt; &quot;0.0.7~&quot; } ] build: [ [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] tags: [ &quot;category:Computer Science/Data Types and Data Structures&quot; &quot;keyword: bloomfilter&quot; &quot;keyword: probability&quot; &quot;date:2020-01-25&quot; ] url { src: &quot;https://github.com/certichain/ceramist/archive/1.0.0.tar.gz&quot; checksum: &quot;sha512=1d75e229cf3deaa654177464fee009807acb22f8f72cfb54bcf9d5ee16cc318f3ed089a1f4c94c520637b1845ba0e5fccac951cacbe6ca7e62cb9a2047b01c72&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-ceramist.1.0.0 coq.8.10.dev</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-ceramist.1.0.0 coq.8.10.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>44 m 42 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-ceramist.1.0.0 coq.8.10.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 h 5 m</dd> </dl> <h2>Installation size</h2> <p>Total: 40 M</p> <ul> <li>24 M <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/tactics.vo</code></li> <li>2 M <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BloomFilter/BloomFilter_Probability.vo</code></li> <li>2 M <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BloomFilter/BloomFilter_Probability.glob</code></li> <li>2 M <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/QuotientFilter/QuotientFilter_Probability.vo</code></li> <li>1 M <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/CountingBloomFilter/CountingBloomFilter_Probability.vo</code></li> <li>1 M <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQ.vo</code></li> <li>849 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQReduction.vo</code></li> <li>575 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/HashVec.vo</code></li> <li>560 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BlockedAMQ/BlockedAMQ.vo</code></li> <li>506 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/rsum_ext.vo</code></li> <li>471 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/rsum_ext.glob</code></li> <li>425 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/CountingBloomFilter/CountingBloomFilter_Definitions.vo</code></li> <li>423 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/FixedList.vo</code></li> <li>283 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/QuotientFilter/QuotientFilter_Probability.glob</code></li> <li>245 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/stirling.vo</code></li> <li>239 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BloomFilter/BloomFilter_Definitions.vo</code></li> <li>225 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/HashVec.glob</code></li> <li>221 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/QuotientFilter/QuotientFilter_Definitions.vo</code></li> <li>216 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQHash.vo</code></li> <li>213 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BlockedAMQ/BlockedAMQ.glob</code></li> <li>210 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/FixedList.glob</code></li> <li>192 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/CountingBloomFilter/CountingBloomFilter_Definitions.glob</code></li> <li>176 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQ.glob</code></li> <li>162 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/InvMisc.vo</code></li> <li>161 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/stirling.glob</code></li> <li>152 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/seq_ext.vo</code></li> <li>143 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/FixedMap.vo</code></li> <li>141 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQReduction.glob</code></li> <li>139 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/CountingBloomFilter/CountingBloomFilter_Probability.glob</code></li> <li>105 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQHash.glob</code></li> <li>96 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/InvMisc.glob</code></li> <li>90 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/Hash.vo</code></li> <li>80 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/QuotientFilter/QuotientFilter_Definitions.glob</code></li> <li>78 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/seq_subset.vo</code></li> <li>76 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Computation/Comp.vo</code></li> <li>72 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Computation/Notationv1.vo</code></li> <li>70 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/seq_ext.glob</code></li> <li>60 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/rsum_ext.v</code></li> <li>59 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BloomFilter/BloomFilter_Probability.v</code></li> <li>55 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BloomFilter/BloomFilter_Definitions.glob</code></li> <li>52 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/FixedList.v</code></li> <li>39 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BlockedAMQ/BlockedAMQ.v</code></li> <li>37 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/HashVec.v</code></li> <li>36 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/CountingBloomFilter/CountingBloomFilter_Definitions.v</code></li> <li>30 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/FixedMap.glob</code></li> <li>29 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/tactics.glob</code></li> <li>29 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQ.v</code></li> <li>27 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/QuotientFilter/QuotientFilter_Probability.v</code></li> <li>22 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQHash.v</code></li> <li>21 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/stirling.v</code></li> <li>20 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/AMQReduction.v</code></li> <li>19 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/InvMisc.v</code></li> <li>16 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/QuotientFilter/QuotientFilter_Definitions.v</code></li> <li>13 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/CountingBloomFilter/CountingBloomFilter_Probability.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/BloomFilter/BloomFilter_Definitions.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/seq_ext.v</code></li> <li>10 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/Hash.glob</code></li> <li>10 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/tactics.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Computation/Comp.glob</code></li> <li>8 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/seq_subset.glob</code></li> <li>7 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/FixedMap.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Computation/Notationv1.glob</code></li> <li>3 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Computation/Comp.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Core/Hash.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Utils/seq_subset.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/ProbHash/Computation/Notationv1.v</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-ceramist.1.0.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
use reversi::*; pub trait AI { fn consider(&mut self, board: &mut Board) -> Command; }
--- layout: post title: MongoDB Atlas tags: [NoSQL] categories: [MongoDB] image: background: triangular.png --- #### What is Mongo Atlas ? Mongo Atlas is the cloud hosted version of MongoDB. This is the software-as-a-service flavor of the NoSQL database. #### Why MongoDB Atlas ? Since this is the software as a service and is hosted on the cloud it has several advantages over the on-premise hosted version: 1. Easy and quick ( in around 10-15 mins) to setup a production standard single replica set or sharded cluster of MongoDB. 2. Highly reliable cluster. The cluster is deployed on AWS (Amazon Web Service). Each member of the replica set is deployed on a different availability zone and thus providing a higher degree of fault tolerance for a particular replica set. 2. No need to have a NoSQl database management expertise. 3. Provides users the ability to configure backups of the database and also restore the data from backup when necessary. 4. Automated handling of failure scenarios. If the primary node goes down then Atlas automatically handles election of a new primary and recovery of the broken node. 5. Tracks various system level and database level metrics. These metrics are represented as graphs for users to drill down for a particular time frame and granularity. 6. Setup alerts based on different metrics and custom user set thresholds. 7. Pay as you go pricing. The pricing is dependent on your usage and the configuration you choose. This gives flexibility to organizations based on their use cases and financial capabilities. ### Setting up a cluster Once you have registered and created an account. You will be presented with a form where you can choose your desired configuration for the database. The pricing displayed in the screenshots below are for the base minimum configuration. The price varies based on the choices you make for the below parameters. ### To quickly give an overview of the choices you have 1. The DB engine (3.2v WiredTiger or 3.4v WiredTiger). The older engine MMAP(memory mapped) is not supported in MongoDB Atlas. 2. Right now the hosting is available only in the Oregon region of AWS. 3. The size of the instances on which to host the database. The instances need to be homogeneous. Different instances have different memory and CPU However, the storage can be configured as desired. 4. Replication factor. Number of replica in a replica set. 5. Whether to setup a single replica set stand-alone cluster or a sharded cluster. 6. If the backup needs to be enabled or not. <figure class="center"> <img src="/images/atlas/cluster-1.png" height="800px"></img> </figure> <figure class="center"> <img src="/images/atlas/cluster-2.png" height="800px"></img> </figure> <figure class="center"> <img src="/images/atlas/cluster-3.png" height="800px"></img> </figure>
// Copyright (c) 2017-2019 Jae-jun Kang // See the file LICENSE for details. using System.Reflection; [assembly: AssemblyTitle("x2net.xpiler")] [assembly: AssemblyDescription("x2net.xpiler")]
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="utf-8"> <title>io.js 주간 뉴스 2015년 3월 27일 | Node.js 한국 커뮤니티</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="description" content="io.js 1.6.2 릴리스 이번 주에는 v1.6.2 릴리스가 있었습니다. GitHub에서 전체 변경사항을 볼 수 있습니다. 주요 변경 사항 1.6.2 Windows: Windows 지원 상태의 개선작업으로 전체 테스트를 다시 통과하게 되었습니다. v1.4.2의 릴리스 노트에서 언급했듯이, CI 시스템과 설정이 Windows 테스트의 바른 문제 보고를"> <meta property="og:type" content="article"> <meta property="og:title" content="io.js 주간 뉴스 2015년 3월 27일"> <meta property="og:url" content="https://nodejs.github.io/nodejs-ko/weekly/2015/03/27/weekly/index.html"> <meta property="og:site_name" content="Node.js 한국 커뮤니티"> <meta property="og:description" content="io.js 1.6.2 릴리스 이번 주에는 v1.6.2 릴리스가 있었습니다. GitHub에서 전체 변경사항을 볼 수 있습니다. 주요 변경 사항 1.6.2 Windows: Windows 지원 상태의 개선작업으로 전체 테스트를 다시 통과하게 되었습니다. v1.4.2의 릴리스 노트에서 언급했듯이, CI 시스템과 설정이 Windows 테스트의 바른 문제 보고를"> <meta property="og:locale"> <meta property="article:published_time" content="2015-03-27T00:00:00.000Z"> <meta property="article:modified_time" content="2021-02-11T02:51:58.772Z"> <meta property="article:author" content="Node.js 한국어 번역팀"> <meta name="twitter:card" content="summary"> <meta name="twitter:creator" content="@nodejs_ko"> <link rel="alternate" href="/nodejs-ko/atom.xml" title="Node.js 한국 커뮤니티" type="application/atom+xml"> <link rel="icon" href="/nodejs-ko/favicon.png"> <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="/nodejs-ko/css/style.css"> <meta name="generator" content="Hexo 5.3.0"></head> <body> <div id="container"> <div id="wrap"> <header id="header"> <div id="banner"></div> <div id="header-outer" class="outer"> <div id="header-title" class="inner"> <h1 id="logo-wrap"> <a href="/nodejs-ko/" id="logo">Node.js 한국 커뮤니티</a> </h1> </div> <div id="header-inner" class="inner"> <nav id="main-nav"> <a id="main-nav-toggle" class="nav-icon"></a> <a class="main-nav-link" href="/nodejs-ko/">Home</a> <a class="main-nav-link" href="/nodejs-ko/archives">Archives</a> </nav> <nav id="sub-nav"> <a id="nav-rss-link" class="nav-icon" href="/nodejs-ko/atom.xml" title="RSS Feed"></a> <a id="nav-search-btn" class="nav-icon" title="Search"></a> </nav> <div id="search-form-wrap"> <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://nodejs.github.io/nodejs-ko"></form> </div> </div> </div> </header> <div class="outer"> <section id="main"><article id="post-weekly" class="article article-type-post" itemscope itemprop="blogPost"> <div class="article-meta"> <a href="/nodejs-ko/weekly/2015/03/27/weekly/" class="article-date"> <time datetime="2015-03-27T00:00:00.000Z" itemprop="datePublished">2015-03-27</time> </a> <div class="article-category"> <a class="article-category-link" href="/nodejs-ko/categories/weekly/">weekly</a> </div> </div> <div class="article-inner"> <header class="article-header"> <h1 class="article-title" itemprop="name"> io.js 주간 뉴스 2015년 3월 27일 </h1> <ul> <li>작성자: <strong>iojs</strong></li> <li> 원문: <strong><a target="_blank" rel="noopener" href="https://medium.com/node-js-javascript/io-js-week-of-march-27th-9555f36bbb9a" taret="_blank"> io.js Week of March 27th — Node &amp;amp; JavaScript </a></strong> </li> <li> 번역: <strong><a href="https://github.com/marocchino" target="_blank">marocchino</a></strong> </li> </ul> </header> <div class="article-entry" itemprop="articleBody"> <h1>io.js 1.6.2 릴리스</h1> <!-- This week we had one io.js releases [v1.6.2](https://iojs.org/dist/v1.6.2/), complete changelog can be found [on GitHub](https://github.com/nodejs/node/blob/v1.x/CHANGELOG.md). --> <p>이번 주에는 <a target="_blank" rel="noopener" href="https://iojs.org/dist/v1.6.2/">v1.6.2</a> 릴리스가 있었습니다. <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/blob/v1.x/CHANGELOG.md">GitHub</a>에서 전체 변경사항을 볼 수 있습니다.</p> <h3>주요 변경 사항</h3> <h4>1.6.2</h4> <!-- * **Windows**: The ongoing work in improving the state of Windows support has resulted in full test suite passes once again. As noted in the release notes for v1.4.2, CI system and configuration problems prevented it from properly reporting problems with the Windows tests, the problems with the CI and the codebase appear to have been fully resolved. * **FreeBSD**: A [kernel bug](https://lists.freebsd.org/pipermail/freebsd-current/2015-March/055043.html) impacting io.js/Node.js was [discovered](https://github.com/joyent/node/issues/9326) and a patch has been introduced to prevent it causing problems for io.js (Fedor Indutny) [#1218](https://github.com/nodejs/node/pull/1218). * **module**: you can now `require('.')` instead of having to `require('./')`, this is considered a bugfix (Michaël Zasso) [#1185](https://github.com/nodejs/node/pull/1185). * **v8**: updated to 4.1.0.25 including patches for `--max_old_space_size` values above `4096` and Solaris support, both of which are already included in io.js. --> <ul> <li><strong>Windows</strong>: Windows 지원 상태의 개선작업으로 전체 테스트를 다시 통과하게 되었습니다. v1.4.2의 릴리스 노트에서 언급했듯이, CI 시스템과 설정이 Windows 테스트의 바른 문제 보고를 방해하던 문제와 CI와 코드베이스의 문제는 완전히 해결된 것으로 보입니다.</li> <li><strong>FreeBSD</strong>: io.js/Node.js에 영향을 주는 <a target="_blank" rel="noopener" href="https://lists.freebsd.org/pipermail/freebsd-current/2015-March/055043.html">커널 버그</a>가 <a target="_blank" rel="noopener" href="https://github.com/joyent/node/issues/9326">발견</a>되어 io.js에서 이 문제가 일어나지 않도록 수정했습니다.(Fedor Indutny) <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/pull/1218">#1218</a>.</li> <li><strong>module</strong>: 이제 <code>require('./')</code> 대신 <code>require('.')</code>를 사용할 수 있습니다. 이 변경은 버그 수정으로 간주합니다.(Michaël Zasso) <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/pull/1185">#1185</a>.</li> <li><strong>v8</strong>: 4.1.0.25로 업데이트 했습니다. 여기에는 <code>--max_old_space_size</code>에 <code>4096</code>을 넘는 값을 사용한 경우 발생하는 문제의 수정사항과 Solaris 지원이 들어있습니다. 언급된 수정은 이미 io.js에 포함되어 있습니다.</li> </ul> <h3>알려진 이슈</h3> <!-- * Possible small memory leak(s) may still exist but have yet to be properly identified, details at [#1075](https://github.com/nodejs/node/issues/1075). * Surrogate pair in REPL can freeze terminal [#690](https://github.com/nodejs/node/issues/690) * Not possible to build io.js as a static library [#686](https://github.com/nodejs/node/issues/686) * `process.send()` is not synchronous as the docs suggest, a regression introduced in 1.0.2, see [#760](https://github.com/nodejs/node/issues/760) and fix in [#774](https://github.com/nodejs/node/issues/774) * Calling `dns.setServers()` while a DNS query is in progress can cause the process to crash on a failed assertion [#894](https://github.com/nodejs/node/issues/894) --> <ul> <li>원인을 아직 알 수 없는 미미한 메모리 누수가 있을 수 있습니다. 자세한 사항은 <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/issues/1075">#1075</a>를 참조하세요.</li> <li>대화형 셸에서 서러게이트 페어(Surrogate pair)가 터미널을 정지시킬 수 있습니다. <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/issues/690">#690</a></li> <li>io.js를 정적 라이브러리로 빌드할 수 없습니다. <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/issues/686">#686</a></li> <li><code>process.send()</code>는 문서에서 설명된 바와는 다르게 동기적이지 않습니다. 이 회귀는 1.0.2에서 발생했습니다. <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/issues/760">#760</a>에서 확인 가능하며 <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/issues/774">#774</a>에서 수정하고 있습니다.</li> <li>DNS 쿼리 중에 <code>dns.setServers()</code>를 호출하면 실패한 단언문 때문에 크래시가 발생할 수 있습니다. <a target="_blank" rel="noopener" href="https://github.com/nodejs/node/issues/894">#894</a></li> </ul> <h1>커뮤니티 업데이트</h1> <!-- * Node.js Technical Governance Draft is proposed, you can check the draft [here](https://github.com/joyent/nodejs-advisory-board/pull/30) * Microsoft Visual Studio team releases Node.js Tools 1.0 for Visual Studio, the release includes rich editor, code completions, interactive window, advanced debugging and profiling. Check [the announcement](http://blogs.msdn.com/b/visualstudio/archive/2015/03/25/node-js-tools-1-0-for-visual-studio.aspx). * [SPM monitor supports node.js and io.js](http://blog.sematext.com/2015/03/30/nodejs-iojs-monitoring/), the monitor adds performance monitoring, alerting, and anomaly detection. --> <ul> <li>Node.js Technical Governance 초안이 제안되었습니다. <a target="_blank" rel="noopener" href="https://github.com/joyent/nodejs-advisory-board/pull/30">여기</a>에서 초안을 확인하실 수 있습니다.</li> <li>Microsoft Visual Studio 팀이 Visual Studio를 위한 Node.js Tools 1.0을 릴리스 했습니다. 이 릴리스에는 리치 에디터, 코드 자동완성, 대화형 윈도우, 고급 디버깅과 프로파일링이 포함됩니다. <a target="_blank" rel="noopener" href="http://blogs.msdn.com/b/visualstudio/archive/2015/03/25/node-js-tools-1-0-for-visual-studio.aspx">공지</a>를 읽어보세요.</li> <li><a target="_blank" rel="noopener" href="http://blog.sematext.com/2015/03/30/nodejs-iojs-monitoring/">node.js, io.js SPM 모니터 지원</a>, 모니터에 성능 모니터링, 경고 및 이상 탐지를 추가합니다.</li> </ul> <h1>다가오는 이벤트</h1> <!-- * [NodeConf](http://nodeconf.com/) tickets are on sale, June 8th and 9th at Oakland, CA and NodeConf Adventure for June 11th - 14th at Walker Creek Ranch, CA * [CascadiaJS](http://2015.cascadiajs.com/) tickets are on sale, July 8th - 10th at Washington State * [NodeConf EU](http://nodeconf.eu/) tickets are on sale, September 6th - 9th at Waterford, Ireland * [nodeSchool tokyo](http://nodejs.connpass.com/event/13182/) will be held in April 12th at Tokyo, Japan --> <ul> <li><a target="_blank" rel="noopener" href="http://nodeconf.com/">NodeConf</a> 입장권을 판매하고 있습니다. 6월 8일과 9일, 캘리포니아 오클랜드에서 열리며, NodeConf Adventure는 6월 11일~14일, 캘리포니아 Walker Creek Ranch에서 열립니다.</li> <li><a target="_blank" rel="noopener" href="http://2015.cascadiajs.com/">CascadiaJS</a> 입장권을 판매하고 있습니다. 7월 8일~10일, 워싱턴주에서 열립니다.</li> <li><a target="_blank" rel="noopener" href="http://nodeconf.eu/">NodeConf EU</a> 입장권을 판매하고 있습니다. 9월 6일~9일, 아일랜드 워터퍼드에서 열립니다.</li> <li><a target="_blank" rel="noopener" href="http://nodejs.connpass.com/event/13182/">nodeSchool tokyo</a>가 4월 12일 일본의 도쿄에서 개최될 예정입니다.</li> </ul> </div> <footer class="article-footer"> <a data-url="https://nodejs.github.io/nodejs-ko/weekly/2015/03/27/weekly/" data-id="ckl09nghp000ly8n7fwbvhz8o" class="article-share-link">Share</a> </footer> </div> <nav id="article-nav"> <a href="/nodejs-ko/articles/2015/04/02/help-us-reconcile-node-js-and-io-js/" id="article-nav-newer" class="article-nav-link-wrap"> <strong class="article-nav-caption">Newer</strong> <div class="article-nav-title"> node.js와 io.js가 손잡을 수 있도록 도와주세요. </div> </a> <a href="/nodejs-ko/weekly/2015/03/20/weekly/" id="article-nav-older" class="article-nav-link-wrap"> <strong class="article-nav-caption">Older</strong> <div class="article-nav-title">io.js 주간 뉴스 2015년 3월 20일</div> </a> </nav> </article> </section> <aside id="sidebar"> <div class="widget-wrap"> <h3 class="widget-title">Menu</h3> <div class="widget"> <ul class="category-list"> <li class="category-list-item"> <a href="/nodejs-ko/">Home</a> </li> <li class="category-list-item"> <a href="/nodejs-ko/CONTRIBUTING.html">번역 참여 가이드</a> </li> <li class="category-list-item"> <a href="/nodejs-ko/about.html">소개</a> </li> <li class="category-list-item"> <a href="/nodejs-ko/categories/articles">글 모음</a> </li> <li class="category-list-item"> <a href="/nodejs-ko/categories/weekly">주간 뉴스</a> </li> <li class="category-list-item"> <a href="/nodejs-ko/archives">보관함</a> </li> <li class="category-list-item"> <a href="https://github.com/nodejs/nodejs-ko" target="_blank">GitHub project</a> </li> </ul> </div> </div> </aside> </div> <footer id="footer"> <div class="outer"> <div id="footer-info" class="inner"> &copy; 2021 Node.js 한국어 번역팀<br> Powered by <a href="http://hexo.io/" target="_blank">Hexo</a> </div> </div> </footer> </div> <nav id="mobile-nav"> <a href="/nodejs-ko/" class="mobile-nav-link">Home</a> <a href="/nodejs-ko/archives" class="mobile-nav-link">Archives</a> </nav> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <link rel="stylesheet" href="/nodejs-ko/fancybox/jquery.fancybox.css"> <script src="/nodejs-ko/fancybox/jquery.fancybox.pack.js"></script> <script src="/nodejs-ko/js/script.js"></script> </div> </body> </html>
import React from 'react' import {Observable} from 'rx' import {TextField} from 'material-ui' import ThemeManager from 'material-ui/lib/styles/theme-manager'; import MyRawTheme from '../components/Theme.js'; import ThemeDecorator from 'material-ui/lib/styles/theme-decorator'; import {compose} from 'recompose' import {observeProps, createEventHandler} from 'rx-recompose' import {clickable} from '../style.css' import {View} from '../components' let Search = compose( // ASDFGHJKL: ThemeDecorator(ThemeManager.getMuiTheme(MyRawTheme)) , observeProps(props$ => { // Create search query observable let setQuery = createEventHandler() let query$ = setQuery.share() query$ // Only search for songs that are not only spaces 😂 .filter(x => x.trim() !== '') // Only every 300 ms .debounce(300) // Get the `doSearch` method from props .withLatestFrom(props$.pluck('doSearch'), (query, doSearch) => doSearch(query)) // Search for the query .subscribe(func => { func() }) return { // Pass down function to set the query setQuery: Observable.just(setQuery), // Pass down the current query value query: query$.startWith(''), // Pass down force-search function when pressing enter doSearch: props$.pluck('doSearch'), // Function to start playing song when clicked on playSong: props$.pluck('playSong'), // Searchresults to display searchResults: Observable.merge( // Results from the search props$.pluck('results$') // Get results observable .distinctUntilChanged() // Only when unique .flatMapLatest(x => x) // Morph into the results$ .startWith([]) // And set off with a empty array , query$ // When query is only spaces .filter(x => x.trim() === '') // Reset the results to empty array .map(() => []) ), } }) )(({query, setQuery, searchResults, playSong, doSearch}) => ( <View> <TextField hintText="Search for a song! :D" onChange={(e,value) => setQuery(e.target.value)} value={query} onEnterKeyDown={doSearch(query)} fullWidth={true} underlineStyle={{borderWidth: 2}} /> <View> { /* List all the results */ } { searchResults.map(result => <View key={result.nid} className={clickable} // On click, reset the query and play the song! onClick={() => { playSong(result)() setQuery('') }} // Same as setting the text, but more compact children={`${result.title} - ${result.artist}`} /> )} </View> </View> )) export default Search
<!DOCTYPE HTML> <html lang="en"> <head> <title>Shower Presentation Engine</title> <meta charset="utf-8"> <meta name="viewport" content="width=792, user-scalable=no"> <meta http-equiv="x-ua-patible" content="ie=edge"> <link rel="stylesheet" href="shower/themes/ribbon/styles/screen.css"> <link rel="stylesheet" href="animations.css"> <style> .row { margin: 0; } .row .col-1 { float: left; width: 16%; } .row .col-2 { float: left; width: 33%; } .row .col-3 { float: left; width: 48%; } .row .col-4 { float: left; width: 64%; } .row .col-5 { float: left; width: 80%; } .row .col-6 { float: left; width: 96%; } .row-divider { margin-top: 4em; } .center { display: block; margin-left: auto; margin-right: auto; } .strike { text-decoration: line-through; } .graytext { opacity: 0.5; } </style> </head> <body class="list"> <section class="slide"><div> <h2><img src="pictures/chrome.png" style="width:1em;height:1em;" /> Responsive CSS Animations</h2> <p>Darren Shen <span class="graytext">(shend@)</span></p> <p>Host: Tim Loh <span class="graytext">(timloh@)</span></p> </div></section> <section class="slide" style="background: url('pictures/first-website.jpg') center no-repeat;"><div> <!-- Intro: First web page--> </div></section> <section class="slide" style="background: url('pictures/best.jpg') center no-repeat; background-size: contain;"><div> <!-- Intro: Best web page--> </div></section> <section class="slide"><div> <!-- What are CSS animations? Ball with eyes --> <div class="row"> <div class="col-2"> <figure class="demo-ball demo-ball-shading"> <div class="demo-ball-eye"></div> <div class="demo-ball-eye-separator"></div> <div class="demo-ball-eye"></div> <div class="demo-ball-moustache"></div> </figure> </div> <div class="col-4"> <pre> <code>.box {</code> <code> background: pink;</code> <code> border-radius: 20%;</code> <code> <mark class="comment">/* etc. */</mark> </code> <code>}</code> </pre> <pre> <code>.eye { <mark class="comment">/* styles for eye */</mark> }</code> </pre> <pre> <code>.moustache { <mark class="comment">/* styles for moustache */</mark> }</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- What are CSS animations? Bouncy ball with keyframes explanation --> <div class="row"> <pre> <code><mark>@keyframes</mark> bounce {</code> <code> <mark>50%</mark> { transform: translateY(-60px); }</code> <code>}</code> </pre> </div> <div class="row row-divider next" style="text-align: center;"> <div class="col-2"> <figure class="demo-ball demo-ball-shading center"> <div class="demo-ball-eye"></div> <div class="demo-ball-eye-separator"></div> <div class="demo-ball-eye"></div> <div class="demo-ball-moustache"></div> </figure> <div>0%</div> </div> <div class="col-2"> <figure class="demo-ball demo-ball-shading center" style="transform: translateY(-60px);"> <div class="demo-ball-eye"></div> <div class="demo-ball-eye-separator"></div> <div class="demo-ball-eye"></div> <div class="demo-ball-moustache"></div> </figure> <div>50%</div> </div> <div class="col-2"> <figure class="demo-ball demo-ball-shading center"> <div class="demo-ball-eye"></div> <div class="demo-ball-eye-separator"></div> <div class="demo-ball-eye"></div> <div class="demo-ball-moustache"></div> </figure> <div>100%</div> </div> </div> </div></section> <section class="slide"><div> <!-- What are CSS animations? Bouncy ball with just translate --> <div class="row"> <div class="col-2"> <figure class="demo-ball demo-ball-shading next" style="-webkit-animation: demo-bounce-1 1s infinite ease-in-out;"> <div class="demo-ball-eye"></div> <div class="demo-ball-eye-separator"></div> <div class="demo-ball-eye"></div> <div class="demo-ball-moustache"></div> </figure> </div> <div class="col-4"> <pre> <code>@keyframes bounce {</code> <code> 50% { transform: translateY(-60px); }</code> <code>}</code> </pre> <pre> <code>.box {</code> <code> <mark class="comment">/* ...styling */</mark></code> <code> <mark>animation: bounce 1s infinite;</mark></code> <code>}</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- What are CSS animations? Bouncy ball with better animation --> <div class="row"> <div class="col-2"> <figure class="demo-ball demo-ball-shading" style="-webkit-animation: demo-bounce-2 1s infinite;"> <div class="demo-ball-eye"></div> <div class="demo-ball-eye-separator"></div> <div class="demo-ball-eye"></div> <div class="demo-ball-moustache"></div> </figure> </div> <div class="col-4"> <pre> <code>@keyframes bounce {</code> <code> <mark>30% { transform: scale(1.1, 0.8); }</mark></code> <code> 50% { transform: translateY(-60px); }</code> <code> <mark>70% { transform: scale(1.1, 0.8); }</mark></code> <code>}</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- What are CSS animations? Bouncy ball with shadow --> <div class="row"> <div class="col-2"> <figure class="demo-ball demo-ball-shading" style="-webkit-animation: demo-bounce-2 1s infinite;"> <div class="demo-ball-eye"></div> <div class="demo-ball-eye-separator"></div> <div class="demo-ball-eye"></div> <div class="demo-ball-moustache"></div> </figure> <div class="demo-ball-shadow" style=" -webkit-animation: demo-shadow 1s infinite ease-in-out;"></div> </div> <div class="col-4"> <pre> <code>@keyframes shadow {</code> <code> <mark>30% { width: 90%; }</mark></code> <code> 50% { width: 75%; }</code> <code> <mark>70% { width: 90%; }</mark></code> <code>}</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- What are CSS animations? Bouncy ball with blinking --> <div class="row"> <div class="col-2"> <figure class="demo-ball demo-ball-shading" style="-webkit-animation: demo-bounce-2 1s infinite;"> <div class="demo-ball-eye" style="-webkit-animation: demo-blink 2.3s infinite;"></div> <div class="demo-ball-eye-separator"></div> <div class="demo-ball-eye" style="-webkit-animation: demo-blink 2.3s infinite;"></div> <div class="demo-ball-moustache"></div> </figure> <div class="demo-ball-shadow" style=" -webkit-animation: demo-shadow 1s infinite ease-in-out;"></div> </div> <div class="col-4"> <pre> <code>@keyframes blink {</code> <code> <mark>40% { height: 5px; }</mark></code> <code> 50% { height: 0px; }</code> <code> <mark>60% { width: 5px; }</mark></code> <code>}</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Unprefixing CSS animations --> <pre> <code><mark>@keyframes</mark> bounce {</code> <code> <mark class="comment">/* awesome animation code */ </mark></code> <code>}</code> </pre> <pre class="next"> <code><mark>@-webkit-keyframes</mark> bounce {</code> <code> <mark class="comment">/* same awesome animation code */ </mark></code> <code>}</code> </pre> </div></section> <section class="slide" style="text-align: center;"><div> <!-- Complaints --> <img src="pictures/complaint2.jpg" /> <img src="pictures/complaint1.jpg" /> <img src="pictures/complaint3.jpg" /> </div></section> <section class="slide"><div> <!-- Issues summary --> <div class="row"> <div class="col-6"><img src="pictures/blocked-on.png"/></div> </div> </div></section> <section class="slide" style="background: white url('pictures/dynamic-keyframes-issue.jpg') center no-repeat; background-size: contain;"><div> <!-- Dynamic keyframes: Issue --> </div></section> <section class="slide"><div> <!-- Dynamic keyframes: Example --> <div class="row"> <div class="col-2"> <div class="demo-square demo-spin-1"> </div> </div> <div class="col-4"> <pre> <code>@keyframes spin {</code> <code> 100% {</code> <code> transform: rotateZ(90deg);</code> <code> }</code> <code>}</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Dynamic keyframes: Modifying rule --> <div class="row"> <div class="col-2"> <div class="demo-square demo-spin-2"> </div> </div> <div class="col-4"> <pre> <code>@keyframes spin {</code> <code> 100% {</code> <code> transform: rotateZ(90deg);</code> <code> <mark>background: orange;</mark></code> <code> }</code> <code>}</code> </pre> <pre> <code>rules = document.cssRules[0];</code> <code><mark>rules[0].style.background = 'orange';</mark></code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Dynamic keyframes: Change key text --> <div class="row"> <div class="col-2"> <div class="demo-square demo-spin-3"> </div> </div> <div class="col-4"> <pre> <code>@keyframes spin {</code> <code> <mark>50%</mark> {</code> <code> transform: rotateZ(90deg);</code> <code> background: orange;</code> <code> }</code> <code>}</code> </pre> <pre> <code>rules = document.cssRules[0];</code> <code>rules[0].style.background = 'orange';</code> <code><mark>rules[0].keyText = '50%';</mark></code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Dynamic keyframes: Change timing --> <div class="row"> <div class="col-2"> <div class="demo-square demo-spin-4"> </div> </div> <div class="col-4"> <pre> <code>@keyframes spin {</code> <code> 50% {</code> <code> transform: rotateZ(90deg);</code> <code> background: orange;</code> <code> }</code> <code>}</code> </pre> <pre> <code>rules = document.cssRules[0];</code> <code>rules[0].style.background = 'orange';</code> <code>rules[0].keyText = '50%';</code> <code><mark>box.style.animationDuration = '3s';</mark></code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Animation engine: No update --> <div class="row"> <div class="col-3"> <h2>Style Recalc</h2> </div> <div class="col-3"> <h2>Update</h2> </div> </div> <div class="row"> <div class="col-3"> <ul> <li class="next">Calculate Update</li> <ul class="next"> <li>Is outdated?</li> <li>Update animation</li> </ul> </ul> </div> <div class="col-3 next"> <ul> <li>Apply Update</li> <ul> <li>Not used</li> </ul> </ul> </div> </div> </div></section> <section class="slide" style="background: black url('pictures/yuno.jpg') center no-repeat;"><div> <!-- Dynamic keyframes: No LGTM --> </div></section> <section class="slide"><div> <!-- Animation engine: No update --> <div class="row"> <div class="col-3"> <h2>Style Recalc</h2> </div> <div class="col-3"> <h2>Update</h2> </div> </div> <div class="row"> <div class="col-3"> <ul> <li>Calculate Update</li> <ul> <li>Is outdated?</li> <li class="strike">Update animation</li> </ul> </ul> </div> <div class="col-3"> <ul> <li>Apply Update</li> <ul> <li>Update animation with new keyframes</li> </ul> </ul> </div> </div> </div></section> <section class="slide"><div> <!-- Animation engine: No update --> <div class="row"> <div class="col-3"> <h2>Style Recalc</h2> </div> <div class="col-3"> <h2>Update</h2> </div> </div> <div class="row"> <div class="col-3"> <ul> <li>Calculate Update</li> <ul> <li>Is outdated?</li> <li class="next"><strong>Create temporary animation</strong></li> </ul> </ul> </div> <div class="col-3"> <ul> <li>Apply Update</li> <ul> <li>Update animation with new keyframes</li> <li class="next"><strong>Delete temporary animation</strong></li> </ul> </ul> </div> </div> </div></section> <section class="slide shout"><div> <!-- Demo --> <h2>Demo!</h2> </div></section> <section class="slide" style="background: white url('pictures/neutral-keyframes-issue.jpg') center no-repeat; background-size: contain;"><div> <!-- Dynamic keyframes: Issue --> </div></section> <section class="slide"><div> <!-- Neutral keyframes: Animating from base style --> <div class="row"> <div class="col-6"> <div class="demo-bar demo-pulse-1"> </div> </div> </div> <div class="row row-divider"> <div class="col-6"> <pre> <code>.bar { width: 50px; }</code> </pre> <pre> <code>@keyframes pulse {</code> <code> <mark>50% { width: 50%; }</mark></code> <code>}</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Neutral keyframes: Animating from 100% --> <div class="row"> <div class="col-6"> <div class="demo-bar demo-pulse-2"> </div> </div> </div> <div class="row row-divider"> <div class="col-6"> <pre> <code>.bar { width: 50px; }</code> </pre> <pre> <code>@keyframes pulse {</code> <code> 50% { width: 50%; }</code> <code>}</code> </pre> <pre> <code><mark>bar.style.width = '100%';</mark></code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Neutral keyframes: Capturing behaviour --> <div class="row"> <div class="col-6"> <div class="demo-bar demo-pulse-1"> </div> </div> </div> <div class="row row-divider"> <div class="col-6"> <pre> <code>@keyframes pulse {</code> <code> <mark class="comment">/* 0% { width: 50px; } */</mark></code> <code> 50% { width: 50%; }</code> <code> <mark class="comment">/* 100% { width: 50px; } */</mark></code> <code>}</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Neutral keyframes: Capturing behaviour --> <div class="row"> <div class="col-6"> <div class="demo-bar demo-pulse-2"> </div> </div> </div> <div class="row row-divider"> <div class="col-6"> <pre> <code>@keyframes pulse {</code> <code> <mark class="comment">/* 0% { width: 100%; } */</mark></code> <code> 50% { width: 50%; }</code> <code> <mark class="comment">/* 100% { width: 100%; } */</mark></code> <code>}</code> </pre> </div> </div> </div></section> <section class="slide"><div> <!-- Conclusion --> <h2>Conclusion</h2> <ul> <li>CSS animations add personality to the web.</li> <li>Ready to use unprefixed animations by default in Chrome.</li> <li>Developers will be much happier.</li> </ul> </div></section> <script src="shower/shower.min.js"></script> <!-- Copyright © 2014 Yours Truly, Famous Inc. --> <!-- Photos by John Carey, fiftyfootshadows.net --> </body> </html>
<?php declare(strict_types=1); namespace Webuntis\Tests\Models; use PHPUnit\Framework\TestCase; use Webuntis\Models\Classes; /** * ClassesTest * @author Tobias Franek <tobias.franek@gmail.com> * @license MIT */ final class ClassesTest extends TestCase { public function testCreate() : void { $data = [ 'id' => 1, 'name' => 'test', 'longName' => 'teststring' ]; $classes = new Classes($data); $this->assertEquals($classes->getAttributes(), $data); $this->assertEquals(1, $classes->getId()); $this->assertEquals('test', $classes->getName()); $this->assertEquals('teststring', $classes->getFullName()); $data['fullName'] = 'teststring'; unset($data['longName']); $this->assertEquals($data, $classes->serialize()); $this->assertEquals(json_encode($data), $classes->serialize('json')); } }
### 定义 - 资源是整数 - 可以自动销毁
(function(ns) { /** * JSON CORS utility * Wraps up all the cors stuff into a simple post or get. Falls back to jsonp */ var JSONCORS = function() { var self = this; var supportsCORS = ('withCredentials' in new XMLHttpRequest()) || (typeof XDomainRequest != 'undefined'); /********************************************************************************/ // Utils /********************************************************************************/ /** * Serializes a dictionary into a url query * @param m: the map to serialize * @return the url query (no preceeding ?) */ var serializeURLQuery = function(m) { var args = []; for (var k in m) { args.push(encodeURIComponent(k) + '=' + encodeURIComponent(m[k])) } return args.join('&'); }; /********************************************************************************/ // CORS /********************************************************************************/ /** * Performs a CORS request which wraps the response through our marshalled API * @param url: the url to visit * @param method: GET|POST the http method * @param payload: the payload to send (undefined for GET) * @param success: executed on success. Given response then http status then xhr * @param failure: executed on failure. Given http status then error then xhr * @return the XHR object */ self.requestCORS = function(url, method, payload, success, failure) { method = method.toUpperCase(); var xhr; if (typeof XDomainRequest != 'undefined') { xhr = new XDomainRequest(); xhr.open(method, url); } else { xhr = new XMLHttpRequest(); xhr.open(method, url, true); } xhr.onload = function() { var json; try { json = JSON.parse(xhr.responseText); } catch(e) { /* noop */ } var status = (json && json.http_status !== undefined) ? json.http_status : xhr.status; if (status >= 200 && status <= 299) { success(json, status, xhr); } else { failure(xhr.status, json ? json.error : undefined, xhr); } }; xhr.onerror = function() { failure(xhr.status, undefined, xhr); }; if (method === 'POST') { xhr.setRequestHeader("Content-type","application/json"); xhr.send(JSON.stringify(payload)); } else { xhr.send(); } return xhr; }; /********************************************************************************/ // JSONP /********************************************************************************/ /** * Performs a JSONP request which wraps the response through our marshalled API * @param url: the url to visit * @param method: GET|POST the http method * @param payload: the payload to send (undefined for GET) * @param success: executed on success. Given response then http status then xhr * @param failure: executed on failure. Given http status then error then xhr * @return the XHR object */ self.requestJSONP = function(url, method, payload, success, failure) { method = method.toUpperCase(); var jsonp = document.createElement('script'); jsonp.type = 'text/javascript'; // Success callback var id = '__jsonp_' + Math.ceil(Math.random() * 10000); var dxhr = { jsonp:true, id:id, response:undefined }; window[id] = function(r) { jsonp.parentElement.removeChild(jsonp); delete window[id]; dxhr.response = r; if (r === undefined || r === null) { success(undefined, 200, dxhr); } else { if (r.http_status >= 200 && r.http_status <= 299) { success(r, r.http_status, dxhr); } else { failure(r.http_status, r.error, dxhr); } } }; // Error callback jsonp.onerror = function() { jsonp.parentElement.removeChild(jsonp); dxhr.jsonp_transport_error = 'ScriptErrorFailure'; failure(0, undefined, dxhr); }; var urlQuery; if (method === 'POST') { urlQuery = '?' + serializeURLQuery(payload) + '&callback=' + id + '&_=' + new Date().getTime(); } else { urlQuery = '?' + 'callback=' + id + '&_=' + new Date().getTime(); } jsonp.src = url + urlQuery; document.head.appendChild(jsonp); return dxhr; }; /********************************************************************************/ // GET /********************************************************************************/ /** * Makes a get request * @param url=/: the url to post to * @param success=undefined: executed on http success with the response * @param failure=undefined: executed on http failure * @param complete=undefined: executed after http success or failure * Returns either the xhr request or a jsonp holding object */ self.get = function(options) { var method = supportsCORS ? 'requestCORS' : 'requestJSONP'; return self[method](options.url || window.location.href, 'GET', undefined, function(response, status, xhr) { if (options.success) { options.success(response, status, xhr); } if (options.complete) { options.complete(); } }, function(status, error, xhr) { if (options.failure) { options.failure(status, error, xhr); } if (options.complete) { options.complete(); } }); }; /********************************************************************************/ // POST /********************************************************************************/ /** * Makes a post request * @param url=/: the url to post to * @param payload={}: the payload to send * @param success=undefined: executed on http success with the response * @param failure=undefined: executed on http failure * @param complete=undefined: executed after http success or failure * Returns either the xhr request or a jsonp holding object */ self.post = function(options) { var method = supportsCORS ? 'requestCORS' : 'requestJSONP'; return self[method](options.url || window.location.href, 'POST', options.payload || {}, function(response, status, xhr) { if (options.success) { options.success(response, status, xhr); } if (options.complete) { options.complete(); } }, function(status, error, xhr) { if (options.failure) { options.failure(status, error, xhr); } if (options.complete) { options.complete(); } }); }; return self; }; ns.stacktodo = ns.stacktodo || {}; ns.stacktodo.core = ns.stacktodo.core || {}; ns.stacktodo.core.jsoncors = new JSONCORS(); })(window);
package fr.inria.jessy.transaction.termination.vote; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import fr.inria.jessy.ConstantPool; /** * * @author Masoud Saeida Ardekani * */ public class VotePiggyback implements Externalizable { private static final long serialVersionUID = -ConstantPool.JESSY_MID; Object piggyback; public VotePiggyback() { } public VotePiggyback(Object piggyback) { this.piggyback = piggyback; } public Object getPiggyback() { return piggyback; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { piggyback = in.readObject(); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(piggyback); } }
{ //using constants const a = 2; console.log( a ); // 2 a = 3; // TypeError! } { //an array constant const a = [1,2,3]; a.push( 4 ); console.log( a ); // [1,2,3,4] a = 42; // TypeError! } //we can change the object using its methods, we just cannot reassign it...
import {ProviderSpecification} from 'dxref-core/system/provider/provider-specification'; import { module, test } from 'qunit'; module('Unit | dxref-core | system | provider | provider-specification'); test('provider-specification', function(assert) { var myFunc = function() {}; var providerSpec = new ProviderSpecification(['VALUE$Date', 'A', 'B', 'C', myFunc]); assert.deepEqual(providerSpec.getDependencies(), ['A', 'B', 'C']); assert.strictEqual(providerSpec.getFunctionArg(), myFunc); assert.equal(providerSpec.getOutputType(), 'VALUE$Date'); }); /** Validation of non-provider-specification conformance is tested in the bootstrap-validators-test.js */
version https://git-lfs.github.com/spec/v1 oid sha256:c1d57d1ad50c4639ecd398deb6c1db998e272cc6faf1314dec77ca509ca49153 size 1303
require "active_support/core_ext/date/calculations" require "active_support/core_ext/numeric/time" require "active_support/core_ext/object/try" require "google/api_client" require "google/api_client/client_secrets" require "ruboty" require "time" module Ruboty module Handlers class GoogleCalendar < Base DEFAULT_CALENDAR_ID = "primary" DEFAULT_DURATION = 1.day env :GOOGLE_CALENDAR_ID, "Google Calendar ID (default: primary)", optional: true env :GOOGLE_CLIENT_ID, "Client ID" env :GOOGLE_CLIENT_SECRET, "Client Secret" env :GOOGLE_REDIRECT_URI, "Redirect URI (http://localhost in most cases)" env :GOOGLE_REFRESH_TOKEN, "Refresh token issued with access token" on( /list events( in (?<minute>\d+) minutes)?\z/, description: "List events from Google Calendar", name: "list_events", ) def list_events(message) event_items = client.list_events( calendar_id: calendar_id, duration: message[:minute].try(:to_i).try(:minute) || DEFAULT_DURATION, ).items if event_items.size > 0 text = event_items.map do |item| ItemView.new(item) end.join("\n") message.reply(text, code: true) else true end end private def calendar_id ENV["GOOGLE_CALENDAR_ID"] || DEFAULT_CALENDAR_ID end def client @client ||= Client.new( client_id: ENV["GOOGLE_CLIENT_ID"], client_secret: ENV["GOOGLE_CLIENT_SECRET"], redirect_uri: ENV["GOOGLE_REDIRECT_URI"], refresh_token: ENV["GOOGLE_REFRESH_TOKEN"], ) end class Client APPLICATION_NAME = "ruboty-google_calendar" AUTH_URI = "https://accounts.google.com/o/oauth2/auth" SCOPE = "https://www.googleapis.com/auth/calendar" TOKEN_URI = "https://accounts.google.com/o/oauth2/token" def initialize(client_id: nil, client_secret: nil, redirect_uri: nil, refresh_token: nil) @client_id = client_id @client_secret = client_secret @redirect_uri = redirect_uri @refresh_token = refresh_token authenticate! end # @param [String] calendar_id # @param [ActiveSupport::Duration] duration def list_events(calendar_id: nil, duration: nil) api_client.execute( api_method: calendar.events.list, parameters: { calendarId: calendar_id, singleEvents: true, orderBy: "startTime", timeMin: Time.now.iso8601, timeMax: duration.since.iso8601 } ).data end private def api_client @api_client ||= begin _api_client = Google::APIClient.new( application_name: APPLICATION_NAME, application_version: Ruboty::GoogleCalendar::VERSION, ) _api_client.authorization = authorization _api_client.authorization.scope = SCOPE _api_client end end def authenticate! api_client.authorization.fetch_access_token! end def authorization client_secrets.to_authorization end def client_secrets Google::APIClient::ClientSecrets.new( flow: :installed, installed: { auth_uri: AUTH_URI, client_id: @client_id, client_secret: @client_secret, redirect_uris: [@redirect_uri], refresh_token: @refresh_token, token_uri: TOKEN_URI, }, ) end def calendar @calendar ||= api_client.discovered_api("calendar", "v3") end end class ItemView def initialize(item) @item = item end def to_s "#{started_at} - #{finished_at} #{summary}" end private def all_day? @item.start.date_time.nil? end def finished_at case when all_day? "--:--" when finished_in_same_day? @item.end.date_time.localtime.strftime("%H:%M") else @item.end.date_time.localtime.strftime("%Y-%m-%d %H:%M") end end def finished_in_same_day? @item.start.date_time.localtime.day == @item.end.date_time.localtime.day end def started_at if all_day? "#{@item.start.date} --:--" else @item.start.date_time.localtime.strftime("%Y-%m-%d %H:%M") end end def summary @item.summary end end end end end
package controller; import java.text.DecimalFormat; import util.Teclado; public class Ex_5 { public static void main(String[] args){ double salario; salario = Teclado.lerDouble("Digite o salário desejado: "); DecimalFormat df = new DecimalFormat("R$ ###, ###, ###.00"); System.out.println(df.format(salario)); } }
team1 = {"name" : "Iron Patriot", "key": "MURICA", "puzzles" : [{"idPz": 0}, // Breakfast {"idPz": 1}, // Blueprints, all {"idPz": 2}, // Morning Rotation # 1 // {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly) {"idPz": 3}, // Morning Rotation # 2 // {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly) {"idPz": 4}, // Morning Rotation # 3 // {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly) {"idPz": 5}, // Morning Rotation # 4 // {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly) {"idPz": 6}, // All together now. {"idPz": 7}, // Lunch Time {"idPz": 8}, // Evening Rotation # 1 {"idPz": 9}, // Evening Rotation # 2 {"idPz": 10}, // Evening Rotation # 3 {"idPz": 11}, // Evening Rotation # 4 {"idPz": 12}, // All together now (Blueprints) {"idPz": 13}, // All together now (Final) ], "wordweb":[], "jarvisStream" : {}, "wordwebUnknown":[0], "currentPuzzle" : 0, "teamNum" : 1, "eveningBufferIndex" : 0 } team2 = {"name" : "War Machine", "key": "WARMACHINEROX", "puzzles" : [{"idPz": 0}, // Breakfast {"idPz": 1}, // Blueprints, all {"idPz": 3}, // Morning Rotation # 2 // {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly) {"idPz": 4}, // Morning Rotation # 3 // {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly) {"idPz": 5}, // Morning Rotation # 4 // {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly) {"idPz": 2}, // Morning Rotation # 1 // {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly) {"idPz": 6}, // All together now. {"idPz": 7}, // Lunch Time {"idPz": 9}, // Evening Rotation # 2 {"idPz": 10}, // Evening Rotation # 3 {"idPz": 11}, // Evening Rotation # 4 {"idPz": 8}, // Evening Rotation # 1 {"idPz": 12}, // All together now (Blueprints) {"idPz": 13}, // All together now (Final) ], "wordweb":[], "jarvisStream" : {}, "wordwebUnknown":[0], "currentPuzzle" : 0, "teamNum" : 2, "eveningBufferIndex" : 0 } team3 = {"name" : "Hulkbuster", "key": "IRONSMASH", "puzzles" : [{"idPz": 0}, // Breakfast {"idPz": 1}, // Blueprints, all {"idPz": 4}, // Morning Rotation # 3 // {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly) {"idPz": 5}, // Morning Rotation # 4 // {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly) {"idPz": 2}, // Morning Rotation # 1 // {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly) {"idPz": 3}, // Morning Rotation # 2 // {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly) {"idPz": 6}, // All together now. {"idPz": 7}, // Lunch Time {"idPz": 10}, // Evening Rotation # 3 {"idPz": 11}, // Evening Rotation # 4 {"idPz": 8}, // Evening Rotation # 1 {"idPz": 9}, // Evening Rotation # 2 {"idPz": 12}, // All together now (Blueprints) {"idPz": 13}, // All together now (Final) ], "wordweb":[], "jarvisStream" : {}, "wordwebUnknown":[0], "currentPuzzle" : 0, "teamNum" : 3, "eveningBufferIndex" : 0 } team4 = {"name" : "Mark I", "key": "OLDSKOOL", "puzzles" : [{"idPz": 0}, // Breakfast {"idPz": 1}, // Blueprints, all {"idPz": 5}, // Morning Rotation # 4 // {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly) {"idPz": 2}, // Morning Rotation # 1 // {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly) {"idPz": 3}, // Morning Rotation # 2 // {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly) {"idPz": 4}, // Morning Rotation # 3 // {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly) {"idPz": 6}, // All together now. {"idPz": 7}, // Lunch Time {"idPz": 11}, // Evening Rotation # 4 {"idPz": 8}, // Evening Rotation # 1 {"idPz": 9}, // Evening Rotation # 2 {"idPz": 10}, // Evening Rotation # 3 {"idPz": 12}, // All together now (Blueprints) {"idPz": 13}, // All together now (Final) ], "wordweb":[], "jarvisStream" : {}, "wordwebUnknown":[0], "currentPuzzle" : 0, "teamNum" : 4, "eveningBufferIndex" : 0 } allPuzzles = [{"name": "Breakfast", //0 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, // "showInput": false, "endCondition" : {"websocket": "breakfastOver"}, // "puzzIntro": {"name": "<a href='www.skeenan.com'>Something to help, take it with you.</a>", // ".mp3": null, // "action": null}, "hint": [{"name": "Welcome to breakfast, relax, eat some.", ".mp3": null, "trig": {'time': 10}, "action": null}] }, {"name": "Blueprints", //1 "desc": "Our first Puzzle!", "file": "./puzzles/puzzle1", "estTime": 40, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "wrong": "Did you really think that was the right answer?", "menace": true, "insect": true, "pluto": true, "cable": true }, "puzzIntro": {"name": "Go pick up physics quizzes", ".mp3": null, "action": null}, "hint": [{"name": "This puzzle isn't about QR codes", // ".mp3": "./audio/puzzle1/hint1", "trig": {'time': 60*10}, "text": "I can't see what you're doing from here, but have you tried to stack them?", "action": null}, {"name": "Look for letters", // ".mp3": "./audio/puzzle1/hint1", "trig": {'time': 60*15}, "text": "I can't see what you're doing from here, but have you tried to stack them?", "action": null}, {"name": "You can use an anagram solver if you want", // ".mp3": "./audio/puzzle1/hint1", "trig": {'time': 60*20}, "text": "I can't see what you're doing from here, but have you tried to stack them?", "action": null}] }, {"name": "The Grid", //2 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "wolverine": true}, "puzzIntro": {"name": "We need you at the Admissions conference room", ".mp3": null, "action": null}, "hint": [{"name": "It's a Sudoku", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*20}, "action": null}, {"name": "Oh look, semaphore!", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*25}, "action": null}, {"name": "You should probably look at it from the side the flags are on", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*30}, "action": null}] }, {"name": "The Arc", //3 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "Colston": true}, "puzzIntro": {"name": "Eat", ".mp3": null, "action": null}, "hint": [] }, {"name": "Lasers", //4 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "nefaria": true}, "puzzIntro": {"name": "Spalding sub-basement", ".mp3": null, "action": null}, "hint": [{"name": "If you give me power, I can give you information", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*15}, "action": null}, {"name": "The dates are important", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*15}, "action": null}, {"name": "Have you tried putting them in order?", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*20}, "action": null}, {"name": "More information about the songs is better (feel free to use Google)", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time': 60*25}, "action": null}] }, {"name": "Rebus", //5 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "isStatPuzzle": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "Harold Hogan": true}, "puzzIntro": {"name": "Lloyd Deck", ".mp3": null, "action": null}, "hint": [{"name": "The number of the puzzle will prove of use", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time':60*10}, "action": null}, {"name": "index puzzle answer by puzzle number", // ".mp3": "./audio/puzzle2/hint1", "trig": {'time':60*15}, "action": null}] }, {"name": "Squares", //6 - Last before lunch "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "overlap": true, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "allSolveTogether": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "jhammer": true}, "puzzIntro": {"name": "Everyone meet at the BBB front patio", ".mp3": null, "action": null}, "hint": [] }, {"name": "Lunch", //7 - Lunch "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "showInput": false, "endCondition" : {"websocket": "lunchOver"}, // "responses": {"": "You could try to give me something, anything before you press enter you know.", // "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "Teamwork", //8 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "endCondition" : {"websocket": "nextAfternoonPuzzle"}, "isAfternoon" : true, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "stop hammer time!": true }, "puzzIntro": {"name": "We need you at CDC 257", ".mp3": null, "action": null}, "hint": [] }, {"name": "Laserz", //9 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "endCondition" : {"websocket": "nextAfternoonPuzzle"}, "isAfternoon" : true, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, "puzzIntro": {"name": "Moore (070 - 2)", ".mp3": null, "action": null}, "hint": [] }, {"name": "The Game", //10 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "endCondition" : {"websocket": "nextAfternoonPuzzle"}, "isAfternoon" : true, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "YAYYYYYYYYYyYYYyY": true}, "puzzIntro": {"name": "A projector room close to home", ".mp3": null, "action": null}, "hint": [] }, {"name": "The Web", //11 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "endCondition" : {"websocket": "nextAfternoonPuzzle"}, "overlap": true, "isAfternoon" : true, "overlap": true, "isWordWeb": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, "puzzIntro": {"name": "", ".mp3": null, "action": null}, "hint": [] }, {"name": "Take two on Blueprints", //12 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "allSolveTogether": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "This is it", //13 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": false}, //Can't have a "correct answer" for the last puzzle, or else crash // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "The Mask", //14 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "The Glove", //15 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "The Core", //16 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] }, {"name": "The Repulsor", //17 "desc": "Our second Puzzle!", "file": "./puzzles/puzzle2", "estTime": 60, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}, // "puzzIntro": {"name": "Eat", // ".mp3": null, // "action": null}, "hint": [] } ] morningBuffers = [{"name": "First Square", //0 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "dues": true, "birth": true, "oracle": true, "yolk": true }, "puzzIntro": {"name": "<a href='squares/1987.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Second Square", //1 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "unix": true, "choose": true, "him": true, "graft": true }, "puzzIntro": {"name": "<a href='squares/2631.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Another Square", //2 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "seer": true, "kraft": true, "eunuchs": true }, "puzzIntro": {"name": "<a href='squares/3237.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "The fourth", //3 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "paced": true, "idle": true, "paws": true, "tea": true }, "puzzIntro": {"name": "<a href='squares/4126.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Num Five.", //4 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "bode": true, "idyll": true, "grease": true, "laze": true }, "puzzIntro": {"name": "<a href='squares/5346.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Square six start", //5 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "lies": true, "ax": true, "tax": true, "bask": true }, "puzzIntro": {"name": "<a href='squares/6987.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Square 7 begin", //6 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "ail": true, "tacks": true, "yolk": true }, "puzzIntro": {"name": "<a href='squares/7123.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Eight Squares In", //7 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "cedar": true, "chorale": true, "marquis": true }, "puzzIntro": {"name": "<a href='squares/8873.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Nine lives, nine squares", //8 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "corral": true, "bruise": true, "sics": true, "pair": true }, "puzzIntro": {"name": "<a href='squares/9314.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Ten Four", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "oohs": true, "six": true, "quire": true, "stayed": true }, "puzzIntro": {"name": "<a href='squares/10242.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Square 11", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "want": true, "few": true, "avricle": true }, "puzzIntro": {"name": "<a href='squares/11235.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "A Dozen!", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "pride": true, "staid": true, "paste": true, "woe": true }, "puzzIntro": {"name": "<a href='squares/12198.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Lucky 13", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "reads": true, "place": true, "whoa": true, "bowed": true }, "puzzIntro": {"name": "<a href='squares/13124.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "14 it is", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "profit": true, "yule": true, "basque": true, "plaice": true }, "puzzIntro": {"name": "<a href='squares/14092.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "You're at 15!", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "lichen": true, "you'll": true, "ale": true }, "puzzIntro": {"name": "<a href='squares/15098.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Sweet 16", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "feeder": true, "cere": true, "sorted": true }, "puzzIntro": {"name": "<a href='squares/16981.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Boring 17", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "pare": true, "none": true, "chews": true, "sordid": true }, "puzzIntro": {"name": "<a href='squares/17092.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "Old enough to go to War(machine)", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "nun": true, "cache": true, "ooze": true, "wave": true }, "puzzIntro": {"name": "<a href='squares/18923.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "19", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "coin": true, "maid": true, "pryed": true, "waive": true }, "puzzIntro": {"name": "<a href='squares/19238.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "20", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "plait": true, "made": true, "reeds": true, "lynx": true }, "puzzIntro": {"name": "<a href='squares/20.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "21", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "links": true, "prophet": true, "floes": true, "rain": true }, "puzzIntro": {"name": "<a href='squares/21.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "22", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "root": true, "reign": true, "liken": true }, "puzzIntro": {"name": "<a href='squares/22.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "23", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "phew": true, "crewel": true, "tapir": true }, "puzzIntro": {"name": "<a href='squares/23.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "24", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "taper": true, "allowed": true }, "puzzIntro": {"name": "<a href='squares/24.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }, {"name": "25", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "cents": true, "ewe": true }, "puzzIntro": {"name": "<a href='squares/25.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "26", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "jewel": true, "whore": true, "sense": true }, "puzzIntro": {"name": "<a href='squares/26.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "27", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "cyclet": true, "liar": true, "joule": true }, "puzzIntro": {"name": "<a href='squares/27.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "28", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "mood": true, "pause": true, "islet": true }, "puzzIntro": {"name": "<a href='squares/28.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "29", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "epoch": true, "phlox": true, "want": true }, "puzzIntro": {"name": "<a href='squares/29.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "30", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "mooed": true, "Greece": true, "word": true }, "puzzIntro": {"name": "<a href='squares/30.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "31", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "acts": true, "whirred": true, "palate": true }, "puzzIntro": {"name": "<a href='squares/31.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "32", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "maize": true, "pallette": true }, "puzzIntro": {"name": "<a href='squares/32.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "33", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "you": true, "sine": true, "marqaee": true }, "puzzIntro": {"name": "<a href='squares/33.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "34", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "brews": true, "massed": true, "hoar": true, "sign": true }, "puzzIntro": {"name": "<a href='squares/34.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "35", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "potpourri": true, "doe": true, "epic": true }, "puzzIntro": {"name": "<a href='squares/35.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "36", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "rabbit": true, "rose": true, "popery": true }, "puzzIntro": {"name": "<a href='squares/36.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] },{"name": "37", //9 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "responses": {"": "You could try to give me something, anything before you press enter you know.", "rabbet": true, "illicit": true }, "puzzIntro": {"name": "<a href='squares/37.jpg'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] } ] eveningBuffers = [{"name": "To Find", //0 "desc": "Keep you computers open to await instruction.", "file": "./puzzles/puzzle1", "estTime": 30, "answerResponse": {"name": "", ".mp3": null}, "isActive": false, "overlap": true, "showInput": false, "endCondition" : {"websocket": "breakfastOver"}, "puzzIntro": {"name": "<a href='www.skeenan.com'>Something to help, take it with you.</a>", ".mp3": null, "action": null}, "hint": [] }] morningBufferIndex = 0 stats = {} adminSockets = {sockets: []}; teams = [team1, team2, team3, team4]; function initTeams() { for (var team in teams) { teams[team].aboutToStart = 0; teams[team].sockets = []; for (var aPuzzle in teams[team].puzzles) { aPuzzle = teams[team].puzzles[aPuzzle]; aPuzzle.puzzle = allPuzzles[aPuzzle.idPz]; aPuzzle.startTime = null; aPuzzle.elapsed = null; aPuzzle.hints = []; } startPuzzle(teams[team]) } } function reloadAllPuzzles(){ for (var team in teams) { for (var aPuzzle in teams[team].puzzles) { aPuzzle = teams[team].puzzles[aPuzzle]; aPuzzle.puzzle = allPuzzles[aPuzzle.idPz]; } } } function startPuzzle(team) { //Init Jarvis stream team.jarvisStream[team.currentPuzzle] = {"name": team.puzzles[team.currentPuzzle].puzzle.name, "desc": team.puzzles[team.currentPuzzle].puzzle.desc, "data": []} var nextIntro = team.puzzles[team.currentPuzzle].puzzle.puzzIntro if (team.puzzles[team.currentPuzzle].puzzIntro){ nextIntro = team.puzzles[team.currentPuzzle].puzzIntro } if (nextIntro){ newJarvisMessageOut(team, nextIntro) } if (team.puzzles[team.currentPuzzle].puzzle.name === "Squares"){ for (var i = morningBufferIndex; i < morningBuffers.length; i++) { newJarvisMessageOut(team, morningBuffers[i].puzzIntro) }; } if (team.puzzles[team.currentPuzzle].puzzle.name === "Lunch"){ morningBufferIndex = morningBuffers.length } startPuzzleTimer(team) } function resaveAllTeams(){ //Save all the teams } function logNewStat(team, statName, value, isIncrement){ // if (!stats[statName]){ // stats[statName] = {1: 0, 2: 0, 3: 0, 4: 0} // } // if (isIncrement){ // stats[statName][team.teamNum] += value // } else { // stats[statName][team.teamNum] = value // } // updateAllCompetitionData() } function logStatsOnTime(team){ if (team.puzzles[team.currentPuzzle].puzzle.isStatPuzzle){ logNewStat(team, team.puzzles[team.currentPuzzle].puzzle.name + " time", Math.floor(team.puzzles[team.currentPuzzle].elapsed/60), false) } } function startNextPuzzle(team){ logStatsOnTime(team) team.puzzles[team.currentPuzzle].puzzle.isActive = false if (team.currentPuzzle === -1) { team.currentPuzzle = team.lastPuzzleIndex } if (team.puzzles[team.currentPuzzle + 1].puzzle.overlap || !team.puzzles[team.currentPuzzle + 1].puzzle.isActive) { if (team.puzzles[team.currentPuzzle].puzzle.isWordWeb){ emitToAllTeams(team, "bootOffWeb", true) } team.currentPuzzle ++ team.puzzles[team.currentPuzzle].puzzle.isActive = true } else { team.lastPuzzleIndex = team.currentPuzzle team.currentPuzzle = -1 team.puzzles[-1] = {} team.puzzles[-1].puzzle = getNextBuffer(team) } startPuzzle(team) } function getNextBuffer(team){ if (morningBufferIndex < morningBuffers.length){ logNewStat(team, "Pieces Found", 1, true) output = morningBuffers[morningBufferIndex] morningBufferIndex ++ return output } else { // I'm just going to assume that we're in the afternoon // if (team.eveningBufferIndex < eveningBuffers.length){ // output = eveningBuffers[team.eveningBufferIndex] // team.eveningBufferIndex ++ // return output // } else { return {"name": "Error finding next puzzle. Let's say SEGFAULT", "responses": {"": "You could try to give me something, anything before you press enter you know.", "answer": true}} // } } } function startPuzzleTimer(team){ if (team.timer == null){ team.puzzles[team.currentPuzzle].elapsed = 0; team.timer = function(){ if (typeof this.puzzles[this.currentPuzzle].elapsed === 'undefined'){ return; } this.puzzles[this.currentPuzzle].elapsed ++; emitToAllTeams(this, 'tick', {'elapsed' : this.puzzles[this.currentPuzzle].elapsed}) checkPuzzTimerHints(this); } var myVar=setInterval(function(){team.timer()},1000); } team.puzzles[team.currentPuzzle].start } function checkPuzzTimerHints(team){ var outHint = null; var puzzHints = allPuzzles[team.currentPuzzle].hint; // var outHintIndex = 0; var isUpdated = false; for (var hint in puzzHints){ if (puzzHints[hint].trig.time != null && puzzHints[hint].trig.time == team.puzzles[team.currentPuzzle].elapsed) { outHint = puzzHints[hint]; isUpdated = true; // isUpdated = (isUpdated || (hint != oldHints[outHintIndex])); // outHintIndex ++; } } if (isUpdated){ newJarvisMessageOut(team, outHint) } } function sendAllPuzzleData(team){ //TODO: Send all relevant puzzle data, how do we make sure client only // renders the most recent hint? var puzzleOut = constructAllPuzzleData(team); emitToAllTeams(team, 'jarvisUpdate', puzzleOut) emitToAllTeams(adminSockets, 'jarvisUpdate', puzzleOut) } function constructAllPuzzleData(team){ out = {}; out.name = team.name out.currentPuzzle = team.currentPuzzle out.currentPuzzleName = team.puzzles[team.currentPuzzle].puzzle.name out.jarvisStream = team.jarvisStream out.teamNum = team.teamNum out.showInput = team.puzzles[team.currentPuzzle].puzzle.showInput out.stats = stats return out } function updateAllCompetitionData(){ try{ var puzzleOut = {} for (team in teams){ team = teams[team] puzzleOut = constructAllPuzzleData(team); emitToAllTeams(team, 'compUpdate', puzzleOut) } emitToAllTeams(adminSockets, 'jarvisUpdate', puzzleOut) } catch (err) { console.log(err) } } function newJarvisMessageOut(team, message){ team.jarvisStream[team.currentPuzzle].data.push(message); // TODO: Persist! sendAllPuzzleData(team); emitToAllTeams(team, 'jarvisMessage', message) } if (teams[0].sockets == null) { initTeams() } reloadAllPuzzles(); module.exports.teams = teams; module.exports.allPuzzles = allPuzzles; module.exports.reloadAllPuzzles = reloadAllPuzzles; module.exports.resaveAllTeams = resaveAllTeams; module.exports.startPuzzle = startPuzzle; module.exports.startNextPuzzle = startNextPuzzle; module.exports.sendAllPuzzleData = sendAllPuzzleData; module.exports.emitToAllTeams = emitToAllTeams; module.exports.constructAllPuzzleData = constructAllPuzzleData; module.exports.adminSockets = adminSockets; module.exports.newJarvisMessageOut = newJarvisMessageOut; module.exports.stats = stats; module.exports.logNewStat = logNewStat;
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; // Return average network hashes per second based on the last 'lookup' blocks, // or from the last difficulty change if 'lookup' is nonpositive. // If 'height' is nonnegative, compute the estimate at the time when a given block was found. Value GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = pindexBest; if (height >= 0 && height < nBestHeight) pb = FindBlockByHeight(height); if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; double sum = 0.0; for (int i = 0; i < lookup; i++) { sum += (pb->GetBlockTime() - pb->pprev->GetBlockTime()) / GetDifficulty(pb); pb = pb->pprev; } return (boost::int64_t)(pow(2.0, 32) / (sum / lookup)); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getnetworkhashps [blocks] [height]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Colossus is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Colossus is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlock(reservekey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Colossus is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Colossus is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlock(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Colossus is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Colossus is downloading blocks..."); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } pblocktemplate = CreateNewBlock(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int index_in_template = i - 1; entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template])); entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template])); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); if (!fAccepted) return "rejected"; // TODO: report validation state return Value::null; }
package com.asksunny.rpc.admin; import java.util.concurrent.ExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.asksunny.protocol.rpc.RPCAdminCommand; import com.asksunny.protocol.rpc.RPCAdminEnvelope; import com.asksunny.protocol.rpc.RPCEnvelope; import com.asksunny.rpc.mtserver.RPCRuntime; public class AdminRPCRuntime implements RPCRuntime{ ExecutorService executorService; final static Logger log = LoggerFactory.getLogger(AdminRPCRuntime.class); public ExecutorService getExecutorService() { return executorService; } public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } public RPCEnvelope invoke(RPCEnvelope request) throws Exception { RPCAdminEnvelope adminRequest = (RPCAdminEnvelope)request; RPCAdminEnvelope response = new RPCAdminEnvelope(); response.setRpcType(RPCEnvelope.RPC_TYPE_RESPONSE); RPCAdminCommand cmd = RPCAdminCommand.valueOf(adminRequest.getAdminCommand()); if(cmd == RPCAdminCommand.PING ){ response.setAdminCommand(RPCAdminCommand.PING); response.addRpcObjects(System.currentTimeMillis()); }else if(cmd == RPCAdminCommand.ECHO ){ response.setAdminCommand(RPCAdminCommand.ECHO); response.setRpcObjects(request.getRpcObjects()); }else if(cmd == RPCAdminCommand.UPTIME ){ response.setAdminCommand(RPCAdminCommand.UPTIME); response.addRpcObjects(System.currentTimeMillis()); }else if(cmd == RPCAdminCommand.STATUS ){ response.setAdminCommand(RPCAdminCommand.STATUS); response.addRpcObjects(System.currentTimeMillis()); }else if(cmd == RPCAdminCommand.HEARTBEAT ){ response.setAdminCommand(RPCAdminCommand.HEARTBEAT); response.addRpcObjects(System.currentTimeMillis()); }else if(cmd == RPCAdminCommand.SHUTDOWN ){ System.exit(0); } return response; } public boolean accept(RPCEnvelope envelope) throws Exception { return envelope.getRpcType()==RPCEnvelope.RPC_ENVELOPE_TYPE_ADMIN; } }
import DBService, { BuilderSingle } from '../DBService' import Approval from '../../../models/extprod/Approval' import { Map } from '../../../utils/map' import { UndefinedError } from '../../../models/Error' interface FindAllOptions { userId?: string } export default class ApprovalService extends DBService<Approval> { constructor() { super(Approval) } public findAll = async (options?: FindAllOptions) => { let query = this.Model.query().eager( '[user, itemPrototype.[itemBase], itemRequest.[itemBase], itemService.[itemBase]]' ) if (options && options.userId) { query = query.where('userId', options.userId) } const approvals = await query if (!approvals) { throw new UndefinedError() } return approvals } }
<?php /* |-------------------------------------------------------------------------- | Oculus XMS |-------------------------------------------------------------------------- | | This file is part of the Oculus XMS Framework package. | | (c) Vince Kronlein <vince@ocx.io> | | For the full copyright and license information, please view the LICENSE | file that was distributed with this source code. | */ namespace Admin\Model\Sale; use Oculus\Engine\Model; use Oculus\Library\Language; class Order extends Model { public function addOrder($data) { $this->theme->model('setting/store'); $store_info = $this->model_setting_store->getStore($data['store_id']); if ($store_info) { $store_name = $store_info['name']; $store_url = $store_info['url']; } else { $store_name = $this->config->get('config_name'); $store_url = $this->app['http.public']; } $this->theme->model('setting/setting'); $setting_info = $this->model_setting_setting->getSetting('setting', $data['store_id']); if (isset($setting_info['invoice_prefix'])) { $invoice_prefix = $setting_info['invoice_prefix']; } else { $invoice_prefix = $this->config->get('config_invoice_prefix'); } $this->theme->model('localization/country'); $this->theme->model('localization/zone'); $country_info = $this->model_localization_country->getCountry($data['shipping_country_id']); if ($country_info) { $shipping_country = $country_info['name']; $shipping_address_format = $country_info['address_format']; } else { $shipping_country = ''; $shipping_address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}'; } $zone_info = $this->model_localization_zone->getZone($data['shipping_zone_id']); if ($zone_info) { $shipping_zone = $zone_info['name']; } else { $shipping_zone = ''; } $country_info = $this->model_localization_country->getCountry($data['payment_country_id']); if ($country_info) { $payment_country = $country_info['name']; $payment_address_format = $country_info['address_format']; } else { $payment_country = ''; $payment_address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}'; } $zone_info = $this->model_localization_zone->getZone($data['payment_zone_id']); if ($zone_info) { $payment_zone = $zone_info['name']; } else { $payment_zone = ''; } $this->theme->model('localization/currency'); $currency_info = $this->model_localization_currency->getCurrencyByCode($this->config->get('config_currency')); if ($currency_info) { $currency_id = $currency_info['currency_id']; $currency_code = $currency_info['code']; $currency_value = $currency_info['value']; } else { $currency_id = 0; $currency_code = $this->config->get('config_currency'); $currency_value = 1.00000; } $this->db->query(" INSERT INTO `{$this->db->prefix}order` SET invoice_prefix = '" . $this->db->escape($invoice_prefix) . "', store_id = '" . (int)$data['store_id'] . "', store_name = '" . $this->db->escape($store_name) . "', store_url = '" . $this->db->escape($store_url) . "', customer_id = '" . (int)$data['customer_id'] . "', customer_group_id = '" . (int)$data['customer_group_id'] . "', firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', payment_firstname = '" . $this->db->escape($data['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($data['payment_lastname']) . "', payment_company = '" . $this->db->escape($data['payment_company']) . "', payment_company_id = '" . $this->db->escape($data['payment_company_id']) . "', payment_tax_id = '" . $this->db->escape($data['payment_tax_id']) . "', payment_address_1 = '" . $this->db->escape($data['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($data['payment_address_2']) . "', payment_city = '" . $this->db->escape($data['payment_city']) . "', payment_postcode = '" . $this->db->escape($data['payment_postcode']) . "', payment_country = '" . $this->db->escape($payment_country) . "', payment_country_id = '" . (int)$data['payment_country_id'] . "', payment_zone = '" . $this->db->escape($payment_zone) . "', payment_zone_id = '" . (int)$data['payment_zone_id'] . "', payment_address_format = '" . $this->db->escape($payment_address_format) . "', payment_method = '" . $this->db->escape($data['payment_method']) . "', payment_code = '" . $this->db->escape($data['payment_code']) . "', shipping_firstname = '" . $this->db->escape($data['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($data['shipping_lastname']) . "', shipping_company = '" . $this->db->escape($data['shipping_company']) . "', shipping_address_1 = '" . $this->db->escape($data['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($data['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($data['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($data['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($shipping_country) . "', shipping_country_id = '" . (int)$data['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($shipping_zone) . "', shipping_zone_id = '" . (int)$data['shipping_zone_id'] . "', shipping_address_format = '" . $this->db->escape($shipping_address_format) . "', shipping_method = '" . $this->db->escape($data['shipping_method']) . "', shipping_code = '" . $this->db->escape($data['shipping_code']) . "', comment = '" . $this->db->escape($data['comment']) . "', order_status_id = '" . (int)$data['order_status_id'] . "', affiliate_id = '" . (int)$data['affiliate_id'] . "', language_id = '" . (int)$this->config->get('config_language_id') . "', currency_id = '" . (int)$currency_id . "', currency_code = '" . $this->db->escape($currency_code) . "', currency_value = '" . (float)$currency_value . "', date_added = NOW(), date_modified = NOW() "); $order_id = $this->db->getLastId(); if (isset($data['order_product'])) { foreach ($data['order_product'] as $order_product) { $this->db->query(" INSERT INTO {$this->db->prefix}order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$order_product['product_id'] . "', name = '" . $this->db->escape($order_product['name']) . "', model = '" . $this->db->escape($order_product['model']) . "', quantity = '" . (int)$order_product['quantity'] . "', price = '" . (float)$order_product['price'] . "', total = '" . (float)$order_product['total'] . "', tax = '" . (float)$order_product['tax'] . "', reward = '" . (int)$order_product['reward'] . "' "); $order_product_id = $this->db->getLastId(); $this->db->query(" UPDATE {$this->db->prefix}product SET quantity = (quantity - " . (int)$order_product['quantity'] . ") WHERE product_id = '" . (int)$order_product['product_id'] . "' AND subtract = '1' "); if (isset($order_product['order_option'])) { foreach ($order_product['order_option'] as $order_option) { $this->db->query(" INSERT INTO {$this->db->prefix}order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$order_option['product_option_id'] . "', product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "', name = '" . $this->db->escape($order_option['name']) . "', `value` = '" . $this->db->escape($order_option['value']) . "', `type` = '" . $this->db->escape($order_option['type']) . "' "); $this->db->query(" UPDATE {$this->db->prefix}product_option_value SET quantity = (quantity - " . (int)$order_product['quantity'] . ") WHERE product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "' AND subtract = '1' "); } } if (isset($order_product['order_download'])) { foreach ($order_product['order_download'] as $order_download) { $this->db->query(" INSERT INTO {$this->db->prefix}order_download SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', name = '" . $this->db->escape($order_download['name']) . "', filename = '" . $this->db->escape($order_download['filename']) . "', mask = '" . $this->db->escape($order_download['mask']) . "', remaining = '" . (int)$order_download['remaining'] . "' "); } } } } if (isset($data['order_giftcard'])) { foreach ($data['order_giftcard'] as $order_giftcard) { $this->db->query(" INSERT INTO {$this->db->prefix}order_giftcard SET order_id = '" . (int)$order_id . "', giftcard_id = '" . (int)$order_giftcard['giftcard_id'] . "', description = '" . $this->db->escape($order_giftcard['description']) . "', code = '" . $this->db->escape($order_giftcard['code']) . "', from_name = '" . $this->db->escape($order_giftcard['from_name']) . "', from_email = '" . $this->db->escape($order_giftcard['from_email']) . "', to_name = '" . $this->db->escape($order_giftcard['to_name']) . "', to_email = '" . $this->db->escape($order_giftcard['to_email']) . "', giftcard_theme_id = '" . (int)$order_giftcard['giftcard_theme_id'] . "', message = '" . $this->db->escape($order_giftcard['message']) . "', amount = '" . (float)$order_giftcard['amount'] . "' "); $this->db->query(" UPDATE {$this->db->prefix}giftcard SET order_id = '" . (int)$order_id . "' WHERE giftcard_id = '" . (int)$order_giftcard['giftcard_id'] . "' "); } } // Get the total $total = 0; if (isset($data['order_total'])) { foreach ($data['order_total'] as $order_total) { $this->db->query(" INSERT INTO {$this->db->prefix}order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($order_total['code']) . "', title = '" . $this->db->escape($order_total['title']) . "', text = '" . $this->db->escape($order_total['text']) . "', `value` = '" . (float)$order_total['value'] . "', sort_order = '" . (int)$order_total['sort_order'] . "' "); } $total+= $order_total['value']; } // Affiliate $affiliate_id = 0; $commission = 0; if (!empty($this->request->post['affiliate_id'])) { $this->theme->model('people/customer'); $affiliate_info = $this->model_people_customer->getCustomer($this->request->post['affiliate_id']); if ($affiliate_info) { $affiliate_id = $affiliate_info['customer_id']; $commission = ($total / 100) * $affiliate_info['commission']; } } // Update order total $this->db->query(" UPDATE `{$this->db->prefix}order` SET total = '" . (float)$total . "', affiliate_id = '" . (int)$affiliate_id . "', commission = '" . (float)$commission . "' WHERE order_id = '" . (int)$order_id . "' "); } public function editOrder($order_id, $data) { $this->theme->model('localization/country'); $this->theme->model('localization/zone'); $country_info = $this->model_localization_country->getCountry($data['shipping_country_id']); if ($country_info) { $shipping_country = $country_info['name']; $shipping_address_format = $country_info['address_format']; } else { $shipping_country = ''; $shipping_address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}'; } $zone_info = $this->model_localization_zone->getZone($data['shipping_zone_id']); if ($zone_info) { $shipping_zone = $zone_info['name']; } else { $shipping_zone = ''; } $country_info = $this->model_localization_country->getCountry($data['payment_country_id']); if ($country_info) { $payment_country = $country_info['name']; $payment_address_format = $country_info['address_format']; } else { $payment_country = ''; $payment_address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}'; } $zone_info = $this->model_localization_zone->getZone($data['payment_zone_id']); if ($zone_info) { $payment_zone = $zone_info['name']; } else { $payment_zone = ''; } // Restock products before subtracting the stock later on $order_query = $this->db->query(" SELECT * FROM `{$this->db->prefix}order` WHERE order_status_id > '0' AND order_id = '" . (int)$order_id . "' "); if ($order_query->num_rows) { $product_query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_product WHERE order_id = '" . (int)$order_id . "' "); foreach ($product_query->rows as $product) { $this->db->query(" UPDATE `{$this->db->prefix}product` SET quantity = (quantity + " . (int)$product['quantity'] . ") WHERE product_id = '" . (int)$product['product_id'] . "' AND subtract = '1' "); $option_query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$product['order_product_id'] . "' "); foreach ($option_query->rows as $option) { $this->db->query(" UPDATE {$this->db->prefix}product_option_value SET quantity = (quantity + " . (int)$product['quantity'] . ") WHERE product_option_value_id = '" . (int)$option['product_option_value_id'] . "' AND subtract = '1' "); } } } $this->db->query(" UPDATE `{$this->db->prefix}order` SET firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', payment_firstname = '" . $this->db->escape($data['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($data['payment_lastname']) . "', payment_company = '" . $this->db->escape($data['payment_company']) . "', payment_company_id = '" . $this->db->escape($data['payment_company_id']) . "', payment_tax_id = '" . $this->db->escape($data['payment_tax_id']) . "', payment_address_1 = '" . $this->db->escape($data['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($data['payment_address_2']) . "', payment_city = '" . $this->db->escape($data['payment_city']) . "', payment_postcode = '" . $this->db->escape($data['payment_postcode']) . "', payment_country = '" . $this->db->escape($payment_country) . "', payment_country_id = '" . (int)$data['payment_country_id'] . "', payment_zone = '" . $this->db->escape($payment_zone) . "', payment_zone_id = '" . (int)$data['payment_zone_id'] . "', payment_address_format = '" . $this->db->escape($payment_address_format) . "', payment_method = '" . $this->db->escape($data['payment_method']) . "', payment_code = '" . $this->db->escape($data['payment_code']) . "', shipping_firstname = '" . $this->db->escape($data['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($data['shipping_lastname']) . "', shipping_company = '" . $this->db->escape($data['shipping_company']) . "', shipping_address_1 = '" . $this->db->escape($data['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($data['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($data['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($data['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($shipping_country) . "', shipping_country_id = '" . (int)$data['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($shipping_zone) . "', shipping_zone_id = '" . (int)$data['shipping_zone_id'] . "', shipping_address_format = '" . $this->db->escape($shipping_address_format) . "', shipping_method = '" . $this->db->escape($data['shipping_method']) . "', shipping_code = '" . $this->db->escape($data['shipping_code']) . "', comment = '" . $this->db->escape($data['comment']) . "', order_status_id = '" . (int)$data['order_status_id'] . "', affiliate_id = '" . (int)$data['affiliate_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "' "); $this->db->query("DELETE FROM {$this->db->prefix}order_product WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_option WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_download WHERE order_id = '" . (int)$order_id . "'"); if (isset($data['order_product'])) { foreach ($data['order_product'] as $order_product) { $this->db->query(" INSERT INTO {$this->db->prefix}order_product SET order_product_id = '" . (int)$order_product['order_product_id'] . "', order_id = '" . (int)$order_id . "', product_id = '" . (int)$order_product['product_id'] . "', name = '" . $this->db->escape($order_product['name']) . "', model = '" . $this->db->escape($order_product['model']) . "', quantity = '" . (int)$order_product['quantity'] . "', price = '" . (float)$order_product['price'] . "', total = '" . (float)$order_product['total'] . "', tax = '" . (float)$order_product['tax'] . "', reward = '" . (int)$order_product['reward'] . "' "); $order_product_id = $this->db->getLastId(); $this->db->query(" UPDATE {$this->db->prefix}product SET quantity = (quantity - " . (int)$order_product['quantity'] . ") WHERE product_id = '" . (int)$order_product['product_id'] . "' AND subtract = '1' "); if (isset($order_product['order_option'])) { foreach ($order_product['order_option'] as $order_option) { $this->db->query(" INSERT INTO {$this->db->prefix}order_option SET order_option_id = '" . (int)$order_option['order_option_id'] . "', order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$order_option['product_option_id'] . "', product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "', name = '" . $this->db->escape($order_option['name']) . "', `value` = '" . $this->db->escape($order_option['value']) . "', `type` = '" . $this->db->escape($order_option['type']) . "' "); $this->db->query(" UPDATE {$this->db->prefix}product_option_value SET quantity = (quantity - " . (int)$order_product['quantity'] . ") WHERE product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "' AND subtract = '1' "); } } if (isset($order_product['order_download'])) { foreach ($order_product['order_download'] as $order_download) { $this->db->query(" INSERT INTO {$this->db->prefix}order_download SET order_download_id = '" . (int)$order_download['order_download_id'] . "', order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', name = '" . $this->db->escape($order_download['name']) . "', filename = '" . $this->db->escape($order_download['filename']) . "', mask = '" . $this->db->escape($order_download['mask']) . "', remaining = '" . (int)$order_download['remaining'] . "' "); } } } } $this->db->query("DELETE FROM {$this->db->prefix}order_giftcard WHERE order_id = '" . (int)$order_id . "'"); if (isset($data['order_giftcard'])) { foreach ($data['order_giftcard'] as $order_giftcard) { $this->db->query(" INSERT INTO {$this->db->prefix}order_giftcard SET order_giftcard_id = '" . (int)$order_giftcard['order_giftcard_id'] . "', order_id = '" . (int)$order_id . "', giftcard_id = '" . (int)$order_giftcard['giftcard_id'] . "', description = '" . $this->db->escape($order_giftcard['description']) . "', code = '" . $this->db->escape($order_giftcard['code']) . "', from_name = '" . $this->db->escape($order_giftcard['from_name']) . "', from_email = '" . $this->db->escape($order_giftcard['from_email']) . "', to_name = '" . $this->db->escape($order_giftcard['to_name']) . "', to_email = '" . $this->db->escape($order_giftcard['to_email']) . "', giftcard_theme_id = '" . (int)$order_giftcard['giftcard_theme_id'] . "', message = '" . $this->db->escape($order_giftcard['message']) . "', amount = '" . (float)$order_giftcard['amount'] . "' "); $this->db->query(" UPDATE {$this->db->prefix}giftcard SET order_id = '" . (int)$order_id . "' WHERE giftcard_id = '" . (int)$order_giftcard['giftcard_id'] . "' "); } } // Get the total $total = 0; $this->db->query("DELETE FROM {$this->db->prefix}order_total WHERE order_id = '" . (int)$order_id . "'"); if (isset($data['order_total'])) { foreach ($data['order_total'] as $order_total) { $this->db->query(" INSERT INTO {$this->db->prefix}order_total SET order_total_id = '" . (int)$order_total['order_total_id'] . "', order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($order_total['code']) . "', title = '" . $this->db->escape($order_total['title']) . "', text = '" . $this->db->escape($order_total['text']) . "', `value` = '" . (float)$order_total['value'] . "', sort_order = '" . (int)$order_total['sort_order'] . "' "); } $total+= $order_total['value']; } // Affiliate $affiliate_id = 0; $commission = 0; if (!empty($this->request->post['affiliate_id'])) { $this->theme->model('people/customer'); $affiliate_info = $this->model_people_customer->getCustomer($this->request->post['affiliate_id']); if ($affiliate_info) { $affiliate_id = $affiliate_info['customer_id']; $commission = ($total / 100) * $affiliate_info['commission']; } } $this->db->query(" UPDATE `{$this->db->prefix}order` SET total = '" . (float)$total . "', affiliate_id = '" . (int)$affiliate_id . "', commission = '" . (float)$commission . "' WHERE order_id = '" . (int)$order_id . "' "); } public function deleteOrder($order_id) { $order_query = $this->db->query(" SELECT * FROM `{$this->db->prefix}order` WHERE order_status_id > '0' AND order_id = '" . (int)$order_id . "' "); if ($order_query->num_rows) { $product_query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_product WHERE order_id = '" . (int)$order_id . "' "); foreach ($product_query->rows as $product) { $this->db->query(" UPDATE `{$this->db->prefix}product` SET quantity = (quantity + " . (int)$product['quantity'] . ") WHERE product_id = '" . (int)$product['product_id'] . "' AND subtract = '1' "); $option_query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$product['order_product_id'] . "' "); foreach ($option_query->rows as $option) { $this->db->query(" UPDATE {$this->db->prefix}product_option_value SET quantity = (quantity + " . (int)$product['quantity'] . ") WHERE product_option_value_id = '" . (int)$option['product_option_value_id'] . "' AND subtract = '1' "); } } } $this->db->query("DELETE FROM `{$this->db->prefix}order` WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_product WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_option WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_download WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_giftcard WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_total WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_history WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_fraud WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}order_fraud WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}customer_credit WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}customer_reward WHERE order_id = '" . (int)$order_id . "'"); $this->db->query("DELETE FROM {$this->db->prefix}customer_commission WHERE order_id = '" . (int)$order_id . "'"); $recurring = $this->db->query(" SELECT order_recurring_id FROM {$this->db->prefix}order_recurring WHERE order_id = '" . (int)$order_id . "'"); if ($recurring->num_rows): $recurring_order_id = $recurring->row['order_recurring_id']; $this->db->query(" DELETE FROM {$this->db->prefix}order_recurring_transaction WHERE order_recurring_id = '" . (int)$recurring_order_id . "'"); $this->db->query(" DELETE FROM {$this->db->prefix}order_recurring WHERE order_id = '" . (int)$order_id . "'"); endif; } public function getOrder($order_id) { $order_query = $this->db->query(" SELECT *, (SELECT CONCAT(c.firstname, ' ', c.lastname) FROM {$this->db->prefix}customer c WHERE c.customer_id = o.customer_id) AS customer FROM `{$this->db->prefix}order` o WHERE o.order_id = '" . (int)$order_id . "' "); if ($order_query->num_rows) { $reward = 0; $order_product_query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_product WHERE order_id = '" . (int)$order_id . "' "); foreach ($order_product_query->rows as $product) { $reward+= $product['reward']; } $country_query = $this->db->query(" SELECT * FROM `{$this->db->prefix}country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "' "); if ($country_query->num_rows) { $payment_iso_code_2 = $country_query->row['iso_code_2']; $payment_iso_code_3 = $country_query->row['iso_code_3']; } else { $payment_iso_code_2 = ''; $payment_iso_code_3 = ''; } $zone_query = $this->db->query(" SELECT * FROM `{$this->db->prefix}zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "' "); if ($zone_query->num_rows) { $payment_zone_code = $zone_query->row['code']; } else { $payment_zone_code = ''; } $country_query = $this->db->query(" SELECT * FROM `{$this->db->prefix}country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "' "); if ($country_query->num_rows) { $shipping_iso_code_2 = $country_query->row['iso_code_2']; $shipping_iso_code_3 = $country_query->row['iso_code_3']; } else { $shipping_iso_code_2 = ''; $shipping_iso_code_3 = ''; } $zone_query = $this->db->query(" SELECT * FROM `{$this->db->prefix}zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "' "); if ($zone_query->num_rows) { $shipping_zone_code = $zone_query->row['code']; } else { $shipping_zone_code = ''; } if ($order_query->row['affiliate_id']) { $affiliate_id = $order_query->row['affiliate_id']; } else { $affiliate_id = 0; } $this->theme->model('people/customer'); $affiliate_info = $this->model_people_customer->getCustomer($affiliate_id); if ($affiliate_info) { $affiliate_firstname = $affiliate_info['firstname']; $affiliate_lastname = $affiliate_info['lastname']; } else { $affiliate_firstname = ''; $affiliate_lastname = ''; } $this->theme->model('localization/language'); $language_info = $this->model_localization_language->getLanguage($order_query->row['language_id']); if ($language_info) { $language_code = $language_info['code']; $language_filename = $language_info['filename']; $language_directory = $language_info['directory']; } else { $language_code = ''; $language_filename = ''; $language_directory = ''; } return array( 'order_id' => $order_query->row['order_id'], 'invoice_no' => $order_query->row['invoice_no'], 'invoice_prefix' => $order_query->row['invoice_prefix'], 'store_id' => $order_query->row['store_id'], 'store_name' => $order_query->row['store_name'], 'store_url' => $order_query->row['store_url'], 'customer_id' => $order_query->row['customer_id'], 'customer' => $order_query->row['customer'], 'customer_group_id' => $order_query->row['customer_group_id'], 'firstname' => $order_query->row['firstname'], 'lastname' => $order_query->row['lastname'], 'telephone' => $order_query->row['telephone'], 'email' => $order_query->row['email'], 'payment_firstname' => $order_query->row['payment_firstname'], 'payment_lastname' => $order_query->row['payment_lastname'], 'payment_company' => $order_query->row['payment_company'], 'payment_company_id' => $order_query->row['payment_company_id'], 'payment_tax_id' => $order_query->row['payment_tax_id'], 'payment_address_1' => $order_query->row['payment_address_1'], 'payment_address_2' => $order_query->row['payment_address_2'], 'payment_postcode' => $order_query->row['payment_postcode'], 'payment_city' => $order_query->row['payment_city'], 'payment_zone_id' => $order_query->row['payment_zone_id'], 'payment_zone' => $order_query->row['payment_zone'], 'payment_zone_code' => $payment_zone_code, 'payment_country_id' => $order_query->row['payment_country_id'], 'payment_country' => $order_query->row['payment_country'], 'payment_iso_code_2' => $payment_iso_code_2, 'payment_iso_code_3' => $payment_iso_code_3, 'payment_address_format' => $order_query->row['payment_address_format'], 'payment_method' => $order_query->row['payment_method'], 'payment_code' => $order_query->row['payment_code'], 'shipping_firstname' => $order_query->row['shipping_firstname'], 'shipping_lastname' => $order_query->row['shipping_lastname'], 'shipping_company' => $order_query->row['shipping_company'], 'shipping_address_1' => $order_query->row['shipping_address_1'], 'shipping_address_2' => $order_query->row['shipping_address_2'], 'shipping_postcode' => $order_query->row['shipping_postcode'], 'shipping_city' => $order_query->row['shipping_city'], 'shipping_zone_id' => $order_query->row['shipping_zone_id'], 'shipping_zone' => $order_query->row['shipping_zone'], 'shipping_zone_code' => $shipping_zone_code, 'shipping_country_id' => $order_query->row['shipping_country_id'], 'shipping_country' => $order_query->row['shipping_country'], 'shipping_iso_code_2' => $shipping_iso_code_2, 'shipping_iso_code_3' => $shipping_iso_code_3, 'shipping_address_format' => $order_query->row['shipping_address_format'], 'shipping_method' => $order_query->row['shipping_method'], 'shipping_code' => $order_query->row['shipping_code'], 'comment' => $order_query->row['comment'], 'total' => $order_query->row['total'], 'reward' => $reward, 'order_status_id' => $order_query->row['order_status_id'], 'affiliate_id' => $order_query->row['affiliate_id'], 'affiliate_firstname' => $affiliate_firstname, 'affiliate_lastname' => $affiliate_lastname, 'commission' => $order_query->row['commission'], 'language_id' => $order_query->row['language_id'], 'language_code' => $language_code, 'language_filename' => $language_filename, 'language_directory' => $language_directory, 'currency_id' => $order_query->row['currency_id'], 'currency_code' => $order_query->row['currency_code'], 'currency_value' => $order_query->row['currency_value'], 'ip' => $order_query->row['ip'], 'forwarded_ip' => $order_query->row['forwarded_ip'], 'user_agent' => $order_query->row['user_agent'], 'accept_language' => $order_query->row['accept_language'], 'date_added' => $order_query->row['date_added'], 'date_modified' => $order_query->row['date_modified'] ); } else { return false; } } public function getOrders($data = array()) { $sql = " SELECT o.order_id, CONCAT(o.firstname, ' ', o.lastname) AS customer, (SELECT os.name FROM {$this->db->prefix}order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS status, o.total, o.currency_code, o.currency_value, o.date_added, o.date_modified FROM `{$this->db->prefix}order` o"; if (isset($data['filter_order_status_id']) && !is_null($data['filter_order_status_id'])) { $sql.= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'"; } else { $sql.= " WHERE o.order_status_id > '0'"; } if (!empty($data['filter_order_id'])) { $sql.= " AND o.order_id = '" . (int)$data['filter_order_id'] . "'"; } if (!empty($data['filter_customer'])) { $sql.= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'"; } if (!empty($data['filter_date_added'])) { $sql.= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')"; } if (!empty($data['filter_date_modified'])) { $sql.= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')"; } if (!empty($data['filter_total'])) { $sql.= " AND o.total = '" . (float)$data['filter_total'] . "'"; } $sort_data = array('o.order_id', 'customer', 'status', 'o.date_added', 'o.date_modified', 'o.total'); if (isset($data['sort']) && in_array($data['sort'], $sort_data)) { $sql.= " ORDER BY {$data['sort']}"; } else { $sql.= " ORDER BY o.order_id"; } if (isset($data['order']) && ($data['order'] == 'DESC')) { $sql.= " DESC"; } else { $sql.= " ASC"; } if (isset($data['start']) || isset($data['limit'])) { if ($data['start'] < 0) { $data['start'] = 0; } if ($data['limit'] < 1) { $data['limit'] = 20; } $sql.= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit']; } $query = $this->db->query($sql); return $query->rows; } public function getOrderProducts($order_id) { $query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_product WHERE order_id = '" . (int)$order_id . "' "); return $query->rows; } public function getOrderOption($order_id, $order_option_id) { $query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_option WHERE order_id = '" . (int)$order_id . "' AND order_option_id = '" . (int)$order_option_id . "' "); return $query->row; } public function getOrderOptions($order_id, $order_product_id) { $query = $this->db->query(" SELECT oo.* FROM {$this->db->prefix}order_option AS oo LEFT JOIN {$this->db->prefix}product_option po USING(product_option_id) LEFT JOIN `{$this->db->prefix}option` o USING(option_id) WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "' ORDER BY o.sort_order "); return $query->rows; } public function getOrderDownloads($order_id, $order_product_id) { $query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_download WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "' "); return $query->rows; } public function getOrderGiftcards($order_id) { $query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_giftcard WHERE order_id = '" . (int)$order_id . "' "); return $query->rows; } public function getOrderGiftcardByGiftcardId($giftcard_id) { $query = $this->db->query(" SELECT * FROM `{$this->db->prefix}order_giftcard` WHERE giftcard_id = '" . (int)$giftcard_id . "' "); return $query->row; } public function getOrderTotals($order_id) { $query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_total WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order "); return $query->rows; } public function getTotalOrders($data = array()) { $sql = " SELECT COUNT(*) AS total FROM `{$this->db->prefix}order`"; if (isset($data['filter_order_status_id']) && !is_null($data['filter_order_status_id'])) { $sql.= " WHERE order_status_id = '" . (int)$data['filter_order_status_id'] . "'"; } else { $sql.= " WHERE order_status_id > '0'"; } if (!empty($data['filter_order_id'])) { $sql.= " AND order_id = '" . (int)$data['filter_order_id'] . "'"; } if (!empty($data['filter_customer'])) { $sql.= " AND CONCAT(firstname, ' ', lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'"; } if (!empty($data['filter_date_added'])) { $sql.= " AND DATE(date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')"; } if (!empty($data['filter_date_modified'])) { $sql.= " AND DATE(date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')"; } if (!empty($data['filter_total'])) { $sql.= " AND total = '" . (float)$data['filter_total'] . "'"; } $query = $this->db->query($sql); return $query->row['total']; } public function getTotalOrdersByStoreId($store_id) { $query = $this->db->query(" SELECT COUNT(*) AS total FROM `{$this->db->prefix}order` WHERE store_id = '" . (int)$store_id . "' "); return $query->row['total']; } public function getTotalOrdersByOrderStatusId($order_status_id) { $query = $this->db->query(" SELECT COUNT(*) AS total FROM `{$this->db->prefix}order` WHERE order_status_id = '" . (int)$order_status_id . "' AND order_status_id > '0' "); return $query->row['total']; } public function getTotalOrdersByLanguageId($language_id) { $query = $this->db->query(" SELECT COUNT(*) AS total FROM `{$this->db->prefix}order` WHERE language_id = '" . (int)$language_id . "' AND order_status_id > '0' "); return $query->row['total']; } public function getTotalOrdersByCurrencyId($currency_id) { $query = $this->db->query(" SELECT COUNT(*) AS total FROM `{$this->db->prefix}order` WHERE currency_id = '" . (int)$currency_id . "' AND order_status_id > '0' "); return $query->row['total']; } public function getTotalSales() { $query = $this->db->query(" SELECT SUM(total) AS total FROM `{$this->db->prefix}order` WHERE order_status_id > '0' "); return $query->row['total']; } public function getTotalSalesByYear($year) { $query = $this->db->query(" SELECT SUM(total) AS total FROM `{$this->db->prefix}order` WHERE order_status_id > '0' AND YEAR(date_added) = '" . (int)$year . "' "); return $query->row['total']; } public function createInvoiceNo($order_id) { $order_info = $this->getOrder($order_id); if ($order_info && !$order_info['invoice_no']) { $query = $this->db->query(" SELECT MAX(invoice_no) AS invoice_no FROM `{$this->db->prefix}order` WHERE invoice_prefix = '" . $this->db->escape($order_info['invoice_prefix']) . "' "); if ($query->row['invoice_no']) { $invoice_no = $query->row['invoice_no'] + 1; } else { $invoice_no = 1; } $this->db->query(" UPDATE `{$this->db->prefix}order` SET invoice_no = '" . (int)$invoice_no . "', invoice_prefix = '" . $this->db->escape($order_info['invoice_prefix']) . "' WHERE order_id = '" . (int)$order_id . "' "); return $order_info['invoice_prefix'] . $invoice_no; } } public function addOrderHistory($order_id, $data) { $this->db->query(" UPDATE `{$this->db->prefix}order` SET order_status_id = '" . (int)$data['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "' "); $this->db->query(" INSERT INTO {$this->db->prefix}order_history SET order_id = '" . (int)$order_id . "', order_status_id = '" . (int)$data['order_status_id'] . "', notify = '" . (isset($data['notify']) ? (int)$data['notify'] : 0) . "', comment = '" . $this->db->escape(strip_tags($data['comment'])) . "', date_added = NOW() "); $order_info = $this->getOrder($order_id); // Send out any gift giftcard mails if ($this->config->get('config_complete_status_id') == $data['order_status_id']) { $this->theme->model('sale/giftcard'); $results = $this->getOrderGiftcards($order_id); foreach ($results as $result) { $this->model_sale_giftcard->sendGiftcard($result['giftcard_id']); } } if ($data['notify']) { $order_status_query = $this->db->query(" SELECT * FROM {$this->db->prefix}order_status WHERE order_status_id = '" . (int)$data['order_status_id'] . "' AND language_id = '" . (int)$order_info['language_id'] . "' "); $status = $order_status_query->row['name']; $link = html_entity_decode($order_info['store_url'] . 'account/order/info&order_id=' . $order_id, ENT_QUOTES, 'UTF-8'); if ($data['comment']): $comment = strip_tags(html_entity_decode($data['comment'], ENT_QUOTES, 'UTF-8')); else: $comment = 'No further comments added.'; endif; $callback = array( 'customer_id' => $order_info['customer_id'], 'order_id' => $order_info['order_id'], 'order' => $order_info, 'status' => $status, 'link' => $link, 'comment' => $comment, 'callback' => array( 'class' => __CLASS__, 'method' => 'admin_order_add_history' ) ); $this->theme->notify('admin_order_add_history', $callback); } } public function getOrderHistories($order_id, $start = 0, $limit = 10) { if ($start < 0) { $start = 0; } if ($limit < 1) { $limit = 10; } $query = $this->db->query(" SELECT oh.date_added, os.name AS status, oh.comment, oh.notify FROM {$this->db->prefix}order_history oh LEFT JOIN {$this->db->prefix}order_status os ON oh.order_status_id = os.order_status_id WHERE oh.order_id = '" . (int)$order_id . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY oh.date_added ASC LIMIT " . (int)$start . "," . (int)$limit); return $query->rows; } public function getTotalOrderHistories($order_id) { $query = $this->db->query(" SELECT COUNT(*) AS total FROM {$this->db->prefix}order_history WHERE order_id = '" . (int)$order_id . "' "); return $query->row['total']; } public function getTotalOrderHistoriesByOrderStatusId($order_status_id) { $query = $this->db->query(" SELECT COUNT(*) AS total FROM {$this->db->prefix}order_history WHERE order_status_id = '" . (int)$order_status_id . "' "); return $query->row['total']; } public function getCustomersByProductsOrdered($products, $start, $end) { $implode = array(); foreach ($products as $product_id) { $implode[] = "op.product_id = '" . (int)$product_id . "'"; } $query = $this->db->query(" SELECT DISTINCT customer_id FROM `{$this->db->prefix}order` o LEFT JOIN {$this->db->prefix}order_product op ON (o.order_id = op.order_id) WHERE (" . implode(" OR ", $implode) . ") AND o.order_status_id <> '0' LIMIT " . (int)$start . "," . (int)$end); return $query->rows; } public function getTotalCustomersByProductsOrdered($products) { $implode = array(); foreach ($products as $product_id) { $implode[] = "op.product_id = '" . (int)$product_id . "'"; } $query = $this->db->query(" SELECT DISTINCT customer_id FROM `{$this->db->prefix}order` o LEFT JOIN {$this->db->prefix}order_product op ON (o.order_id = op.order_id) WHERE (" . implode(" OR ", $implode) . ") AND o.order_status_id <> '0' "); return $query->row['total']; } public function getShippingModules() { $modules = array(); $this->theme->model('setting/module'); $query = $this->model_setting_module->getAll('shipping'); foreach ($query as $module): if ($module['status']): $this->theme->language('shipping/' . $module['code']); $modules[] = array( 'code' => $module['code'], 'name' => $this->language->get('lang_heading_title') ); endif; endforeach; return $modules; } public function getPaymentModules() { $modules = array(); $this->theme->model('setting/module'); $query = $this->model_setting_module->getAll('payment'); foreach ($query as $module): if ($module['status']): $this->theme->language('payment/' . $module['code']); $modules[] = array( 'code' => $module['code'], 'name' => $this->language->get('lang_heading_title') ); endif; endforeach; return $modules; } /* |-------------------------------------------------------------------------- | NOTIFICATIONS |-------------------------------------------------------------------------- | | The below methods are notification callbacks. | */ public function admin_order_add_history($data, $message) { $search = array( '!order_id!', '!status!', '!link!', '!comment!' ); $replace = array( $data['order_id'], $data['status'], $data['link'], $data['comment'] ); $html_replace = array( $data['order_id'], $data['status'], $data['link'], nl2br($data['comment']) ); foreach ($message as $key => $value): if ($key == 'html'): $message['html'] = str_replace($search, $html_replace, $value); else: $message[$key] = str_replace($search, $replace, $value); endif; endforeach; return $message; } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateRestaurantCusineTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('restaurant_cuisine', function (Blueprint $table) { $table->increments('id'); $table->bigInteger('restaurant_id')->unsigned(); $table->index('restaurant_id'); $table->foreign('restaurant_id')->references('id')->on('restaurant')->onDelete('cascade'); $table->integer('cuisine_id')->unsigned(); $table->index('cuisine_id'); $table->foreign('cuisine_id')->references('id')->on('cuisine')->onDelete('cascade'); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('restaurant_cuisine'); } }
import Off from './Off'; import On from './On'; // ============================== // CONCRETE CONTEXT // ============================== export default class Computer { constructor() { this._currentState = null; this._states = { off: new Off(), on: new On() }; } power() { this._currentState.power(this); } getCurrentState() { return this._currentState; } setCurrentState(state) { this._currentState = state; } getStates() { return this._states; } }
// Copyright (c) Eugene Berdnikov. See License.txt in the project root for license information. using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Recaptcha.Web.Tests.Compatibility { #pragma warning disable 618 [TestClass] public class EnumTests { [TestMethod] [TestCategory(CompatibilityTests.Category)] public void VerificationResultIsInt32Enum() { Assert.AreEqual(typeof(int), Enum.GetUnderlyingType(typeof(RecaptchaVerificationResult))); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void VerificationResultUnknownErrorHasCorrectValue() { Assert.AreEqual((RecaptchaVerificationResult)0, RecaptchaVerificationResult.UnknownError); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void VerificationResultSuccessHasCorrectValue() { Assert.AreEqual((RecaptchaVerificationResult)1, RecaptchaVerificationResult.Success); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void VerificationResultIncorrectCaptchaSolutionHasCorrectValue() { Assert.AreEqual((RecaptchaVerificationResult)2, RecaptchaVerificationResult.IncorrectCaptchaSolution); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void VerificationResultInvalidCookieParametersHasCorrectValue() { Assert.AreEqual((RecaptchaVerificationResult)3, RecaptchaVerificationResult.InvalidCookieParameters); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void VerificationResultInvalidPrivateKeyHasCorrectValue() { Assert.AreEqual((RecaptchaVerificationResult)4, RecaptchaVerificationResult.InvalidPrivateKey); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void VerificationResultNullOrEmptyCaptchaSolutionHasCorrectValue() { Assert.AreEqual((RecaptchaVerificationResult)5, RecaptchaVerificationResult.NullOrEmptyCaptchaSolution); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void VerificationResultChallengeNotProvidedHasCorrectValue() { Assert.AreEqual((RecaptchaVerificationResult)6, RecaptchaVerificationResult.ChallengeNotProvided); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void ThemeIsInt32Enum() { Assert.AreEqual(typeof(int), Enum.GetUnderlyingType(typeof(RecaptchaTheme))); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void ThemeRedHasCorrectValue() { Assert.AreEqual((RecaptchaTheme)0, RecaptchaTheme.Red); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void ThemeBlackglassHasCorrectValue() { Assert.AreEqual((RecaptchaTheme)1, RecaptchaTheme.Blackglass); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void ThemeWhiteHasCorrectValue() { Assert.AreEqual((RecaptchaTheme)2, RecaptchaTheme.White); } [TestMethod] [TestCategory(CompatibilityTests.Category)] public void ThemeCleanHasCorrectValue() { Assert.AreEqual((RecaptchaTheme)3, RecaptchaTheme.Clean); } } }
/* * Functions used to build the ast */ #pragma once #include "structures.h" /* TreeNode, NodeList and such*/ #include <stdio.h> /*printfs*/ #include <stdlib.h> /*mallocs et all*/ #include <string.h> /*strcmp*/ TreeNode* InitTreeNode(enum NodeType type); NodeList* InitNodeList(TreeNode* node); TreeNode* InsertTerminal(char* terminalValue, enum NodeType terminalType); /*Tree generation*/ TreeNode* InsertClass(TreeNode* name,NodeList* sons); TreeNode* InsertMethod(TreeNode* Type, TreeNode* name, NodeList* paramSons, NodeList* bodySons); TreeNode* InsertVarDecl(TreeNode* type,NodeList* names); NodeList* InsertFormalParams(TreeNode* type,TreeNode* name,NodeList* existing); TreeNode* InsertIfElse(TreeNode* condition, TreeNode* ifBody, TreeNode* elseBody); TreeNode* InsertWhile(TreeNode* condition, TreeNode* body); TreeNode* InsertPrint(TreeNode* expr); TreeNode* InsertStore(TreeNode* varName, TreeNode* expr); TreeNode* InsertStoreArray(TreeNode* arrayName, TreeNode* indexExpr, TreeNode* value); /*TreeNode* insertInitArray(TreeNode* sizeExpr, enum NodeType type);*/ TreeNode* InsertExpression(TreeNode* son1, enum NodeType exprType, TreeNode* son2); TreeNode* InsertParseArgs(TreeNode* name, TreeNode* index); TreeNode* InsertCall(TreeNode* name, NodeList* args); TreeNode* InsertBraces(NodeList* statements); NodeList* InsertTreeNodeIntoList(TreeNode* newTreeNode, NodeList* existing); TreeNode* AddSonsToTreeNode(TreeNode* node, NodeList* sons); NodeList* MergeLists(NodeList* first, NodeList* second); NodeList* InsertMainArgs(TreeNode* argName);
module UkAddressParser VERSION = "0.2.0" end
module SpecHelpers def setup_site site = create('test site') writers = build(:content_type, site: site, name: "Writers", _user: true) writers.entries_custom_fields.build(label: "Email", type: "email") writers.entries_custom_fields.build(label: "First Name", type: "string", required: false) writers.save! editors = build(:content_type, site: site, name: "Editors", _user: true) editors.entries_custom_fields.build(label: "Email", type: "email") editors.entries_custom_fields.build(label: "First Name", type: "string", required: false) editors.save! # @ctype = build(:content_type, site: site, name: "Examples") # @ctype.entries_custom_fields.build(label: "Name", type: "string", searchable: true) # @ctype.save! # @stuff_field = @ctype.entries_custom_fields.build(label: "Stuff", type: "text", searchable: false) # @stuff_field.save! # @ctype.entries.create!(name: "Findable entry", stuff: "Some stuff") # @ctype.entries.create!(name: "Hidden", stuff: "Not findable") create(:sub_page, site: site, title: "Please search for this findable page", slug: "findable", raw_template: "This is what you were looking for") create(:sub_page, site: site, title: "Unpublished findable", slug: "unpublished-findable", raw_template: "Not published, so can't be found", published: false) create(:sub_page, site: site, title: "Seems findable", slug: "seems-findable", raw_template: "Even if it seems findable, it sound't be found because of the searchable flag") # create(:sub_page, site: site, title: "search", slug: "search", raw_template: <<-EOT # * Search results: # <ul> # {% for result in site.search %} # {% if result.content_type_slug == 'examples' %} # <li><a href="/examples/{{result._slug}}">{{ result.name }}</a></li> # {% else %} # <li><a href="/{{result.fullpath}}">{{ result.title }}</a></li> # {% endif %} # {% endfor %} # </ul> # EOT # ) another_site = create('another site') create(:sub_page, site: another_site, title: 'Writers', slug: 'writers', raw_template: 'CMS Writers Page' ) [site, another_site].each do |s| create(:sub_page, site: s, title: 'User Status', slug: 'status', raw_template: <<-EOT User Status: {% if end_user.logged_in? %} Logged in as {{ end_user.type }} with email {{ end_user.email }} {% else %} Not logged in. {% endif %} EOT ) home = s.pages.where(slug: 'index').first home.raw_template = <<-EOF Notice: {{ flash.notice }} Error: {{ flash.error }} Content of the home page. EOF home.save! end another_editors = build(:content_type, site: another_site, name: "Editors", _user: true) another_editors.entries_custom_fields.build(label: "Email", type: "email") another_editors.entries_custom_fields.build(label: "First Name", type: "string", required: false) another_editors.save! end end RSpec.configure { |c| c.include SpecHelpers }
var dir_f4703b3db1bd5f8d2d3fca771c570947 = [ [ "led.c", "led_8c.html", "led_8c" ], [ "tick.c", "tick_8c.html", "tick_8c" ], [ "usart2.c", "usart2_8c.html", "usart2_8c" ] ];
<!DOCTYPE html> <!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]--> <!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]--> <!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--> <html lang="en" xmlns="http://www.w3.org/1999/html"> <!--<![endif]--> <head> <!-- Basic Page Needs ================================================== --> <meta charset="utf-8" /> <title>Font Awesome License</title> <meta name="description" content="Font Awesome, the iconic font designed for Bootstrap"> <meta name="author" content="Dave Gandy"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--<meta name="viewport" content="initial-scale=1; maximum-scale=1">--> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- CSS ================================================== --> <link rel="stylesheet" href="../assets/css/site.css"> <link rel="stylesheet" href="../assets/css/pygments.css"> <link rel="stylesheet" href="../assets/font-awesome/css/font-awesome.css"> <!--[if IE 7]> <link rel="stylesheet" href="../assets/font-awesome/css/font-awesome-ie7.css"> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="../assets/ico/favicon.ico"> <script type="text/javascript" src="//use.typekit.net/wnc7ioh.js"></script> <script type="text/javascript">try{Typekit.load();}catch(e){}</script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-30136587-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body data-spy="scroll" data-target=".navbar"> <div class="wrapper"> <!-- necessary for sticky footer. wrap all content except footer --> <div class="navbar navbar-inverse navbar-static-top hidden-print"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="../"><i class="icon-flag"></i> Font Awesome</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="hidden-tablet "><a href="../">Home</a></li> <li><a href="../get-started/">Get Started</a></li> <li class="dropdown-split-left"><a href="../icons/">Icons</a></li> <li class="dropdown dropdown-split-right hidden-phone"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-caret-down"></i> </a> <ul class="dropdown-menu pull-right"> <li><a href="../icons/"><i class="icon-flag icon-fixed-width"></i>&nbsp; Icons</a></li> <li class="divider"></li> <li><a href="../icons/#new"><i class="icon-shield icon-fixed-width"></i>&nbsp; New Icons in 3.2.1</a></li> <li><a href="../icons/#web-application"><i class="icon-camera-retro icon-fixed-width"></i>&nbsp; Web Application Icons</a></li> <li><a href="../icons/#currency"><i class="icon-won icon-fixed-width"></i>&nbsp; Currency Icons</a></li> <li><a href="../icons/#text-editor"><i class="icon-file-text-alt icon-fixed-width"></i>&nbsp; Text Editor Icons</a></li> <li><a href="../icons/#directional"><i class="icon-hand-right icon-fixed-width"></i>&nbsp; Directional Icons</a></li> <li><a href="../icons/#video-player"><i class="icon-play-sign icon-fixed-width"></i>&nbsp; Video Player Icons</a></li> <li><a href="../icons/#brand"><i class="icon-github icon-fixed-width"></i>&nbsp; Brand Icons</a></li> <li><a href="../icons/#medical"><i class="icon-medkit icon-fixed-width"></i>&nbsp; Medical Icons</a></li> </ul> </li> <li class="dropdown-split-left"><a href="../examples/">Examples</a></li> <li class="dropdown dropdown-split-right hidden-phone"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-caret-down"></i> </a> <ul class="dropdown-menu pull-right"> <li><a href="../examples/">Examples</a></li> <li class="divider"></li> <li><a href="../examples/#new-styles">New Styles</a></li> <li><a href="../examples/#inline-icons">Inline Icons</a></li> <li><a href="../examples/#larger-icons">Larger Icons</a></li> <li><a href="../examples/#bordered-pulled">Bordered & Pulled</a></li> <li><a href="../examples/#buttons">Buttons</a></li> <li><a href="../examples/#button-groups">Button Groups</a></li> <li><a href="../examples/#button-dropdowns">Button Dropdowns</a></li> <li><a href="../examples/#bulleted-lists">Bulleted Lists</a></li> <li><a href="../examples/#navigation">Navigation</a></li> <li><a href="../examples/#form-inputs">Form Inputs</a></li> <li><a href="../examples/#animated-spinner">Animated Spinner</a></li> <li><a href="../examples/#rotated-flipped">Rotated &amp; Flipped</a></li> <li><a href="../examples/#stacked">Stacked</a></li> <li><a href="../examples/#custom">Custom CSS</a></li> </ul> </li> <li><a href="../whats-new/"> <span class="hidden-tablet">What's </span>New</a> </li> <li><a href="../community/">Community</a></li> <li class="active"><a href="../license/">License</a></li> </ul> <ul class="nav pull-right"> <li><a href="http://blog.fontawesome.io">Blog</a></li> </ul> </div> </div> </div> </div> <div class="jumbotron jumbotron-ad hidden-print"> <div class="container"> <h1><i class="icon-legal icon-large"></i>&nbsp; License</h1> <p>The full details of how Font Awesome is licensed</p> </div> </div> <div id="social-buttons" class="hidden-print"> <div class="container"> <ul class="unstyled inline"> <li> <iframe class="github-btn" src="http://ghbtns.com/github-btn.html?user=FortAwesome&repo=Font-Awesome&type=watch&count=true" allowtransparency="true" frameborder="0" scrolling="0" width="100px" height="20px"></iframe> </li> <li> <iframe class="github-btn" src="http://ghbtns.com/github-btn.html?user=FortAwesome&repo=Font-Awesome&type=fork&count=true" allowtransparency="true" frameborder="0" scrolling="0" width="102px" height="20px"></iframe> </li> <li class="follow-btn"> <a href="https://twitter.com/fontawesome" class="twitter-follow-button" data-link-color="#0069D6" data-show-count="true">Follow @fontawesome</a> </li> <li class="tweet-btn hidden-phone"> <a href="https://twitter.com/share" class="twitter-share-button" data-url="http://fontawesome.io" data-text="Font Awesome, the iconic font designed for Bootstrap" data-counturl="http://fortawesome.github.com/Font-Awesome/" data-count="horizontal" data-via="fontawesome" data-related="davegandy:Creator of Font Awesome">Tweet</a> </li> </ul> </div> </div> <div class="container"> <section class="hidden-print"> <div class="row stripe-ad"> <div class="span8"> <p class="lead"> Font Awesome is fully open source and is GPL compatible. You can use it for commercial projects, open source projects, or really just about whatever you want. </p> </div> <div class="span4"> <div id="carbonads-container"><div class="carbonad"><div id="azcarbon"></div><script type="text/javascript">var z = document.createElement("script"); z.type = "text/javascript"; z.async = true; z.src = "http://engine.carbonads.com/z/32291/azcarbon_2_1_0_HORIZ"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s);</script></div></div> </div> </div> </section> <div> <div class="alert alert-info"> <ul class="icons-ul margin-bottom-none"> <li> <i class="icon-li icon-info-sign icon-large"></i>Attribution is no longer required as of Font Awesome 3.0 but is much appreciated: "Font Awesome by Dave Gandy - http://fontawesome.io". </li> </ul> </div> </div> <section> <h2 class="page-header">Font License</h2> <ul> <li> Applies to all desktop and webfont files in the following directory: <code>font-awesome/font/</code>. </li> <li>License: SIL OFL 1.1</li> <li>URL: <a href="http://scripts.sil.org/OFL">http://scripts.sil.org/OFL</a></li> </ul> </section> <section> <h2 class="page-header">Code License</h2> <ul> <li> Applies to all CSS and LESS files in the following directories: <code>font-awesome/css/</code> and <code>font-awesome/less/</code>. </li> <li>License: MIT License</li> <li>URL: <a href="http://opensource.org/licenses/mit-license.html">http://opensource.org/licenses/mit-license.html</a></li> </ul> </section> <section> <h2 class="page-header">Documentation License</h2> <ul> <li>Applies to all Font Awesome project files that are not a part of the Font or Code licenses.</li> <li>License: CC BY 3.0</li> <li>URL: <a href="http://creativecommons.org/licenses/by/3.0/">http://creativecommons.org/licenses/by/3.0/</a></li> </ul> </section> <section> <h2 class="page-header">Brand Icons</h2> <ul class="margin-bottom-none"> <li>All brand icons are trademarks of their respective owners.</li> <li>The use of these trademarks does not indicate endorsement of the trademark holder by Font Awesome, nor vice versa.</li> </ul> </section> </div> <div class="push"><!-- necessary for sticky footer --></div> </div> <footer class="footer hidden-print"> <div class="container text-center"> <div> <i class="icon-flag"></i> Font Awesome 3.2.1 <span class="hidden-phone">&middot;</span><br class="visible-phone"> Created and Maintained by <a href="http://twitter.com/davegandy">Dave Gandy</a> </div> <div> Font Awesome licensed under <a href="http://scripts.sil.org/OFL">SIL OFL 1.1</a> <span class="hidden-phone">&middot;</span><br class="visible-phone"> Code licensed under <a href="http://opensource.org/licenses/mit-license.html">MIT License</a> <span class="hidden-phone hidden-tablet">&middot;</span><br class="visible-phone visible-tablet"> Documentation licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a> </div> <div> Thanks to <a href="http://maxcdn.com"><i class="icon-maxcdn"></i> MaxCDN</a> for providing the excellent <a href="http://www.bootstrapcdn.com/#tab_fontawesome">BootstrapCDN for Font Awesome</a> </div> <div class="project"> <a href="https://github.com/FortAwesome/Font-Awesome">GitHub Project</a> &middot; <a href="https://github.com/FortAwesome/Font-Awesome/issues">Issues</a> </div> </div> </footer> <script src="http://platform.twitter.com/widgets.js"></script> <script src="../assets/js/jquery-1.7.1.min.js"></script> <script src="../assets/js/ZeroClipboard-1.1.7.min.js"></script> <script src="../assets/js/bootstrap-2.3.1.min.js"></script> <script src="../assets/js/site.js"></script> </body> </html>
using System; using System.Text.RegularExpressions; using System.CodeDom.Compiler; using System.IO; using System.Reflection; namespace Backend { /// <summary> /// Operation compiler. /// </summary> public static class OperationCompiler { /// <summary> /// Compiles a mathematical operation given by a string and constrained by the available parameters. /// </summary> /// <returns>The operation.</returns> /// <param name="func">The arithmetic expression</param> /// <param name="parameterNames">Array of all parameter by name</param> public static Func<double[],double> CompileOperation (string func, string[] parameterNames) { //the blueprint for the class, wich will be compiled string tobecompiled = @"using System; public class DynamicClass { public static double Main(double[] parameters) { try{ return ( function ); } catch(Exception e) { Console.Error.WriteLine(e); } return double.NaN; } }"; //replace parameternames with representation in the array int pos = 0; // func = func.Replace ("A", ""); // func = func.Replace ("a", ""); foreach (string s in parameterNames) { var value = s.Replace (" ", ""); func = func.Replace (value, "parameters[" + pos + "]"); pos++; } //add a fored conversion to double, after each operator //this is because of the way c# handles values without floating points var parts = Regex.Split (func, @"(?<=[+,-,*,/])"); func = @"(double)" + parts [0]; for (int i = 1; i < parts.Length; i++) { func += @"(double)" + parts [i]; } tobecompiled = tobecompiled.Replace ("function", func); var provider = CodeDomProvider.CreateProvider ("c#"); var options = new CompilerParameters (); var assemblyContainingNotDynamicClass = Path.GetFileName (Assembly.GetExecutingAssembly ().Location); options.ReferencedAssemblies.Add (assemblyContainingNotDynamicClass); var results = provider.CompileAssemblyFromSource (options, new[] { tobecompiled }); //if there were no errors while compiling if (results.Errors.Count > 0) { #if DEBUG foreach (var error in results.Errors) { Console.WriteLine (error); } #endif } else { //extract class and method var t = results.CompiledAssembly.GetType ("DynamicClass"); return (Func<double[],double>)Delegate.CreateDelegate (typeof(Func<double[],double>), t.GetMethod ("Main")); } return null; } } }
module Kissable VERSION = "1.0.1" end
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("circle", { cx: "7.2", cy: "14.4", r: "3.2" }), h("circle", { cx: "14.8", cy: "18", r: "2" }), h("circle", { cx: "15.2", cy: "8.8", r: "4.8" })), 'BubbleChart');
import UtilMath = require('./UtilMath'); import Timer = require('./Timer'); import Browser = require('./Browser'); import BaserElement = require('./BaserElement'); import AlignedBoxes = require('./AlignedBoxes'); import BackgroundContainer = require('./BackgroundContainer'); import Checkbox = require('./Checkbox'); import Radio = require('./Radio'); import Select = require('./Select'); import Scroll = require('./Scroll'); import GoogleMaps = require('./GoogleMaps'); import YouTube = require('./YouTube'); import BreakPointsOption = require('../Interface/BreakPointsOption'); import BackgroundContainerOption = require('../Interface/BackgroundContainerOption'); import AlignedBoxCallback = require('../Interface/AlignedBoxCallback'); import CheckableElementOption = require('../Interface/CheckableElementOption'); import SelectOption = require('../Interface/SelectOption'); import ScrollOptions = require('../Interface/ScrollOptions'); import GoogleMapsOption = require('../Interface/GoogleMapsOption'); import YouTubeOption = require('../Interface/YouTubeOption'); class JQueryAdapter { public static bcScrollTo (selector: any, options?: ScrollOptions): void { const scroll: Scroll = new Scroll(); scroll.to(selector, options); } /** * 自信の要素を基準に、指定の子要素を背景のように扱う * * TODO: BaserElement化する * * CSSの`background-size`の`contain`と`cover`の振る舞いに対応 * * 基準も縦横のセンター・上下・左右に指定可能 * * @version 0.11.0 * @since 0.0.9 * @param {Object} options オプション * * * * * * * ## Sample * * ### Target HTML * * ```html * <div class="sample" data-id="rb0zOstIiyU" data-width="3840" data-height="2160"></div> * ``` * * ### Execute * * ```js * $('.sample').bcYoutube().find('iframe').bcKeepAspectRatio(); * ``` * * ### Result * * comming soon... * */ public bcBackground (options: BackgroundContainerOption): JQuery { const self: JQuery = $(this); return self.each( (i: number, elem: HTMLElement): void => { /* tslint:disable */ new BackgroundContainer(elem, options); /* tslint:enable */ }); } /** * 要素の高さを揃える * * @version 0.7.0 * @since 0.0.15 * */ public bcBoxAlignHeight (columnOrKeyword: string | number | BreakPointsOption<number> = 0, detailTarget?: string, callback?: AlignedBoxCallback): JQuery { const self: JQuery = $(this); if (typeof columnOrKeyword === 'string') { const keyword: string = columnOrKeyword; switch (keyword) { case 'destroy': { const boxes: AlignedBoxes = <AlignedBoxes> self.data(AlignedBoxes.DATA_KEY); boxes.destroy(); break; } default: { // void } } } else { const column: number | BreakPointsOption<number> = columnOrKeyword; // 要素群の高さを揃え、setsに追加 if (detailTarget) { const $detailTarget: JQuery = self.find(detailTarget); if ($detailTarget.length) { self.each(function () { const $split: JQuery = $(this).find(detailTarget); /* tslint:disable */ new AlignedBoxes($split, column, callback); /* tslint:enable */ }); } } else { /* tslint:disable */ new AlignedBoxes(self, column, callback); /* tslint:enable */ } } return self; } // @version 0.12.1 // @since 0.1.0 public bcBoxLink (): JQuery { return $(this).on('click', function (e: JQueryEventObject): void { const $elem: JQuery = $(this); const $link: JQuery = $elem.find('a, area').eq(0); const href: string = $link.prop('href'); if ($link.length && href) { const isBlank: boolean = $link.prop('target') === '_blank'; Browser.jumpTo(href, isBlank); e.preventDefault(); } }); } /** * WAI-ARIAに対応した装飾可能な汎用要素でラップしたチェックボックスに変更する * * @version 0.9.0 * @since 0.0.1 * * * * * * * ## Sample * * comming soon... * */ public bcCheckbox (options: CheckableElementOption): JQuery { const self: JQuery = $(this); return self.each( (i: number, elem: HTMLInputElement): void => { if (elem.nodeName === 'INPUT') { /* tslint:disable */ new Checkbox(elem, options); /* tslint:enable */ } else if ('console' in window) { console.warn('TypeError: A Node is not HTMLInputElement'); } }); } /** * WAI-ARIAに対応した装飾可能な汎用要素でラップしたラジオボタンに変更する * * @version 0.9.0 * @since 0.0.1 * * * * * * * ## Sample * * comming soon... * */ public bcRadio (options: CheckableElementOption): JQuery { const self: JQuery = $(this); return self.each( (i: number, elem: HTMLInputElement): void => { if (elem.nodeName === 'INPUT') { /* tslint:disable */ new Radio(elem, options); /* tslint:enable */ } else if ('console' in window) { console.warn('TypeError: A Node is not HTMLInputElement'); } }); } /** * WAI-ARIAに対応した装飾可能な汎用要素でラップしたセレクトボックスに変更する * * @version 0.9.2 * @since 0.0.1 * * * * * * * ## Sample * * comming soon... * */ public bcSelect (options: string | SelectOption): JQuery { const self: JQuery = $(this); return self.each( (i: number, elem: HTMLSelectElement): void => { const $elem: JQuery = $(elem); if (typeof options === 'string') { switch (options) { case 'update': { const select: Select = <Select> $elem.data('bc-element'); select.update(); break; } default: { // void } } } else if (elem.nodeName === 'SELECT') { /* tslint:disable */ new Select(elem, options); /* tslint:enable */ } else if ('console' in window) { console.warn('TypeError: A Node is not HTMLSelectElement'); } }); } /** * 要素内の画像の読み込みが完了してからコールバックを実行する * * @version 0.9.0 * @since 0.0.9 * * * * * * * ## Sample * * comming soon... * */ public bcImageLoaded (success: () => any, error?: (e: Event) => any): JQuery { const self: JQuery = $(this); return self.each( (i: number, elem: HTMLElement): void => { const $elem: JQuery = $(elem); const manifest: JQueryPromise<any>[] = []; const $imgs: JQuery = $elem.filter('img').add($elem.find('img')); if ($imgs.length) { $imgs.each(function (): void { const loaded: JQueryDeferred<any> = $.Deferred(); let img: HTMLImageElement = new Image(); img.onload = function (): any { loaded.resolve(); img.onload = null; // GC img = null; // GC }; img.onabort = img.onerror = function (e: Event): any { loaded.reject(e); img.onload = null; // GC img = null; // GC }; img.src = this.src; manifest.push(loaded.promise()); }); $.when.apply($, manifest).done( (): void => { success.call(elem); }).fail( (e: Event): void => { if (error) { error.call(elem, e); } }); } else { success.call(elem); } }); } /** * 親のコンテナ要素の幅に合わせて、自信の縦横比を保ったまま幅の変更に対応する * * iframeなどの縦横比を保ちたいが、幅を変更しても高さが変化しない要素などに有効 * * @version 0.0.9 * @since 0.0.9 * * * * * * * ## Sample * * ### Target HTML * * ```html * <div class="sample" data-id="rb0zOstIiyU" data-width="3840" data-height="2160"></div> * ``` * * ### Execute * * ```js * $('.sample').bcYoutube().find('iframe').bcKeepAspectRatio(); * ``` * * ### Result * * comming soon... * */ public bcKeepAspectRatio (): JQuery { const $w: JQuery = $(window); const self: JQuery = $(this); self.each( (i: number, elem: HTMLElement): void => { const $elem: JQuery = $(elem); const baseWidth: number = <number> +$elem.data('width'); const baseHeight: number = <number> +$elem.data('height'); const aspectRatio: number = baseWidth / baseHeight; $w.on('resize', (): void => { const width: number = $elem.width(); $elem.css({ width: '100%', height: width / aspectRatio, }); }).trigger('resize'); }); Timer.wait(30, () => { $w.trigger('resize'); }); return self; } /** * リンク要素からのアンカーまでスムーズにスクロールをさせる * * @version 0.1.0 * @since 0.0.8 * * * * * * * ## Sample * * comming soon... * */ public bcScrollTo (options?: ScrollOptions): JQuery { const self: JQuery = $(this); return self.on('click', function (e: JQueryMouseEventObject): void { const $this: JQuery = $(this); let href: string = $this.attr('href'); const scroll: Scroll = new Scroll(); if (href) { // キーワードを一番に優先する if (options && $.isPlainObject(options.keywords)) { for (const keyword in options.keywords) { if (options.keywords.hasOwnProperty(keyword)) { const target: string = options.keywords[keyword]; if (keyword === href) { scroll.to(target, options); e.preventDefault(); return; } } } } // 「/pathname/#hash」のリンクパターンの場合 // 「/pathname/」が現在のURLだった場合「#hash」に飛ばすようにする const absPath: string = $this.prop('href'); const currentReferer: string = location.protocol + '//' + location.host + location.pathname + location.search; href = absPath.replace(currentReferer, ''); // #top はHTML5ではページトップを意味する if (href === '#top') { scroll.to(0, options); e.preventDefault(); return; } // セレクタとして要素が存在する場合はその要素に移動 // 「/」で始まるなどセレクターとして不正な場合、例外を投げることがあるので無視する try { const target: JQuery = $(href); if (target.length) { scroll.to(target, options); e.preventDefault(); return; } } catch (err) { /* void */ } } return; }); } /** * リストを均等に分割する * * @version 0.2.0 * @since 0.0.14 * */ public bcSplitList (columnSize: number, options: any): JQuery { const self: JQuery = $(this); const CLASS_NAME: string = 'splited-list'; const CLASS_NAME_NTH: string = 'nth'; const CLASS_NAME_ITEM: string = 'item'; const config: any = $.extend( { dataKey: '-bc-split-list-index', splitChildren: true, }, options, ); self.each( (index: number, elem: HTMLElement): void => { const $container: JQuery = $(elem); const $list: JQuery = $container.find('>ul'); let $items: JQuery; if (!config.splitChildren) { // 直下のliのみ取得 $items = $list.find('>li').detach(); } else { // 入れ子のliも含めて全て取得 $items = $list.find('li').detach(); // 入れ子のulの削除 $items.find('ul').remove(); } // リストアイテムの総数 const size: number = $items.length; const splited: number[] = UtilMath.split(size, columnSize); const itemArray: HTMLElement[] = $items.toArray(); for (let i: number = 0; i < columnSize; i++) { const sizeByColumn: number = splited[i]; const $col: JQuery = $('<ul></ul>'); BaserElement.addClassTo($col, CLASS_NAME); BaserElement.addClassTo($col, CLASS_NAME, '', CLASS_NAME_NTH + columnSize); $col.appendTo($container); for (let j: number = 0; j < sizeByColumn; j++) { const $item: JQuery = $(itemArray.shift()); $item.appendTo($col); $item.data(config.dataKey, i); BaserElement.addClassTo($item, CLASS_NAME, CLASS_NAME_ITEM); BaserElement.addClassTo($item, CLASS_NAME, CLASS_NAME_ITEM, CLASS_NAME_NTH + i); } } $list.remove(); }); return self; } /** * マウスオーバー時に一瞬透明になるエフェクトをかける * * @version 0.0.14 * @since 0.0.14 * */ public bcWink (options: any): JQuery { const self: JQuery = $(this); const config: any = $.extend( { close: 50, open: 200, opacity: 0.4, target: null, stopOnTouch: true, }, options, ); self.each( (i: number, elem: HTMLElement): void => { const $this: JQuery = $(elem); let $target: JQuery; if (config.target) { $target = $this.find(config.target); } else { $target = $this; } $this.on('mouseenter', (e: JQueryEventObject): boolean => { if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) { $this.data('-bc-is-touchstarted', false); return true; } $target .stop(true, false) .fadeTo(config.close, config.opacity) .fadeTo(config.open, 1); return true; }); if (config.stopOnTouch) { $this.on('touchstart', (e: JQueryEventObject): boolean => { $this.data('-bc-is-touchstarted', true); return true; }); } }); return self; } /** * マップを埋め込む * * 現在の対応はGoogleMapsのみ * * @version 0.9.0 * @since 0.0.8 * * * * * * * ## Sample * * ### Target HTML * * ```html * <div class="sample" data-lat="33.606785" data-lng="130.418314"></div> * ``` * * ### Execute * * ```js * $('.sample').bcMaps(); * ``` * * ### Result * * comming soon... * */ public bcMaps (options?: GoogleMapsOption): JQuery { const self: JQuery = $(this); return self.each( (i: number, elem: HTMLElement): void => { const $elem: JQuery = $(elem); const data: GoogleMaps = $elem.data(GoogleMaps.className); if (data) { data.reload(options); } else { /* tslint:disable */ new GoogleMaps(elem, options); /* tslint:enable */ } }); } /** * YouTubeを埋め込む * * @version 0.9.0 * @since 0.0.8 * * * * * * * ## Sample * * ### Target HTML * * ```html * <div class="sample" data-id="rb0zOstIiyU" data-width="720" data-height="480"></div> * ``` * * ### Execute * * ```js * $('.sample').bcYoutube(); * ``` * */ public bcYoutube (options?: YouTubeOption): JQuery { const self: JQuery = $(this); return self.each( (i: number, elem: HTMLElement): void => { const $elem: JQuery = $(elem); const data: YouTube = $elem.data(YouTube.className); if (data) { data.reload(options); } else { /* tslint:disable */ new YouTube(elem, options); /* tslint:enable */ } }); } /** * マウスオーバー時に画像を切り替える * * 【使用非推奨】できるかぎり CSS の `:hover` と `background-image` を使用するべきです。 * * @deprecated * @version 0.0.15 * @since 0.0.15 * */ public bcRollover (options: any): JQuery { const self: JQuery = $(this); const config: any = $.extend( { pattern: /_off(\.(?:[a-z0-9]{1,6}))$/i, replace: '_on$1', dataPrefix: '-bc-rollover-', ignore: '', filter: null, stopOnTouch: true, }, options, ); const dataKeyOff: string = config.dataPrefix + 'off'; const dataKeyOn: string = config.dataPrefix + 'on'; self.each( (i: number, elem: HTMLElement): void => { const nodeName: string = elem.nodeName.toLowerCase(); const $img: JQuery = $(elem).not(config.ignore); if ($img.length && nodeName === 'img' || (nodeName === 'input' && $img.prop('type') === 'image')) { let avail: boolean = true; if ($.isFunction(config.filter)) { avail = !!config.filter.call(elem); } else if (config.filter) { avail = !!$img.filter(config.filter).length; } if (avail) { const src: string = $img.attr('src'); if (src.match(config.pattern)) { const onSrc: string = src.replace(config.pattern, config.replace); $img.data(dataKeyOff, src); $img.data(dataKeyOn, onSrc); } } } }); self.on('mouseenter', function (e: JQueryEventObject): boolean { const $this: JQuery = $(this); if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) { $this.data('-bc-is-touchstarted', false); return true; } const onSrc: string = <string> $this.data(dataKeyOn); $this.prop('src', onSrc); return true; }); self.on('mouseleave', function (e: JQueryEventObject): boolean { const $this: JQuery = $(this); if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) { $this.data('-bc-is-touchstarted', false); return true; } const offSrc: string = <string> $this.data(dataKeyOff); $this.prop('src', offSrc); return true; }); if (config.stopOnTouch) { self.on('touchstart', function (e: JQueryEventObject): boolean { const $this: JQuery = $(this); $this.data('-bc-is-touchstarted', true); return true; }); } return self; } /** * マウスオーバー時に半透明になるエフェクトをかける * * 【使用非推奨】できるかぎり CSS の `:hover` と `opacity`、そして `transition` を使用するべきです。 * * @deprecated * @version 0.0.15 * @since 0.0.15 * */ public bcShy (options: any): JQuery { const self: JQuery = $(this); const config: any = $.extend( { close: 300, open: 300, opacity: 0.6, target: null, stopOnTouch: true, }, options, ); self.each( (i: number, elem: HTMLElement): void => { const $this: JQuery = $(elem); let $target: JQuery; if (config.target) { $target = $this.find(config.target); } else { $target = $this; } $this.on('mouseenter', (e: JQueryEventObject): boolean => { if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) { $this.data('-bc-is-touchstarted', false); return true; } $target .stop(true, false) .fadeTo(config.close, config.opacity); return true; }); $this.on('mouseleave', (e: JQueryEventObject): boolean => { if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) { $this.data('-bc-is-touchstarted', false); return true; } $target .stop(true, false) .fadeTo(config.open, 1); return true; }); if (config.stopOnTouch) { $this.on('touchstart', (e: JQueryEventObject): boolean => { $this.data('-bc-is-touchstarted', true); return true; }); } }); return self; } } export = JQueryAdapter;
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) 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. */ package org.spongepowered.common.registry.type.world.gen; import net.minecraft.block.BlockLeaves; import net.minecraft.block.BlockOldLeaf; import net.minecraft.block.BlockOldLog; import net.minecraft.block.BlockPlanks; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.gen.feature.WorldGenBigTree; import net.minecraft.world.gen.feature.WorldGenBirchTree; import net.minecraft.world.gen.feature.WorldGenCanopyTree; import net.minecraft.world.gen.feature.WorldGenMegaJungle; import net.minecraft.world.gen.feature.WorldGenMegaPineTree; import net.minecraft.world.gen.feature.WorldGenSavannaTree; import net.minecraft.world.gen.feature.WorldGenShrub; import net.minecraft.world.gen.feature.WorldGenSwamp; import net.minecraft.world.gen.feature.WorldGenTaiga1; import net.minecraft.world.gen.feature.WorldGenTaiga2; import net.minecraft.world.gen.feature.WorldGenTrees; import net.minecraft.world.gen.feature.WorldGenerator; import org.spongepowered.api.registry.util.RegisterCatalog; import org.spongepowered.api.util.weighted.VariableAmount; import org.spongepowered.api.world.gen.PopulatorObject; import org.spongepowered.api.world.gen.type.BiomeTreeType; import org.spongepowered.api.world.gen.type.BiomeTreeTypes; import org.spongepowered.common.bridge.world.gen.WorldGenTreesBridge; import org.spongepowered.common.registry.type.AbstractPrefixAlternateCatalogTypeRegistryModule; import org.spongepowered.common.world.gen.type.SpongeBiomeTreeType; import javax.annotation.Nullable; @RegisterCatalog(BiomeTreeTypes.class) public class BiomeTreeTypeRegistryModule extends AbstractPrefixAlternateCatalogTypeRegistryModule<BiomeTreeType> { public BiomeTreeTypeRegistryModule() { super("minecraft"); } @Override public void registerDefaults() { register(create("oak", new WorldGenTrees(false), new WorldGenBigTree(false))); register(create("birch", new WorldGenBirchTree(false, false), new WorldGenBirchTree(false, true))); WorldGenMegaPineTree tall_megapine = new WorldGenMegaPineTree(false, true); WorldGenMegaPineTree megapine = new WorldGenMegaPineTree(false, false); register(create("tall_taiga", new WorldGenTaiga2(false), tall_megapine)); register(create("pointy_taiga", new WorldGenTaiga1(), megapine)); IBlockState jlog = Blocks.LOG.getDefaultState() .withProperty(BlockOldLog.VARIANT, BlockPlanks.EnumType.JUNGLE); IBlockState jleaf = Blocks.LEAVES.getDefaultState() .withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE) .withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); IBlockState leaf = Blocks.LEAVES.getDefaultState() .withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE) .withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); WorldGenTreesBridge trees = (WorldGenTreesBridge) new WorldGenTrees(false, 4, jlog, jleaf, true); trees.bridge$setMinHeight(VariableAmount.baseWithRandomAddition(4, 7)); WorldGenMegaJungle mega = new WorldGenMegaJungle(false, 10, 20, jlog, jleaf); register(create("jungle", (WorldGenTrees) trees, mega)); WorldGenShrub bush = new WorldGenShrub(jlog, leaf); register(create("jungle_bush", bush, null)); register(create("savanna", new WorldGenSavannaTree(false), null)); register(create("canopy", new WorldGenCanopyTree(false), null)); register(create("swamp", new WorldGenSwamp(), null)); } private SpongeBiomeTreeType create(String name, WorldGenerator small, @Nullable WorldGenerator large) { return new SpongeBiomeTreeType("minecraft:" + name, name, (PopulatorObject) small, (PopulatorObject) large); } }
var Nightmare = require('nightmare') var NTU = require('./NightmareTestUtils') const NounPhraseTest = (nightmare, delay) => { return nightmare // Can I open the addedit form and make it go away by clicking cancel? .click('#add-np').wait(delay) .click('#np-addedit-form #cancel').wait(delay) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) // If I open the addedit form, enter and a save a noun, // will the form then go away and can I see the insertNounPhraseCheck mark in the quiz? /*.then( res => { return nightmare .click('#add-np').wait(delay) .type('#base', 'carrot').wait(delay) .click('#save-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#insertNounPhraseCheck', true)}) // Can I open the addedit form via editing and make it go away by clicking cancel? .then( res => { return nightmare .click('#id1').wait(delay) .click('#cancel').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) // If I open the addedit form via editing, change and a save a noun, // will the form then go away and can I see the updateNounPhraseCheck mark in the quiz? .then( res => { return nightmare .click('#id1').wait(delay) .type('#base', 'beaver').wait(delay) .click('#save-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#updateNounPhraseCheck', true)}) // If I open the addedit form via editing and delete the noun, // will the form then go away and can I see the deleteNounPhraseCheck mark in the quiz? .then( res => { return nightmare .click('#id1').wait(delay) .click('#delete-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#deleteNounPhraseCheck', true)}) //.then( res => {return NTU.lookFor(nightmare, '#quiz', false)}) .then( res => { return nightmare .click('#add-np').wait(delay) .type('#base', 'carrot').wait(delay) .click('#save-np').wait(delay) })*/ // Can I see the examples button? //.then( res => {return NTU.lookFor(nightmare, '#examples', true)}) // Does it go away after I click it? //.then( res => {return nightmare.click('#examples')}) //.then( res => {return NTU.lookFor(nightmare, '#examples', false)}) } module.exports = NounPhraseTest
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../image/favicon.ico"> <title>生活缴费 - 宿舍管理系统</title> <link href="../css/bootstrap.min.css" rel="stylesheet"> <link href="../css/student.css" rel="stylesheet"> <style> .table tbody tr td { vertical-align: middle; } </style> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">学生宿舍管理系统</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="info_student.html"><span class="glyphicon glyphicon-user"></span> 何铭宜 同学</a></li> <li><a href="#">注销</a></li> </ul> </div> </div> </nav> <div class="container-fluid"> <div class="row"> <div class="col-sm-3 col-md-2 col-xs-3 sidebar" id="side"> <ul class="nav nav-sidebar"> <li> <a href="index.html">宿舍退调申请</a> </li> <li> <a href="repair.html">宿舍设施报修申请</a> </li> <li class="active"> <a href="payment.html">生活缴费</a> </li> <li> <a href="resource.html">宿舍资源申请</a> </li> <li> <a href="meeting.html">研讨室申请</a> </li> <li> <a href="activity.html">社区活动申请</a> </li> <li> <a href="book.html">共享书屋<span class="sr-only">(current)</span></a> </li> </ul> </div> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h1 class="page-header"> 生活缴费 </h1> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"> <a href="#record" aria-controls="record" role="tab" data-toggle="tab">用费记录</a> </li> <li role="presentation"> <a href="#pay_record" aria-controls="pay_record" role="tab" data-toggle="tab">缴费记录</a> </li> </ul> <div class="tab-content" style="margin-top: 10px"> <div role="tabpanel" class="tab-pane active" id="record"> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>用费单号</th> <th>宿舍地址</th> <th>缴费项目</th> <th>费用</th> <th>计量区间</th> <th>是否缴费</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td>#123123123</td> <td>东莞 422D</td> <td>空调</td> <td>三蚊鸡</td> <td>2017年4月11日-5月41日3分</td> <td><span class="label label-danger">未缴费</span></td> <td> <button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#pay">缴费</button> </td> </tr> <tr> <td>#123123123</td> <td>弘毅 411C</td> <td>空调</td> <td>五百万</td> <td>2017年4月11日-5月41日3分</td> <td><span class="label label-success">已缴费</span></td> <td> <button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#pay">缴费</button> </td> </tr> </tbody> </table> <div class="pull-right"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="active"><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </div> <!-- ./pagination --> </div> </div> <!-- /.tab-pane --> <div role="tabpanel" class="tab-pane" id="pay_record"> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>用费单号</th> <th>宿舍地址</th> <th>缴费项目</th> <th>费用</th> <th>计量区间</th> <th>学生学号</th> </tr> </thead> <tbody> <tr> <td>#123123123</td> <td>东莞 422D</td> <td>空调</td> <td>三蚊鸡</td> <td>2017年4月11日-5月41日3分</td> <td>2014101027</td> </tr> <tr> <td>#123123123</td> <td>弘毅 411C</td> <td>空调</td> <td>五百万</td> <td>2017年4月11日-5月41日3分</td> <td>2014101027</td> </tr> </tbody> </table> </div> <div class="pull-right"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="active"><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </div> <!-- ./pagination --> </div> <!-- /.tab-pane --> </div> </div> </div> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="../js/jquery-2.2.1.min.js"></script> <script src="../js/bootstrap.min.js"></script> <!-- Just to make our placeholder images work. Don't actually copy the next line! --> <script src="../js/holder.min.js"></script> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>V8 API Reference Guide for node.js v8.9.2: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v8.9.2 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1ExtensionConfiguration.html">ExtensionConfiguration</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::ExtensionConfiguration Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>begin</b>() const (defined in <a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a>)</td><td class="entry"><a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>end</b>() const (defined in <a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a>)</td><td class="entry"><a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ExtensionConfiguration</b>() (defined in <a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a>)</td><td class="entry"><a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ExtensionConfiguration</b>(int name_count, const char *names[]) (defined in <a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a>)</td><td class="entry"><a class="el" href="classv8_1_1ExtensionConfiguration.html">v8::ExtensionConfiguration</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
<?php namespace Soga\NominaBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table(name="trasladoeps") * @ORM\Entity(repositoryClass="Soga\NominaBundle\Repository\TrasladoEpsRepository") */ class TrasladoEps { /** * @ORM\Id * @ORM\Column(name="id", type="integer") */ private $id; /** * @ORM\Column(name="cedemple", type="string", length=15, nullable=false) */ private $cedemple; /** * @ORM\Column(name="codigo_eps_actual_fk", type="integer") */ private $codigoEpsActualFk; /** * @ORM\Column(name="codigo_eps_nueva_fk", type="integer") */ private $codigoEpsNuevaFk; /** * @ORM\Column(name="fecha_inicio_traslado", type="date", nullable=true) */ private $fechaInicioTraslado; /** * @ORM\Column(name="fecha_aplicacion_traslado", type="date", nullable=true) */ private $fechaAplicacionTraslado; /** * Set id * * @param integer $id * @return TrasladoEps */ public function setId($id) { $this->id = $id; return $this; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set cedemple * * @param string $cedemple * @return TrasladoEps */ public function setCedemple($cedemple) { $this->cedemple = $cedemple; return $this; } /** * Get cedemple * * @return string */ public function getCedemple() { return $this->cedemple; } /** * Set codigoEpsActualFk * * @param integer $codigoEpsActualFk * @return TrasladoEps */ public function setCodigoEpsActualFk($codigoEpsActualFk) { $this->codigoEpsActualFk = $codigoEpsActualFk; return $this; } /** * Get codigoEpsActualFk * * @return integer */ public function getCodigoEpsActualFk() { return $this->codigoEpsActualFk; } /** * Set codigoEpsNuevaFk * * @param integer $codigoEpsNuevaFk * @return TrasladoEps */ public function setCodigoEpsNuevaFk($codigoEpsNuevaFk) { $this->codigoEpsNuevaFk = $codigoEpsNuevaFk; return $this; } /** * Get codigoEpsNuevaFk * * @return integer */ public function getCodigoEpsNuevaFk() { return $this->codigoEpsNuevaFk; } /** * Set fechaInicioTraslado * * @param \DateTime $fechaInicioTraslado * @return TrasladoEps */ public function setFechaInicioTraslado($fechaInicioTraslado) { $this->fechaInicioTraslado = $fechaInicioTraslado; return $this; } /** * Get fechaInicioTraslado * * @return \DateTime */ public function getFechaInicioTraslado() { return $this->fechaInicioTraslado; } /** * Set fechaAplicacionTraslado * * @param \DateTime $fechaAplicacionTraslado * @return TrasladoEps */ public function setFechaAplicacionTraslado($fechaAplicacionTraslado) { $this->fechaAplicacionTraslado = $fechaAplicacionTraslado; return $this; } /** * Get fechaAplicacionTraslado * * @return \DateTime */ public function getFechaAplicacionTraslado() { return $this->fechaAplicacionTraslado; } }
<!doctype html> <html> <head> <title>400</title> <link rel="shortcut icon" href="/static/img/favicon.ico" type="image/x-icon"/> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name="format-detection" content="telephone=no"/> <meta name="robots" content="noindex, nofollow"/> <link href="/static/css/0-normalize.min.css" rel="stylesheet" type="text/css"/> <link href="/static/css/2-main.css" rel="stylesheet" type="text/css"/> </head> <body> <div class="page-wrap"> <div class="page"> <div class="error-text">400<div class="error-text-under">Go <a href="/">Home</a></div></div> </div> </div> </body> </html>
import { UIPanel, UIRow, UIHorizontalRule } from './libs/ui.js'; import { AddObjectCommand } from './commands/AddObjectCommand.js'; import { RemoveObjectCommand } from './commands/RemoveObjectCommand.js'; import { MultiCmdsCommand } from './commands/MultiCmdsCommand.js'; import { SetMaterialValueCommand } from './commands/SetMaterialValueCommand.js'; function MenubarEdit( editor ) { var strings = editor.strings; var container = new UIPanel(); container.setClass( 'menu' ); var title = new UIPanel(); title.setClass( 'title' ); title.setTextContent( strings.getKey( 'menubar/edit' ) ); container.add( title ); var options = new UIPanel(); options.setClass( 'options' ); container.add( options ); // Undo var undo = new UIRow(); undo.setClass( 'option' ); undo.setTextContent( strings.getKey( 'menubar/edit/undo' ) ); undo.onClick( function () { editor.undo(); } ); options.add( undo ); // Redo var redo = new UIRow(); redo.setClass( 'option' ); redo.setTextContent( strings.getKey( 'menubar/edit/redo' ) ); redo.onClick( function () { editor.redo(); } ); options.add( redo ); // Clear History var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/clear_history' ) ); option.onClick( function () { if ( confirm( 'The Undo/Redo History will be cleared. Are you sure?' ) ) { editor.history.clear(); } } ); options.add( option ); editor.signals.historyChanged.add( function () { var history = editor.history; undo.setClass( 'option' ); redo.setClass( 'option' ); if ( history.undos.length == 0 ) { undo.setClass( 'inactive' ); } if ( history.redos.length == 0 ) { redo.setClass( 'inactive' ); } } ); // --- options.add( new UIHorizontalRule() ); // Clone var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/clone' ) ); option.onClick( function () { var object = editor.selected; if ( object.parent === null ) return; // avoid cloning the camera or scene object = object.clone(); editor.execute( new AddObjectCommand( editor, object ) ); } ); options.add( option ); // Delete var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/delete' ) ); option.onClick( function () { var object = editor.selected; if ( object !== null && object.parent !== null ) { editor.execute( new RemoveObjectCommand( editor, object ) ); } } ); options.add( option ); // Minify shaders var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/minify_shaders' ) ); option.onClick( function () { var root = editor.selected || editor.scene; var errors = []; var nMaterialsChanged = 0; var path = []; function getPath( object ) { path.length = 0; var parent = object.parent; if ( parent !== undefined ) getPath( parent ); path.push( object.name || object.uuid ); return path; } var cmds = []; root.traverse( function ( object ) { var material = object.material; if ( material !== undefined && material.isShaderMaterial ) { try { var shader = glslprep.minifyGlsl( [ material.vertexShader, material.fragmentShader ] ); cmds.push( new SetMaterialValueCommand( editor, object, 'vertexShader', shader[ 0 ] ) ); cmds.push( new SetMaterialValueCommand( editor, object, 'fragmentShader', shader[ 1 ] ) ); ++ nMaterialsChanged; } catch ( e ) { var path = getPath( object ).join( "/" ); if ( e instanceof glslprep.SyntaxError ) errors.push( path + ":" + e.line + ":" + e.column + ": " + e.message ); else { errors.push( path + ": Unexpected error (see console for details)." ); console.error( e.stack || e ); } } } } ); if ( nMaterialsChanged > 0 ) { editor.execute( new MultiCmdsCommand( editor, cmds ), 'Minify Shaders' ); } window.alert( nMaterialsChanged + " material(s) were changed.\n" + errors.join( "\n" ) ); } ); options.add( option ); options.add( new UIHorizontalRule() ); // Set textures to sRGB. See #15903 var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/fixcolormaps' ) ); option.onClick( function () { editor.scene.traverse( fixColorMap ); } ); options.add( option ); var colorMaps = [ 'map', 'envMap', 'emissiveMap' ]; function fixColorMap( obj ) { var material = obj.material; if ( material !== undefined ) { if ( Array.isArray( material ) === true ) { for ( var i = 0; i < material.length; i ++ ) { fixMaterial( material[ i ] ); } } else { fixMaterial( material ); } editor.signals.sceneGraphChanged.dispatch(); } } function fixMaterial( material ) { var needsUpdate = material.needsUpdate; for ( var i = 0; i < colorMaps.length; i ++ ) { var map = material[ colorMaps[ i ] ]; if ( map ) { map.encoding = THREE.sRGBEncoding; needsUpdate = true; } } material.needsUpdate = needsUpdate; } return container; } export { MenubarEdit };
using System.Collections.Generic; using System.Threading; using LanguageExt; namespace SJP.Schematic.Core { public interface IDatabaseViewProvider { OptionAsync<IDatabaseView> GetView(Identifier viewName, CancellationToken cancellationToken = default); IAsyncEnumerable<IDatabaseView> GetAllViews(CancellationToken cancellationToken = default); } }
import React from 'react'; class Icon extends React.Component { constructor(props) { super(props); this.displayName = 'Icon'; this.icon = "fa " + this.props.icon + " " + this.props.size; } render() { return ( <i className={this.icon}></i> ); } } export default Icon;
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"1":"8","2":"C D e K I N J"},C:{"1":"DB EB O GB HB","2":"0 1 2 3 4 5 7 9 gB BB F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB aB ZB"},D:{"1":"8 HB TB PB NB mB OB LB QB RB","2":"0 1 2 3 4 5 7 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB"},E:{"1":"6 C D p bB","2":"4 F L H G E A SB KB UB VB WB XB YB","132":"B"},F:{"1":"0 1 2 3 z","2":"5 6 7 E B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y cB dB eB fB p AB hB"},G:{"1":"D tB uB vB","2":"G KB iB FB kB lB MB nB oB pB qB rB","132":"sB"},H:{"2":"wB"},I:{"1":"O","2":"BB F xB yB zB 0B FB 1B 2B"},J:{"2":"H A"},K:{"2":"6 A B C M p AB"},L:{"1":"LB"},M:{"1":"O"},N:{"2":"A B"},O:{"2":"3B"},P:{"2":"F 4B 5B 6B 7B 8B"},Q:{"2":"9B"},R:{"2":"AC"},S:{"2":"BC"}},B:7,C:"CSS Environment Variables env()"};
import './init' import React from 'react' import ReactDom from 'react-dom' import Root from './root' import {APP_THEMES_LIGHT, APP_THEMES_DARK} from 'reducers/settings/constants' import LocalStorage from 'lib/localStorage' import {initializeStore} from './redux/store' import {initServiceWorker} from './swWindow' // render app const renderApp = (Component, appRoot, store) => { initServiceWorker(store) ReactDom.render( <Component store={store} />, appRoot, () => { // need to make this for feature tests - application ready for testing window.__isAppReady = true }) } const prepareStoreData = () => { let theme = LocalStorage.getItem('theme') if (!theme) { if (window.matchMedia('(prefers-color-scheme: dark)')?.matches) { theme = APP_THEMES_DARK } } return { settings: { theme: theme || APP_THEMES_LIGHT } } } // init store and start app const appRoot = document.getElementById('app-root') const store = initializeStore(prepareStoreData()) renderApp(Root, appRoot, store)
import pyak import yikbot import time # Latitude and Longitude of location where bot should be localized yLocation = pyak.Location("42.270340", "-83.742224") yb = yikbot.YikBot("yikBot", yLocation) print "DEBUG: Registered yikBot with handle %s and id %s" % (yb.handle, yb.id) print "DEBUG: Going to sleep, new yakkers must wait ~90 seconds before they can act" time.sleep(90) print "DEBUG: yikBot instance 90 seconds after initialization" print vars(yb) yb.boot()
A CMSViewDescription is a data structure to describe what information any CMSEmbeddedComponent shall contain and how it is supposed to be built. Instance Variables buttons: <OrderedCollection> generalStructure: <OrderedCollection> header: <String> tables: <OrderedCollection > traceDescription: <OrderedCollection> buttons - xxxxx generalStructure - the topics of the main box displayed at the top of each CMSEmbeddedComponent and its contents header - the header of the CMSEmbeddedComponent being displayed above all its content tables - all tables (each in an own box) being displayed at the CMSEmbeddedComponent. traceDescription - a String and a symbol describing what to show in the tracer and where to go when this part of the tracer is clicked.
/** * @author Kai Salmen / www.kaisalmen.de */ 'use strict'; if ( KSX.test.projectionspace === undefined ) KSX.test.projectionspace = {}; KSX.test.projectionspace.VerifyPP = (function () { PPCheck.prototype = Object.create(KSX.core.ThreeJsApp.prototype, { constructor: { configurable: true, enumerable: true, value: PPCheck, writable: true } }); function PPCheck(elementToBindTo, loader) { KSX.core.ThreeJsApp.call(this); this.configure({ name: 'PPCheck', htmlCanvas: elementToBindTo, useScenePerspective: true, loader: loader }); this.controls = null; this.projectionSpace = new KSX.instancing.ProjectionSpace({ low: { index: 0, name: 'Low', x: 240, y: 100, defaultHeightFactor: 9, mesh: null }, medium: { index: 1, name: 'Medium', x: 720, y: 302, defaultHeightFactor: 18, mesh: null } }, 0); this.cameraDefaults = { posCamera: new THREE.Vector3( 300, 300, 300 ), far: 100000 }; } PPCheck.prototype.initPreGL = function() { var scope = this; var callbackOnSuccess = function () { scope.preloadDone = true; }; scope.projectionSpace.loadAsyncResources( callbackOnSuccess ); }; PPCheck.prototype.initGL = function () { this.projectionSpace.initGL(); this.projectionSpace.flipTexture( 'linkPixelProtest' ); this.scenePerspective.scene.add( this.projectionSpace.dimensions[this.projectionSpace.index].mesh ); this.scenePerspective.setCameraDefaults( this.cameraDefaults ); this.controls = new THREE.TrackballControls( this.scenePerspective.camera ); }; PPCheck.prototype.resizeDisplayGL = function () { this.controls.handleResize(); }; PPCheck.prototype.renderPre = function () { this.controls.update(); }; return PPCheck; })();
# The Aya Programming Language ![Running Aya from the command line.](images/aya-demo.png) ## Features - Terse, yet readable syntax - Standard library written in aya code - Key-value pair dictionaries and objects - Number types: double, arbitrary precision float, rational, and complex - Basic support for objects and data structures using metatables - Pre-evaluation stack manipulation (custom infix operators) - List comprehension - String Interpolation, Unicode, and special characters - Interactive GUI - Built in plotting, graphics, and gui dialog library - I/O operators for file streams, web downloads, tcp/sockets, and more - Interactive help and Documentation - Metaprogramming ## Overview Aya is a terse stack based programming language originally intended for code golf and programming puzzles. The original design was heavily inspired by [CJam](https://sourceforge.net/p/cjam/wiki/Home/) and [GolfScript](http://www.golfscript.com/golfscript/). Currently, Aya is much more than a golfing language as it supports user-defined types, key-value pair dictionaries, natural variable scoping rules, and many other things which allow for more complex programs and data structures than other stack based languages. Aya comes with a standard library written entirely in Aya code. The standard library features types such as matrices, sets, dates, colors and more. It also features hundreds of functions for working working on numerical computations, strings, plotting and file I/O. It even features a basic turtle library for creating drawings in the plot window. Aya also features a minimal GUI that interfaces with Aya's stdin and stdout. The GUI features plotting, tab-completion for special characters, and an interactive way to search QuickSearch help data. ## Useful Links - [A Tour of Aya](https://github.com/nick-paul/aya-lang/wiki/A-Tour-of-Aya) - [Documentation / Wiki](https://github.com/nick-paul/aya-lang/wiki) - [Examples](https://github.com/nick-paul/aya-lang/tree/master/examples) - [Esolang Wiki](http://esolangs.org/wiki/Aya) ## Installation Download the latest release from the release page ([https://github.com/nick-paul/aya-lang/releases](https://github.com/nick-paul/aya-lang/releases)) and unpack the archive. Aya requires Java 8. To run the GUI, double click the jar file or run the command: ``` java -jar aya.jar ``` To run Aya interactively from the command line use `-i` ``` java -jar aya.jar -i ``` To run scripts from the command line: ``` java -jar aya.jar filename.aya ``` ## Examples ### Hypotenuse Formula Given side lengths `a` and `b` of a right triangle, compute the hypotenuse `c` - `x y ^`: Raise `x` to `y`th power - `x y +`: Add `x` and `y` - `x .^`: Square root of x ``` {a b, a 2 ^ b 2 ^ + .^ }:hypot; aya> 3 4 hypot 5 ``` Pure stack based (no local function variables) ``` aya> {J2^S.^}:hypot; ``` - `x y J`: Wrap `x` and `y` in a list (`[x y]`) - `[] 2 ^`: Broadcast `2 ^` across the list - `[] S`: Sum the list - `z .^`: Square root Operator breakdown: ``` aya> 3 4 J [ 3 4 ] aya> 3 4 J 2 ^ [ 9 16 ] aya> 3 4 J 2 ^ S 25 aya> 3 4 J 2 ^ S .^ 5 ``` ### Primality Test Test if a number is prime *(without using aya's built-in primaity test operator `G`)* Algorithm utilzing stack-based concatenative programming and aya's operators Note that `R`, `B`, and `S` (and all other uppercase letters) are operators just like `+`, `-`, `*`, `/`, etc. ``` aya> { RB\%0.=S1= }:isprime; aya> 11 isprime 1 ``` Same algorithm using more verbose syntax ``` {n, n 2 < { .# n is less than 2, not prime 0 } { .# n is greater than or equal to 2, check for any factors .# for each number in the set [2 to (n-1)] `i`, do.. [2 (n 1 -),] #: {i, .# check if (n%i == 0) n i % 0 = } .# If any are true (equal to 1), the number is not prime {1 =} any ! } .? }:isprime; ``` ### Define a 2D vector type Type definition: ``` struct ::vec [::x ::y] .# Member function def vec::len {self, self.x 2^ self.y 2^ + .^ } .# Print overload def vec::__repr__ {self, .# Aya supports string interpolation "<$(self.x),$(self.y)>" } .# Operator overload def vec::+ {self other, self.x other.x + self.y other.y + vec! } ``` Call constructor using `!` operator and print using `__repr__` definition: ``` aya> 3 4 vec! :v <3,4> ``` Perform operations on the type: ``` aya> v.len 5 aya> 10 10 vec! v + <13,14> ``` ### Generate a Mandelbrot Fractal Complex numbers are built in to aya's number system can can be used seamlessly with other numeric types. Aya also includes a graphics library. The `viewmat` module uses it to draw a 2d intensity image. ``` import ::viewmat { a , 0 { 2^ a+ } 30 % }:mandl; 0.008 :y_step; 0.008 :x_step; 3 :max_thresh; [1 $y_step- :1,] :# {y, [:2 $x_step+ 0.5,] :# {x, x y MI mandl .| max_thresh .> } } viewmat.show ``` ![Mandelbrot Fractal](images/mandel.png) ### Draw Using a Turtle Use aya's `turtle` and `color` modules to draw a pattern ``` import ::turtle import ::color {, 400:width; 400:height; color.colors.darkblue :bg_color; } turtle!:t; 5 :n; color.colors.blue :c; { n t.fd 89.5 t.right 1 c.hueshift :c; c t.pencolor n 0.75 + :n; } 400 % ``` ![Turtle Example](images/turtle.png) ### Load, Examine, and Visualize Datasets ``` import ::dataframe import ::plot import ::stats "Downloading file..." :P {, "https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/LakeHuron.csv":filename 1:csvindex } dataframe.read_csv :df; df.["time"] :x; df.["value"] :y; .# stats.regression returns a function x y stats.regression :r; plot.plot! :plt; x y {, "Water Level":label} plt.plot x {r} {, "Trend":label} plt.plot "Water Level of Lake Huron" plt.:title; [575 583] plt.y.:lim; 1 plt.y.:gridlines; "####" plt.x.:numberformat; 2 plt.:stroke; plt.view ``` ![Lake Huron](images/lakehuron.png) ### Interactive help Add a `?` to a line comment operator `.#` to add the comment to the interactive help. The interactive help can be searched from within the REPL or IDE and can be used to document source files. ``` aya> .#? A help comment!\n This comment will be added to the interactive help aya> \? help comment A help comment! This comment will be added to the interactive help ``` Sample documentation from `math.aya` ``` {Mp}:primes; .#? N primes\n returns a list containing the primes up to and including N {{*}U}:product; .#? L product\n product of a list {.!}:signnum; .#? N signnum \n returns the sign of a number (1,0,-1) {.^}:sqrt; .#? N sqrt\n square root ``` # TODO - *See issues page for more detailed todos* - **Optimization**: Parts of the interpreter run fairly slow and can be optimized to run faster. Many operators also need to be optimized. - **More Operators**: Most of the dot (`.<op>`), misc (`M<op>`), and colon (`:<op>`) operators have not yet been assigned. - **Refine the Standard Library**: Debug, fix small errors, clean ## Contributing If you find any bugs or have any feature or operator ideas, please submit an issue on the issue page. Alternively, implement any feature or bugfix yourself and submit a pull request.
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :address do name "" city "" postal_number "00970" country "" street "Aarteenetsijänkuja 8D 24" phone_number "+358445655606" description "" end end
package com.avocarrot.adapters.sample.admob; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import com.avocarrot.adapters.sample.R; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdLoader; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.formats.NativeAd; import com.google.android.gms.ads.formats.NativeAppInstallAd; import com.google.android.gms.ads.formats.NativeAppInstallAdView; import com.google.android.gms.ads.formats.NativeContentAd; import com.google.android.gms.ads.formats.NativeContentAdView; import java.util.List; public class AdmobNativeActivity extends AppCompatActivity { @NonNull private static final String EXTRA_AD_UNIT_ID = "ad_unit_id"; @NonNull public static Intent buildIntent(@NonNull final Context context, @NonNull final String adUnitId) { return new Intent(context, AdmobNativeActivity.class).putExtra(EXTRA_AD_UNIT_ID, adUnitId); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admob_native); final Intent intent = getIntent(); final String adUnitId = intent.getStringExtra(EXTRA_AD_UNIT_ID); if (TextUtils.isEmpty(adUnitId)) { finish(); return; } final AdLoader adLoader = new AdLoader.Builder(this, adUnitId) .forAppInstallAd(new NativeAppInstallAd.OnAppInstallAdLoadedListener() { @Override public void onAppInstallAdLoaded(final NativeAppInstallAd ad) { final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.admob_ad_view); final NativeAppInstallAdView adView = (NativeAppInstallAdView) getLayoutInflater().inflate(R.layout.admob_ad_app_install, null); populate(ad, adView); frameLayout.removeAllViews(); frameLayout.addView(adView); } }) .forContentAd(new NativeContentAd.OnContentAdLoadedListener() { @Override public void onContentAdLoaded(final NativeContentAd ad) { final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.admob_ad_view); final NativeContentAdView adView = (NativeContentAdView) getLayoutInflater().inflate(R.layout.admob_ad_content, null); populate(ad, adView); frameLayout.removeAllViews(); frameLayout.addView(adView); } }) .withAdListener(new AdListener() { @Override public void onAdFailedToLoad(final int errorCode) { Toast.makeText(getApplicationContext(), "Custom event native ad failed with code: " + errorCode, Toast.LENGTH_LONG).show(); } }) .build(); adLoader.loadAd(new AdRequest.Builder().build()); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } /** * Populates a {@link NativeAppInstallAdView} object with data from a given {@link NativeAppInstallAd}. */ private void populate(@NonNull final NativeAppInstallAd nativeAppInstallAd, @NonNull final NativeAppInstallAdView adView) { adView.setNativeAd(nativeAppInstallAd); adView.setHeadlineView(adView.findViewById(R.id.appinstall_headline)); adView.setImageView(adView.findViewById(R.id.appinstall_image)); adView.setBodyView(adView.findViewById(R.id.appinstall_body)); adView.setCallToActionView(adView.findViewById(R.id.appinstall_call_to_action)); adView.setIconView(adView.findViewById(R.id.appinstall_app_icon)); adView.setPriceView(adView.findViewById(R.id.appinstall_price)); adView.setStarRatingView(adView.findViewById(R.id.appinstall_stars)); adView.setStoreView(adView.findViewById(R.id.appinstall_store)); // Some assets are guaranteed to be in every NativeAppInstallAd. ((TextView) adView.getHeadlineView()).setText(nativeAppInstallAd.getHeadline()); ((TextView) adView.getBodyView()).setText(nativeAppInstallAd.getBody()); ((Button) adView.getCallToActionView()).setText(nativeAppInstallAd.getCallToAction()); ((ImageView) adView.getIconView()).setImageDrawable(nativeAppInstallAd.getIcon().getDrawable()); final List<NativeAd.Image> images = nativeAppInstallAd.getImages(); if (images.size() > 0) { ((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable()); } // Some aren't guaranteed, however, and should be checked. if (nativeAppInstallAd.getPrice() == null) { adView.getPriceView().setVisibility(View.INVISIBLE); } else { adView.getPriceView().setVisibility(View.VISIBLE); ((TextView) adView.getPriceView()).setText(nativeAppInstallAd.getPrice()); } if (nativeAppInstallAd.getStore() == null) { adView.getStoreView().setVisibility(View.INVISIBLE); } else { adView.getStoreView().setVisibility(View.VISIBLE); ((TextView) adView.getStoreView()).setText(nativeAppInstallAd.getStore()); } if (nativeAppInstallAd.getStarRating() == null) { adView.getStarRatingView().setVisibility(View.INVISIBLE); } else { ((RatingBar) adView.getStarRatingView()).setRating(nativeAppInstallAd.getStarRating().floatValue()); adView.getStarRatingView().setVisibility(View.VISIBLE); } } /** * Populates a {@link NativeContentAdView} object with data from a given {@link NativeContentAd}. */ private void populate(@NonNull final NativeContentAd nativeContentAd, @NonNull final NativeContentAdView adView) { adView.setNativeAd(nativeContentAd); adView.setHeadlineView(adView.findViewById(R.id.contentad_headline)); adView.setImageView(adView.findViewById(R.id.contentad_image)); adView.setBodyView(adView.findViewById(R.id.contentad_body)); adView.setCallToActionView(adView.findViewById(R.id.contentad_call_to_action)); adView.setLogoView(adView.findViewById(R.id.contentad_logo)); adView.setAdvertiserView(adView.findViewById(R.id.contentad_advertiser)); // Some assets are guaranteed to be in every NativeContentAd. ((TextView) adView.getHeadlineView()).setText(nativeContentAd.getHeadline()); ((TextView) adView.getBodyView()).setText(nativeContentAd.getBody()); ((TextView) adView.getCallToActionView()).setText(nativeContentAd.getCallToAction()); ((TextView) adView.getAdvertiserView()).setText(nativeContentAd.getAdvertiser()); final List<NativeAd.Image> images = nativeContentAd.getImages(); if (images.size() > 0) { ((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable()); } // Some aren't guaranteed, however, and should be checked. final NativeAd.Image logoImage = nativeContentAd.getLogo(); if (logoImage == null) { adView.getLogoView().setVisibility(View.INVISIBLE); } else { ((ImageView) adView.getLogoView()).setImageDrawable(logoImage.getDrawable()); adView.getLogoView().setVisibility(View.VISIBLE); } } }
google-site-verification: google11bac26bd88984eb.html
--- layout: post title: "A Python Watchdog with Threaded Queuing" date: 2017-09-06 categories: [python] --- So here's something cool I made this afternoon at work. Currently I am building an ETL pipeline that ingests some god-awful proprietary software data format type, decodes it into something useful, performs a number of validation and cleansing steps and then loads it into a speedy columnar database ready for some interesting analysis to be done. Once in production this pipeline will be handling 100's of individual files (each will be loaded as it's own separate table), ranging in sizes from 10MB through to ~0.5TB. The database, while having a pretty damn fast write speed, doesn't seem to handle lots of concurrent write processes too well (if the DB is hit too hard it will rollback one or all jobs complaing of concurrency conflicts). For a robustness there is a real need to serialize the database load component of the pipeline. However we obviously don't want to constrain the entire ETL pipeline to a single process (the database load is only one of many processes that will utilise the transformed data). What we really need is a way to decouple the extract-transform from the load... ### Enter our Watchdog powered job queue The basic idea of the jobs queue is that we set up a background process to monitor a directory for changes. When a data set is ready to be loaded into the database a trigger file will be created in the directory. This triggers the watchdog to place a load job in a waiting queue There are three key libraries that are used in our watchdog jobs queue: * `watchdog` * `threading` * `Queue` I havn't used the [Python watchdog library](http://pythonhosted.org/watchdog/) before but it's pretty slick. It's a Python api layered over one of a number of watchdog tools depending on the OS you're using. All these tools detect changes in a directory structure and then perform a set action when a change is detected (for instance if a file is modified do X; if it is deleted do Y). The threading and queue libraries provides a high level interface to manage threads. Threading is one approach to achieving parallelism and concurrency in Python (the other major one being multiprocessing). Given our jobs queue will be lightweight and memory non-intensive a thread is the perfect option. Queues operate as the conduits through which threads (or processes) communicate. The code is in a git repo here with a simple working example. So lets walk through the code. Lets start with the main bit, here we instantiate a Queue object, a thread object and run it in daemon (detached) mode and instantiate a watchdog. Lastly we place a poll that waits for a `ctrl-C` kill command and if it recieves one shuts everything down gracefully. ```python if __name__ == '__main__': # create queue watchdog_queue = Queue() # Set up a worker thread to process database load worker = Thread(target=process_load_queue, args=(watchdog_queue,)) worker.setDaemon(True) worker.start() # setup watchdog to monitor directory for trigger files args = sys.argv[1:] patt = ["*.trigger"] event_handler = SqlLoaderWatchdog(watchdog_queue, patterns=patt) observer = Observer() observer.schedule(event_handler, path=args[0] if args else '.') observer.start() try: while True: time.sleep(2) except KeyboardInterrupt: observer.stop() observer.join() ``` Next, we define a define a watchdog class. This class inherits from the Watchdog `PatternMatchingEventHandler` class. In this code our watchdog will only be triggered if a file is moved to have a `.trigger` extension. Once triggered the watchdog places the event object on the queue, ready to be picked up by the worker thread (described below). ```python class SqlLoaderWatchdog(PatternMatchingEventHandler): ''' Watches a nominated directory and when a trigger file is moved to take the ".trigger" extension it proceeds to execute the commands within that trigger file. Notes ============ Intended to be run in the background and pickup trigger files generated by other ETL process ''' def __init__(self, queue, patterns): PatternMatchingEventHandler.__init__(self, patterns=patterns) self.queue = queue def process(self, event): ''' event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file ''' self.queue.put(event) def on_moved(self, event): self.process(event) ``` For a database load the contents of the trigger file looks something like this: ```bash include trigger file contents ``` Lastly we define a worker thread. The worker thread is intended to be a backgrounded (daemon) process running indefinitely so we use an always true `while` statement. The worker thread then "polls" the queue every second, checking if any jobs have been placed on it by the watchdog process. When it detects a job on the queue it pulls it off and proceeds to run the bash command in a shell (using the `subprocess` library). In our example with is a CLI command to load the data into the database ```python def process_load_queue(q): '''This is the worker thread function. It is run as a daemon threads that only exit when the main thread ends. Args ========== q: Queue() object ''' while True: if not q.empty(): event = q.get() now = datetime.datetime.utcnow() print "{0} -- Pulling {1} off the queue ...".format(now.strftime("%Y/%m/%d %H:%M:%S"), event.dest_path) log_path = "/path/to/logging.txt" with open(log_path, "a") as f: f.write("{0} -- Processing {1}...\n".format(now.strftime("%Y/%m/%d %H:%M:%S"), event.dest_path)) # read the contents of the trigger file cmd = "cat {0} | while read command; do ${{command}}; done >> {1} 2>&1".format(event.dest_path, log_path) subprocess.call(cmd, shell=True) # once done, remove the trigger file os.remove(event.dest_path) # log the operation has been completed successfully now = datetime.datetime.utcnow() with open(log_path, "a") as f: f.write("{0} -- Finished processing {1}...\n".format(now.strftime("%Y/%m/%d %H:%M:%S"), event.dest_path)) else: time.sleep(1) ``` And that's it! Check out the simple working example here that illustrates these principles (though instead of a database load it simply echos the contents of the trigger file).
# frozen_string_literal: true require 'expectacle/version' require 'expectacle/thrower' # Expectable: simple pry/expect wrapper. module Expectacle; end
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited // Copyright (c) 2014-2018 Esteban Tovagliari, The appleseedhq Organization // // 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. // // appleseed.renderer headers. #include "renderer/modeling/scene/scene.h" // appleseed.foundation headers. #include "foundation/platform/python.h" namespace bpy = boost::python; using namespace foundation; using namespace renderer; // Work around a regression in Visual Studio 2015 Update 3. #if defined(_MSC_VER) && _MSC_VER == 1900 namespace boost { template <> Scene const volatile* get_pointer<Scene const volatile>(Scene const volatile* p) { return p; } } #endif namespace { auto_release_ptr<Scene> create_scene() { return SceneFactory::create(); } } void bind_scene() { bpy::class_<Scene, auto_release_ptr<Scene>, bpy::bases<Entity, BaseGroup>, boost::noncopyable>("Scene", bpy::no_init) .def("__init__", bpy::make_constructor(create_scene)) .def("get_uid", &Identifiable::get_uid) .def("cameras", &Scene::cameras, bpy::return_value_policy<bpy::reference_existing_object>()) .def("get_environment", &Scene::get_environment, bpy::return_value_policy<bpy::reference_existing_object>()) .def("set_environment", &Scene::set_environment) .def("environment_edfs", &Scene::environment_edfs, bpy::return_value_policy<bpy::reference_existing_object>()) .def("environment_shaders", &Scene::environment_shaders, bpy::return_value_policy<bpy::reference_existing_object>()) .def("compute_bbox", &Scene::compute_bbox) ; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2014-2019 The DigiByte Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/db.h> #include <addrman.h> #include <hash.h> #include <protocol.h> #include <utilstrencodings.h> #include <wallet/walletutil.h> #include <stdint.h> #ifndef WIN32 #include <sys/stat.h> #endif #include <boost/thread.hpp> namespace { //! Make sure database has a unique fileid within the environment. If it //! doesn't, throw an error. BDB caches do not work properly when more than one //! open database has the same fileid (values written to one database may show //! up in reads to other databases). //! //! BerkeleyDB generates unique fileids by default //! (https://docs.oracle.com/cd/E17275_01/html/programmer_reference/program_copy.html), //! so digibyte should never create different databases with the same fileid, but //! this error can be triggered if users manually copy database files. void CheckUniqueFileid(const BerkeleyEnvironment& env, const std::string& filename, Db& db) { if (env.IsMock()) return; u_int8_t fileid[DB_FILE_ID_LEN]; int ret = db.get_mpf()->get_fileid(fileid); if (ret != 0) { throw std::runtime_error(strprintf("BerkeleyBatch: Can't open database %s (get_fileid failed with %d)", filename, ret)); } for (const auto& item : env.mapDb) { u_int8_t item_fileid[DB_FILE_ID_LEN]; if (item.second && item.second->get_mpf()->get_fileid(item_fileid) == 0 && memcmp(fileid, item_fileid, sizeof(fileid)) == 0) { const char* item_filename = nullptr; item.second->get_dbname(&item_filename, nullptr); throw std::runtime_error(strprintf("BerkeleyBatch: Can't open database %s (duplicates fileid %s from %s)", filename, HexStr(std::begin(item_fileid), std::end(item_fileid)), item_filename ? item_filename : "(unknown database)")); } } } CCriticalSection cs_db; std::map<std::string, BerkeleyEnvironment> g_dbenvs GUARDED_BY(cs_db); //!< Map from directory name to open db environment. } // namespace BerkeleyEnvironment* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename) { fs::path env_directory; if (fs::is_regular_file(wallet_path)) { // Special case for backwards compatibility: if wallet path points to an // existing file, treat it as the path to a BDB data file in a parent // directory that also contains BDB log files. env_directory = wallet_path.parent_path(); database_filename = wallet_path.filename().string(); } else { // Normal case: Interpret wallet path as a directory path containing // data and log files. env_directory = wallet_path; database_filename = "wallet.dat"; } LOCK(cs_db); // Note: An ununsed temporary BerkeleyEnvironment object may be created inside the // emplace function if the key already exists. This is a little inefficient, // but not a big concern since the map will be changed in the future to hold // pointers instead of objects, anyway. return &g_dbenvs.emplace(std::piecewise_construct, std::forward_as_tuple(env_directory.string()), std::forward_as_tuple(env_directory)).first->second; } // // BerkeleyBatch // void BerkeleyEnvironment::Close() { if (!fDbEnvInit) return; fDbEnvInit = false; for (auto& db : mapDb) { auto count = mapFileUseCount.find(db.first); assert(count == mapFileUseCount.end() || count->second == 0); if (db.second) { db.second->close(0); delete db.second; db.second = nullptr; } } int ret = dbenv->close(0); if (ret != 0) LogPrintf("BerkeleyEnvironment::Close: Error %d closing database environment: %s\n", ret, DbEnv::strerror(ret)); if (!fMockDb) DbEnv((u_int32_t)0).remove(strPath.c_str(), 0); } void BerkeleyEnvironment::Reset() { dbenv.reset(new DbEnv(DB_CXX_NO_EXCEPTIONS)); fDbEnvInit = false; fMockDb = false; } BerkeleyEnvironment::BerkeleyEnvironment(const fs::path& dir_path) : strPath(dir_path.string()) { Reset(); } BerkeleyEnvironment::~BerkeleyEnvironment() { Close(); } bool BerkeleyEnvironment::Open(bool retry) { if (fDbEnvInit) return true; boost::this_thread::interruption_point(); fs::path pathIn = strPath; TryCreateDirectories(pathIn); if (!LockDirectory(pathIn, ".walletlock")) { LogPrintf("Cannot obtain a lock on wallet directory %s. Another instance of digibyte may be using it.\n", strPath); return false; } fs::path pathLogDir = pathIn / "database"; TryCreateDirectories(pathLogDir); fs::path pathErrorFile = pathIn / "db.log"; LogPrintf("BerkeleyEnvironment::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string()); unsigned int nEnvFlags = 0; if (gArgs.GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB)) nEnvFlags |= DB_PRIVATE; dbenv->set_lg_dir(pathLogDir.string().c_str()); dbenv->set_cachesize(0, 0x100000, 1); // 1 MiB should be enough for just the wallet dbenv->set_lg_bsize(0x10000); dbenv->set_lg_max(1048576); dbenv->set_lk_max_locks(40000); dbenv->set_lk_max_objects(40000); dbenv->set_errfile(fsbridge::fopen(pathErrorFile, "a")); /// debug dbenv->set_flags(DB_AUTO_COMMIT, 1); dbenv->set_flags(DB_TXN_WRITE_NOSYNC, 1); dbenv->log_set_config(DB_LOG_AUTO_REMOVE, 1); int ret = dbenv->open(strPath.c_str(), DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_THREAD | DB_RECOVER | nEnvFlags, S_IRUSR | S_IWUSR); if (ret != 0) { LogPrintf("BerkeleyEnvironment::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret)); int ret2 = dbenv->close(0); if (ret2 != 0) { LogPrintf("BerkeleyEnvironment::Open: Error %d closing failed database environment: %s\n", ret2, DbEnv::strerror(ret2)); } Reset(); if (retry) { // try moving the database env out of the way fs::path pathDatabaseBak = pathIn / strprintf("database.%d.bak", GetTime()); try { fs::rename(pathLogDir, pathDatabaseBak); LogPrintf("Moved old %s to %s. Retrying.\n", pathLogDir.string(), pathDatabaseBak.string()); } catch (const fs::filesystem_error&) { // failure is ok (well, not really, but it's not worse than what we started with) } // try opening it again one more time if (!Open(false /* retry */)) { // if it still fails, it probably means we can't even create the database env return false; } } else { return false; } } fDbEnvInit = true; fMockDb = false; return true; } void BerkeleyEnvironment::MakeMock() { if (fDbEnvInit) throw std::runtime_error("BerkeleyEnvironment::MakeMock: Already initialized"); boost::this_thread::interruption_point(); LogPrint(BCLog::DB, "BerkeleyEnvironment::MakeMock\n"); dbenv->set_cachesize(1, 0, 1); dbenv->set_lg_bsize(10485760 * 4); dbenv->set_lg_max(10485760); dbenv->set_lk_max_locks(10000); dbenv->set_lk_max_objects(10000); dbenv->set_flags(DB_AUTO_COMMIT, 1); dbenv->log_set_config(DB_LOG_IN_MEMORY, 1); int ret = dbenv->open(nullptr, DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_THREAD | DB_PRIVATE, S_IRUSR | S_IWUSR); if (ret > 0) throw std::runtime_error(strprintf("BerkeleyEnvironment::MakeMock: Error %d opening database environment.", ret)); fDbEnvInit = true; fMockDb = true; } BerkeleyEnvironment::VerifyResult BerkeleyEnvironment::Verify(const std::string& strFile, recoverFunc_type recoverFunc, std::string& out_backup_filename) { LOCK(cs_db); assert(mapFileUseCount.count(strFile) == 0); Db db(dbenv.get(), 0); int result = db.verify(strFile.c_str(), nullptr, nullptr, 0); if (result == 0) return VerifyResult::VERIFY_OK; else if (recoverFunc == nullptr) return VerifyResult::RECOVER_FAIL; // Try to recover: bool fRecovered = (*recoverFunc)(fs::path(strPath) / strFile, out_backup_filename); return (fRecovered ? VerifyResult::RECOVER_OK : VerifyResult::RECOVER_FAIL); } bool BerkeleyBatch::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename) { std::string filename; BerkeleyEnvironment* env = GetWalletEnv(file_path, filename); // Recovery procedure: // move wallet file to walletfilename.timestamp.bak // Call Salvage with fAggressive=true to // get as much data as possible. // Rewrite salvaged data to fresh wallet file // Set -rescan so any missing transactions will be // found. int64_t now = GetTime(); newFilename = strprintf("%s.%d.bak", filename, now); int result = env->dbenv->dbrename(nullptr, filename.c_str(), nullptr, newFilename.c_str(), DB_AUTO_COMMIT); if (result == 0) LogPrintf("Renamed %s to %s\n", filename, newFilename); else { LogPrintf("Failed to rename %s to %s\n", filename, newFilename); return false; } std::vector<BerkeleyEnvironment::KeyValPair> salvagedData; bool fSuccess = env->Salvage(newFilename, true, salvagedData); if (salvagedData.empty()) { LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename); return false; } LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size()); std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(env->dbenv.get(), 0); int ret = pdbCopy->open(nullptr, // Txn pointer filename.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { LogPrintf("Cannot create database file %s\n", filename); pdbCopy->close(0); return false; } DbTxn* ptxn = env->TxnBegin(); for (BerkeleyEnvironment::KeyValPair& row : salvagedData) { if (recoverKVcallback) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); if (!(*recoverKVcallback)(callbackDataIn, ssKey, ssValue)) continue; } Dbt datKey(&row.first[0], row.first.size()); Dbt datValue(&row.second[0], row.second.size()); int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } ptxn->commit(0); pdbCopy->close(0); return fSuccess; } bool BerkeleyBatch::VerifyEnvironment(const fs::path& file_path, std::string& errorStr) { std::string walletFile; BerkeleyEnvironment* env = GetWalletEnv(file_path, walletFile); fs::path walletDir = env->Directory(); LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0)); LogPrintf("Using wallet %s\n", walletFile); // Wallet file must be a plain filename without a directory if (walletFile != fs::basename(walletFile) + fs::extension(walletFile)) { errorStr = strprintf(_("Wallet %s resides outside wallet directory %s"), walletFile, walletDir.string()); return false; } if (!env->Open(true /* retry */)) { errorStr = strprintf(_("Error initializing wallet database environment %s!"), walletDir); return false; } return true; } bool BerkeleyBatch::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, BerkeleyEnvironment::recoverFunc_type recoverFunc) { std::string walletFile; BerkeleyEnvironment* env = GetWalletEnv(file_path, walletFile); fs::path walletDir = env->Directory(); if (fs::exists(walletDir / walletFile)) { std::string backup_filename; BerkeleyEnvironment::VerifyResult r = env->Verify(walletFile, recoverFunc, backup_filename); if (r == BerkeleyEnvironment::VerifyResult::RECOVER_OK) { warningStr = strprintf(_("Warning: Wallet file corrupt, data salvaged!" " Original %s saved as %s in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), walletFile, backup_filename, walletDir); } if (r == BerkeleyEnvironment::VerifyResult::RECOVER_FAIL) { errorStr = strprintf(_("%s corrupt, salvage failed"), walletFile); return false; } } // also return true if files does not exists return true; } /* End of headers, beginning of key/value data */ static const char *HEADER_END = "HEADER=END"; /* End of key/value data */ static const char *DATA_END = "DATA=END"; bool BerkeleyEnvironment::Salvage(const std::string& strFile, bool fAggressive, std::vector<BerkeleyEnvironment::KeyValPair>& vResult) { LOCK(cs_db); assert(mapFileUseCount.count(strFile) == 0); u_int32_t flags = DB_SALVAGE; if (fAggressive) flags |= DB_AGGRESSIVE; std::stringstream strDump; Db db(dbenv.get(), 0); int result = db.verify(strFile.c_str(), nullptr, &strDump, flags); if (result == DB_VERIFY_BAD) { LogPrintf("BerkeleyEnvironment::Salvage: Database salvage found errors, all data may not be recoverable.\n"); if (!fAggressive) { LogPrintf("BerkeleyEnvironment::Salvage: Rerun with aggressive mode to ignore errors and continue.\n"); return false; } } if (result != 0 && result != DB_VERIFY_BAD) { LogPrintf("BerkeleyEnvironment::Salvage: Database salvage failed with result %d.\n", result); return false; } // Format of bdb dump is ascii lines: // header lines... // HEADER=END // hexadecimal key // hexadecimal value // ... repeated // DATA=END std::string strLine; while (!strDump.eof() && strLine != HEADER_END) getline(strDump, strLine); // Skip past header std::string keyHex, valueHex; while (!strDump.eof() && keyHex != DATA_END) { getline(strDump, keyHex); if (keyHex != DATA_END) { if (strDump.eof()) break; getline(strDump, valueHex); if (valueHex == DATA_END) { LogPrintf("BerkeleyEnvironment::Salvage: WARNING: Number of keys in data does not match number of values.\n"); break; } vResult.push_back(make_pair(ParseHex(keyHex), ParseHex(valueHex))); } } if (keyHex != DATA_END) { LogPrintf("BerkeleyEnvironment::Salvage: WARNING: Unexpected end of file while reading salvage output.\n"); return false; } return (result == 0); } void BerkeleyEnvironment::CheckpointLSN(const std::string& strFile) { dbenv->txn_checkpoint(0, 0, 0); if (fMockDb) return; dbenv->lsn_reset(strFile.c_str(), 0); } BerkeleyBatch::BerkeleyBatch(BerkeleyDatabase& database, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr) { fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w')); fFlushOnClose = fFlushOnCloseIn; env = database.env; if (database.IsDummy()) { return; } const std::string &strFilename = database.strFile; bool fCreate = strchr(pszMode, 'c') != nullptr; unsigned int nFlags = DB_THREAD; if (fCreate) nFlags |= DB_CREATE; { LOCK(cs_db); if (!env->Open(false /* retry */)) throw std::runtime_error("BerkeleyBatch: Failed to open database environment."); pdb = env->mapDb[strFilename]; if (pdb == nullptr) { int ret; std::unique_ptr<Db> pdb_temp = MakeUnique<Db>(env->dbenv.get(), 0); bool fMockDb = env->IsMock(); if (fMockDb) { DbMpoolFile* mpf = pdb_temp->get_mpf(); ret = mpf->set_flags(DB_MPOOL_NOFILE, 1); if (ret != 0) { throw std::runtime_error(strprintf("BerkeleyBatch: Failed to configure for no temp file backing for database %s", strFilename)); } } ret = pdb_temp->open(nullptr, // Txn pointer fMockDb ? nullptr : strFilename.c_str(), // Filename fMockDb ? strFilename.c_str() : "main", // Logical db name DB_BTREE, // Database type nFlags, // Flags 0); if (ret != 0) { throw std::runtime_error(strprintf("BerkeleyBatch: Error %d, can't open database %s", ret, strFilename)); } // Call CheckUniqueFileid on the containing BDB environment to // avoid BDB data consistency bugs that happen when different data // files in the same environment have the same fileid. // // Also call CheckUniqueFileid on all the other g_dbenvs to prevent // digibyte from opening the same data file through another // environment when the file is referenced through equivalent but // not obviously identical symlinked or hard linked or bind mounted // paths. In the future a more relaxed check for equal inode and // device ids could be done instead, which would allow opening // different backup copies of a wallet at the same time. Maybe even // more ideally, an exclusive lock for accessing the database could // be implemented, so no equality checks are needed at all. (Newer // versions of BDB have an set_lk_exclusive method for this // purpose, but the older version we use does not.) for (auto& env : g_dbenvs) { CheckUniqueFileid(env.second, strFilename, *pdb_temp); } pdb = pdb_temp.release(); env->mapDb[strFilename] = pdb; if (fCreate && !Exists(std::string("version"))) { bool fTmp = fReadOnly; fReadOnly = false; WriteVersion(CLIENT_VERSION); fReadOnly = fTmp; } } ++env->mapFileUseCount[strFilename]; strFile = strFilename; } } void BerkeleyBatch::Flush() { if (activeTxn) return; // Flush database activity from memory pool to disk log unsigned int nMinutes = 0; if (fReadOnly) nMinutes = 1; env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0); } void BerkeleyDatabase::IncrementUpdateCounter() { ++nUpdateCounter; } void BerkeleyBatch::Close() { if (!pdb) return; if (activeTxn) activeTxn->abort(); activeTxn = nullptr; pdb = nullptr; if (fFlushOnClose) Flush(); { LOCK(cs_db); --env->mapFileUseCount[strFile]; } } void BerkeleyEnvironment::CloseDb(const std::string& strFile) { { LOCK(cs_db); if (mapDb[strFile] != nullptr) { // Close the database handle Db* pdb = mapDb[strFile]; pdb->close(0); delete pdb; mapDb[strFile] = nullptr; } } } bool BerkeleyBatch::Rewrite(BerkeleyDatabase& database, const char* pszSkip) { if (database.IsDummy()) { return true; } BerkeleyEnvironment *env = database.env; const std::string& strFile = database.strFile; while (true) { { LOCK(cs_db); if (!env->mapFileUseCount.count(strFile) || env->mapFileUseCount[strFile] == 0) { // Flush log data to the dat file env->CloseDb(strFile); env->CheckpointLSN(strFile); env->mapFileUseCount.erase(strFile); bool fSuccess = true; LogPrintf("BerkeleyBatch::Rewrite: Rewriting %s...\n", strFile); std::string strFileRes = strFile + ".rewrite"; { // surround usage of db with extra {} BerkeleyBatch db(database, "r"); std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(env->dbenv.get(), 0); int ret = pdbCopy->open(nullptr, // Txn pointer strFileRes.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { LogPrintf("BerkeleyBatch::Rewrite: Can't create database file %s\n", strFileRes); fSuccess = false; } Dbc* pcursor = db.GetCursor(); if (pcursor) while (fSuccess) { CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret1 = db.ReadAtCursor(pcursor, ssKey, ssValue); if (ret1 == DB_NOTFOUND) { pcursor->close(); break; } else if (ret1 != 0) { pcursor->close(); fSuccess = false; break; } if (pszSkip && strncmp(ssKey.data(), pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0) continue; if (strncmp(ssKey.data(), "\x07version", 8) == 0) { // Update version: ssValue.clear(); ssValue << CLIENT_VERSION; } Dbt datKey(ssKey.data(), ssKey.size()); Dbt datValue(ssValue.data(), ssValue.size()); int ret2 = pdbCopy->put(nullptr, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } if (fSuccess) { db.Close(); env->CloseDb(strFile); if (pdbCopy->close(0)) fSuccess = false; } else { pdbCopy->close(0); } } if (fSuccess) { Db dbA(env->dbenv.get(), 0); if (dbA.remove(strFile.c_str(), nullptr, 0)) fSuccess = false; Db dbB(env->dbenv.get(), 0); if (dbB.rename(strFileRes.c_str(), nullptr, strFile.c_str(), 0)) fSuccess = false; } if (!fSuccess) LogPrintf("BerkeleyBatch::Rewrite: Failed to rewrite database file %s\n", strFileRes); return fSuccess; } } MilliSleep(100); } } void BerkeleyEnvironment::Flush(bool fShutdown) { int64_t nStart = GetTimeMillis(); // Flush log data to the actual data file on all files that are not in use LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started"); if (!fDbEnvInit) return; { LOCK(cs_db); std::map<std::string, int>::iterator mi = mapFileUseCount.begin(); while (mi != mapFileUseCount.end()) { std::string strFile = (*mi).first; int nRefCount = (*mi).second; LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount); if (nRefCount == 0) { // Move log data to the dat file CloseDb(strFile); LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s checkpoint\n", strFile); dbenv->txn_checkpoint(0, 0, 0); LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s detach\n", strFile); if (!fMockDb) dbenv->lsn_reset(strFile.c_str(), 0); LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s closed\n", strFile); mapFileUseCount.erase(mi++); } else mi++; } LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart); if (fShutdown) { char** listp; if (mapFileUseCount.empty()) { dbenv->log_archive(&listp, DB_ARCH_REMOVE); Close(); if (!fMockDb) { fs::remove_all(fs::path(strPath) / "database"); } g_dbenvs.erase(strPath); } } } } bool BerkeleyBatch::PeriodicFlush(BerkeleyDatabase& database) { if (database.IsDummy()) { return true; } bool ret = false; BerkeleyEnvironment *env = database.env; const std::string& strFile = database.strFile; TRY_LOCK(cs_db, lockDb); if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; std::map<std::string, int>::iterator mit = env->mapFileUseCount.begin(); while (mit != env->mapFileUseCount.end()) { nRefCount += (*mit).second; mit++; } if (nRefCount == 0) { boost::this_thread::interruption_point(); std::map<std::string, int>::iterator mi = env->mapFileUseCount.find(strFile); if (mi != env->mapFileUseCount.end()) { LogPrint(BCLog::DB, "Flushing %s\n", strFile); int64_t nStart = GetTimeMillis(); // Flush wallet file so it's self contained env->CloseDb(strFile); env->CheckpointLSN(strFile); env->mapFileUseCount.erase(mi++); LogPrint(BCLog::DB, "Flushed %s %dms\n", strFile, GetTimeMillis() - nStart); ret = true; } } } return ret; } bool BerkeleyDatabase::Rewrite(const char* pszSkip) { return BerkeleyBatch::Rewrite(*this, pszSkip); } bool BerkeleyDatabase::Backup(const std::string& strDest) { if (IsDummy()) { return false; } while (true) { { LOCK(cs_db); if (!env->mapFileUseCount.count(strFile) || env->mapFileUseCount[strFile] == 0) { // Flush log data to the dat file env->CloseDb(strFile); env->CheckpointLSN(strFile); env->mapFileUseCount.erase(strFile); // Copy wallet file fs::path pathSrc = env->Directory() / strFile; fs::path pathDest(strDest); if (fs::is_directory(pathDest)) pathDest /= strFile; try { if (fs::equivalent(pathSrc, pathDest)) { LogPrintf("cannot backup to wallet source file %s\n", pathDest.string()); return false; } fs::copy_file(pathSrc, pathDest, fs::copy_option::overwrite_if_exists); LogPrintf("copied %s to %s\n", strFile, pathDest.string()); return true; } catch (const fs::filesystem_error& e) { LogPrintf("error copying %s to %s - %s\n", strFile, pathDest.string(), e.what()); return false; } } } MilliSleep(100); } } void BerkeleyDatabase::Flush(bool shutdown) { if (!IsDummy()) { env->Flush(shutdown); if (shutdown) env = nullptr; } }
<?php /** * @link http://zoopcommerce.github.io/shard * @package Zoop * @license MIT */ namespace Zoop\Shard\Serializer\Reference; use Zend\ServiceManager\ServiceLocatorAwareInterface; use Zend\ServiceManager\ServiceLocatorAwareTrait; /** * * @since 1.0 * @author Tim Roediger <superdweebie@gmail.com> */ class Eager implements ReferenceSerializerInterface, ServiceLocatorAwareInterface { use ServiceLocatorAwareTrait; protected $serializer; public function serialize($document) { if ($document) { return $this->getSerializer()->toArray($document); } else { return null; } } protected function getSerializer() { if (!isset($this->serializer)) { $this->serializer = $this->serviceLocator->get('serializer'); } return $this->serializer; } }
package com.piggymetrics.user.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQuery; @Entity @NamedQuery(name = "User.findByName", query = "select name,address from User u where u.name=?1") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id long id; @Column(name = "name") String name; @Column(name = "address") String address; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return this.id + "," + this.name + "," + this.address; } }
import test from 'ava' import Vue from 'vue' import {createRenderer} from 'vue-server-renderer' import ContentPlaceholder from '../src' test.cb('ssr', t => { const rows = [{height: '5px', boxes: [[0, '40px']]}] const renderer = createRenderer() const app = new Vue({ template: '<content-placeholder :rows="rows"></content-placeholder>', components: {ContentPlaceholder}, data: {rows} }) renderer.renderToString(app, (err, html) => { t.falsy(err) t.true(html.includes('data-server-rendered')) t.end() }) })
## About Autoloads JS files based on name when the class is needed. This is designed to be used with Joose classes in the "Foo.Bar.Baz" format This module removes the needs of using require() all over your files. Simply define the autoloader to your codebase, and use the names relative to the files. ie lib/Foo/Bar/Baz.js when you load 'lib/' makes Foo.Bar.Baz require('./lib/Foo/Bar/Baz.js') automatically and return the value. ## Install Install with npm install autoloader ## Usage Folder structure: /lib/ Foo/ Foo.js Bar.js test.js package.json (main: 'test.js') File contents: Foo.js: module.export = function() { console.log("Foo") Foo.Bar(); }; Bar.js: module.export = function() { console.log("Foo.Bar") }; test.js: require('autoloader').autoload(__dirname + '/lib') Foo(); loading the module would print to screen: Foo Foo.Bar ALL MODULES MUST RETURN AN OBJECT/FUNCTION. It can not return Scalar Values! ## Custom Loaders If you pass a function as the 2nd argument, autoloader will execute that before requiring the file with the following arguments: function (fullPath, className, object, key) { } fullPath will be the full path to the module file to load, classname would be 'Foo.Bar.Baz' for example, object would be the object to add a new value to, and key is the key of object to assign the response. so if you load 'Foo', object is global, and key is Foo, likewise if you load Foo.Bar, object is Foo and key is 'Bar'. You can then do what ever magic it is you need to do, and optionally assign it yourself. If you don't assign it yourself, simply return the value and autoloader will assign it for you. ## License The MIT License Copyright (c) 2011 Daniel Ennis <aikar@aikar.co> 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.
App::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin end
package com.hkm.urbansdk.gson; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; /** * Created by hesk on 2/17/15. */ public class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.equals(String.class)) { return null; } return (TypeAdapter<T>) new StringAdapter(); } public class StringAdapter extends TypeAdapter<String> { public String read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return ""; } return reader.nextString(); } public void write(JsonWriter writer, String value) throws IOException { if (value == null) { writer.nullValue(); return; } writer.value(value); } } }
{% extends "empty_layout.html" %} {% block title %}{{ _('Edit voting variant') }} :: {% endblock %} {% block body %} <h1>{{ _('Voting variant editor') }}</h1> <ol class="breadcrumb"> <li><a href="{{ url_for('voting.voting_list') }}">{{ _('Votings') }}</a></li> <li><a href="{{ url_for('voting.voting_page', voting_id=variant.voting_id) }}">{{ _('Voting') }}</a></li> <li>{{ variant.title|default(_('Add variant'), true) }}</li> </ol> <form method="post" action="{{ url_for('voting.variant_save') }}"> {% if variant.id %} <input type="hidden" name="id" value="{{ variant.id }}" /> {% else %} <input type="hidden" name="voting_id" value="{{ variant.voting_id }}" /> {% endif %} <div class="form-group"> <label>{{ _('Title') }}</label> <input type="text" class="form-control" name="title" placeholder="{{ _('Variant title') }}" value="{{ variant.title|default('', true) }}" autocomplete="off"> </div> <div class="form-group"> <label>{{ _('Description') }}</label> <textarea rows="6" class="form-control" name="description" placeholder="{{ _('Variant description') }}">{{ variant.description|default('', true) }}</textarea> </div> <div class="form-group"> <input type="submit" value="{{ _('Save') }}" class="btn btn-success" /> </div> </form> {% endblock %}
package net.h31ix.travelpad.api; import net.h31ix.travelpad.LangManager; import org.bukkit.Location; import org.bukkit.entity.Player; /** * <p> * Defines a new Unnamed TravelPad on the map, this is only used before a pad is named by the player. */ public class UnnamedPad { private Location location = null; private Player owner = null; public UnnamedPad(Location location, Player owner) { this.location = location; this.owner = owner; } /** * Get the location of the pad * * @return location Location of the obsidian center of the pad */ public Location getLocation() { return location; } /** * Get the owner of the pad * * @return owner Player who owns the pad's name */ public Player getOwner() { return owner; } }
package jelly.exception.level; public class LevelNotFound extends Exception { }
import { dealsService } from '../services'; const fetchDealsData = () => { return dealsService().getDeals() .then(res => { return res.data }) // Returning [] as a placeholder now so it does not error out when this service // fails. We should be handling this in our DISPATCH_REQUEST_FAILURE .catch(() => []); }; export default fetchDealsData;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quicken.Core.Index.Enumerations { public enum TargetType { File = 0, Desktop = 1, Metro = 2 } }
-- Faster lookup for built-in globals. local find = string.find local fmt = string.format local cut = string.sub local error = error -- The heart of the matter. local function spliter(str, delimiter) -- Handle special cases concerning the delimiter parameter. -- If the pattern is nil, split on contiguous whitespace. -- Error out if the delimiter would lead to infinite loops. local delimiter = delimiter or '%s+' if delimiter == '' then delimiter = '.' end if find('', delimiter, 1) then local msg = fmt('The delimiter (%s) would match the empty string.', delimiter) error(msg) end local s, e, subsection local position = 1 local function iter() s, e = find(str, delimiter, position) if s then subsection = cut(str, position, s-1) position = e + 1 return subsection elseif position < #str then subsection = cut(str, position) position = #str + 2 return subsection elseif position == #str + 1 then position = #str + 2 return '' end end return iter end -- Return the split function, so it can be required. return spliter
<!DOCTYPE html> <html> <meta charset="utf-8"> <head> <title>🐾 Teach Brian How to Code</title> <link rel="stylesheet" href="stylesheets/blog-stylesheet.css" type="text/css"> </head> <body> <div class="sub-div"> <p><a href="../index.html">Back to Home</a></p> </div> <main> <h6>Create jQuery Library with Vanilla JS</h6> <h2>July 28, 2015</h2> <p>It's kind of fun project. Create jQuery Library like functions with vanilla JS.<p> <h4>$ object</h4> <p>What is $? $ is not a special keyword. It is just a variable name. It will return every incidet of argument from DOM. The task is to create an array like element (must have a function of length) when it is called $(); so we can manuplate the DOM.</p> <div class=text-editor> var $ = function(selector) { if (!(this instanceof $)) { return new $(selector) //this way we don't have to use 'new' every time } var elements = document.querySelectorAll(selector); for (var i=0; i"<"elements.length; i++) { this[i] = elements[i]; } this.length = elements.length; } //or simply: Array.prototype.push.apply(this, elements); </div> <p>Most important concept here is that 'this'. The reason we are creating $ is that we want to return every elements that are instance of $. Without it, we can't call $('selector').OTHERFUNCTION. </p> <h4>$.expend(target, object)</h4> <p>Don't think too hard. You will ruin it. This was one of the function that I was most struggle with. How to make sure that the function is assigned as same as other function? Just assign it. </p> <div class=text-editor> $.expend = function(target, object) { for (var i in object) { target[i] = object[i]; }; return target; }; </div> <h4>$.isArray(obj)</h4> <p>This will return true if the object is Array (not Arraylike obj)</p> <div class=text-editor> $.isArray = function(obj) { Object.prototype.toString.call(obj) === "[object Array]" }; <p>This is something to remember. To see if the argument is true array, the only way to check is to see toString.call(obj) and return '[object Array]'</p> </div> <h4>$.ArrayLike(obj)</h4> <p>Like what $(); returns, arraylike stuff but not exactly an array. So what's difference between array and array-like obj? An array-like object has: </p> <li>indexed access to elements and the property length that tells us how many elements the object has.</li> <li> It does not however have: array methods such as push, forEach and indexOf.</li> <div class=text-editor> $.ArrayLike = function(obj) { if (!(obj.push || obj.forEach || obj.indexOf)) { return true; } return false; }; </div> <h4>$.each</h4> <p>As you guess, each function is one of the fundamentals. One thing about this challenge is that the cb looks like function(index, value) {}; </p> <div class=text-editor> $.each = function(collection, cb) { if ($.isArray(collection)) { for (var i=0; i'<'collection.length; i++) { return cb.call(collection[i], i, collection[i]); } else if ($.isArrayLike(collection)) { for (var prep in collection) { return cb.call(collection[prep], i, collection[prep]); } } }; return collection; }; </div> <h4>$.makeArray</h4> <p>This function returns new array. To do so we can use $.each()</p> <div class=text-editor> $.makeArray = function(arr) { if ($.isArray(arr)) { return arr; } var newarr = []; $.each(arr, function(i, item) { newarr[i] = item; }); } </div> <h4>$.proxy</h4> <p>Take a function and retuns a new one that calls the original with a particular context.</p> <div class=text-editor> $.proxy = function(fn, context) { return function() { return fn.apply(context, arguments) }; }; </div> <p>The key here is to invoke the function with apply, we need another function. The proxy returns a function which will call the function. The reson is that if the function being called then it will set 'this' something other than context. </p> <h4>$.html(mewHTML)</h4> <p>There is a property called 'innerText' which returns text within the element</p> <div class=text-editor> $.html = function(newHtml) { if (arguments.length) { return $.each(this, function(i, element){ element.innerText = newHTML; }) }else { return this[0].innertext; } } </div> <h4>$.text(newText)</h4> <p>The text function will get/set the text portion of an element. This is actually big hard question. Let's take a look more on textnode. </p> <p>textnode is literally 'text' in the element. It is possible to create text node like var text = document.createTextNode('hello');. More importantly, each node like elementnode and textnode has different value. </p> <p>The challenge of this problem is if argument is not passed, first, we have to get all textnode from each and every nested elements. If the element's child nodetype === 3, which is TEXT_NODE, then it will return, otherwise go down to child's child node until it finds text node to return</p> <div class=text-editor> $.getText = function(node) { var text = ''; $.each(node, function(index, child){ if (node.nodetype === 3) { text+=child.nodeValue; }else { text+= getText(child.childNodes); } }); return text; }; $.text = function(newText) { if (arguments.length) { //this.html(""); this will do el.innerHTML = "" $.each(this, function(index, element) { element.innerHTML = ""; var textnode = document.createTextNode(newText); element.appendChild(textnode); }) } else { return getText.call(this[0].childNodes) } }; </div> </main> </body> <hr> <footer> Sarah Kwak 2015 &#169; copyrights </footer> </html>
# generator-hapi-mysql-routes
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Peach.Transformers.compress</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="Peach-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://peachfuzzer.com">Peach API</a></th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="Peach-module.html">Package&nbsp;Peach</a> :: <a href="Peach.Transformers-module.html">Package&nbsp;Transformers</a> :: Module&nbsp;compress </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== MODULE DESCRIPTION ==================== --> <h1 class="epydoc">Module compress</h1><p class="nomargin-top"><span class="codelink"><a href="Peach.Transformers.compress-pysrc.html">source&nbsp;code</a></span></p> <p>Some default compression transforms (gzip, compress, etc).</p> <hr /> <div class="fields"> <p><strong>Author:</strong> Michael Eddington </p> <p><strong>Version:</strong> $Id: compress.py 2020 2010-04-14 23:13:14Z meddingt $ </p> </div><!-- ==================== CLASSES ==================== --> <a name="section-Classes"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Classes</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Classes" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="Peach.Transformers.compress.GzipCompress-class.html" class="summary-name">GzipCompress</a><br /> Gzip compression transform. </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="Peach.Transformers.compress.GzipDecompress-class.html" class="summary-name">GzipDecompress</a><br /> Gzip decompression transform. </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="Peach.Transformers.compress.Bz2Compress-class.html" class="summary-name">Bz2Compress</a><br /> bzip2 compression transform. </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="Peach.Transformers.compress.Bz2Decompress-class.html" class="summary-name">Bz2Decompress</a><br /> bzip2 decompression transform. </td> </tr> </table> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="Peach-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://peachfuzzer.com">Peach API</a></th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Thu Apr 15 18:19:28 2010 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>