<commit_before>/**
 * Created by Machine on 20-Mar-17.
 */

'use strict'

const request = require('request')
const fetch = require('node-fetch')
const Config = require('../config')

const callSendAPI = function (messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {access_token: Config.FB_PAGE_TOKEN},
    method: 'POST',
    json: messageData
  }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      let recipientId = body.recipient_id
      let messageId = body.message_id
      if (messageId) {
        console.log("Successfully sent message with id %s to recipient %s", messageId, recipientId)
      } else {
        console.log("Successfully called Send API for recipient %s", recipientId)
      }
    } else {
      console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error)
    }
  })
}

const sendTextMessage = function (recipientId, messageText) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText,
      metadata: 'DEV_HACKING'
    }
  }
  callSendAPI(messageData)
}

const sendMessageType = function (recipientId, type, payload) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: type,
        payload: payload
      }
    }
  }

  callSendAPI(messageData)
}

const sendQuickReply = function (recipientId, message) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    message: message
  }
  callSendAPI(messageData)
}

const sendReadReceipt = function (recipientId) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    sender_action: 'mark_seen'
  }
  callSendAPI(messageData)
}

const sendTypingOn = function (recipientId) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    sender_action: 'typing_on'
  };

  callSendAPI(messageData);
}

const sendTypingOff = function (recipientId) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    sender_action: 'typing_off'
  };

  callSendAPI(messageData);
}

const sendMessageTemplate = function (event) {
  let senderID = event.sender.id;
  let recipientID = event.recipient.id;
  let timeOfMessage = event.timestamp;
  let message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  let isEcho = message.is_echo;
  let messageId = message.mid;
  let appId = message.app_id;
  let metadata = message.metadata;

  // You may get a text or attachment but not both
  let messageText = message.text;
  let messageAttachments = message.attachments;
  let quickReply = message.quick_reply;

  if (isEcho) {
    // Just logging message echoes to console
    console.log("Received echo for message %s and app %d with metadata %s",
      messageId, appId, metadata);
    return;
  } else if (quickReply) {
    let quickReplyPayload = quickReply.payload;
    console.log("Quick reply for message %s with payload %s",
      messageId, quickReplyPayload);

    sendTextMessage(senderID, "Quick reply tapped");
    return;
  }

  if (messageText) {

    // If we receive a text message, check to see if it matches any special
    // keywords and send back the corresponding example. Otherwise, just echo
    // the text we received.
    switch (messageText) {
      case 'image':
        sendMessageType(senderID, 'image', {
          url: Config.SERVER_URL + '/assets/image.png'
        })
        break;

      case 'gif':
        sendMessageType(senderID, 'image', {
          url: Config.SERVER_URL + '/assets/image.gif'
        });
        break;

      case 'audio':
        sendMessageType(senderID, 'audio', {
          url: Config.SERVER_URL + '/assets/music.mp3'
        });
        break;

      case 'video':
        sendMessageType(senderID, 'video', {
          url: Config.SERVER_URL + '/assets/bigbuck.mp4'
        });
        break;

      case 'file':
        sendMessageType(senderID, 'file', {
          url: Config.SERVER_URL + '/assets/prototype.pdf'
        });
        break;

      case 'button':
        sendMessageType(senderID, 'template', {
          template_type: 'button',
          text: 'The 100dayproject',
          buttons: [{
            type: 'web_url',
            url: 'http://100dayproject.org',
            title: 'Open Web Url'
          }, {
            type: 'postback',
            title: 'Trigger Postback',
            payload: 'DEV_DEFINED_PAYLOAD'
          }, {
            type: 'phone_number',
            title: 'Call Phone Number',
            payload: "0963296583"
          }]
        })
        break;

      case 'generic':
        sendMessageType(senderID, 'template', {
          template_type: 'generic',
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: Config.SERVER_URL + "/assets/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: Config.SERVER_URL + "/assets/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        })
        break;

      case 'receipt':
        sendMessageType(senderID, 'template', {
          template_type: "receipt",
          recipient_name: "Peter Chang",
          order_number: senderID,
          currency: "USD",
          payment_method: "Visa 1234",
          timestamp: "1428444852",
          elements: [{
            title: "Oculus Rift",
            subtitle: "Includes: headset, sensor, remote",
            quantity: 1,
            price: 599.00,
            currency: "USD",
            image_url: Config.SERVER_URL + "/assets/riftsq.png"
          }, {
            title: "Samsung Gear VR",
            subtitle: "Frost White",
            quantity: 1,
            price: 99.99,
            currency: "USD",
            image_url: Config.SERVER_URL + "/assets/gearvrsq.png"
          }],
          address: {
            street_1: "1 Hacker Way",
            street_2: "",
            city: "Menlo Park",
            postal_code: "94025",
            state: "CA",
            country: "US"
          },
          summary: {
            subtotal: 698.99,
            shipping_cost: 20.00,
            total_tax: 57.67,
            total_cost: 626.66
          },
          adjustments: [{
            name: "New Customer Discount",
            amount: -50
          }, {
            name: "$100 Off Coupon",
            amount: -100
          }]
        })
        break;

      case 'quick reply':
        sendQuickReply(senderID, {
          text: "What's your favorite movie genre?",
          quick_replies: [
            {
              "content_type": "text",
              "title": "Action",
              "payload": "DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_ACTION"
            },
            {
              "content_type": "text",
              "title": "Comedy",
              "payload": "DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_COMEDY"
            },
            {
              "content_type": "text",
              "title": "Drama",
              "payload": "DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_DRAMA"
            }
          ]
        })
        break;

      case 'read receipt':
        sendReadReceipt(senderID);
        break;

      case 'typing on':
        sendTypingOn(senderID);
        break;

      case 'typing off':
        sendTypingOff(senderID);
        break;

      case 'account linking':
        sendMessageType(senderID, 'template', {
          template_type: 'button',
          text: 'Welcome. Link your account',
          buttons: [{
            type: 'account_link',
            url: Config.SERVER_URL + '/authorize'
          }]
        })
        break;

      default:
        sendTextMessage(senderID, messageText)
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, 'Message with attachment received')
  }
}

module.exports = {
  sendMessageTemplate: sendMessageTemplate,
  sendMessageType: sendMessageType,
  sendTextMessage: sendTextMessage,
  sendQuickReply: sendQuickReply,
  sendTypingOn: sendTypingOn,
  sendTypingOff: sendTypingOff
}
<commit_msg>Fix sendQuickReply, add parse template<commit_after>/**
 * Created by Machine on 20-Mar-17.
 */

'use strict'

const request = require('request')
const fetch = require('node-fetch')
const Config = require('../config')

const callSendAPI = function (messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {access_token: Config.FB_PAGE_TOKEN},
    method: 'POST',
    json: messageData
  }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      let recipientId = body.recipient_id
      let messageId = body.message_id
      if (messageId) {
        console.log("Successfully sent message with id %s to recipient %s", messageId, recipientId)
      } else {
        console.log("Successfully called Send API for recipient %s", recipientId)
      }
    } else {
      console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error)
    }
  })
}

const sendTextMessage = function (recipientId, messageText) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText,
      metadata: 'DEV_HACKING'
    }
  }
  callSendAPI(messageData)
}

const sendMessageType = function (recipientId, type, payload) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      attachment: {
        type: type,
        payload: payload
      }
    }
  }

  callSendAPI(messageData)
}

const sendQuickReply = function (recipientId, payload) {
  let message = {
    text: payload.text,
    quick_replies: payload.map(function (item) {
      return {
        'content_type': 'text',
        'title': item,
        'payload:': item
      }
    })
  }

  let messageData = {
    recipient: {
      id: recipientId
    },
    message: message
  }
  callSendAPI(messageData)
}

const sendReadReceipt = function (recipientId) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    sender_action: 'mark_seen'
  }
  callSendAPI(messageData)
}

const sendTypingOn = function (recipientId) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    sender_action: 'typing_on'
  };

  callSendAPI(messageData);
}

const sendTypingOff = function (recipientId) {
  let messageData = {
    recipient: {
      id: recipientId
    },
    sender_action: 'typing_off'
  };

  callSendAPI(messageData);
}

