text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using Friendly.Core;

namespace Friendly.UWP.Inside
{
    class FriendlyOperationServer
    {
        string _uri;
        Task _loop;
        Exception _loopException;
        HttpListener _listener;
        Stack<ProtocolInfo> _stackProtocol = new Stack<ProtocolInfo>();
        ProtocolSerializer _serializer;

        class ProtocolAndRet
        {
            internal ProtocolInfo Info { get; set; }
            internal ReturnInfo Ret { get; set; }
        }
        List<ProtocolAndRet> _ret = new List<ProtocolAndRet>();

        internal void StartLoop(string uri)
        {
            _uri = uri;
            _loop = Task.Factory.StartNew(Loop);
        }

        internal ReturnInfo SendAndReceive(ProtocolInfo info)
        {
            lock(_stackProtocol)
            {
                _stackProtocol.Push(info);
            }

            while (true)
            {
                lock(_ret)
                {
                    var ret = _ret.Where(e => ReferenceEquals(e.Info, info)).FirstOrDefault();
                    if (ret != null)
                    {
                        _ret.Remove(ret);
                        return ret.Ret;
                    }
                    if (_loopException != null)
                    {
                        throw _loopException;
                    }
                }
            }
        }

        internal void Stop()
        {
            _listener.Abort();
            _loop.Wait();
        }

        void Loop()
        {
            try
            {
                _serializer = new ProtocolSerializer();
                LoopCore();
            }
            catch (Exception e)
            {
                _loopException = e;
            }
        }

        void LoopCore()
        {
            _listener = new HttpListener();
            _listener.Prefixes.Add(_uri);
            _listener.Start();

            while (true)
            {
                ProtocolInfo info = WaitRequest();
                if (info == null)
                {
                    continue;
                }
                var obj = GetReturnInfo();
                lock (_ret)
                {
                    _ret.Add(new ProtocolAndRet() { Info = info, Ret = obj });
                }
            }
        }

        ProtocolInfo WaitRequest()
        {
            var context = _listener.GetContext();
            using (var response = context.Response)
            {
                ProtocolInfo info = null;
                lock (_stackProtocol)
                {
                    if (_stackProtocol.Count == 0)
                    {
                        return null;
                    }
                    info = _stackProtocol.Pop();
                }

                var reader = new StreamReader(context.Request.InputStream);
                var requestString = reader.ReadToEnd();
                if (!string.IsNullOrEmpty(requestString))
                {
                    return null;
                }

                var bin = _serializer.WriteObject(info);
                response.OutputStream.Write(bin, 0, bin.Length);
                return info;
            }
        }

        ReturnInfo GetReturnInfo()
        {
            var context = _listener.GetContext();
            using (var response = context.Response)
            {
                var reader = new StreamReader(context.Request.InputStream);
                var requestString = reader.ReadToEnd();
                return (ReturnInfo)_serializer.ReadObject(Encoding.UTF8.GetBytes(requestString));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
| Command | Arguments | Description |
|---------|-----------|-------------|
| vote | issue_id, y/n | Add vote transaction on the given issue. |

### tests

| Name | Assertions | Description |
|------|------------|-------------|
| vote_y | yes vote entered against real issue | Create a valid issue then vote on it. |
| vote_n | no vote entered against real issue | Create a valid issue then vote on it. |
| vote_no_issue | warn, no action | vote entered against invalid issue |


text:
template<typename... CallbackArgs>
class Event {
public:
    typedef std::function<void(CallbackArgs...)> Callback;

    inline void trigger(CallbackArgs... args) const {
        if (!m_callbacks.size()) {
            return;
        }
        auto it = m_callbacks.begin();
        for (; it != m_callbacks.end(); it++) {
            (*it)(args...);
        }
    }
    inline void push(Callback fn) {
        m_callbacks.push_back(fn);
    }

private:
    std::vector<Callback> m_callbacks;
};

#endif // EVENTS_H


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Kabkota extends CI_Controller {
  //CONSTRUCT FOR LOGIN
  function __construct(){
    parent::__construct();
    //CALL LIBRARY
    $this->load->database();
    $this->load->dbforge();
    $this->load->library(array('PHPExcel','PHPExcel/IOFactory'));
    define('TABLE','kabkota');
  }

  //INDEX FOR FIRST VIEW
	public function Index(){
    //PUT YOUR FIELD HERE
    $fields = array(
      'parent_id' => array(
              'type' => 'VARCHAR',
              'constraint' => '5',
      ),
      'id_kabkota' => array(
              'type' => 'VARCHAR',
              'constraint' => '5',
      ),
      'kabkota' => array(
              'type' => 'VARCHAR',
              'constraint' => '150',
      ),
      'deleted' =>array(
              'type' => 'TINYINT',
              'default' => '0'
      )
    );
    //COMPILE FOR CREATE TABLE
    $this->dbforge->add_field('id');
    $this->dbforge->add_field($fields);
    $this->dbforge->create_table(TABLE);
    echo('Compile for create table '.TABLE.' success');
	}

  public function Drop(){
    //COMPILE FOR DROP TABLE
    $this->dbforge->drop_table(TABLE);
    echo('Compile for drop table '.TABLE.' success');
  }

  public function Insert()
  {
    if($this->input->post('Import'))
    {
      //FOR UPLOAD
      $fileName = $_FILES['fileimport']['name'];
      //FOR UPLOAD
      $config['upload_path'] = BASEPATH.'../includes/assets/';
      $config['file_name'] = $fileName;
      $config['allowed_types'] = 'csv';
      $config['max_size'] = 1000000;

      $this->load->library('upload');
      $this->upload->initialize($config);

      if(!$this->upload->do_upload('fileimport')){
        $error = $this->upload->display_errors();
        echo $error; exit;
      }
      //FOR READ
      $inputFileName = BASEPATH.'../includes/assets/'.$fileName;

      //READ your excel workbook
      try {
        $inputFileType = IOFactory::identify($inputFileName);
        $objReader = IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
      } catch(Exception $e) {
        die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
      }

      //Get Worksheet dimendions
      $sheet = $objPHPExcel->getSheet(0);
      $highestRow = $sheet->getHighestRow();
      $highestColumn = $sheet->getHighestColumn();
      //Loop through each row of thw Worksheet in turn
      for($row = 1; $row <= $highestRow; $row++)//Read a row of data into an array
      {
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);

        //iNSERT ROW DATA ARRAY INTO YOUR DATABASE OF CHOISE HERE
        $data_upload = array(
          'parent_id'=>$rowData[0][0],
          'id_kabkota'=>$rowData[0][1],
          'kabkota'=>$rowData[0][2],
        );
        $this->db->insert(TABLE,$data_upload);
      }
      echo 'Compile for insert to table '.TABLE.' success';
    }else{
      $view_data['controller'] = 'kabkota';
      $view_data['table'] = TABLE;
      $view_data['body'] = 'compiler/import';
      $this->load->view('compiler/wrapper',$view_data);
    }
  }

}


text:
<?php

namespace FDevs\MoscowOpenData\Model;

class DataType
{
    use GenericPropertiesTrait;

    /**
     * Unique identifier
     *
     * @var int
     */
    private $id;

    /**
     * Theme category id
     *
     * @var int
     */
    private $categoryId;

    /**
     * @var string
     */
    private $categoryCaption;

    /**
     * Responsible for data department identifier
     *
     * @var int
     */
    private $departmentId;

    /**
     * @var string
     */
    private $departmentCaption;

    /**
     * Title of data type
     *
     * @var string
     */
    private $caption;

    /**
     * @var string
     */
    private $description;

    /**
     * @var bool
     */
    private $hasGeodata;

    /**
     * @param string $caption
     * @return self
     */
    public function setCaption($caption)
    {
        $this->caption = $caption;

        return $this;
    }

    /**
     * @return string
     */
    public function getCaption()
    {
        return $this->caption;
    }

    /**
     * @param int $categoryId
     * @return self
     */
    public function setCategoryId($categoryId)
    {
        $this->categoryId = $categoryId;

        return $this;
    }

    /**
     * @return int
     */
    public function getCategoryId()
    {
        return $this->categoryId;
    }

    /**
     * @param int $departmentId
     * @return self
     */
    public function setDepartmentId($departmentId)
    {
        $this->departmentId = $departmentId;

        return $this;
    }

    /**
     * @return int
     */
    public function getDepartmentId()
    {
        return $this->departmentId;
    }

    /**
     * @param int $id
     * @return self
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $categoryCaption
     * @return self
     */
    public function setCategoryCaption($categoryCaption)
    {
        $this->categoryCaption = $categoryCaption;

        return $this;
    }

    /**
     * @return string
     */
    public function getCategoryCaption()
    {
        return $this->categoryCaption;
    }

    /**
     * @param string $departmentCaption
     * @return self
     */
    public function setDepartmentCaption($departmentCaption)
    {
        $this->departmentCaption = $departmentCaption;

        return $this;
    }

    /**
     * @return string
     */
    public function getDepartmentCaption()
    {
        return $this->departmentCaption;
    }

    /**
     * @param string $description
     * @return self
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param boolean $hasGeodata
     * @return self
     */
    public function setHasGeodata($hasGeodata)
    {
        $this->hasGeodata = (bool) $hasGeodata;

        return $this;
    }

    /**
     * @return boolean
     */
    public function getHasGeodata()
    {
        return $this->hasGeodata;
    }
}


text:
package org.antlr.symtab;

import org.antlr.v4.runtime.ParserRuleContext;

import java.util.Collections;
import java.util.List;

/** An abstract base class used to house common functionality.
 *  You can associate a node in the parse tree that is responsible
 *  for defining this symbol.
 */
public abstract class BaseSymbol implements Symbol {
	protected final String name;   		 // All symbols at least have a name
	protected Type type;				 // If language statically typed, record type
	protected Scope scope;      		 // All symbols know what scope contains them.
	protected ParserRuleContext defNode; // points at definition node in tree
	protected int lexicalOrder; 		 // order seen or insertion order from 0; compilers often need this

	public BaseSymbol(String name) { this.name = name; }

	@Override public String getName() { return name; }
	@Override public Scope getScope() { return scope; }
	@Override public void setScope(Scope scope) { this.scope = scope; }

	public Type getType() { return type; }
	public void setType(Type type) { this.type = type; }

	public void setDefNode(ParserRuleContext defNode) {
		this.defNode = defNode;
	}

	public ParserRuleContext getDefNode() {
		return defNode;
	}

	@Override
	public boolean equals(Object obj) {
		if ( !(obj instanceof Symbol) ) {
			return false;
		}
        if ( obj==this ) {
			return true;
		}
		return name.equals(((Symbol)obj).getName());
	}

	@Override
	public int hashCode() {
		return name.hashCode();
	}

	@Override
	public int getInsertionOrderNumber() {
		return lexicalOrder;
	}

	@Override
	public void setInsertionOrderNumber(int i) {
		this.lexicalOrder = i;
	}

	public String getFullyQualifiedName(String scopePathSeparator) {
		List<Scope> path = scope.getEnclosingPathToRoot();
		Collections.reverse(path);
		String qualifier = Utils.joinScopeNames(path, scopePathSeparator);
		return qualifier + scopePathSeparator + name;
	}

	public String toString() {
		String s = "";
		if ( scope!=null ) s = scope.getName()+".";
		if ( type!=null ) {
			String ts = type.toString();
			if ( type instanceof SymbolWithScope ) {
				ts = ((SymbolWithScope) type).getFullyQualifiedName(".");
			}
			return '<'+s+getName()+":"+ts+'>';
		}
		return s+getName();
	}
}


text:
module Netzke::Generators::Widget
  class BlPanelGenerator < AbstractBase
    module TemplateHelper
      def regions_js
        res = []
        all_regions.each do |region|
          res << %Q{
          :#{region[:name]} => {
            :class_name => "#{region[:class_name]}"#{model_js(region)}
            :ext_config => {
              :title => "#{title(region)}"
            }
          }}
        end
        res.join(",\n")
      end

