text:
/*! normalize.css v2.1.3 | MIT License | git.io/normalize */
/* ==========================================================================
   HTML5 display definitions
   ========================================================================== */
/**
 * Correct `block` display not defined in IE 8/9.
 */
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
  display: block; }

/**
 * Correct `inline-block` display not defined in IE 8/9.
 */
audio,
canvas,
video {
  display: inline-block; }

/**
 * Prevent modern browsers from displaying `audio` without controls.
 * Remove excess height in iOS 5 devices.
 */
audio:not([controls]) {
  display: none;
  height: 0; }

/**
 * Address `[hidden]` styling not present in IE 8/9.
 * Hide the `template` element in IE, Safari, and Firefox < 22.
 */
[hidden],
template {
  display: none; }

/* ==========================================================================
   Base
   ========================================================================== */
/**
 * 1. Set default font family to sans-serif.
 * 2. Prevent iOS text size adjust after orientation change, without disabling
 *    user zoom.
 */
html {
  font-family: sans-serif;
  /* 1 */
  -ms-text-size-adjust: 100%;
  /* 2 */
  -webkit-text-size-adjust: 100%;
  /* 2 */ }

/**
 * Remove default margin.
 */
body {
  margin: 0; }

/* ==========================================================================
   Links
   ========================================================================== */
/**
 * Remove the gray background color from active links in IE 10.
 */
a {
  background: transparent; }

/**
 * Address `outline` inconsistency between Chrome and other browsers.
 */
a:focus {
  outline: thin dotted; }

/**
 * Improve readability when focused and also mouse hovered in all browsers.
 */
a:active,
a:hover {
  outline: 0; }

/* ==========================================================================
   Typography
   ========================================================================== */
/**
 * Address variable `h1` font-size and margin within `section` and `article`
 * contexts in Firefox 4+, Safari 5, and Chrome.
 */
h1 {
  font-size: 2em;
  margin: 0.67em 0; }

/**
 * Address styling not present in IE 8/9, Safari 5, and Chrome.
 */
abbr[title] {
  border-bottom: 1px dotted; }

/**
 * Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome.
 */
b,
strong {
  font-weight: bold; }

/**
 * Address styling not present in Safari 5 and Chrome.
 */
dfn {
  font-style: italic; }

/**
 * Address differences between Firefox and other browsers.
 */
hr {
  -moz-box-sizing: content-box;
  box-sizing: content-box;
  height: 0; }

/**
 * Address styling not present in IE 8/9.
 */
mark {
  background: #ff0;
  color: #000; }

/**
 * Correct font family set oddly in Safari 5 and Chrome.
 */
code,
kbd,
pre,
samp {
  font-family: monospace, serif;
  font-size: 1em; }

/**
 * Improve readability of pre-formatted text in all browsers.
 */
pre {
  white-space: pre-wrap; }

/**
 * Set consistent quote types.
 */
q {
  quotes: "\201C" "\201D" "\2018" "\2019"; }

/**
 * Address inconsistent and variable font size in all browsers.
 */
small {
  font-size: 80%; }

/**
 * Prevent `sub` and `sup` affecting `line-height` in all browsers.
 */
sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline; }

sup {
  top: -0.5em; }

sub {
  bottom: -0.25em; }

/* ==========================================================================
   Embedded content
   ========================================================================== */
/**
 * Remove border when inside `a` element in IE 8/9.
 */
img {
  border: 0; }

/**
 * Correct overflow displayed oddly in IE 9.
 */
svg:not(:root) {
  overflow: hidden; }

/* ==========================================================================
   Figures
   ========================================================================== */
/**
 * Address margin not present in IE 8/9 and Safari 5.
 */
figure {
  margin: 0; }

/* ==========================================================================
   Forms
   ========================================================================== */
/**
 * Define consistent border, margin, and padding.
 */
fieldset {
  border: 1px solid #c0c0c0;
  margin: 0 2px;
  padding: 0.35em 0.625em 0.75em; }

/**
 * 1. Correct `color` not being inherited in IE 8/9.
 * 2. Remove padding so people aren't caught out if they zero out fieldsets.
 */
legend {
  border: 0;
  /* 1 */
  padding: 0;
  /* 2 */ }

/**
 * 1. Correct font family not being inherited in all browsers.
 * 2. Correct font size not being inherited in all browsers.
 * 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.
 */
button,
input,
select,
textarea {
  font-family: inherit;
  /* 1 */
  font-size: 100%;
  /* 2 */
  margin: 0;
  /* 3 */ }

/**
 * Address Firefox 4+ setting `line-height` on `input` using `!important` in
 * the UA stylesheet.
 */
button,
input {
  line-height: normal; }

/**
 * Address inconsistent `text-transform` inheritance for `button` and `select`.
 * All other form control elements do not inherit `text-transform` values.
 * Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+.
 * Correct `select` style inheritance in Firefox 4+ and Opera.
 */
button,
select {
  text-transform: none; }

/**
 * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
 *    and `video` controls.
 * 2. Correct inability to style clickable `input` types in iOS.
 * 3. Improve usability and consistency of cursor style between image-type
 *    `input` and others.
 */
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
  -webkit-appearance: button;
  /* 2 */
  cursor: pointer;
  /* 3 */ }

/**
 * Re-set default cursor for disabled elements.
 */
button[disabled],
html input[disabled] {
  cursor: default; }

/**
 * 1. Address box sizing set to `content-box` in IE 8/9/10.
 * 2. Remove excess padding in IE 8/9/10.
 */
input[type="checkbox"],
input[type="radio"] {
  box-sizing: border-box;
  /* 1 */
  padding: 0;
  /* 2 */ }

/**
 * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
 * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
 *    (include `-moz` to future-proof).
 */
input[type="search"] {
  -webkit-appearance: textfield;
  /* 1 */
  -moz-box-sizing: content-box;
  -webkit-box-sizing: content-box;
  /* 2 */
  box-sizing: content-box; }

/**
 * Remove inner padding and search cancel button in Safari 5 and Chrome
 * on OS X.
 */
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none; }

/**
 * Remove inner padding and border in Firefox 4+.
 */
button::-moz-focus-inner,
input::-moz-focus-inner {
  border: 0;
  padding: 0; }

/**
 * 1. Remove default vertical scrollbar in IE 8/9.
 * 2. Improve readability and alignment in all browsers.
 */
textarea {
  overflow: auto;
  /* 1 */
  vertical-align: top;
  /* 2 */ }

/* ==========================================================================
   Tables
   ========================================================================== */
/**
 * Remove most spacing between table cells.
 */
table {
  border-collapse: collapse;
  border-spacing: 0; }

html, body {
  -webkit-transform: translateZ(0);
  -moz-transform: translateZ(0);
  transform: translateZ(0);
  background: #fff;
  height: 100%;
  box-sizing: border-box; }

body, input, select, textarea, .pac-container {
  font-family: "Trebuchet MS", Trebuchet, Arial, Helvetica, sans-serif;
  font-size: 14px; }

body {
  min-height: 400px;
  min-width: 500px;
  position: relative;
  background: #000; }

#container, #crop, #mapa {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden; }

.screenreader {
  position: absolute;
  left: -9999px; }

.input {
  position: relative; }
  .input .icon {
    position: absolute;
    top: 50%;
    margin-top: -8px;
    right: 20px; }

.icon {
  display: inline-block;
  overflow: hidden;
  font-size: 1px;
  width: 16px;
  height: 16px;
  background: url(images/sprite-ui@2x.png) no-repeat -1000px -1000px;
  background-size: 116px 78px; }
  .icon.lugar {
    width: 13px;
    background-position: -16px -62px; }
  .icon.tiempo {
    background-position: -0px -62px; }

input[type=text], input[type=number], input[type=email], textarea {
  display: block;
  background: #221e35;
  border: 1px solid #161324;
  border-radius: 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  width: 100%;
  margin: 0;
  font-size: 14px;
  padding: 15px 45px 15px 15px;
  color: #ffffff; }
  input[type=text]::-webkit-input-placeholder, input[type=number]::-webkit-input-placeholder, input[type=email]::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
    color: #e0eaf4;
    font-style: "italic";
    font-weight: "normal"; }
  input[type=text]:-moz-placeholder, input[type=number]:-moz-placeholder, input[type=email]:-moz-placeholder, textarea:-moz-placeholder {
    color: #e0eaf4;
    font-style: "italic";
    font-weight: "normal"; }
  input[type=text]::-moz-placeholder, input[type=number]::-moz-placeholder, input[type=email]::-moz-placeholder, textarea::-moz-placeholder {
    color: #e0eaf4;
    font-style: "italic";
    font-weight: "normal"; }
  input[type=text]:-ms-input-placeholder, input[type=number]:-ms-input-placeholder, input[type=email]:-ms-input-placeholder, textarea:-ms-input-placeholder {
    color: #e0eaf4;
    font-style: "italic";
    font-weight: "normal"; }
  input[type=text]:focus, input[type=number]:focus, input[type=email]:focus, textarea:focus {
    outline: none; }

input[type=number]::-webkit-outer-spin-button, input[type=number]::-webkit-inner-spin-button {
  /* display: none; <- Crashes Chrome on hover */
  -webkit-appearance: none;
  margin: 0;
  /* <-- Apparently some margin are still there even though it's hidden */ }

.btn {
  display: block;
  padding: 17px 10px;
  width: 100%;
  box-sizing: border-box;
  border: none;
  border-radius: 2px;
  text-align: center;
  cursor: pointer;
  font-size: 13px;
  font-weight: normal;
  color: #ffffff;
  text-decoration: none;
  outline: none;
  transition: all 0.2s ease-out; }
  .btn.disabled {
    box-shadow: inset 0px 1px 0px #595472;
    cursor: default; }
  .btn:hover {
    background: #221e35; }

#reportar {
  width: 250px;
  position: absolute;
  background: #2a263f;
  top: 0;
  left: 0;
  min-height: 100%;
  z-index: 2; }
  #reportar .header {
    height: 44px;
    background: rgba(255, 255, 255, 0.05);
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    position: relative; }
    #reportar .header h2 {
      margin: 0;
      color: #fff;
      font-size: 16px;
      line-height: 44px;
      padding: 0 15px; }
    #reportar .header .cerrar {
      position: absolute;
      top: 0px;
      right: 0px;
      cursor: pointer;
      width: 12px;
      height: 13px;
      border: 15px solid #403c53;
      text-align: center;
      text-indent: -9999px;
      overflow: hidden;
      background: url(images/sprite-ui.png) no-repeat -26px -31px #403c53; }
  #reportar input[type=text] {
    background: #221e35;
    border: none;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    width: 100%;
    height: 38px;
    line-height: 21px;
    padding: 0 35px 0 15px;
    font-size: 13px;
    margin: 0 0 5px;
    position: relative;
    z-index: 1;
    outline: none;
    color: #fff; }
  #reportar label {
    display: block;
    position: relative; }
    #reportar label.active, #reportar label:hover {
      color: #fff; }
    #reportar label:after {
      content: "";
      width: 13px;
      height: 13px;
      display: block;
      position: absolute;
      right: 10px;
      top: 13px;
      z-index: 10; }
    #reportar label[for=horas]:after {
      background: url(images/sprite-ui.png) no-repeat 0px -31px; }
    #reportar label[for=direccion]:after {
      background: url(images/sprite-ui.png) no-repeat -14px -31px;
      width: 11px; }
  #reportar .error {
    display: none;
    color: white;
    background: #fff2ab;
    padding: 10px 35px;
    font-size: 12px;
    text-align: center;
    color: #545454; }
  #reportar .btn {
    display: block;
    padding: 17px 10px;
    margin: 20px auto 20px auto;
    width: 220px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    border: none;
    border-radius: 2px;
    text-align: center;
    cursor: pointer;
    font-size: 13px;
    font-weight: normal;
    color: #ffffff;
    text-decoration: none;
    outline: none;
    transition: all 0.2s ease-out;
    background: #403d55;
    color: #595472; }
    #reportar .btn.disabled {
      cursor: default; }
    #reportar .btn.hay-luz {
      background: #00ff95;
      color: #ffffff; }
    #reportar .btn.corte-cuadra {
      background: #ff7d1f;
      color: #fff; }
    #reportar .btn.corte-amplio {
      background: #f8312e;
      color: #fff; }