const sendMessageTemplate = function (event) {
  let senderID = event.sender.id;
  let recipientID = event.recipient.id;
  let timeOfMessage = event.timestamp;
  let message = event.message;

  console.log("Received message for user %d and page %d at %d with message:",
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  let isEcho = message.is_echo;
  let messageId = message.mid;
  let appId = message.app_id;
  let metadata = message.metadata;

  // You may get a text or attachment but not both
  let messageText = message.text;
  let messageAttachments = message.attachments;
  let quickReply = message.quick_reply;

  if (isEcho) {
    // Just logging message echoes to console
    console.log("Received echo for message %s and app %d with metadata %s",
      messageId, appId, metadata);
    return;
  } else if (quickReply) {
    let quickReplyPayload = quickReply.payload;
    console.log("Quick reply for message %s with payload %s",
      messageId, quickReplyPayload);

    sendTextMessage(senderID, "Quick reply tapped");
    return;
  }

  if (messageText) {

    // If we receive a text message, check to see if it matches any special
    // keywords and send back the corresponding example. Otherwise, just echo
    // the text we received.
    switch (messageText) {
      case 'image':
        sendMessageType(senderID, 'image', {
          url: Config.SERVER_URL + '/assets/image.png'
        })
        break;

      case 'gif':
        sendMessageType(senderID, 'image', {
          url: Config.SERVER_URL + '/assets/image.gif'
        });
        break;

      case 'audio':
        sendMessageType(senderID, 'audio', {
          url: Config.SERVER_URL + '/assets/music.mp3'
        });
        break;

      case 'video':
        sendMessageType(senderID, 'video', {
          url: Config.SERVER_URL + '/assets/bigbuck.mp4'
        });
        break;

      case 'file':
        sendMessageType(senderID, 'file', {
          url: Config.SERVER_URL + '/assets/prototype.pdf'
        });
        break;

      case 'button':
        sendMessageType(senderID, 'template', {
          template_type: 'button',
          text: 'The 100dayproject',
          buttons: [{
            type: 'web_url',
            url: 'http://100dayproject.org',
            title: 'Open Web Url'
          }, {
            type: 'postback',
            title: 'Trigger Postback',
            payload: 'DEV_DEFINED_PAYLOAD'
          }, {
            type: 'phone_number',
            title: 'Call Phone Number',
            payload: "0963296583"
          }]
        })
        break;

      case 'generic':
        sendMessageType(senderID, 'template', {
          template_type: 'generic',
          elements: [{
            title: "rift",
            subtitle: "Next-generation virtual reality",
            item_url: "https://www.oculus.com/en-us/rift/",
            image_url: Config.SERVER_URL + "/assets/rift.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/rift/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for first bubble",
            }],
          }, {
            title: "touch",
            subtitle: "Your Hands, Now in VR",
            item_url: "https://www.oculus.com/en-us/touch/",
            image_url: Config.SERVER_URL + "/assets/touch.png",
            buttons: [{
              type: "web_url",
              url: "https://www.oculus.com/en-us/touch/",
              title: "Open Web URL"
            }, {
              type: "postback",
              title: "Call Postback",
              payload: "Payload for second bubble",
            }]
          }]
        })
        break;

      case 'receipt':
        sendMessageType(senderID, 'template', {
          template_type: "receipt",
          recipient_name: "Peter Chang",
          order_number: senderID,
          currency: "USD",
          payment_method: "Visa 1234",
          timestamp: "1428444852",
          elements: [{
            title: "Oculus Rift",
            subtitle: "Includes: headset, sensor, remote",
            quantity: 1,
            price: 599.00,
            currency: "USD",
            image_url: Config.SERVER_URL + "/assets/riftsq.png"
          }, {
            title: "Samsung Gear VR",
            subtitle: "Frost White",
            quantity: 1,
            price: 99.99,
            currency: "USD",
            image_url: Config.SERVER_URL + "/assets/gearvrsq.png"
          }],
          address: {
            street_1: "1 Hacker Way",
            street_2: "",
            city: "Menlo Park",
            postal_code: "94025",
            state: "CA",
            country: "US"
          },
          summary: {
            subtotal: 698.99,
            shipping_cost: 20.00,
            total_tax: 57.67,
            total_cost: 626.66
          },
          adjustments: [{
            name: "New Customer Discount",
            amount: -50
          }, {
            name: "$100 Off Coupon",
            amount: -100
          }]
        })
        break;

      case 'quick reply':
        sendQuickReply(senderID, {
          text: "What's your favorite movie genre?",
          quick_replies: [
            {
              "content_type": "text",
              "title": "Action",
              "payload": "DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_ACTION"
            },
            {
              "content_type": "text",
              "title": "Comedy",
              "payload": "DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_COMEDY"
            },
            {
              "content_type": "text",
              "title": "Drama",
              "payload": "DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_DRAMA"
            }
          ]
        })
        break;

      case 'read receipt':
        sendReadReceipt(senderID);
        break;

      case 'typing on':
        sendTypingOn(senderID);
        break;

      case 'typing off':
        sendTypingOff(senderID);
        break;

      case 'account linking':
        sendMessageType(senderID, 'template', {
          template_type: 'button',
          text: 'Welcome. Link your account',
          buttons: [{
            type: 'account_link',
            url: Config.SERVER_URL + '/authorize'
          }]
        })
        break;

      default:
        sendTextMessage(senderID, messageText)
    }
  } else if (messageAttachments) {
    sendTextMessage(senderID, 'Message with attachment received')
  }
}

module.exports = {
  sendMessageTemplate: sendMessageTemplate,
  sendMessageType: sendMessageType,
  sendTextMessage: sendTextMessage,
  sendQuickReply: sendQuickReply,
  sendTypingOn: sendTypingOn,
  sendTypingOff: sendTypingOff
}
<|endoftext|>


<commit_before>const request = require('sync-request')
const textrApostrophes = require('typographic-apostrophes')
const textrApostrophesForPlurals = require('typographic-apostrophes-for-possessive-plurals')
const textrCopyright = require('typographic-copyright')
const textrEllipses = require('typographic-ellipses')
const textrEmDashes = require('typographic-em-dashes')
const textrEnDashes = require('typographic-en-dashes')
const textrRegisteredTrademark = require('typographic-registered-trademark')
const textrSingleSpaces = require('typographic-single-spaces')
const textrTrademark = require('typographic-trademark')

const textrColon = require('typographic-colon')
const textrEmDash = require('typographic-em-dash')
const textrExclamationMark = require('typographic-exclamation-mark')
const textrGuillemets = require('typographic-guillemets')
const textrPercent = require('typographic-percent')
const textrPermille = require('typographic-permille')
const textrQuestionMark = require('typographic-question-mark')
const textrSemicolon = require('typographic-semicolon')

const remarkConfig = {
  reParse: {
    gfm: true,
    commonmark: false,
    footnotes: true,
    pedantic: true,
    /* sets list of known blocks to nothing, otherwise
hey
 would become
    <h3>hey</h3> instead of
<h3>hey</h3>
 */
    blocks: [],
  },

  textr: {
    plugins: [
      textrApostrophes,
      textrApostrophesForPlurals,
      textrEllipses,
      textrEmDashes,
      textrEnDashes,
      textrCopyright,
      textrRegisteredTrademark,
      textrSingleSpaces,
      textrTrademark,

      textrColon,
      textrEmDash,
      textrExclamationMark,
      textrGuillemets,
      textrPercent,
      textrPermille,
      textrQuestionMark,
      textrSemicolon,
    ],
    options: {
      locale: 'fr',
    },
  },

  autolinkHeadings: {
    behaviour: 'append',
  },

  headingShifter: 0,

  remark2rehype: {
    allowDangerousHTML: true
  },

  footnotesTitles: 'Retourner au texte de la note $id',

  alignBlocks: {
    center: 'align-center',
    right: 'align-right',
  },

  customBlocks: {
    secret: 'spoiler',
    s: 'spoiler',
    information: 'information ico-after',
    i: 'information ico-after',
    question: 'question ico-after',
    q: 'question ico-after',
    attention: 'warning ico-after',
    a: 'warning ico-after',
    erreur: 'error ico-after',
    e: 'error ico-after',
  },

  escapeEscaped: ['&'],

  emoticons: {
    emoticons: {
      ':ange:': '/static/smileys/ange.png',
      ':colere:': '/static/smileys/angry.gif',
      'o_O': '/static/smileys/blink.gif',
      ';)': '/static/smileys/clin.png',
      ':diable:': '/static/smileys/diable.png',
      ':D': '/static/smileys/heureux.png',
      '^^': '/static/smileys/hihi.png',
      ':o': '/static/smileys/huh.png',
      ':p': '/static/smileys/langue.png',
      ':magicien:': '/static/smileys/magicien.png',
      ':colere2:': '/static/smileys/mechant.png',
      ':ninja:': '/static/smileys/ninja.png',
      'x(': '/static/smileys/pinch.png',
      ':pirate:': '/static/smileys/pirate.png',
      ":'(": '/static/smileys/pleure.png',
      ':lol:': '/static/smileys/rire.gif',
      ':honte:': '/static/smileys/rouge.png',
      ':-°': '/static/smileys/siffle.png',
      ':)': '/static/smileys/smile.png',
      ':soleil:': '/static/smileys/soleil.png',
      ':(': '/static/smileys/triste.png',
      ':euh:': '/static/smileys/unsure.gif',
      ':waw:': '/static/smileys/waw.png',
      ':zorro:': '/static/smileys/zorro.png',
    },
    classes: 'smiley'
  },

  math: {
    inlineMathDouble: true
  },

  katex: {
    inlineMathDoubleDisplay: true
  },

  iframes: {
    'www.dailymotion.com': {
      tag: 'iframe',
      width: 480,
      height: 270,
      disabled: false,
      replace: [
        ['video/', 'embed/video/'],
      ],
      thumbnail: {
        format: 'http://www.dailymotion.com/thumbnail/video/{id}',
        id: '.+/(.+)$'
      }
    },
    'www.vimeo.com': {
      tag: 'iframe',
      width: 500,
      height: 281,
      disabled: false,
      replace: [
        ['http://', 'https://'],
        ['www.', ''],
        ['vimeo.com/', 'player.vimeo.com/video/'],
      ]
    },
    'vimeo.com': {
      tag: 'iframe',
      width: 500,
      height: 281,
      disabled: false,
      replace: [
        ['http://', 'https://'],
        ['www.', ''],
        ['vimeo.com/', 'player.vimeo.com/video/'],
      ]
    },
    'www.youtube.com': {
      tag: 'iframe',
      width: 560,
      height: 315,
      disabled: false,
      replace: [
        ['watch?v=', 'embed/'],
        ['http://', 'https://'],
      ],
      thumbnail: {
        format: 'http://img.youtube.com/vi/{id}/0.jpg',
        id: '.+/(.+)$'
      },
      removeAfter: '&'
    },
    'youtube.com': {
      tag: 'iframe',
      width: 560,
      height: 315,
      disabled: false,
      replace: [
        ['watch?v=', 'embed/'],
        ['http://', 'https://'],
      ],
      thumbnail: {
        format: 'http://img.youtube.com/vi/{id}/0.jpg',
        id: '.+/(.+)$'
      },
      removeAfter: '&'
    },
    'youtu.be': {
      tag: 'iframe',
      width: 560,
      height: 315,
      disabled: false,
      replace: [
        ['watch?v=', 'embed/'],
        ['youtu.be', 'www.youtube.com/embed'],
      ],
      thumbnail: {
        format: 'http://img.youtube.com/vi/{id}/0.jpg',
        id: '.+/(.+)$'
      },
      removeAfter: '&'
    },
    'www.ina.fr': {
      tag: 'iframe',
      width: 620,
      height: 349,
      disabled: false,
      replace: [
        ['www.', 'player.'],
        ['/video/', '/player/embed/'],
      ],
      append: '/1/1b0bd203fbcd702f9bc9b10ac3d0fc21/560/315/1/148db8',
      removeFileName: true
    },
    'www.jsfiddle.net': {
      tag: 'iframe',
      width: 560,
      height: 560,
      disabled: false,
      replace: [
        ['http://', 'https://'],
      ],
      append: 'embedded/result,js,html,css/',
      match: /https?:\/\/(www\.)?jsfiddle\.net\/([\w\d]+\/[\w\d]+\/\d+\/?|[\w\d]+\/\d+\/?|[\w\d]+\/?)$/,
      thumbnail: {
        format: 'http://www.unixstickers.com/image/data/stickers' +
        '/jsfiddle/JSfiddle-blue-w-type.sh.png',
      },
    },
    'jsfiddle.net': {
      tag: 'iframe',
      width: 560,
      height: 560,
      disabled: false,
      replace: [
        ['http://', 'https://'],
      ],
      append: 'embedded/result,js,html,css/',
      match: /https?:\/\/(www\.)?jsfiddle\.net\/([\w\d]+\/[\w\d]+\/\d+\/?|[\w\d]+\/\d+\/?|[\w\d]+\/?)$/,
      thumbnail: {
        format: 'http://www.unixstickers.com/image/data/stickers' +
        '/jsfiddle/JSfiddle-blue-w-type.sh.png',
      },
    }
  },

  captions: {
    external: {
      table: 'Table:',
      gridTable: 'Table:',
      code: 'Code:',
      math: 'Equation:',
    },
    internal: {
      iframe: 'Video:',
      math: 'Equation:',
      inlineMath: 'Equation:',
      image: 'Figure:'
    }
  },

  ping: {
    pingUsername: (username) => {
      try {
        const result = request(
          'GET',
          `https://zestedesavoir.com/api/membres/exists/?search=${username}`,
          {timeout: 300}
        )
        return result.statusCode === 200
      } catch (ex) {
        console.error(ex)
        return false
      }
    },
    userURL: (username) => `/membres/voir/${username}/`,
  },

  disableTokenizers: {},
}

