text:
module ApplicationHelper
	#def current_user
	#	@controller.current_user
	#	return nil if session[:current_user].nil?
	#	if session[:current_user].is_a?(Hash)
	#		session[:current_user] = session[:current_user]['id']
	#	end
	#	User.find(session[:current_user])
	#end
end


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.Cdn.Models
{
    /// <summary>
    /// The provisioning state of the resources.
    /// </summary>
    public enum PSProvisioningState
    {
        /// <summary>
        /// The resource is in creating state.
        /// </summary>
        Creating,

        /// <summary>
        /// The resource is created successfully.
        /// </summary>
        Succeeded,

        /// <summary>
        /// The resource creation failed.
        /// </summary>
        Failed
    }
}

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import json
import time
from easyzone import easyzone
import subprocess
import dns.resolver

# archlinux.clavator.com.	CAA	0 issue "letsencrypt.org"
# archlinux.clavator.com. CAA     0 issuewild ";"

def updateSoa(cbot_json):
  z = easyzone.zone_from_file(myDomain(cbot_json), myUnsignedRefFname(cbot_json, '.ref.soa'))
  print(z.root.soa.serial)
  z.save(autoserial=True)

def txtDomainLine(cbot_json):
  return "%s. 3600 IN TXT %s" % (cbot_json['txt_domain'], cbot_json['validation'])

def myDomain(cbot_json):
  splitted = cbot_json['domain'].split('.')
  if len(splitted) > 2 :
    return '.'.join(cbot_json['domain'].split('.')[1:])
  else:
    return cbot_json['domain']

def myDomainDir(cbot_json):
  return ''.join(['/etc/bind/zones.signed/', myDomain(cbot_json)])

def myUnsignedRefFname(cbot_json, ext = '.ref'):
  return '/'.join([myDomainDir(cbot_json), 'unsigned%s' % (ext)])

def myUnsignedRefFile(cbot_json):
  return [line.rstrip('\n') for line in open(myUnsignedRefFname(cbot_json))]

def updateTxtDomainLine(cbot_json, dnsList):
  domainFound = []
  txtFound = []
  out = []
  for idx, line in enumerate(dnsList):
    if line.startswith(cbot_json['txt_domain']):
      txtFound.append(idx)
    if line.startswith(cbot_json['domain']):
      domainFound.append(idx)
    out.append(line)
  print(domainFound)
  print(txtFound)
  for i in txtFound:
   del out[i]

  if len(domainFound) <= 0 :
   out.append(txtDomainLine(cbot_json))
  else:
   out.insert(domainFound[-1] + 1, txtDomainLine(cbot_json))
  return out

def cleanTxtDomainLine(cbot_json, dnsList):
  return list(filter(lambda x: not (x.startswith(cbot_json['txt_domain']) and x.endswith(cbot_json['validation'])), dnsList))

def signZone(cbot_json):
  zoneSaltFname = '/'.join([myDomainDir(cbot_json), 'zone.salt'])
  if not os.path.isfile(zoneSaltFname) :
    return
  wd = os.getcwd()
  os.chdir(myDomainDir(cbot_json))
  salt = [line.rstrip('\n') for line in open(zoneSaltFname)][0]
  cmds = ["/usr/sbin/dnssec-signzone",
                  "-u", "-S", "-A", "-3", salt, "-N", "INCREMENT",
                  "-o", myDomain(cbot_json), "-t", myUnsignedRefFname(cbot_json)]
  print(' '.join(cmds))
  subprocess.run(cmds, stderr=subprocess.STDOUT)
  os.chdir(wd)

def rndc(cbot_json, cmd):
  subprocess.run(["/usr/sbin/rndc", cmd, myDomain(cbot_json)], stderr=subprocess.STDOUT)

def swapFname(fname1, fname2):
  swapFname = '-'.join([fname1, 'swapFname'])
  os.rename(fname1, swapFname)
  os.rename(fname2, fname1)
  os.rename(swapFname, fname2)

def waitForDns(cbot_json):
  res = dns.resolver.Resolver()
  nss = res.query(myDomain(cbot_json), 'ns')
  nssList = []
  for ns in nss:
    print(ns.to_text())
    nslist = []
    for a in res.query(ns.to_text(), 'a'):
     nslist.append(a.address)
    for a in res.query(ns.to_text(), 'aaaa'):
     nslist.append(a.address)
    nssList.append(nslist)
  found = False
  while not found :
    founds = []
    for ns in nssList:
      res = dns.resolver.Resolver(configure=False)
      # print(ns)
      res.nameservers = ns
      try:
        print("%s:%s" % (cbot_json['txt_domain'], ns))
        txts = res.query(cbot_json['txt_domain'], 'txt')
        for txt in txts:
          for str in txt.strings:
            if str.decode() == cbot_json['validation'] :
              founds.append(txt)
      except dns.exception.DNSException as e:
        founds = founds
    found = len(founds) == len(nssList)
    if not found :
      print('retry found:%d/%d' % (len(founds), len(nssList)))
      time.sleep(1)

cbot_json=json.loads(os.environ['cbot_json'])
print(cbot_json['cmd'])
if cbot_json['cmd'] == 'perform_challenge' :
  # print(myUnsignedRefFile(cbot_json))
  print(txtDomainLine(cbot_json))
  updated = updateTxtDomainLine(cbot_json, myUnsignedRefFile(cbot_json))
  if not updated :
    print('updateTxtDomainLine failed')
    sys.exit(9)
  #print(updated);
  outfile = open(myUnsignedRefFname(cbot_json, '.ref.orig'), 'w')
  outfile.write("\n".join(updated + ["\n"]))
  outfile.close()
  swapFname(myUnsignedRefFname(cbot_json), myUnsignedRefFname(cbot_json, '.ref.orig'))
  rndc(cbot_json, 'thaw')
  rndc(cbot_json, 'freeze')
  updateSoa(cbot_json)
  signZone(cbot_json)
  rndc(cbot_json, 'thaw')
  waitForDns(cbot_json)
  sys.exit(0)

if cbot_json['cmd'] == 'wait_for_dns' :
  waitForDns(cbot_json)
  sys.exit(0)

if cbot_json['cmd'] == 'clean_challenge' :
  print(myUnsignedRefFname(cbot_json, '.le'))
  outfile = open(myUnsignedRefFname(cbot_json, '.ref.orig'), 'w')
  outfile.write("\n".join(cleanTxtDomainLine(cbot_json, myUnsignedRefFile(cbot_json))))
  outfile.close()
  swapFname(myUnsignedRefFname(cbot_json), myUnsignedRefFname(cbot_json, '.ref.orig'))
  rndc(cbot_json, 'thaw')
  rndc(cbot_json, 'freeze')
  updateSoa(cbot_json)
  signZone(cbot_json)
  rndc(cbot_json, 'thaw')
  waitForDns(cbot_json)
  sys.exit(0)

if cbot_json['cmd'] == 'cleanup' :
  sys.exit(0)

sys.exit(7)


text:
//
//  ThemisSwift-Bridging-Header.h
//  ThemisSwift
//
//  Created by Anastasi Voitova on 18.04.16.
//  Copyright © 2016 CossackLabs. All rights reserved.
//

#ifndef ThemisSwift_Bridging_Header_h
#define ThemisSwift_Bridging_Header_h

    #import <objcthemis/objcthemis.h>

    #define SECURE_COMPARATOR_ENABLED
    #import <objcthemis/scomparator.h>

#endif /* ThemisSwift_Bridging_Header_h */


text:
layout: default
ref: index
lang: es
---

be together. not the same.

welcome to android... be yourself. do your thing. see what's going on.

    <button id="main_category" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" style="margin-top: 5%;border-radius: 10px 10px 10px 10px">Comienza a aprender</button>

Aprende y Enseña

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

Categorias

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et

        <button class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect">
          school iniciar
        </button>

        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et

        <button class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect">
          school iniciar
        </button>

        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et

        <button class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect">
          school iniciar
        </button>

¿Expresar tus conocimientos?

email

no pierdas tiempo, avisame


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class syntaxhighlight.Style (Java Prettify)
</TITLE>

<META NAME="date" CONTENT="2013-04-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
syntaxhighlight.Style

Packages that use Style

syntaxhighlight

Uses of Style in syntaxhighlight

Fields in syntaxhighlight declared as Style

protected  Style
Theme.plain

          The default style.

Fields in syntaxhighlight with type parameters of type Style

protected  java.util.Map<java.lang.String,Style>
Theme.styles

          The styles of this theme.

Methods in syntaxhighlight that return Style

 Style
Theme.addStyle(java.lang.String styleKey,
         Style style)

          Add style.

 Style
Style.clone()

 Style
Theme.getPlain()

          Get the default style.

 Style
Theme.getStyle(java.lang.String key)

          Get the style by keyword.

 Style
Theme.removeStyle(java.lang.String styleKey)

          Remove style by keyword.

Methods in syntaxhighlight that return types with arguments of type Style

 java.util.Map<java.lang.String,Style>
Theme.getStyles()

          Get all styles.

Methods in syntaxhighlight with parameters of type Style

 Style
Theme.addStyle(java.lang.String styleKey,
         Style style)

          Add style.

 void
Theme.setPlain(Style plain)

          Set the default style.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
define([
    'elenajs/declare'
], function(declare) {

    var Commands = declare('Commands',null, {
        cache: {},
        register: function(commandClass) {
            var name = commandClass.declaredClass;
            if (!this.cache[name]) {
                this.cache[name] = commandClass;
            }
        },
        list: function () {
            return Object.keys(this.cache).sort();
        },
        get: function (name) {
            return this.cache[name];
        }
    });

    return new Commands();
});