#situacion-luz {
  margin: 0;
  padding: 0;
  overflow: hidden; }
  #situacion-luz label {
    cursor: pointer; }
  #situacion-luz li {
    width: 33%;
    float: left;
    padding: 15px 0;
    list-style: none;
    font-size: 10px;
    color: rgba(255, 255, 255, 0.3);
    text-align: center; }
    #situacion-luz li input {
      opacity: 0;
      position: absolute;
      top: 0;
      left: 0; }

.pac-container {
  background: #2a263f;
  overflow: auto;
  border: none;
  z-index: 10000;
  /* Scrollbars */ }
  .pac-container::-webkit-scrollbar {
    background: none;
    width: 6px; }
  .pac-container::-webkit-scrollbar-thumb {
    background: #221e35;
    border-radius: 6px; }
  .pac-container:after {
    display: none; }
  .pac-container .pac-item {
    display: block;
    line-height: 16px;
    padding: 10px 15px;
    color: rgba(255, 255, 255, 0.7);
    border: 1px solid #221e35;
    border-left: none;
    border-right: none;
    cursor: pointer;
    font-weight: normal; }
    .pac-container .pac-item .pac-icon {
      display: none; }
    .pac-container .pac-item .pac-item-query {
      font-size: 11px;
      font-weight: bold;
      color: #ffffff;
      display: block; }
    .pac-container .pac-item:hover, .pac-container .pac-item.pac-item-selected {
      background: rgba(0, 0, 0, 0.1); }

.carita {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin: 0 auto 10px;
  box-shadow: 0px 0px 0px 4px rgba(0, 0, 0, 0.15);
  position: relative;
  cursor: pointer; }
  .carita:before {
    content: "";
    position: absolute;
    top: 15px;
    left: 11px;
    display: block;
    width: 29px;
    height: 22px; }

.hay-luz .carita {
  background: #00ff95; }
  .hay-luz .carita:before {
    background: url(images/sprite-ui.png) no-repeat 0px 0px; }

.corte-cuadra .carita {
  background: #ff7d1f; }
  .corte-cuadra .carita:before {
    background: url(images/sprite-ui.png) no-repeat -30px 0px; }

.corte-amplio .carita {
  background: #f8312e; }
  .corte-amplio .carita:before {
    background: url(images/sprite-ui.png) no-repeat -60px 0px; }

#acciones {
  margin: 0;
  padding: 15px;
  position: absolute;
  pointer-events: none;
  min-height: 100%;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  z-index: 3; }
  #acciones:after {
    content: "";
    height: 0;
    clear: both;
    display: block; }
  #acciones li {
    float: left;
    background: rgba(255, 255, 255, 0.7);
    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
    font-weight: bold;
    font-size: 13px;
    list-style: none;
    border-radius: 2px;
    position: relative;
    pointer-events: auto; }
    #acciones li a {
      color: #545454;
      text-decoration: none;
      display: block;
      padding: 7px 10px; }
    #acciones li.logo {
      height: 43px;
      line-height: 43px;
      padding: 0;
      background: none;
      float: left;
      box-shadow: none;
      position: relative;
      top: -13px;
      margin-right: 10px; }
      #acciones li.logo a {
        background: url(images/logo-acanohayluz.png) no-repeat left;
        padding-left: 55px;
        color: #221e35;
        text-shadow: 0px 1px 2px white, 0px -1px 2px white, -1px 0px 2px white, 1px 0px 2px white;
        font-weight: bold;
        text-decoration: none; }
      #acciones li.logo:hover {
        background: none; }
    #acciones li.compartir {
      float: right;
      padding-left: 20px; }
      #acciones li.compartir:before {
        content: "";
        width: 16px;
        height: 13px;
        background: url(images/sprite-ui.png) no-repeat -39px -31px;
        display: block;
        position: absolute;
        top: 7px;
        left: 10px; }
    #acciones li.abrir-panel {
      padding-left: 20px; }
      #acciones li.abrir-panel:before {
        content: "";
        width: 16px;
        height: 13px;
        background: url(images/sprite-ui.png) no-repeat -55px -31px;
        display: block;
        position: absolute;
        top: 7px;
        left: 10px; }
    #acciones li:hover {
      background: #fff; }
    #acciones li.share-link {
      background: none;
      position: fixed;
      bottom: 15px;
      right: 10px;
      box-shadow: none; }
    #acciones li.fb {
      bottom: 45px; }

#mapa .gm-style div.map-barrio {
  font-family: "Aller", "Trebuchet MS", Trebuchet, Arial, Helvetica, sans-serif;
  text-align: center;
  font-size: 12px;
  line-height: 14px;
  z-index: 999;
  text-shadow: 0px 1px 3px white, 0px -1px 3px white, 0px 0px 3px white; }
  #mapa .gm-style div.map-barrio.luz {
    color: #0c452d; }
  #mapa .gm-style div.map-barrio.inconvenientes {
    color: #0c452d; }
  #mapa .gm-style div.map-barrio.cortes {
    color: #5e2700; }
  #mapa .gm-style div.map-barrio.apagon {
    color: #4f1110; }
  #mapa .gm-style div.map-barrio.apagonazo {
    color: #030204; }
  #mapa .gm-style div.map-barrio h6 {
    position: absolute;
    width: 100%;
    top: 45%;
    margin: 0;
    margin-top: -10px;
    box-sizing: border-box;
    padding: 0px 30px;
    font-size: 12px;
    line-height: 100%;
    font-weight: bold; }
    #mapa .gm-style div.map-barrio h6 small {
      display: block;
      font-size: 0.8em;
      font-weight: normal; }
  #mapa .gm-style div.map-barrio.belgrano h6 {
    top: 55%; }
  #mapa .gm-style div.map-barrio.coghlan h6 {
    padding: 0px 10px; }
  #mapa .gm-style div.map-barrio.boca h6 {
    padding: 0px 50% 0px 10px; }
  #mapa .gm-style div.map-barrio.flores h6 {
    padding: 0px 32% 0px 10px; }
  #mapa .gm-style div.map-barrio.constitucion h6 {
    padding: 0px 10% 0px 10px; }
  #mapa .gm-style div.map-barrio.villa-ortuzar h6 {
    padding: 0px 5px 0px 16%; }
#mapa.barrios-no-visibles .gm-style div.map-barrio {
  display: none !important; }
#mapa.zoom-14 .gm-style div.map-barrio h6 {
  font-size: 16px; }
#mapa.zoom-15 .gm-style div.map-barrio h6 {
  font-size: 18px; }
#mapa.zoom-16 .gm-style div.map-barrio h6 {
  font-size: 22px; }
#mapa.zoom-17 .gm-style div.map-barrio h6, #mapa.zoom-18 .gm-style div.map-barrio h6 {
  font-size: 24px; }
#mapa.zoom-19 .gm-style div.map-barrio h6, #mapa.zoom-20 .gm-style div.map-barrio h6, #mapa.zoom-21 .gm-style div.map-barrio h6 {
  font-size: 26px; }
#mapa .gm-style-iw {
  padding: 5px 0px;
  min-height: 40px; }
  #mapa .gm-style-iw h6 {
    font-size: 14px;
    line-height: 160%;
    margin: 0px; }
    #mapa .gm-style-iw h6.hay-luz {
      color: #188658; }
    #mapa .gm-style-iw h6.corte-cuadra {
      color: #ab4700; }
    #mapa .gm-style-iw h6.corte-amplio {
      color: #8f1e1d; }
  #mapa .gm-style-iw p {
    font-size: 12px;
    line-height: 140%;
    margin: 0px; }

/* Selector de Ubicación */
#ubicacion {
  display: none;
  position: fixed;
  top: 15px;
  left: 350px;
  width: auto;
  max-width: 230px;
  color: white;
  background: #2a263f;
  border: 1px solid #221e35;
  overflow: auto;
  z-index: 9800;
  opacity: 0.5;
  box-shadow: inset 0px 1px 0px #595472;
  border-radius: 2px;
  transition: opacity 0.2s ease-out; }
  #ubicacion:hover, #ubicacion.open {
    opacity: 1.0; }
  #ubicacion li, #ubicacion .seleccionada {
    display: block;
    cursor: pointer;
    line-height: 16px;
    padding: 10px 40px 10px 20px;
    color: #ffffff;
    border-left: none;
    border-right: none;
    cursor: pointer;
    transition: background 0.16s ease-out; }
    #ubicacion li:hover, #ubicacion .seleccionada:hover {
      background: rgba(0, 0, 0, 0.1); }
  #ubicacion ul.opciones li {
    border-top: 1px solid #221e35; }
  #ubicacion .seleccionada:after {
    position: absolute;
    display: block;
    top: 11px;
    right: 20px;
    content: ">";
    font-size: 18px;
    color: #e6e6e6;
    margin-left: 10px;
    transition: all 0.1s ease-out;
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    transform: rotate(90deg); }
  #ubicacion.open .seleccionada:after {
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -ms-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);
    transform: rotate(-90deg); }
  #ubicacion ul.opciones {
    padding: 0px;
    margin: 0px;
    height: 1px;
    max-height: 1px;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
    /* Scrollbars */ }
    #ubicacion ul.opciones::-webkit-scrollbar {
      background: none;
      width: 6px; }
    #ubicacion ul.opciones::-webkit-scrollbar-thumb {
      background: #221e35;
      border-radius: 6px; }
  #ubicacion.open ul.opciones {
    height: auto;
    max-height: 300px; }

.box-gracias {
  display: none; }
  .box-gracias .mensaje {
    padding: 30px 20px 10px 20px; }
  .box-gracias h2 {
    text-align: center;
    color: white;
    margin: 0; }
  .box-gracias p {
    color: white;
    font-size: 12px;
    text-align: center;
    padding: 0px 20px; }

.box-social {
  margin-top: 20px;
  padding: 10px 20px;
  text-align: center;
  background: #221e35;
  border: 1px solid #161324;
  border-left: none;
  border-right: none; }
  .box-social h4 {
    font-size: 12px;
    line-height: 100%;
    margin: 0;
    margin-bottom: 13px;
    font-weight: normal;
    color: white; }
  .box-social .icon {
    cursor: pointer;
    display: inline-block;
    margin: 0px 10px;
    width: 38px;
    height: 38px;
    font-size: 1px;
    overflow: hidden; }
    .box-social .icon.facebook {
      background-position: 0px -23px; }
    .box-social .icon.twitter {
      background-position: -39px -23px; }
    .box-social .icon.google {
      background-position: -78px -23px; }