module.exports = remarkConfig
<commit_msg>zmarkdown: iframe captions are external<commit_after>const request = require('sync-request')
const textrApostrophes = require('typographic-apostrophes')
const textrApostrophesForPlurals = require('typographic-apostrophes-for-possessive-plurals')
const textrCopyright = require('typographic-copyright')
const textrEllipses = require('typographic-ellipses')
const textrEmDashes = require('typographic-em-dashes')
const textrEnDashes = require('typographic-en-dashes')
const textrRegisteredTrademark = require('typographic-registered-trademark')
const textrSingleSpaces = require('typographic-single-spaces')
const textrTrademark = require('typographic-trademark')

const textrColon = require('typographic-colon')
const textrEmDash = require('typographic-em-dash')
const textrExclamationMark = require('typographic-exclamation-mark')
const textrGuillemets = require('typographic-guillemets')
const textrPercent = require('typographic-percent')
const textrPermille = require('typographic-permille')
const textrQuestionMark = require('typographic-question-mark')
const textrSemicolon = require('typographic-semicolon')

const remarkConfig = {
  reParse: {
    gfm: true,
    commonmark: false,
    footnotes: true,
    pedantic: true,
    /* sets list of known blocks to nothing, otherwise
hey
 would become
    <h3>hey</h3> instead of
<h3>hey</h3>
 */
    blocks: [],
  },

  textr: {
    plugins: [
      textrApostrophes,
      textrApostrophesForPlurals,
      textrEllipses,
      textrEmDashes,
      textrEnDashes,
      textrCopyright,
      textrRegisteredTrademark,
      textrSingleSpaces,
      textrTrademark,

      textrColon,
      textrEmDash,
      textrExclamationMark,
      textrGuillemets,
      textrPercent,
      textrPermille,
      textrQuestionMark,
      textrSemicolon,
    ],
    options: {
      locale: 'fr',
    },
  },

  autolinkHeadings: {
    behaviour: 'append',
  },

  headingShifter: 0,

  remark2rehype: {
    allowDangerousHTML: true
  },

  footnotesTitles: 'Retourner au texte de la note $id',

  alignBlocks: {
    center: 'align-center',
    right: 'align-right',
  },

  customBlocks: {
    secret: 'spoiler',
    s: 'spoiler',
    information: 'information ico-after',
    i: 'information ico-after',
    question: 'question ico-after',
    q: 'question ico-after',
    attention: 'warning ico-after',
    a: 'warning ico-after',
    erreur: 'error ico-after',
    e: 'error ico-after',
  },

  escapeEscaped: ['&'],

  emoticons: {
    emoticons: {
      ':ange:': '/static/smileys/ange.png',
      ':colere:': '/static/smileys/angry.gif',
      'o_O': '/static/smileys/blink.gif',
      ';)': '/static/smileys/clin.png',
      ':diable:': '/static/smileys/diable.png',
      ':D': '/static/smileys/heureux.png',
      '^^': '/static/smileys/hihi.png',
      ':o': '/static/smileys/huh.png',
      ':p': '/static/smileys/langue.png',
      ':magicien:': '/static/smileys/magicien.png',
      ':colere2:': '/static/smileys/mechant.png',
      ':ninja:': '/static/smileys/ninja.png',
      'x(': '/static/smileys/pinch.png',
      ':pirate:': '/static/smileys/pirate.png',
      ":'(": '/static/smileys/pleure.png',
      ':lol:': '/static/smileys/rire.gif',
      ':honte:': '/static/smileys/rouge.png',
      ':-°': '/static/smileys/siffle.png',
      ':)': '/static/smileys/smile.png',
      ':soleil:': '/static/smileys/soleil.png',
      ':(': '/static/smileys/triste.png',
      ':euh:': '/static/smileys/unsure.gif',
      ':waw:': '/static/smileys/waw.png',
      ':zorro:': '/static/smileys/zorro.png',
    },
    classes: 'smiley'
  },

  math: {
    inlineMathDouble: true
  },

  katex: {
    inlineMathDoubleDisplay: true
  },

  iframes: {
    'www.dailymotion.com': {
      tag: 'iframe',
      width: 480,
      height: 270,
      disabled: false,
      replace: [
        ['video/', 'embed/video/'],
      ],
      thumbnail: {
        format: 'http://www.dailymotion.com/thumbnail/video/{id}',
        id: '.+/(.+)$'
      }
    },
    'www.vimeo.com': {
      tag: 'iframe',
      width: 500,
      height: 281,
      disabled: false,
      replace: [
        ['http://', 'https://'],
        ['www.', ''],
        ['vimeo.com/', 'player.vimeo.com/video/'],
      ]
    },
    'vimeo.com': {
      tag: 'iframe',
      width: 500,
      height: 281,
      disabled: false,
      replace: [
        ['http://', 'https://'],
        ['www.', ''],
        ['vimeo.com/', 'player.vimeo.com/video/'],
      ]
    },
    'www.youtube.com': {
      tag: 'iframe',
      width: 560,
      height: 315,
      disabled: false,
      replace: [
        ['watch?v=', 'embed/'],
        ['http://', 'https://'],
      ],
      thumbnail: {
        format: 'http://img.youtube.com/vi/{id}/0.jpg',
        id: '.+/(.+)$'
      },
      removeAfter: '&'
    },
    'youtube.com': {
      tag: 'iframe',
      width: 560,
      height: 315,
      disabled: false,
      replace: [
        ['watch?v=', 'embed/'],
        ['http://', 'https://'],
      ],
      thumbnail: {
        format: 'http://img.youtube.com/vi/{id}/0.jpg',
        id: '.+/(.+)$'
      },
      removeAfter: '&'
    },
    'youtu.be': {
      tag: 'iframe',
      width: 560,
      height: 315,
      disabled: false,
      replace: [
        ['watch?v=', 'embed/'],
        ['youtu.be', 'www.youtube.com/embed'],
      ],
      thumbnail: {
        format: 'http://img.youtube.com/vi/{id}/0.jpg',
        id: '.+/(.+)$'
      },
      removeAfter: '&'
    },
    'www.ina.fr': {
      tag: 'iframe',
      width: 620,
      height: 349,
      disabled: false,
      replace: [
        ['www.', 'player.'],
        ['/video/', '/player/embed/'],
      ],
      append: '/1/1b0bd203fbcd702f9bc9b10ac3d0fc21/560/315/1/148db8',
      removeFileName: true
    },
    'www.jsfiddle.net': {
      tag: 'iframe',
      width: 560,
      height: 560,
      disabled: false,
      replace: [
        ['http://', 'https://'],
      ],
      append: 'embedded/result,js,html,css/',
      match: /https?:\/\/(www\.)?jsfiddle\.net\/([\w\d]+\/[\w\d]+\/\d+\/?|[\w\d]+\/\d+\/?|[\w\d]+\/?)$/,
      thumbnail: {
        format: 'http://www.unixstickers.com/image/data/stickers' +
        '/jsfiddle/JSfiddle-blue-w-type.sh.png',
      },
    },
    'jsfiddle.net': {
      tag: 'iframe',
      width: 560,
      height: 560,
      disabled: false,
      replace: [
        ['http://', 'https://'],
      ],
      append: 'embedded/result,js,html,css/',
      match: /https?:\/\/(www\.)?jsfiddle\.net\/([\w\d]+\/[\w\d]+\/\d+\/?|[\w\d]+\/\d+\/?|[\w\d]+\/?)$/,
      thumbnail: {
        format: 'http://www.unixstickers.com/image/data/stickers' +
        '/jsfiddle/JSfiddle-blue-w-type.sh.png',
      },
    }
  },

  captions: {
    external: {
      table: 'Table:',
      gridTable: 'Table:',
      code: 'Code:',
      math: 'Equation:',
      iframe: 'Video:',
    },
    internal: {
      math: 'Equation:',
      inlineMath: 'Equation:',
      image: 'Figure:',
    }
  },

  ping: {
    pingUsername: (username) => {
      try {
        const result = request(
          'GET',
          `https://zestedesavoir.com/api/membres/exists/?search=${username}`,
          {timeout: 300}
        )
        return result.statusCode === 200
      } catch (ex) {
        console.error(ex)
        return false
      }
    },
    userURL: (username) => `/membres/voir/${username}/`,
  },

  disableTokenizers: {},
}

module.exports = remarkConfig
<|endoftext|>


<commit_before>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var SortPipe = (function () {
    function SortPipe() {
    }
    SortPipe.prototype.transform = function (array, args) {
        array.sort(function (a, b) {
            if (a[args] < b[args]) {
                return -1;
            }
            else if (a[args] > b[args]) {
                return 1;
            }
            else {
                return 0;
            }
        });
        return array;
    };
    SortPipe = __decorate([
        core_1.Pipe({ name: "sortBy" }),
        __metadata('design:paramtypes', [])
    ], SortPipe);
    return SortPipe;
}());
exports.SortPipe = SortPipe;
//# sourceMappingURL=sort.pipe.js.map<commit_msg>Delete sort.pipe.js<commit_after><|endoftext|>


<commit_before>/** @babel */
// converted from https://github.com/atom/atom/blob/master/spec/spec-helper.coffee