text:
package scala.collection.mutable

import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

import scala.collection.mutable

@RunWith(classOf[JUnit4])
class TreeMapTest {

  @Test
  def rangeMkString() {

    val map = mutable.TreeMap[String, String]()

    List("a", "b", "c", "d").foreach(v => map.put(v, v))

    val range = map.range("b", "c")

    val valuesRange = range.values
    val keysRange = range.keys

    assertEquals(1, valuesRange.size)
    assertEquals(1, keysRange.size)

    assertEquals("b", valuesRange.mkString(","))
    assertEquals("b", keysRange.mkString(","))
    assertEquals("b -> b", range.mkString(","))

  }

}


text:
/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2005,2006,2007 INRIA
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
 */

#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/mobility-module.h"
#include "ns3/stats-module.h"
#include "ns3/wifi-module.h"

#include <iostream>

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("Main");

class Experiment
{
public:
  Experiment ();
  Experiment (std::string name);
  Gnuplot2dDataset Run (const WifiHelper &wifi, const YansWifiPhyHelper &wifiPhy,
                        const WifiMacHelper &wifiMac, const YansWifiChannelHelper &wifiChannel);
private:
  void ReceivePacket (Ptr<Socket> socket);
  void SetPosition (Ptr<Node> node, Vector position);
  Vector GetPosition (Ptr<Node> node);
  void AdvancePosition (Ptr<Node> node);
  Ptr<Socket> SetupPacketReceive (Ptr<Node> node);

  uint32_t m_bytesTotal;
  Gnuplot2dDataset m_output;
};

Experiment::Experiment ()
{
}

Experiment::Experiment (std::string name)
  : m_output (name)
{
  m_output.SetStyle (Gnuplot2dDataset::LINES);
}

void
Experiment::SetPosition (Ptr<Node> node, Vector position)
{
  Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
  mobility->SetPosition (position);
}

Vector
Experiment::GetPosition (Ptr<Node> node)
{
  Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
  return mobility->GetPosition ();
}

void
Experiment::AdvancePosition (Ptr<Node> node)
{
  Vector pos = GetPosition (node);
  double mbs = ((m_bytesTotal * 8.0) / 1000000);
  m_bytesTotal = 0;
  m_output.Add (pos.x, mbs);
  pos.x += 1.0;
  if (pos.x >= 210.0)
    {
      return;
    }
  SetPosition (node, pos);
  //std::cout << "x="<<pos.x << std::endl;
  Simulator::Schedule (Seconds (1.0), &Experiment::AdvancePosition, this, node);
}

void
Experiment::ReceivePacket (Ptr<Socket> socket)
{
  Ptr<Packet> packet;
  while ((packet = socket->Recv ()))
    {
      m_bytesTotal += packet->GetSize ();
    }
}

Ptr<Socket>
Experiment::SetupPacketReceive (Ptr<Node> node)
{
  TypeId tid = TypeId::LookupByName ("ns3::PacketSocketFactory");
  Ptr<Socket> sink = Socket::CreateSocket (node, tid);
  sink->Bind ();
  sink->SetRecvCallback (MakeCallback (&Experiment::ReceivePacket, this));
  return sink;
}

Gnuplot2dDataset
Experiment::Run (const WifiHelper &wifi, const YansWifiPhyHelper &wifiPhy,
                 const WifiMacHelper &wifiMac, const YansWifiChannelHelper &wifiChannel)
{
  m_bytesTotal = 0;

  NodeContainer c;
  c.Create (2);

  PacketSocketHelper packetSocket;
  packetSocket.Install (c);

  YansWifiPhyHelper phy = wifiPhy;
  phy.SetChannel (wifiChannel.Create ());

  WifiMacHelper mac = wifiMac;
  NetDeviceContainer devices = wifi.Install (phy, mac, c);

  MobilityHelper mobility;
  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
  positionAlloc->Add (Vector (5.0, 0.0, 0.0));
  mobility.SetPositionAllocator (positionAlloc);
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");

  mobility.Install (c);

  PacketSocketAddress socket;
  socket.SetSingleDevice (devices.Get (0)->GetIfIndex ());
  socket.SetPhysicalAddress (devices.Get (1)->GetAddress ());
  socket.SetProtocol (1);

  OnOffHelper onoff ("ns3::PacketSocketFactory", Address (socket));
  onoff.SetConstantRate (DataRate (60000000));
  onoff.SetAttribute ("PacketSize", UintegerValue (2000));

  ApplicationContainer apps = onoff.Install (c.Get (0));
  apps.Start (Seconds (0.5));
  apps.Stop (Seconds (250.0));

  Simulator::Schedule (Seconds (1.5), &Experiment::AdvancePosition, this, c.Get (1));
  Ptr<Socket> recvSink = SetupPacketReceive (c.Get (1));

  Simulator::Run ();

  Simulator::Destroy ();

  return m_output;
}

int main (int argc, char *argv[])
{
  // disable fragmentation
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));

  CommandLine cmd;
  cmd.Parse (argc, argv);

  Gnuplot gnuplot = Gnuplot ("reference-rates.png");

  Experiment experiment;
  WifiHelper wifi;
  wifi.SetStandard (WIFI_PHY_STANDARD_80211a);
  WifiMacHelper wifiMac;
  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
  Gnuplot2dDataset dataset;

  wifiMac.SetType ("ns3::AdhocWifiMac");

  NS_LOG_DEBUG ("54");
  experiment = Experiment ("54mb");
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue ("OfdmRate54Mbps"));
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("48");
  experiment = Experiment ("48mb");
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue ("OfdmRate48Mbps"));
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("36");
  experiment = Experiment ("36mb");
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue ("OfdmRate36Mbps"));
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("24");
  experiment = Experiment ("24mb");
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue ("OfdmRate24Mbps"));
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("18");
  experiment = Experiment ("18mb");
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue ("OfdmRate18Mbps"));
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("12");
  experiment = Experiment ("12mb");
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue ("OfdmRate12Mbps"));
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("9");
  experiment = Experiment ("9mb");
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue ("OfdmRate9Mbps"));
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("6");
  experiment = Experiment ("6mb");
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode", StringValue ("OfdmRate6Mbps"));
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  gnuplot.GenerateOutput (std::cout);

  gnuplot = Gnuplot ("rate-control.png");
  wifi.SetStandard (WIFI_PHY_STANDARD_holland);

  NS_LOG_DEBUG ("arf");
  experiment = Experiment ("arf");
  wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("aarf");
  experiment = Experiment ("aarf");
  wifi.SetRemoteStationManager ("ns3::AarfWifiManager");
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("aarf-cd");
  experiment = Experiment ("aarf-cd");
  wifi.SetRemoteStationManager ("ns3::AarfcdWifiManager");
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("cara");
  experiment = Experiment ("cara");
  wifi.SetRemoteStationManager ("ns3::CaraWifiManager");
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("rraa");
  experiment = Experiment ("rraa");
  wifi.SetRemoteStationManager ("ns3::RraaWifiManager");
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  NS_LOG_DEBUG ("ideal");
  experiment = Experiment ("ideal");
  wifi.SetRemoteStationManager ("ns3::IdealWifiManager");
  dataset = experiment.Run (wifi, wifiPhy, wifiMac, wifiChannel);
  gnuplot.AddDataset (dataset);

  gnuplot.GenerateOutput (std::cout);

  return 0;
}


text:
extern "C" {
#define VPX_CODEC_DISABLE_COMPAT 1
#include "third_party/libvpx/libvpx.h"
}