.box-seguinos {
  padding: 20px;
  font-size: 11px;
  text-align: center; }
  .box-seguinos a {
    color: #a398d0;
    text-decoration: none; }
    .box-seguinos a:hover {
      text-decoration: underline; }

#reportar {
  display: none;
  overflow: hidden;
  opacity: 0.0;
  transition: opacity 0.3s ease-out; }

#acciones li.logo {
  transition: all 0.25s ease-out; }

#ubicacion {
  display: none !important; }

#container.reportando #reportar {
  opacity: 1.0; }
#container.reportando #acciones .abrir-panel {
  display: none; }
#container.reportando #acciones li.logo {
  left: 250px; }


text:
/*******************************************************************************
  SPI Driver Functions for Static Standard Buffer Driver Tasks Functions

  Company:
    Microchip Technology Inc.

  File Name:
    drv_spi_static_rm_tasks.c

  Summary:
    SPI driver tasks functions

  Description:
    The SPI device driver provides a simple interface to manage the SPI
    modules on Microchip microcontrollers. This file contains implemenation
    for the SPI driver.

  Remarks:
  This file is generated from framework/driver/spi/template/drv_spi_static_rm_tasks.c.ftl
*******************************************************************************/

//DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2015 released Microchip Technology Inc.  All rights reserved.

Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*******************************************************************************/
//DOM-IGNORE-END

#include "system_config.h"
#include "system_definitions.h"

int32_t DRV_SPI0_MasterRMSend8BitPolled( struct DRV_SPI_OBJ * pDrvObj )
{
    register DRV_SPI_JOB_OBJECT * currentJob = pDrvObj->currentJob;

    /* Check to see if we have any more bytes to transmit */
    if (currentJob->dataLeftToTx + currentJob->dummyLeftToTx == 0)
    {
        return 0;
    }
    /* Check to see if the transmit buffer is empty*/
    if (!PLIB_SPI_TransmitBufferIsEmpty(SPI_ID_4))
    {
        return 0;
    }
    /* Make sure that we don't have something in progress and overrun the RX buffer */
    if (pDrvObj->symbolsInProgress != 0)
    {
        return 0;
    }
    if (currentJob->dataLeftToTx != 0)
    {
    /* Transmit the data & update the counts */
        PLIB_SPI_BufferWrite(SPI_ID_4, currentJob->txBuffer[currentJob->dataTxed]);
        currentJob->dataTxed++;
        currentJob->dataLeftToTx--;
    }
    else
    {
        /* Transmit the dummy data & update the counts */
        PLIB_SPI_BufferWrite(SPI_ID_4, (uint8_t)pDrvObj->dummyByteValue);
        currentJob->dummyLeftToTx--;
    }
    /* We now have a symbol in progress*/
    pDrvObj->symbolsInProgress = 1;

    return 0;
}