      def title region
        return region[:model].pluralize if region[:model]
        region[:class_name]
      end

      def model_js region
        return %Q{,
            :model_name => "#{region[:model]}",} if region[:model]
        ""
      end

      def all_regions
        regions = []
        [:center, :north, :south, :east, :west].each do |region|
          regions << get_region(options[region], region) if options[region]
        end
        regions
      end

      def get_region region, name
        class_name, model = region.split(':')
        region = {:name => name, :class_name => class_name}
        region.merge!(:model => model) if model
        region
      end
    end
  end
end


text:
package me.wener.commons.patterns.structural.Decorator.window;

// The first concrete decorator which adds vertical scrollbar functionality
class VerticalScrollBarDecorator extends WindowDecorator
{
    public VerticalScrollBarDecorator(Window windowToBeDecorated)
    {
        super(windowToBeDecorated);
    }

    @Override
    public void draw()
    {
        super.draw();
        drawVerticalScrollBar();
    }

    private void drawVerticalScrollBar()
    {
        // Draw the vertical scrollbar
    }

    @Override
    public String getDescription()
    {
        return super.getDescription() + ", including vertical scrollbars";
    }
}


text:
export const transformArrayToObject = (array) => {
  return array?.length > 0
    ? array.reduce((previous, current) => ({ ...previous, ...current }))
    : {}
}


text:
import java.util.*;
import java.io.*;
import java.awt.image.*;
import java.awt.Graphics2D;
import javax.imageio.*;

public class SimpleTester {
   private static int red(int rgb) {return rgb >> 16 & 0xFF;}
   private static int green(int rgb) {return rgb >> 8 & 0xFF;}
   private static int blue(int rgb) {return rgb & 0xFF;}

   public static BufferedImage filterBoard(boolean rGT, int r, boolean gGT, int g, boolean bGT, int b, BufferedImage img) {
      BufferedImage i = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);

      for (int x = 0; x < img.getWidth(); x++) {
         for (int y = 0; y < img.getHeight(); y++) {
            int rgb = img.getRGB(x,y);
            int color = (red(rgb) > r == rGT) && (green(rgb) > g == gGT) && (blue(rgb) > b == bGT) ? 0xFF : 0;
            i.setRGB(x,y,color);
         }
      }

      return i;
   }

   public static void main(String[] args) throws Exception {
      if (args.length != 1) {
         System.err.println("wtf? Need 1 argument...");
         return;
      }

      Scanner scan = new Scanner(System.in);

      File file = new File(args[0]);
      BufferedImage src = ImageIO.read(file);

      while (scan.hasNext()) {
         boolean rGT = scan.next().charAt(0) == '>';
         int r = scan.nextInt();
         boolean gGT = scan.next().charAt(0) == '>';
         int g = scan.nextInt();
         boolean bGT = scan.next().charAt(0) == '>';
         int b = scan.nextInt();

         ImageIO.write(filterBoard(rGT,r,gGT,g,bGT,b,src), "png", new File("out.png"));
         Runtime.getRuntime().exec("gnome-open out.png").waitFor();
      }
   }
}


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

<meta name="generator" content="JDiff v1.1.0">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
android.app.usage.NetworkStatsManager
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />

<nobr>Android Developers | Android.com</nobr>

        API Diff Specification

        To Level:
        24

        From Level:
        23

        Generated
        2016.06.13 13:31

        Statistics

Class android.app.usage.NetworkStatsManager

  Added Methods

  <nobr>NetworkStats queryDetailsForUidTag(int,</nobr> String<nobr>,</nobr> long<nobr>,</nobr> long<nobr>,</nobr> int<nobr>,</nobr> int<nobr><nobr>)</nobr>

  <nobr>void registerUsageCallback(int,</nobr> String<nobr>,</nobr> long<nobr>,</nobr> UsageCallback<nobr><nobr>)</nobr>

  <nobr>void registerUsageCallback(int,</nobr> String<nobr>,</nobr> long<nobr>,</nobr> UsageCallback<nobr>,</nobr> Handler<nobr><nobr>)</nobr>

  <nobr>void unregisterUsageCallback(UsageCallback)</nobr>

        Except as noted, this content is licensed under
         Creative Commons Attribution 2.5.
        For details and restrictions, see the Content License.

        Site Terms of Service -
        Privacy Policy -
        Brand Guidelines


text:
namespace onnxruntime {
namespace cuda {

INcclService& GetINcclService() {
  return NcclService::GetInstance();
}

bool NcclTask::Compare(const NcclTask& other) const {
  if (type != other.type) {
    return false;
  }
  if (peers.size() != other.peers.size()) {
    return false;
  }
  for (size_t i = 0; i < peers.size(); ++i) {
    if (peers[i] != other.peers[i]) {
      return false;
    }
  }

  return true;
}

void NcclTask::ResetTask() {
  ptr = nullptr;
  size = 0;
  is_enqueued = false;
  is_finished = false;
}

void NcclTaskGroup::PlanTask(
    const NcclTask::Type type,
    const std::vector<int> peers) {
  batch.push_back({type, peers, nullptr, 0, false, false, ""});
};

const NcclTask* NcclTaskGroup::EqueueTask(
    const NcclTask::Type type,
    const std::vector<int> peers,
    void* ptr,
    const size_t size,
    const std::string info) {
  NcclTask scheduled_task;
  scheduled_task.type = type;
  scheduled_task.peers = peers;

  for (auto& task : batch) {
    if (!task.Compare(scheduled_task)) {
      // "scheduled_task" doesn't match "task" in task "batch" in this time slot.
      // Go checking if "scheduled_task" matches next one.
      continue;
    }

    ORT_ENFORCE(!task.is_finished, "Cannot enqueue finished NCCL P2P task again before calling ResetAllTasks in a time slot.");
    ORT_ENFORCE(!task.is_enqueued, "Cannot enqueue duplicated NCCL P2P tasks in a time slot.");

    // "scheduled_task" matches "task", so we add the task details for launching NCCL call.
    task.ptr = ptr;
    task.size = size;
    task.is_enqueued = true;
    task.info = info;
    return &task;
  }

  return nullptr;
};

bool NcclTaskGroup::IsAllTasksEqueued() const {
  return std::all_of(
      batch.begin(), batch.end(), [&](const NcclTask& task) {
        return task.is_enqueued;
      });
};

bool NcclTaskGroup::IsAllTasksFinished() const {
  return std::all_of(
      batch.begin(), batch.end(), [&](const NcclTask& task) {
        return task.is_finished;
      });
};

void NcclTaskGroup::ResetAllTasks() {
  for (auto& task : batch) {
    task.ptr = nullptr;
    task.size = 0;
    task.is_enqueued = false;
    task.is_finished = false;
  }
};

void NcclService::PlanStart() {
  ORT_ENFORCE(!is_planned_, "Communication plan cannot be changed after calling PlanEnd.");
};

void NcclService::PlanEnd() {
  is_planned_ = true;
};

void NcclService::PlanNewGroupStart() {
  group_status_.push_back(true);
  schedule_.push_back(NcclTaskGroup());
};

void NcclService::PlanNewGroupEnd() {
  group_status_.back() = false;
};

void NcclService::PlanSend(const int dst) {
  ORT_ENFORCE(group_status_.back(), "Last communication group can not be changed after call PlanEndNewGroup.");

  schedule_.back().PlanTask(NcclTask::Type::SEND, {dst});
};

void NcclService::PlanRecv(const int src) {
  ORT_ENFORCE(group_status_.back(), "Last communication group can not be changed after call PlanEndNewGroup.");
  schedule_.back().PlanTask(NcclTask::Type::RECV, {src});
};

void NcclService::WaitForLaunch() {
  std::unique_lock<std::mutex> lock(mutex_);
  cv_.wait(lock, [this] { return is_running_; });
}

std::ostream& operator<<(std::ostream& stream, const NcclTaskGroup& task_group) {
  for (int i = 0; static_cast<size_t>(i) < task_group.batch.size(); ++i) {
    std::string line = "  ";
    auto& task = task_group.batch[i];
    if (task.type == NcclTask::Type::SEND) {
      line += "Send, ";
    } else if (task.type == NcclTask::Type::RECV) {
      line += "Recv, ";
    }

    for (int j = 0; static_cast<size_t>(j) < task.peers.size(); ++j) {
      line += std::to_string(task.peers[j]);
      if (static_cast<size_t>(j) != task.peers.size() - 1) {
        line += ", ";
      } else {
        line += "\n";
      }
    }
    stream << line;
  }
  return stream;
}

std::ostream& operator<<(std::ostream& stream, const NcclService& service) {
  for (int i = 0; static_cast<size_t>(i) < service.schedule_.size(); ++i) {
    stream << "NCCL operations at time " << i << std::endl;
    stream << service.schedule_[i];
  }
  return stream;
}

int NcclService::FindNextCommunicationTime() const {
  for (int i = 0; static_cast<size_t>(i) < schedule_.size(); ++i) {
    if (schedule_[i].IsAllTasksEqueued() && !schedule_[i].IsAllTasksFinished()) {
      return i;
    }
  }
  return -1;
};

void NcclService::SubmitSendAndWait(void* ptr, size_t size, int peer) {
  // Wait until NCCL service is launched.
  WaitForLaunch();
  // Pointer to enqueued task.
  const NcclTask* task;

  // Submit task.
  {
    std::lock_guard<std::mutex> guard(mutex_);
#ifdef ENABLE_NVTX_PROFILE
    auto& profile_context = profile::Context::GetInstance();
    const std::string tag = profile_context.GetThreadTagOrDefault(std::this_thread::get_id());
#else
    const std::string tag = "";
#endif
    task = schedule_[time_].EqueueTask(NcclTask::Type::SEND, std::vector<int>{peer}, ptr, size, tag);

    ORT_ENFORCE(task, "Unplanned NCCL Send encountered.");
  }

  // Wait for task to be finished.
  {
    std::unique_lock<std::mutex> lock(mutex_);
    cv_.wait(lock, [&] { return task->is_finished; });
  }
};

void NcclService::SubmitRecvAndWait(void* ptr, size_t size, int peer) {
  // Wait until NCCL service is launched.
  WaitForLaunch();

  // Pointer to euqueued task.
  const NcclTask* task;
  {
    std::lock_guard<std::mutex> guard(mutex_);
#ifdef ENABLE_NVTX_PROFILE
    auto& profile_context = profile::Context::GetInstance();
    const std::string tag = profile_context.GetThreadTagOrDefault(std::this_thread::get_id());
#else
    const std::string tag = "";
#endif
    task = schedule_[time_].EqueueTask(NcclTask::Type::RECV, std::vector<int>{peer}, ptr, size, tag);
    ORT_ENFORCE(task, "Unplanned NCCL Send encountered.");
  }

  // Wait for task to be finished.
  {
    std::unique_lock<std::mutex> lock(mutex_);
    cv_.wait(lock, [&] { return task->is_finished; });
  }
};

void NcclService::Initialize() {
  // Here we assume GPU i is assigned to local process i.
  // TODO: Create a general class to describe for computation topology and unify all similar uses.
  // Hardware a process can own:
  //   GPUs
  //   CPUs
  //   Other devices

  const int mpi_rank = onnxruntime::training::MPIContext::GetInstance().GetWorldRank();
  const int mpi_local_rank = onnxruntime::training::MPIContext::GetInstance().GetLocalRank();
  const int mpi_size = onnxruntime::training::MPIContext::GetInstance().GetWorldSize();

  // Set device this NCCL communicator runs on.
  CUDA_CALL_THROW(cudaSetDevice(mpi_local_rank));

  // Create communication stream.
  CUDA_CALL_THROW(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking));