namespace remoting {

DecoderVp8::DecoderVp8()
    : state_(kUninitialized),
      codec_(NULL),
      last_image_(NULL),
      clip_rect_(SkIRect::MakeEmpty()),
      output_size_(SkISize::Make(0, 0)) {
}

DecoderVp8::~DecoderVp8() {
  if (codec_) {
    vpx_codec_err_t ret = vpx_codec_destroy(codec_);
    CHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec";
  }
  delete codec_;
}

void DecoderVp8::Initialize(scoped_refptr<media::VideoFrame> frame) {
  DCHECK_EQ(kUninitialized, state_);

  if (frame->format() != media::VideoFrame::RGB32) {
    LOG(INFO) << "DecoderVp8 only supports RGB32 as output";
    state_ = kError;
    return;
  }
  frame_ = frame;

  state_ = kReady;
}

Decoder::DecodeResult DecoderVp8::DecodePacket(const VideoPacket* packet) {
  DCHECK_EQ(kReady, state_);

  // Initialize the codec as needed.
  if (!codec_) {
    codec_ = new vpx_codec_ctx_t();

    // TODO(hclam): Scale the number of threads with number of cores of the
    // machine.
    vpx_codec_dec_cfg config;
    config.w = 0;
    config.h = 0;
    config.threads = 2;
    vpx_codec_err_t ret =
        vpx_codec_dec_init(
            codec_, vpx_codec_vp8_dx(), &config, 0);
    if (ret != VPX_CODEC_OK) {
      LOG(INFO) << "Cannot initialize codec.";
      delete codec_;
      codec_ = NULL;
      state_ = kError;
      return DECODE_ERROR;
    }
  }

  // Do the actual decoding.
  vpx_codec_err_t ret = vpx_codec_decode(
      codec_, reinterpret_cast<const uint8*>(packet->data().data()),
      packet->data().size(), NULL, 0);
  if (ret != VPX_CODEC_OK) {
    LOG(INFO) << "Decoding failed:" << vpx_codec_err_to_string(ret) << "\n"
              << "Details: " << vpx_codec_error(codec_) << "\n"
              << vpx_codec_error_detail(codec_);
    return DECODE_ERROR;
  }

  // Gets the decoded data.
  vpx_codec_iter_t iter = NULL;
  vpx_image_t* image = vpx_codec_get_frame(codec_, &iter);
  if (!image) {
    LOG(INFO) << "No video frame decoded";
    return DECODE_ERROR;
  }
  last_image_ = image;

  SkRegion region;
  for (int i = 0; i < packet->dirty_rects_size(); ++i) {
    Rect remoting_rect = packet->dirty_rects(i);
    SkIRect rect = SkIRect::MakeXYWH(remoting_rect.x(),
                                     remoting_rect.y(),
                                     remoting_rect.width(),
                                     remoting_rect.height());
    region.op(rect, SkRegion::kUnion_Op);
  }

  RefreshRegion(region);
  return DECODE_DONE;
}

void DecoderVp8::GetUpdatedRegion(SkRegion* region) {
  region->swap(updated_region_);
}

void DecoderVp8::Reset() {
  frame_ = NULL;
  state_ = kUninitialized;
}

bool DecoderVp8::IsReadyForData() {
  return state_ == kReady;
}

VideoPacketFormat::Encoding DecoderVp8::Encoding() {
  return VideoPacketFormat::ENCODING_VP8;
}

void DecoderVp8::SetOutputSize(const SkISize& size) {
  output_size_ = size;
}

void DecoderVp8::SetClipRect(const SkIRect& clip_rect) {
  clip_rect_ = clip_rect;
}

void DecoderVp8::RefreshRegion(const SkRegion& region) {
  // TODO(wez): Fix the rest of the decode pipeline not to assume the frame
  // size is the host dimensions, since it's not when scaling.  If the host
  // gets smaller, then the output size will be too big and we'll overrun the
  // frame, so currently we render 1:1 in that case; the app will see the
  // host size change and resize us if need be.
  if (output_size_.width() > static_cast<int>(frame_->width()))
    output_size_.set(frame_->width(), output_size_.height());
  if (output_size_.height() > static_cast<int>(frame_->height()))
    output_size_.set(output_size_.width(), frame_->height());

  if (!DoScaling()) {
    ConvertRegion(region, &updated_region_);
  } else {
    ScaleAndConvertRegion(region, &updated_region_);
  }
}

bool DecoderVp8::DoScaling() const {
  DCHECK(last_image_);
  return !output_size_.equals(last_image_->d_w, last_image_->d_h);
}

void DecoderVp8::ConvertRegion(const SkRegion& input_region,
                               SkRegion* output_region) {
  if (!last_image_)
    return;

  output_region->setEmpty();

  // Clip based on both the output dimensions and Pepper clip rect.
  // ConvertYUVToRGB32WithRect() requires even X and Y coordinates, so we align
  // |clip_rect| to prevent clipping from breaking alignment.  We then clamp it
  // to the image dimensions, which may lead to odd width & height, which we
  // can cope with.
  SkIRect clip_rect = AlignRect(clip_rect_);
  if (!clip_rect.intersect(SkIRect::MakeWH(last_image_->d_w, last_image_->d_h)))
    return;

  uint8* output_rgb_buf = frame_->data(media::VideoFrame::kRGBPlane);
  const int output_stride = frame_->stride(media::VideoFrame::kRGBPlane);

  for (SkRegion::Iterator i(input_region); !i.done(); i.next()) {
    // Align the rectangle so the top-left coordinates are even, for
    // ConvertYUVToRGB32WithRect().
    SkIRect dest_rect(AlignRect(i.rect()));

    // Clip the rectangle, preserving alignment since |clip_rect| is aligned.
    if (!dest_rect.intersect(clip_rect))
      continue;

    ConvertYUVToRGB32WithRect(last_image_->planes[0],
                              last_image_->planes[1],
                              last_image_->planes[2],
                              output_rgb_buf,
                              dest_rect,
                              last_image_->stride[0],
                              last_image_->stride[1],
                              output_stride);

    output_region->op(dest_rect, SkRegion::kUnion_Op);
  }
}

void DecoderVp8::ScaleAndConvertRegion(const SkRegion& input_region,
                                       SkRegion* output_region) {
  if (!last_image_)
    return;

  DCHECK(output_size_.width() <= static_cast<int>(frame_->width()));
  DCHECK(output_size_.height() <= static_cast<int>(frame_->height()));

  output_region->setEmpty();

  // Clip based on both the output dimensions and Pepper clip rect.
  SkIRect clip_rect = clip_rect_;
  if (!clip_rect.intersect(SkIRect::MakeSize(output_size_)))
    return;

  SkISize image_size = SkISize::Make(last_image_->d_w, last_image_->d_h);
  uint8* output_rgb_buf = frame_->data(media::VideoFrame::kRGBPlane);
  const int output_stride = frame_->stride(media::VideoFrame::kRGBPlane);

  for (SkRegion::Iterator i(input_region); !i.done(); i.next()) {
    // Determine the scaled area affected by this rectangle changing.
    SkIRect output_rect = ScaleRect(i.rect(), image_size, output_size_);
    if (!output_rect.intersect(clip_rect))
      continue;

    // The scaler will not to read outside the input dimensions.
    media::ScaleYUVToRGB32WithRect(last_image_->planes[0],
                                   last_image_->planes[1],
                                   last_image_->planes[2],
                                   output_rgb_buf,
                                   image_size.width(),
                                   image_size.height(),
                                   output_size_.width(),
                                   output_size_.height(),
                                   output_rect.x(),
                                   output_rect.y(),
                                   output_rect.right(),
                                   output_rect.bottom(),
                                   last_image_->stride[0],
                                   last_image_->stride[1],
                                   output_stride);

    output_region->op(output_rect, SkRegion::kUnion_Op);
  }
}

}  // namespace remoting


text:
<?php

namespace CodeGen\Frameworks\Apache2;