export default async function (options, setupView) {
	if (options === false) {
		return;
	}
	const all = (options === true);

	const installDep = require("./install-dep");

	const install = async function (pkg, version) {
		setupView.install(pkg, version);
		if (version) {
			await installDep(pkg, version);
		}

		require(pkg);
	};

	try {
		if (all || options.atom) {
			await install("./atom");
		}

		if (all || options.attachToDom) {
			await install("./attach-to-dom");
		}

		if (all || options.customMatchers) {
			await install("jasmine2-atom-matchers", "^1.1.0");
		}

		if (all || options.jasmineJson) {
			await install("jasmine2-json", "^1.1.0");
		}

		if (all || options.jasminePass) {
			await install("jasmine-pass", "^1.1.0");
		}

		if (all || options.jasmineShouldFail) {
			await install("jasmine-should-fail", "^1.1.4");
		}

		if (all || options.jasmineTagged) {
			await install("jasmine2-tagged", "^1.1.0");
		}

		if (all || options.jasmineFocused) {
			await install("jasmine2-focused", "^1.1.0");
		}

		if (all || options.mockClock) {
			await install("./clock");
		}

		if (all || options.mockLocalStorage) {
			await install("jasmine-local-storage", "^1.1.0");
		}

		if (all || options.pathwatcher) {
			await install("pathwatcher", "^8.0.1");
			await install("./pathwatcher");
		}

		if (all || options.profile) {
			await install("./profile");
		}

		if (all || options.set) {
			await install("./set");
		}

		if (all || options.unspy) {
			// TODO: use https://github.com/jasmine/jasmine/pull/1289 if it is merged
			await install("jasmine-unspy", "^1.1.0");
		}

		if (all || options.ci) {
			await install("./ci");
		}
	} catch (ex) {
		setupView.error(ex.toString());

		throw ex;
	}
};
<commit_msg>update jasmine-should-fail<commit_after>/** @babel */
// converted from https://github.com/atom/atom/blob/master/spec/spec-helper.coffee

export default async function (options, setupView) {
	if (options === false) {
		return;
	}
	const all = (options === true);

	const installDep = require("./install-dep");

	const install = async function (pkg, version) {
		setupView.install(pkg, version);
		if (version) {
			await installDep(pkg, version);
		}

		require(pkg);
	};

	try {
		if (all || options.atom) {
			await install("./atom");
		}

		if (all || options.attachToDom) {
			await install("./attach-to-dom");
		}

		if (all || options.customMatchers) {
			await install("jasmine2-atom-matchers", "^1.1.0");
		}

		if (all || options.jasmineJson) {
			await install("jasmine2-json", "^1.1.0");
		}

		if (all || options.jasminePass) {
			await install("jasmine-pass", "^1.1.0");
		}

		if (all || options.jasmineShouldFail) {
			await install("jasmine-should-fail", "^1.1.5");
		}

		if (all || options.jasmineTagged) {
			await install("jasmine2-tagged", "^1.1.0");
		}

		if (all || options.jasmineFocused) {
			await install("jasmine2-focused", "^1.1.0");
		}

		if (all || options.mockClock) {
			await install("./clock");
		}

		if (all || options.mockLocalStorage) {
			await install("jasmine-local-storage", "^1.1.0");
		}

		if (all || options.pathwatcher) {
			await install("pathwatcher", "^8.0.1");
			await install("./pathwatcher");
		}

		if (all || options.profile) {
			await install("./profile");
		}

		if (all || options.set) {
			await install("./set");
		}

		if (all || options.unspy) {
			// TODO: use https://github.com/jasmine/jasmine/pull/1289 if it is merged
			await install("jasmine-unspy", "^1.1.0");
		}

		if (all || options.ci) {
			await install("./ci");
		}
	} catch (ex) {
		setupView.error(ex.toString());

		throw ex;
	}
};
<|endoftext|>


<commit_before>/**
 * @fileoverview 所有关于系统中对文档进行的相关操作的方法，包括增删查改等等的操作
 * @version 2012.10.03
 *
 */

var EventProxy = require('eventproxy').EventProxy;

/**
 * @description 获取所有的文章的方法
 * @param {function} callback 获取成功后触发的回调函数
 */
exports.getAllPosts = function(callback) {
    var Post = db.models.Post, Tag = db.models.Tag, Category = db.models.Category;
    var proxy = new EventProxy;
    var eventHooks = ['posts', 'categories', 'tags'];
    proxy.assign(eventHooks, callback);

    Post.find(function(error, posts) {
        var pids = [];
        for(var i in posts) {
            var pid = posts[i]._id;
            pids.push(pid.toString());
        }
        Category.find({pid: {'$in': pids}}, function(error, categories) {
            proxy.trigger('categories', categories);
        });
        Tag.find({pid: {'$in': pids}}, function(error, tags) {
            proxy.trigger('tags', tags)
        });
        proxy.trigger('posts', posts);
    });
}

/**
 * @description 获取单篇文章的内容
 * @param {string} pid 需要获取的文章的id
 * @param {function} callback 获取内容成功后的回调
 */
exports.getPost = function(pid, callback) {
    var Post = db.models.Post, Tag = db.models.Tag, Category = db.models.Category, Comment = db.models.Comment;
    var proxy = new EventProxy;
    var eventHooks = ['post', 'tags', 'categories', 'comments'];
    proxy.assign(eventHooks, callback);
    Post.findById(pid, function(error, post) {

    	// 更具时间获取前后两篇文章
    	// var postTime = post.date;
    	// console.log(postTime.toString());

        proxy.trigger('post', post);
    });
    Tag.find({pid: pid}, function(error, tags) {
        proxy.trigger('tags', tags);
    });
    Category.find({pid: pid}, function(error, categories) {
        proxy.trigger('categories', categories);
    });
    Comment.find({pid: pid}, function(error, comments) {
        proxy.trigger('comments', comments);
    });
}

/**
 * @description 获取近期发表的文章
 * @param {function} callback 获取内容成功后的回调
 */
exports.getRecentPosts = function(callback) {
    var Post = db.models.Post;
    callback();
}<commit_msg>ÂÒÂëÁË£¿<commit_after>/**
 * @fileoverview 所有关于系统中对文档进行的相关操作的方法，包括增删查改等等的操作
 * @version 2012.10.03
 *
 */

var EventProxy = require('eventproxy').EventProxy;

/**
 * @description 获取所有的文章的方法
 * @param {function} callback 获取成功后触发的回调函数
 */
exports.getAllPosts = function(callback) {
    var Post = db.models.Post, Tag = db.models.Tag, Category = db.models.Category;
    var proxy = new EventProxy;
    var eventHooks = ['posts', 'categories', 'tags'];
    proxy.assign(eventHooks, callback);

    Post.find(function(error, posts) {
        var pids = [];
        for(var i in posts) {
            var pid = posts[i]._id;
            pids.push(pid.toString());
        }
        Category.find({pid: {'$in': pids}}, function(error, categories) {
            proxy.trigger('categories', categories);
        });
        Tag.find({pid: {'$in': pids}}, function(error, tags) {
            proxy.trigger('tags', tags)
        });
        proxy.trigger('posts', posts);
    });
}

/**
 * @description 获取单篇文章的内容
 * @param {string} pid 需要获取的文章的id
 * @param {function} callback 获取内容成功后的回调
 */
exports.getPost = function(pid, callback) {
    var Post = db.models.Post, Tag = db.models.Tag, Category = db.models.Category, Comment = db.models.Comment;
    var proxy = new EventProxy;
    var eventHooks = ['post', 'tags', 'categories', 'comments'];
    proxy.assign(eventHooks, callback);
    Post.findById(pid, function(error, post) {

    	// 更具时间获取前后两篇文章
    	// var postTime = post.date;
    	// console.log(postTime.toString());

        proxy.trigger('post', post);
    });
    Tag.find({pid: pid}, function(error, tags) {
        proxy.trigger('tags', tags);
    });
    Category.find({pid: pid}, function(error, categories) {
        proxy.trigger('categories', categories);
    });
    Comment.find({pid: pid}, function(error, comments) {
        proxy.trigger('comments', comments);
    });
}

/**
 * @description 获取近期发表的文章
 * @param {function} callback 获取内容成功后的回调
 */
exports.getRecentPosts = function(callback) {
    var Post = db.models.Post;
    callback();
}<|endoftext|>


<commit_before>"use strict";

var deliver = require("eventual/deliver")
var defer = require("eventual/defer")
var when = require("eventual/when")
var accumulate = require("./accumulate")
var isError = require("./is-error")
var isReduced = require("./is-reduced")
var reduced = require("./reduced")

function reduce(source, f, state) {
  var promise = defer()
  accumulate(source, function reduce(value) {
    if (value === null) return reduced(deliver(promise, state))
    else if (isError(value)) return reduced(deliver(promise, value))
    else if (isReduced(value)) return value
    else return (state = f(state, value))
  }, state)
  return when(promise)
}

module.exports = reduce
<commit_msg>Update reduce.<commit_after>"use strict";

var deliver = require("eventual/deliver")
var defer = require("eventual/defer")
var when = require("eventual/when")
var accumulate = require("./accumulate")
var isError = require("./is-error")
var end = require("./end")

function reduce(source, next, initial) {
  var promise = defer()
  accumulate(source, function reduce(value, state) {
    if (value === end) deliver(promise, state)
    else if (isError(value)) deliver(promise, value)
    else state = next(state, value)

    return state
  }, initial)
  return when(promise, null, function(error) { return error })
}

module.exports = reduce
<|endoftext|>


<commit_before>var db = require('../models/DB_MYSQL');
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport();

module.exports.sendMail = function (book_id) {
  db.getQueueByBookId(book_id, function (err, result) {
    if(err) throw err;
      var mailOptions={
              from: 'noreply@programming.kr.ua',
              subject: 'Library SH++',
              html: 'The book with id= '+ book_id +' is free!',
              text: 'The book with id='+ book_id +' is free!'
      };
      for(var i = 0; i < result.length; i++){
          mailOptions.to = result[i].email;
          transporter.sendMail(mailOptions, function(error, info){
              if(error){
                  console.log(error);
              }
              db.deleteFromQueue(book_id,mailOptions.to,function (err, result) {
                  if(err){
                      console.log(err);
                  }
                  console.log(result);
              })
          });
      }
  });
};<commit_msg>mailer fix<commit_after>var db = require('../models/DB_MYSQL');
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport();