int32_t DRV_SPI0_MasterRMReceive8BitPolled( struct DRV_SPI_OBJ * pDrvObj )
{
    register DRV_SPI_JOB_OBJECT * currentJob = pDrvObj->currentJob;

    if (currentJob == NULL)
    {
        return 0;
    }
    if (PLIB_SPI_ReceiverBufferIsFull(SPI_ID_4))
    {
        /* We have data waiting in the SPI buffer */
        if (currentJob->dataLeftToRx != 0)
        {
            /* Receive the data and updates the count */
            currentJob->rxBuffer[currentJob->dataRxed] = PLIB_SPI_BufferRead(SPI_ID_4);
            currentJob->dataRxed++;
            currentJob->dataLeftToRx --;
        }
        else
        {
            /* No Data but dummy data: Note: We cannot just clear the
               buffer because we have to keep track of how many symbols/units we
               have received, and the number may have increased since we checked
               how full the buffer is.*/
            PLIB_SPI_BufferRead(SPI_ID_4);
            //SYS_CONSOLE_MESSAGE("Rd ");
            currentJob->dummyLeftToRx--;
        }
        /* No longer have a symbol in progress */
        pDrvObj->symbolsInProgress = 0;
    }

    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
module ActiveData
  module Model
    module Conventions
      extend ActiveSupport::Concern

      included do
        attr_reader :embedder

        delegate :logger, to: ActiveData
        self.include_root_in_json = ActiveData.include_root_in_json
      end

      def persisted?
        false
      end

      def new_record?
        !persisted?
      end
      alias_method :new_object?, :new_record?

      module ClassMethods
        def i18n_scope
          ActiveData.i18n_scope
        end

        def to_ary
          nil
        end

        def primary_name
          nil
        end
      end
    end
  end
end


text:
#ifndef STROMX_RUNTIME_IMPL_DATACONTAINERIMPL_H
#define STROMX_RUNTIME_IMPL_DATACONTAINERIMPL_H

#include <boost/thread/condition_variable.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include "stromx/runtime/Config.h"

namespace stromx
{
    namespace runtime
    {
        class Data;
        class Recycler;

        namespace impl
        {
            class DataContainerImpl
            {
            public:
                explicit DataContainerImpl(Data* data);
                ~DataContainerImpl();

                void getReadAccess(const bool waitWithTimeout, const unsigned int timeout);
                void returnReadAccess();

                void getWriteAccess(const bool waitWithTimeout, const unsigned int timeout);
                void returnWriteAccess();

                void getRecycleAccess(Recycler* const recycler);
                void returnRecycleAccess();

                Data* data() const { return m_data; }

            private:
                typedef boost::lock_guard<boost::mutex> lock_t;
                typedef boost::unique_lock<boost::mutex> unique_lock_t;

                boost::mutex m_mutex;
                boost::condition_variable_any m_cond;

                void recycle();

                unsigned int m_readAccessCounter;
                bool m_writeAccess;
                Recycler* m_recycleAccess;
                Data* m_data;
            };
        }
    }
}

#endif // STROMX_RUNTIME_IMPL_DATACONTAINERIMPL_H


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<!-- Iron elements -->
<link rel="import" href="../bower_components/iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../bower_components/iron-icons/iron-icons.html">

<!-- Paper elements -->
<link rel="import" href="../bower_components/paper-material/paper-material.html">
<link rel="import" href="../bower_components/paper-styles/typography.html">

<!-- Configure your routes here -->

<!-- Add your elements here -->

<!-- app theme -->
<link rel="import" href="../styles/app-theme.html">


text:
"""Tool to show a pattern of easy access to an API.

Relies on the google-api-python-client and its embedded oauth2client.
See the README for more details on google-api-python-client.
"""

import pprint
import textwrap
import time

from apiclient import errors as apiclient_errors
from apiclient.discovery import build
from utils import admin_api_tool_errors
from utils import http_utils
from utils import log_utils

_MISSING_FIELD_STUB = '%s field not found in user data.'

def GetFieldFromUser(user, field_name, sub_field_name=None):
  """Safely retrieves a field from a user dictionary object.

  Some User fields are expressed as dictionaries of sub-fields instead of as
  simple values. This method allows retrieval of both field values and
  sub_field values.  In the following sample User record:

    fields: customerId, isAdmin, kind, name
    sub_fields: fullName, givenName, familyName

    {customerId: A03abcde4
     isAdmin: True
     kind: directory#user
     name: {u'fullName': u'George Enlighten', u'givenName': u'George',
            u'familyName': u'Enlighten'}
    }

  Args:
    user: A user object returned from an Apiary service.
    field_name: String field name for an element in a dictionary.
    sub_field_name: Sometimes retrieve a field from an embedded dictionary.

  Returns:
    If the field is present, returns the field contents.
    Otherwise returns template text to warn the user
    that data fields have changed.
  """
  if field_name not in user:
    return _MISSING_FIELD_STUB % field_name
  field_value = user.get(field_name)
  if sub_field_name:
    if not field_value or sub_field_name not in field_value:
      return _MISSING_FIELD_STUB % ('[%s][%s]' % (field_name, sub_field_name))
    return field_value.get(sub_field_name)
  return field_value

class UsersApiWrapper(object):
  """Demonstrates a few needed functions of user provisioning."""

  def __init__(self, http):
    """Create our service object with access to Admin SDK APIs.

    Args:
      http: An authorized http interface object.
    """
    self._service = build(serviceName='admin', version='directory_v1',
                          http=http)
    self._users = self._service.users()

  @staticmethod
  def _ShowAllUserFields(user):
    """Show all fields [this can be many] of user data.

    Available fields include (use ls_user -u xxx@mybiz.com -l to see real data):
      agreedToTerms, changePasswordAtNextLogin, creationTime, customerId,
      emails, id, includeInGlobalAddressList, ipWhitelisted, isAdmin,
      isDelegatedAdmin, isMailboxSetup, kind, lastLoginTime,
      name ({'familyName': 'xx', 'fullName': 'yy', 'givenName': 'zz'}),
      nonEditableAliases, orgUnitPath, primaryEmail and suspended.

    Args:
      user: user json object returned from the users API list().

    Returns:
      Dictionary of the entire user metadata.
    """
    return user

  @staticmethod
  def _ShowBasicUserFields(user):
    """Select and show only 3 basic fields from returned user json.

    Args:
      user: user json object returned from the users API list().

    Returns:
      Tuple reflecting the user: (email, user_id, full_name).
    """
    return (GetFieldFromUser(user, 'primaryEmail'),
            GetFieldFromUser(user, 'id'),
            GetFieldFromUser(user, 'name', sub_field_name='fullName'))

  @staticmethod
  def _ProcessCustomerId(user):
    """Select 'customerId from returned user json.

    Args:
      user: user json object returned from the users API list().

    Returns:
      String user_id for the supplied user.
    """
    return GetFieldFromUser(user, 'customerId')

  @staticmethod
  def _PrintCustomerId(user):
    """Get commonly needed CustomerId from the domain name.

    Args:
      user: user json object returned from the users API list().
    """
    print 'CustomerId for %s:' % GetFieldFromUser(user, 'primaryEmail').split(
        '@')[1]
    print GetFieldFromUser(user, 'customerId')

  @staticmethod
  def _PrintOneLine(email, user_id, full_name):
    """Formats a user print line a little like ls -l.

    Example output:

    Users from domain altostrat.com:
    ID                     Email                                 Full Name
    000000558298938768732  george@altostrat.com                  George Lasta
    000000858699628788601  superadmin@altostrat.com              Super Lastb

    Args:
      email: User email (e.g. myemail@mydomain.com).
      user_id: 21 digit domain id.
      full_name: first and last name.
    """
    # Left justify all but the last as string fields.
    print '%-22s %-40s %s' % (user_id, email, full_name)

  @staticmethod
  def _PrintUserHeader():
    """Print user header for ls_users and ls_user."""
    UsersApiWrapper._PrintOneLine('Email', 'ID', 'Full Name')

  @staticmethod
  def _PrintOneUser(user, long_list=False):
    """Prints select fields from returned user json.

    Available fields include:
      agreedToTerms, changePasswordAtNextLogin, creationTime, customerId,
      emails, id, includeInGlobalAddressList, ipWhitelisted, isAdmin,
      isDelegatedAdmin, isMailboxSetup, kind, lastLoginTime,
      name ({'familyName': 'xx', 'fullName': 'yy', 'givenName': 'zz'}),
      nonEditableAliases, orgUnitPath, primaryEmail and suspended.
    Special handling is needed for:
      emails, name, nonEditableAliases, name: sort for deterministic output.

    Args:
      user: user json object returned from the users API list().
      long_list: if True, print all known user fields.
    """
    UsersApiWrapper._PrintOneLine(GetFieldFromUser(user, 'primaryEmail'),
                                  GetFieldFromUser(user, 'id'),
                                  GetFieldFromUser(user, 'name',
                                                   sub_field_name='fullName'))
    if long_list:
      for field in sorted(user.keys()):
        if field in ('primaryEmail', 'id', 'fullName'):  # already displayed.
          continue
        # For deterministic output, need to pprint container objects like
        # dict. Textwrap is used for the hanging indent.  We use a hanging
        # indent of 7 because 4 spaces is the normal margin and the extra
        # 3 spaces are used for: colon, space and opening brace.
        formatted_text = textwrap.fill(
            pprint.pformat(GetFieldFromUser(user, field)),
            subsequent_indent=(7+len(field)) * ' ', break_on_hyphens=False)
        print '    %s: %s' % (field, formatted_text)

  def _ProcessUserListPage(self, apps_domain, max_page, next_page_token=None,
                           query_filter=None):
    """Helper that handles exceptions retrieving pages of users.

    Args:
      apps_domain: Users apps domain e.g. mybiz.com.
      max_page: Used to optimize paging (1-500).
      next_page_token: Used for ongoing paging of users.
      query_filter: Optinally allow filtering based on many fields.
                    Obvious ones include orgName and orgUnitPath.

    Returns:
      List of users retrieved (one page).
    """
    request = self._users.list(domain=apps_domain, maxResults=max_page,
                               pageToken=next_page_token,
                               query=query_filter)
    backoff = http_utils.Backoff()
    while backoff.Loop():
      try:
        users_list = request.execute()
        return users_list
      except apiclient_errors.HttpError as e:
        if e.resp.status not in http_utils.RETRY_RESPONSE_CODES:
          raise admin_api_tool_errors.AdminAPIToolUserError(
              '%s\nPlease check your domain spelling (%s).' % (
                  http_utils.ParseHttpResult(e.uri, e.resp, e.content),
                  apps_domain))
        log_utils.LogInfo(
            'Possible quota problem retrieving users (%d).' % e.resp.status)
        backoff.Fail()

  def _ProcessDomainUsers(self, apps_domain, process_fn, max_results=None,
                          max_page=100, query_filter=None):
    """Helper to allow multiple, different print functions.

    Args:
      apps_domain: Users apps domain e.g. mybiz.com.
      process_fn: Function to be used against each user object (e.g. print).
      max_results: If not None, stop after this many users.
      max_page: Used to optimize paging (1-500).
      query_filter: Optinally allow filtering based on many fields.
                    Obvious ones include orgName and orgUnitPath.

    Returns:
      Tuple of (result list, count of users retrieved). The result list is
      populated using results from process_fn().
    """
    results = []
    retrieved_count = 0
    next_page_token = None

    if max_page < 1 or max_page > 500:
      max_page = 100  # API default.
    if max_results is not None and max_results < max_page:
      max_page = max_results

    users_list = self._ProcessUserListPage(apps_domain=apps_domain,
                                           max_page=max_page,
                                           query_filter=query_filter)
    while True:
      for user in users_list.get('users', []):
        result = process_fn(user)
        if result:
          results.append(result)
        retrieved_count += 1
        if max_results is not None and retrieved_count >= max_results:
          return results, retrieved_count
      next_page_token = users_list.get('nextPageToken')
      if not next_page_token:
        return results, retrieved_count
      users_list = self._ProcessUserListPage(apps_domain=apps_domain,
                                             max_page=max_page,
                                             query_filter=query_filter,
                                             next_page_token=next_page_token)

  def GetCustomerId(self, apps_domain):
    """Look up the customer_id for a specific apps_domain.

    Other APIs use customer_id as the key to domain-specific
    requests.

    Args:
      apps_domain: Users apps domain e.g. mybiz.com.

    Returns:
      The single customer_id as a string.
    """
    results, _ = self._ProcessDomainUsers(apps_domain=apps_domain,
                                          process_fn=self._ProcessCustomerId,
                                          max_results=1)
    if results:
      return results[0]
    return None  # Only occurs if an authenticated domain has no users.

  def PrintCustomerId(self, apps_domain):
    """Simple lookup of the customerId from the first user.

    Args:
      apps_domain: Users apps domain e.g. mybiz.com.
    """
    self._ProcessDomainUsers(apps_domain=apps_domain,
                             process_fn=self._PrintCustomerId,
                             max_results=1)

  def GetDomainUsers(self, apps_domain, basic=True, max_results=None,
                     max_page=500, query_filter=None):
    """List user details into a data structure.

    Used to serialize a large list of users to a (json) file.

    Args:
      apps_domain: Users apps domain e.g. mybiz.com.
      basic: If True, return a 3-tuple of (email, user_id, full_name) for
             each user, else return the whole user dictionary for each.
      max_results: If not None, stop after this many users.
      max_page: Used to optimize paging (1-500).
      query_filter: Optinally allow filtering based on many fields.
                    Obvious ones include orgName and orgUnitPath.

    Returns:
      List of tuples of user details [(email, id, full_name)...]
    """
    log_utils.LogDebug('GetDomainUsers (%s).' % max_results)
    if basic:
      user_attribute_filter_fn = self._ShowBasicUserFields
    else:
      user_attribute_filter_fn = self._ShowAllUserFields
    results, _ = self._ProcessDomainUsers(apps_domain=apps_domain,
                                          max_results=max_results,
                                          max_page=max_page,
                                          query_filter=query_filter,
                                          process_fn=user_attribute_filter_fn)
    return results

  def PrintDomainUsers(self, apps_domain, max_results=None, max_page=500):
    """Powerful demonstration of ease of user provisioning API.

    If the customer is interested in multiple domains, this might
    be rewritten to use customer=customer_id instead of domain=xxx.

    Args:
      apps_domain: Users apps domain e.g. mybiz.com.
      max_results: If not None, stop after this many users.
      max_page: Used to optimize paging (1-500).
    """
    print 'Users from domain %s:' % apps_domain
    self._PrintUserHeader()
    _, count = self._ProcessDomainUsers(apps_domain=apps_domain,
                                        process_fn=self._PrintOneUser,
                                        max_results=max_results,
                                        max_page=max_page)
    print '%d users found.' % count

  def GetDomainUser(self, user_mail):
    """Retrieve document for a user in an apps domain.

    A common reason to call this is to retrieve the user_id from an email name.

    Args:
      user_mail: username to check.

    Returns:
      The user document (available fields listed in _PrintOneUser()).
    """
    log_utils.LogDebug('GetDomainUser (%s).' % user_mail)
    request = self._users.get(userKey=user_mail)
    backoff = http_utils.Backoff()
    while backoff.Loop():
      try:
        return request.execute()
      except apiclient_errors.HttpError as e:  # Missing user raises HttpError.
        if e.resp.status not in http_utils.RETRY_RESPONSE_CODES:
          error_text = http_utils.ParseHttpResult(e.uri, e.resp, e.content)
          if error_text.startswith('ERROR: status=404'):
            # User not found is reflected by 404 - resource not found.
            return None
          raise admin_api_tool_errors.AdminAPIToolUserError(
              'User %s not found: %s' % (user_mail, error_text))
        log_utils.LogInfo(
            'Possible quota problem retrieving user %s (%d). Retrying after '
            'a short wait.' % (user_mail, e.resp.status))
        backoff.Fail()

  def IsDomainUser(self, user_mail):
    """Check if domain users exists.

    Args:
      user_mail: user email to check.

    Returns:
      True if user exists else False.
    """
    log_utils.LogDebug('IsDomainuser (%s).' % user_mail)
    return self.GetDomainUser(user_mail) is not None

  def PrintDomainUser(self, user_mail, long_list=False):
    """Print basic details of a domain user.

    Used by a command line utility to possible check if a user exists.
    If used with --long_list, all user details are printed.

    Args:
      user_mail: user email to find.
      long_list: If True, print added user fields.
    """
    user = self.GetDomainUser(user_mail)
    if user:
      self._PrintUserHeader()
      self._PrintOneUser(user=user, long_list=long_list)
    else:
      print 'User %s not found.' % user_mail

  def AddDomainUser(self, first_name, last_name, user_mail, new_password,
                    verify=False):
    """Adds user to the domain.

    Checks if the user already exists.  Users are created by default
    as unsuspended, non-admin users.

    Args:
      first_name: Given first name.
      last_name: Family name.
      user_mail: user_mail to add.
      new_password: Password to set.
      verify: If True, verify user was created.
    """
    log_utils.LogDebug('AddDomainUser (%s).' % user_mail)
    if self.IsDomainUser(user_mail):
      raise admin_api_tool_errors.AdminAPIToolUserError(
          'User %s already exists.' % user_mail)
    body = {
        'primaryEmail': user_mail,
        'name': {'givenName': first_name, 'familyName': last_name},
        'password': new_password
        }
    backoff = http_utils.Backoff()
    while backoff.Loop():
      try:
        self._users.insert(body=body).execute()
        if verify:
          time.sleep(2)  # Seems to be needed for Verify to work consistently.
          if not self.IsDomainUser(user_mail):
            raise admin_api_tool_errors.AdminAPIToolUserError(
                'Problem creating user: %s' % user_mail)
        return
      except apiclient_errors.HttpError as e:
        if e.resp.status not in http_utils.RETRY_RESPONSE_CODES:
          raise admin_api_tool_errors.AdminAPIToolUserError(
              http_utils.ParseHttpResult(e.uri, e.resp, e.content))
        log_utils.LogInfo(
            'Possible quota problem adding user %s (%d). Retrying after '
            'a short wait.' % (user_mail, e.resp.status))
        backoff.Fail()

  def DeleteDomainUser(self, user_mail, verify=False):
    """Deletes user from the domain.

    Checks if the user already exists before attempting delete.

    Args:
      user_mail: user_mail to add.
      verify: If True, verify user was deleted.

    Raises:
      AdminAPIToolUserError: Unable to delete user.
    """
    log_utils.LogDebug('DeleteDomainUser (%s).' % user_mail)
    if not self.IsDomainUser(user_mail):
      raise admin_api_tool_errors.AdminAPIToolUserError(
          'ERROR: user (%s) not a domain member. You may need to check "Enable '
          'provisioning API" in your Domain Settings->User Settings.' % (
              user_mail))
    backoff = http_utils.Backoff()
    while backoff.Loop():
      try:
        self._users.delete(userKey=user_mail).execute()
        if verify:
          time.sleep(2)  # Seems to be needed for Verify to work consistently.
          if self.IsDomainUser(user_mail):
            raise admin_api_tool_errors.AdminAPIToolUserError(
                'Problem deleting user %s.' % user_mail)
        return
      except apiclient_errors.HttpError as e:
        if e.resp.status not in http_utils.RETRY_RESPONSE_CODES:
          raise admin_api_tool_errors.AdminAPIToolUserError(
              http_utils.ParseHttpResult(e.uri, e.resp, e.content))
        log_utils.LogInfo(
            'Possible quota problem deleting user %s (%d). Retrying after '
            'a short wait.' % (user_mail, e.resp.status))
        backoff.Fail()


text:
[1] https://docs.python.org/3.5/library/urllib.html

[2] https://docs.python.org/3.5/library/email.message.html#email.message.Message

[3] https://docs.python.org/3.5/library/json.html


text:
import datetime
from unittest import mock

real_datetime_class = datetime.datetime

def mock_datetime_now(target, datetime_module):
    """Override ``datetime.datetime.now()`` with a custom target value.

    This creates a new datetime.datetime class, and alters its now()/utcnow()
    methods.

    Returns:
        A mock.patch context, can be used as a decorator or in a with.
    """

    # See https://bugs.python.org/msg68532
    # And https://docs.python.org/3/reference/datamodel.html#customizing-instance-and-subclass-checks
    class DatetimeSubclassMeta(type):
        """We need to customize the __instancecheck__ method for isinstance().

        This must be performed at a metaclass level.
        """

        @classmethod
        def __instancecheck__(mcs, obj):
            return isinstance(obj, real_datetime_class)

    class MockedDatetime(real_datetime_class, metaclass=DatetimeSubclassMeta):
        @classmethod
        def now(cls, tz=None):
            return target.replace(tzinfo=tz)

        @classmethod
        def utcnow(cls):
            return target

    return mock.patch.object(datetime_module, 'datetime', MockedDatetime)

real_date_class = datetime.date

def mock_date_today(target, datetime_module):
    """Override ``datetime.date.today()`` with a custom target value.

    This creates a new datetime.date class, and alters its today() method.

    Returns:
        A mock.patch context, can be used as a decorator or in a with.
    """

    # See https://bugs.python.org/msg68532
    # And https://docs.python.org/3/reference/datamodel.html#customizing-instance-and-subclass-checks
    class DateSubclassMeta(type):
        """We need to customize the __instancecheck__ method for isinstance().

        This must be performed at a metaclass level.
        """

        @classmethod
        def __instancecheck__(mcs, obj):
            return isinstance(obj, real_date_class)

    class MockedDate(real_date_class, metaclass=DateSubclassMeta):
        @classmethod
        def today(cls):
            return target

    return mock.patch.object(datetime_module, 'date', MockedDate)

def main():  # pragma: no cover
    """Run a couple of tests"""
    target_dt = real_datetime_class(2009, 1, 1)
    target_date = real_date_class(2009, 1, 1)

    print("Entering mock")
    with mock_datetime_now(target_dt, datetime):
        print("- now                       ->", datetime.datetime.now())
        print("- isinstance(now, dt)       ->", isinstance(datetime.datetime.now(), datetime.datetime))
        print("- isinstance(target, dt)    ->", isinstance(target_dt, datetime.datetime))

    with mock_date_today(target_date, datetime):
        print("- today                     ->", datetime.date.today())
        print("- isinstance(now, date)     ->", isinstance(datetime.date.today(), datetime.date))
        print("- isinstance(target, date)  ->", isinstance(target_date, datetime.date))

    print("Outside mock")
    print("- now                       ->", datetime.datetime.now())
    print("- isinstance(now, dt)       ->", isinstance(datetime.datetime.now(), datetime.datetime))
    print("- isinstance(target, dt)    ->", isinstance(target_dt, datetime.datetime))

    print("- today                     ->", datetime.date.today())
    print("- isinstance(now, date)     ->", isinstance(datetime.date.today(), datetime.date))
    print("- isinstance(target, date)  ->", isinstance(target_date, datetime.date))


text:
import SocketServer
import multiprocessing
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import subprocess
import matplotlib
matplotlib.use("Agg")
from pylab import *
from numpy import NaN
from io import BytesIO

class MyHandler(BaseHTTPRequestHandler):
  """ HTTP request Handler that will generate a Mandelbrot set on each request to
  root path (/). Request to /health-check receives an instant 200 OK response.
  """

  # create an array for X and Y values
  X = arange(-2, .5, .02)
  Y = arange(-1, 1, .02)
  # create an array for results
  results = zeros((len(Y), len(X)))

  def m(self, a):
    """ calculate Mandelbrot function

        Keyword arguments:
        a -- the complex number for which the function should be executed
    """
    z = 0
    for n in range(1, 100):
      z = z**2 + a
      if abs(z) > 2:
        return n
    return NaN

  def do_GET(self):
    """ Respond to HTTP GET requests"""

    # When root is requested, calculate Mandelbrot on request
    if self.path == "/":
      # Calculate each pixel of the image
      for ix, x in enumerate(self.X):
        for iy, y in enumerate(self.Y):
          self.results[iy, ix] = self.m(x + 1j * y)
      # Save image from array as PNG with pyplot
      imshow(
          self.results,
          cmap=plt.cm.prism,
          interpolation="none",
          extent=(self.X.min(), self.X.max(), self.Y.min(), self.Y.max()))
      xlabel("Re(c)")
      ylabel("Im(c)")
      self.send_response(200)
      self.send_header("Content-Type", "image/png")
      self.end_headers()
      # Send image as response
      with BytesIO() as buffer:
        savefig(buffer, format="png")
        self.wfile.write(buffer.getvalue())
    # On health check send an empty response
    elif self.path == "/health-check":
      self.send_response(200)
    # All other paths send a 404
    else:
      self.send_response(404)

class ThreadedHTTPServer(SocketServer.ForkingMixIn, HTTPServer):
  """ Have a HTTP Server forking to different threads """
  pass

# Start web server when script is started
if __name__ == "__main__":
  try:
    server = ThreadedHTTPServer(("", 80), MyHandler)
    print "Started httpserver on port 80"
    # Wait forever for incoming http requests
    server.serve_forever()
  except KeyboardInterrupt:
    print "^C received, shutting down the web server"
    server.socket.close()


text:
package com.github.gfx.android.orma.migration.test;

import com.github.gfx.android.orma.migration.SchemaDiffMigration;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import android.content.Context;

import java.util.Arrays;
import java.util.Collections;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

@RunWith(AndroidJUnit4.class)
public class IndexDiffTest {

    static final String SCHEMA_HASH = "abc";

    SchemaDiffMigration migration;

    Context getContext() {
        return ApplicationProvider.getApplicationContext();
    }

    @Before
    public void setUp() throws Exception {
        migration = new SchemaDiffMigration(getContext(), SCHEMA_HASH);
    }

    @Test
    public void buildDropIndexStatement() throws Exception {
        assertThat(migration.buildDropIndexStatement("CREATE INDEX IF NOT EXISTS index_foo ON foo (bar)"),
                is("DROP INDEX IF EXISTS `index_foo`"));
    }

    @Test
    public void buildDropIndexStatement_caseInsensitive() throws Exception {
        assertThat(migration.buildDropIndexStatement("create index if not exists index_foo on foo (bar)"),
                is("DROP INDEX IF EXISTS `index_foo`"));
    }

    @Test
    public void buildDropIndexStatement_spaceInsensitive() throws Exception {
        assertThat(migration.buildDropIndexStatement("create \n"
                        + "index \n"
                        + "if \n"
                        + "not \n"
                        + "exists \n"
                        + "index_foo \n"
                        + "on \n"
                        + "foo \n"
                        + "(bar)\n"),
                is("DROP INDEX IF EXISTS `index_foo`"));
    }

    @Test
    public void buildDropIndexStatement_omitIfNotExists() throws Exception {
        assertThat(migration.buildDropIndexStatement("CREATE INDEX index_foo ON foo (bar)"),
                is("DROP INDEX IF EXISTS `index_foo`"));
    }

    @Test
    public void buildDropIndexStatement_doubleQuotedNames() throws Exception {
        assertThat(migration.buildDropIndexStatement("CREATE INDEX IF NOT EXISTS `index_foo` ON `foo` (`bar`)"),
                is("DROP INDEX IF EXISTS `index_foo`"));
    }

    @Test
    public void buildDropIndexStatement_backQuotedNames() throws Exception {
        assertThat(migration.buildDropIndexStatement("CREATE INDEX IF NOT EXISTS `index_foo` ON `foo` (`bar`)"),
                is("DROP INDEX IF EXISTS `index_foo`"));
    }

    @Test
    public void testIndexDiff() throws Exception {
        assertThat(migration.indexDiff(Collections.<String>emptyList(), Arrays.asList(
                "CREATE INDEX IF NOT EXISTS `index_foo` ON `t` (`foo`)",
                "CREATE INDEX IF NOT EXISTS `index_bar` ON `t` (`bar`)"
        )), contains(
                "CREATE INDEX IF NOT EXISTS `index_foo` ON `t` (`foo`)",
                "CREATE INDEX IF NOT EXISTS `index_bar` ON `t` (`bar`)"
        ));
    }

    @Test
    public void indexDiff_removeUnique() throws Exception {
        assertThat(migration.indexDiff(Collections.singletonList(
                "CREATE UNIQUE INDEX IF NOT EXISTS `index_foo` ON `t` (`foo`)"
        ), Collections.singletonList(
                "CREATE INDEX IF NOT EXISTS `index_foo` ON `t` (`foo`)"
        )), contains(
                "DROP INDEX IF EXISTS `index_foo`",
                "CREATE INDEX IF NOT EXISTS `index_foo` ON `t` (`foo`)"
        ));
    }

    @Test
    public void indexDiff_multiColumnIndex() throws Exception {
        assertThat(migration.indexDiff(Collections.<String>emptyList(), Collections.singletonList(
                "CREATE INDEX IF NOT EXISTS `index_foo` ON `t` (`foo`, `bar`)"
        )), contains(
                "CREATE INDEX IF NOT EXISTS `index_foo` ON `t` (`foo`, `bar`)"
        ));
    }
}


text:
Provides a standard, reusable and tested way of saving data in application isolated storage. Intended use case is application settings or reasonably sized user data

Data is JSON serialized and written to the application's own isolated store for each platform.
The Universal Platform implementation also encrypts data before writing it to disk using Windows's own Data Protection API (DPAPI) using a user scoped key.

All AppStorageService implementations on different platforms implement the IAppStorageService interface, defined in AppStorageService.Core (a portable class library) assembly.
This is to allow easier sharing of business logic in PCLs across different platforms (add the AppStorageService.Core NuGet package to import the interface definition).
It also makes it easier to create mocks for unit testing and IOC usage.

##Installation

###Universal apps

```
Install-Package AppStorageService.Universal
```

###Classic desktop applications

```
Install-Package AppStorageService.Desktop
```

##Usage

Data to be handled needs to be marked as serializable.
For example:

```
[DataContract]
public class Data
{
    [DataMember]
    public string StringProperty { get; set; }
}
```

##Instantiate service

```
var service = new AppStorageService<Data>("File.json");
```

###Save data

```
var dataToSave = new Data { StringProperty = "SomeValue" };
await service.SaveDataAsync(dataToSave);
```

###Load data

```
var loadedData = await service.LoadDataAsync();
```

###Delete data
```
await service.DeleteDataAsync();
```

It is recommended to instantiate the service once per datatype and reuse that instance throughout the application

##Avoiding data corruption

To prevent data corruption when performing IO operations, application closure should be delayed to allow them to complete.

```
//request application closure delay

var pollingTime = TimeSpan.FromMilliseconds(100);
while(service.OperationInProgress)
{
    await Task.Delay(pollingTime);
}

//allow application to close
```


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe "NilClass#&" do
  it "returns false" do
    (nil & nil).should == false
    (nil & true).should == false
    (nil & false).should == false
    (nil & "").should == false
    (nil & mock('x')).should == false
  end
end


text:
export function spongeCase(input: string): string {
  let result = "";
  for (let i = 0; i < input.length; i++) {
    result +=
      Math.random() > 0.5 ? input[i].toUpperCase() : input[i].toLowerCase();
  }
  return result;
}


text:
package org.geoint.lbac.policy;

/**
 *
 */
public interface WeightedControlPolicy
        extends ControlPolicy, Comparable<WeightedControlPolicy> {

    public int getWeight();

}


text:
import React, { PureComponent } from 'react';

import { DataSourcePluginOptionsEditorProps } from '@grafana/data';
import { ConnectionConfig } from '@grafana/google-sdk';

import { CloudMonitoringOptions, CloudMonitoringSecureJsonData } from '../../types';

export type Props = DataSourcePluginOptionsEditorProps<CloudMonitoringOptions, CloudMonitoringSecureJsonData>;

export class ConfigEditor extends PureComponent<Props> {
  render() {
    return (
      <>
        <ConnectionConfig {...this.props}></ConnectionConfig>
      </>
    );
  }
}


text:
import {defineOption, ProseMirror} from "prosemirror/dist/edit"
import {updateCommands, Command, CommandSet} from "prosemirror/dist/edit/command"
import {TextSelection} from "prosemirror/dist/edit/selection"
import {Textblock, Pos} from "prosemirror/dist/model"
import {getNodeEndpoints} from "./util"

window.ProseMirror = ProseMirror

defineOption("find", false, (pm, value) => {
  if (pm.mod.find) {
    pm.mod.find.detach()
    pm.mod.find = null
  }
  if (value) {
    pm.mod.find = new Find(pm, value)
  }
})

//Recursively finds matches within a given node
function findInNode(node, findResult) {
  let ret = []

  if(node.isTextblock) {
    let index = 0, foundAt, ep = getNodeEndpoints(pm.doc, node)
    while((foundAt = node.textContent.slice(index).search(findResult.findRegExp)) > -1) {
      let sel = new TextSelection(ep.from + index + foundAt + 1, ep.from + index + foundAt + findResult.findTerm.length + 1)
      ret.push(sel)
      index = index + foundAt + findResult.findTerm.length
    }
  } else {
    node.content.forEach((child, i) => ret = ret.concat(findInNode(child, findResult)))
  }
  return ret
}

//Finds the selection that comes after the end of the current selection
function selectNext(pm, selections) {
  if(selections.length === 0) {
    return null
  }

  for(let i=0;i<selections.length;i++) {
    if(pm.selection.to <= selections[i].from ) {
      removeActiveFind(pm)
      markActiveFind(pm,selections[i])
      pm.setSelection(selections[i])
      pm.scrollIntoView(selections[i].head)
      return selections[i]
    }
  }
  removeActiveFind(pm)
  markActiveFind(pm,selections[0])
  pm.setSelection(selections[0])
  pm.scrollIntoView(selections[0].head)
  return selections[0];
}

//Marks selections with the findClass specificed in options
function markFinds(pm, finds) {
  finds.forEach(selection => {
    var matchingRanges = pm.ranges.ranges.filter(function(range){return range.from === selection.from && range.to === selection.to})
    if(matchingRanges.length === 0){
      pm.markRange(selection.from, selection.to, {className: pm.mod.find.options.findClass})
    }
  })
}

//Removes MarkedRanges that reside within a given node
  function removeFinds(pm, node = pm.doc) {
  pm.ranges.ranges.filter(r => r.options.className === pm.mod.find.options.findClass && pm.doc.resolve(r.from).path.indexOf(node) > -1).forEach(r => pm.ranges.removeRange(r))
}

function markActiveFind(pm,selection){
  pm.markRange(selection.from, selection.to, {className: pm.mod.find.options.activeFindClass})
}
function removeActiveFind(pm, node = pm.doc){
  pm.ranges.ranges.filter(r => r.options.className === pm.mod.find.options.activeFindClass && pm.doc.resolve(r.from).path.indexOf(node) > -1).forEach(r => pm.ranges.removeRange(r))
}

//Calculates the start and end nodes of a transform
function rangeFromTransform(tr) {
  let from, to
  for (let i = 0; i < tr.steps.length; i++) {
    let step = tr.steps[i], map = tr.maps[i]
    let stepFrom = map.map(step.from || step.pos, -1).pos
    let stepTo = map.map(step.to || step.pos, 1).pos
    from = from ? map.map(from, -1).pos.min(stepFrom) : stepFrom
    to = to ? map.map(to, 1).pos.max(stepTo) : stepTo
  }
  return {from, to}
}

//Removes and recalcualtes finds between a start and end point
function processNodes (pm, from, to, findResult) {
  if(!findResult) return
  let processed = []
  function processNode (node, path) {
    if(node.isTextblock && processed.indexOf(node) === -1) {
      removeFinds(pm, node)
      removeActiveFind(pm, node)
      let matches = findInNode(node, findResult, [].concat(path))
      markFinds(pm, matches)
      processed.push(node)
    }
  }
  pm.doc.nodesBetween(from, to, (node, path, parent) => processNode(node, path))
}

//Calculates default value for find input
//Selected text > Last search > Empty
function defaultFindTerm(pm) {
  if(!pm.selection.empty) {
    return pm.doc.slice(pm.selection.from, pm.selection.to).content.textContent
  }
  if(pm.mod.find.findOptions) {
    return pm.mod.find.findOptions.findTerm
  }
  return null
}

//Calculates default value for replace input
//Last search > Empty
function defaultReplaceWith(pm) {
  if(pm.mod.find.findOptions) {
    return pm.mod.find.findOptions.replaceWith
  }
  return null
}

//A default set of commands
export var findCommands = {
  find: {
    label: "Find occurances of a string",
    run: function(pm, findTerm) {
      pm.mod.find.find(findTerm)
    },
    params: [
      {label: "Find", type: "text", prefill: defaultFindTerm}
    ],
    keys: ["Mod-F"]
  },
  findNext: {
    label: "Find next occurance of last searched string",
    run: function(pm,findTerm) {
      pm.mod.find.findNext()
    },
    keys: ["Alt-Mod-F"]
  },
  clearFind: {
    label: "Clear highlighted finds",
    run: function(pm) {
      pm.mod.find.clearFind()
    }
  },
  replace: {
    label: "Replaces selected/next occurance of a string",
    run: function(pm, findTerm, replaceWith) {
      pm.mod.find.replace(findTerm, replaceWith)
    },
    params: [
      {label: "Find", type: "text", prefill: defaultFindTerm},
      {label: "Replace", type: "text", prefill: defaultReplaceWith}
    ],
    keys: ["Shift-Mod-F"]
  },
  replaceAll: {
    label: "Replaces all occurances of a string",
    run: function(pm, findTerm, replaceWith) {
      pm.mod.find.replaceAll(findTerm, replaceWith)
    },
    params: [
      {label: "Find", type: "text", prefill: defaultFindTerm},
      {label: "Replace", type: "text", prefill: defaultReplaceWith}
    ],
    keys: ["Shift-Alt-Mod-F"]
  }
}

//Class to handle a set of find/replace terms and results
class FindOptions {
  constructor(pm, findTerm, replaceWith, caseSensitive = true) {
    this.pm = pm
    this.findTerm = findTerm
    this.replaceWith = replaceWith
    this.caseSensitive = caseSensitive
  }

  //Constructs a regex based on find term and case sensitivity
  get findRegExp() {
    return RegExp(this.findTerm, !this.caseSensitive ? "i" : "")
  }

  //Calculates results for a set of terms
  results() {
    return findInNode(this.pm.doc, this)
  }
}

class Find {
  constructor(pm, options) {
    this.pm = pm
    this.findOptions = null

    this.options = Object.create(this.defaultOptions)
    for(let option in options){
      this.options[option] = options[option]
    }

    pm.mod.find = this

    //Recalculate changed blocks on transform
    this.onTransform = function(transform) {
      //If there was a find
      if(pm.mod.find.findOptions) {
        let {from, to} = rangeFromTransform(transform)
        processNodes(pm, from, to, pm.mod.find.findOptions)
      }
    }

    pm.on("transform", this.onTransform)
  }

  detach() {
    this.clearFind()
    pm.off("transform", this.onTransform)
  }

  //Default set of options
  get defaultOptions() {
    return {
      autoSelectNext: true, //move selection to next find after 'find' or 'replace'
      findClass: "find", //class to add to MarkedRanges
      activeFindClass: "activeFind"
    }
  }

  //Gets last find options
  get findOptions() {
    return this._findOptions
  }

  //Clears last find display and sets new find options
  set findOptions(val) {
    if(this._findOptions) this.clearFind() //clear out existing results if there are any
    this._findOptions = val
  }

  //Find and mark instnaces of a find term, optionally case insensitive
  //Will move selection to the next match, if autoSelectNext option is true
  find(findTerm, caseSensitive = true) {
    this.findOptions = new FindOptions(this.pm, findTerm, null, caseSensitive)

    let selections = this.findOptions.results()

    markFinds(this.pm, selections)

    if(this.options.autoSelectNext) {
      selectNext(this.pm, selections)
    }

    return selections
  }

  //Moves the selection to the next instance of the find term, optionall case insensitive
  findNext(findTerm, caseSensitive = true) {
    if(findTerm) {
      this.findOptions = new FindOptions(this.pm, findTerm, null, caseSensitive)
    }
    if(this.findOptions) {
      let selections = this.findOptions.results()
      markFinds(this.pm, selections)
      return selectNext(this.pm, selections)
    }
    return null
  }

  //Clears find display and nulls out stored find options
  clearFind() {
    removeFinds(this.pm)
    removeActiveFind(this.pm)
    this._findOptions = null
  }

  //Replaces next match of a findTerm with the repalceWith string, optionally case insensitive
  //If current selection matches the find term it will be replaced
  //Otherwise, selection  will be moved to the next match and that will be replaced
  //If options.autoFindNext is true the match that proceeds replaced on will be selected
  replace(findTerm, replaceWith, caseSensitive = true) {
    this.findOptions = new FindOptions(this.pm, findTerm, replaceWith, caseSensitive)

    if(!this.pm.doc.slice(this.pm.selection.from, this.pm.selection.to).content.textContent.match(this.findOptions.findRegExp)) {
      if(!selectNext(this.pm, this.findOptions.results())) {
        return null
      }
    }

    let transform = this.pm.tr.typeText(replaceWith).apply({scrollIntoView: true})

    if(this.options.autoSelectNext) {

      let otherResults = this.findOptions.results()
      if(otherResults.length) {
        removeFinds(this.pm)
        removeActiveFind(this.pm)
        markFinds(this.pm, otherResults)
      }
      selectNext(this.pm, otherResults)

    }

    return transform
  }

  //Replaces all occurances of a findTerm with the replaceWith string, optionally case insensitive
  replaceAll(findTerm, replaceWith, caseSensitive = true) {
    this.findOptions = new FindOptions(this.pm, findTerm, replaceWith, caseSensitive)

    let selections = this.findOptions.results(),
        selection, transform,
        transforms = [];

    while(selection = selections.shift()) {
      this.pm.setSelection(selection)
      transform = this.pm.tr.typeText(replaceWith).apply({scrollIntoView: true})
      transforms.push(transform)
      selections = selections.map(s => s.map(this.pm.doc, transform.maps[0]))
    }
    return transforms
  }

}


text:
/*
 *               In the name of Allah
 * This file is part of The "Quran Teacher or Learn Arabic" Project. Use is subject to
 * license terms.
 *
 * @author:         Fazle Rabbi Rahat
 *
 */
package QuranTeacher.Preferences;

/**
 * @author Rahat
 *@Date: 28-July-2015
 */
public class AdvancedAnimPref extends Preferences{

	private int lineGap;
	private int extraHeight;
	private int wordGap;
	private boolean hidePartial;
	private int deltaPixel=DeltaPixelProperty.minDeltaPixel;

	private static final String[] prefStrings={
		"lineGap=","extraHeight=","wordGap=","hidePartial=","deltaPixel="};

	public AdvancedAnimPref(String id) {
		super(id);
	}
	public AdvancedAnimPref(String id,int lineGap,int extraHeight,int wordGap,boolean hidePartial,
			int deltaPixel) {
		super(id);
		this.lineGap=lineGap;
		this.extraHeight=extraHeight;
		this.wordGap=wordGap;
		this.hidePartial=hidePartial;
		this.deltaPixel=deltaPixel;
	}

	@Override
	public void resetToDefault() {
		// TODO Auto-generated method stub
		//nothing to do
	}

	@Override
	public void checkAndGrab(String text) {
		int value=Integer.parseInt(text.substring(text.indexOf("=")+1));
		if(text.startsWith(prefStrings[0]))
			lineGap=value;

		else if(text.startsWith(prefStrings[1]))
			extraHeight=value;

		else if(text.startsWith(prefStrings[2]))
			wordGap=value;

		else if(text.startsWith(prefStrings[3]))
			hidePartial=value==0?false:true;

		else if(text.startsWith(prefStrings[4]))
			deltaPixel=value;
	}

	@Override
	public String toString() {
		int k=0;
		if(hidePartial)k=1;

		return prefStrings[0]+Integer.toString(lineGap)
				+"\n"+prefStrings[1]+Integer.toString(extraHeight)
				+"\n"+prefStrings[2]+Integer.toString(wordGap)
				+"\n"+prefStrings[3]+Integer.toString(k)
				+"\n"+prefStrings[4]+Integer.toString(deltaPixel);
	}

	public int getLineGap() {
		return lineGap;
	}

	public int getExtraHeight() {
		return extraHeight;
	}

	public int getWordGap() {
		return wordGap;
	}

	public boolean isHidePartial() {
		return hidePartial;
	}

	public int getDeltaPixel(){
		return deltaPixel;
	}
}


text:
var request = require('supertest');
var path = require('path');
var rewire = require('rewire');
var assert = require('assert');
var fs = require('fs');

/**
 * Creates instance of example app using an injected version of express-hbs to track the number of times a
 * file is read. Additionally, the $NODE_ENV environment variable may be set.
 *
 * @param env
 * @returns {{app: hbs, readCounts: {}}}
 */
function createApp(env) {
  var readCounts = {};
  var hbs = rewire('../lib/hbs');
  hbs.__set__('fs', {
    readFileSync: function(filename, encoding) {
      if (typeof readCounts[filename] === 'undefined') {
        readCounts[filename] = 1;
      } else {
        readCounts[filename] += 1;
      }

      return fs.readFileSync(filename, encoding);
    },

    readFile: function(filename, encoding, cb) {
      if (typeof readCounts[filename] === 'undefined') {
        readCounts[filename] = 1;
      } else {
        readCounts[filename] += 1;
      }

      fs.readFile(filename, encoding, cb);
    },
    existsSync: function(filename, encoding) {
      return fs.existsSync(filename, encoding);
    }
  });

  // used mocked hbs in example
  var example = require('../example/app');
  var app = example.create(hbs, env);
  return {app: app, readCounts: readCounts};
}

describe('express-hbs', function() {
  describe('cache', function() {

    it('should not cache layout in `development`', function(done) {
      var mock = createApp('development');

      request(mock.app)
        .get('/')
        .end(function(err) {
          assert.ifError(err);

          request(mock.app)
            .get('/')
            .expect(/DEFAULT LAYOUT/)
            .end(function(err) {
              assert.ifError(err);

              var filename = path.resolve(__dirname, '../example/views/layout/default.hbs');
              assert.equal(mock.readCounts[filename], 2);
              done();
            });
        });
    });

    it('should cache layout in `production` reading file once', function(done) {
      var mock = createApp('production');

      // reads layout from fs once
      request(mock.app)
        .get('/')
        .end(function(err) {
          assert.ifError(err);

          request(mock.app)
            .get('/')
            .expect(/DEFAULT LAYOUT/)
            .end(function(err, res) {
              assert.ifError(err);

              var filename = path.resolve(__dirname, '../example/views/layout/default.hbs');
              assert.equal(mock.readCounts[filename], 1);
              done();
            });
        });
    });

    it('should not cache partials in `development`', function(done) {
      var mock = createApp('development');

      request(mock.app)
        .get('/veggies')
        .expect(/just a comment/)
        .end(function(err) {
          assert.ifError(err);
          request(mock.app)
            .get('/veggies')
            .expect(/just a comment/)
            .end(function(err) {
              assert.ifError(err);

              var filename = path.resolve(__dirname, '../example/views/partials/sub/comment.hbs');
              assert.equal(mock.readCounts[filename], 2);
              done();
            });
        });
    });

    it('should cache partials in `production', function (done) {
      var mock = createApp('production');

      request(mock.app)
        .get('/veggies')
        .expect(/just a comment/)
        .end(function(err) {
          assert.ifError(err);
          request(mock.app)
            .get('/veggies')
            .expect(/just a comment/)
            .end(function(err) {
              assert.ifError(err);

              var filename = path.resolve(__dirname, '../example/views/partials/sub/comment.hbs');
              assert.equal(mock.readCounts[filename], 1);
              done();
            });
        });
    });
  });
});


text:
stripe-ctf3
===========

They're in the branches. Just look.


text:
namespace Browsio.Domain
{
    #region << Using >>

    using System.Collections.Generic;
    using System.Linq;
    using Incoding.CQRS;
    using Incoding.Data;

    #endregion

    public class GetStoresByTopQuery : QueryBase<List<Store>>
    {
        protected override List<Store> ExecuteResult()
        {
            return Repository.Query(paginatedSpecification: new PaginatedSpecification(1, 10),
                                    fetchSpecification: new StoreWithUserFetchSpec())
                             .ToList();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.bragitoff.curvefit_leastsquares.MainActivity">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stretchColumns="*">

        <TableRow
            android:layout_width="0dp"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:id="@+id/test"
                android:text="Enter x-values:"
                android:layout_alignParentTop="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_toLeftOf="@+id/submit_x"
                android:layout_toStartOf="@+id/submit_x" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:id="@+id/test1"
                android:text="Enter y-values:"
                android:layout_alignParentTop="true"
                android:layout_alignLeft="@+id/calc"
                android:layout_alignStart="@+id/calc" />
        </TableRow>

        <TableRow
            android:layout_width="0dp"
            android:layout_height="match_parent">

            <EditText
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:inputType="numberSigned|numberDecimal"
                android:ems="10"
                android:id="@+id/x"
                android:hint="x-axis values"
                android:layout_below="@+id/test"
                android:layout_toLeftOf="@+id/calc"
                android:layout_toStartOf="@+id/calc"
                android:imeOptions="actionDone"/>

            <EditText
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:inputType="numberSigned|numberDecimal"
                android:ems="10"
                android:id="@+id/y"
                android:hint="y-axis values"
                android:layout_below="@+id/test"
                android:layout_toRightOf="@+id/test"
                android:layout_toEndOf="@+id/test"
                android:imeOptions="actionDone"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <FrameLayout
                android:layout_width="0dp"
                android:layout_height="match_parent">

                <Button
                    android:text="Update"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/updatex"
                    android:visibility="invisible"
                    android:background="@color/colorAccent"
                    tools:textColor="@color/icons"
                    android:textColor="@color/icons"
                    android:layout_marginRight="5dp"
                    android:elevation="9dp"/>

                <Button
                    android:text="Insert"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/insertx"
                    android:visibility="invisible"
                    android:background="@color/colorAccent"
                    tools:textColor="@color/icons"
                    android:textColor="@color/icons"
                    android:layout_marginRight="5dp"
                    android:elevation="9dp"/>

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Submit"
                    android:id="@+id/submit_x"
                    android:layout_below="@+id/x"
                    android:layout_toStartOf="@+id/submit_y"
                    android:layout_alignParentLeft="false"
                    android:background="@color/colorPrimary"
                    tools:textColor="@color/icons"
                    android:textColor="@color/icons"
                    android:layout_marginRight="5dp"
                    android:elevation="9dp" />
            </FrameLayout>

            <FrameLayout
                android:layout_width="0dp"
                android:layout_height="match_parent">

                <Button
                    android:text="Update"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/updatey"
                    android:visibility="invisible"
                    android:background="@color/colorAccent"
                    tools:textColor="@color/icons"
                    android:textColor="@color/icons"
                    android:layout_marginRight="5dp"
                    android:elevation="9dp"/>

                <Button
                    android:text="Insert"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/inserty"
                    android:visibility="invisible"
                    android:background="@color/colorAccent"
                    tools:textColor="@color/icons"
                    android:textColor="@color/icons"
                    android:layout_marginRight="5dp"
                    android:elevation="9dp"/>

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Submit"
                    android:id="@+id/submit_y"
                    android:layout_below="@+id/y"
                    android:layout_alignRight="@+id/calc"
                    android:layout_alignEnd="@+id/calc"
                    android:textColor="@color/icons"
                    android:background="@color/colorPrimary" />
            </FrameLayout>

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ListView
                android:layout_width="0dp"
                android:layout_height="200dp"
                android:id="@+id/x_axis"
                android:layout_below="@+id/submit_x"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_weight="0.5"
                android:background="@color/primary_light"
                android:layout_marginRight="1dp" />

            <ListView
                android:layout_width="0dp"
                android:layout_height="200dp"
                android:id="@+id/y_axis"
                android:layout_centerHorizontal="true"
                android:layout_below="@+id/submit_y"
                android:layout_weight="0.5"
                android:background="@color/primary_light" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Clear"
                android:onClick="clear"
                android:id="@+id/clear"
                android:layout_below="@+id/y_axis"
                android:layout_centerHorizontal="true"
                android:textColor="@color/icons"
                android:background="@color/colorAccent"
                android:layout_marginRight="5dp" />

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Calculate"
                android:id="@+id/calc"
                android:onClick="calc_fit"
                android:layout_below="@+id/y_axis"
                android:layout_centerHorizontal="true"
                android:layout_toRightOf="@+id/clear"
                android:background="@color/colorAccent"
                android:textColor="@color/icons" />
        </TableRow>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save as CSV"
            android:onClick="save_csv"
            android:id="@+id/csv_save"
            android:textColor="@color/icons"
            android:background="@color/colorPrimaryDark"
            android:layout_marginTop="3dp"
            android:elevation="5dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Read CSV"
            android:id="@+id/button4"
            android:onClick="read_csv2"
            android:layout_below="@+id/csv_save"
            android:layout_centerHorizontal="true"
            android:textColor="@color/icons"
            android:background="@color/colorPrimaryDark"
            android:layout_marginTop="3dp"
            android:elevation="16dp" />

    </TableLayout>

</RelativeLayout>
</ScrollView>


text:
using ColossalFramework.IO;
using NetworkSkins.Net;
using NetworkSkins.Skins.Serialization;

namespace NetworkSkins.Skins.Modifiers
{
    public class StreetLightModifier : NetworkSkinModifier
    {
        public readonly PropInfo StreetLight;

        public readonly float RepeatDistance;

        public StreetLightModifier(PropInfo streetLight, float repeatDistance = 40) : base(NetworkSkinModifierType.StreetLight)
        {
            StreetLight = streetLight;
            RepeatDistance = repeatDistance;
        }

        public override void Apply(NetworkSkin skin)
        {
            if (skin.m_lanes == null) return;

            for (var l = 0; l < skin.m_lanes.Length; l++)
            {
                var laneProps = skin.m_lanes[l]?.m_laneProps?.m_props;
                if (laneProps == null) continue;

                for (var p = laneProps.Length - 1; p >= 0; p--)
                {
                    if (StreetLightUtils.IsStreetLightProp(laneProps[p]?.m_finalProp))
                    {
                        if (StreetLight != null) {
                            skin.UpdateLaneProp(l, p, laneProp =>
                            {
                                laneProp.m_prop = StreetLight;
                                laneProp.m_finalProp = StreetLight;
                                laneProp.m_repeatDistance = RepeatDistance;
                                StreetLightUtils.CorrectStreetLightPropAngleAndPosition(skin.Prefab, laneProp, skin.Prefab.m_halfWidth, skin.m_lanes[l].m_position);
                            });
                        }
                        else
                        {
                            skin.RemoveLaneProp(l, p);
                        }
                    }
                }
            }
        }

        #region Serialization
        protected override void SerializeImpl(DataSerializer s)
        {
            s.WriteUniqueString(StreetLight?.name);
            s.WriteFloat(RepeatDistance);
        }

        public static StreetLightModifier DeserializeImpl(DataSerializer s, IPrefabCollection prefabCollection, NetworkSkinLoadErrors errors)
        {
            var streetLight = prefabCollection.FindPrefab<PropInfo>(s.ReadUniqueString(), errors);
            var repeatDistance = s.ReadFloat();

            return new StreetLightModifier(streetLight, repeatDistance);
        }
        #endregion

        #region Equality
        protected bool Equals(StreetLightModifier other)
        {
            return Equals(StreetLight, other.StreetLight) && RepeatDistance.Equals(other.RepeatDistance);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            if (obj.GetType() != GetType())
            {
                return false;
            }

            return Equals((StreetLightModifier) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return ((StreetLight != null ? StreetLight.GetHashCode() : 0) * 397) ^ RepeatDistance.GetHashCode();
            }
        }
        #endregion
    }
}


text:
<?php

// Private filters, can change at any time
add_filter('ls_slider_title', 'ls_filter_slider_title', 10, 2);
add_filter('ls_preview_for_slider', 'ls_preview_for_slider', 10, 1);
add_filter('ls_get_thumbnail', 'ls_get_thumbnail', 10, 3);
add_filter('ls_get_image', 'ls_get_image', 10, 2);

// Public filters
add_filter('ls_parse_defaults', 'ls_parse_defaults', 10, 2);

function ls_filter_slider_title($sliderName = '', $maxLength = 50) {
	$name = empty($sliderName) ? 'Unnamed' : htmlspecialchars(stripslashes($sliderName));
	return isset($name[$maxLength]) ? substr($name, 0, $maxLength) . ' ...' : $name;
}

function ls_preview_for_slider( $slider = array() ) {

	// Attempt to find pre-defined slider banner
	if( ! empty($slider['data']['meta']) && ! empty($slider['data']['meta']['preview']) ) {
		return $slider['data']['meta']['preview'];
	}

	// Find an image
	if( isset($slider['data']['layers']) ) {
		foreach( $slider['data']['layers'] as $layer) {
			if( !empty($layer['properties']['background']) && $layer['properties']['background'] !== '[image-url]' ) {
				$image = $layer['properties']['background'];

				if( ! empty($layer['properties']['backgroundId'] ) ) {
					$src = wp_get_attachment_image_src( $layer['properties']['backgroundId'], 'medium');
					if( ! empty( $src[0] ) ) {
						$image = $src[0];
					}
				}

				break;
			}
		}
	}

	return ! empty( $image ) ? $image : '';
}

function ls_get_thumbnail($id = null, $url = null, $blankPlaceholder = false) {

	// Image ID
	if(!empty($id)) {
		if($image = wp_get_attachment_thumb_url($id, 'thumbnail')) {
			return $image;
		}
	}

	if(!empty($url)) {

		$thumb = substr_replace($url, '-150x150.', strrpos($url,'.'), 1);
		$file = LS_ROOT_PATH.'/sampleslider/'.basename($thumb);

		if(file_exists($file)) { return $thumb; } else { return $url; }
	}

	return LS_ROOT_URL.'/static/admin/img/blank.gif';
}

function ls_get_image($id = null, $url = null) {

	if( ! empty( $id )) {
		if($image = wp_get_attachment_url($id, 'thumbnail')) {
			return $image;
		}
	} elseif( ! empty( $url ) ) {
		return $url;
	}

	return LS_ROOT_URL.'/static/admin/img/blank.gif';
}

function ls_parse_defaults($defaults = array(), $raw = array()) {

	$activated = get_option('layerslider-authorized-site', false);
	$permission = current_user_can('publish_posts');
	$ret = array();

	foreach($defaults as $key => $default) {

		$phpKey = is_string($default['keys']) ? $default['keys'] : $default['keys'][0];
		$jsKey  = is_string($default['keys']) ? $default['keys'] : $default['keys'][1];
		$retKey = isset($default['props']['meta']) ? 'props' : 'attrs';

		// Check premium features
		$isPremium = false;
		if( ! empty( $default['premium'] ) && ! $activated ) {
			if( ! $permission ) {

				if( ! empty( $raw['styles'][$phpKey] ) ) {
					unset( $ret['props']['styles'][$jsKey] );
				}

				continue;
			}

			$isPremium = true;
		}

		if( isset($default['props']['forceoutput']) ) {
			if( ! isset($raw[$phpKey]) ) {
				$ret[$retKey][$jsKey] = $default['value'];
			} else {
				$ret[$retKey][$jsKey] = $raw[$phpKey];
			}

		} elseif(isset($raw[$phpKey]) && isset($default['props']['output']) ) {
			$ret[$retKey][$jsKey] = $raw[$phpKey];

		} elseif(isset($raw[$phpKey]) && is_array($raw[$phpKey])) {
			$ret[$retKey][$jsKey] = $raw[$phpKey];

		} elseif(isset($raw[$phpKey]) && is_bool($default['value'])) {
			if($default['value'] == true && empty($raw[$phpKey])) {
				$ret[$retKey][$jsKey] = false;
			} elseif($default['value'] == false && !empty($raw[$phpKey])) {
				$ret[$retKey][$jsKey] = true;
			}

		} elseif(isset($raw[$phpKey])) {

			if(
				isset($default['props']['meta']) ||
				(
					(string)$default['value'] !== (string)$raw[$phpKey] &&
					(string)$raw[$phpKey] !== '')
				)
			{
				$raw[$phpKey] = isset($default['props']['raw']) ? addslashes($raw[$phpKey]) : $raw[$phpKey];
				$ret[$retKey][$jsKey] = stripslashes($raw[$phpKey]);
			}
		}

		$premiumStyle = false;
		if( $isPremium && ! empty( $raw['styles'][$phpKey] ) ) {
			if( (string)$default['value'] !== (string)$raw['styles'][$jsKey] ) {
				$premiumStyle = true;
			}
		}

		if( ! $activated && $isPremium && ( isset($ret[$retKey][$jsKey]) || ! empty( $premiumStyle ) ) ) {
			$feature = ! empty( $default['name'] ) ? $default['name'] : $jsKey;
			$GLOBALS['lsPremiumNotice'][ sanitize_title($feature) ] = $feature;
		}

	}

	return $ret;
}

function ls_array_to_attr($arr, $mode = '') {
	if(!empty($arr) && is_array($arr)) {
		$ret = array();
		foreach($arr as $key => $val) {
			if($mode == 'css' && is_numeric($val) ) {
				$ret[] = ''.$key.':'.layerslider_check_unit($val, $key).';';
			} elseif(is_bool($val)) {
				$bool = $val ? 'true' : 'false';
				$ret[] = "$key:$bool;";
			} else {
				$ret[] = "$key:$val;";
			}
		}
		return implode('', $ret);
	}
}

function layerslider_loaded() {
	if(has_action('layerslider_ready')) {
		do_action('layerslider_ready');
	}
}

?>


text:
<?php

namespace MjBiz\Bundle\GithubBundle\Github;

use Github\HttpClient\CachedHttpClient as Base;
use Guzzle\Http\ClientInterface;
use RuntimeException;

class CachedHttpClient extends Base
	{
	public function __construct(array $options = array(), ClientInterface $client = null)
		{
		parent::__construct($options, $client);
		if (key_exists('recheck', $options))
			{
			$this->recheck = $options['recheck'];
			}
		else
			{
			$this->recheck = 3600;
			}
		} // __construct()

	/**
	 * @return CacheInterface
	 */
	public function getCache()
	{
		if (null === $this->cache)
			{
			$this->cache = new FilesystemCache($this->options['cache_dir'] ?: sys_get_temp_dir().DIRECTORY_SEPARATOR.'php-github-api-cache');
			}
		return $this->cache;
	}

	public function request($path, $body = null, $httpMethod = 'GET', array $headers = array(), array $options = array())
		{
		// Do not throw a exception on 4xx and 5xx. We want to cache those too.
		$options['exceptions'] = false;

		$response = null;

		if ($httpMethod == 'GET' and $modifiedAt = $this->getCache()->getModifiedSince($path))
			{
			$now = time();
			if (($now - $modifiedAt) < ($this->recheck))
				{
				$response = $this->getCache()->get($path);
				}
			}

		if (is_null($response))
			{
			$response = parent::request($path, $body, $httpMethod, $headers, $options);
			touch($this->getCache()->touch($path));
			}

		if ($response->getStatusCode() >= 400)
			{
			throw new RuntimeException("{$path} returned {$response->getStatusCode()}");
			}

		return $response;
		}

	} // class CachedHttpClient