  // Get NCCL unique ID at rank 0 and broadcast it to all others.
  ncclUniqueId id;
  if (mpi_rank == 0) NCCL_CALL_THROW(ncclGetUniqueId(&id));
  MPI_CHECK(MPI_Bcast((void*)&id, sizeof(id), MPI_BYTE, 0, MPI_COMM_WORLD));
  NCCL_CALL_THROW(ncclCommInitRank(&comm_, mpi_size, id, mpi_rank));
}

void NcclService::Launch() {
  worker_ = std::thread([this]() {
    {
      std::lock_guard<std::mutex> guard(mutex_);
      ORT_ENFORCE(is_planned_, "NCCL service must know its communication plan before launching.");
      // The NCCL service object can only be launched once because it's a
      // singlton class.
      ORT_ENFORCE(!is_running_, "NCCL service cannot be repeatedly launched.");

      // Set this flag so that others will not call this again.
      is_running_ = true;
      cv_.notify_all();
    }

    Initialize();

    while (is_running_) {
      // Enter critical region of performing concurrent NCCL P2P operations (for example, Send's and Recv's).
      // The state of this class cannot be modified by other threads.
      {
        std::lock_guard<std::mutex> guard(mutex_);
        // All tasks must be ready with a valid time.
        if (schedule_.empty() ||
            time_ > schedule_.size() - 1 ||
            !schedule_[time_].IsAllTasksEqueued() ||
            schedule_[time_].IsAllTasksFinished()) {
          continue;
        }

        // Start NCCL parallel communication.
        NCCL_CALL_THROW(ncclGroupStart());
        for (auto& task : schedule_[time_].batch) {
          ORT_ENFORCE(task.is_enqueued,
                      "Unscheduled task cannot be run.",
                      " Use PlanTask to schedule tasks before executing the graph.");
#ifndef NDEBUG
          CheckIfMemoryOnCurrentGpuDevice(task.ptr);
#endif
          switch (task.type) {
            case NcclTask::Type::SEND:
              ORT_ENFORCE(task.peers.size() == 1, "Send can only send data to one rank.");
              NCCL_CALL_THROW(ncclSend(task.ptr, task.size, ncclChar, task.peers.front(), comm_, stream_));
              break;
            case NcclTask::Type::RECV:
              ORT_ENFORCE(task.peers.size() == 1, "Recv can only send data to one rank.");
              NCCL_CALL_THROW(ncclRecv(task.ptr, task.size, ncclChar, task.peers.front(), comm_, stream_));
              break;
            default:
              ORT_NOT_IMPLEMENTED("NCCL service currently only support ncclSend and ncclRecv.");
          }
          task.is_finished = true;
        }
        NCCL_CALL_THROW(ncclGroupEnd());

        // Make sure all NCCL computation are done.
        // Since the Submit*andWait are blocked by the following "cv_.notify_all()",
        // all NCCL Send and Recv called above are all finished before Submit*andWait returning.
        // Thus, CUDA operations after Send and Recv won't be inserted by other threads
        // when we call NCCL Send's and Recv's.
        CUDA_CALL_THROW(cudaStreamSynchronize(stream_));

        // This round of communication is done.
        // We can start waiting for the tasks to be fully scheduled.
        ++time_;
        ++total_time_;
      }
      cv_.notify_all();
    }
  });
}

void NcclService::Reset() {
  WaitForLaunch();
  {
    std::unique_lock<std::mutex> lock(mutex_);

    // We can only reset after all planned tasks are done,
    // so wait for unfinished tasks here.
    cv_.wait(lock, [this] {
      bool is_all_tasks_finished = true;
      for (auto& task_group : schedule_) {
        if (task_group.IsAllTasksFinished()) {
          continue;
        }
        is_all_tasks_finished = false;
      };
      return is_all_tasks_finished;
    });
  }

  {
    std::lock_guard<std::mutex> guard(mutex_);
    time_ = 0;

    // All scheduled communication tasks are done for finishing
    // gradient accumulation steps + one model update step.
    // To start next round of gradient accumulation and model update,
    // we need to reset the "done" status of all tasks in the schedule.
    for (auto& task_group : schedule_) {
      task_group.ResetAllTasks();
    }

    cv_.notify_all();
  }
}

void NcclService::Terminate() {
  WaitForLaunch();
  {
    std::unique_lock<std::mutex> lock(mutex_);
    cv_.wait(lock, [this] { return schedule_.empty() || (total_time_ > 0 && time_ == 0); });
  }

  CUDA_CALL_THROW(cudaStreamDestroy(stream_));

  is_running_ = false;
  is_planned_ = false;
  time_ = 0;
  total_time_ = 0;

  group_status_.clear();
  schedule_.clear();
  worker_.join();
  NCCL_CALL_THROW(ncclCommDestroy(comm_));
}

}  // namespace cuda
}  // namespace onnxruntime

#endif


text:
/* See license.txt for terms of usage */

"use strict";

module.metadata = {
  "stability": "experimental"
};

const { Trace, TraceError } = require("../core/trace.js").get(module.id);

// Module implementation
let Dom = {};

Dom.clearNode = function(node) {
  node.textContent = "";
};

Dom.getAncestorByClass = function(node, className) {
  for (var parent = node; parent; parent = parent.parentNode) {
    if (parent.classList && parent.classList.contains(className)) {
      return parent;
    }
  }
  return null;
};

Dom.getAncestorByTagName = function(node, tagName) {
  for (var parent = node; parent; parent = parent.parentNode) {
    if (parent.localName && parent.tagName.toLowerCase() == tagName) {
      return parent;
    }
  }
  return null;
};

/**
 * Centers an element inside a scrollable area
 * @param {Object} element Element to scroll to
 * @param {Object} scrollBox Scrolled element (Must be an ancestor of
 * "element" or null for automatically determining the ancestor)
 * @param {Boolean} notX Specifies whether the element should be
 * centered horizontally
 * @param {Boolean} notY Specifies whether the element should be
 * centered vertically
 */
Dom.scrollIntoCenterView = function(element, scrollBox, notX, notY) {
  Dom.scrollTo(element, scrollBox, notX ? "none" : "centerOrLeft",
    notY ? "none" : "centerOrTop");
};

/**
 * Scrolls an element into view
 * @param {Object} element Element to scroll to
 * @param {Object} scrollBox Scrolled element (Must be an ancestor of
 * "element" or null for automatically determining the ancestor)
 * @param {String} alignmentX Horizontal alignment for the element
 * (valid values: "centerOrLeft", "left", "middle", "right", "none")
 * @param {String} alignmentY Vertical alignment for the element
 * (valid values: "centerOrTop", "top", "middle", "bottom", "none")
 * @param {Boolean} scrollWhenVisible Specifies whether "scrollBox"
 * should be scrolled even when "element" is completely visible
 */
// xxxHonza: fix code style
Dom.scrollTo = function(element, scrollBox, alignmentX, alignmentY,
  scrollWhenVisible) {
  if (!element) {
    return;
  }

  if (!scrollBox) {
    scrollBox = Dom.getOverflowParent(element);
  }

  if (!scrollBox) {
    return;
  }

  var offset = Dom.getAncestorOffset(element, scrollBox);

  if (!alignmentX) {
    alignmentX = "centerOrLeft";
  }

  if (!alignmentY) {
    alignmentY = "centerOrTop";
  }

  if (alignmentY) {
    let topSpace = offset.y - scrollBox.scrollTop;
    let bottomSpace = (scrollBox.scrollTop + scrollBox.clientHeight) -
      (offset.y + element.offsetHeight);

    let y;

    // Element is vertically not completely visible or scrolling is enforced
    if (topSpace < 0 || bottomSpace < 0 || scrollWhenVisible) {
      switch (alignmentY) {
        case "top":
          scrollBox.scrollTop = offset.y;
          break;

        case "center":
        case "centerOrTop":
          let elementFitsIntoScrollBox =
            element.offsetHeight <= scrollBox.clientHeight;
          y = elementFitsIntoScrollBox || alignmentY != "centerOrTop" ?
            offset.y - (scrollBox.clientHeight - element.offsetHeight) / 2 :
            offset.y;
          scrollBox.scrollTop = y;
          break;

        case "bottom":
          y = offset.y + element.offsetHeight - scrollBox.clientHeight;
          scrollBox.scrollTop = y;
          break;
      }
    }
  }

  if (alignmentX) {
    let leftSpace = offset.x - scrollBox.scrollLeft;
    let rightSpace = (scrollBox.scrollLeft + scrollBox.clientWidth) -
      (offset.x + element.clientWidth);

    let x;

    // Element is horizontally not completely visible or scrolling is enforced
    if (leftSpace < 0 || rightSpace < 0 || scrollWhenVisible) {
      switch (alignmentX) {
        case "left":
          scrollBox.scrollLeft = offset.x;
          break;

        case "center":
        case "centerOrLeft":
          let elementFitsIntoScrollBox =
            element.offsetWidth <= scrollBox.clientWidth;
          x = elementFitsIntoScrollBox || alignmentX != "centerOrLeft" ?
            offset.x - (scrollBox.clientWidth - element.offsetWidth) / 2 :
            offset.x;
          scrollBox.scrollLeft = x;
          break;

        case "right":
          x = offset.x + element.offsetWidth - scrollBox.clientWidth;
          scrollBox.scrollLeft = x;
          break;
      }
    }
  }

  Trace.sysout("dom.scrollTo;", element);
};