module.exports.sendMail = function (book_id) {
    db.getBook(book_id,function (err, bookInfo) {
        if (err){
            return console.log(err);
        }
        db.getQueueByBookId(bookInfo.id, function (err, result) {
            if (err){
                return console.log(err);
            }

            var mailOptions={
                from: 'noreply@programming.kr.ua',
                subject: 'Library SH++',
                html: 'Книга '+ bookInfo.title +' автор: ' + bookInfo.author + ', на которую вы подписались, теперь свободна.',
                text: 'Книга '+ bookInfo.title +' автор: ' + bookInfo.author + ', на которую вы подписались, теперь свободна.'
            };
            for(var i = 0; i < result.length; i++){
                mailOptions.to = result[i].email;
                transporter.sendMail(mailOptions, function(error, info){
                    if(error){
                        console.log(error);
                    }
                    db.deleteFromQueue(book_id,mailOptions.to,function (err, result) {
                        if(err){
                            console.log(err);
                        }
                        console.log(result);
                    })
                });
            }
        });
    });
};<|endoftext|>


<commit_before>var path = require('path');
// Postgres DATABASE_URL = postgress://user:passwd@host:port/database
// SQLite DATABASE_URL = sqlite://:@:/
var url =  process.env.DATABASE_URL.match(/(.*)\:\/\/(.*?)\:(.*)@(.*)\:(.*)\/(.*)/);
var protocol = (url[1] || null);
var dialect = (url[1] || null);
var user = (url[2] || null);
var pwd = (url[3] || null);
var host = (url[4] || null);
var port = (url[5] || null);
var DB_name = (url[6] || null);
var storage = process.env.DATABASE_STORAGE;
console.log("base de datos" + url);

// Cargar Modelo ORM
var Sequelize = require('sequelize');

// Usar BBDD SQLite: o Postgres
var sequelize = new Sequelize(DB_name, user, pwd,
	{ dialect: 	dialect,
	  protocol: protocol,
	  port: 	port,
	  host: 	host,
	  storage: 	storage,  //solo SQLite (.env)
	  omitNull: true		// solo Postgres
	}
);
console.log("base de datos" + sequelize.dialect + sequelize.protocol +sequelize.port + sequelize.host);
// Importar la definicion de la tabla Quiz en quiz.js
//var quiz_path = path.join(__dirname, 'quiz');
var Quiz = sequelize.import(path.join(__dirname, 'quiz'));
console.log("path" + path.join(__dirname, 'quiz'));
exports.Quiz = Quiz; // exportar definición de tabla Quiz
console.log("Quiz" + Quiz.pregunta);
// sequelize.sync() crea e inicializa tabla de preguntas en DB
sequelize.sync().then(function(){
	// then(..) ejecuta el manejador una vez creada la table
	Quiz.count().then(function(count){
		if(count === 0){
			Quiz.create({ pregunta : 'Capital de Italia', respuesta : 'Roma', tema: 'humanidades'});
			Quiz.create({ pregunta : 'Capital de Portugal', respuesta : 'Lisboa', tema: 'humanidades'});
		}
	});
});
<commit_msg>Subida practica 8 6<commit_after>var path = require('path');
// Postgres DATABASE_URL = postgress://user:passwd@host:port/database
// SQLite DATABASE_URL = sqlite://:@:/
var url =  process.env.DATABASE_URL.match(/(.*)\:\/\/(.*?)\:(.*)@(.*)\:(.*)\/(.*)/);
var protocol = (url[1] || null);
var dialect = (url[1] || null);
var user = (url[2] || null);
var pwd = (url[3] || null);
var host = (url[4] || null);
var port = (url[5] || null);
var DB_name = (url[6] || null);
var storage = process.env.DATABASE_STORAGE;

// Cargar Modelo ORM
var Sequelize = require('sequelize');

// Usar BBDD SQLite: o Postgres
var sequelize = new Sequelize(DB_name, user, pwd,
	{ dialect: 	dialect,
	  protocol: protocol,
	  port: 	port,
	  host: 	host,
	  storage: 	storage,  //solo SQLite (.env)
	  omitNull: true		// solo Postgres
	}
);
// Importar la definicion de la tabla Quiz en quiz.js
//var quiz_path = path.join(__dirname, 'quiz');
var Quiz = sequelize.import(path.join(__dirname, 'quiz'));
exports.Quiz = Quiz; // exportar definición de tabla Quiz
// sequelize.sync() crea e inicializa tabla de preguntas en DB
sequelize.sync().then(function(){
	// then(..) ejecuta el manejador una vez creada la table
	Quiz.count().then(function(count){
		if(count === 0){
			Quiz.create({ pregunta : 'Capital de Italia', respuesta : 'Roma', tema: 'humanidades'});
			Quiz.create({ pregunta : 'Capital de Portugal', respuesta : 'Lisboa', tema: 'humanidades'});
		}
	});
});
<|endoftext|>


<commit_before>/**
 * Definición de como se construye el modelo
 */

var path = require('path');

// Postgres DATABASE_URL = postgres://user:password@host:port/database
// SQLite   DATEBASE_URL = sqlite://:@:/
var url = process.env.DATABASE_URL.match(/(.*)\:\/\/(.*?)\:(.*)@(.*)\:(.*)\/(.*)/);
var DB_name = (url[6] || null);
var user = (url[2] || null);
var pwd = (url[3] || null);
var protocol = (url[1] || null);
var dialect = (url[1] || 'sqlite');
var port = (url[5] || null);
var host = (url[4] || null);
var storage = DB_name !== null ? process.env.DATABASE_STORAGE : 'quiz.sqlite';

// Cargar el modelo ORM
var Sequelize = require('sequelize');

// Usar BBDD SQLite o Postgres
var sequelize = new Sequelize(DB_name, user, pwd, {
	dialect: dialect,
	protocol: protocol,
	port: port,
	host: host,
	storage: storage, // solo SQLite (.env)
	omitNull: true // solo Postgres
	});

// Importar la definición de la tabla Quiz en quiz.js
var Quiz = sequelize.import(path.join(__dirname, 'quiz'));

// Quiz.drop({});

exports.Quiz = Quiz; // Exportar definición de tabla Quiz

var binomios = [
                {pregunta: 'Capital de Italia', respuesta: 'Roma', tema: 'humanidades'},
                {pregunta: 'Capital de Portugal', respuesta: 'Lisboa', tema: 'humanidades'}
                ];

// sequelize.sync() crea e inicializa tabla de preguntas en DB
sequelize.sync().then( function () {
	// la tabla se inicializa solo si está vacia
	for (var indexBi in binomios) {
		Quiz.findOrCreate({where: {pregunta: binomios[indexBi].pregunta}, defaults: {respuesta: binomios[indexBi].respuesta, tema: binomios[indexBi].tema}})
		  .spread(function(user, created) {
		    console.log(user.get({ plain: true }))
		});
	}
	console.log('Base de datos inicializada');
});<commit_msg>Ejercicio obligatorio modulo 8.1<commit_after>/**
 * Definición de como se construye el modelo
 */

var path = require('path');

// Postgres DATABASE_URL = postgres://user:password@host:port/database
// SQLite   DATEBASE_URL = sqlite://:@:/
var url = process.env.DATABASE_URL.match(/(.*)\:\/\/(.*?)\:(.*)@(.*)\:(.*)\/(.*)/);
var DB_name = (url[6] || null);
var user = (url[2] || null);
var pwd = (url[3] || null);
var protocol = (url[1] || null);
var dialect = (url[1] || 'sqlite');
var port = (url[5] || null);
var host = (url[4] || null);
var storage = DB_name !== null ? process.env.DATABASE_STORAGE : 'quiz.sqlite';

// Cargar el modelo ORM
var Sequelize = require('sequelize');

// Usar BBDD SQLite o Postgres
var sequelize = new Sequelize(DB_name, user, pwd, {
	dialect: dialect,
	protocol: protocol,
	port: port,
	host: host,
	storage: storage, // solo SQLite (.env)
	omitNull: true // solo Postgres
	});

// Importar la definición de la tabla Quiz en quiz.js
var Quiz = sequelize.import(path.join(__dirname, 'quiz'));

Quiz.drop({});

exports.Quiz = Quiz; // Exportar definición de tabla Quiz

var binomios = [
                {pregunta: 'Capital de Italia', respuesta: 'Roma', tema: 'humanidades'},
                {pregunta: 'Capital de Portugal', respuesta: 'Lisboa', tema: 'humanidades'}
                ];

// sequelize.sync() crea e inicializa tabla de preguntas en DB
sequelize.sync().then( function () {
	// la tabla se inicializa solo si está vacia
	for (var indexBi in binomios) {
		Quiz.findOrCreate({where: {pregunta: binomios[indexBi].pregunta}, defaults: {respuesta: binomios[indexBi].respuesta, tema: binomios[indexBi].tema}})
		  .spread(function(user, created) {
		    console.log(user.get({ plain: true }))
		});
	}
	console.log('Base de datos inicializada');
});<|endoftext|>


<commit_before>Cu.import("resource://gre/modules/XPCOMUtils.jsm");

var prefAutoCompleteFactory = null;

var gPreferencesListbox = null;

function onPreferencesLoad() {
  gPreferencesListbox = document.getElementById("preferences-listbox");
}
window.addEventListener("load", onPreferencesLoad, false);

function onPreferencesUnload() {
}
window.addEventListener("unload", onPreferencesUnload, false);

//boolean, integer, string

function setPreferences(config) {
  if ("preferences" in config) {
    for (var preference in config.preferences) {
      addPreference(preference, config.preferences[preference].value,
                       typeof config.preferences[preference].value,
                       config.preferences[preference].locked)
    }
  }
}

function getPreferences(config) {
  if (gPreferencesListbox.itemCount > 0) {
    if (!config.preferences) {
      config.preferences = {};
    }
  }
  for (var i=0; i < gPreferencesListbox.itemCount; i++) {
    var prefinfo = {};
    var listitem = gPreferencesListbox.getItemAtIndex(i);
    var name = listitem.childNodes[0].getAttribute("label");
    var type = listitem.childNodes[2].getAttribute("label");
    prefinfo.value = listitem.childNodes[3].getAttribute("label");
    switch (type) {
      case "integer":
        prefinfo.value = parseInt(prefinfo.value);
        break;
      case "boolean":
        prefinfo.value = JSON.parse(prefinfo.value);
        break;
    }
    if (listitem.hasAttribute("locked")) {
      prefinfo.locked = true;
    }
    config.preferences[name] = prefinfo;
  }
  return config;
}

function resetPreferences() {
  while (gPreferencesListbox.itemCount > 0) {
    gPreferencesListbox.removeItemAt(0);
  }
}