class DirectoryMatch
    extends \CodeGen\Frameworks\Apache2\DirectoryMatchDirectiveGroup
{

    public function setPattern($entry)
    {
        $this->pattern = $entry;
    }

    public function getPattern()
    {
        return $this->pattern;
    }

    public function setPath($entry)
    {
        $this->path = $entry;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function addOption($entry)
    {
        $this->options[] = $entry;
    }

    public function removeOption($entry)
    {
        $pos = array_search($entry, $this->options, true);
        if ($pos !== -1) {
            unset($this->options[$pos]);
            return true;
        }
        return false;
    }

    public function setOptions(array $entries)
    {
        $this->options = $entries;
    }

    public function getOptions()
    {
        return $this->options;
    }

    public function setAllowOverride($entry)
    {
        $this->allowOverride = $entry;
    }

    public function getAllowOverride()
    {
        return $this->allowOverride;
    }

    public function setRequire($entry)
    {
        $this->require = $entry;
    }

    public function getRequire()
    {
        return $this->require;
    }
}


text:
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Abp.EntityFramework;
using Abp.EntityFramework.Repositories;

namespace Abp.TestBase.SampleApplication.EntityFramework.Repositories
{
    public class SampleApplicationEfRepositoryBase<TEntity> : SampleApplicationEfRepositoryBase<TEntity, int>, IRepository<TEntity>
        where TEntity : class, IEntity<int>
    {
        public SampleApplicationEfRepositoryBase(IDbContextProvider<SampleApplicationDbContext> dbContextProvider)
            : base(dbContextProvider)
        {
        }
    }

    public class SampleApplicationEfRepositoryBase<TEntity, TPrimaryKey> : EfRepositoryBase<SampleApplicationDbContext, TEntity, TPrimaryKey>
    where TEntity : class, IEntity<TPrimaryKey>
    {
        public SampleApplicationEfRepositoryBase(IDbContextProvider<SampleApplicationDbContext> dbContextProvider)
            : base(dbContextProvider)
        {
        }
    }
}


text:
/**
 * This package contains the API for Dagger's assisted injection.
 *
 * TODO(bcorso): Link to dagger.dev documentation.
 */
package dagger.assisted;


text:
import unittest

from conans.client.generators.boostbuild import BoostBuildGenerator
from conans.model.settings import Settings
from conans.model.conan_file import ConanFile
from conans.model.build_info import CppInfo
from conans.model.ref import ConanFileReference
from conans.model.env_info import EnvValues

class BoostJamGeneratorTest(unittest.TestCase):

    def variables_setup_test(self):

        conanfile = ConanFile(None, None)
        conanfile.initialize(Settings({}), EnvValues())

        ref = ConanFileReference.loads("MyPkg/0.1@lasote/stables")
        cpp_info = CppInfo("dummy_root_folder1")
        cpp_info.defines = ["MYDEFINE1"]
        cpp_info.cflags.append("-Flag1=23")
        cpp_info.version = "1.3"
        cpp_info.description = "My cool description"
        cpp_info.libs = ["MyLib1"]

        conanfile.deps_cpp_info.update(cpp_info, ref.name)
        ref = ConanFileReference.loads("MyPkg2/0.1@lasote/stables")
        cpp_info = CppInfo("dummy_root_folder2")
        cpp_info.libs = ["MyLib2"]
        cpp_info.defines = ["MYDEFINE2"]
        cpp_info.version = "2.3"
        cpp_info.exelinkflags = ["-exelinkflag"]
        cpp_info.sharedlinkflags = ["-sharedlinkflag"]
        cpp_info.cppflags = ["-cppflag"]
        cpp_info.public_deps = ["MyPkg"]
        cpp_info.lib_paths.extend(["Path\\with\\slashes", "regular/path/to/dir"])
        cpp_info.include_paths.extend(["other\\Path\\with\\slashes", "other/regular/path/to/dir"])
        conanfile.deps_cpp_info.update(cpp_info, ref.name)
        generator = BoostBuildGenerator(conanfile)

        self.assertEquals(generator.content, """lib MyLib1 :
	: # requirements
	<name>MyLib1
	: # default-build
	: # usage-requirements
	<define>MYDEFINE1
	<cflags>-Flag1=23
	;

lib MyLib2 :
	: # requirements
	<name>MyLib2
	<search>Path/with/slashes
	<search>regular/path/to/dir
	: # default-build
	: # usage-requirements
	<define>MYDEFINE2
	<include>other/Path/with/slashes
	<include>other/regular/path/to/dir
	<cxxflags>-cppflag
	<ldflags>-sharedlinkflag
	;

alias conan-deps :
	MyLib1
	MyLib2
;
""")


text:
local utils = require "environ.utils"
local reg   = require "environ.win32.reg"
local core  = require "environ.core"

local function get_env_type(value)
  if nil ~= string.find(value, '%', 1, true) then
    return reg.EXPAND_SZ
  end
  return reg.SZ
end

---
-- Environment function
--
local PATHS = {
  user      = [[HKEY_CURRENT_USER\Environment]];
  sys       = [[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]];
  volatile  = [[HKEY_CURRENT_USER\Volatile Environment]];
}

local function get_raw_env(path, name)
  path = assert(PATHS[string.lower(path)])
  return reg.get_key(path, name)
end

local function set_raw_env(path, name, value, normalize)
  path = assert(PATHS[string.lower(path)])
  if value then
    if normalize then
      value = utils.normalize(value)
    end
    return reg.set_key(path, name, value, get_env_type(value))
  end
  return reg.del_key(path, name)
end

local function del_raw_env(path, name) -- luacheck: ignore
  path = assert(PATHS[string.lower(path)])
  return reg.del_key(path, name)
end

local function get_raw_env_t(path, upper)
  path = assert(PATHS[string.lower(path)])
  local t = reg.get_keys(path)
  local result = {}
  for k, v in pairs(t) do
    if upper then
      k = string.upper(k)
    end
    result[string.upper(k)] = v.value
  end
  return result
end

local function make_module(path)
  local setenv = function(key, value, normalize)
    return set_raw_env(path, key, value, normalize)
  end

  local getenv = function(key)
    return get_raw_env(path, key)
  end

  local environ = function(upper)
    return get_raw_env_t(path, upper)
  end

  local update = core.update_win or function() end

  local enum   = function () return next, environ() end

  local env = {
    environ     = environ;
    getenv      = getenv;
    setenv      = setenv;
    update      = update;
    enum        = enum;
  }

  env.ENV = utils.make_env_map(env)
  return env
end

return {
  make_module = make_module
}


text:
package at.jku.sea.cloud.stream.sink;

import at.jku.sea.cloud.stream.Context;

public class ChainedSink<T> implements Sink<T> {
  private Sink<T> downStream;

  @Override
  public void apply(Context c, T t) {
    downStream.apply(c, t);
  }

  public void setDownStreamSink(Sink<T> downStream) {
    this.downStream = downStream;
  }

  @Override
  public boolean isCancelled() {
    return downStream.isCancelled();
  }
}


text:
class HHChannelPopulation : public RungeKuttaEquation
{
public:
	HHChannelPopulation();
	HHChannelPopulation(double InitialVoltage_V, double Temperature_DegreesC);
	virtual void CalculateRates(double Voltage_V) = 0;
	virtual double GetCurrent_Amperes(void);
	void CalculateSteadyState(void);
	void SetCompartment(HHCompartment *theCompartment) {myCompartment = theCompartment;}

	double MaxConductance_Siemens;		// Set up by the derived class constructor
	double ReversalPotential_V;			// Set up by the derived class constructor
	double alpha, beta;					// Activation and inactivation rates
	double activation;					// Current conductance activation value (0..1)

	virtual double GetDerivative(double IntermediateY, double InstantaneousVoltage_V);

	void SetTemperature_DegreesC(double Temperature_DegreesC);
	inline double TemperatureFactor_2(void)   {return T2;}
	inline double TemperatureFactor_2_5(void) {return T2_5;}
	inline double TemperatureFactor_3(void)   {return T3;}
	inline double TemperatureFactor_10(void)  {return T10;}

protected:
	double Temperature_DegreesC;
	double T2, T2_5, T3, T10;
	HHCompartment *myCompartment;
};
#endif // _HH_CHANNEL_POPULATION_H_INCLUDED


text:
Pull requests and bug reports are welcomed!

### Want to help out?
Here are some ways you can help contribute. Gulp is used for build minification.

- Horizontal scrolling.
- Test coverage.
- Cool examples.
- Documentation.
- Browser testing.


text:
import { ImageAsset as ImageAssetDefinition, ImageAssetOptions } from '.';
import { Observable } from '../data/observable';
import { Screen } from '../platform';

export class ImageAssetBase extends Observable implements ImageAssetDefinition {
	private _options: ImageAssetOptions;
	private _nativeImage: any;

	ios: PHAsset;
	android: string;

	constructor() {
		super();
		this._options = { keepAspectRatio: true, autoScaleFactor: true };
	}

	get options(): ImageAssetOptions {
		return this._options;
	}

	set options(value: ImageAssetOptions) {
		this._options = value;
	}

	get nativeImage(): any {
		return this._nativeImage;
	}

	set nativeImage(value: any) {
		this._nativeImage = value;
	}

	public getImageAsync(callback: (image: any, error: Error) => void) {
		//
	}
}

export function getAspectSafeDimensions(sourceWidth, sourceHeight, reqWidth, reqHeight) {
	const widthCoef = sourceWidth / reqWidth;
	const heightCoef = sourceHeight / reqHeight;
	const aspectCoef = Math.min(widthCoef, heightCoef);

	return {
		width: Math.floor(sourceWidth / aspectCoef),
		height: Math.floor(sourceHeight / aspectCoef),
	};
}

export function getRequestedImageSize(src: { width: number; height: number }, options: ImageAssetOptions): { width: number; height: number } {
	let reqWidth = options.width || Math.min(src.width, Screen.mainScreen.widthPixels);
	let reqHeight = options.height || Math.min(src.height, Screen.mainScreen.heightPixels);

	if (options && options.keepAspectRatio) {
		const safeAspectSize = getAspectSafeDimensions(src.width, src.height, reqWidth, reqHeight);
		reqWidth = safeAspectSize.width;
		reqHeight = safeAspectSize.height;
	}

	return {
		width: reqWidth,
		height: reqHeight,
	};
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace WeeklyRobot.Service
{
    public sealed class ActionScheduler
    {
        private CancellationTokenSource token = null;

        public void Start(TimeSpan interval, Action action)
        {
            Start(interval, t =>
            {
                if (!t.IsCancellationRequested)
                {
                    action();
                }
            });
        }

        public void Start(TimeSpan interval, Action<CancellationToken> action)
        {
            Start(interval, t =>
            {
                action(t);
                return Task.FromResult(true);
            });
        }

        public void Start(TimeSpan interval, Func<Task> action)
        {
            Start(interval, t => t.IsCancellationRequested ? action() : Task.FromResult(true));
        }

        public void Start(TimeSpan interval, Func<CancellationToken, Task> action)
        {
            if (interval.TotalSeconds == 0)
            {
                throw new ArgumentException("interval must be > 0 seconds", "interval");
            }

            if (this.token != null)
            {
                throw new InvalidOperationException("Scheduler is already started.");
            }

            this.token = new CancellationTokenSource();

            RunScheduler(interval, action, this.token);
        }

        private static void RunScheduler(TimeSpan interval, Func<CancellationToken, Task> action, CancellationTokenSource token)
        {
            Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    try
                    {
                        await Task.Delay(interval, token.Token).ConfigureAwait(false);
                        try
                        {
                            await action(token.Token).ConfigureAwait(false);
                        }
                        catch (Exception x)
                        {
                            Logger.Error($"Error while executing action scheduler.\r\n{x.ToString()}");
                            SmtpHelper.SendMail("error", x.ToString());
                            token.Cancel();
                        }
                    }
                    catch (TaskCanceledException) { }
                }
            }, token.Token);
        }

        public void Stop()
        {
            if (token != null)
            {
                token.Cancel();
            }
        }

        public void Dispose()
        {
            if (token != null)
            {
                token.Cancel();
                token.Dispose();
            }
        }
    }
}


text:
package io.netty.handler.codec.smtp;

import io.netty.util.internal.UnstableApi;

import java.util.List;

/**
 * An SMTP request.
 */
@UnstableApi
public interface SmtpRequest {

    /**
     * Returns the {@link SmtpCommand} that belongs to the request.
     */
    SmtpCommand command();

    /**
     * Returns a {@link List} which holds all the parameters of a request, which may be an empty list.
     */
    List<CharSequence> parameters();
}


text:
data_dir = './data'

# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
import os
import pickle as pkl
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)

# ## Explore the Data
# ### MNIST
# As you're aware, the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset contains images of handwritten digits. You can view the first number of examples by changing `show_n_images`.

# In[2]:

show_n_images = 25

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
#get_ipython().magic('matplotlib inline')
import os
from glob import glob
from matplotlib import pyplot
import ipdb
from IPython import embed
pyplot.ion()

mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')

# ### CelebA
# The [CelebFaces Attributes Dataset (CelebA)](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset contains over 200,000 celebrity images with annotations.  Since you're going to be generating faces, you won't need the annotations.  You can view the first number of examples by changing `show_n_images`.

# In[3]:

show_n_images = 25

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))

# ## Preprocess the Data
# Since the project's main focus is on building the GANs, we'll preprocess the data for you.  The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images.  The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.
#
# The MNIST images are black and white images with a single [color channel](https://en.wikipedia.org/wiki/Channel_(digital_image%29) while the CelebA images have [3 color channels (RGB color channel)](https://en.wikipedia.org/wiki/Channel_(digital_image%29#RGB_Images).
# ## Build the Neural Network
# You'll build the components necessary to build a GANs by implementing the following functions below:
# - `model_inputs`
# - `discriminator`
# - `generator`
# - `model_loss`
# - `model_opt`
# - `train`
#
# ### Check the Version of TensorFlow and Access to GPU
# This will check to make sure you have the correct version of TensorFlow and access to a GPU

# In[4]:

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf

# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer.  You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))

# Check for a GPU
if not tf.test.gpu_device_name():
    warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))

# ### Input
# Implement the `model_inputs` function to create TF Placeholders for the Neural Network. It should create the following placeholders:
# - Real input images placeholder with rank 4 using `image_width`, `image_height`, and `image_channels`.
# - Z input placeholder with rank 2 using `z_dim`.
# - Learning rate placeholder with rank 0.
#
# Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)

# In[5]:

import problem_unittests as tests

def model_inputs(image_width, image_height, image_channels, z_dim):
    """
    Create the model inputs
    :param image_width: The input image width
    :param image_height: The input image height
    :param image_channels: The number of image channels
    :param z_dim: The dimension of Z
    :return: Tuple of (tensor of real input images, tensor of z data, learning rate)
    """
    # TODO: Implement Function
    real_input = tf.placeholder(tf.float32,shape=(None, image_width, image_height, image_channels),name='real_input')
    tensor_z = tf.placeholder(tf.float32, shape=(None,z_dim),name='random_z')
    learning_rate = tf.placeholder(tf.float32,name='lr')
    return real_input, tensor_z, learning_rate

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)

# ### Discriminator
# Implement `discriminator` to create a discriminator neural network that discriminates on `images`.  This function should be able to reuse the variabes in the neural network.  Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "discriminator" to allow the variables to be reused.  The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).

# In[6]:

def discriminator(images, reuse=False, is_train=True):
    """
    Create the discriminator network
    :param image: Tensor of input image(s)
    :param reuse: Boolean if the weights should be reused
    :return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
    """
    with tf.variable_scope('discriminator', reuse=reuse) as scope:
        # input is 28X28X3
        alpha = 0.2
        x = tf.layers.conv2d(images,32,(5,5),strides=(2,2), activation=None, padding='same')
        x = tf.maximum(alpha*x,x)
        # x is 14X14X32
        x = tf.layers.conv2d(x,64,(5,5),strides=(2,2), activation=None, padding='same')
        x = tf.layers.batch_normalization(x, training=is_train)
        x = tf.maximum(alpha*x,x)
        # x is 7X7X64
        x = tf.layers.conv2d(x,128,(5,5),strides=(2,2), activation=None, padding='same')
        x = tf.layers.batch_normalization(x, training=is_train)
        x = tf.maximum(alpha*x,x)
        # x is 4X4X128

        flat = tf.reshape(x, (-1, 4*4*128))
        logits = tf.layers.dense(flat,1)
        out = tf.nn.sigmoid(logits)
    return out, logits

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)

# ### Generator
# Implement `generator` to generate an image using `z`. This function should be able to reuse the variabes in the neural network.  Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x `out_channel_dim` images.

# In[7]:

def generator(z, out_channel_dim, is_train=True):
    """
    Create the generator network
    :param z: Input z
    :param out_channel_dim: The number of channels in the output image
    :param is_train: Boolean if generator is being used for training
    :return: The tensor output of the generator
    """
    alpha = 0.2
    in_channels = 512
    with tf.variable_scope('generator', reuse= (not is_train)) as scope:
        # TODO: Implement Function
        # z is a one dimensional random vector
        x = tf.layers.dense(z, 4*4*in_channels)
        x = tf.reshape(x,(-1, 4, 4, in_channels))
        x = tf.layers.batch_normalization(x, training=is_train, center=False, scale=False)
        x = tf.maximum(alpha*x, x)
        # 4*4*in_channels

        x = tf.layers.conv2d_transpose(x, int(in_channels/2), (5,5),(2,2),padding='same')
        x = tf.layers.batch_normalization(x, training=is_train, center=False, scale=False)
        x = tf.maximum(alpha*x, x)
        # 8*8*in_channels/2        - 512

        x1 = tf.slice(x,[0,1,1,0],[-1,-1,-1,-1])
        # 7*7*in_channels/2

        x1 = tf.layers.conv2d_transpose(x1,int(in_channels/4),(5,5),(2,2),padding='same')
        x1 = tf.layers.batch_normalization(x1, training=is_train, center=False, scale=False)
        x1 = tf.maximum(alpha*x1, x1)
        # 14*14*in_channels/2  - 256
        if in_channels>512:
            x1 = tf.layers.conv2d_transpose(x1,int(in_channels/8),(5,5),(2,2),padding='same')
            x1 = tf.layers.batch_normalization(x1, training=is_train, center=False, scale=False)
            x1 = tf.maximum(alpha*x1, x1)
            x1 = tf.layers.conv2d_transpose(x1, out_channel_dim,(5,5),(1,1),padding='same')
            # 28*28*in_channels/2  - 128
        else:
            x1 = tf.layers.conv2d_transpose(x1, out_channel_dim,(5,5),(2,2),padding='same')
            # 28X28* 128

        out = tf.tanh(x1)

    return out

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
#tests.test_generator(generator, tf)

# ### Loss
# Implement `model_loss` to build the GANs for training and calculate the loss.  The function should return a tuple of (discriminator loss, generator loss).  Use the following functions you implemented:
# - `discriminator(images, reuse=False)`
# - `generator(z, out_channel_dim, is_train=True)`

# In[8]:

def model_loss(input_real, input_z, out_channel_dim):
    """
    Get the loss for the discriminator and generator
    :param input_real: Images from the real dataset
    :param input_z: Z input
    :param out_channel_dim: The number of channels in the output image
    :return: A tuple of (discriminator loss, generator loss)
    """
    real_out, real_logits = discriminator(input_real, reuse=False)
    fake_image = generator(input_z, out_channel_dim, is_train=True)
    fake_out, fake_logits = discriminator(fake_image, reuse=True)
    smooth = 0.9
    d_real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = real_logits, labels = tf.ones_like(real_logits)*smooth))
    d_fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = fake_logits, labels = tf.zeros_like(fake_logits)))
    d_loss = d_real_loss + d_fake_loss

    g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = fake_logits, labels = tf.ones_like(fake_logits)))

    return d_loss, g_loss

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)

# ### Optimization
# Implement `model_opt` to create the optimization operations for the GANs. Use [`tf.trainable_variables`](https://www.tensorflow.org/api_docs/python/tf/trainable_variables) to get all the trainable variables.  Filter the variables with names that are in the discriminator and generator scope names.  The function should return a tuple of (discriminator training operation, generator training operation).

# In[9]:

def model_opt(d_loss, g_loss, learning_rate, beta1):
    """
    Get optimization operations
    :param d_loss: Discriminator loss Tensor
    :param g_loss: Generator loss Tensor
    :param learning_rate: Learning Rate Placeholder
    :param beta1: The exponential decay rate for the 1st moment in the optimizer
    :return: A tuple of (discriminator training operation, generator training operation)
    """
    # TODO: Implement Function
    t_vars = tf.trainable_variables()
    d_vars = [var for var in t_vars if var.name.startswith('discriminator')]
    g_vars = [var for var in t_vars if var.name.startswith('generator')]

    with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
        d_train_opt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(d_loss,var_list = d_vars)
        g_train_opt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(g_loss,var_list = g_vars)

    return d_train_opt, g_train_opt

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)

# ## Neural Network Training
# ### Show Output
# Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training.

# In[10]:

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np

def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
    """
    Show example output for the generator
    :param sess: TensorFlow session
    :param n_images: Number of Images to display
    :param input_z: Input Z Tensor
    :param out_channel_dim: The number of channels in the output image
    :param image_mode: The mode to use for images ("RGB" or "L")
    """
    cmap = None if image_mode == 'RGB' else 'gray'
    z_dim = input_z.get_shape().as_list()[-1]
    example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])

    samples = sess.run(
        generator(input_z, out_channel_dim, False),
        feed_dict={input_z: example_z})

    #ipdb.set_trace()
    images_grid = helper.images_square_grid(samples, image_mode)
    pyplot.imshow(images_grid, cmap=cmap)
    pyplot.show()
    return samples

# ### Train
# Implement `train` to build and train the GANs.  Use the following functions you implemented:
# - `model_inputs(image_width, image_height, image_channels, z_dim)`
# - `model_loss(input_real, input_z, out_channel_dim)`
# - `model_opt(d_loss, g_loss, learning_rate, beta1)`
#
# Use the `show_generator_output` to show `generator` output while you train. Running `show_generator_output` for every batch will drastically increase training time and increase the size of the notebook.  It's recommended to print the `generator` output every 100 batches.

# In[11]:

def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):
    """
    Train the GAN
    :param epoch_count: Number of epochs
    :param batch_size: Batch Size
    :param z_dim: Z dimension
    :param learning_rate: Learning Rate
    :param beta1: The exponential decay rate for the 1st moment in the optimizer
    :param get_batches: Function to get batches
    :param data_shape: Shape of the data
    :param data_image_mode: The image mode to use for images ("RGB" or "L")
    """
    # TODO: Build Model
    ckpt_dir = './checkpoint'
    if not os.path.exists(ckpt_dir):
        os.makedirs(ckpt_dir)

    show_every = 100 # show every 1000 iter
    num_train_examples = data_shape[0]
    image_width = data_shape[1]
    image_height = data_shape[2]
    image_channels = data_shape[3]
    sample_z = np.random.uniform(-1,1,size=(batch_size,z_dim))

    # defined the net here
    input_real, input_z, learning_rate_ph = model_inputs(image_width, image_height, image_channels,z_dim)
    d_loss, g_loss = model_loss(input_real, input_z, image_channels )
    d_train_opt, g_train_opt = model_opt(d_loss, g_loss, learning_rate_ph, beta1)

    saver = tf.train.Saver()
    counter = 0
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        #samples = sess.run(generator(input_z, image_channels, False), feed_dict={input_z:np.random.uniform(-1, 1, size=[batch_size, z_dim])})
        # images1 = next(get_batches(batch_size))
        # samples = sess.run(discriminator(input_real,True), feed_dict={input_real:images1})
        for epoch_i in range(epoch_count):
            generated_sample_list = []
            for iter, batch_images in enumerate(get_batches(batch_size)):
                batch_z = np.random.uniform(-1,1,size=(batch_size,z_dim))
                counter +=1
                # TODO: Train Model
                if iter % 5 == 0:
                    _, d_loss_val = sess.run([d_train_opt, d_loss],feed_dict =
                                             {input_real:batch_images,
                                              input_z: batch_z,
                                             learning_rate_ph:learning_rate})

                _, g_loss_val = sess.run([g_train_opt, g_loss],feed_dict={input_real:batch_images,
                                                  input_z: batch_z,
                                                  learning_rate_ph:learning_rate})
                if counter % 10 == 0:
                    print ('epoch:{} iter:{} counter:{} d_loss:{} g_loss:{}'.format(epoch_i, iter, counter, d_loss_val, g_loss_val))

                if show_every > 0 and counter % show_every == 0:
                    n_images = 16
                    generated_samples = show_generator_output(sess, n_images, input_z, image_channels, data_image_mode)
                    generated_sample_list.append((epoch_i, counter, generated_samples))

            ckpt = '{}/generator_epoch_{}.ckpt'.format(ckpt_dir,epoch_i)
            saver.save(sess, ckpt)
            with open('samples{}.pkl'.format(epoch_i), 'wb') as fp:
                pkl.dump(generated_sample_list,fp)

# ### MNIST
# Test your GANs architecture on MNIST.  After 2 epochs, the GANs should be able to generate images that look like handwritten digits.  Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.

# In[13]:

batch_size = 128
z_dim = 100
learning_rate = 0.0002
beta1 = 0.5

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
do_train = True
epochs = 2
mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
if do_train:
    with tf.Graph().as_default():
        train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
              mnist_dataset.shape, mnist_dataset.image_mode)

def inference(ckpt, batch_size, z_dim, get_batches, data_shape, data_image_mode):

    show_every = 1 # show every 1000 iter
    num_train_examples = data_shape[0]
    image_width = data_shape[1]
    image_height = data_shape[2]
    image_channels = data_shape[3]
    sample_z = np.random.uniform(-1,1,size=(batch_size,z_dim))
    generated_sample_list = []

    # defined the net here
    input_real, input_z, learning_rate_ph = model_inputs(image_width, image_height, image_channels,z_dim)
    d_loss, g_loss = model_loss(input_real, input_z, image_channels )
    d_train_opt, g_train_opt = model_opt(d_loss, g_loss, learning_rate_ph, beta1)

    saver = tf.train.Saver()
    counter = 0
    n_images = 10
    with tf.Session() as sess:
        saver.restore(sess, ckpt)
        print ('Model restored')
        generated_samples = show_generator_output(sess, n_images, input_z, image_channels, data_image_mode)
        generated_sample_list.append((0, counter, generated_samples))
        #ipdb.set_trace()

if not do_train:
    with tf.Graph().as_default():
        ckpt1 = './checkpoint/generator_epoch_0.ckpt'
        inference(ckpt1, batch_size, z_dim, mnist_dataset.get_batches, mnist_dataset.shape, mnist_dataset.image_mode)

if 0:
    # ### CelebA
    # Run your GANs on CelebA.  It will take around 20 minutes on the average GPU to run one epoch.  You can run the whole epoch or stop when it starts to generate realistic faces.

    # In[ ]:

    batch_size = None
    z_dim = None
    learning_rate = None
    beta1 = None

    """
    DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
    """
    epochs = 1

    celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
    with tf.Graph().as_default():
        train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
              celeba_dataset.shape, celeba_dataset.image_mode)

    # ### Submitting This Project
    # When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.


text:
package controllers;

import com.google.inject.Inject;
import exceptions.NoAppExistException;
import exceptions.NoProjectExistException;
import model.ProjectApiKey;
import play.libs.Json;
import play.mvc.Result;
import services.IProjectApiKeyService;

/**
 * Created by mitesh on 22/12/16.
 */
public class ProjectApiKeyController extends CoreController {
    @Inject
    IProjectApiKeyService projectApiKeyService;

    public Result get(String projectId, String envId) {
        ProjectApiKey projectApiKey = null;
        try {
            projectApiKey = this.projectApiKeyService.getByProjectId(projectId, envId);
        } catch (NoProjectExistException e) {
            return badRequest();
        }
        return ok(Json.toJson(projectApiKey));
    }
}


text:
package tokenizer

import (
	"bufio"
	"io"
	"os"
	"regexp"
	"strings"
)

type contraction struct {
	Regexp      *regexp.Regexp
	Replacement string
}

var wordWithoutLastPunct *regexp.Regexp = nil
var commonContractions []contraction = nil

// BagOfWordsTokenizer output a list of words suitable to be used to build a bag of words matrix.
//
// It uses a Treebank tokenizer internally but removes puncutation, and stopwords.
type BagOfWordsTokenizer struct {
	wordTokenizer Tokenizer
	stopWords     map[string]struct{}
	initalized    bool
}

func (t *BagOfWordsTokenizer) Tokenize(text string) []string {
	if !(*t).initalized {
		panic("BagOfWordsTokenizer: Initalize first by calling NewBagOfWordsTokenizer")
	}
	_text := t.preprocessing(text)

	words := (*t).wordTokenizer.Tokenize(_text)

	tokens := make([]string, 0, len(words))
	for _, word := range words {
		cleanWord := t.cleanupWord(word)
		if cleanWord != "" {
			tokens = append(tokens, cleanWord)
		}
	}
	return tokens
}

func (t *BagOfWordsTokenizer) init(pathToStopWords string) {
	f, err := os.Open(pathToStopWords)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	wordWithoutLastPunct = regexp.MustCompile(`^(\pL+)[^\pL]?$`)
	commonContractions = []contraction{
		contraction{regexp.MustCompile("can't"), "can not"},
		contraction{regexp.MustCompile("won't"), "will not"},
		contraction{regexp.MustCompile(`([^' ])('[sS]) `), "${1} is "},
		contraction{regexp.MustCompile(`([^' ])('[mM]) `), "${1} am "},
		contraction{regexp.MustCompile(`([^' ])('[dD]) `), "${1} had "},
	}
	(*t).stopWords = loadStopWords(f)
	(*t).wordTokenizer = NewTreebankWordTokenizer()
	(*t).initalized = true
}

func (t *BagOfWordsTokenizer) preprocessing(text string) string {
	_text := text
	for _, commonContraction := range commonContractions {
		_text = commonContraction.Regexp.ReplaceAllString(_text, commonContraction.Replacement)
	}
	return _text
}

func (t *BagOfWordsTokenizer) cleanupWord(word string) string {
	if !wordWithoutLastPunct.MatchString(word) {
		return ""
	}
	_word := wordWithoutLastPunct.ReplaceAllString(word, "${1}")
	_word = strings.ToLower(_word)
	if _, isStopWord := (*t).stopWords[_word]; isStopWord {
		return ""
	}
	return _word
}

func NewBagOfWordsTokenizer(pathToStopWords string) *BagOfWordsTokenizer {
	t := new(BagOfWordsTokenizer)
	t.init(pathToStopWords)
	return t
}

func loadStopWords(reader io.Reader) map[string]struct{} {
	stopWords := make(map[string]struct{})
	scanner := bufio.NewScanner(reader)
	for scanner.Scan() {
		stopWords[scanner.Text()] = struct{}{}
	}
	return stopWords
}


text:
FROM ubuntu:utopic

ENV DEBIAN_FRONTEND noninteractive

# Update apt sources contents
RUN sed 's/main$/main universe/' -i /etc/apt/sources.list && apt-get update

#Set fr_FR.UTF-8 as default locale
RUN locale-gen fr_FR.UTF-8 && dpkg-reconfigure locales
ENV LANGUAGE fr_FR.UTF-8
ENV LANG fr_FR.UTF-8
ENV LC_ALL fr_FR.UTF-8

# Prepare for OpenJDK 7
# Fake a fuse install -- required for openjdk-7
# from https://gist.github.com/henrik-muehe/6155333
RUN apt-get update && apt-get install libfuse2  && apt-get clean
RUN cd /tmp && mkdir fuseinst && cd fuseinst && apt-get download fuse && dpkg-deb -x fuse_* . && dpkg-deb -e fuse_* && rm fuse_*.deb && /bin/echo -en '#!/bin/bash\nexit 0\n' > DEBIAN/postinst && dpkg-deb -b . /fuse.deb && dpkg -i /fuse.deb && rm -rf /tmp/fuseinst && cd /