/**
 * Get the next scrollable ancestor
 * @param {Object} element Element to search the ancestor for
 * @returns {Object} Scrollable ancestor
 */
Dom.getOverflowParent = function(element) {
  for (let scrollParent = element.parentNode; scrollParent;
    scrollParent = scrollParent.offsetParent) {
    if (scrollParent.scrollHeight > scrollParent.offsetHeight) {
      return scrollParent;
    }
  }
};

/**
 * Gets the offset of an element relative to an ancestor
 * @param {Element} elt Element to get the info for
 * @param {Element} ancestor Ancestor element used as origin
 */
Dom.getAncestorOffset = function(elt, ancestor) {
  let offset = { x: 0, y: 0 };
  let offsetParent = elt;
  do {
    offset.x += offsetParent.offsetLeft;
    offset.y += offsetParent.offsetTop;
    offsetParent = offsetParent.offsetParent;
  } while (offsetParent && offsetParent !== ancestor);

  return offset;
};

Dom.addScript = function(doc, id, src) {
  let element = doc.getElementById(id);
  if (element) {
    return element;
  }

  element = doc.createElementNS("http://www.w3.org/1999/xhtml", "html:script");
  element.setAttribute("type", "text/javascript");
  element.setAttribute("id", id);
  element.textContent = src;

  if (doc.documentElement) {
    doc.documentElement.appendChild(element);
  }
  else {
    // See issue 1079, the svg test case gives this error
    TraceError.sysout("dom.addScript; ERROR doc has no documentElement (" +
      doc.readyState + ") " + doc.location, doc);
    return;
  }

  return element;
};

Dom.loadScript = function(doc, src, successCallback) {
  let script = doc.createElementNS("http://www.w3.org/1999/xhtml", "html:script");
  script.type = "text/javascript";
  script.async = true;
  script.src = src;
  script.addEventListener("load", event => {
    successCallback(event);
  });

  doc.documentElement.appendChild(script);

  return script;
};

// Exports from this module
exports.Dom = Dom;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>demos</groupId>
		<artifactId>demos</artifactId>
		<version>${revision}</version>
		<relativePath>..</relativePath>
	</parent>

	<artifactId>demos-jsr223</artifactId>
	<name>demos-jsr223</name>
	<url>https://github.com/han-feng/demos</url>

	<dependencies>
		<dependency>
			<groupId>org.codehaus.groovy</groupId>
			<artifactId>groovy-jsr223</artifactId>
			<version>2.4.8</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jruby</groupId>
			<artifactId>jruby</artifactId>
			<version>9.1.7.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.clojars.ato</groupId>
			<artifactId>clojure-jsr223</artifactId>
			<version>1.5.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.python</groupId>
			<artifactId>jython-standalone</artifactId>
			<version>2.7.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.luaj</groupId>
			<artifactId>luaj-jse</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-jcl</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.fusesource.jansi</groupId>
			<artifactId>jansi</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>clojars</id>
			<url>http://clojars.org/repo/</url>
		</repository>
	</repositories>

</project>


text:
set(CMAKE_BUILD_TYPE "Distribution" CACHE STRING "Build type")
set(CFLAGS "-mno-avx" CACHE STRING "CFLAGS")
set(CXXFLAGS "-mno-avx" CACHE STRING "CXXFLAGS")
set(CFLAGS "-mno-avx" CACHE STRING "CFLAGS")
set(CXXFLAGS "-mno-avx" CACHE STRING "CXXFLAGS")

set(USE_BLAS "open" CACHE STRING "BLAS Vendor")
set(USE_CUDA ON CACHE BOOL "Build with CUDA support")
set(USE_CUDNN ON CACHE BOOL "Build with CUDNN support")
set(USE_NCCL ON CACHE BOOL "Build with NCCL support")
set(USE_OPENCV ON CACHE BOOL "Build with OpenCV support")
set(USE_OPENMP ON CACHE BOOL "Build with Openmp support")
set(USE_ONEDNN ON CACHE BOOL "Build with oneDNN support")
set(USE_LAPACK ON CACHE BOOL "Build with lapack support")
set(USE_TVM_OP OFF CACHE BOOL "Enable use of TVM operator build system.")
set(USE_SSE ON CACHE BOOL "Build with x86 SSE instruction support")
set(USE_F16C OFF CACHE BOOL "Build with x86 F16C instruction support")
set(USE_LIBJPEG_TURBO ON CACHE BOOL "Build with libjpeg-turbo")
set(USE_DIST_KVSTORE ON CACHE BOOL "Build with DIST_KVSTORE support")
set(CUDACXX "/usr/local/cuda-10.1/bin/nvcc" CACHE STRING "Cuda compiler")
set(MXNET_CUDA_ARCH "3.0;5.0;6.0;7.0" CACHE STRING "Cuda architectures")


text:
var bannedVars = ["Serial", "LOW", "HIGH", "INPUT", "OUTPUT", "RISING", "FALLING", "CHANGE",
                  "pinMode", "digitalWrite", "analogWrite", "digitalRead", "millis",
                  "analogRead", "delay", "main", "attachInterrupt", "detachInterrupt"];
var Range = ace.require('ace/range').Range;

function Debugger(editor) {

  //Breakpoints
  this.breakpoints = [];
  this.toggleBreakpoint = function(line) {
    if (this.breakpoints.includes(line)) {
      editor.session.clearBreakpoint(line);
      this.breakpoints.remove(line);
    } else {
      editor.session.setBreakpoint(line);
      this.breakpoints.push(line);
    }
    this.sendUpdatedBreakpoints();
  };
  this.sendUpdatedBreakpoints = function() {
    try {
      var breakpointsCopy = this.breakpoints.slice();
      var fixedBreakpoints = breakpointsCopy.map((x) => aceToJSCPP(x));
      jscpp.postMessage({type: "breakpoints", breakpoints: fixedBreakpoints});
    } catch (e) {

    }
  };

  this.stopDebuggingSession = function() {
    jscpp.postMessage({type: "debugger", action: "enabled", state: false});
    this.doContinue();
  };

  //Enabled
  this.isEnabled = function() {
    return document.getElementById("debugging-enabled").checked && this.breakpoints.length !== 0;
  };
  this.sendUpdateEnabled = function () {
    try {
      jscpp.postMessage({type: "debugger", action: "enabled", state: this.isEnabled()});
    } catch (e) {
      console.log(e);
    }
  };

  this.isLineValid = function(line) {
    return !(line < 0 || line >= editor.getSession().getLength());
  };

  this.handleMessage = function(message) {
    var sLine = JSCPPToAce(message.node.sLine);
    var eLine = JSCPPToAce(message.node.eLine);
    if (!this.isLineValid(sLine) || !this.isLineValid(eLine)) {
      this.doStepLine();
      return;
    }
    console.log(message.node);
    this.markedLine = editor.getSession().addMarker(
      new Range(sLine, message.node.sColumn - 1, eLine, message.node.eColumn - 1),
      "current-line",
      false);
    this.showVariables(message.variables);
    var fm = makeFrameManager(message.frameManager);
    this.renderState(fm);
  };

  //Marker
  this.markedLine = null;
  this.removeMarker = function() {
    if (this.markedLine !== null) {
      editor.getSession().removeMarker(this.markedLine);
    }
  };

  //Stepping
  this.doContinue = function() {
    if(running) {
      try {
        jscpp.postMessage({type: "debugger", action: "continue"});
        this.cleanup();
      } catch (e) {

      }
    } else {
      runCode();
    }
  };
  this.doStepLine = function() {
    try {
      jscpp.postMessage({type: "debugger", action: "stepLine"});
      this.cleanup();
    } catch (e) {

    }
  };
  this.doStepExpression = function() {
    try {
      jscpp.postMessage({type: "debugger", action: "stepExpression"});
      this.cleanup();
    } catch (e) {

    }
  };
  this.cleanup = function() {
    this.removeMarker();
    hideCanvas();
  };

  //Render
  this.showVariables = function(vars) {
    $("#control-tabs a[href=\"#debug\"]").tab("show");
    var tbody = $("#variables-table-body");
    tbody.html("");
    vars.forEach(function(v) {
      if (bannedVars.includes(v.name)) {
        return;
      }
      var tr = $("<tr>");
      var type = $("<td>");
      var name = $("<td>");
      var value = $("<td>");

      type.text(v.type);
      name.text(v.name);
      value.text(v.value);

      tr.append(type);
      tr.append(name);
      tr.append(value);

      tbody.append(tr);
    });
  };
  this.renderState = function(frameManager) {

    var date = new Date();
    var dateString = date.toDateString();
    var timeString = date.toLocaleTimeString();

    var name = nameField.value;
    var exerciseNumber = exerciseField.value;
    currentBoard.setContext({
      isCorrect: undefined,
      dateString: dateString,
      timeString: timeString,
      exerciseNumber: exerciseNumber,
      name: name
    });

    canvas.height = currentBoard.canvasHeight;
    canvas.width = currentBoard.canvasWidth;

    for (var i = 0; i < frameManager.frames.length; i++) {
      currentBoard.advance(frameManager.frames[i], i, frameManager);
    }

    currentBoard.draw(canvas.getContext("2d"));

    setStatus("Current State:", "");

    showCanvas(true);
  };

  //Editor
  editor.on("gutterclick", function(e) {
    debug.toggleBreakpoint(e.getDocumentPosition().row);
    e.stop();
  });
  editor.on("guttermousedown", function(e) {
    e.stop();
  });
}


text:
@implementation Channel

+ (NSArray *)channels {

    //1.获取目录,加载dict,取出array
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"topic_news.json" withExtension:nil];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    NSArray *tList = dict[dict.keyEnumerator.nextObject];

    //2.遍历添加到arrayM
    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:tList.count];
    [tList enumerateObjectsUsingBlock:^(id  __nonnull obj, NSUInteger idx, BOOL * __nonnull stop) {
        [arrayM addObject:[self objWithDict:obj]];
    }];

    return [arrayM sortedArrayUsingComparator:^NSComparisonResult(Channel  __nonnull *obj1, Channel  __nonnull *obj2) {
        return [obj1.tid compare:obj2.tid];
    }];
}