function onAddPreference() {
  var retVals = { name: null, value: null, type: null };
  var confirm = window.openDialog("chrome://cck2wizard/content/preferences-dialog.xul", "cck2wizard-preference", "modal,centerscreen", retVals);
  if ("cancel" in retVals) {
    return;
  }
  addPreference(retVals.name, retVals.value, retVals.type, false);
}

function addPreference(name, value, type, locked) {
  for (var i=0; i < gPreferencesListbox.itemCount; i++) {
    var listitem = gPreferencesListbox.getItemAtIndex(i);
    var label = listitem.firstChild.getAttribute("label");
    if (label == name) {
      Services.prompt.alert(window, "CCK2", "An entry for " + name + " already exists.")
      return;
    }
    if (label > name) {
      gPreferencesListbox.insertBefore(createPreferenceListItem(name, value, type, locked),
                                       listitem);
      return;
    }
  }
  gPreferencesListbox.appendChild(createPreferenceListItem(name, value, type, locked));
}

function createPreferenceListItem(name, value, type, locked) {
  var listitem = document.createElement("listitem");
  listitem.setAttribute("equalsize", "always");
  listitem.setAttribute("tooltiptext", name + ": " + value);
  var nameCell = document.createElement("listcell");
  nameCell.setAttribute("flex", "1");
  nameCell.setAttribute("crop", "end");
  nameCell.setAttribute("label", name);
  var typeCell = document.createElement("listcell");
  typeCell.setAttribute("flex", "1");
  if (type == "number") {
    type = "integer";
  }
  typeCell.setAttribute("label", type);
  var statusCell = document.createElement("listcell");
  statusCell.setAttribute("flex", "1");
  if (locked) {
    statusCell.setAttribute("label", "locked");
    listitem.setAttribute("locked", "true");
  } else {
    statusCell.setAttribute("label", "default");
  }
  var valueCell = document.createElement("listcell");
  valueCell.setAttribute("flex", "1");
  valueCell.setAttribute("label", value);
  listitem.appendChild(nameCell);
  listitem.appendChild(statusCell);
  listitem.appendChild(typeCell);
  listitem.appendChild(valueCell);
  listitem.setAttribute("context", "preferences-contextmenu");
  return listitem;
}

function updatePreferenceListItem(listitem, name, value, type, locked) {
  listitem.childNodes[0].setAttribute("label", name);
  listitem.childNodes[2].setAttribute("label", type);
  listitem.childNodes[3].setAttribute("label", value);
  listitem.setAttribute("tooltiptext", name + ": " + value);
}

function onDeletePreference() {
  if (gPreferencesListbox.selectedIndex == -1) {
    return;
  }
  gPreferencesListbox.removeChild(gPreferencesListbox.selectedItem);
}

function convertListItemToPreference(listitem) {
  var preference = {};
  preference.name = listitem.childNodes[0].getAttribute("label");
  preference.type = listitem.childNodes[2].getAttribute("label");
  var value = listitem.childNodes[3].getAttribute("label");
  switch (preference.type) {
    case "integer":
      value = parseInt(value);
      break;
    case "boolean":
      value = JSON.parse(value);
      break;
  }
  preference.value = value;
//    var locked = listitem.childNodes[3].getAttribute("label");
  return preference;
}

function onLockUnlockPreference() {
  var listitem = gPreferencesListbox.selectedItem;
  if (listitem.getAttribute("locked")) {
    listitem.removeAttribute("locked");
    listitem.childNodes[1].setAttribute("label", "default");
  } else {
    listitem.setAttribute("locked", "true");
    listitem.childNodes[1].setAttribute("label", "locked");
  }
}

function onPreferencesPopup(event) {
  var listitem = gPreferencesListbox.selectedItem;
  if (listitem.hasAttribute("locked")) {
    document.getElementById("preferences-lock").hidden = true;
    document.getElementById("preferences-unlock").hidden = false;
  } else {
    document.getElementById("preferences-lock").hidden = false;
    document.getElementById("preferences-unlock").hidden = true;
  }
}

function onEditPreference() {
  if (gPreferencesListbox.selectedIndex == -1) {
    return;
  }
  var retVals = convertListItemToPreference(gPreferencesListbox.selectedItem);
  window.openDialog("chrome://cck2wizard/content/preferences-dialog.xul", "cck2wizard-preference", "modal,centerscreen", retVals);
  if ("cancel" in retVals) {
    return;
  }
  updatePreferenceListItem(listitem, retVals.name, retVals.value, retVals.type, false);
}

function onKeyPressPreference(event) {
  if (event.keyCode == event.DOM_VK_ENTER ||
      event.keyCode == event.DOM_VK_RETURN) {
    onEditPreference();
  } else if (event.keyCode == event.DOM_VK_DELETE ||
             event.keyCode == event.DOM_VK_BACK_SPACE) {
    onDeletePreference();
  }
}<commit_msg>Bug where editing pref doesn't work<commit_after>Cu.import("resource://gre/modules/XPCOMUtils.jsm");

var prefAutoCompleteFactory = null;

var gPreferencesListbox = null;

function onPreferencesLoad() {
  gPreferencesListbox = document.getElementById("preferences-listbox");
}
window.addEventListener("load", onPreferencesLoad, false);

function onPreferencesUnload() {
}
window.addEventListener("unload", onPreferencesUnload, false);

//boolean, integer, string

function setPreferences(config) {
  if ("preferences" in config) {
    for (var preference in config.preferences) {
      addPreference(preference, config.preferences[preference].value,
                       typeof config.preferences[preference].value,
                       config.preferences[preference].locked)
    }
  }
}

function getPreferences(config) {
  if (gPreferencesListbox.itemCount > 0) {
    if (!config.preferences) {
      config.preferences = {};
    }
  }
  for (var i=0; i < gPreferencesListbox.itemCount; i++) {
    var prefinfo = {};
    var listitem = gPreferencesListbox.getItemAtIndex(i);
    var name = listitem.childNodes[0].getAttribute("label");
    var type = listitem.childNodes[2].getAttribute("label");
    prefinfo.value = listitem.childNodes[3].getAttribute("label");
    switch (type) {
      case "integer":
        prefinfo.value = parseInt(prefinfo.value);
        break;
      case "boolean":
        prefinfo.value = JSON.parse(prefinfo.value);
        break;
    }
    if (listitem.hasAttribute("locked")) {
      prefinfo.locked = true;
    }
    config.preferences[name] = prefinfo;
  }
  return config;
}

function resetPreferences() {
  while (gPreferencesListbox.itemCount > 0) {
    gPreferencesListbox.removeItemAt(0);
  }
}

function onAddPreference() {
  var retVals = { name: null, value: null, type: null };
  var confirm = window.openDialog("chrome://cck2wizard/content/preferences-dialog.xul", "cck2wizard-preference", "modal,centerscreen", retVals);
  if ("cancel" in retVals) {
    return;
  }
  addPreference(retVals.name, retVals.value, retVals.type, false);
}

function addPreference(name, value, type, locked) {
  for (var i=0; i < gPreferencesListbox.itemCount; i++) {
    var listitem = gPreferencesListbox.getItemAtIndex(i);
    var label = listitem.firstChild.getAttribute("label");
    if (label == name) {
      Services.prompt.alert(window, "CCK2", "An entry for " + name + " already exists.")
      return;
    }
    if (label > name) {
      gPreferencesListbox.insertBefore(createPreferenceListItem(name, value, type, locked),
                                       listitem);
      return;
    }
  }
  gPreferencesListbox.appendChild(createPreferenceListItem(name, value, type, locked));
}

function createPreferenceListItem(name, value, type, locked) {
  var listitem = document.createElement("listitem");
  listitem.setAttribute("equalsize", "always");
  listitem.setAttribute("tooltiptext", name + ": " + value);
  var nameCell = document.createElement("listcell");
  nameCell.setAttribute("flex", "1");
  nameCell.setAttribute("crop", "end");
  nameCell.setAttribute("label", name);
  var typeCell = document.createElement("listcell");
  typeCell.setAttribute("flex", "1");
  if (type == "number") {
    type = "integer";
  }
  typeCell.setAttribute("label", type);
  var statusCell = document.createElement("listcell");
  statusCell.setAttribute("flex", "1");
  if (locked) {
    statusCell.setAttribute("label", "locked");
    listitem.setAttribute("locked", "true");
  } else {
    statusCell.setAttribute("label", "default");
  }
  var valueCell = document.createElement("listcell");
  valueCell.setAttribute("flex", "1");
  valueCell.setAttribute("label", value);
  listitem.appendChild(nameCell);
  listitem.appendChild(statusCell);
  listitem.appendChild(typeCell);
  listitem.appendChild(valueCell);
  listitem.setAttribute("context", "preferences-contextmenu");
  return listitem;
}

function updatePreferenceListItem(listitem, name, value, type, locked) {
  listitem.childNodes[0].setAttribute("label", name);
  listitem.childNodes[2].setAttribute("label", type);
  listitem.childNodes[3].setAttribute("label", value);
  listitem.setAttribute("tooltiptext", name + ": " + value);
}

function onDeletePreference() {
  if (gPreferencesListbox.selectedIndex == -1) {
    return;
  }
  gPreferencesListbox.removeChild(gPreferencesListbox.selectedItem);
}

function convertListItemToPreference(listitem) {
  var preference = {};
  preference.name = listitem.childNodes[0].getAttribute("label");
  preference.type = listitem.childNodes[2].getAttribute("label");
  var value = listitem.childNodes[3].getAttribute("label");
  switch (preference.type) {
    case "integer":
      value = parseInt(value);
      break;
    case "boolean":
      value = JSON.parse(value);
      break;
  }
  preference.value = value;
//    var locked = listitem.childNodes[3].getAttribute("label");
  return preference;
}

function onLockUnlockPreference() {
  var listitem = gPreferencesListbox.selectedItem;
  if (listitem.getAttribute("locked")) {
    listitem.removeAttribute("locked");
    listitem.childNodes[1].setAttribute("label", "default");
  } else {
    listitem.setAttribute("locked", "true");
    listitem.childNodes[1].setAttribute("label", "locked");
  }
}

function onPreferencesPopup(event) {
  var listitem = gPreferencesListbox.selectedItem;
  if (listitem.hasAttribute("locked")) {
    document.getElementById("preferences-lock").hidden = true;
    document.getElementById("preferences-unlock").hidden = false;
  } else {
    document.getElementById("preferences-lock").hidden = false;
    document.getElementById("preferences-unlock").hidden = true;
  }
}