# Proceed with installations
RUN apt-get update && apt-get install -y apt-transport-https openjdk-7-jdk curl wget supervisor unzip rsync git ssh python-software-properties software-properties-common libaio1 && apt-get clean

# Run supervisord by default
CMD ["/usr/bin/supervisord", "--nodaemon", "--configuration=/etc/supervisor/supervisord.conf"]


text:
package org.openengsb.core.test;

import java.io.File;
import java.net.URL;

import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.junit.BeforeClass;

public abstract class AbstractOpenEngSBTest {

    private static final String LOG4J_PROPERTIES_LOCAL = "log4j.local.properties";

    @BeforeClass
    public static void adaptLoggerPreferences() throws Exception {
        URL log4jLocalFile = ClassLoader.getSystemResource(LOG4J_PROPERTIES_LOCAL);
        if (log4jLocalFile == null) {
            return;
        }
        if (new File(log4jLocalFile.toURI()).exists()) {
            LogManager.resetConfiguration();
            PropertyConfigurator.configure(log4jLocalFile);
        }
    }

    protected AbstractOpenEngSBTest() {
    }
}


text:
package net.cromulence.imgur.apiv3.endpoints;

import net.cromulence.imgur.apiv3.api.Imgur;
import net.cromulence.imgur.apiv3.api.exceptions.ApiRequestException;
import net.cromulence.imgur.apiv3.datamodel.Image;
import net.cromulence.imgur.apiv3.endpoints.params.ImageUploadDetails;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class ImageEndpoint extends AbstractEndpoint {

    private static final Logger LOG = LoggerFactory.getLogger(ImageEndpoint.class);

    private static final String ENDPOINT_NAME = "image";

    public ImageEndpoint(Imgur imgur) {
        super(imgur);
    }

    @Override
    public String getEndpointName() {
        return ENDPOINT_NAME;
    }

    public Image getImage(String imageId) throws ApiRequestException {
        String imageUrl = endpointUrlWithSinglePathParameter(imageId);

        return getImgur().http.typedGet(imageUrl, Image.class);
    }

    public Image uploadImage(ImageUploadDetails details) throws ApiRequestException {
        return uploadImage(details, true);
    }

    public Image uploadAnonymousImage(ImageUploadDetails details) throws ApiRequestException {
        return uploadImage(details, false);
    }

    private Image uploadImage(ImageUploadDetails details, boolean authenticated) throws ApiRequestException {

        ArrayList<NameValuePair> postParameters = new ArrayList<>();

        postParameters.add(new BasicNameValuePair("image", details.getImageData()));
        postParameters.add(new BasicNameValuePair("type", details.getUploadType()));

        if (details.getTitle() != null) {
            postParameters.add(new BasicNameValuePair("title", details.getTitle()));
        }

        if (details.getDescription() != null) {
            postParameters.add(new BasicNameValuePair("description", details.getDescription()));
        }

        if (details.getTitle() != null) {
            postParameters.add(new BasicNameValuePair("name", details.getName()));
        }

        return getImgur().http.typedPost(getEndpointUrl(), Image.class, postParameters, authenticated);
    }

    public void deleteImage(String imageId) throws ApiRequestException {
        String url = getEndpointUrl() + "/" + imageId;

        getImgur().http.delete(url, true);
    }

    public void deleteAnonymousImage(String deleteHash) throws ApiRequestException {
        String url = getEndpointUrl() + "/" + deleteHash;

        getImgur().http.delete(url, false);
    }

    public void updateImageInfo(String imageId, String title, String description) throws ApiRequestException {
        doUpdateImageInfo(imageId, title, description, true);
    }

    public void updateAnonymousImageInfo(String imageId, String title, String description) throws ApiRequestException {
        doUpdateImageInfo(imageId, title, description, false);
    }

    private void doUpdateImageInfo(String imageId, String title, String description, boolean authenticated) throws ApiRequestException {
        String url = endpointUrlWithSinglePathParameter(imageId);

        List<NameValuePair> postParameters = new ArrayList<>();

        postParameters.add(new BasicNameValuePair("title", title));
        postParameters.add(new BasicNameValuePair("description", description));

        getImgur().http.post(url, postParameters, authenticated);
    }

    public void favoriteImage(String imageId) throws ApiRequestException {
        favoriteImage(imageId, true);
    }

    public void unfavoriteImage(String imageId) throws ApiRequestException {
        favoriteImage(imageId, false);
    }

    private void favoriteImage(String imageId, boolean favourite) throws ApiRequestException {
        final String url = String.format("%s/%s/favorite", getEndpointUrl(), imageId);

        if(favourite) {
            getImgur().http.post(url);
        } else {
            getImgur().http.delete(url);
        }

    }
}


text:
<?php

namespace App\Transformer;

class Serializer
{
    public static function serialize($data) {
        return array_map(function ($datum) {
            return str_replace(' ', '_', $datum);
        }, $data);
    }

    public static function deserialize($data) {
        return array_map(function ($datum) {
            return str_replace('_', ' ', $datum);
        }, $data);
    }
}


text:
using namespace onnxruntime::cuda;
using namespace ::onnxruntime::common;
using namespace ONNX_NAMESPACE;