- (void)setTid:(NSString *)tid {
    _tid = tid.copy;
    _urlString = [NSString stringWithFormat:@"%@/0-20.html", tid];
}

@end


text:
require_relative "kuaipan_renamer/version"
require "colored"
require "shellwords"
require "logger"

module KuaipanRenamer

  def self.rename_recursively( root, opts={} )
    Walker.new( root, opts ).rename_recursively
  end

  class Walker

    attr_reader :root

    def initialize( root, dry_run: false )
      @root = root
      @dry_run = dry_run
      @err_log = Logger.new(STDERR)
    end

    def rename_recursively
      rename_folder root
    end

    def rename_folder( folder )
      #puts "glob: #{folder}"
      Dir.glob( "#{folder.shellescape}/*" ) do |f|
        #puts "  - " + f
        if File.directory? f
          #puts "folder #{f}"
          rename_folder f
        else
          rename_file f
        end
      end

      rename_file folder
    end

    def rename_file( file )
      dir, base = *File.split(file)
      new_name  = new_name_for base
      unless base == new_name
        fullpath = File.join dir, new_name
        puts "#{file.ljust(50).red} => #{fullpath.green}"
        unless @dry_run
          begin
            File.rename file, fullpath
          rescue => e
            @err_log.error "Error renaming #{file} to #{fullpath}".red.bold
            @err_log.error "  - " << e.message
          end
        end
      end
    end

    def new_name_for file
      map = {
        "(" => "(",
        ")" => ")",
        "[" => "【",
        "]" => "】"
      }
      file.dup.tap do |f|
        map.each do |from, to|
          f.gsub!( from, to )
        end
      end
    end

  end

end


text:
title: OnFileUploaded
page_title: OnFileUploaded | RadAsyncUpload for ASP.NET AJAX Documentation
description: OnFileUploaded
slug: asyncupload/server-side-programming/onfileuploaded
tags: onfileuploaded
published: True
position: 2
---

# OnFileUploaded

##

The server-side **FileUploaded** occurs after a file is uploaded and a postback is triggered.

>note When the [PostbackTriggers]({%slug asyncupload/how-to/how-to-persist-uploaded-files%}) property of the **RadAsyncUpload** is set to a particular button, the **FileUploaded** event will fire only when that button is clicked.
>

The **FileUploaded** event handler receives two arguments:

* The **RadAsyncUpload** control that initiated the file upload. This argument is of type object, but can be cast to the **RadAsyncUpload** type.

* An **FileUploadedEventArgs** object that has three properties:

* **IsValid** - Allows you to specify whether the uploaded file is valid. If it is, **RadAsyncUpload** will automatically save it to the TargetFolder, if one is set.

* **File** - Provides reference to the file uploaded.

* **UploadResult** - A container object containing information sent from the **RadAsyncUpload** file handler. For additional information, visit [How to extend the RadAsyncUpload handler.]({%slug asyncupload/how-to/how-to-extend-the-radasyncupload-handler%})

The example below demonstrates how to prepare the previously uploaded file to send as an e-mail attachment:

````C#
void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
    e.IsValid = !CheckUploadedFileValidity();
    if (e.IsValid)
    {
        byte[] buffer = new byte[e.File.ContentLength];
        using (Stream str = e.File.InputStream)
        {
            str.Read(buffer, 0, e.File.ContentLength);
            var attachment = createAttachment(buffer);
            // more code
        }
    }
}
````
````VB.NET
Private Sub RadAsyncUpload1_FileUploaded(ByVal sender As Object, ByVal e As FileUploadedEventArgs)
    e.IsValid = Not CheckUploadedFileValidity()
    If e.IsValid Then
        Dim buffer As Byte() = New Byte(e.File.ContentLength - 1) {}
        Using str As Stream = e.File.InputStream
            str.Read(buffer, 0, e.File.ContentLength)
            ' more code
            Dim attachment = createAttachment(buffer)
        End Using
    End If
End Sub
````

## See Also

[Getting Started]({%slug asyncupload/getting-started%})

[How to extend the RadAsyncUpload handler]({%slug asyncupload/how-to/how-to-extend-the-radasyncupload-handler%})

[Server-Side Events]({%slug asyncupload/server-side-programming/events%})


text:
package io.joern.joerncli.console

import io.joern.console.workspacehandling.{Project, ProjectFile}
import io.joern.dataflowengineoss.queryengine.EngineContext
import io.joern.dataflowengineoss.semanticsloader.Semantics
import io.shiftleft.codepropertygraph.Cpg

import java.nio.file.Path

class JoernProject(
  projectFile: ProjectFile,
  path: Path,
  cpg: Option[Cpg] = None,
  var context: EngineContext = EngineContext(Semantics.empty)
) extends Project(projectFile, path, cpg) {}


text:
import {PerformsTasks, Task} from 'serenity-js/lib/screenplay';
import { Navigate } from '../common/navigate';

export class StartContacts implements Task {

    performAs(actor: PerformsTasks): PromiseLike<void> {
        return actor.attemptsTo(
            Navigate.to('http://www.ramblers.org.uk/group-walks-and-events-manager.aspx?tab=Contacts'),
        );
    }

}


text:
package com.ptoceti.osgi.obix.impl.entity;

import java.sql.Connection;
import java.sql.SQLException;

import com.ptoceti.osgi.data.IResultSetGeneratedKeysHandler;
import com.ptoceti.osgi.data.IResultSetMultipleHandler;
import com.ptoceti.osgi.data.IResultSetSingleHandler;
import com.ptoceti.osgi.data.JdbcDevice;
import com.ptoceti.osgi.obix.impl.service.ObixDataHandler;

public class AbstractEntity {

	private Connection getCurrentConnection() {
		return ObixDataHandler.getInstance().getCurrentConnection();
	}

	private JdbcDevice getDevice(){
		return ObixDataHandler.getInstance().getDataDevice();
	}

	public void query(String query, IResultSetSingleHandler resultSetHandler) throws EntityException{
		try {
			getDevice().query(getCurrentConnection(), query, resultSetHandler);
		} catch (SQLException ex) {
			throw new EntityException("Exception in " + this.getClass().getName() + " queryMultiple", ex);
		}
	}

	public void query(String query, Object[] params, IResultSetSingleHandler resultSetHandler) throws EntityException {
		try {
			getDevice().query(getCurrentConnection(), query, params, resultSetHandler);
		} catch (SQLException ex) {
			throw new EntityException("Exception in " + this.getClass().getName() + " query", ex);
		}
	}

	public void queryMultiple(String query, Object[] params,IResultSetMultipleHandler resultSetHandler) throws EntityException{

		try {
			getDevice().queryMultiple(getCurrentConnection(), query, params,resultSetHandler);
		} catch (SQLException ex) {
			throw new EntityException("Exception in " + this.getClass().getName() + " queryMultiple", ex);
		}
	}

	public void queryMultiple(String query, IResultSetMultipleHandler resultSetHandler) throws EntityException {
		try {
			getDevice().queryMultiple(getCurrentConnection(), query,resultSetHandler);
		} catch (SQLException ex) {
			throw new EntityException("Exception in " + this.getClass().getName() + " queryMultiple", ex);
		}
	}

	public int update(String query, IResultSetGeneratedKeysHandler handler) throws EntityException {

		int result = -1;
		try {
			result = getDevice().update(getCurrentConnection(), query, handler);
		} catch (SQLException ex) {
			throw new EntityException("Exception in " + this.getClass().getName() + " update", ex);
		}

		return result;
	}

	public int update(String query, Object[] params, IResultSetGeneratedKeysHandler handler) throws EntityException {
		int result = -1;
		try {
			result = getDevice().update(getCurrentConnection(), query, params,handler);
		} catch (SQLException ex) {
			throw new EntityException("Exception in " + this.getClass().getName() + " update", ex);
		}

		return result;
	}

}


text:
package org.zmpp.swingui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.zmpp.media.InformMetadata;
import org.zmpp.media.Resources;
import org.zmpp.media.StoryMetadata;

/**
 * This dialog displays information about a story given its meta information.
 *
 * @author Wei-ju Wu
 * @version 1.0
 */
public class GameInfoDialog extends JDialog {

    private static final int STD_WIDTH = 400;
    private static final long serialVersionUID = 1L;

    public GameInfoDialog(JFrame owner, Resources resources) {
        super(owner, Main.getMessage("caption.about") + " "
                + resources.getMetadata().getStoryInfo().getTitle());
        getContentPane().add(createInfoPanel(resources));
        getContentPane().add(createButtonPanel(), BorderLayout.SOUTH);
        pack();
        setLocationRelativeTo(owner);
    }

    private JPanel createPicturePanel(Resources resources, int coverartnum) {

        JPanel picpanel = new JPanel();

        if (coverartnum > 0) {
            BufferedImage image
                    = resources.getImages().getResource(coverartnum).getImage();
            JLabel label = new PictureLabel(image);
            label.setPreferredSize(new Dimension(STD_WIDTH, 400));
            picpanel.add(label);
        }
        return picpanel;
    }

    private JComponent createInfoPanel(Resources resources) {

        StoryMetadata storyinfo = resources.getMetadata().getStoryInfo();
        Box infopanel = Box.createVerticalBox();
        infopanel.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
        JComponent panel = infopanel;

        // in case cover art is available, stack it into the info panel
        int coverartnum = getCoverartNum(resources);
        if (coverartnum > 0 && resources.getImages().getNumResources() > 0) {

            Box wholepanel = Box.createHorizontalBox();
            wholepanel.add(createPicturePanel(resources, coverartnum));
            wholepanel.add(infopanel);
            panel = wholepanel;
        }

        infopanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        infopanel.setPreferredSize(new Dimension(STD_WIDTH, 400));

        List<JLabel> labels = new ArrayList<JLabel>();
        labels.add(new JLabel(storyinfo.getTitle()));

        if (storyinfo.getHeadline() != null) {

            labels.add(new JLabel(storyinfo.getHeadline()));
        }

        labels.add(new JLabel(storyinfo.getAuthor() + " ("
                + storyinfo.getYear() + ")"));

        for (JLabel label : labels) {

            infopanel.add(label);
            label.setAlignmentX(Component.LEFT_ALIGNMENT);

            // Ensure that the label fonts are all bold
            label.setFont(label.getFont().deriveFont(Font.BOLD));
        }

        infopanel.add(Box.createVerticalStrut(6));

        JTextArea descarea = new JTextArea(storyinfo.getDescription());
        descarea.setLineWrap(true);
        descarea.setWrapStyleWord(true);
        descarea.setEditable(false);
        Insets margins = new Insets(3, 3, 3, 3);
        descarea.setMargin(margins);
        descarea.setFont(labels.get(0).getFont().deriveFont(Font.PLAIN));

        JScrollPane spane = new JScrollPane(descarea);
        spane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        spane.setPreferredSize(new Dimension(STD_WIDTH, 200));
        spane.setAlignmentX(Component.LEFT_ALIGNMENT);
        infopanel.add(spane);
        return panel;
    }