function onEditPreference() {
  if (gPreferencesListbox.selectedIndex == -1) {
    return;
  }
  var retVals = convertListItemToPreference(gPreferencesListbox.selectedItem);
  window.openDialog("chrome://cck2wizard/content/preferences-dialog.xul", "cck2wizard-preference", "modal,centerscreen", retVals);
  if ("cancel" in retVals) {
    return;
  }
  updatePreferenceListItem(gPreferencesListbox.selectedItem, retVals.name, retVals.value, retVals.type, false);
}

function onKeyPressPreference(event) {
  if (event.keyCode == event.DOM_VK_ENTER ||
      event.keyCode == event.DOM_VK_RETURN) {
    onEditPreference();
  } else if (event.keyCode == event.DOM_VK_DELETE ||
             event.keyCode == event.DOM_VK_BACK_SPACE) {
    onDeletePreference();
  }
}<|endoftext|>


<commit_before>define(function() {

return {

  // The following palette description
  // is copied from compiled CoffeeScript.
  COFFEESCRIPT_PALETTE: [
    {
      name: 'Move',
      color: 'red',
      blocks: [
        {
          block: 'fd 100',
          title: 'Move forward'
        }, {
          block: 'rt 90',
          title: 'Turn right'
        }, {
          block: 'lt 90',
          title: 'Turn left'
        }, {
          block: 'bk 100',
          title: 'Move backward'
        }, {
          block: 'rt 180, 100',
          title: 'Make a wide right arc'
        }, {
          block: 'lt 180, 100',
          title: 'Make a wide left arc'
        }, {
          block: 'speed 10',
          title: 'Set the speed of the turtle'
        }, {
          block: 'speed Infinity',
          title: 'Use infinite speed'
        }, {
          block: 'home()',
          title: 'Jump to the origin, turned up'
        }, {
          block: 'turnto 270',
          title: 'Turn to an absolute direction'
        }, {
          block: 'turnto lastclick',
          title: 'Turn toward a located object'
        }, {
          block: 'moveto 100, 50',
          title: 'Move to coordinates'
        }, {
          block: 'movexy 30, 20',
          title: 'Move by changing x and y'
        }, {
          block: 'move 10, 5',
          title: "Move sideways or diagonal from turtle's angle"
        }, {
          block: 'jumpto 100, 50',
          title: 'Jump to coordinates without drawing'
        }, {
          block: 'jumpxy 30, 20',
          title: 'Jump changing x and y without drawing'
        }, {
          block: 'jump 10, 5',
          title: "Move sideways or diagonal without drawing"
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for [1..3]\n  ``',
          title: 'Do something multiple times'
        }, {
          block: 'if `` is ``\n  ``',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if `` is ``\n  ``\nelse\n  ``',
          title: 'Do something if a condition is true, otherwise something else'
        }, {
          block: "tick 1, ->\n  write 'ticked'",
          title: 'Repeat something forever at qually-spaced times'
        }, {
          block: "button \'Click\', ->\n  write 'clicked'",
          title: 'Make a button and do something when clicked'
        }, {
          block: "keydown \'X\', ->\n  write 'x pressed'",
          title: 'Do something when a keyboard key is pressed'
        }, {
          block: "click (e) ->\n  moveto e",
          title: 'Move to a location when document is clicked'
        }
      ]
    }, {
      name: 'Looks',
      color: 'blue',
      blocks: [
         {
          block: 'pen purple, 10',
          title: 'Set pen color and size'
        }, {
          block: 'dot green, 50',
          title: 'Make a dot'
        }, {
          block: 'box yellow, 50',
          title: 'Make a square'
        }, {
          block: 'fill blue',
          title: 'Fill traced shape'
        }, {
          block: 'wear \'/img/apple\'',
          title: 'Use an image for the turtle'
        }, {
          block: 'scale 3',
          title: 'Scale turtle drawing'
        }, {
          block: 'ht()',
          title: 'Hide the main turtle'
        }, {
          block: 'st()',
          title: 'Show the main turtle'
        }, {
          block: 'cs()',
          title: 'Clear screen'
        }, {
          block: 'cg()',
          title: 'Clear graphics'
        }, {
          block: 'pu()',
          title: 'Lift the pen up'
        }, {
          block: 'pd()',
          title: 'Put the pen down'
        }, {
          block: 'drawon s',
          title: 'Draw on sprite s'
        }, {
          block: 'drawon document',
          title: 'Draw on the document'
        }
      ]
    }, {
      name: 'Operators',
      color: 'green',
      blocks: [
        {
          block: 'x = ``',
          title: 'Set a variable'
        }, {
          block: '`` is ``',
          title: 'Compare two values'
        }, {
          block: '`` < ``',
          title: 'Compare two values'
        }, {
          block: '`` > ``',
          title: 'Compare two values'
        }, {
          block: '`` + ``',
          title: 'Add two numbers'
        }, {
          block: '`` - ``',
          title: 'Subtract two numbers'
        }, {
          block: '`` * ``',
          title: 'Multiply two numbers'
        }, {
          block: '`` / ``',
          title: 'Divide two numbers'
        }, {
          block: 'random [1..100]',
          title: 'Get a random number in a range'
        }, {
          block: 'round ``',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs ``',
          title: 'Absolute value'
        }, {
          block: 'max ``, ``',
          title: 'Get the larger of two numbers'
        }, {
          block: 'min ``, ``',
          title: 'Get the smaller on two numbers'
        }, {
          block: 'x.match /pattern/',
          title: 'Test if a text pattern is found in x'
        }, {
          block: 'f = (x) ->\n  ``',
          title: 'Define a new function'
        }, {
          block: 'f(x)',
          title: 'Use a custom function'
        }
      ]
    }, {
      name: 'Text',
      color: 'yellow',
      blocks: [
        {
          block: 'write \'Hello.\'',
          title: 'Write text in the document'
        }, {
          block: 'type \'zz*(-.-)*zz\'',
          title: 'Typewrite text in the document'
        }, {
          block: 'label \'spot\'',
          title: 'Write text at the turtle'
        }, {
          block: 'read \'?\', (x) ->\n  write x',
          title: 'Read input from the user'
        }, {
          block: 'readnum \'?\', (x) ->\n  write x',
          title: 'Read a number from the user'
        }, {
          block: 'log [1..10]',
          title: 'Log an object to debug'
        }
      ]
    }, {
      name: 'Sprites',
      color: 'violet',
      blocks: [
        {
          block: 't = new Turtle red',
          title: 'Make a new turtle'
        }, {
          block: 's = new Sprite',
          title: 'Make a blank sprite'
        }, {
          block: 'p = new Piano',
          title: 'Make a visible insturment'
        }, {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }, {
          block: 'q = new Pencil',
          title: 'Make an invisible and fast drawing sprite'
        }
      ]
    }, {
      name: 'Sound',
      color: 'violet',
      blocks: [
        {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }
      ]
    }, {
      name: 'Snippets',
      color: 'yellow',
      blocks: [
        {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }
      ]
    }
  ],

  JAVASCRIPT_PALETTE: [
    {
      name: 'Draw',
      color: 'blue',
      blocks: [
        {
          block: 'pen(red);',
          title: 'Set the pen color'
        }, {
          block: 'fd(100);',
          title: 'Move forward'
        }, {
          block: 'rt(90);',
          title: 'Turn right'
        }, {
          block: 'lt(90);',
          title: 'Turn left'
        }, {
          block: 'bk(100);',
          title: 'Move backward'
        }, {
          block: 'speed(10);',
          title: 'Set the speed of the turtle'
        }, {
          block: 'dot(blue, 50);',
          title: 'Make a dot'
        }, {
          block: 'box(green, 50);',
          title: 'Make a square'
        }, {
          block: 'write(\'hello\');',
          title: 'Write text on the screen'
        }, {
          block: 'label(\'hello\');',
          title: 'Write text at the turtle'
        }, {
          block: 'ht();',
          title: 'Hide the turtle'
        }, {
          block: 'st();',
          title: 'Show the turtle'
        }, {
          block: 'pu();',
          title: 'Pick the pen up'
        }, {
          block: 'pd();',
          title: 'Put the pen down'
        }, {
          block: 'pen(purple, 10);',
          title: 'Set the pen color and thickness'
        }, {
          block: 'rt(180, 100);',
          title: 'Make a wide right turn'
        }, {
          block: 'lt(180, 100);',
          title: 'Make a wide left turn'
        }, {
          block: 'slide(100, 20);',
          title: 'Slide sideways or diagonally'
        }, {
          block: 'jump(100, 20);',
          title: 'Jump without drawing'
        }, {
          block: 'play(\'GEC\');',
          title: 'Play music notes'
        }, {
          block: 'wear(\'/img/cat-icon\');',
          title: 'Change the turtle image'
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for (var i = 0; i < 4; i++) {\n  __;\n}',
          title: 'Do something multiple times'
        }, {
          block: 'if (__) {\n  __;\n}',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if (__) {\n  __;\n} else {\n  __;\n}',
          title: 'Do something if a condition is true, otherwise do something else'
        }, {
          block: 'while (__) {\n  __;\n}',
          title: 'Repeat something while a condition is true'
        }
      ]
    }, {
      name: 'Math',
      color: 'green',
      blocks: [
        {
          block: 'var x = __;',
          title: 'Create a variable for the first time'
        }, {
          block: 'x = __;',
          title: 'Reassign a variable'
        }, {
          block: '__ + __',
          title: 'Add two numbers'
        }, {
          block: '__ - __',
          title: 'Subtract two numbers'
        }, {
          block: '__ * __',
          title: 'Multiply two numbers'
        }, {
          block: '__ / __',
          title: 'Divide two numbers'
        }, {
          block: '__ === __',
          title: 'Compare two numbers'
        }, {
          block: '__ > __',
          title: 'Compare two numbers'
        }, {
          block: '__ < __',
          title: 'Compare two numbers'
        }, {
          block: 'random(1, 100)',
          title: 'Get a random number in a range'
        }, {
          block: 'round(__)',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs(__)',
          title: 'Absolute value'
        }, {
          block: 'max(__, __)',
          title: 'Absolute value'
        }, {
          block: 'min(__, __)',
          title: 'Absolute value'
        }
      ]
    }, {
      name: 'Functions',
      color: 'violet',
      blocks: [
        {
          block: 'function myFunction() {\n  __;\n}',
          title: 'Create a function without an argument'
        }, {
          block: 'function myFunction(n) {\n  __;\n}',
          title: 'Create a function with an argument'
        }, {
          block: 'myFunction()',
          title: 'Use a function without an argument'
        }, {
          block: 'myFunction(n)',
          title: 'Use a function with argument'
        }
      ]
    }
  ]
};

});
<commit_msg>Add some blocks to snippet (test)<commit_after>define(function() {

return {

  // The following palette description
  // is copied from compiled CoffeeScript.
  COFFEESCRIPT_PALETTE: [
    {
      name: 'Move',
      color: 'red',
      blocks: [
        {
          block: 'fd 100',
          title: 'Move forward'
        }, {
          block: 'rt 90',
          title: 'Turn right'
        }, {
          block: 'lt 90',
          title: 'Turn left'
        }, {
          block: 'bk 100',
          title: 'Move backward'
        }, {
          block: 'rt 180, 100',
          title: 'Make a wide right arc'
        }, {
          block: 'lt 180, 100',
          title: 'Make a wide left arc'
        }, {
          block: 'speed 10',
          title: 'Set the speed of the turtle'
        }, {
          block: 'speed Infinity',
          title: 'Use infinite speed'
        }, {
          block: 'home()',
          title: 'Jump to the origin, turned up'
        }, {
          block: 'turnto 270',
          title: 'Turn to an absolute direction'
        }, {
          block: 'turnto lastclick',
          title: 'Turn toward a located object'
        }, {
          block: 'moveto 100, 50',
          title: 'Move to coordinates'
        }, {
          block: 'movexy 30, 20',
          title: 'Move by changing x and y'
        }, {
          block: 'move 10, 5',
          title: "Move sideways or diagonal from turtle's angle"
        }, {
          block: 'jumpto 100, 50',
          title: 'Jump to coordinates without drawing'
        }, {
          block: 'jumpxy 30, 20',
          title: 'Jump changing x and y without drawing'
        }, {
          block: 'jump 10, 5',
          title: "Move sideways or diagonal without drawing"
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for [1..3]\n  ``',
          title: 'Do something multiple times'
        }, {
          block: 'if `` is ``\n  ``',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if `` is ``\n  ``\nelse\n  ``',
          title: 'Do something if a condition is true, otherwise something else'
        }, {
          block: "tick 1, ->\n  write 'ticked'",
          title: 'Repeat something forever at qually-spaced times'
        }, {
          block: "button \'Click\', ->\n  write 'clicked'",
          title: 'Make a button and do something when clicked'
        }, {
          block: "keydown \'X\', ->\n  write 'x pressed'",
          title: 'Do something when a keyboard key is pressed'
        }, {
          block: "click (e) ->\n  moveto e",
          title: 'Move to a location when document is clicked'
        }
      ]
    }, {
      name: 'Looks',
      color: 'blue',
      blocks: [
         {
          block: 'pen purple, 10',
          title: 'Set pen color and size'
        }, {
          block: 'dot green, 50',
          title: 'Make a dot'
        }, {
          block: 'box yellow, 50',
          title: 'Make a square'
        }, {
          block: 'fill blue',
          title: 'Fill traced shape'
        }, {
          block: 'wear \'/img/apple\'',
          title: 'Use an image for the turtle'
        }, {
          block: 'scale 3',
          title: 'Scale turtle drawing'
        }, {
          block: 'ht()',
          title: 'Hide the main turtle'
        }, {
          block: 'st()',
          title: 'Show the main turtle'
        }, {
          block: 'cs()',
          title: 'Clear screen'
        }, {
          block: 'cg()',
          title: 'Clear graphics'
        }, {
          block: 'pu()',
          title: 'Lift the pen up'
        }, {
          block: 'pd()',
          title: 'Put the pen down'
        }, {
          block: 'drawon s',
          title: 'Draw on sprite s'
        }, {
          block: 'drawon document',
          title: 'Draw on the document'
        }
      ]
    }, {
      name: 'Operators',
      color: 'green',
      blocks: [
        {
          block: 'x = ``',
          title: 'Set a variable'
        }, {
          block: '`` is ``',
          title: 'Compare two values'
        }, {
          block: '`` < ``',
          title: 'Compare two values'
        }, {
          block: '`` > ``',
          title: 'Compare two values'
        }, {
          block: '`` + ``',
          title: 'Add two numbers'
        }, {
          block: '`` - ``',
          title: 'Subtract two numbers'
        }, {
          block: '`` * ``',
          title: 'Multiply two numbers'
        }, {
          block: '`` / ``',
          title: 'Divide two numbers'
        }, {
          block: 'random [1..100]',
          title: 'Get a random number in a range'
        }, {
          block: 'round ``',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs ``',
          title: 'Absolute value'
        }, {
          block: 'max ``, ``',
          title: 'Get the larger of two numbers'
        }, {
          block: 'min ``, ``',
          title: 'Get the smaller on two numbers'
        }, {
          block: 'x.match /pattern/',
          title: 'Test if a text pattern is found in x'
        }, {
          block: 'f = (x) ->\n  ``',
          title: 'Define a new function'
        }, {
          block: 'f(x)',
          title: 'Use a custom function'
        }
      ]
    }, {
      name: 'Text',
      color: 'yellow',
      blocks: [
        {
          block: 'write \'Hello.\'',
          title: 'Write text in the document'
        }, {
          block: 'type \'zz*(-.-)*zz\'',
          title: 'Typewrite text in the document'
        }, {
          block: 'label \'spot\'',
          title: 'Write text at the turtle'
        }, {
          block: 'read \'?\', (x) ->\n  write x',
          title: 'Read input from the user'
        }, {
          block: 'readnum \'?\', (x) ->\n  write x',
          title: 'Read a number from the user'
        }, {
          block: 'log [1..10]',
          title: 'Log an object to debug'
        }
      ]
    }, {
      name: 'Sprites',
      color: 'violet',
      blocks: [
        {
          block: 't = new Turtle red',
          title: 'Make a new turtle'
        }, {
          block: 's = new Sprite',
          title: 'Make a blank sprite'
        }, {
          block: 'p = new Piano',
          title: 'Make a visible insturment'
        }, {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }, {
          block: 'q = new Pencil',
          title: 'Make an invisible and fast drawing sprite'
        }
      ]
    }, {
      name: 'Sound',
      color: 'violet',
      blocks: [
        {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }
      ]
    }, {
      name: 'Snippets',
      color: 'yellow',
      blocks: [
        {
          block: "tick 10, ->\n  if pressed 'W'\n    fd 2",
          title: 'Poll a key and move while it is depressed'
        }, {
          block: "click (e) ->\n  moveto e",
          title: 'Move to a location when document is clicked'
        }
      ]
    }
  ],

  JAVASCRIPT_PALETTE: [
    {
      name: 'Draw',
      color: 'blue',
      blocks: [
        {
          block: 'pen(red);',
          title: 'Set the pen color'
        }, {
          block: 'fd(100);',
          title: 'Move forward'
        }, {
          block: 'rt(90);',
          title: 'Turn right'
        }, {
          block: 'lt(90);',
          title: 'Turn left'
        }, {
          block: 'bk(100);',
          title: 'Move backward'
        }, {
          block: 'speed(10);',
          title: 'Set the speed of the turtle'
        }, {
          block: 'dot(blue, 50);',
          title: 'Make a dot'
        }, {
          block: 'box(green, 50);',
          title: 'Make a square'
        }, {
          block: 'write(\'hello\');',
          title: 'Write text on the screen'
        }, {
          block: 'label(\'hello\');',
          title: 'Write text at the turtle'
        }, {
          block: 'ht();',
          title: 'Hide the turtle'
        }, {
          block: 'st();',
          title: 'Show the turtle'
        }, {
          block: 'pu();',
          title: 'Pick the pen up'
        }, {
          block: 'pd();',
          title: 'Put the pen down'
        }, {
          block: 'pen(purple, 10);',
          title: 'Set the pen color and thickness'
        }, {
          block: 'rt(180, 100);',
          title: 'Make a wide right turn'
        }, {
          block: 'lt(180, 100);',
          title: 'Make a wide left turn'
        }, {
          block: 'slide(100, 20);',
          title: 'Slide sideways or diagonally'
        }, {
          block: 'jump(100, 20);',
          title: 'Jump without drawing'
        }, {
          block: 'play(\'GEC\');',
          title: 'Play music notes'
        }, {
          block: 'wear(\'/img/cat-icon\');',
          title: 'Change the turtle image'
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for (var i = 0; i < 4; i++) {\n  __;\n}',
          title: 'Do something multiple times'
        }, {
          block: 'if (__) {\n  __;\n}',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if (__) {\n  __;\n} else {\n  __;\n}',
          title: 'Do something if a condition is true, otherwise do something else'
        }, {
          block: 'while (__) {\n  __;\n}',
          title: 'Repeat something while a condition is true'
        }
      ]
    }, {
      name: 'Math',
      color: 'green',
      blocks: [
        {
          block: 'var x = __;',
          title: 'Create a variable for the first time'
        }, {
          block: 'x = __;',
          title: 'Reassign a variable'
        }, {
          block: '__ + __',
          title: 'Add two numbers'
        }, {
          block: '__ - __',
          title: 'Subtract two numbers'
        }, {
          block: '__ * __',
          title: 'Multiply two numbers'
        }, {
          block: '__ / __',
          title: 'Divide two numbers'
        }, {
          block: '__ === __',
          title: 'Compare two numbers'
        }, {
          block: '__ > __',
          title: 'Compare two numbers'
        }, {
          block: '__ < __',
          title: 'Compare two numbers'
        }, {
          block: 'random(1, 100)',
          title: 'Get a random number in a range'
        }, {
          block: 'round(__)',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs(__)',
          title: 'Absolute value'
        }, {
          block: 'max(__, __)',
          title: 'Absolute value'
        }, {
          block: 'min(__, __)',
          title: 'Absolute value'
        }
      ]
    }, {
      name: 'Functions',
      color: 'violet',
      blocks: [
        {
          block: 'function myFunction() {\n  __;\n}',
          title: 'Create a function without an argument'
        }, {
          block: 'function myFunction(n) {\n  __;\n}',
          title: 'Create a function with an argument'
        }, {
          block: 'myFunction()',
          title: 'Use a function without an argument'
        }, {
          block: 'myFunction(n)',
          title: 'Use a function with argument'
        }
      ]
    }
  ]
};

});
<|endoftext|>