namespace onnxruntime {
namespace contrib {
namespace cuda {

#define REGISTER_KERNEL_TYPED(T)                                  \
  ONNX_OPERATOR_TYPED_KERNEL_EX(                                  \
      LongformerAttention,                                        \
      kMSDomain,                                                  \
      1,                                                          \
      T,                                                          \
      kCudaExecutionProvider,                                     \
      (*KernelDefBuilder::Create())                               \
          .TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
      LongformerAttention<T>);

REGISTER_KERNEL_TYPED(float)
REGISTER_KERNEL_TYPED(MLFloat16)

template <typename T>
LongformerAttention<T>::LongformerAttention(const OpKernelInfo& info)
    : CudaKernel(info), LongformerAttentionBase(info) {
  use_compact_memory_ = ParseEnvironmentVariableWithDefault<bool>(longformer::kUseCompactMemory, true);
  use_half4_ = ParseEnvironmentVariableWithDefault<bool>(longformer::kUseHalf4, true);
}

template <typename T>
Status LongformerAttention<T>::ComputeInternal(OpKernelContext* context) const {
  const Tensor* input = context->Input<Tensor>(0);
  const Tensor* weights = context->Input<Tensor>(1);
  const Tensor* bias = context->Input<Tensor>(2);
  const Tensor* attention_mask = context->Input<Tensor>(3);
  const Tensor* global_weights = context->Input<Tensor>(4);
  const Tensor* global_bias = context->Input<Tensor>(5);
  const Tensor* global_attention_mask = context->Input<Tensor>(6);
  ORT_RETURN_IF_ERROR(CheckInputs(input->Shape(), weights->Shape(), bias->Shape(), attention_mask->Shape(),
                                  global_weights->Shape(), global_bias->Shape(), global_attention_mask->Shape()));
  // Input shapes:
  //   input                 : (batch_size, sequence_length, hidden_size)
  //   weights               : (hidden_size, 3 * hidden_size) -- format 1
  //                           (3, hidden_size, hidden_size)  -- format 0
  //   bias                  : (3 * hidden_size)              -- format 1 (bias for Q, K, V)
  //                           (5 * hidden_size)              -- format 0 (bias for Q, K, V, Global_K, Global_V)
  //   attention_mask        : (batch_size, sequence_length)
  //   global_weights        : (hidden_size, 3 * hidden_size) -- format 1
  //                           (3, hidden_size, hidden_size)  -- format 0
  //   global_bias           : (3 * hidden_size)              -- format 1 (bias for Global_Q, Global_K, Global_V)
  //                           (1 * hidden_size)              -- format 0 (bias for Global_Q)
  //   global_attention_mask : (batch_size, sequence_length)
  // Output shapes:
  //   output         : (batch_size, sequence_length, hidden_size)

  const auto& shape = input->Shape();
  int batch_size = static_cast<int>(shape[0]);
  int sequence_length = static_cast<int>(shape[1]);
  int hidden_size = static_cast<int>(shape[2]);
  int head_size = hidden_size / num_heads_;

  Tensor* output = context->Output(0, shape);

  cublasHandle_t cublas = CublasHandle();
  cudaStream_t stream = Stream();
  CUBLAS_RETURN_IF_ERROR(cublasSetStream(cublas, stream));

  constexpr size_t element_size = sizeof(T);

  // TODO(tianleiwu): only calculate global index once per model instead of once per LongformerAttention node.
  // Build Global Index
  auto global_index_buffer = GetScratchBuffer<int>(static_cast<size_t>(batch_size) * sequence_length);
  auto batch_global_num_buffer = GetScratchBuffer<int>(batch_size);

  size_t global_scratch_bytes = GetGlobalScratchSize(sequence_length);
  auto global_scratch_buffer = GetScratchBuffer<void>(global_scratch_bytes);

  auto& device_prop = GetDeviceProp();
  ORT_RETURN_IF_ERROR(BuildGlobalIndex(
      device_prop,
      stream,
      global_attention_mask->Data<int>(),
      batch_size,
      sequence_length,
      global_index_buffer.get(),
      batch_global_num_buffer.get(),
      global_scratch_buffer.get(),
      global_scratch_bytes));

  // Copy batch_global_num to CPU
  size_t pinned_buffer_bytes = GetPinnedBufferSize(batch_size);
  auto pinned_buffer = AllocateBufferOnCPUPinned<void>(pinned_buffer_bytes);
  int* batch_global_num_pinned = reinterpret_cast<int*>(pinned_buffer.get());
  CUDA_RETURN_IF_ERROR(cudaMemcpyAsync(batch_global_num_pinned,
                                       batch_global_num_buffer.get(),
                                       batch_size * sizeof(int),
                                       cudaMemcpyDeviceToHost,
                                       stream));

  // Create an event to make sure the async copy is finished before reading the data.
  AutoDestoryCudaEvent new_event;
  cudaEvent_t& is_copy_done = new_event.Get();

  CUDA_RETURN_IF_ERROR(cudaEventCreateWithFlags(&is_copy_done, cudaEventDisableTiming));
  CUDA_RETURN_IF_ERROR(cudaEventRecord(is_copy_done, stream));

  size_t qkv_size = batch_size * sequence_length * 3 * hidden_size * element_size;
  // Buffer for GEMM outputs of q, k, v, global_q, global_k and global_v
  // TODO(tianleiwu): compact global_q only need batch_size * window * hidden_size * element_size buffer size.
  auto gemm_buffer = GetScratchBuffer<void>(qkv_size + qkv_size);

  bool use_merged_qkv_weights = (weights->Shape().NumDimensions() == 2);

  int m = batch_size * sequence_length;
  int n = use_merged_qkv_weights ? 3 * hidden_size : hidden_size;
  int k = hidden_size;
  typedef typename ToCudaType<T>::MappedType CudaT;
  const CudaT* input_data = reinterpret_cast<const CudaT*>(input->Data<T>());
  const CudaT* weights_data = reinterpret_cast<const CudaT*>(weights->Data<T>());
  const CudaT* global_weights_data = reinterpret_cast<const CudaT*>(global_weights->Data<T>());

  float one = 1.0f;
  float zero = 0.0f;
  if (use_merged_qkv_weights) {
    // Gemm, note that CUDA assumes col-major, so result(N, M) = 1 * weights x input + 0 x B.
    CUBLAS_RETURN_IF_ERROR(cublasGemmHelper(
        cublas, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &one,
        weights_data, n,
        input_data, k,
        &zero, reinterpret_cast<CudaT*>(gemm_buffer.get()), n, device_prop));
  } else {
    // q
    const CudaT* q_weight = weights_data;
    CudaT* q_data = reinterpret_cast<CudaT*>(gemm_buffer.get());
    CUBLAS_RETURN_IF_ERROR(cublasGemmHelper(
        cublas, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &one,
        q_weight, n,
        input_data, k,
        &zero, q_data, n, device_prop));

    // k
    const CudaT* k_weight = q_weight + hidden_size * hidden_size;
    CudaT* k_data = q_data + batch_size * sequence_length * hidden_size;
    CUBLAS_RETURN_IF_ERROR(cublasGemmHelper(
        cublas, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &one,
        k_weight, n,
        input_data, k,
        &zero, k_data, n, device_prop));

    // v
    const CudaT* v_weight = k_weight + hidden_size * hidden_size;
    CudaT* v_data = k_data + batch_size * sequence_length * hidden_size;
    CUBLAS_RETURN_IF_ERROR(cublasGemmHelper(
        cublas, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &one,
        v_weight, n,
        input_data, k,
        &zero, v_data, n, device_prop));
  }

  // Wait for async copy of batch_global_num
  CUDA_RETURN_IF_ERROR(cudaEventSynchronize(is_copy_done));

  // Find the maximum number of global tokens in all batches
  int max_num_global = 0;
  for (int i = 0; i < batch_size; ++i) {
    if (max_num_global < batch_global_num_pinned[i]) {
      max_num_global = batch_global_num_pinned[i];
    }
  }

  // Do not use compact memory kernel in the following situations:
  // (1) global tokens > windows size, compact memory kernel cannot be used due to its assumptions.
  // (2) sequence_length == 2 * attention_window, compact memory kernel has parity issue.
  // (3) user sets environment variable ORT_LONGFORMER_COMPACT_MEMORY=0
  bool disable_compact_memory = (max_num_global > window_ || sequence_length == 2 * window_ || !use_compact_memory_);

  // Fully connection for global projection.
  // Note that Q only need handle global query tokens if we split GEMM to global Q/K/V separately.
  // When there is no global token, need not run global GEMM.
  CudaT* global_gemm_buffer = nullptr;

  if (max_num_global > 0) {
    global_gemm_buffer = reinterpret_cast<CudaT*>(reinterpret_cast<char*>(gemm_buffer.get()) + qkv_size);

    if (use_merged_qkv_weights) {
      CUBLAS_RETURN_IF_ERROR(cublasGemmHelper(
          cublas, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &one,
          reinterpret_cast<const CudaT*>(global_weights->Data<T>()), n,
          input_data, k,
          &zero, global_gemm_buffer, n, device_prop));
    } else {
      // global q
      const CudaT* global_q_weight = global_weights_data;
      CudaT* global_q = global_gemm_buffer + 2 * batch_size * sequence_length * hidden_size;
      if (disable_compact_memory) {
        CUBLAS_RETURN_IF_ERROR(cublasGemmHelper(
            cublas, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &one,
            global_q_weight, n,
            input_data, k,
            &zero, global_q, n, device_prop));
      } else {
        CUBLAS_RETURN_IF_ERROR(cublasGemmStridedBatchedHelper(cublas,
                                                              CUBLAS_OP_N,
                                                              CUBLAS_OP_N,
                                                              hidden_size,                    // m
                                                              max_num_global,                 // n
                                                              hidden_size,                    // k
                                                              &one,                           // alpha
                                                              global_q_weight,                // A
                                                              hidden_size,                    // lda
                                                              0,                              // strideA
                                                              input_data,                     // B
                                                              hidden_size,                    // ldb
                                                              sequence_length * hidden_size,  // strideB
                                                              &zero,                          // beta
                                                              global_q,                       // C
                                                              hidden_size,                    // ldc
                                                              max_num_global * hidden_size,   // strideC
                                                              batch_size,                     // batch count
                                                              device_prop));
      }
      // global k
      const CudaT* global_k_weight = global_weights_data + hidden_size * hidden_size;
      CudaT* global_k = global_gemm_buffer;
      CUBLAS_RETURN_IF_ERROR(cublasGemmHelper(
          cublas, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &one,
          global_k_weight, n,
          input_data, k,
          &zero, global_k, n, device_prop));

      // global v
      const CudaT* global_v_weight = global_k_weight + hidden_size * hidden_size;
      CudaT* global_v = global_gemm_buffer + batch_size * sequence_length * hidden_size;
      CUBLAS_RETURN_IF_ERROR(cublasGemmHelper(
          cublas, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &one,
          global_v_weight, n,
          input_data, k,
          &zero, global_v, n, device_prop));
    }
  }

  size_t workSpaceSize = GetLongformerAttentionWorkspaceSize(element_size,
                                                             batch_size,
                                                             num_heads_,
                                                             head_size,
                                                             sequence_length,
                                                             max_num_global,
                                                             window_,
                                                             disable_compact_memory);
  auto workspace_buffer = GetScratchBuffer<void>(workSpaceSize);
  ORT_RETURN_IF_ERROR(LaunchLongformerAttentionKernel(
          device_prop,
          cublas,
          stream,
          reinterpret_cast<const CudaT*>(gemm_buffer.get()),
          reinterpret_cast<const CudaT*>(bias->Data<T>()),
          reinterpret_cast<const CudaT*>(attention_mask->Data<T>()),
          reinterpret_cast<const CudaT*>(global_gemm_buffer),
          reinterpret_cast<const CudaT*>(global_bias->Data<T>()),
          global_attention_mask->Data<int>(),
          global_index_buffer.get(),
          batch_global_num_buffer.get(),
          pinned_buffer.get(),
          workspace_buffer.get(),
          output->MutableData<T>(),
          batch_size,
          sequence_length,
          num_heads_,
          head_size,
          window_,
          max_num_global,
          element_size,
          disable_compact_memory,
          use_merged_qkv_weights,
          use_half4_));

  // Defer release of pinned memory since cudaStreamSynchronize is not used here and kernel need access the buffer.
  this->AddDeferredReleaseCPUPtr(pinned_buffer.release());

  return Status::OK();
}

}  // namespace cuda
}  // namespace contrib
}  // namespace onnxruntime


text: import _ from "jquery-validation-unobtrusive"


text:
'use strict';

// MODULES //

var isNumber = require( '@stdlib/assert/is-number' ).isObject;
var NINF = require( '@stdlib/constants/float64/ninf' );

// MAIN //

/**
* Tests if a value is a number object having a value equal to negative zero.
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if a value is a number object having a value equal to negative zero
*
* @example
* var bool = isNegativeZero( -0.0 );
* // returns false
*
* @example
* var bool = isNegativeZero( new Number( -0.0 ) );
* // returns true
*/
function isNegativeZero( value ) {
	return (
		isNumber( value ) &&
		( 1.0 / value.valueOf() ) === NINF
	);
}

// EXPORTS //

module.exports = isNegativeZero;


text:
package de.philworld.bukkit.compassex;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.kitteh.vanish.VanishManager;
import org.kitteh.vanish.VanishPlugin;

public class VanishHelper {

	public static VanishHelper get() {
		try {
			VanishPlugin plugin = (VanishPlugin) Bukkit.getServer().getPluginManager().getPlugin("VanishNoPacket");
			if (plugin == null)
				return null;
			return new VanishHelper(plugin);
		} catch (NoClassDefFoundError e) {
			return null;
		}
	}

	private final VanishManager vanish;

	private VanishHelper(VanishPlugin plugin) {
		this.vanish = plugin.getManager();
	}

	public boolean isVanished(Player p) {
		return vanish.isVanished(p);
	}

}