    private JPanel createButtonPanel() {

        // Set up the other controls
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton okButton = new JButton(Main.getMessage("caption.ok"));
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
        getRootPane().setDefaultButton(okButton);
        buttonPanel.add(okButton);
        return buttonPanel;
    }

    private int getCoverartNum(Resources resources) {

        int coverartnum = resources.getCoverArtNum();
        InformMetadata metadata = resources.getMetadata();

    // If the picture number is not in the Frontispiece chunk, retrieve it
        // from the metadata
        if (coverartnum <= 0) {
            coverartnum = metadata.getStoryInfo().getCoverPicture();
        }
        return coverartnum;
    }
}


text:
import sys
import logging as log
import signal
from statistics import mean
from abc import ABC, abstractmethod
import torch

import vedanet as vn

__all__ = ['Engine']

class Engine(ABC):
    """ This class removes the boilerplate code needed for writing your training cycle. |br|
    Here is the code that runs when the engine is called:

    .. literalinclude:: /../lightnet/engine/engine.py
       :language: python
       :pyobject: Engine.__call__
       :dedent: 4

    Args:
        network (lightnet.network.Darknet, optional): Lightnet network to train
        optimizer (torch.optim, optional): Optimizer for the network
        dataloader (lightnet.data.DataLoader or torch.utils.data.DataLoader, optional): Dataloader for the training data
        **kwargs (dict, optional): Keywords arguments that will be set as attributes of the engine

    Attributes:
        self.network: Lightnet network
        self.optimizer: Torch optimizer
        self.batch_size: Number indicating batch_size; Default **1**
        self.mini_batch_size: Size of a mini_batch; Default **1**
        self.max_batches: Maximum number of batches to process; Default **None**
        self.test_rate: How often to run test; Default **None**
        self.sigint: Boolean value indicating whether a SIGINT (CTRL+C) was send; Default **False**
    """
    __allowed_overwrite = ['batch_size', 'mini_batch_size', 'max_batches', 'test_rate']
    batch_size = 1
    mini_batch_size = 1
    max_batches = None
    test_rate = None

    #def __init__(self, network, optimizer, dataloader, **kwargs):
    def __init__(self, network, optimizer, dataloader):
        if network is not None:
            self.network = network
        else:
            log.warn('No network given, make sure to have a self.network property for this engine to work with.')

        if optimizer is not None:
            self.optimizer = optimizer
        else:
            log.warn('No optimizer given, make sure to have a self.optimizer property for this engine to work with.')

        if dataloader is not None:
            self.dataloader = dataloader
        else:
            log.warn('No dataloader given, make sure to have a self.dataloader property for this engine to work with.')

        # Rates
        self.__lr = self.optimizer.param_groups[0]['lr']
        self.__rates = {}

        # Sigint handling
        self.sigint = False
        signal.signal(signal.SIGINT, self.__sigint_handler)

        # Set attributes
        '''
        for key in kwargs:
            if not hasattr(self, key) or key in self.__allowed_overwrite:
                setattr(self, key, kwargs[key])
            else:
                log.warn(f'{key} attribute already exists on engine. Keeping original value [{getattr(self, key)}]')
        '''

    def __call__(self):
        """ Start the training cycle. """
        self.start()
        self._update_rates()
        if self.test_rate is not None:
            last_test = self.batch - (self.batch % self.test_rate)

        log.info('Start training')
        self.network.train()
        while True:
            loader = self.dataloader
            for idx, data in enumerate(loader):
                # Forward and backward on (mini-)batches
                self.process_batch(data)
                if (idx + 1) % self.batch_subdivisions != 0:
                    continue

                # Optimizer step
                self.train_batch()

                # Check if we need to stop training
                if self.quit() or self.sigint:
                    log.info('Reached quitting criteria')
                    return

                # Check if we need to perform testing
                if self.test_rate is not None and self.batch - last_test >= self.test_rate:
                    log.info('Start testing')
                    last_test += self.test_rate
                    self.network.eval()
                    self.test()
                    log.debug('Done testing')
                    self.network.train()

                # Check if we need to stop training
                if self.quit() or self.sigint:
                    log.info('Reached quitting criteria')
                    return

                # Automatically update registered rates
                self._update_rates()

                # Not enough mini-batches left to have an entire batch
                if (len(loader) - idx) <= self.batch_subdivisions:
                    break

    @property
    def batch(self):
        """ Get current batch number.

        Return:
            int: Computed as self.network.seen // self.batch_size
        """
        return self.network.seen // self.batch_size

    @property
    def batch_subdivisions(self):
        """ Get number of mini-batches per batch.

        Return:
            int: Computed as self.batch_size // self.mini_batch_size
        """
        return self.batch_size // self.mini_batch_size

    @property
    def learning_rate(self):
        """ Get and set the learning rate

        Args:
            lr (Number): Set the learning rate for all values of optimizer.param_groups[i]['lr']

        Return:
            Number: The current learning rate
        """
        return self.__lr

    @learning_rate.setter
    def learning_rate(self, lr):
        log.info(f'Adjusting learning rate to [{lr*self.batch_size}]')
        self.__lr = lr
        for param_group in self.optimizer.param_groups:
            param_group['lr'] = lr

    def add_rate(self, name, steps, values, default=None):
        """ Add a rate to the engine.
        Rates are object attributes that automatically change according to the current batch number.

        Args:
            name (str): Name that will be used for the attribute. You can access the value with self.name
            steps (list): Batches at which the rate should change
            values (list): New values that will be used for the attribute
            default (optional): Default value to use for the rate; Default **None**

        Note:
            You can also set the ``learning_rate`` with this method.
            This will actually use the ``learning_rate`` computed property of this class and set the learning rate of the optimizer. |br|
            This is great for automating adaptive learning rates, and can work in conjunction with pytorch schedulers.

        Example:
            >>> class MyEngine(ln.engine.Engine):
            ...     batch_size = 2
            ...     def process_batch(self, data):
            ...         raise NotImplementedError()
            ...     def train_batch(self):
            ...         raise NotImplementedError()
            >>> net = ln.models.Yolo()
            >>> eng = MyEngine(
            ...     net,
            ...     torch.optim.SGD(net.parameters(), lr=.1),
            ...     None    # Should be dataloader
            ... )
            >>> eng.add_rate('test_rate', [1000, 10000], [100, 500], 50)
            >>> eng.add_rate('learning_rate', [1000, 10000], [.01, .001])
            >>> eng.test_rate
            50
            >>> eng.learning_rate
            0.1
            >>> net.seen = 2000     # batch_size = 2
            >>> eng._update_rates() # Happens automatically during training loop
            >>> eng.test_rate
            100
            >>> eng.learning_rate
            0.01
        """
        if default is not None or not hasattr(self, name):
            setattr(self, name, default)
        if name in self.__rates:
            log.warn(f'{name} rate was already used, overwriting...')

        if len(steps) > len(values):
            diff = len(steps) - len(values)
            values = values + diff * [values[-1]]
            log.warn(f'{name} has more steps than values, extending values to {values}')
        elif len(steps) < len(values):
            values = values[:len(steps)]
            log.warn(f'{name} has more values than steps, shortening values to {values}')

        self.__rates[name] = (steps, values)

    def _update_rates(self):
        """ Update rates according to batch size. |br|
        This function gets automatically called every batch, and should generally not be called by the user.
        """
        for key, (steps, values) in self.__rates.items():
            new_rate = None
            for i in range(len(steps)):
                if self.batch >= steps[i]:
                    new_rate = values[i]
                else:
                    break

            if new_rate is not None and new_rate != getattr(self, key):
                #log.info(f'Adjusting {key} [{new_rate*self.batch_size}]')
                setattr(self, key, new_rate)

    def start(self):
        """ First function that gets called when starting the engine. |br|
            Use it to create your dataloader, set the correct starting values for your rates, etc.
        """
        pass

    @abstractmethod
    def process_batch(self, data):
        """ This function should contain the code to process the forward and backward pass of one (mini-)batch. """
        pass

    @abstractmethod
    def train_batch(self):
        """ This function should contain the code to update the weights of the network. |br|
        Statistical computations, performing backups at regular intervals, etc. also happen here.
        """
        pass

    def test(self):
        """ This function should contain the code to perform an evaluation on your test-set. """
        log.error('test() function is not implemented')

    def quit(self):
        """ This function gets called after every training epoch and decides if the training cycle continues.

        Return:
            Boolean: Whether are not to stop the training cycle

        Note:
            This function gets called before checking the ``self.sigint`` attribute.
            This means you can also check this attribute in this function. |br|
            If it evaluates to **True**, you know the program will exit after this function and you can thus
            perform the necessary actions (eg. save final weights).
        """
        if self.max_batches is not None:
            return self.batch >= self.max_batches
        else:
            return False

    def __sigint_handler(self, signal, frame):
        if not self.sigint:
            log.debug('SIGINT caught. Waiting for gracefull exit')
            self.sigint = True


text:
import re

from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.utils.importlib import import_module
from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed

SESSION_KEY = '_auth_user_id'
BACKEND_SESSION_KEY = '_auth_user_backend'
REDIRECT_FIELD_NAME = 'next'

def load_backend(path):
    i = path.rfind('.')
    module, attr = path[:i], path[i + 1:]
    try:
        mod = import_module(module)
    except ImportError as e:
        raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (path, e))
    except ValueError:
        raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
    try:
        cls = getattr(mod, attr)
    except AttributeError:
        raise ImproperlyConfigured('Module "%s" does not define a "%s" authentication backend' % (module, attr))
    return cls()

def get_backends():
    from django.conf import settings
    backends = []
    for backend_path in settings.AUTHENTICATION_BACKENDS:
        backends.append(load_backend(backend_path))
    if not backends:
        raise ImproperlyConfigured('No authentication backends have been defined. Does AUTHENTICATION_BACKENDS contain anything?')
    return backends

def _clean_credentials(credentials):
    """
    Cleans a dictionary of credentials of potentially sensitive info before
    sending to less secure functions.

    Not comprehensive - intended for user_login_failed signal
    """
    SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
    CLEANSED_SUBSTITUTE = '********************'
    for key in credentials:
        if SENSITIVE_CREDENTIALS.search(key):
            credentials[key] = CLEANSED_SUBSTITUTE
    return credentials

def authenticate(**credentials):
    """
    If the given credentials are valid, return a User object.
    """
    for backend in get_backends():
        try:
            user = backend.authenticate(**credentials)
        except TypeError:
            # This backend doesn't accept these credentials as arguments. Try the next one.
            continue
        except PermissionDenied:
            # This backend says to stop in our tracks - this user should not be allowed in at all.
            return None
        if user is None:
            continue
        # Annotate the user object with the path of the backend.
        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
        return user

    # The credentials supplied are invalid to all backends, fire signal
    user_login_failed.send(sender=__name__,
            credentials=_clean_credentials(credentials))

def login(request, user):
    """
    Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request. Note that data set during
    the anonymous session is retained when the user logs in.
    """
    if user is None:
        user = request.user
    # TODO: It would be nice to support different login methods, like signed cookies.
    if SESSION_KEY in request.session:
        if request.session[SESSION_KEY] != user.pk:
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = user.pk
    request.session[BACKEND_SESSION_KEY] = user.backend
    if hasattr(request, 'user'):
        request.user = user
    user_logged_in.send(sender=user.__class__, request=request, user=user)

def logout(request):
    """
    Removes the authenticated user's ID from the request and flushes their
    session data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.
    user = getattr(request, 'user', None)
    if hasattr(user, 'is_authenticated') and not user.is_authenticated():
        user = None
    user_logged_out.send(sender=user.__class__, request=request, user=user)

    request.session.flush()
    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser()

def get_user_model():
    "Return the User model that is active in this project"
    from django.conf import settings
    from django.db.models import get_model

    try:
        app_label, model_name = settings.AUTH_USER_MODEL.split('.')
    except ValueError:
        raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
    user_model = get_model(app_label, model_name)
    if user_model is None:
        raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL)
    return user_model

def get_user(request):
    from django.contrib.auth.models import AnonymousUser
    try:
        user_id = request.session[SESSION_KEY]
        backend_path = request.session[BACKEND_SESSION_KEY]
        backend = load_backend(backend_path)
        user = backend.get_user(user_id) or AnonymousUser()
    except KeyError:
        user = AnonymousUser()
    return user


text:
.header {
  display: flex;
  justify-content: space-between;

  align-items: center;
  align-content: center;
}

.settingsContainer {
  align-items: flex-start;
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.insulinSettingsContainer {
  width: 25%;
  min-width: 240px;
  margin-bottom: 15px;
}

.basalSettingsContainer {
  flex-basis: 25%;
}

.bolusSettingsContainer {
  display: flex;
  flex-wrap: wrap;
  flex-basis: 75%;
}

.bolusSettingsInnerContainer {
  display: flex;
  flex-flow: row wrap;
  width: 100%;
  gap: 10px;
}

.categoryTitle {
  composes: mediumContrastText from '../../styles/typography.css';
  width: 100%;
  padding-bottom: 10px;
}

.categoryContainer {
  margin-bottom: 10px;
  width: 100%;
  flex: 1;
}

.bolusSettingsInnerContainer .categoryContainer:last-child {
  padding-right: 0;
}

.basalTable {
  composes: basalTable from './settings.css';
}

.basalTable td:first-child, .basalTable th:first-child {
  padding-left: 28px;
}

.settingsTable {
  composes: settingsTable from './settings.css';
}

.settingsTableInverted {
  composes: settingsTableInverted from './settings.css';
}

.settingsTable td:first-child, .settingsTable th:first-child,
.settingsTableInverted td:first-child, .settingsTableInverted th:first-child {
  padding-left: 28px;
}

.singleLineBasalScheduleHeader {
  composes: basalHeaderBackground settingsHeader from './settings.css';
  justify-content: space-between;
}

.automatedSingleLineBasalScheduleHeader {
  composes: automatedBasalHeaderBackground settingsHeader from './settings.css';
  justify-content: space-between;
  font-size: 16px;
  padding: 0;
}

.twoLineBasalScheduleHeader {
  composes: basalHeaderBackground settingsHeaderDecoration settingsHeaderLayout settingsHeaderText from './settings.css';
}

.twoLineBasalScheduleHeader > div:first-child {
  padding-left: 0;
}

.insulinSettingsHeader {
  composes: bolusHeaderBackground settingsHeader from './settings.css';
}

.bolusSettingsHeader {
  composes: bolusHeaderBackground settingsHeader from './settings.css';
}

.automatedBasalHeaderBackground {
  composes: automatedBasalHeaderBackground from './settings.css';
  text-align: left;
  padding-left: 28px;
  padding-top: 8px;
  padding-bottom: 8px
}

.automatedBasalHeaderBackground > span {
  padding-left: 5px;
}

@media print {

  .categoryContainer {
    max-width: 280px;
    min-width: 250px;
    width: 100%;
    margin-bottom: 10px;
    margin-right: 10px;
  }

  .settingsContainer {
    display: block;
  }

  .basalSettingsContainer {
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
    page-break-after: auto;
  }

  .categoryTitle {
    font-weight: normal;
    font-size: 20px;
    color: var(--text-black);
    width: 100%;
    padding-bottom: 10px;
  }
}


text:
namespace BundleTransformer.Autoprefixer.Configuration
{
	using System.Configuration;

	/// <summary>
	/// Configuration settings of Clean CSS-minifier
	/// </summary>
	public sealed class BrowserSettingsCollection : ConfigurationElementCollection
	{
	    protected override ConfigurationElement CreateNewElement()
	    {
	        return new BrowserSettings();
	    }

	    protected override object GetElementKey(ConfigurationElement element)
	    {
            return ((BrowserSettings)element).Definition;
	    }
	}
}


text:
module Dapp
  module Dimg
    class Builder::Base
      attr_reader :dimg

      def initialize(dimg)
        @dimg = dimg
      end

      def before_build_check
      end

      def before_dimg_should_be_built_check
      end

      def before_install?
        false
      end

      def before_install(_image)
        raise
      end

      def before_install_checksum
        raise
      end

      def before_setup?
        false
      end

      def before_setup(_image)
        raise
      end

      def before_setup_checksum
        raise
      end

      def install?
        false
      end

      def install(_image)
        raise
      end

      def install_checksum
        raise
      end

      def setup?
        false
      end

      def setup(_image)
        raise
      end

      def setup_checksum
        raise
      end

      def build_artifact?
        false
      end

      def build_artifact(_image)
        raise
      end

      def build_artifact_checksum
        raise
      end
    end # Builder::Base
  end # Dimg
end # Dapp


text:
package org.apache.commons.vfs2.provider.test;

import java.io.File;

import junit.framework.Test;

import org.apache.commons.AbstractVfsTestCase;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
import org.apache.commons.vfs2.test.ProviderTestSuite;

/**
 * Test cases for the virtual file system provider.
 */
public class VirtualProviderTestCase extends AbstractProviderTestConfig {
    public static Test suite() throws Exception {
        final ProviderTestSuite testSuite = new ProviderTestSuite(new VirtualProviderTestCase());
        testSuite.addTests(JunctionTests.class);
        return testSuite;
    }

    /**
     * Returns the base folder for tests.
     */
    @Override
    public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
        final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
        final FileObject baseFile = manager.toFileObject(baseDir);
        return manager.createVirtualFileSystem(baseFile);
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title>
			Catégorie: librairie

			- hypermégatop, parfois

		</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="description" content="Blogue technologique sur node.js, backbone et autres merveilles Javascript.">
		<meta name="author" content="">
		<link rel="author" href="/humans.txt" />
		<meta name="sendgrid" content="Prove ownership of site to sendgrid.com." />
		<link href="/css/hmt.min.css" rel="stylesheet">

		<link href="/feed.xml" rel="alternate" title="RSS" type="application/rss+xml">

					hypermégatop, parfois

Fil RSS

@PuerkitoBio sur Twitter

Billets dans la catégorie librairie

				<time class="published" datetime='2012-07-12'>
12 juillet 2012
</time>

						Du code et de la tôle à chaudière

En ces deux mois et demi de silence hypermégatopien, je n'ai pas chômé. Je suis parti en guerre contre la tôle à chaudière.

				<time class="published" datetime='2012-04-13'>
13 avril 2012
</time>

						Propriétés calculées avec Backbone

La beauté de l'univers du code libre est que lorsqu'il manque une fonctionnalité, on peut se retrousser les manches, ouvrir le code et l'ajouter. Voici ma petite histoire des propriétés calculées avec Backbone.

				<time class="published" datetime='2012-04-02'>
02 avril 2012
</time>

						implement.js: typage fort et Javascript

L'injection de dépendance avec Javascript a comme conséquence de ne pouvoir assumer que les fonctionnalités offertes par l'instance reçue seront celles attendues.

Pile technologique

Jekyll: usine de pages.

Twitter Bootstrap: rampe de lancement.

Calepin: muse typographique.

JQuery: dictateur du DOM.

Google Code Prettify: maquilleur de code.

LESS: sorcier CSS.

GitHub: foyer d'accueil.

À propos

Le code du site est disponible en logiciel libre.

Le contenu (les articles) est © 2012 Martin Angers .

Reproduction permise avec lien sur l'article d'origine. Une notification serait appréciée.

Pour tout problème d'utilisation, inscrire une anomalie.


text:
class Jobs::ClearCache < Jobs::Job
  def self.run
    Rails.cache.clear
  end
end


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
use Concrete\Core\Http\ResponseAssetGroup;
use Concrete\Core\ImageEditor\ImageEditor;
use Concrete\Core\File\Image\BitmapFormat;
use Whoops\Exception\ErrorException;

$editorid = substr(sha1(time()), 0, 5); // Just enough entropy.

$u = Core::make(Concrete\Core\User\User::class);
$form = Loader::helper('form');
/** @var FileVersion $fv */
$f = $fv->getFile();
$fp = new Permissions($f);
if (!$fp->canEditFileContents()) {
    die(t("Access Denied."));
}
$token = Core::make('token')->generate();

$req = ResponseAssetGroup::get();
$req->requireAsset('core/imageeditor');

/** @var ImageEditor $editor */
if (!isset($editor) || !$editor) {
    $editor = \Core::make('editor/image/core');
}

$filters = $editor->getFilterList();
$controls = $editor->getControlList()

?>

            <div id='<?= $editorid ?>' class='Editor'>

                        <?php
                        if (!$controls) {
                            echo " ";
                        }
                        /** @var \Concrete\Core\ImageEditor\EditorExtensionInterface $control */
                        foreach ((array) $controls as $control) {
                            $control_handle = $control->getHandle();
                            $assets = $control->getAssets();
                            $javascript_asset = $control->getExtensionAsset();

                            foreach ($assets as $asset) {
                                $req->addOutputAsset($asset);
                            }
                            ?>
                            <div class="controlset controlset-<?= $control_handle ?> control control-<?= $control_handle ?>"
                                 data-namespace="<?= $control_handle ?>"
                                 data-src="<?= $javascript_asset->getAssetUrl() ?>">

<?= $control->getName() ?>

                                        <?php
                                        try {
                                            $view = $control->getView();
                                            $view->addScopeItems(array('editor' => $editor, 'fv' => $fv));
                                            echo $view->render();
                                        } catch (ErrorException $e) {
                                            echo t("Invalid View: '{$e->getMessage()}''");
                                        }
                            ?>

                        <?php

                        }
                        ?>

                    <button class='cancel btn'><?= t('Cancel')?></button>
                    <button class='save btn pull-right btn-primary'><?= t('Save')?></button>

<?php
if (empty($settings)) {
    $settings = array();
}
$fnames = array();

foreach ($filters as $filter) {
    $assets = $filter->getAssets();
    $extension_asset = $filter->getExtensionAsset();
    $filter_handle = $filter->getHandle();

    foreach ($assets as $handle => $asset) {
        $req->addOutputAsset($asset);
    }

    $fnames[$filter_handle] = array(
        'src' => $extension_asset->getAssetURL(),
        'name' => h($filter->getName()),
        "selector" => ".filter.filter-{$filter_handle}",
    );
}
$url = $fv->getRelativePath();
?>


text:
.class Landroid/media/MediaPluginDLNA$switchDimModeTimerTask;
.super Ljava/util/TimerTask;
.source "MediaPluginDLNA.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/MediaPluginDLNA;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "switchDimModeTimerTask"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/media/MediaPluginDLNA;

# direct methods
.method private constructor <init>(Landroid/media/MediaPluginDLNA;)V
    .locals 0
    .parameter

    .prologue
    .line 616
    iput-object p1, p0, Landroid/media/MediaPluginDLNA$switchDimModeTimerTask;->this$0:Landroid/media/MediaPluginDLNA;

    invoke-direct {p0}, Ljava/util/TimerTask;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/media/MediaPluginDLNA;Landroid/media/MediaPluginDLNA$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 616
    invoke-direct {p0, p1}, Landroid/media/MediaPluginDLNA$switchDimModeTimerTask;-><init>(Landroid/media/MediaPluginDLNA;)V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 2

    .prologue
    .line 619
    iget-object v0, p0, Landroid/media/MediaPluginDLNA$switchDimModeTimerTask;->this$0:Landroid/media/MediaPluginDLNA;

    #calls: Landroid/media/MediaPluginDLNA;->getState()I
    invoke-static {v0}, Landroid/media/MediaPluginDLNA;->access$900(Landroid/media/MediaPluginDLNA;)I

    move-result v0

    const/16 v1, 0x1010

    if-ne v0, v1, :cond_0

    .line 620
    iget-object v0, p0, Landroid/media/MediaPluginDLNA$switchDimModeTimerTask;->this$0:Landroid/media/MediaPluginDLNA;

    #calls: Landroid/media/MediaPluginDLNA;->enterDimMode()V
    invoke-static {v0}, Landroid/media/MediaPluginDLNA;->access$1200(Landroid/media/MediaPluginDLNA;)V

    .line 621
    :cond_0
    return-void
.end method


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#DDDDDD"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="20dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:paddingRight="20dp"
        android:background="#FFFFFF"
        android:paddingBottom="14dp"
        android:paddingTop="14dp"
        android:gravity="center_vertical"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawablePadding="8dp"
            android:paddingRight="8dp"
            android:text="开户银行    "/>
        <View
            android:layout_width="0.8dp"
            android:layout_height="match_parent"
            android:background="#AAAAAAAA"
            android:paddingBottom="1.5dp"
            android:paddingTop="1.5dp"/>

        <EditText
            android:layout_marginLeft="4dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入开户银行"
            android:background="@null"
            android:textColorHint="#FFFFFF"
            android:id="@+id/et_kaihuhang"/>
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#DDDDDD">

    </View>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:layout_marginBottom="20dp"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingBottom="14dp"
            android:paddingTop="14dp"
            android:gravity="center_vertical"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawablePadding="8dp"
                android:paddingRight="8dp"
                android:text="银行卡号    "/>
            <View
                android:layout_width="0.8dp"
                android:layout_height="match_parent"
                android:background="#AAAAAAAA"
                android:paddingBottom="1.5dp"
                android:paddingTop="1.5dp"/>

            <EditText
                android:layout_marginLeft="4dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入银行卡号"
                android:background="@null"
                android:textColorHint="#FFFFFF"
                android:id="@+id/et_yhkh"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#66666666">

        </View>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingBottom="14dp"
            android:paddingTop="14dp"
            android:gravity="center_vertical"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawablePadding="8dp"
                android:paddingRight="8dp"
                android:text="持卡人姓名"/>
            <View
                android:layout_width="0.8dp"
                android:layout_height="match_parent"
                android:background="#AAAAAAAA"
                android:paddingBottom="1.5dp"
                android:paddingTop="1.5dp"/>

            <EditText
                android:layout_marginLeft="4dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入持卡人姓名"
                android:background="@null"
                android:textColorHint="#FFFFFF"
                android:id="@+id/et_ckrname"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#66666666">

        </View>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingBottom="14dp"
            android:paddingTop="14dp"
            android:gravity="center_vertical"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawablePadding="8dp"
                android:paddingRight="8dp"
                android:text="证件类型    "/>
            <View
                android:layout_width="0.8dp"
                android:layout_height="match_parent"
                android:background="#AAAAAAAA"
                android:paddingBottom="1.5dp"
                android:paddingTop="1.5dp"/>

            <TextView
                android:layout_marginLeft="4dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:text="身份证"
                android:textColor="#666666" />
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#66666666">

        </View>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingBottom="14dp"
            android:paddingTop="14dp"
            android:gravity="center_vertical"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawablePadding="8dp"
                android:paddingRight="8dp"
                android:text="证件号码    "/>
            <View
                android:layout_width="0.8dp"
                android:layout_height="match_parent"
                android:background="#AAAAAAAA"
                android:paddingBottom="1.5dp"
                android:paddingTop="1.5dp"/>

            <EditText
                android:layout_marginLeft="4dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入证件号"
                android:background="@null"
                android:textColorHint="#FFFFFF"
                android:id="@+id/et_sfz"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#66666666">

        </View>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingBottom="14dp"
            android:paddingTop="14dp"
            android:gravity="center_vertical"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawablePadding="8dp"
                android:paddingRight="8dp"
                android:text="手机号        "/>
            <View
                android:layout_width="0.8dp"
                android:layout_height="match_parent"
                android:background="#AAAAAAAA"
                android:paddingBottom="1.5dp"
                android:paddingTop="1.5dp"/>

            <EditText
                android:layout_marginLeft="4dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="请输入手机号"
                android:background="@null"
                android:textColorHint="#FFFFFF"
                android:id="@+id/et_phone"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#66666666">

        </View>
    </LinearLayout>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="20dp"
        android:paddingBottom="14dp"
        android:textColor="#555555"
        android:text="温馨提示"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:paddingLeft="20dp"
        android:textColor="#555555"
        android:text="请您保护好自己的账户安全,本公司不会以任何名义向您索取银行卡账户、密码、以及支付密码。"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:id="@+id/btn_add"
        android:gravity="center"
        android:layout_marginBottom="0dp"
        android:background="@drawable/register_btn_bg_selector"
        android:textColor="#FFFFFF"
        android:text="确定"/>
</LinearLayout>


text:
<?php
 /**
 magia_version: 0.0.8
 **/ ?>

<?php _t("Buscar"); ?>

<form class="" action="index.php" method="get">
<input type="hidden" name="p" value="cambio_claves">
<input type="hidden" name="c" value="buscar">

     <?php _t("Usuario");?>
       <input type="text" class="form-control" name="cambio_claves_usuario" id="cambio_claves_usuario" placeholder="<?php _t("Usuario"); ?> ">

     <?php _t("Codigo");?>
       <input type="text" class="form-control" name="cambio_claves_codigo" id="cambio_claves_codigo" placeholder="<?php _t("Codigo"); ?> ">

     <?php _t("Fecha_solicitud");?>
       <input type="text" class="form-control" name="cambio_claves_fecha_solicitud" id="cambio_claves_fecha_solicitud" placeholder="<?php _t("Fecha_solicitud"); ?> ">

     <?php _t("Codigo_usado");?>
       <input type="text" class="form-control" name="cambio_claves_codigo_usado" id="cambio_claves_codigo_usado" placeholder="<?php _t("Codigo_usado"); ?> ">

       <button type="submit" class="btn btn-primary"><?php _t("Buscar"); ?></button>
 </form>


text:
<?php
/**
 * Class containing methods for fetching and storing
 * extension Category information.
 *
 * @package extensionmanager
 */
class ExtensionCategory extends DataObject
{

    public static $db = array(
        'CategoryName' => 'Varchar(100)',
        );

    public static $has_many = array(
        'Extensions' => 'ExtensionData',
        );

    public static $searchable_fields = array(
        'CategoryName' => array(
            'title' => 'Category Name',
            'field' => 'TextField',
            'filter' => 'PartialMatchFilter',
            ),
        'Extensions.Name' => array(
            'title' => 'Extension Name',
            'field' => 'TextField',
            'filter' => 'PartialMatchFilter',
            )
        );

    public static $summary_fields = array(
        'CategoryName' => array(
            'title' => 'Category Name',
        ),
    );
}


text:
const sign = require('ethjs-signer').sign;
const SignerProvider = require('ethjs-provider-signer');

module.exports = (options) => ({
  entry: [
    'environments.json',
    'contracts',
  ],
  output: {
    path: './',
    filename: 'environments.json',
  },
  module: {
    loaders: [
      { test: /\.(json)$/, loader: '../loaders/solc-json.js' },
    ],
    environment: {
      name: 'ropsten',
      provider: new SignerProvider('http://localhost:8545', {
        accounts: (cb) => cb(null, ['0x2233eD250Ea774146B0fBbC1da0Ffa6a81514cCC']),
        signTransaction: (rawTx, cb) => {
          cb(null, sign(rawTx, '0x..privateKey...'));
        },
      }),
      defaultTxObject: {
        from: 0,
        gas: 3000000,
      },
    },
    deployment: (deploy, contracts, done) => {
      deploy(contracts.SimpleStore).then((simpleStoreInstance) => {
        console.log(simpleStoreInstance); // eslint-disable-line

        done();
      });
    },
  },
  plugins: [
    new options.plugins.JSONMinifier(),
  ],
});