code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
;(function() {
'use strict';
const nodemailer = require('nodemailer');
const htmlToText = require('nodemailer-html-to-text').htmlToText;
module.exports = Extension => class Mailer extends Extension {
_constructor() {
this.send.context = Extension.ROUTER;
}
send(ctx) {
let subject = ctx.arg('subject');
let formKeys = Object.keys(ctx.body)
.filter(key => key.startsWith(ctx.arg('prefix')))
.reduce((map, key) => map.set(key.slice(ctx.arg('prefix').length), ctx.body[key]), new Map());
formKeys.forEach((key, value) => subject = subject.replace(`{${key}}`, value));
let content = ctx.render(formKeys);
let transporter = nodemailer.createTransport();
transporter.use('compile', htmlToText());
ctx.logger.log(ctx.logger.debug, 'sending mail...');
transporter.sendMail({
from: ctx.arg('from'),
to: ctx.arg('to'),
subject: subject,
html: content
}, function(err, info) {
if (err) {
ctx.logger.log(ctx.logger.error, 'can\'t send mail: {0}', err);
} else {
ctx.logger.log(ctx.logger.info, 'mail sent: {0}', info.response);
}
ctx.set('status', err);
return ctx.success();
});
}
}
})();
| xabinapal/verlag | extensions/mailer.js | JavaScript | mit | 1,288 |
<?php
include('dbconnect.php');
include('_admin_session.php');
if(isset($_POST['form1'])){
$acc_date = $_POST['acc_date'];
$acc_desc = $_POST['acc_desc'];
$acc_amo = $_POST['acc_amo'];
$acc_dr_cr = $_POST['acc_dr_cr'];
$acc_total = $_POST['acc_total'];
$result = mysql_query("insert into accounts (acc_date, acc_desc, acc_amo, acc_dr_cr, acc_total) values('$acc_date','$acc_desc','$acc_amo','$acc_dr_cr','$acc_total')")or die(mysql_error());
if ($result) {
echo ("<p style='font-size:20px;'>Accounts Data input successfully</p>");
} else {
echo ("<p style='font-size:20px;'>Accounts Data input Failed</p>");
}
}
//header("location: index.php?action=_accounts_view");
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>প্রতিষ্ঠানের একাউন্টস</title>
<script type="text/javascript">
function confirm_del() {
return confirm('Do you want to delete this data ?');
}
</script>
</head>
<body>
<h2>প্রতিষ্ঠানের একাউন্টস</h2>
<form action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>তারিখ: </td>
<td><input type="text" name="acc_date" placeholder="ex: ১২/০৯।২০১৫ " required /></td>
</tr>
<tr>
<td>টাকার বিবরণ: </td>
<td><input type="text" name="acc_desc" placeholder="ex: টাকার বিবরণ লিখুন " required /></td>
</tr>
<tr>
<td>পরিমান: </td>
<td><input type="text" name="acc_amo" placeholder="ex: ৪,০০০ /=" required /></td>
</tr>
<tr>
<td>জমা/ খরচ: </td>
<td>
<select name="acc_dr_cr" id="">
<option value="--Select--">--Select A Option--</option>
<option value="জমা">জমা</option>
<option value="খরচ">খরচ</option>
</select>
</td>
</tr>
<tr>
<td>মোট পরিমাণ: </td>
<td><input type="text" name="acc_total" placeholder="ex: ১২,০০০ /=" required /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="সেভ করুন" name="form1"/></td>
</tr>
</table>
</form>
<br />
<table border="1" id="mytable">
<tr>
<th>ক্রমিক নং</th>
<th>তারিখ</th>
<th>টাকার বিবরণ</th>
<th>পরিমান</th>
<th>জমা/ খরচ</th>
<th>মোট পরিমাণ</th>
<th>নিয়ন্ত্রণ করুন</th>
</tr>
<?php
$i = 0;
$result= mysql_query("select * from accounts" ) or die (mysql_error());
while ($row = mysql_fetch_array ($result)){
$i++;
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $row['acc_date'];?></td>
<td><?php echo $row['acc_desc'];?></td>
<td><?php echo $row['acc_amo'];?>/=</td>
<td><?php echo $row['acc_dr_cr'];?></td>
<td><?php echo $row['acc_total'];?>/=</td>
<td>
<a href="_accounts_edit.php?id=<?php echo $row['acc_id'];?>">এডিট </a> |
<a onClick="return confirm_del();" href="_accounts_del.php?id=<?php echo $row['acc_id'];?>">ডিলিট </a>
</td>
</tr>
<?php } ?>
</table>
</body>
</html> | saidurwd/muradschool | backend/_accounts_view.php | PHP | mit | 3,202 |
require 'spec_helper'
require_relative '../../lib/concerns/linkable'
describe Linkable do
context 'link' do
class Example
include Linkable
def initialize(response)
@response = response
end
end
it 'removes all \ from strings' do
e = Example.new("\"https:\\/\\/ead.local.co\\/videos\\/aulas\\/cooolllllller\\/asdfasdf.pdf?secure=asdfasdf\"")
expect(e.link).to eq('https://ead.local.co/videos/aulas/cooolllllller/asdfasdf.pdf?secure=asdfasdf')
end
end
end
| fortesinformatica/iesde | spec/concerns/linkable_spec.rb | Ruby | mit | 514 |
from django import forms
class SearchForm(forms.Form):
criteria = forms.CharField(label='Criteria', max_length=100, required=True) | chaocodes/playlist-manager-django | manager/search/forms.py | Python | mit | 135 |
# frozen_string_literal: true
module DropletKit
class DomainMapping
include Kartograph::DSL
kartograph do
mapping Domain
root_key plural: 'domains', singular: 'domain', scopes: [:read]
property :name, scopes: [:read, :create]
property :ttl, scopes: [:read]
property :zone_file, scopes: [:read]
property :ip_address, scopes: [:create]
end
end
end | digitalocean/droplet_kit | lib/droplet_kit/mappings/domain_mapping.rb | Ruby | mit | 400 |
package com.example.author.boundary;
import com.example.author.entity.Author;
import com.example.author.repository.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.IdGenerator;
import java.util.Collection;
import java.util.UUID;
/**
* Implementation for {@link AuthorService}.
*/
@Service
@Transactional(readOnly = true)
public class AuthorServiceImpl implements AuthorService {
private final AuthorRepository authorRepository;
private final IdGenerator idGenerator;
/**
* Constructor.
*
* @param authorRepository the {@link AuthorRepository}
* @param idGenerator the {@link IdGenerator}
*/
@Autowired
public AuthorServiceImpl(AuthorRepository authorRepository, IdGenerator idGenerator) {
this.authorRepository = authorRepository;
this.idGenerator = idGenerator;
}
@Transactional
@Override
public Author createAuthor(Author author) {
if (author.getIdentifier() == null) {
author.setIdentifier(idGenerator.generateId());
}
return this.authorRepository.save(author);
}
@Override
public Author findByIdentifier(UUID identifier) {
return this.authorRepository.findByIdentifier(identifier);
}
@Override
public Collection<Author> findAllAuthors() {
return this.authorRepository.findAll();
}
@Override
public Collection<Author> findByLastname(String lastName) {
return this.authorRepository.findByLastname(lastName);
}
@Transactional
@Override
public boolean deleteAuthor(UUID identifier) {
return this.authorRepository.deleteByIdentifier(identifier);
}
}
| andifalk/spring-rest-docs-demo | src/main/java/com/example/author/boundary/AuthorServiceImpl.java | Java | mit | 1,838 |
using System.Collections.Generic;
using BizHawk.Emulation.Common;
namespace BizHawk.Emulation.Cores.Computers.AmstradCPC
{
/// <summary>
/// CPCHawk: Core Class
/// * Controllers *
/// </summary>
public partial class AmstradCPC
{
/// <summary>
/// The one CPCHawk ControllerDefinition
/// </summary>
public ControllerDefinition AmstradCPCControllerDefinition
{
get
{
ControllerDefinition definition = new ControllerDefinition();
definition.Name = "AmstradCPC Controller";
// joysticks
List<string> joys1 = new List<string>
{
// P1 Joystick
"P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Fire1", "P1 Fire2", "P1 Fire3"
};
foreach (var s in joys1)
{
definition.BoolButtons.Add(s);
definition.CategoryLabels[s] = "J1";
}
List<string> joys2 = new List<string>
{
// P2 Joystick
"P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Fire",
};
foreach (var s in joys2)
{
definition.BoolButtons.Add(s);
definition.CategoryLabels[s] = "J2";
}
// keyboard
List<string> keys = new List<string>
{
// http://www.cpcwiki.eu/index.php/Programming:Keyboard_scanning
// http://www.cpcwiki.eu/index.php/File:Grimware_cpc464_version3_case_top.jpg
// Keyboard - row 1
"Key ESC", "Key 1", "Key 2", "Key 3", "Key 4", "Key 5", "Key 6", "Key 7", "Key 8", "Key 9", "Key 0", "Key Dash", "Key Hat", "Key CLR", "Key DEL",
// Keyboard - row 2
"Key TAB", "Key Q", "Key W", "Key E", "Key R", "Key T", "Key Y", "Key U", "Key I", "Key O", "Key P", "Key @", "Key LeftBracket", "Key RETURN",
// Keyboard - row 3
"Key CAPSLOCK", "Key A", "Key S", "Key D", "Key F", "Key G", "Key H", "Key J", "Key K", "Key L", "Key Colon", "Key SemiColon", "Key RightBracket",
// Keyboard - row 4
"Key SHIFT", "Key Z", "Key X", "Key C", "Key V", "Key B", "Key N", "Key M", "Key Comma", "Key Period", "Key ForwardSlash", "Key BackSlash",
// Keyboard - row 5
"Key SPACE", "Key CONTROL",
// Keyboard - Cursor
"Key CURUP", "Key CURDOWN", "Key CURLEFT", "Key CURRIGHT", "Key COPY",
// Keyboard - Numpad
"Key NUM0", "Key NUM1", "Key NUM2", "Key NUM3", "Key NUM4", "Key NUM5", "Key NUM6", "Key NUM7", "Key NUM8", "Key NUM9", "Key NUMPERIOD", "KEY ENTER"
};
foreach (var s in keys)
{
definition.BoolButtons.Add(s);
definition.CategoryLabels[s] = "Keyboard";
}
// Power functions
List<string> power = new List<string>
{
// Power functions
"Reset", "Power"
};
foreach (var s in power)
{
definition.BoolButtons.Add(s);
definition.CategoryLabels[s] = "Power";
}
// Datacorder (tape device)
List<string> tape = new List<string>
{
// Tape functions
"Play Tape", "Stop Tape", "RTZ Tape", "Record Tape", "Insert Next Tape",
"Insert Previous Tape", "Next Tape Block", "Prev Tape Block", "Get Tape Status"
};
foreach (var s in tape)
{
definition.BoolButtons.Add(s);
definition.CategoryLabels[s] = "Datacorder";
}
// Datacorder (tape device)
List<string> disk = new List<string>
{
// Tape functions
"Insert Next Disk", "Insert Previous Disk", /*"Eject Current Disk",*/ "Get Disk Status"
};
foreach (var s in disk)
{
definition.BoolButtons.Add(s);
definition.CategoryLabels[s] = "Amstrad Disk Drive";
}
return definition;
}
}
}
/// <summary>
/// The possible joystick types
/// </summary>
public enum JoystickType
{
NULL,
Joystick1,
Joystick2
}
}
| ircluzar/RTC3 | Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Controllers.cs | C# | mit | 4,843 |
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <math.h>
#include<cstdio>
#include<string.h>
using namespace std;
int main(){
int in=0,x,o=0,n;
cin>>n;
for (int i = 0; i < n; i++) {
cin>>x;
if(x>=10&&x<=20)
in++;
else
o++;
}
printf("%d in\n%d out\n",in,o);
return 0;
}
| ahmedengu/URI-solutions | Beginner/1072 - Interval 2.cpp | C++ | mit | 354 |
namespace p03_WildFarm.Models.Foods
{
public class Vegetable : Food
{
public Vegetable(int quantity) : base(quantity)
{
}
}
} | DimitarIvanov8/software-university | C#_OOP_Basics/Polymorphism/p03_WildFarm/Models/Foods/Vegetable.cs | C# | mit | 164 |
<?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2013 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version 1.7.9, 2013-06-02
*/
/** PHPExcel root directory */
if (!defined('PHPEXCEL_ROOT')) {
/**
* @ignore
*/
define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}
/**
* PHPExcel_Reader_SYLK
*
* @category PHPExcel
* @package PHPExcel_Reader
* @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Reader_SYLK extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader
{
/**
* Input encoding
*
* @var string
*/
private $_inputEncoding = 'ANSI';
/**
* Sheet index to read
*
* @var int
*/
private $_sheetIndex = 0;
/**
* Formats
*
* @var array
*/
private $_formats = array();
/**
* Format Count
*
* @var int
*/
private $_format = 0;
/**
* Create a new PHPExcel_Reader_SYLK
*/
public function __construct() {
$this->_readFilter = new PHPExcel_Reader_DefaultReadFilter();
}
/**
* Validate that the current file is a SYLK file
*
* @return boolean
*/
protected function _isValidFormat()
{
// Read sample data (first 2 KB will do)
$data = fread($this->_fileHandle, 2048);
// Count delimiters in file
$delimiterCount = substr_count($data, ';');
if ($delimiterCount < 1) {
return FALSE;
}
// Analyze first line looking for ID; signature
$lines = explode("\n", $data);
if (substr($lines[0],0,4) != 'ID;P') {
return FALSE;
}
return TRUE;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'ANSI')
{
$this->_inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->_inputEncoding;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
*
* @param string $pFilename
* @throws PHPExcel_Reader_Exception
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
rewind($fileHandle);
$worksheetInfo = array();
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
// Loop through file
$rowData = array();
// loop through one row (line) at a time in the file
$rowIndex = 0;
while (($rowData = fgets($fileHandle)) !== FALSE) {
$columnIndex = 0;
// convert SYLK encoded $rowData to UTF-8
$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t",str_replace('짚',';',str_replace(';',"\t",str_replace(';;','짚',rtrim($rowData)))));
$dataType = array_shift($rowData);
if ($dataType == 'C') {
// Read cell value data
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' :
$columnIndex = substr($rowDatum,1) - 1;
break;
case 'R' :
case 'Y' :
$rowIndex = substr($rowDatum,1);
break;
}
$worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex);
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex);
}
}
}
$worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
// Close file
fclose($fileHandle);
return $worksheetInfo;
}
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel_Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel
$objPHPExcel = new PHPExcel();
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel $objPHPExcel
* @return PHPExcel
* @throws PHPExcel_Reader_Exception
*/
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
{
// Open file
$this->_openFile($pFilename);
if (!$this->_isValidFormat()) {
fclose ($this->_fileHandle);
throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->_fileHandle;
rewind($fileHandle);
// Create new PHPExcel
while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex( $this->_sheetIndex );
$fromFormats = array('\-', '\ ');
$toFormats = array('-', ' ');
// Loop through file
$rowData = array();
$column = $row = '';
// loop through one row (line) at a time in the file
while (($rowData = fgets($fileHandle)) !== FALSE) {
// convert SYLK encoded $rowData to UTF-8
$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t",str_replace('짚',';',str_replace(';',"\t",str_replace(';;','짚',rtrim($rowData)))));
$dataType = array_shift($rowData);
// Read shared styles
if ($dataType == 'P') {
$formatArray = array();
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'P' : $formatArray['numberformat']['code'] = str_replace($fromFormats,$toFormats,substr($rowDatum,1));
break;
case 'E' :
case 'F' : $formatArray['font']['name'] = substr($rowDatum,1);
break;
case 'L' : $formatArray['font']['size'] = substr($rowDatum,1);
break;
case 'S' : $styleSettings = substr($rowDatum,1);
for ($i=0;$i<strlen($styleSettings);++$i) {
switch ($styleSettings{$i}) {
case 'I' : $formatArray['font']['italic'] = true;
break;
case 'D' : $formatArray['font']['bold'] = true;
break;
case 'T' : $formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'B' : $formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'L' : $formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'R' : $formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
$this->_formats['P'.$this->_format++] = $formatArray;
// Read cell value data
} elseif ($dataType == 'C') {
$hasCalculatedValue = false;
$cellData = $cellDataFormula = '';
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
case 'K' : $cellData = substr($rowDatum,1);
break;
case 'E' : $cellDataFormula = '='.substr($rowDatum,1);
// Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"',$cellDataFormula);
$key = false;
foreach($temp as &$value) {
// Only count/replace in alternate array entries
if ($key = !$key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/',$value, $cellReferences,PREG_SET_ORDER+PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
// the formula
$cellReferences = array_reverse($cellReferences);
// Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
// then modify the formula to use that new reference
foreach($cellReferences as $cellReference) {
$rowReference = $cellReference[2][0];
// Empty R reference is the current row
if ($rowReference == '') $rowReference = $row;
// Bracketed R references are relative to the current row
if ($rowReference{0} == '[') $rowReference = $row + trim($rowReference,'[]');
$columnReference = $cellReference[4][0];
// Empty C reference is the current column
if ($columnReference == '') $columnReference = $column;
// Bracketed C references are relative to the current column
if ($columnReference{0} == '[') $columnReference = $column + trim($columnReference,'[]');
$A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference;
$value = substr_replace($value,$A1CellReference,$cellReference[0][1],strlen($cellReference[0][0]));
}
}
}
unset($value);
// Then rebuild the formula string
$cellDataFormula = implode('"',$temp);
$hasCalculatedValue = true;
break;
}
}
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
$cellData = PHPExcel_Calculation::_unwrapResult($cellData);
// Set cell value
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
if ($hasCalculatedValue) {
$cellData = PHPExcel_Calculation::_unwrapResult($cellData);
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData);
}
// Read cell formatting
} elseif ($dataType == 'F') {
$formatStyle = $columnWidth = $styleSettings = '';
$styleData = array();
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
case 'P' : $formatStyle = $rowDatum;
break;
case 'W' : list($startCol,$endCol,$columnWidth) = explode(' ',substr($rowDatum,1));
break;
case 'S' : $styleSettings = substr($rowDatum,1);
for ($i=0;$i<strlen($styleSettings);++$i) {
switch ($styleSettings{$i}) {
case 'I' : $styleData['font']['italic'] = true;
break;
case 'D' : $styleData['font']['bold'] = true;
break;
case 'T' : $styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'B' : $styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'L' : $styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'R' : $styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
if (($formatStyle > '') && ($column > '') && ($row > '')) {
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
if (isset($this->_formats[$formatStyle])) {
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->_formats[$formatStyle]);
}
}
if ((!empty($styleData)) && ($column > '') && ($row > '')) {
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData);
}
if ($columnWidth > '') {
if ($startCol == $endCol) {
$startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
} else {
$startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
$endCol = PHPExcel_Cell::stringFromColumnIndex($endCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
do {
$objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
} while ($startCol != $endCol);
}
}
} else {
foreach($rowData as $rowDatum) {
switch($rowDatum{0}) {
case 'C' :
case 'X' : $column = substr($rowDatum,1);
break;
case 'R' :
case 'Y' : $row = substr($rowDatum,1);
break;
}
}
}
}
// Close file
fclose($fileHandle);
// Return
return $objPHPExcel;
}
/**
* Get sheet index
*
* @return int
*/
public function getSheetIndex() {
return $this->_sheetIndex;
}
/**
* Set sheet index
*
* @param int $pValue Sheet index
* @return PHPExcel_Reader_SYLK
*/
public function setSheetIndex($pValue = 0) {
$this->_sheetIndex = $pValue;
return $this;
}
}
| cigiko/brdnc.cafe24.com | os/PHPExcel/Classes/PHPExcel/Reader/SYLK.php | PHP | mit | 14,181 |
package com.polydes.common.comp.utils;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
public class HierarchyLeaveListener extends TemporaryAWTListener implements FocusListener
{
private boolean inHierarchy; //was the last click in the component's hierarchy
private final Component component;
private final Runnable callback;
public HierarchyLeaveListener(Component component, final Runnable callback)
{
super(AWTEvent.MOUSE_EVENT_MASK);
this.component = component;
this.callback = callback;
component.addFocusListener(this);
}
@Override
public void eventDispatched(AWTEvent e)
{
if(e instanceof MouseEvent)
{
MouseEvent me = (MouseEvent) e;
if(me.getClickCount() > 0 && e.toString().contains("PRESSED"))
{
Component c = (Component) me.getSource();
if(inHierarchy != SwingUtils.isDescendingFrom(c, component))
{
inHierarchy = !inHierarchy;
if(!inHierarchy)
callback.run();
}
}
}
}
@Override
public void dispose()
{
super.dispose();
component.removeFocusListener(this);
}
@Override
public void focusGained(FocusEvent e)
{
inHierarchy = true;
start();
}
@Override
public void focusLost(FocusEvent e)
{
if(!inHierarchy)
stop();
}
}
| justin-espedal/polydes | Common/src/com/polydes/common/comp/utils/HierarchyLeaveListener.java | Java | mit | 1,420 |
import {bindable} from 'aurelia-framework';
export class SideBarLeft {
@bindable router;
@bindable layoutCnf = {};
}
| hoalongntc/aurelia-material | src/components/layout/sidebar-left.js | JavaScript | mit | 122 |
/* globals document, ajaxurl, tinymce, window */
define([
'jquery',
'modal',
'jquery-ui.sortable'
], function ($, modal) {
return function(areas, callback) {
var $areas = $(areas).filter(':not(.initialized)');
$areas.addClass('initialized');
var updateData = function() {
if(typeof tinymce !== 'undefined' && tinymce.get('content')) {
//use WordPress native beforeunload warning if content is modified
tinymce.get('content').isNotDirty = false;
}
var data = {};
$areas.each(function () {
var col = [];
$(this).find('> ul, > div > ul').find('> li[data-widget]:not(.removed)').each(function () {
col.push({
"widgetId": $(this).data('widget'),
"instance": $(this).data('instance')
});
});
data[$(this).data('id')] = col;
});
callback(data);
};
$areas.find('> ul, > div > ul').sortable({
connectWith: $areas.find('> ul, > div > ul'),
placeholder: "neochic-woodlets-placeholder",
delay: 250,
update: updateData,
receive: function (e, ui) {
var $area = $(this).closest('.woodlets-content-area');
var widgetId = ui.item.data('widget');
var allowed = $area.data('allowed');
if ($.inArray(widgetId, allowed) < 0) {
ui.sender.sortable("cancel");
}
}
});
$areas.on('click', '.add-element', function (e) {
var $button = $(this);
if ($button.hasClass('blocked')) {
return;
}
$button.addClass('blocked');
e.preventDefault();
var $area = $(this).closest('.woodlets-content-area');
$.ajax({
method: "post",
url: ajaxurl,
data: {
action: "neochic_woodlets_get_widget_list",
allowed: $area.data('allowed')
}
}).done(function (data) {
var $content = $(data);
var selectWidget = function($widget, preventClose) {
var widget = $widget.closest('.widget').data('widget');
$button.removeClass('blocked');
$.ajax({
method: "post",
url: ajaxurl,
data: {
"action": "neochic_woodlets_get_widget_preview",
"widget": widget,
"instance": null
}
}).done(function (result) {
var item = $(result);
$area.find('> ul, > div > ul').append(item);
updateData();
if (!preventClose) {
modal.close();
}
item.trigger('click');
});
};
var $widgets = $content.find('.widget-top');
if ($widgets.length === 1) {
selectWidget($widgets, true);
return;
}
$content.on('click', '.widget-top', function () {
selectWidget($(this));
});
$content.on('click', '.cancel', function() {
modal.close();
});
modal.open($content, 'Add item');
});
});
$areas.on('click', '.delete', function () {
var removed = $(this).closest('.neochic-woodlets-widget');
removed.addClass('removed');
updateData();
});
$areas.on('click', '.revert-removal a', function() {
var reverted = $(this).closest('.neochic-woodlets-widget');
//we wan't the click event to bubble first
window.setTimeout(function() {
reverted.removeClass('removed');
updateData();
}, 4);
});
$areas.on('click', '> ul > li.neochic-woodlets-widget, > div > ul > li.neochic-woodlets-widget', function (e) {
var el = $(this);
if (el.hasClass('blocked') || el.hasClass('removed')) {
return;
}
el.addClass('blocked');
/*
* stop propagation to prevent widget getting collapsed by WordPress
*/
e.stopPropagation();
/*
* do not open widget form if an action (like "delete") is clicked
*/
if (!$(e.target).is('.edit') && $(e.target).closest('.row-actions').length > 0) {
return;
}
var widget = $(this).data('widget');
//this should be done more elegant!
var name = $(this).find(".widget-title h4").text();
var data = {
action: "neochic_woodlets_get_widget_form",
widget: widget,
instance: JSON.stringify(el.data('instance'))
};
var pageIdEle = $("#post_ID");
if (pageIdEle.length) {
data.woodletsPageId = pageIdEle.val();
}
$.ajax({
method: "post",
url: ajaxurl,
data: data
}).done(function (data) {
var form = $('<form>' + data + '<span class="button cancel">Cancel</span> <button type="submit" class="button button-primary">Save</button></form>');
form.on('submit', function (e) {
$(document).trigger('neochic-woodlets-form-end', form);
$.ajax({
method: "post",
url: ajaxurl,
data: $(this).serialize() + '&widget=' + widget + '&action=neochic_woodlets_get_widget_update' + (pageIdEle.length ? '&woodletsPageId=' + pageIdEle.val() : "")
}).done(function (result) {
var instance = $.parseJSON(result);
el.data('instance', instance);
var previewData = {
"action": "neochic_woodlets_get_widget_preview",
"widget": widget,
"instance": JSON.stringify(instance)
};
if (pageIdEle.length) {
previewData.woodletsPageId = pageIdEle.val();
}
$.ajax({
method: "post",
url: ajaxurl,
data: previewData
}).done(function (result) {
el.replaceWith($(result));
});
modal.close();
updateData();
});
e.preventDefault();
});
form.on('click', '.cancel', function() {
modal.close();
});
modal.open(form, name);
$(document).trigger('neochic-woodlets-form-init', form);
el.removeClass('blocked');
});
});
};
});
| Neochic/Woodlets | js/content-area-manager.js | JavaScript | mit | 7,553 |
Factory.define :content_element_text do |p|
p.content_element { |c| c.association(:content_element, :element_type => "ContentElementText") }
end | dkd/palani | spec/factories/content_element_text_factory.rb | Ruby | mit | 146 |
<?php
include('head.php');
global $TPL;
?>
<div class="page-header">
<h1>Dateiliste</h1>
</div>
<?php
if($_SESSION['login_msg']) {
$_SESSION['login_msg']=false;
?>
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Erfolgreich eingeloggt.</h4>
Willkommen
<?php echo $_SESSION['whoami']; ?>
</div>
<?php
}
?>
<p>Folgende Dateien wurden gefunden:</p>
<?php
include('foot.php');
?>
<script type="text/javascript">
var filelist = <?php echo json_encode($TPL['files']) . ';';
?>
</script>
<script src="tpl/default/js/filelist.js"></script> | jnugh/php-miniupload | tpl/default/list.php | PHP | mit | 603 |
(function() {
'use strict';
angular
.module('material')
.controller('MainController', MainController);
/** @ngInject */
function MainController($timeout, webDevTec, toastr) {
var vm = this;
vm.awesomeThings = [];
vm.classAnimation = '';
vm.creationDate = 1437577753474;
vm.showToastr = showToastr;
activate();
function activate() {
getWebDevTec();
$timeout(function() {
vm.classAnimation = 'rubberBand';
}, 4000);
}
function showToastr() {
toastr.info('Fork <a href="https://github.com/Swiip/generator-gulp-angular" target="_blank"><b>generator-gulp-angular</b></a>');
vm.classAnimation = '';
}
function getWebDevTec() {
vm.awesomeThings = webDevTec.getTec();
angular.forEach(vm.awesomeThings, function(awesomeThing) {
awesomeThing.rank = Math.random();
});
}
}
})();
| LuukMoret/gulp-angular-examples | es5/material/src/app/main/main.controller.js | JavaScript | mit | 906 |
package io.github.intrainos.samsungltool;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button gotoAppops = (Button) findViewById(R.id.gotoAppops);
gotoAppops.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent AppopsIntent = new Intent();
AppopsIntent.setClassName("com.android.settings", "com.android.settings.Settings");
AppopsIntent.setAction("android.intent.action.MAIN");
AppopsIntent.addCategory("android.intent.category.DEFAULT");
AppopsIntent.setFlags(268468224);
AppopsIntent.putExtra(":android:show_fragment", "com.android.settings.applications.AppOpsSummary");
startActivity(AppopsIntent);
}
});
Button TouchLightSetting = (Button) findViewById(R.id.gotoTouchlightSetting);
TouchLightSetting.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent TouchLightSetting = new Intent(getApplicationContext(), TouchLight.class);
startActivity(TouchLightSetting);
}
});
Button gotoSViewWPSetting = (Button) findViewById(R.id.gotoSViewWPSetting);
gotoSViewWPSetting.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent gotoSViewWPSetting = new Intent();
gotoSViewWPSetting.setClassName("com.android.settings", "com.android.settings.SViewColor2014");
gotoSViewWPSetting.setAction("android.intent.action.MAIN");
gotoSViewWPSetting.addCategory("android.intent.category.DEFAULT");
gotoSViewWPSetting.setFlags(268468224);
startActivity(gotoSViewWPSetting);
}
});
Button gotoToolBoxSetting = (Button) findViewById(R.id.gotoToolBoxSetting);
gotoToolBoxSetting.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent gotoToolBoxSetting = new Intent();
gotoToolBoxSetting.setClassName("com.android.settings", "com.android.settings.Settings$ToolboxMenuActivity");
gotoToolBoxSetting.setAction("android.intent.action.MAIN");
gotoToolBoxSetting.addCategory("android.intent.category.DEFAULT");
gotoToolBoxSetting.setFlags(268468224);
startActivity(gotoToolBoxSetting);
}
});
Button gotoToolBoxList = (Button) findViewById(R.id.gotoToolBoxList);
gotoToolBoxList.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent gotoToolBoxList = new Intent();
gotoToolBoxList.setClassName("com.android.settings", "com.android.settings.Settings$ToolboxListActivity");
gotoToolBoxList.setAction("android.intent.action.MAIN");
gotoToolBoxList.addCategory("android.intent.category.DEFAULT");
gotoToolBoxList.setFlags(268468224);
startActivity(gotoToolBoxList);
}
});
Button gotoDownloadBoosterSetting = (Button) findViewById(R.id.gotoDownloadBoosterSetting);
gotoDownloadBoosterSetting.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent gotoDownloadBoosterSetting = new Intent();
gotoDownloadBoosterSetting.setClassName("com.android.settings", "com.android.settings.Settings$SmartBondingSettingsActivity");
gotoDownloadBoosterSetting.setAction("android.intent.action.MAIN");
gotoDownloadBoosterSetting.addCategory("android.intent.category.DEFAULT");
gotoDownloadBoosterSetting.setFlags(268468224);
startActivity(gotoDownloadBoosterSetting);
}
});
Button goto2014PowerSavingModeSetting = (Button) findViewById(R.id.goto2014PowerSavingModeSetting);
goto2014PowerSavingModeSetting.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goto2014PowerSavingModeSetting = new Intent();
goto2014PowerSavingModeSetting.setClassName("com.android.settings", "com.android.settings.Settings$PowerSavingModeSettings2014Activity");
goto2014PowerSavingModeSetting.setAction("android.intent.action.MAIN");
goto2014PowerSavingModeSetting.addCategory("android.intent.category.DEFAULT");
goto2014PowerSavingModeSetting.setFlags(268468224);
startActivity(goto2014PowerSavingModeSetting);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
/*
//Not Use
//noinspection SimplifiableIfStatement
if (id == R.id.action_about)
{
return true;
}
return super.onOptionsItemSelected(item);
*/
return false;
}
}
| Intrainos/SamsungLTool | src/main/java/io/github/intrainos/samsungltool/Main.java | Java | mit | 5,768 |
import { makeStyles } from '@material-ui/core/styles';
const drawerWidth = 240;
export const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
height: '100vh',
},
appBar: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
toolbar: {
display: 'flex',
'justify-content': 'space-between',
background: '#5700FA',
},
toolbarSpacer: theme.mixins.toolbar,
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
position: 'relative',
height: 'calc(100% - 64px)',
},
headerButtonText: {
marginLeft: '0.5rem',
},
headerButton: {
paddingLeft: '0.5rem',
paddingRight: '0.5rem',
height: '34px',
},
iframe: {
border: 'none',
},
}));
| diegodoumecq/joymap | examples/Main/styles.ts | TypeScript | mit | 872 |
import getValue from './getValue.js';
import getNumberValue from './getNumberValue.js';
export default function getOverlayPlaneModule(metaData) {
const overlays = [];
for (let overlayGroup = 0x00; overlayGroup <= 0x1e; overlayGroup += 0x02) {
let groupStr = `x60${overlayGroup.toString(16)}`;
if (groupStr.length === 4) {
groupStr = `x600${overlayGroup.toString(16)}`;
}
const data = getValue(metaData[`${groupStr}3000`]);
if (!data) {
continue;
}
const pixelData = [];
for (let i = 0; i < data.length; i++) {
for (let k = 0; k < 8; k++) {
const byte_as_int = metaData.Value[data.dataOffset + i];
pixelData[i * 8 + k] = (byte_as_int >> k) & 0b1; // eslint-disable-line no-bitwise
}
}
overlays.push({
rows: getNumberValue(metaData[`${groupStr}0010`]),
columns: getNumberValue(metaData[`${groupStr}0011`]),
type: getValue(metaData[`${groupStr}0040`]),
x: getNumberValue(metaData[`${groupStr}0050`], 1) - 1,
y: getNumberValue(metaData[`${groupStr}0050`], 0) - 1,
pixelData,
description: getValue(metaData[`${groupStr}0022`]),
label: getValue(metaData[`${groupStr}1500`]),
roiArea: getValue(metaData[`${groupStr}1301`]),
roiMean: getValue(metaData[`${groupStr}1302`]),
roiStandardDeviation: getValue(metaData[`${groupStr}1303`]),
});
}
return {
overlays,
};
}
| chafey/cornerstoneWADOImageLoader | src/imageLoader/wadors/metaData/getOverlayPlaneModule.js | JavaScript | mit | 1,430 |
class Solution:
def combine(self, n, k):
return [list(elem) for elem in itertools.combinations(xrange(1, n + 1), k)]
| rahul-ramadas/leetcode | combinations/Solution.6808610.py | Python | mit | 132 |
'use strict';
/**********************************************************************
* Angular Application (client side)
**********************************************************************/
angular.module('SwagApp', ['ngRoute', 'appRoutes', 'ui.bootstrap', 'ui.bootstrap.tpls' , 'MainCtrl', 'LoginCtrl', 'MySwagCtrl', 'MySwagService', 'GeekCtrl', 'GeekService'])
.config(function($routeProvider, $locationProvider, $httpProvider) {
//================================================
// Add an interceptor for AJAX errors
//================================================
$httpProvider.responseInterceptors.push(function($q, $location) {
return function(promise) {
return promise.then(
// Success: just return the response
function(response){
return response;
},
// Error: check the error status to get only the 401
function(response) {
if (response.status === 401)
$location.url('/login');
return $q.reject(response);
}
);
}
});
//================================================
}) //end of config
.run(function($rootScope, $http){
$rootScope.message = '';
// Logout function is available in any pages
$rootScope.logout = function(){
$rootScope.message = 'Logged out.';
$http.post('/logout');
};
});
| e2themillions/swaggatar | public/js/app.js | JavaScript | mit | 1,462 |
import os
import unittest
from erettsegit import argparse, yearify, monthify, levelify
from erettsegit import MessageType, message_for
class TestErettsegit(unittest.TestCase):
def test_yearify_raises_out_of_bounds_years(self):
with self.assertRaises(argparse.ArgumentTypeError):
yearify(2003)
yearify(1999)
yearify(2)
yearify(2999)
def test_yearify_pads_short_year(self):
self.assertEqual(yearify(12), 2012)
def test_monthify_handles_textual_dates(self):
self.assertEqual(monthify('Feb'), 2)
self.assertEqual(monthify('majus'), 5)
self.assertEqual(monthify('ősz'), 10)
def test_levelify_handles_multi_lang(self):
self.assertEqual(levelify('mid-level'), 'k')
self.assertEqual(levelify('advanced'), 'e')
def test_messages_get_interpolated_with_extra(self):
os.environ['ERETTSEGIT_LANG'] = 'EN'
self.assertEqual(message_for(MessageType.e_input, MessageType.c_year),
'incorrect year')
def test_messages_ignore_unnecessary_extra(self):
self.assertNotIn('None', message_for(MessageType.i_quit, extra=None))
| z2s8/erettsegit | test_erettsegit.py | Python | mit | 1,186 |
module Boxy
class HomesickHandler
def install(url, options)
url = URI.parse(url)
name = File.basename(url.path)
unless castle_cloned?(name)
system "homesick clone #{url.to_s}"
system "homesick symlink #{name}"
else
puts "skipping #{name}, already installed"
end
end
private
def castle_cloned?(name)
`homesick status #{name} > /dev/null 2>&1`
$? == 0
end
end
Boxy.register(:homesick, HomesickHandler.new)
end
| fooheads/boxy | lib/boxy/homesick.rb | Ruby | mit | 505 |
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.core.paginator import InvalidPage, Paginator
from django.db import models
from django.http import HttpResponseRedirect
from django.template.response import SimpleTemplateResponse, TemplateResponse
from django.utils.datastructures import SortedDict
from django.utils.encoding import force_unicode, smart_unicode
from django.utils.html import escape, conditional_escape
from django.utils.safestring import mark_safe
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from nadmin.util import lookup_field, display_for_field, label_for_field, boolean_icon
from base import ModelAdminView, filter_hook, inclusion_tag, csrf_protect_m
# List settings
ALL_VAR = 'all'
ORDER_VAR = 'o'
PAGE_VAR = 'p'
TO_FIELD_VAR = 't'
COL_LIST_VAR = '_cols'
ERROR_FLAG = 'e'
DOT = '.'
# Text to display within change-list table cells if the value is blank.
EMPTY_CHANGELIST_VALUE = _('Null')
class FakeMethodField(object):
"""
This class used when a column is an model function, wrap function as a fake field to display in select columns.
"""
def __init__(self, name, verbose_name):
# Initial comm field attrs
self.name = name
self.verbose_name = verbose_name
self.primary_key = False
class ResultRow(dict):
pass
class ResultItem(object):
def __init__(self, field_name, row):
self.classes = []
self.text = ' '
self.wraps = []
self.tag = 'td'
self.tag_attrs = []
self.allow_tags = False
self.btns = []
self.menus = []
self.is_display_link = False
self.row = row
self.field_name = field_name
self.field = None
self.attr = None
self.value = None
@property
def label(self):
text = mark_safe(
self.text) if self.allow_tags else conditional_escape(self.text)
if force_unicode(text) == '':
text = mark_safe(' ')
for wrap in self.wraps:
text = mark_safe(wrap % text)
return text
@property
def tagattrs(self):
return mark_safe(
'%s%s' % ((self.tag_attrs and ' '.join(self.tag_attrs) or ''),
(self.classes and (' class="%s"' % ' '.join(self.classes)) or '')))
class ResultHeader(ResultItem):
def __init__(self, field_name, row):
super(ResultHeader, self).__init__(field_name, row)
self.tag = 'th'
self.tag_attrs = ['scope="col"']
self.sortable = False
self.allow_tags = True
self.sorted = False
self.ascending = None
self.sort_priority = None
self.url_primary = None
self.url_remove = None
self.url_toggle = None
class ListAdminView(ModelAdminView):
"""
Display models objects view. this class has ordering and simple filter features.
"""
list_display = ('__str__',)
list_display_links = ()
list_display_links_details = False
list_select_related = None
list_per_page = 50
list_max_show_all = 200
list_exclude = ()
search_fields = ()
paginator_class = Paginator
ordering = None
# Change list templates
object_list_template = None
def init_request(self, *args, **kwargs):
if not self.has_view_permission():
raise PermissionDenied
request = self.request
request.session['LIST_QUERY'] = (self.model_info, self.request.META['QUERY_STRING'])
self.pk_attname = self.opts.pk.attname
self.lookup_opts = self.opts
self.list_display = self.get_list_display()
self.list_display_links = self.get_list_display_links()
# Get page number parameters from the query string.
try:
self.page_num = int(request.GET.get(PAGE_VAR, 0))
except ValueError:
self.page_num = 0
# Get params from request
self.show_all = ALL_VAR in request.GET
self.to_field = request.GET.get(TO_FIELD_VAR)
self.params = dict(request.GET.items())
if PAGE_VAR in self.params:
del self.params[PAGE_VAR]
if ERROR_FLAG in self.params:
del self.params[ERROR_FLAG]
@filter_hook
def get_list_display(self):
"""
Return a sequence containing the fields to be displayed on the list.
"""
self.base_list_display = (COL_LIST_VAR in self.request.GET and self.request.GET[COL_LIST_VAR] != "" and \
self.request.GET[COL_LIST_VAR].split('.')) or self.list_display
return list(self.base_list_display)
@filter_hook
def get_list_display_links(self):
"""
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
"""
if self.list_display_links or not self.list_display:
return self.list_display_links
else:
# Use only the first item in list_display as link
return list(self.list_display)[:1]
def make_result_list(self):
# Get search parameters from the query string.
self.base_queryset = self.queryset()
self.list_queryset = self.get_list_queryset()
self.ordering_field_columns = self.get_ordering_field_columns()
self.paginator = self.get_paginator()
# Get the number of objects, with admin filters applied.
self.result_count = self.paginator.count
# Get the total number of objects, with no admin filters applied.
# Perform a slight optimization: Check to see whether any filters were
# given. If not, use paginator.hits to calculate the number of objects,
# because we've already done paginator.hits and the value is cached.
if not self.list_queryset.query.where:
self.full_result_count = self.result_count
else:
self.full_result_count = self.base_queryset.count()
self.can_show_all = self.result_count <= self.list_max_show_all
self.multi_page = self.result_count > self.list_per_page
# Get the list of objects to display on this page.
if (self.show_all and self.can_show_all) or not self.multi_page:
self.result_list = self.list_queryset._clone()
else:
try:
self.result_list = self.paginator.page(
self.page_num + 1).object_list
except InvalidPage:
if ERROR_FLAG in self.request.GET.keys():
return SimpleTemplateResponse('nadmin/views/invalid_setup.html', {
'title': _('Database error'),
})
return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1')
self.has_more = self.result_count > (
self.list_per_page * self.page_num + len(self.result_list))
@filter_hook
def get_result_list(self):
return self.make_result_list()
@filter_hook
def post_result_list(self):
return self.make_result_list()
@filter_hook
def get_list_queryset(self):
"""
Get model queryset. The query has been filted and ordered.
"""
# First, get queryset from base class.
queryset = self.queryset()
# Use select_related() if one of the list_display options is a field
# with a relationship and the provided queryset doesn't already have
# select_related defined.
if not queryset.query.select_related:
if self.list_select_related:
queryset = queryset.select_related()
elif self.list_select_related is None:
related_fields = []
for field_name in self.list_display:
try:
field = self.opts.get_field(field_name)
except models.FieldDoesNotExist:
pass
else:
if isinstance(field.rel, models.ManyToOneRel):
related_fields.append(field_name)
if related_fields:
queryset = queryset.select_related(*related_fields)
else:
pass
# Then, set queryset ordering.
queryset = queryset.order_by(*self.get_ordering())
# Return the queryset.
return queryset
# List ordering
def _get_default_ordering(self):
ordering = []
if self.ordering:
ordering = self.ordering
elif self.opts.ordering:
ordering = self.opts.ordering
return ordering
@filter_hook
def get_ordering_field(self, field_name):
"""
Returns the proper model field name corresponding to the given
field_name to use for ordering. field_name may either be the name of a
proper model field or the name of a method (on the admin or model) or a
callable with the 'admin_order_field' attribute. Returns None if no
proper model field name can be matched.
"""
try:
field = self.opts.get_field(field_name)
return field.name
except models.FieldDoesNotExist:
# See whether field_name is a name of a non-field
# that allows sorting.
if callable(field_name):
attr = field_name
elif hasattr(self, field_name):
attr = getattr(self, field_name)
else:
attr = getattr(self.model, field_name)
return getattr(attr, 'admin_order_field', None)
@filter_hook
def get_ordering(self):
"""
Returns the list of ordering fields for the change list.
First we check the get_ordering() method in model admin, then we check
the object's default ordering. Then, any manually-specified ordering
from the query string overrides anything. Finally, a deterministic
order is guaranteed by ensuring the primary key is used as the last
ordering field.
"""
ordering = list(super(ListAdminView, self).get_ordering()
or self._get_default_ordering())
if ORDER_VAR in self.params and self.params[ORDER_VAR]:
# Clear ordering and used params
ordering = [pfx + self.get_ordering_field(field_name) for n, pfx, field_name in
map(
lambda p: p.rpartition('-'),
self.params[ORDER_VAR].split('.'))
if self.get_ordering_field(field_name)]
# Ensure that the primary key is systematically present in the list of
# ordering fields so we can guarantee a deterministic order across all
# database backends.
pk_name = self.opts.pk.name
if not (set(ordering) & set(['pk', '-pk', pk_name, '-' + pk_name])):
# The two sets do not intersect, meaning the pk isn't present. So
# we add it.
ordering.append('-pk')
return ordering
@filter_hook
def get_ordering_field_columns(self):
"""
Returns a SortedDict of ordering field column numbers and asc/desc
"""
# We must cope with more than one column having the same underlying sort
# field, so we base things on column numbers.
ordering = self._get_default_ordering()
ordering_fields = SortedDict()
if ORDER_VAR not in self.params or not self.params[ORDER_VAR]:
# for ordering specified on ModelAdmin or model Meta, we don't know
# the right column numbers absolutely, because there might be more
# than one column associated with that ordering, so we guess.
for field in ordering:
if field.startswith('-'):
field = field[1:]
order_type = 'desc'
else:
order_type = 'asc'
for attr in self.list_display:
if self.get_ordering_field(attr) == field:
ordering_fields[field] = order_type
break
else:
for p in self.params[ORDER_VAR].split('.'):
none, pfx, field_name = p.rpartition('-')
ordering_fields[field_name] = 'desc' if pfx == '-' else 'asc'
return ordering_fields
def get_check_field_url(self, f):
"""
Return the select column menu items link.
We must use base_list_display, because list_display maybe changed by plugins.
"""
fields = [fd for fd in self.base_list_display if fd != f.name]
if len(self.base_list_display) == len(fields):
if f.primary_key:
fields.insert(0, f.name)
else:
fields.append(f.name)
return self.get_query_string({COL_LIST_VAR: '.'.join(fields)})
def get_model_method_fields(self):
"""
Return the fields info defined in model. use FakeMethodField class wrap method as a db field.
"""
methods = []
for name in dir(self):
try:
if getattr(getattr(self, name), 'is_column', False):
methods.append((name, getattr(self, name)))
except:
pass
return [FakeMethodField(name, getattr(method, 'short_description', capfirst(name.replace('_', ' '))))
for name, method in methods]
@filter_hook
def get_context(self):
"""
Prepare the context for templates.
"""
self.title = _('%s List') % force_unicode(self.opts.verbose_name)
model_fields = [(f, f.name in self.list_display, self.get_check_field_url(f))
for f in (self.opts.fields + tuple(self.get_model_method_fields())) if f.name not in self.list_exclude]
new_context = {
'model_name': force_unicode(self.opts.verbose_name_plural),
'title': self.title,
'cl': self,
'model_fields': model_fields,
'clean_select_field_url': self.get_query_string(remove=[COL_LIST_VAR]),
'has_add_permission': self.has_add_permission(),
'app_label': self.app_label,
'brand_name': self.opts.verbose_name_plural,
'brand_icon': self.get_model_icon(self.model),
'add_url': self.model_admin_url('add'),
'result_headers': self.result_headers(),
'results': self.results()
}
context = super(ListAdminView, self).get_context()
context.update(new_context)
return context
@filter_hook
def get_response(self, context, *args, **kwargs):
pass
@csrf_protect_m
@filter_hook
def get(self, request, *args, **kwargs):
"""
The 'change list' admin view for this model.
"""
response = self.get_result_list()
if response:
return response
context = self.get_context()
context.update(kwargs or {})
response = self.get_response(context, *args, **kwargs)
return response or TemplateResponse(request, self.object_list_template or
self.get_template_list('views/model_list.html'), context, current_app=self.admin_site.name)
@filter_hook
def post_response(self, *args, **kwargs):
pass
@csrf_protect_m
@filter_hook
def post(self, request, *args, **kwargs):
return self.post_result_list() or self.post_response(*args, **kwargs) or self.get(request, *args, **kwargs)
@filter_hook
def get_paginator(self):
return self.paginator_class(self.list_queryset, self.list_per_page, 0, True)
@filter_hook
def get_page_number(self, i):
if i == DOT:
return mark_safe(u'<span class="dot-page">...</span> ')
elif i == self.page_num:
return mark_safe(u'<span class="this-page">%d</span> ' % (i + 1))
else:
return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(self.get_query_string({PAGE_VAR: i})), (i == self.paginator.num_pages - 1 and ' class="end"' or ''), i + 1))
# Result List methods
@filter_hook
def result_header(self, field_name, row):
ordering_field_columns = self.ordering_field_columns
item = ResultHeader(field_name, row)
text, attr = label_for_field(field_name, self.model,
model_admin=self,
return_attr=True
)
item.text = text
item.attr = attr
if attr and not getattr(attr, "admin_order_field", None):
return item
# OK, it is sortable if we got this far
th_classes = ['sortable']
order_type = ''
new_order_type = 'desc'
sort_priority = 0
sorted = False
# Is it currently being sorted on?
if field_name in ordering_field_columns:
sorted = True
order_type = ordering_field_columns.get(field_name).lower()
sort_priority = ordering_field_columns.keys().index(field_name) + 1
th_classes.append('sorted %sending' % order_type)
new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]
# build new ordering param
o_list_asc = [] # URL for making this field the primary sort
o_list_desc = [] # URL for making this field the primary sort
o_list_remove = [] # URL for removing this field from sort
o_list_toggle = [] # URL for toggling order type for this field
make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n)
for j, ot in ordering_field_columns.items():
if j == field_name: # Same column
param = make_qs_param(new_order_type, j)
# We want clicking on this header to bring the ordering to the
# front
o_list_asc.insert(0, j)
o_list_desc.insert(0, '-' + j)
o_list_toggle.append(param)
# o_list_remove - omit
else:
param = make_qs_param(ot, j)
o_list_asc.append(param)
o_list_desc.append(param)
o_list_toggle.append(param)
o_list_remove.append(param)
if field_name not in ordering_field_columns:
o_list_asc.insert(0, field_name)
o_list_desc.insert(0, '-' + field_name)
item.sorted = sorted
item.sortable = True
item.ascending = (order_type == "asc")
item.sort_priority = sort_priority
menus = [
('asc', o_list_asc, 'caret-up', _(u'Sort ASC')),
('desc', o_list_desc, 'caret-down', _(u'Sort DESC')),
]
if sorted:
row['num_sorted_fields'] = row['num_sorted_fields'] + 1
menus.append((None, o_list_remove, 'times', _(u'Cancel Sort')))
item.btns.append('<a class="toggle" href="%s"><i class="fa fa-%s"></i></a>' % (
self.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), 'sort-up' if order_type == "asc" else 'sort-down'))
item.menus.extend(['<li%s><a href="%s" class="active"><i class="fa fa-%s"></i> %s</a></li>' %
(
(' class="active"' if sorted and order_type == i[
0] else ''),
self.get_query_string({ORDER_VAR: '.'.join(i[1])}), i[2], i[3]) for i in menus])
item.classes.extend(th_classes)
return item
@filter_hook
def result_headers(self):
"""
Generates the list column headers.
"""
row = ResultRow()
row['num_sorted_fields'] = 0
row.cells = [self.result_header(
field_name, row) for field_name in self.list_display]
return row
@filter_hook
def result_item(self, obj, field_name, row):
"""
Generates the actual list of data.
"""
item = ResultItem(field_name, row)
try:
f, attr, value = lookup_field(field_name, obj, self)
except (AttributeError, ObjectDoesNotExist):
item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)
else:
if f is None:
item.allow_tags = getattr(attr, 'allow_tags', False)
boolean = getattr(attr, 'boolean', False)
if boolean:
item.allow_tags = True
item.text = boolean_icon(value)
else:
item.text = smart_unicode(value)
else:
if isinstance(f.rel, models.ManyToOneRel):
field_val = getattr(obj, f.name)
if field_val is None:
item.text = mark_safe("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)
else:
item.text = field_val
else:
item.text = display_for_field(value, f)
if isinstance(f, models.DateField)\
or isinstance(f, models.TimeField)\
or isinstance(f, models.ForeignKey):
item.classes.append('nowrap')
item.field = f
item.attr = attr
item.value = value
# If list_display_links not defined, add the link tag to the first field
if (item.row['is_display_first'] and not self.list_display_links) \
or field_name in self.list_display_links:
item.row['is_display_first'] = False
item.is_display_link = True
if self.list_display_links_details:
item_res_uri = self.model_admin_url("detail", getattr(obj, self.pk_attname))
if item_res_uri:
if self.has_change_permission(obj):
edit_url = self.model_admin_url("change", getattr(obj, self.pk_attname))
else:
edit_url = ""
item.wraps.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s">%%s</a>'
% (item_res_uri, edit_url, _(u'Details of %s') % str(obj)))
else:
url = self.url_for_result(obj)
item.wraps.append(u'<a href="%s">%%s</a>' % url)
return item
@filter_hook
def result_row(self, obj):
row = ResultRow()
row['is_display_first'] = True
row['object'] = obj
row.cells = [self.result_item(
obj, field_name, row) for field_name in self.list_display]
return row
@filter_hook
def results(self):
results = []
for obj in self.result_list:
results.append(self.result_row(obj))
return results
@filter_hook
def url_for_result(self, result):
return self.get_object_url(result)
# Media
@filter_hook
def get_media(self):
media = super(ListAdminView, self).get_media() + self.vendor('nadmin.page.list.js', 'nadmin.page.form.js')
if self.list_display_links_details:
media += self.vendor('nadmin.plugin.details.js', 'nadmin.form.css')
return media
# Blocks
@inclusion_tag('nadmin/includes/pagination.html')
def block_pagination(self, context, nodes, page_type='normal'):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = self.paginator, self.page_num
pagination_required = (
not self.show_all or not self.can_show_all) and self.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = {'normal': 5, 'small': 3}.get(page_type, 3)
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(
range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(
range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(
paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = self.can_show_all and not self.show_all and self.multi_page
return {
'cl': self,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and self.get_query_string({ALL_VAR: ''}),
'page_range': map(self.get_page_number, page_range),
'ALL_VAR': ALL_VAR,
'1': 1,
}
| A425/django-nadmin | nadmin/views/list.py | Python | mit | 25,811 |
<?php
namespace Dragoon\MoviesBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class DragoonMoviesBundle extends Bundle
{
}
| lboulay/sonata | src/Dragoon/MoviesBundle/DragoonMoviesBundle.php | PHP | mit | 134 |
import { bindable, customAttribute, inject } from 'aurelia-framework';
import { AttributeManager } from '../common/attributeManager';
@customAttribute('b-button')
@inject(Element)
export class BButton {
@bindable bStyle = 'default';
@bindable bSize = null;
@bindable bBlock = null;
@bindable bDisabled = false;
@bindable bActive = false;
constructor(element) {
this.element = element;
this.fixedAttributeManager = new AttributeManager(this.element);
}
attached() {
this.fixedAttributeManager.addClasses('btn');
this.fixedAttributeManager.addClasses(`btn-${this.bStyle}`);
if (this.bSize) {
this.fixedAttributeManager.addClasses(`btn-${this.bSize}`);
}
if (this.bBlock) {
this.fixedAttributeManager.addClasses('btn-block');
}
if (this.bDisabled === true) {
this.fixedAttributeManager.addClasses('disabled');
}
if (this.bActive === true) {
this.fixedAttributeManager.addClasses('active');
}
}
}
| aurelia-ui-toolkits/aurelia-bootstrap-bridge | src/button/button.js | JavaScript | mit | 1,041 |
<?php
namespace ZPB\AdminBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* AnimationProgramRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class AnimationProgramRepository extends EntityRepository
{
public function animationsInMonth($month, $year = 2014)
{
$m = \DateTime::createFromFormat('j/n/Y', '1/'.$month.'/'.$year);
$daysInMonth = (int)$m->format('t') + 1;
$result = [];
for($i = 1; $i < $daysInMonth; $i++){
$d = \DateTime::createFromFormat('Y/n/j',$year.'/'.$month.'/'.$i);
$qb = $this->createQueryBuilder('p')->where('p.daytime = :theDate')
->setParameter('theDate', $d, \Doctrine\DBAL\Types\Type::DATE);
$result[] = $qb->getQuery()->getOneOrNullResult();
}
return $result;
}
public function getAnimationsInMonth($month, $year = 2014)
{
$programs = $this->animationsInMonth($month, $year);
$result = ['error'=>false, 'message'=>'NO ERROR','year'=>$year, 'month'=>$month, 'days'=>[]];
foreach($programs as $prog){
if($prog != null){
/** @var \ZPB\AdminBundle\Entity\AnimationProgram $prog */
$days = $prog->getAnimationDays();
$tmp = [];
foreach($days as $day){
/** @var \ZPB\AdminBundle\Entity\AnimationDay $day */
$tmp[] = $day->toArray();
}
$result['days'][] = $tmp;
} else {
$result['days'][] = [];
}
}
return $result;
}
}
| Grosloup/multisite3 | src/ZPB/AdminBundle/Entity/AnimationProgramRepository.php | PHP | mit | 1,680 |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "stdafx.h"
#include "CullDataVisualizer.h"
#include "DXSampleHelper.h"
using namespace DirectX;
namespace
{
const wchar_t* s_boundingSphereMsFilename = L"BoundingSphereMS.cso";
const wchar_t* s_normalConeMsFilename = L"NormalConeMS.cso";
const wchar_t* s_debugDrawPsFilename = L"DebugDrawPS.cso";
std::wstring GetAssetFullPath(const wchar_t* path)
{
WCHAR assetsPath[512];
GetAssetsPath(assetsPath, _countof(assetsPath));
return std::wstring(assetsPath) + path;
}
}
CullDataVisualizer::CullDataVisualizer()
: m_constantData(nullptr)
, m_frameIndex(0)
{ }
void CullDataVisualizer::CreateDeviceResources(ID3D12Device2* device, DXGI_FORMAT rtFormat, DXGI_FORMAT dsFormat)
{
// Load shader bytecode and extract root signature
struct
{
byte* data;
uint32_t size;
} normalConeMs, boundingSphereMs, pixelShader;
ReadDataFromFile(GetAssetFullPath(s_normalConeMsFilename).c_str(), &normalConeMs.data, &normalConeMs.size);
ReadDataFromFile(GetAssetFullPath(s_boundingSphereMsFilename).c_str(), &boundingSphereMs.data, &boundingSphereMs.size);
ReadDataFromFile(GetAssetFullPath(s_debugDrawPsFilename).c_str(), &pixelShader.data, &pixelShader.size);
ThrowIfFailed(device->CreateRootSignature(0, normalConeMs.data, normalConeMs.size, IID_PPV_ARGS(&m_rootSignature)));
// Disable culling
CD3DX12_RASTERIZER_DESC rasterDesc = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
rasterDesc.CullMode = D3D12_CULL_MODE_NONE;
// Disable depth test & writes
CD3DX12_DEPTH_STENCIL_DESC dsDesc = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
dsDesc.DepthEnable = false;
dsDesc.StencilEnable = false;
dsDesc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
// Populate the Mesh Shader PSO descriptor
D3DX12_MESH_SHADER_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.pRootSignature = m_rootSignature.Get();
psoDesc.PS = { pixelShader.data, pixelShader.size };
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = rtFormat;
psoDesc.DSVFormat = dsFormat;
psoDesc.RasterizerState = rasterDesc;
psoDesc.DepthStencilState = dsDesc;
psoDesc.SampleMask = UINT_MAX;
psoDesc.SampleDesc = DefaultSampleDesc();
// Create normal cone pipeline
{
// Cone lines are drawn opaquely
psoDesc.MS = { normalConeMs.data, normalConeMs.size };
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); // Opaque
auto meshStreamDesc = CD3DX12_PIPELINE_MESH_STATE_STREAM(psoDesc);
// Populate the stream desc with our defined PSO descriptor
D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {};
streamDesc.SizeInBytes = sizeof(meshStreamDesc);
streamDesc.pPipelineStateSubobjectStream = &meshStreamDesc;
ThrowIfFailed(device->CreatePipelineState(&streamDesc, IID_PPV_ARGS(&m_normalConePso)));
}
// Create bounding sphere pipeline
{
// bounding sphere pipeline requires additive blending
D3D12_BLEND_DESC blendDesc = {};
blendDesc.RenderTarget[0].BlendEnable = true;
blendDesc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
blendDesc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_MAX;
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ZERO;
blendDesc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ONE;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
psoDesc.MS = { boundingSphereMs.data, boundingSphereMs.size };
psoDesc.BlendState = blendDesc;
auto meshStreamDesc = CD3DX12_PIPELINE_MESH_STATE_STREAM(psoDesc);
// Populate the stream desc with our defined PSO descriptor
D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = {};
streamDesc.SizeInBytes = sizeof(meshStreamDesc);
streamDesc.pPipelineStateSubobjectStream = &meshStreamDesc;
ThrowIfFailed(device->CreatePipelineState(&streamDesc, IID_PPV_ARGS(&m_boundingSpherePso)));
}
const CD3DX12_HEAP_PROPERTIES constantBufferHeapProps(D3D12_HEAP_TYPE_UPLOAD);
const CD3DX12_RESOURCE_DESC constantBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(Constants) * 2);
// Create shared constant buffer
ThrowIfFailed(device->CreateCommittedResource(
&constantBufferHeapProps,
D3D12_HEAP_FLAG_NONE,
&constantBufferDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&m_constantResource)
));
ThrowIfFailed(m_constantResource->Map(0, nullptr, &m_constantData));
}
void CullDataVisualizer::ReleaseResources()
{
m_rootSignature.Reset();
m_boundingSpherePso.Reset();
m_normalConePso.Reset();
m_constantResource.Reset();
}
void CullDataVisualizer::SetConstants(FXMMATRIX world, CXMMATRIX view, CXMMATRIX proj, CXMVECTOR color)
{
m_frameIndex = (m_frameIndex + 1) % 2;
XMVECTOR scl, rot, pos;
XMMatrixDecompose(&scl, &rot, &pos, world);
XMMATRIX viewToWorld = XMMatrixTranspose(view);
XMVECTOR camUp = XMVector3TransformNormal(g_XMIdentityR1, viewToWorld); // Y-axis is up direction
XMVECTOR camForward = XMVector3TransformNormal(g_XMNegIdentityR2, viewToWorld); // -Z-axis is forward direction
auto& constants = *(reinterpret_cast<Constants*>(m_constantData) + m_frameIndex);
XMStoreFloat4x4(&constants.ViewProj, XMMatrixTranspose(view * proj));
XMStoreFloat4x4(&constants.World, XMMatrixTranspose(world));
XMStoreFloat4(&constants.Color, color);
XMStoreFloat4(&constants.ViewUp, camUp);
XMStoreFloat3(&constants.ViewForward, camForward);
constants.Scale = XMVectorGetX(scl);
constants.Color.w = 0.3f;
}
void CullDataVisualizer::Draw(ID3D12GraphicsCommandList6* commandList, const Mesh& mesh, uint32_t offset, uint32_t count)
{
// Push constant data to GPU for our shader invocations
assert(offset + count <= static_cast<uint32_t>(mesh.Meshlets.size()));
// Shared root signature between two shaders
commandList->SetGraphicsRootSignature(m_rootSignature.Get());
commandList->SetGraphicsRootConstantBufferView(0, m_constantResource->GetGPUVirtualAddress() + sizeof(Constants) * m_frameIndex);
commandList->SetGraphicsRoot32BitConstant(1, offset, 0);
commandList->SetGraphicsRoot32BitConstant(1, count, 1);
commandList->SetGraphicsRootShaderResourceView(2, mesh.CullDataResource->GetGPUVirtualAddress());
// Dispatch bounding sphere draw
commandList->SetPipelineState(m_boundingSpherePso.Get());
commandList->DispatchMesh(count, 1, 1);
// Dispatch normal cone draw
commandList->SetPipelineState(m_normalConePso.Get());
commandList->DispatchMesh(count, 1, 1);
}
| SuperWangKai/DirectX-Graphics-Samples | Samples/Desktop/D3D12MeshShaders/src/MeshletCull/CullDataVisualizer.cpp | C++ | mit | 7,493 |
package org.javacs.rewrite;
/** JavaType represents a potentially parameterized named type. */
public class JavaType {
final String name;
final JavaType[] parameters;
public JavaType(String name, JavaType[] parameters) {
this.name = name;
this.parameters = parameters;
}
}
| georgewfraser/vscode-javac | src/main/java/org/javacs/rewrite/JavaType.java | Java | mit | 307 |
/*
* Copyright (c) 2018 Rain Agency <contact@rain.agency>
* Author: Rain Agency <contact@rain.agency>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
export function toSSML(statement?: string): string | undefined {
if (!statement) {
return undefined;
}
if (statement.startsWith("<speak>")) {
return statement;
}
// Hack. Full xml escaping would be better, but the & is currently the only special character used.
statement = statement.replace(/&/g, "&");
return `<speak>${statement}</speak>`;
}
| armonge/voxa | src/ssml.ts | TypeScript | mit | 1,552 |
$(document).ready(function(){
var nav = navigator.userAgent.toLowerCase(); //La variable nav almacenará la información del navegador del usuario
if(nav.indexOf("firefox") != -1){ //En caso de que el usuario este usando el navegador MozillaFirefox
$("#fecha_inicio").mask("9999-99-99",{placeholder:"AAAA-MM-DD"}); //Se inicializa el campo fecha con el plugIn de maskedInput
$("#fecha_fin").mask("9999-99-99",{placeholder:"AAAA-MM-DD"}); //Se inicializa el campo fecha con el plugIn de maskedInput
}
$("#accordion").on("show.bs.collapse", ".collapse", function(e){
$(this).parent(".panel").find(".panel-heading .panel-title a span").removeClass("glyphicon-plus").addClass("glyphicon-minus");
});
$("#accordion").on("hide.bs.collapse", ".collapse", function(e){
$(this).parent(".panel").find(".panel-heading .panel-title a span").addClass("glyphicon-plus").removeClass("glyphicon-minus");
});
$("#hora_inicio").mask("99:99",{placeholder:"00:00"});
$("#hora_fin").mask("99:99",{placeholder:"00:00"});
$('#registro-evento').validator();
$("#registro-evento").on("submit", function(){
$(this).attr("disabled","disabled");
$('#seccion2').animate({scrollTop : 0}, 500);
});
$("#imagen").fileinput({
language: "es",
fileType: "image",
showUpload: false,
browseLabel: 'Examinar …',
removeLabel: 'Remover'
});
$("#img-change").on("click", function(){
if ($("#img-change").is(":checked")) {
$("#imagen-content figure").hide();
$("#imagen-content h4").hide();
$("#imagen-content .form-group").removeClass("hidden");
}else{
$("#imagen-content figure").show();
$("#imagen-content h4").show();
$("#imagen-content .form-group").addClass("hidden");
}
});
}); | JoseSoto33/proyecto-sismed | assets/js/funciones-formulario-evento.js | JavaScript | mit | 1,944 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["shared-components"] = factory(require("react"));
else
root["shared-components"] = factory(root["react"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
__webpack_require__(2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var NumberPicker = function (_React$Component) {
_inherits(NumberPicker, _React$Component);
function NumberPicker(props) {
_classCallCheck(this, NumberPicker);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(NumberPicker).call(this, props));
_this.MAX_VALUE = _this.maxValue();
return _this;
}
_createClass(NumberPicker, [{
key: "maxValue",
value: function maxValue() {
var str_max = "";
for (var i = 0; i < this.props.digits; i++) {
str_max += "9";
}if (this.props.showDecimal) str_max += ".99";
return parseFloat(str_max);
}
}, {
key: "digitInteger",
value: function digitInteger(ltr_digit) {
var sValue = this.props.value.toString();
var a_sValue = sValue.split(".");
var integer = a_sValue[0];
var rtl_digit = this.props.digits - (ltr_digit - 1);
if (rtl_digit > integer.length) return "0";
return integer[integer.length - rtl_digit];
}
}, {
key: "digitDecimal",
value: function digitDecimal(ltr_digit) {
var sValue = this.props.value.toString();
var a_sValue = sValue.split(".");
var decimal = a_sValue.length > 1 && a_sValue[1].length > 0 ? a_sValue[1] : "00";
if (decimal.length > 2) decimal = decimal.substr(0, 2);
if (decimal.length < 2) decimal = decimal + "0";
return decimal[ltr_digit - 1];
}
}, {
key: "modifyValue",
value: function modifyValue(type, value, event) {
event.preventDefault();
if (!this.props.onChange) return;
var value_to_add = type === "down" ? value * -1 : value;
var new_value = this.props.value + value_to_add;
/* adjust float operations */
var str_new_value = this.props.showDecimal ? new_value.toFixed(2) : new_value.toFixed(0);
var adjusted_new_value = parseFloat(str_new_value);
/* dont work with negative values, YET */
if (adjusted_new_value < 0) adjusted_new_value = 0;
/* prevent from exceed maximum possible values */
if (adjusted_new_value > this.MAX_VALUE) adjusted_new_value = this.MAX_VALUE;
this.props.onChange(adjusted_new_value);
}
}, {
key: "renderButtons",
value: function renderButtons(type) {
var elements = [];
/* display an invisible cell */
if (this.props.currency) {
elements.push(_react2.default.createElement("div", { key: "currency", className: "NumberPicker__cell button" }));
}
/* display tob/bottom buttons */
for (var i = 0; i < this.props.digits; i++) {
var value_to_add = Math.pow(10, this.props.digits - i - 1);
elements.push(_react2.default.createElement(
"div",
{ key: "integer-" + i, className: "NumberPicker__cell button " + type },
_react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, value_to_add) })
));
}
/* display invisible cell to decimal separator and tob/bottom buttons for decimals */
if (this.props.showDecimal) {
elements.push(_react2.default.createElement("div", { key: "decimal-separator", className: "NumberPicker__cell decimal-separator" }));
elements.push(_react2.default.createElement(
"div",
{ key: "decimal-1", className: "NumberPicker__cell button " + type },
_react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, 0.1) })
));
elements.push(_react2.default.createElement(
"div",
{ key: "decimal-2", className: "NumberPicker__cell button " + type },
_react2.default.createElement("span", { className: type, onClick: this.modifyValue.bind(this, type, 0.01) })
));
}
return elements;
}
}, {
key: "renderDigits",
value: function renderDigits() {
var elements = [];
if (this.props.currency) {
elements.push(_react2.default.createElement(
"div",
{ key: "currency", className: "NumberPicker__cell currency" },
_react2.default.createElement(
"span",
{ className: "currency" },
this.props.currency
)
));
}
for (var i = 0; i < this.props.digits; i++) {
var digit = i + 1;
elements.push(_react2.default.createElement(
"div",
{ key: digit, className: "NumberPicker__cell digit" },
_react2.default.createElement(
"span",
{ className: "digit" },
this.digitInteger(digit)
)
));
}
if (this.props.showDecimal) {
elements.push(_react2.default.createElement(
"div",
{ key: "decimal-separator", className: "NumberPicker__cell decimal-separator" },
_react2.default.createElement(
"span",
{ className: "decimal-separator" },
this.props.decimalSeparator
)
));
elements.push(_react2.default.createElement(
"div",
{ key: "decimal-1", className: "NumberPicker__cell digit" },
_react2.default.createElement(
"span",
{ className: "digit" },
this.digitDecimal(1)
)
));
elements.push(_react2.default.createElement(
"div",
{ key: "decimal-2", className: "NumberPicker__cell digit" },
_react2.default.createElement(
"span",
{ className: "digit" },
this.digitDecimal(2)
)
));
}
return elements;
}
}, {
key: "render",
value: function render() {
return _react2.default.createElement(
"div",
{ className: "NumberPicker__wrapper" },
_react2.default.createElement(
"div",
{ className: "NumberPicker__table" },
_react2.default.createElement(
"div",
{ className: "NumberPicker__row" },
this.renderButtons("up")
),
_react2.default.createElement(
"div",
{ className: "NumberPicker__row" },
this.renderDigits()
),
_react2.default.createElement(
"div",
{ className: "NumberPicker__row" },
this.renderButtons("down")
)
)
);
}
}]);
return NumberPicker;
}(_react2.default.Component);
NumberPicker.propTypes = {
onChange: _react2.default.PropTypes.func,
digits: _react2.default.PropTypes.number.isRequired,
currency: _react2.default.PropTypes.string,
value: _react2.default.PropTypes.number.isRequired,
showDecimal: _react2.default.PropTypes.bool.isRequired,
decimalSeparator: _react2.default.PropTypes.string.isRequired
};
NumberPicker.defaultProps = {
digits: 1,
currency: null,
value: 0.00,
decimalSeparator: ".",
showDecimal: false
};
exports.default = NumberPicker;
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }
/******/ ])
});
; | mrlew/react-number-picker | dist/react-number-picker.js | JavaScript | mit | 10,328 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'http://training_ci.happy.cba/';
//$config['base_url'] = 'http://localhost:81/Training_CI-master/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = FALSE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| http://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = '';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
| DeRossi/Training_CI | application/config/config.php | PHP | mit | 18,210 |
import json
import re
from pygeocoder import Geocoder
from pygeolib import GeocoderError
import requests
# from picasso.index.models import Tag
from picasso.index.models import Address, Listing, Tag
__author__ = 'tmehta'
url = 'http://www.yellowpages.ca/ajax/search/music+teachers/Toronto%2C+ON?sType=si&sort=rel&pg=1&' + \
'skipNonPaids=56&trGeo=43.797452066539165,-79.15031040820315&blGeo=43.55112164714018,-79.6419485917969'
base_url = 'http://www.yellowpages.ca/bus/'
city = 'Toronto'
def extract_cats(p):
try:
p_s = p.split('Products and Services</h3>')[1].split('</span>')[0].replace('<span>', '')
except IndexError:
return []
p_s = p_s.split("'>")[1:]
cats = []
for line in p_s:
cats.append(line.split('</li>')[0])
return cats
def extract_phone(p):
try:
phone = p.split('class="phone"')[1].split('<span >')[1].split('</span>')[0]
except IndexError:
phone = ''
return phone
r = requests.get(url)
listings = json.loads(r.text)['features']
for l in listings:
name = l['properties']['name']
scraped_url = base_url + str(l['properties']['id']) + '.html'
try:
lst = Listing.objects.get(scraped_url=scraped_url)
page = requests.get(scraped_url).text
try:
location = page.split('itemprop="streetAddress">')[1].split('</span>')[0]
except IndexError:
location = ''
try:
postalCode = page.split('itemprop="postalCode">')[1].split('</span>')[0]
except IndexError:
postalCode = ''
lat = l["geometry"]["coordinates"][0]
lon = l["geometry"]["coordinates"][1]
point = "POINT(%s %s)" % (lon, lat)
lst.address.point = point
lst.save()
except Listing.DoesNotExist:
active = True
place = 'Sch'
email = ''
page = requests.get(scraped_url).text
categories = extract_cats(page)
tags = []
for cat in categories:
t = Tag.objects.get_or_create(tag_name=cat)
phone_number = extract_phone(page)
try:
location = page.split('itemprop="streetAddress">')[1].split('</span>')[0]
except IndexError:
location = ''
try:
postalCode = page.split('itemprop="postalCode">')[1].split('</span>')[0]
except IndexError:
postalCode = ''
try:
description = page.split('itemprop="description">')[1].split('</article>')[0].split('<a href')[0].replace(
'<span', '').replace('</span>', '')
except IndexError:
description = ''
lat = l["geometry"]["coordinates"][0]
lon = l["geometry"]["coordinates"][1]
point = "POINT(%s %s)" % (lon, lat)
add = Address.objects.create(location=location, postal_code=postalCode, city=city, point=point)
lst = Listing.objects.create(address=add, listing_name=name, scraped_url=scraped_url, description=description,
phone=phone_number)
for t in tags:
lst.tags.add(t)
lst.save()
| TejasM/picasso | picasso/yellow_pages.py | Python | mit | 3,125 |
require 'timeout'
require 'spec_helper'
shared_examples 'using a mysql database' do
before :all do
within 'form#jira-setup-database' do
# select using external database
choose 'jira-setup-database-field-database-external'
# allow some time for the DOM to change
sleep 1
# fill in database configuration
select "MySQL", from: 'jira-setup-database-field-database-type'
fill_in 'jdbcHostname', with: @container_db.host
fill_in 'jdbcPort', with: '3306'
fill_in 'jdbcDatabase', with: 'jiradb'
fill_in 'jdbcUsername', with: 'root'
fill_in 'jdbcPassword', with: 'mysecretpassword'
# continue database setup
click_button 'Next'
end
end
end
| wpxgit/docker-atlassian-jira | spec/support/shared_examples/using_a_mysql_database_shared_example.rb | Ruby | mit | 678 |
package com.sincsmart.attendance.util;
import com.activeandroid.util.Log;
import android.content.Context;
import android.util.TypedValue;
//常用单位转换的辅助类
public class DensityUtils {
private DensityUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* dp转px
*
* @param context
* @param val
* @return
*/
public static int dp2px(Context context, float dpVal) {
final float scale = context.getResources().getDisplayMetrics().density;
Log.i("ldb", "分辨率" + scale);
return (int) (dpVal * scale + 0.5f);
}
/**
* sp转px
*
* @param context
* @param val
* @return
*/
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px转dp
*
* @param context
* @param pxVal
* @return
*/
public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
/**
* px转sp
*
* @param fontScale
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
| zhilianxinke/attendance | src/com/sincsmart/attendance/util/DensityUtils.java | Java | mit | 1,335 |
import './clean-rich-text-editor.css';
import select from 'select-dom';
import onetime from 'onetime';
import * as pageDetect from 'github-url-detection';
import features from '.';
function hideButtons(): void {
document.body.classList.add('rgh-clean-rich-text-editor');
}
function hideTextareaTooltip(): void {
for (const textarea of select.all('.comment-form-textarea')) {
textarea.title = '';
}
}
void features.add(__filebasename, {
include: [
pageDetect.hasRichTextEditor,
],
deduplicate: 'has-rgh-inner',
init: hideTextareaTooltip,
}, {
include: [
pageDetect.isRepo,
],
awaitDomReady: false,
init: onetime(hideButtons),
});
| sindresorhus/refined-github | source/features/clean-rich-text-editor.tsx | TypeScript | mit | 650 |
import subprocess
with open('names.txt') as f:
names = f.read().splitlines()
with open('portraits.txt') as f:
portraits = f.read().splitlines()
for i, name in enumerate(names):
portrait = portraits[i]
if portrait.endswith('.png'):
subprocess.call(['cp', 'minor/{}'.format(portrait), '{}.png'.format(name.lower())])
| dcripplinger/rotj | data/images/portraits/copy_portraits.py | Python | mit | 341 |
<h2>New Group</h2>
<br>
<?php echo render('admin/group/_form'); ?>
<p><?php echo Html::anchor('admin/group', 'Back'); ?></p>
| hrabbit/newzearch | fuel/app/views/admin/group/create.php | PHP | mit | 128 |
import React from "react";
export default class TransactionSentModal extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div className={this.props.transactionSent ? "transaction-sent-wrap active" : "transaction-sent-wrap"}>
{
this.props.transactionSent
?
<form className="container transactionSent" onSubmit={this.props.closeSuccessModal}>
<div className="head">
<h3>Sent </h3>
<span className="close" onClick={this.props.closeSuccessModal}>X</span>
</div>
<div className="currency">
<span>Currency:</span>
<img className={this.props.sendCoin === 'safex'
? 'coin'
: 'coin hidden-xs hidden-sm hidden-md hidden-lg'}
onClick={this.props.sendCoinSafex}
src="images/coin-white.png" alt="Safex Coin"/>
<img className={this.props.sendCoin === 'btc'
? 'coin'
: 'coin hidden-xs hidden-sm hidden-md hidden-lg'}
onClick={this.props.sendCoinBtc} src="images/btc-coin.png"
alt="Bitcoin Coin"/>
</div>
<div className="input-group">
<label htmlFor="from">From:</label>
<textarea name="from" className="form-control" readOnly
value={this.props.publicKey} placeholder="Address"
aria-describedby="basic-addon1">
</textarea>
</div>
<div className="input-group">
<label htmlFor="destination">To:</label>
<textarea name="destination" className="form-control" readOnly
value={this.props.receiveAddress} placeholder="Address"
aria-describedby="basic-addon1">
</textarea>
</div>
<div className="input-group">
<label htmlFor="txid">TX ID:</label>
<textarea name="txid" className="form-control" readOnly
value={this.props.txid} placeholder="Address"
aria-describedby="basic-addon1" rows="3">
</textarea>
</div>
<input type="hidden" readOnly name="private_key"
value={this.props.privateKey} />
<input type="hidden" readOnly name="public_key"
value={this.props.publicKey} />
<div className="form-group">
<label htmlFor="amount">Amount:</label>
<input readOnly name="amount" value={this.props.sendAmount} />
</div>
<div className="form-group">
<label htmlFor="fee">Fee(BTC):</label>
<input readOnly name="fee" value={this.props.sendFee} />
</div>
<div className="form-group">
<label htmlFor="total">Total:</label>
<input readOnly name="total" value={this.props.sendTotal} />
</div>
<button type="submit" className="sent-close button-shine">
Close
</button>
</form>
:
<div></div>
}
</div>
);
}
} | safex/safex_wallet | src/components/partials/TransactionSentModal.js | JavaScript | mit | 4,367 |
#pragma once
#include <vector>
#include <memory>
#ifndef ARBITER_IS_AMALGAMATION
#include <arbiter/driver.hpp>
#include <arbiter/util/http.hpp>
#endif
#ifdef ARBITER_CUSTOM_NAMESPACE
namespace ARBITER_CUSTOM_NAMESPACE
{
#endif
namespace arbiter
{
namespace drivers
{
/** @brief HTTP driver. Intended as both a standalone driver as well as a base
* for derived drivers build atop HTTP.
*
* Derivers should overload the HTTP-specific put/get methods that accept
* headers and query parameters rather than Driver::put and Driver::get.
*
* Internal methods for derivers are provided as protected methods.
*/
class ARBITER_DLL Http : public Driver
{
public:
Http(http::Pool& pool);
static std::unique_ptr<Http> create(http::Pool& pool);
// Inherited from Driver.
virtual std::string type() const override { return "http"; }
/** By default, performs a HEAD request and returns the contents of the
* Content-Length header.
*/
virtual std::unique_ptr<std::size_t> tryGetSize(
std::string path) const override;
virtual void put(
std::string path,
const std::vector<char>& data) const final override
{
put(path, data, http::Headers(), http::Query());
}
/* HTTP-specific driver methods follow. Since many drivers (S3, Dropbox,
* etc.) are built atop HTTP, we'll provide HTTP-specific methods for
* derived classes to use in addition to the generic PUT/GET combinations.
*
* Specifically, we'll add POST/HEAD calls, and allow headers and query
* parameters to be passed as well.
*/
/** Perform an HTTP GET request. */
std::string get(
std::string path,
http::Headers headers = http::Headers(),
http::Query query = http::Query()) const;
/** Perform an HTTP GET request. */
std::unique_ptr<std::string> tryGet(
std::string path,
http::Headers headers = http::Headers(),
http::Query query = http::Query()) const;
/* Perform an HTTP HEAD request. */
std::size_t getSize(
std::string path,
http::Headers headers,
http::Query query = http::Query()) const;
/* Perform an HTTP HEAD request. */
std::unique_ptr<std::size_t> tryGetSize(
std::string path,
http::Headers headers,
http::Query query = http::Query()) const;
/** Perform an HTTP GET request. */
std::vector<char> getBinary(
std::string path,
http::Headers headers,
http::Query query) const;
/** Perform an HTTP GET request. */
std::unique_ptr<std::vector<char>> tryGetBinary(
std::string path,
http::Headers headers,
http::Query query) const;
/** Perform an HTTP PUT request. */
void put(
std::string path,
const std::string& data,
http::Headers headers,
http::Query query) const;
/** HTTP-derived Drivers should override this version of PUT to allow for
* custom headers and query parameters.
*/
/** Perform an HTTP PUT request. */
virtual void put(
std::string path,
const std::vector<char>& data,
http::Headers headers,
http::Query query) const;
void post(
std::string path,
const std::string& data,
http::Headers headers,
http::Query query) const;
void post(
std::string path,
const std::vector<char>& data,
http::Headers headers,
http::Query query) const;
/* These operations are other HTTP-specific calls that derived drivers may
* need for their underlying API use.
*/
http::Response internalGet(
std::string path,
http::Headers headers = http::Headers(),
http::Query query = http::Query(),
std::size_t reserve = 0) const;
http::Response internalPut(
std::string path,
const std::vector<char>& data,
http::Headers headers = http::Headers(),
http::Query query = http::Query()) const;
http::Response internalHead(
std::string path,
http::Headers headers = http::Headers(),
http::Query query = http::Query()) const;
http::Response internalPost(
std::string path,
const std::vector<char>& data,
http::Headers headers = http::Headers(),
http::Query query = http::Query()) const;
protected:
/** HTTP-derived Drivers should override this version of GET to allow for
* custom headers and query parameters.
*/
virtual bool get(
std::string path,
std::vector<char>& data,
http::Headers headers,
http::Query query) const;
http::Pool& m_pool;
private:
virtual bool get(
std::string path,
std::vector<char>& data) const final override
{
return get(path, data, http::Headers(), http::Query());
}
std::string typedPath(const std::string& p) const;
};
/** @brief HTTPS driver. Identical to the HTTP driver except for its type
* string.
*/
class Https : public Http
{
public:
Https(http::Pool& pool) : Http(pool) { }
static std::unique_ptr<Https> create(http::Pool& pool)
{
return std::unique_ptr<Https>(new Https(pool));
}
virtual std::string type() const override { return "https"; }
};
} // namespace drivers
} // namespace arbiter
#ifdef ARBITER_CUSTOM_NAMESPACE
}
#endif
| connormanning/arbiter | arbiter/drivers/http.hpp | C++ | mit | 5,624 |
Chance = require('chance');
chance = new Chance();
function generateStudent() {
var numberOfStudent = chance.integer({
min: 0,
max: 10
})
console.log(numberOfStudent);
var students = [];
for (var i = 0; i < numberOfStudent; i++) {
var birthYear = chance.year({
min: 1990,
max: 2000
});
var gender = chance.gender();
students.push({
firstname: chance.first({
gender: gender
}),
lastname: chance.last(),
gender: gender,
birthday: chance.birthday({
year: birthYear
})
});
}
console.log(students);
return students;
}
function genPlaName() {
var planetsName = ["Sun", "Kepler", "Earth", "Dagoba", "Coruscant", "Venus", "Jupiter", "Hoth"];
var idName = chance.integer({
min: 0,
max: planetsName.length-1
});
var rndNumber = chance.integer({
min: 1,
max: 9999
});
return planetsName[idName] + "-" + rndNumber;
}
function generatePlanet() {
var nbrOfPlanet = chance.integer({
min: 1,
max: 10
});
var planets = [];
for (var i = 0; i < nbrOfPlanet; i++) {
var minTemperature = chance.integer({
min: -270,
max: 1000
});
var maxTemperature = chance.integer({
min: minTemperature,
max: 1000
});
planets.push({
name: genPlaName(),
minTemperature: minTemperature,
maxTemperature: maxTemperature
});
}
console.log(planets);
return planets;
}
function generatePayload() {
return generatePlanet();
}
exports.generatePayload = generatePayload;
| verdonarthur/Teaching-HEIGVD-RES-2016-Labo-HTTPInfra | docker-images/node-image/src/jsonPayloadGen.js | JavaScript | mit | 1,797 |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from distutils.core import setup, Extension
setup(name='sample',
ext_modules=[
Extension('sample',
['pysample.c'],
include_dirs=['/some/dir'],
define_macros=[('FOO', '1')],
undef_macros=['BAR'],
library_dirs=['/usr/local/lib'],
libraries=['sample']
)
]
)
| xu6148152/Binea_Python_Project | PythonCookbook/interaction_c/setup.py | Python | mit | 474 |
<?php
namespace Override\ScrumBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Override\FosUserBundle\Entity\User;
use Override\ScrumBundle\Form\UserType as UserType;
use Override\ScrumBundle\Entity\SecretaireFormation;
use Override\ScrumBundle\Entity\Professeur;
use Override\ScrumBundle\Entity\Etudiant;
/**
* User controller.
*
* @Route("/user")
*/
class UserController extends Controller
{
/**
* Lists all User entities.
*
* @Secure({"ROLE_ADMIN", "ROLE_SECRETARY"})
* @Route("/", name="user")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('OverrideFosUserBundle:User')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Displays a form to edit an existing User entity.
*
* @Secure(roles="ROLE_ADMIN")
* @Route("/{id}/edit", name="user_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('OverrideFosUserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a User entity.
*
* @param User $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(User $entity)
{
$form = $this->createForm(new UserType(), $entity, array(
'action' => $this->generateUrl('user_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing User entity.
*
* @Secure(roles="ROLE_ADMIN")
* @Route("/{id}", name="user_update")
* @Method("PUT")
* @Template("OverrideScrumBundle:User:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
/** Retrieve the user **/
$user = $em->getRepository('OverrideFosUserBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
/** Set edit and delete form **/
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($user);
$editForm->handleRequest($request);
/** Form is valid we can insert the user **/
if ($editForm->isValid()) {
/** Remove user from all table where he can exist**/
$issetSecretaire = $em->getRepository('OverrideScrumBundle:SecretaireFormation')->findOneBy(array('user' => $user->getId()));
if($issetSecretaire) {
$em->remove($issetSecretaire);
}
$issetProfesseur = $em->getRepository('OverrideScrumBundle:Professeur')->findOneBy(array('user' => $user->getId()));
if($issetProfesseur) {
$em->remove($issetProfesseur);
}
$issetEtudiant = $em->getRepository('OverrideScrumBundle:Etudiant')->findOneBy(array('user' => $user->getId()));
if($issetEtudiant) {
$em->remove($issetEtudiant);
}
// Flushes remove from enity
$em->flush();
// Set the user role and persist
$user->setRoles(array($editForm->get('roles')->getData()));
$em->persist($user);
/** Insert in database (depends of user role) **/
switch ($editForm->get('roles')->getData()) {
case 'ROLE_ADMIN':
$user->setRoles(array('ROLE_ADMIN'));
break;
case 'ROLE_SECRETARY':
$secretaire = new SecretaireFormation();
$secretaire->setUser($user);
$em->persist($secretaire);
break;
case 'ROLE_PROFESSOR':
$professeur = new Professeur();
$professeur->setUser($user);
$em->persist($professeur);
break;
case 'ROLE_STUDENT':
// If the diplome is null redirect the user
if($editForm->get('dernierDiplome')->getData() == NULL) {
$this->get('session')->getFlashBag()->add(
"danger",
"Le diplôme doit être rempli pour l'étudiant."
);
return $this->redirect($this->generateUrl('user_edit', array('id' => $user->getId())));
}
$etudiant = new Etudiant();
$etudiant->setUser($user);
$etudiant->setDernierDiplome($editForm->get('dernierDiplome')->getData());
$em->persist($etudiant);
break;
default:
return $this->redirect($this->generateUrl('user_edit', array('id' => $user->getId())));
break;
}
// Flush in the database
$em->flush();
// Redirect to the user list
return $this->redirect($this->generateUrl('user'));
}
// Redirect to the form when form not valid
return array(
'entity' => $user,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a User entity.
*
* @Secure(roles="ROLE_ADMIN")
* @Route("/{id}", name="user_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('OverrideFosUserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('user'));
}
/**
* Creates a form to delete a User entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('user_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
} | debflav/scrum | src/Override/ScrumBundle/Controller/UserController.php | PHP | mit | 7,518 |
dojo.provide("plugins.core.Agua.File");
/* SUMMARY: THIS CLASS IS INHERITED BY Agua.js AND CONTAINS FILE CACHE
AND FILE MANIPULATION METHODS
*/
dojo.declare( "plugins.core.Agua.File", [ ], {
/////}}}
// FILECACHE METHODS
getFoldersUrl : function () {
return Agua.cgiUrl + "agua.cgi?";
},
setFileCaches : function (url) {
console.log("Agua.File.setFileCache url: " + url);
var callback = dojo.hitch(this, function (data) {
//console.log("Agua.File.setFileCache BEFORE setData, data: ");
//console.dir({data:data});
this.setData("filecaches", data);
});
//console.log("Agua.File.setFileCache Doing this.fetchJson(url, callback)");
this.fetchJson(url, callback);
},
fetchJson : function (url, callback) {
console.log("Agua.File.fetchJson url: " + url);
var thisObject = this;
dojo.xhrGet({
url: url,
sync: false,
handleAs: "json",
handle: function(data) {
//console.log("Agua.File.fetchJson data: ");
//console.dir({data:data});
callback(data);
},
error: function(response) {
console.log("Agua.File.fetchJson Error with JSON Post, response: " + response);
}
});
},
getFileCache : function (username, location) {
console.log("Agua.File.getFileCache username: " + username);
console.log("Agua.File.getFileCache location: " + location);
var fileCaches = this.cloneData("filecaches");
console.log("Agua.File.getFileCache fileCaches: ");
console.dir({fileCaches:fileCaches});
// RETURN IF NO ENTRIES FOR USER
if ( ! fileCaches[username] ) return null;
return fileCaches[username][location];
},
setFileCache : function (username, location, item) {
console.log("Agua.File.setFileCache username: " + username);
console.log("Agua.File.setFileCache location: " + location);
console.log("Agua.File.setFileCache item: ");
console.dir({item:item});
var fileCaches = this.getData("filecaches");
console.log("Agua.File.setFileCache fileCaches: ");
console.dir({fileCaches:fileCaches});
if ( ! fileCaches ) fileCaches = {};
if ( ! fileCaches[username] ) fileCaches[username] = {};
fileCaches[username][location] = item;
var parentDir = this.getParentDir(location);
console.log("Agua.File.setFileCache parentDir: " + parentDir);
if ( ! parentDir ) {
console.log("Agua.File.setFileCache SETTING fileCaches[" + username + "][" + location + "] = item");
fileCaches[username][location] = item;
return;
}
var parent = fileCaches[username][parentDir];
console.log("Agua.File.setFileCache parent: " + parent);
if ( ! parent ) return;
console.log("Agua.File.setFileCache parent: " + parent);
this.addItemToParent(parent, item);
console.log("Agua.File.setFileCache parent: " + parent);
console.dir({parent:parent});
},
addItemToParent : function (parent, item) {
parent.items.push(item);
},
getFileSystem : function (putData, callback, request) {
console.log("Agua.File.getFileSystem caller: " + this.getFileSystem.caller.nom);
console.log("Agua.File.getFileSystem putData:");
console.dir({putData:putData});
console.log("Agua.File.getFileSystem callback: " + callback);
console.dir({callback:callback});
console.log("Agua.File.getFileSystem request:");
console.dir({request:request});
// SET DEFAULT ARGS EMPTY ARRAY
if ( ! request )
request = new Array;
// SET LOCATION
var location = '';
if ( putData.location || putData.query )
location = putData.query || putData.location;
console.log("Agua.File.getFileSystem location: " + location);
var username = putData.username;
console.log("Agua.File.getFileSystem username: " + username);
// USE IF CACHED
var fileCache = this.getFileCache(username, location);
console.log("Agua.File.getFileSystem fileCache:");
console.dir({fileCache:fileCache});
if ( fileCache ) {
console.log("Agua.File.getFileSystem fileCache IS DEFINED. Doing setTimeout callback(fileCache, request)");
// DELAY TO AVOID node is undefined ERROR
setTimeout( function() {
callback(fileCache, request);
},
10,
this);
return;
}
else {
console.log("Agua.File.getFileSystem fileCache NOT DEFINED. Doing remote query");
this.queryFileSystem(putData, callback, request);
}
},
queryFileSystem : function (putData, callback, request) {
console.log("Agua.File.queryFileSystem putData:");
console.dir({putData:putData});
console.log("Agua.File.queryFileSystem callback:");
console.dir({callback:callback});
console.log("Agua.File.queryFileSystem request:");
console.dir({request:request});
// SET LOCATION
var location = '';
if ( putData.location || putData.query )
location = putData.query;
if ( ! putData.path && location ) putData.path = location;
console.log("Agua.File.queryFileSystem location: " + location);
// SET USERNAME
var username = putData.username;
var url = this.cgiUrl + "agua.cgi";
// QUERY REMOTE
var thisObject = this;
var putArgs = {
url : url,
//url : putData.url,
contentType : "text",
sync : false,
preventCache: true,
handleAs : "json-comment-optional",
putData : dojo.toJson(putData),
handle : function(response) {
console.log("Agua.File.queryFileSystem handle response:");
console.dir({response:response});
console.log("Agua.File.queryFileSystem BEFORE this.setFileCache()");
thisObject.setFileCache(username, location, dojo.clone(response));
console.log("Agua.File.queryFileSystem AFTER this.setFileCache()");
//callback(response, request);
}
};
var deferred = dojo.xhrPut(putArgs);
deferred.addCallback(callback);
var scope = request.scope || dojo.global;
deferred.addErrback(function(error){
if(request.onError){
request.onError.call(scope, error, request);
}
});
},
removeFileTree : function (username, location) {
console.log("Agua.File.removeFileTree username: " + username);
console.log("Agua.File.removeFileTree location: " + location);
var fileCaches = this.getData("filecaches");
console.log("Agua.File.removeFileTree fileCaches: ");
console.dir({fileCaches:fileCaches});
if ( ! fileCaches ) {
console.log("Agua.File.removeFileTree fileCaches is null. Returning");
return;
}
var rootTree = fileCaches[username];
console.log("Agua.File.removeFileTree rootTree: ");
console.dir({rootTree:rootTree});
if ( ! rootTree ) {
console.log("Agua.File.removeFileTree rootTree is null. Returning");
return;
}
for ( var fileRoot in fileCaches[username] ) {
if ( fileRoot.match('^' + location +'$')
|| fileRoot.match('^' + location +'\/') ) {
console.log("Agua.File.removeFileTree DELETING fileRoot: " + fileRoot);
// delete fileCaches[username][fileRoot];
}
}
if ( ! location.match(/^(.+)\/[^\/]+$/) ) {
console.log("Agua.File.removeFileTree No parentDir. Returning");
return;
}
var parentDir = location.match(/^(.+)\/[^\/]+$/)[1];
var child = location.match(/^.+\/([^\/]+)$/)[1];
console.log("Agua.File.removeFileTree parentDir: " + parentDir);
console.log("Agua.File.removeFileTree child: " + child);
this.removeItemFromParent(fileCaches[username][parentDir], child);
var project1 = fileCaches[username][parentDir];
console.log("Agua.File.removeFileTree project1: " + project1);
console.dir({project1:project1});
console.log("Agua.File.removeFileTree END");
},
removeItemFromParent : function (parent, childName) {
for ( i = 0; i < parent.items.length; i++ ) {
var childObject = parent.items[i];
if ( childObject.name == childName ) {
parent.items.splice(i, 1);
break;
}
}
},
removeRemoteFile : function (username, location, callback) {
console.log("Agua.File.removeRemoteFile username: " + username);
console.log("Agua.File.removeRemoteFile location: " + location);
console.log("Agua.File.removeRemoteFile callback: " + callback);
// DELETE ON REMOTE
var url = this.getFoldersUrl();
var putData = new Object;
putData.mode = "removeFile";
putData.module = "Folders";
putData.sessionid = Agua.cookie('sessionid');
putData.username = Agua.cookie('username');
putData.file = location;
var thisObject = this;
dojo.xhrPut(
{
url : url,
putData : dojo.toJson(putData),
handleAs : "json",
sync : false,
handle : function(response) {
if ( callback ) callback(response);
}
}
);
},
renameFileTree : function (username, oldLocation, newLocation) {
console.log("Agua.File.renameFileTree username: " + username);
console.log("Agua.File.renameFileTree oldLocation: " + oldLocation);
console.log("Agua.File.renameFileTree newLocation: " + newLocation);
var fileCaches = this.getData("filecaches");
console.log("Agua.File.renameFileTree fileCaches: ");
console.dir({fileCaches:fileCaches});
if ( ! fileCaches ) {
console.log("Agua.File.renameFileTree fileCaches is null. Returning");
return;
}
var rootTree = fileCaches[username];
console.log("Agua.File.renameFileTree rootTree: ");
console.dir({rootTree:rootTree});
if ( ! rootTree ) {
console.log("Agua.File.renameFileTree rootTree is null. Returning");
return;
}
for ( var fileRoot in fileCaches[username] ) {
if ( fileRoot.match('^' + oldLocation +'$')
|| fileRoot.match('^' + oldLocation +'\/') ) {
console.log("Agua.File.renameFileTree DELETING fileRoot: " + fileRoot);
var value = fileCaches[username][fileRoot];
var re = new RegExp('^' + oldLocation);
var newRoot = fileRoot.replace(re, newLocation);
console.log("Agua.File.renameFileTree ADDING newRoot: " + newRoot);
delete fileCaches[username][fileRoot];
fileCaches[username][newRoot] = value;
}
}
console.log("Agua.File.renameFileTree oldLocation: " + oldLocation);
var parentDir = this.getParentDir(oldLocation);
console.log("Agua.File.renameFileTree oldLocation: " + oldLocation);
if ( ! parentDir ) return;
console.log("Agua.File.renameFileTree Doing this.renameItemInParent()");
var child = this.getChild(oldLocation);
var newChild = newLocation.match(/^.+\/([^\/]+)$/)[1];
console.log("Agua.File.renameFileTree parentDir: " + parentDir);
console.log("Agua.File.renameFileTree child: " + child);
console.log("Agua.File.renameFileTree newChild: " + newChild);
var parent = fileCaches[username][parentDir];
this.renameItemInParent(parent, child, newChild);
console.log("Agua.File.renameFileTree parent: " + parent);
console.dir({parent:parent});
console.log("Agua.File.renameFileTree END");
},
renameItemInParent : function (parent, childName, newChildName) {
for ( i = 0; i < parent.items.length; i++ ) {
var childObject = parent.items[i];
if ( childObject.name == childName ) {
var re = new RegExp(childName + "$");
parent.items[i].name= parent.items[i].name.replace(re, newChildName);
console.log("Agua.File.renameItemInParent NEW parent.items[" + i + "].name: " + parent.items[i].name);
parent.items[i].path= parent.items[i].path.replace(re, newChildName);
console.log("Agua.File.repathItemInParent NEW parent.items[" + i + "].path: " + parent.items[i].path);
break;
}
}
},
getParentDir : function (location) {
if ( ! location.match(/^(.+)\/[^\/]+$/) ) return null;
return location.match(/^(.+)\/[^\/]+$/)[1];
},
getChild : function (location) {
if ( ! location.match(/^.+\/([^\/]+)$/) ) return null;
return location.match(/^.+\/([^\/]+)$/)[1];
},
isDirectory : function (username, location) {
// USE IF CACHED
var fileCache = this.getFileCache(username, location);
console.log("Agua.File.isDirectory username: " + username);
console.log("Agua.File.isDirectory location: " + location);
console.log("Agua.File.isDirectory fileCache: ");
console.dir({fileCache:fileCache});
if ( fileCache ) return fileCache.directory;
return null;
},
isFileCacheItem : function (username, directory, itemName) {
console.log("Agua.isFileCacheItem username: " + username);
console.log("Agua.isFileCacheItem directory: " + directory);
console.log("Agua.isFileCacheItem itemName: " + itemName);
var fileCache = this.getFileCache(username, directory);
console.log("Agua.isFileCacheItem fileCache: " + fileCache);
console.dir({fileCache:fileCache});
if ( ! fileCache || ! fileCache.items ) return false;
for ( var i = 0; i < fileCache.items.length; i++ ) {
if ( fileCache.items[i].name == itemName) return true;
}
return false;
},
// FILE METHODS
renameFile : function (oldFilePath, newFilePath) {
// RENAME FILE OR FOLDER ON SERVER
var url = this.getFoldersUrl();
var query = new Object;
query.mode = "renameFile";
query.module = "Agua::Folders";
query.sessionid = Agua.cookie('sessionid');
query.username = Agua.cookie('username');
query.oldpath = oldFilePath;
query.newpath = newFilePath;
this.doPut({ url: url, query: query, sync: false });
},
createFolder : function (folderPath) {
// CREATE FOLDER ON SERVER
var url = this.getFoldersUrl();
var query = new Object;
query.mode = "newFolder";
query.module = "Agua::Folders";
query.sessionid = Agua.cookie('sessionid');
query.username = Agua.cookie('username');
query.folderpath = folderPath;
this.doPut({ url: url, query: query, sync: false });
},
// FILEINFO METHODS
getFileInfo : function (stageParameterObject, fileinfo) {
// GET THE BOOLEAN fileInfo VALUE FOR A STAGE PARAMETER
if ( fileinfo != null )
{
console.log("Agua.File.getFileInfo fileinfo parameter is present. Should you be using setFileInfo instead?. Returning null.");
return null;
}
return this._fileInfo(stageParameterObject, fileinfo);
},
setFileInfo : function (stageParameterObject, fileinfo) {
// SET THE BOOLEAN fileInfo VALUE FOR A STAGE PARAMETER
if ( ! stageParameterObject ) return;
if ( fileinfo == null )
{
console.log("Agua.File.setFileInfo fileinfo is null. Returning null.");
return null;
}
return this._fileInfo(stageParameterObject, fileinfo);
},
_fileInfo : function (stageParameterObject, fileinfo) {
// RETURN THE fileInfo BOOLEAN FOR A STAGE PARAMETER
// OR SET IT IF A VALUE IS SUPPLIED: RETURN NULL IF
// UNSUCCESSFUL, TRUE OTHERWISE
console.log("Agua.File._fileInfo plugins.core.Data._fileInfo()");
console.log("Agua.File._fileInfo stageParameterObject: ");
console.dir({stageParameterObject:stageParameterObject});
console.log("Agua.File._fileInfo fileinfo: ");
console.dir({fileinfo:fileinfo});
var uniqueKeys = ["username", "project", "workflow", "appname", "appnumber", "name", "paramtype"];
var valueArray = new Array;
for ( var i = 0; i < uniqueKeys.length; i++ ) {
valueArray.push(stageParameterObject[uniqueKeys[i]]);
}
var stageParameter = this.getEntry(this.cloneData("stageparameters"), uniqueKeys, valueArray);
console.log("Agua.File._fileInfo stageParameter found: ");
console.dir({stageParameter:stageParameter});
if ( stageParameter == null ) {
console.log("Agua.File._fileInfo stageParameter is null. Returning null");
return null;
}
// RETURN FOR GETTER
if ( fileinfo == null ) {
console.log("Agua.File._fileInfo DOING the GETTER. Returning stageParameter.exists: " + stageParameter.fileinfo.exists);
return stageParameter.fileinfo.exists;
}
console.log("Agua.File._fileInfo DOING the SETTER");
// ELSE, DO THE SETTER
stageParameter.fileinfo = fileinfo;
var success = this._removeStageParameter(stageParameter);
if ( success == false ) {
console.log("Agua.File._fileInfo Could not remove stage parameter. Returning null");
return null;
}
console.log("Agua.File._fileInfo BEFORE success = this._addStageParameter(stageParameter)");
success = this._addStageParameter(stageParameter);
if ( success == false ) {
console.log("Agua.File._fileInfo Could not add stage parameter. Returning null");
return null;
}
return true;
},
// VALIDITY METHODS
getParameterValidity : function (stageParameterObject, booleanValue) {
// GET THE BOOLEAN parameterValidity VALUE FOR A STAGE PARAMETER
//console.log("Agua.File.getParameterValidity plugins.core.Data.getParameterValidity()");
////console.log("Agua.File.getParameterValidity stageParameterObject: " + dojo.toJson(stageParameterObject));
////console.log("Agua.File.getParameterValidity booleanValue: " + booleanValue);
if ( booleanValue != null )
{
//console.log("Agua.File.getParameterValidity booleanValue parameter is present. Should you be using "setParameterValidity" instead?. Returning null.");
return null;
}
var isValid = this._parameterValidity(stageParameterObject, booleanValue);
//console.log("Agua.File.getParameterValidity '" + stageParameterObject.name + "' isValid: " + isValid);
return isValid;
},
setParameterValidity : function (stageParameterObject, booleanValue) {
// SET THE BOOLEAN parameterValidity VALUE FOR A STAGE PARAMETER
////console.log("Agua.File.setParameterValidity plugins.core.Data.setParameterValidity()");
////console.log("Agua.File.setParameterValidity stageParameterObject: " + dojo.toJson(stageParameterObject));
////console.log("Agua.File.setParameterValidity " + stageParameterObject.name + " booleanValue: " + booleanValue);
if ( booleanValue == null )
{
//console.log("Agua.File.setParameterValidity booleanValue is null. Returning null.");
return null;
}
var isValid = this._parameterValidity(stageParameterObject, booleanValue);
//console.log("Agua.File.setParameterValidity '" + stageParameterObject.name + "' isValid: " + isValid);
return isValid;
},
_parameterValidity : function (stageParameterObject, booleanValue) {
// RETURN THE parameterValidity BOOLEAN FOR A STAGE PARAMETER
// OR SET IT IF A VALUE IS SUPPLIED
////console.log("Agua.File._parameterValidity plugins.core.Data._parameterValidity()");
//console.log("Agua.File._parameterValidity stageParameterObject: " + dojo.toJson(stageParameterObject, true));
////console.log("Agua.File._parameterValidity booleanValue: " + booleanValue);
//////var filtered = this._getStageParameters();
//////var keys = ["appname"];
//////var values = ["image2eland.pl"];
//////filtered = this.filterByKeyValues(filtered, keys, values);
////////console.log("Agua.File._parameterValidity filtered: " + dojo.toJson(filtered, true));
var uniqueKeys = ["project", "workflow", "appname", "appnumber", "name", "paramtype"];
var valueArray = new Array;
for ( var i = 0; i < uniqueKeys.length; i++ )
{
valueArray.push(stageParameterObject[uniqueKeys[i]]);
}
var stageParameter = this.getEntry(this._getStageParameters(), uniqueKeys, valueArray);
//console.log("Agua.File._parameterValidity stageParameter found: " + dojo.toJson(stageParameter, true));
if ( stageParameter == null )
{
//console.log("Agua.File._parameterValidity stageParameter is null. Returning null");
return null;
}
if ( booleanValue == null )
return stageParameter.isValid;
//console.log("Agua.File._parameterValidity stageParameter: " + dojo.toJson(stageParameter, true));
//console.log("Agua.File._parameterValidity booleanValue: " + booleanValue);
// SET isValid BOOLEAN VALUE
stageParameter.isValid = booleanValue;
var success = this._removeStageParameter(stageParameter);
if ( success == false )
{
//console.log("Agua.File._parameterValidity Could not remove stage parameter. Returning null");
return null;
}
////console.log("Agua.File._parameterValidity BEFORE success = this._addStageParameter(stageParameter)");
success = this._addStageParameter(stageParameter);
if ( success == false )
{
//console.log("Agua.File._parameterValidity Could not add stage parameter. Returning null");
return null;
}
return true;
}
}); | aguadev/aguadev | html/plugins/core/Agua/File.js | JavaScript | mit | 19,766 |
<?php
/**
* LitePubl CMS
*
* @copyright 2010 - 2017 Vladimir Yushko http://litepublisher.com/ http://litepublisher.ru/
* @license https://github.com/litepubl/cms/blob/master/LICENSE.txt MIT
* @link https://github.com/litepubl\cms
* @version 7.08
*/
namespace litepubl\admin\widget;
use litepubl\admin\Link;
use litepubl\core\PropException;
class Widget extends \litepubl\admin\Panel
{
public $widget;
public function __construct()
{
parent::__construct();
$this->lang->section = 'widgets';
}
public function __get($name)
{
if (method_exists($this, $get = 'get' . $name)) {
return $this->$get();
}
throw new PropException(get_class($this), $name);
}
protected function getAdminurl()
{
return Link::url('/admin/views/widgets/?idwidget=');
}
protected function getForm(): string
{
$title = $this->widget->gettitle($this->widget->id);
$this->args->title = $title;
$this->args->formtitle = $title . ' ' . $this->lang->widget;
return $this->theme->getInput('text', 'title', $title, $this->lang->widgettitle);
}
public function getContent(): string
{
$form = $this->getForm();
return $this->admin->form($form, $this->args);
}
public function processForm()
{
$widget = $this->widget;
$widget->lock();
if (isset($_POST['title'])) {
$widget->settitle($widget->id, $_POST['title']);
}
$this->doProcessForm();
$widget->unlock();
return $this->admin->success($this->lang->updated);
}
protected function doProcessForm()
{
}
}
| litepubl/cms | lib/admin/widget/Widget.php | PHP | mit | 1,705 |
<?php
/**
* Copyright (c) Frank Förster (http://frankfoerster.com)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Frank Förster (http://frankfoerster.com)
* @link http://github.com/frankfoerster/cakephp-migrations
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class IndexAlreadyExistsException extends Exception {
}
| frankfoerster/cakephp-migrations | Model/Exception/IndexAlreadyExistsException.php | PHP | mit | 537 |
using System;
using System.Collections;
namespace AppStudio.Data
{
/// <summary>
/// Implementation of the MainSchema class.
/// </summary>
public class MainSchema : BindableSchemaBase, IEquatable<MainSchema>
{
private string _title;
private string _subtitle;
private string _image;
private string _description;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public string Subtitle
{
get { return _subtitle; }
set { SetProperty(ref _subtitle, value); }
}
public string Image
{
get { return _image; }
set { SetProperty(ref _image, value); }
}
public string Description
{
get { return _description; }
set { SetProperty(ref _description, value); }
}
public override string DefaultTitle
{
get { return Title; }
}
public override string DefaultSummary
{
get { return Subtitle; }
}
public override string DefaultImageUrl
{
get { return Image; }
}
public override string DefaultContent
{
get { return Subtitle; }
}
override public string GetValue(string fieldName)
{
if (!String.IsNullOrEmpty(fieldName))
{
switch (fieldName.ToLowerInvariant())
{
case "title":
return String.Format("{0}", Title);
case "subtitle":
return String.Format("{0}", Subtitle);
case "image":
return String.Format("{0}", Image);
case "description":
return String.Format("{0}", Description);
case "defaulttitle":
return DefaultTitle;
case "defaultsummary":
return DefaultSummary;
case "defaultimageurl":
return DefaultImageUrl;
default:
break;
}
}
return String.Empty;
}
public bool Equals(MainSchema other)
{
if (other == null)
{
return false;
}
return this.Title == other.Title && this.Subtitle == other.Subtitle && this.Image == other.Image && this.Description == other.Description;
}
}
}
| AppStudioSamples/Menu | scr/ClientApp/AppStudio.Data/DataSchemas/MainSchema.cs | C# | mit | 2,679 |
package org.onceatime.concurrent;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class RwSample {
public static void main(String[] args) {
class CachedData {
Object data;
volatile boolean cacheValid;
final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
void processCachedData() {
rwl.readLock().lock();
if (!cacheValid) {
// Must release read lock before acquiring write lock
rwl.readLock().unlock();
rwl.writeLock().lock();
try {
// Recheck state because another thread might have
// acquired write lock and changed state before we did.
if (!cacheValid) {
data = getData();
cacheValid = true;
}
// Downgrade by acquiring read lock before releasing write lock
rwl.readLock().lock();
} finally {
rwl.writeLock().unlock(); // Unlock write, still hold read
}
}
try {
use(data);
} finally {
rwl.readLock().unlock();
}
}
private Object getData() {
// TODO Auto-generated method stub
return null;
}
private void use(Object data2) {
// TODO Auto-generated method stub
}
}}
}
| chinafzy/java-practise | src/main/java/org/onceatime/concurrent/RwSample.java | Java | mit | 1,437 |
import { globalThis } from './global-this';
/**
* Detect if running in Node.js.
* @type {boolean}
*/
const isNode = Object.prototype.toString.call(globalThis.process) === '[object process]';
export { isNode };
| zant95/otpauth | src/utils/is-node.js | JavaScript | mit | 215 |
/**
* History.js Core
* History.js HTML4 Support
* @author Benjamin Arthur Lupton <contact@balupton.com>
* @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
define(function(require){
"use strict";
// ========================================================================
// Initialise
// Localise Globals
var
console = window.console||undefined, // Prevent a JSLint complain
document = window.document, // Make sure we are using the correct document
navigator = window.navigator, // Make sure we are using the correct navigator
sessionStorage = window.sessionStorage||false, // sessionStorage
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
setInterval = window.setInterval,
clearInterval = window.clearInterval,
JSON = window.JSON,
alert = window.alert,
History = window.History = window.History||{}, // Public History Object
history = window.history; // Old History Object
try {
sessionStorage.setItem('TEST', '1');
sessionStorage.removeItem('TEST');
} catch(e) {
sessionStorage = false;
}
// MooTools Compatibility
JSON.stringify = JSON.stringify||JSON.encode;
JSON.parse = JSON.parse||JSON.decode;
// Check Existence
if ( typeof History.init !== 'undefined' ) {
throw new Error('History.js Core has already been loaded...');
}
// Add the Adapter
History.Adapter = {
/**
* History.Adapter.handlers[uid][eventName] = Array
*/
handlers: {},
/**
* History.Adapter._uid
* The current element unique identifier
*/
_uid: 1,
/**
* History.Adapter.uid(element)
* @param {Element} element
* @return {String} uid
*/
uid: function(element){
return element._uid || (element._uid = History.Adapter._uid++);
},
/**
* History.Adapter.bind(el,event,callback)
* @param {Element} element
* @param {String} eventName - custom and standard events
* @param {Function} callback
* @return
*/
bind: function(element,eventName,callback){
// Prepare
var uid = History.Adapter.uid(element);
// Apply Listener
History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
History.Adapter.handlers[uid][eventName].push(callback);
// Bind Global Listener
element['on'+eventName] = (function(element,eventName){
return function(event){
History.Adapter.trigger(element,eventName,event);
};
})(element,eventName);
},
/**
* History.Adapter.trigger(el,event)
* @param {Element} element
* @param {String} eventName - custom and standard events
* @param {Object} event - a object of event data
* @return
*/
trigger: function(element,eventName,event){
// Prepare
event = event || {};
var uid = History.Adapter.uid(element),
i,n;
// Apply Listener
History.Adapter.handlers[uid] = History.Adapter.handlers[uid] || {};
History.Adapter.handlers[uid][eventName] = History.Adapter.handlers[uid][eventName] || [];
// Fire Listeners
for ( i=0,n=History.Adapter.handlers[uid][eventName].length; i<n; ++i ) {
History.Adapter.handlers[uid][eventName][i].apply(this,[event]);
}
},
/**
* History.Adapter.extractEventData(key,event,extra)
* @param {String} key - key for the event data to extract
* @param {String} event - custom and standard events
* @return {mixed}
*/
extractEventData: function(key,event){
var result = (event && event[key]) || undefined;
return result;
},
/**
* History.Adapter.onDomLoad(callback)
* @param {Function} callback
* @return
*/
onDomLoad: function(callback) {
var timeout = window.setTimeout(function(){
callback();
},2000);
window.onload = function(){
clearTimeout(timeout);
callback();
};
}
};
// Initialise HTML4 Support
History.initHtml4 = function(){
// Initialise
if ( typeof History.initHtml4.initialized !== 'undefined' ) {
// Already Loaded
return false;
}
else {
History.initHtml4.initialized = true;
}
// ====================================================================
// Properties
/**
* History.enabled
* Is History enabled?
*/
History.enabled = true;
// ====================================================================
// Hash Storage
/**
* History.savedHashes
* Store the hashes in an array
*/
History.savedHashes = [];
/**
* History.isLastHash(newHash)
* Checks if the hash is the last hash
* @param {string} newHash
* @return {boolean} true
*/
History.isLastHash = function(newHash){
// Prepare
var oldHash = History.getHashByIndex(),
isLast;
// Check
isLast = newHash === oldHash;
// Return isLast
return isLast;
};
/**
* History.isHashEqual(newHash, oldHash)
* Checks to see if two hashes are functionally equal
* @param {string} newHash
* @param {string} oldHash
* @return {boolean} true
*/
History.isHashEqual = function(newHash, oldHash){
newHash = encodeURIComponent(newHash).replace(/%25/g, "%");
oldHash = encodeURIComponent(oldHash).replace(/%25/g, "%");
return newHash === oldHash;
};
/**
* History.saveHash(newHash)
* Push a Hash
* @param {string} newHash
* @return {boolean} true
*/
History.saveHash = function(newHash){
// Check Hash
if ( History.isLastHash(newHash) ) {
return false;
}
// Push the Hash
History.savedHashes.push(newHash);
// Return true
return true;
};
/**
* History.getHashByIndex()
* Gets a hash by the index
* @param {integer} index
* @return {string}
*/
History.getHashByIndex = function(index){
// Prepare
var hash = null;
// Handle
if ( typeof index === 'undefined' ) {
// Get the last inserted
hash = History.savedHashes[History.savedHashes.length-1];
}
else if ( index < 0 ) {
// Get from the end
hash = History.savedHashes[History.savedHashes.length+index];
}
else {
// Get from the beginning
hash = History.savedHashes[index];
}
// Return hash
return hash;
};
// ====================================================================
// Discarded States
/**
* History.discardedHashes
* A hashed array of discarded hashes
*/
History.discardedHashes = {};
/**
* History.discardedStates
* A hashed array of discarded states
*/
History.discardedStates = {};
/**
* History.discardState(State)
* Discards the state by ignoring it through History
* @param {object} State
* @return {true}
*/
History.discardState = function(discardedState,forwardState,backState){
//History.debug('History.discardState', arguments);
// Prepare
var discardedStateHash = History.getHashByState(discardedState),
discardObject;
// Create Discard Object
discardObject = {
'discardedState': discardedState,
'backState': backState,
'forwardState': forwardState
};
// Add to DiscardedStates
History.discardedStates[discardedStateHash] = discardObject;
// Return true
return true;
};
/**
* History.discardHash(hash)
* Discards the hash by ignoring it through History
* @param {string} hash
* @return {true}
*/
History.discardHash = function(discardedHash,forwardState,backState){
//History.debug('History.discardState', arguments);
// Create Discard Object
var discardObject = {
'discardedHash': discardedHash,
'backState': backState,
'forwardState': forwardState
};
// Add to discardedHash
History.discardedHashes[discardedHash] = discardObject;
// Return true
return true;
};
/**
* History.discardedState(State)
* Checks to see if the state is discarded
* @param {object} State
* @return {bool}
*/
History.discardedState = function(State){
// Prepare
var StateHash = History.getHashByState(State),
discarded;
// Check
discarded = History.discardedStates[StateHash]||false;
// Return true
return discarded;
};
/**
* History.discardedHash(hash)
* Checks to see if the state is discarded
* @param {string} State
* @return {bool}
*/
History.discardedHash = function(hash){
// Check
var discarded = History.discardedHashes[hash]||false;
// Return true
return discarded;
};
/**
* History.recycleState(State)
* Allows a discarded state to be used again
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.recycleState = function(State){
//History.debug('History.recycleState', arguments);
// Prepare
var StateHash = History.getHashByState(State);
// Remove from DiscardedStates
if ( History.discardedState(State) ) {
delete History.discardedStates[StateHash];
}
// Return true
return true;
};
// ====================================================================
// HTML4 HashChange Support
if ( History.emulated.hashChange ) {
/*
* We must emulate the HTML4 HashChange Support by manually checking for hash changes
*/
/**
* History.hashChangeInit()
* Init the HashChange Emulation
*/
History.hashChangeInit = function(){
// Define our Checker Function
History.checkerFunction = null;
// Define some variables that will help in our checker function
var lastDocumentHash = '',
iframeId, iframe,
lastIframeHash, checkerRunning,
startedWithHash = Boolean(History.getHash());
// Handle depending on the browser
if ( History.isInternetExplorer() ) {
// IE6 and IE7
// We need to use an iframe to emulate the back and forward buttons
// Create iFrame
iframeId = 'historyjs-iframe';
iframe = document.createElement('iframe');
// Adjust iFarme
// IE 6 requires iframe to have a src on HTTPS pages, otherwise it will throw a
// "This page contains both secure and nonsecure items" warning.
iframe.setAttribute('id', iframeId);
iframe.setAttribute('src', '#');
iframe.style.display = 'none';
// Append iFrame
document.body.appendChild(iframe);
// Create initial history entry
iframe.contentWindow.document.open();
iframe.contentWindow.document.close();
// Define some variables that will help in our checker function
lastIframeHash = '';
checkerRunning = false;
// Define the checker function
History.checkerFunction = function(){
// Check Running
if ( checkerRunning ) {
return false;
}
// Update Running
checkerRunning = true;
// Fetch
var
documentHash = History.getHash(),
iframeHash = History.getHash(iframe.contentWindow.document);
// The Document Hash has changed (application caused)
if ( documentHash !== lastDocumentHash ) {
// Equalise
lastDocumentHash = documentHash;
// Create a history entry in the iframe
if ( iframeHash !== documentHash ) {
//History.debug('hashchange.checker: iframe hash change', 'documentHash (new):', documentHash, 'iframeHash (old):', iframeHash);
// Equalise
lastIframeHash = iframeHash = documentHash;
// Create History Entry
iframe.contentWindow.document.open();
iframe.contentWindow.document.close();
// Update the iframe's hash
iframe.contentWindow.document.location.hash = History.escapeHash(documentHash);
}
// Trigger Hashchange Event
History.Adapter.trigger(window,'hashchange');
}
// The iFrame Hash has changed (back button caused)
else if ( iframeHash !== lastIframeHash ) {
//History.debug('hashchange.checker: iframe hash out of sync', 'iframeHash (new):', iframeHash, 'documentHash (old):', documentHash);
// Equalise
lastIframeHash = iframeHash;
// If there is no iframe hash that means we're at the original
// iframe state.
// And if there was a hash on the original request, the original
// iframe state was replaced instantly, so skip this state and take
// the user back to where they came from.
if (startedWithHash && iframeHash === '') {
History.back();
}
else {
// Update the Hash
History.setHash(iframeHash,false);
}
}
// Reset Running
checkerRunning = false;
// Return true
return true;
};
}
else {
// We are not IE
// Firefox 1 or 2, Opera
// Define the checker function
History.checkerFunction = function(){
// Prepare
var documentHash = History.getHash()||'';
// The Document Hash has changed (application caused)
if ( documentHash !== lastDocumentHash ) {
// Equalise
lastDocumentHash = documentHash;
// Trigger Hashchange Event
History.Adapter.trigger(window,'hashchange');
}
// Return true
return true;
};
}
// Apply the checker function
History.intervalList.push(setInterval(History.checkerFunction, History.options.hashChangeInterval));
// Done
return true;
}; // History.hashChangeInit
// Bind hashChangeInit
History.Adapter.onDomLoad(History.hashChangeInit);
} // History.emulated.hashChange
// ====================================================================
// HTML5 State Support
// Non-Native pushState Implementation
if ( History.emulated.pushState ) {
/*
* We must emulate the HTML5 State Management by using HTML4 HashChange
*/
/**
* History.onHashChange(event)
* Trigger HTML5's window.onpopstate via HTML4 HashChange Support
*/
History.onHashChange = function(event){
//History.debug('History.onHashChange', arguments);
// Prepare
var currentUrl = ((event && event.newURL) || History.getLocationHref()),
currentHash = History.getHashByUrl(currentUrl),
currentState = null,
currentStateHash = null,
currentStateHashExits = null,
discardObject;
// Check if we are the same state
if ( History.isLastHash(currentHash) ) {
// There has been no change (just the page's hash has finally propagated)
//History.debug('History.onHashChange: no change');
History.busy(false);
return false;
}
// Reset the double check
History.doubleCheckComplete();
// Store our location for use in detecting back/forward direction
History.saveHash(currentHash);
// Expand Hash
if ( currentHash && History.isTraditionalAnchor(currentHash) ) {
//History.debug('History.onHashChange: traditional anchor', currentHash);
// Traditional Anchor Hash
History.Adapter.trigger(window,'anchorchange');
History.busy(false);
return false;
}
// Create State
currentState = History.extractState(History.getFullUrl(currentHash||History.getLocationHref()),true);
// Check if we are the same state
if ( History.isLastSavedState(currentState) ) {
//History.debug('History.onHashChange: no change');
// There has been no change (just the page's hash has finally propagated)
History.busy(false);
return false;
}
// Create the state Hash
currentStateHash = History.getHashByState(currentState);
// Check if we are DiscardedState
discardObject = History.discardedState(currentState);
if ( discardObject ) {
// Ignore this state as it has been discarded and go back to the state before it
if ( History.getHashByIndex(-2) === History.getHashByState(discardObject.forwardState) ) {
// We are going backwards
//History.debug('History.onHashChange: go backwards');
History.back(false);
} else {
// We are going forwards
//History.debug('History.onHashChange: go forwards');
History.forward(false);
}
return false;
}
// Push the new HTML5 State
//History.debug('History.onHashChange: success hashchange');
History.pushState(currentState.data,currentState.title,encodeURI(currentState.url),false);
// End onHashChange closure
return true;
};
History.Adapter.bind(window,'hashchange',History.onHashChange);
/**
* History.pushState(data,title,url)
* Add a new State to the history object, become it, and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.pushState = function(data,title,url,queue){
//History.debug('History.pushState: called', arguments);
// We assume that the URL passed in is URI-encoded, but this makes
// sure that it's fully URI encoded; any '%'s that are encoded are
// converted back into '%'s
url = encodeURI(url).replace(/%25/g, "%");
// Check the State
if ( History.getHashByUrl(url) ) {
throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.pushState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.pushState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy
History.busy(true);
// Fetch the State Object
var newState = History.createStateObject(data,title,url),
newStateHash = History.getHashByState(newState),
oldState = History.getState(false),
oldStateHash = History.getHashByState(oldState),
html4Hash = History.getHash(),
wasExpected = History.expectedStateId == newState.id;
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Recycle the State
History.recycleState(newState);
// Force update of the title
History.setTitle(newState);
// Check if we are the same State
if ( newStateHash === oldStateHash ) {
//History.debug('History.pushState: no change', newStateHash);
History.busy(false);
return false;
}
// Update HTML5 State
History.saveState(newState);
// Fire HTML5 Event
if(!wasExpected)
History.Adapter.trigger(window,'statechange');
// Update HTML4 Hash
if ( !History.isHashEqual(newStateHash, html4Hash) && !History.isHashEqual(newStateHash, History.getShortUrl(History.getLocationHref())) ) {
History.setHash(newStateHash,false);
}
History.busy(false);
// End pushState closure
return true;
};
/**
* History.replaceState(data,title,url)
* Replace the State and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.replaceState = function(data,title,url,queue){
//History.debug('History.replaceState: called', arguments);
// We assume that the URL passed in is URI-encoded, but this makes
// sure that it's fully URI encoded; any '%'s that are encoded are
// converted back into '%'s
url = encodeURI(url).replace(/%25/g, "%");
// Check the State
if ( History.getHashByUrl(url) ) {
throw new Error('History.js does not support states with fragment-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.replaceState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.replaceState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy
History.busy(true);
// Fetch the State Objects
var newState = History.createStateObject(data,title,url),
newStateHash = History.getHashByState(newState),
oldState = History.getState(false),
oldStateHash = History.getHashByState(oldState),
previousState = History.getStateByIndex(-2);
// Discard Old State
History.discardState(oldState,newState,previousState);
// If the url hasn't changed, just store and save the state
// and fire a statechange event to be consistent with the
// html 5 api
if ( newStateHash === oldStateHash ) {
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Recycle the State
History.recycleState(newState);
// Force update of the title
History.setTitle(newState);
// Update HTML5 State
History.saveState(newState);
// Fire HTML5 Event
//History.debug('History.pushState: trigger popstate');
History.Adapter.trigger(window,'statechange');
History.busy(false);
}
else {
// Alias to PushState
History.pushState(newState.data,newState.title,newState.url,false);
}
// End replaceState closure
return true;
};
} // History.emulated.pushState
// ====================================================================
// Initialise
// Non-Native pushState Implementation
if ( History.emulated.pushState ) {
/**
* Ensure initial state is handled correctly
*/
if ( History.getHash() && !History.emulated.hashChange ) {
History.Adapter.onDomLoad(function(){
History.Adapter.trigger(window,'hashchange');
});
}
} // History.emulated.pushState
}; // History.initHtml4
// Initialise History
History.init = function(options){
// Check Load Status of Adapter
if ( typeof History.Adapter === 'undefined' ) {
return false;
}
// Check Load Status of Core
if ( typeof History.initCore !== 'undefined' ) {
History.initCore();
}
// Check Load Status of HTML4 Support
if ( typeof History.initHtml4 !== 'undefined' ) {
History.initHtml4();
}
// Return true
return true;
};
// ========================================================================
// Initialise Core
// Initialise Core
History.initCore = function(options){
// Initialise
if ( typeof History.initCore.initialized !== 'undefined' ) {
// Already Loaded
return false;
}
else {
History.initCore.initialized = true;
}
// ====================================================================
// Options
/**
* History.options
* Configurable options
*/
History.options = History.options||{};
/**
* History.options.hashChangeInterval
* How long should the interval be before hashchange checks
*/
History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
/**
* History.options.safariPollInterval
* How long should the interval be before safari poll checks
*/
History.options.safariPollInterval = History.options.safariPollInterval || 500;
/**
* History.options.doubleCheckInterval
* How long should the interval be before we perform a double check
*/
History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
/**
* History.options.disableSuid
* Force History not to append suid
*/
History.options.disableSuid = History.options.disableSuid || false;
/**
* History.options.storeInterval
* How long should we wait between store calls
*/
History.options.storeInterval = History.options.storeInterval || 1000;
/**
* History.options.busyDelay
* How long should we wait between busy events
*/
History.options.busyDelay = History.options.busyDelay || 250;
/**
* History.options.debug
* If true will enable debug messages to be logged
*/
History.options.debug = History.options.debug || false;
/**
* History.options.initialTitle
* What is the title of the initial state
*/
History.options.initialTitle = History.options.initialTitle || document.title;
/**
* History.options.html4Mode
* If true, will force HTMl4 mode (hashtags)
*/
History.options.html4Mode = History.options.html4Mode || false;
/**
* History.options.delayInit
* Want to override default options and call init manually.
*/
History.options.delayInit = History.options.delayInit || false;
// ====================================================================
// Interval record
/**
* History.intervalList
* List of intervals set, to be cleared when document is unloaded.
*/
History.intervalList = [];
/**
* History.clearAllIntervals
* Clears all setInterval instances.
*/
History.clearAllIntervals = function(){
var i, il = History.intervalList;
if (typeof il !== "undefined" && il !== null) {
for (i = 0; i < il.length; i++) {
clearInterval(il[i]);
}
History.intervalList = null;
}
};
// ====================================================================
// Debug
/**
* History.debug(message,...)
* Logs the passed arguments if debug enabled
*/
History.debug = function(){
if ( (History.options.debug||false) ) {
History.log.apply(History,arguments);
}
};
/**
* History.log(message,...)
* Logs the passed arguments
*/
History.log = function(){
// Prepare
var
consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
textarea = document.getElementById('log'),
message,
i,n,
args,arg
;
// Write to Console
if ( consoleExists ) {
args = Array.prototype.slice.call(arguments);
message = args.shift();
if ( typeof console.debug !== 'undefined' ) {
console.debug.apply(console,[message,args]);
}
else {
console.log.apply(console,[message,args]);
}
}
else {
message = ("\n"+arguments[0]+"\n");
}
// Write to log
for ( i=1,n=arguments.length; i<n; ++i ) {
arg = arguments[i];
if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) {
try {
arg = JSON.stringify(arg);
}
catch ( Exception ) {
// Recursive Object
}
}
message += "\n"+arg+"\n";
}
// Textarea
if ( textarea ) {
textarea.value += message+"\n-----\n";
textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
}
// No Textarea, No Console
else if ( !consoleExists ) {
alert(message);
}
// Return true
return true;
};
// ====================================================================
// Emulated Status
/**
* History.getInternetExplorerMajorVersion()
* Get's the major version of Internet Explorer
* @return {integer}
* @license Public Domain
* @author Benjamin Arthur Lupton <contact@balupton.com>
* @author James Padolsey <https://gist.github.com/527683>
*/
History.getInternetExplorerMajorVersion = function(){
var result = History.getInternetExplorerMajorVersion.cached =
(typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
? History.getInternetExplorerMajorVersion.cached
: (function(){
var v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
return (v > 4) ? v : false;
})()
;
return result;
};
/**
* History.isInternetExplorer()
* Are we using Internet Explorer?
* @return {boolean}
* @license Public Domain
* @author Benjamin Arthur Lupton <contact@balupton.com>
*/
History.isInternetExplorer = function(){
var result =
History.isInternetExplorer.cached =
(typeof History.isInternetExplorer.cached !== 'undefined')
? History.isInternetExplorer.cached
: Boolean(History.getInternetExplorerMajorVersion())
;
return result;
};
/**
* History.emulated
* Which features require emulating?
*/
if (History.options.html4Mode) {
History.emulated = {
pushState : true,
hashChange: true
};
}
else {
History.emulated = {
pushState: !Boolean(
window.history && window.history.pushState && window.history.replaceState
&& !(
(/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
|| (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
)
),
hashChange: Boolean(
!(('onhashchange' in window) || ('onhashchange' in document))
||
(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
)
};
}
/**
* History.enabled
* Is History enabled?
*/
History.enabled = !History.emulated.pushState;
/**
* History.bugs
* Which bugs are present
*/
History.bugs = {
/**
* Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
* https://bugs.webkit.org/show_bug.cgi?id=56249
*/
setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
/**
* Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
* https://bugs.webkit.org/show_bug.cgi?id=42940
*/
safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
/**
* MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
*/
ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
/**
* MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
*/
hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
};
/**
* History.isEmptyObject(obj)
* Checks to see if the Object is Empty
* @param {Object} obj
* @return {boolean}
*/
History.isEmptyObject = function(obj) {
for ( var name in obj ) {
if ( obj.hasOwnProperty(name) ) {
return false;
}
}
return true;
};
/**
* History.cloneObject(obj)
* Clones a object and eliminate all references to the original contexts
* @param {Object} obj
* @return {Object}
*/
History.cloneObject = function(obj) {
var hash,newObj;
if ( obj ) {
hash = JSON.stringify(obj);
newObj = JSON.parse(hash);
}
else {
newObj = {};
}
return newObj;
};
// ====================================================================
// URL Helpers
/**
* History.getRootUrl()
* Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
* @return {String} rootUrl
*/
History.getRootUrl = function(){
// Create
var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
if ( document.location.port||false ) {
rootUrl += ':'+document.location.port;
}
rootUrl += '/';
// Return
return rootUrl;
};
/**
* History.getBaseHref()
* Fetches the `href` attribute of the `<base href="...">` element if it exists
* @return {String} baseHref
*/
History.getBaseHref = function(){
// Create
var
baseElements = document.getElementsByTagName('base'),
baseElement = null,
baseHref = '';
// Test for Base Element
if ( baseElements.length === 1 ) {
// Prepare for Base Element
baseElement = baseElements[0];
baseHref = baseElement.href.replace(/[^\/]+$/,'');
}
// Adjust trailing slash
baseHref = baseHref.replace(/\/+$/,'');
if ( baseHref ) baseHref += '/';
// Return
return baseHref;
};
/**
* History.getBaseUrl()
* Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
* @return {String} baseUrl
*/
History.getBaseUrl = function(){
// Create
var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
// Return
return baseUrl;
};
/**
* History.getPageUrl()
* Fetches the URL of the current page
* @return {String} pageUrl
*/
History.getPageUrl = function(){
// Fetch
var
State = History.getState(false,false),
stateUrl = (State||{}).url||History.getLocationHref(),
pageUrl;
// Create
pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
return (/\./).test(part) ? part : part+'/';
});
// Return
return pageUrl;
};
/**
* History.getBasePageUrl()
* Fetches the Url of the directory of the current page
* @return {String} basePageUrl
*/
History.getBasePageUrl = function(){
// Create
var basePageUrl = (History.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
return (/[^\/]$/).test(part) ? '' : part;
}).replace(/\/+$/,'')+'/';
// Return
return basePageUrl;
};
/**
* History.getFullUrl(url)
* Ensures that we have an absolute URL and not a relative URL
* @param {string} url
* @param {Boolean} allowBaseHref
* @return {string} fullUrl
*/
History.getFullUrl = function(url,allowBaseHref){
// Prepare
var fullUrl = url, firstChar = url.substring(0,1);
allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
// Check
if ( /[a-z]+\:\/\//.test(url) ) {
// Full URL
}
else if ( firstChar === '/' ) {
// Root URL
fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
}
else if ( firstChar === '#' ) {
// Anchor URL
fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
}
else if ( firstChar === '?' ) {
// Query URL
fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
}
else {
// Relative URL
if ( allowBaseHref ) {
fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
} else {
fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
}
// We have an if condition above as we do not want hashes
// which are relative to the baseHref in our URLs
// as if the baseHref changes, then all our bookmarks
// would now point to different locations
// whereas the basePageUrl will always stay the same
}
// Return
return fullUrl.replace(/\#$/,'');
};
/**
* History.getShortUrl(url)
* Ensures that we have a relative URL and not a absolute URL
* @param {string} url
* @return {string} url
*/
History.getShortUrl = function(url){
// Prepare
var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
// Trim baseUrl
if ( History.emulated.pushState ) {
// We are in a if statement as when pushState is not emulated
// The actual url these short urls are relative to can change
// So within the same session, we the url may end up somewhere different
console.log ('History.getShortUrl IE :: ' + 'shortUrl: ' + shortUrl + ' baseUrl ' + baseUrl );
shortUrl = shortUrl.replace(baseUrl,'');
}
// Trim rootUrl
shortUrl = shortUrl.replace(rootUrl,'/');
console.log('short url pre: ', shortUrl);
// Ensure we can still detect it as a state
if ( History.isTraditionalAnchor(shortUrl) ) {
// shortUrl = './'+shortUrl;
}
// Clean It
shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
console.log('short url post: ', shortUrl);
// Return
return shortUrl;
};
/**
* History.getLocationHref(document)
* Returns a normalized version of document.location.href
* accounting for browser inconsistencies, etc.
*
* This URL will be URI-encoded and will include the hash
*
* @param {object} document
* @return {string} url
*/
History.getLocationHref = function(doc) {
doc = doc || document;
// most of the time, this will be true
if (doc.URL === doc.location.href)
return doc.location.href;
// some versions of webkit URI-decode document.location.href
// but they leave document.URL in an encoded state
if (doc.location.href === decodeURIComponent(doc.URL))
return doc.URL;
// FF 3.6 only updates document.URL when a page is reloaded
// document.location.href is updated correctly
if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
return doc.location.href;
if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
return doc.location.href;
return doc.URL || doc.location.href;
};
// ====================================================================
// State Storage
/**
* History.store
* The store for all session specific data
*/
History.store = {};
/**
* History.idToState
* 1-1: State ID to State Object
*/
History.idToState = History.idToState||{};
/**
* History.stateToId
* 1-1: State String to State ID
*/
History.stateToId = History.stateToId||{};
/**
* History.urlToId
* 1-1: State URL to State ID
*/
History.urlToId = History.urlToId||{};
/**
* History.storedStates
* Store the states in an array
*/
History.storedStates = History.storedStates||[];
/**
* History.savedStates
* Saved the states in an array
*/
History.savedStates = History.savedStates||[];
/**
* History.noramlizeStore()
* Noramlize the store by adding necessary values
*/
History.normalizeStore = function(){
History.store.idToState = History.store.idToState||{};
History.store.urlToId = History.store.urlToId||{};
History.store.stateToId = History.store.stateToId||{};
};
/**
* History.getState()
* Get an object containing the data, title and url of the current state
* @param {Boolean} friendly
* @param {Boolean} create
* @return {Object} State
*/
History.getState = function(friendly,create){
// Prepare
if ( typeof friendly === 'undefined' ) { friendly = true; }
if ( typeof create === 'undefined' ) { create = true; }
// Fetch
var State = History.getLastSavedState();
// Create
if ( !State && create ) {
State = History.createStateObject();
}
// Adjust
if ( friendly ) {
State = History.cloneObject(State);
State.url = State.cleanUrl||State.url;
}
// Return
return State;
};
/**
* History.getIdByState(State)
* Gets a ID for a State
* @param {State} newState
* @return {String} id
*/
History.getIdByState = function(newState){
// Fetch ID
var id = History.extractId(newState.url),
str;
if ( !id ) {
// Find ID via State String
str = History.getStateString(newState);
if ( typeof History.stateToId[str] !== 'undefined' ) {
id = History.stateToId[str];
}
else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
id = History.store.stateToId[str];
}
else {
// Generate a new ID
while ( true ) {
id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
break;
}
}
// Apply the new State to the ID
History.stateToId[str] = id;
History.idToState[id] = newState;
}
}
// Return ID
return id;
};
/**
* History.normalizeState(State)
* Expands a State Object
* @param {object} State
* @return {object}
*/
History.normalizeState = function(oldState){
// Variables
var newState, dataNotEmpty;
// Prepare
if ( !oldState || (typeof oldState !== 'object') ) {
oldState = {};
}
// Check
if ( typeof oldState.normalized !== 'undefined' ) {
return oldState;
}
// Adjust
if ( !oldState.data || (typeof oldState.data !== 'object') ) {
oldState.data = {};
}
// ----------------------------------------------------------------
// Create
newState = {};
newState.normalized = true;
newState.title = oldState.title||'';
newState.url = History.getFullUrl(oldState.url?oldState.url:(History.getLocationHref()));
newState.hash = History.getShortUrl(newState.url);
newState.data = History.cloneObject(oldState.data);
// Fetch ID
newState.id = History.getIdByState(newState);
// ----------------------------------------------------------------
// Clean the URL
newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
newState.url = newState.cleanUrl;
// Check to see if we have more than just a url
dataNotEmpty = !History.isEmptyObject(newState.data);
// Apply
if ( (newState.title || dataNotEmpty) && History.options.disableSuid !== true ) {
// Add ID to Hash
newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
if ( !/\?/.test(newState.hash) ) {
newState.hash += '?';
}
newState.hash += '&_suid='+newState.id;
}
// Create the Hashed URL
newState.hashedUrl = History.getFullUrl(newState.hash);
// ----------------------------------------------------------------
// Update the URL if we have a duplicate
if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
newState.url = newState.hashedUrl;
}
// ----------------------------------------------------------------
// Return
return newState;
};
/**
* History.createStateObject(data,title,url)
* Creates a object based on the data, title and url state params
* @param {object} data
* @param {string} title
* @param {string} url
* @return {object}
*/
History.createStateObject = function(data,title,url){
// Hashify
var State = {
'data': data,
'title': title,
'url': url
};
// Expand the State
State = History.normalizeState(State);
// Return object
return State;
};
/**
* History.getStateById(id)
* Get a state by it's UID
* @param {String} id
*/
History.getStateById = function(id){
// Prepare
id = String(id);
// Retrieve
var State = History.idToState[id] || History.store.idToState[id] || undefined;
// Return State
return State;
};
/**
* Get a State's String
* @param {State} passedState
*/
History.getStateString = function(passedState){
// Prepare
var State, cleanedState, str;
// Fetch
State = History.normalizeState(passedState);
// Clean
cleanedState = {
data: State.data,
title: passedState.title,
url: passedState.url
};
// Fetch
str = JSON.stringify(cleanedState);
// Return
return str;
};
/**
* Get a State's ID
* @param {State} passedState
* @return {String} id
*/
History.getStateId = function(passedState){
// Prepare
var State, id;
// Fetch
State = History.normalizeState(passedState);
// Fetch
id = State.id;
// Return
return id;
};
/**
* History.getHashByState(State)
* Creates a Hash for the State Object
* @param {State} passedState
* @return {String} hash
*/
History.getHashByState = function(passedState){
// Prepare
var State, hash;
// Fetch
State = History.normalizeState(passedState);
// Hash
hash = State.hash;
// Return
return hash;
};
/**
* History.extractId(url_or_hash)
* Get a State ID by it's URL or Hash
* @param {string} url_or_hash
* @return {string} id
*/
History.extractId = function ( url_or_hash ) {
// Prepare
var id,parts,url, tmp;
// Extract
// If the URL has a #, use the id from before the #
if (url_or_hash.indexOf('#') != -1)
{
tmp = url_or_hash.split("#")[0];
}
else
{
tmp = url_or_hash;
}
parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
url = parts ? (parts[1]||url_or_hash) : url_or_hash;
id = parts ? String(parts[2]||'') : '';
// Return
return id||false;
};
/**
* History.isTraditionalAnchor
* Checks to see if the url is a traditional anchor or not
* @param {String} url_or_hash
* @return {Boolean}
*/
History.isTraditionalAnchor = function(url_or_hash){
// Check
var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
// Return
return isTraditional;
};
/**
* History.extractState
* Get a State by it's URL or Hash
* @param {String} url_or_hash
* @return {State|null}
*/
History.extractState = function(url_or_hash,create){
// Prepare
var State = null, id, url;
create = create||false;
// Fetch SUID
id = History.extractId(url_or_hash);
if ( id ) {
State = History.getStateById(id);
}
// Fetch SUID returned no State
if ( !State ) {
// Fetch URL
url = History.getFullUrl(url_or_hash);
// Check URL
id = History.getIdByUrl(url)||false;
if ( id ) {
State = History.getStateById(id);
}
// Create State
if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
State = History.createStateObject(null,null,url);
}
}
// Return
return State;
};
/**
* History.getIdByUrl()
* Get a State ID by a State URL
*/
History.getIdByUrl = function(url){
// Fetch
var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
// Return
return id;
};
/**
* History.getLastSavedState()
* Get an object containing the data, title and url of the current state
* @return {Object} State
*/
History.getLastSavedState = function(){
return History.savedStates[History.savedStates.length-1]||undefined;
};
/**
* History.getLastStoredState()
* Get an object containing the data, title and url of the current state
* @return {Object} State
*/
History.getLastStoredState = function(){
return History.storedStates[History.storedStates.length-1]||undefined;
};
/**
* History.hasUrlDuplicate
* Checks if a Url will have a url conflict
* @param {Object} newState
* @return {Boolean} hasDuplicate
*/
History.hasUrlDuplicate = function(newState) {
// Prepare
var hasDuplicate = false,
oldState;
// Fetch
oldState = History.extractState(newState.url);
// Check
hasDuplicate = oldState && oldState.id !== newState.id;
// Return
return hasDuplicate;
};
/**
* History.storeState
* Store a State
* @param {Object} newState
* @return {Object} newState
*/
History.storeState = function(newState){
// Store the State
History.urlToId[newState.url] = newState.id;
// Push the State
History.storedStates.push(History.cloneObject(newState));
// Return newState
return newState;
};
/**
* History.isLastSavedState(newState)
* Tests to see if the state is the last state
* @param {Object} newState
* @return {boolean} isLast
*/
History.isLastSavedState = function(newState){
// Prepare
var isLast = false,
newId, oldState, oldId;
// Check
if ( History.savedStates.length ) {
newId = newState.id;
oldState = History.getLastSavedState();
oldId = oldState.id;
// Check
isLast = (newId === oldId);
}
// Return
return isLast;
};
/**
* History.saveState
* Push a State
* @param {Object} newState
* @return {boolean} changed
*/
History.saveState = function(newState){
// Check Hash
if ( History.isLastSavedState(newState) ) {
return false;
}
// Push the State
History.savedStates.push(History.cloneObject(newState));
// Return true
return true;
};
/**
* History.getStateByIndex()
* Gets a state by the index
* @param {integer} index
* @return {Object}
*/
History.getStateByIndex = function(index){
// Prepare
var State = null;
// Handle
if ( typeof index === 'undefined' ) {
// Get the last inserted
State = History.savedStates[History.savedStates.length-1];
}
else if ( index < 0 ) {
// Get from the end
State = History.savedStates[History.savedStates.length+index];
}
else {
// Get from the beginning
State = History.savedStates[index];
}
// Return State
return State;
};
/**
* History.getCurrentIndex()
* Gets the current index
* @return (integer)
*/
History.getCurrentIndex = function(){
// Prepare
var index = null;
// No states saved
if(History.savedStates.length < 1) {
index = 0;
}
else {
index = History.savedStates.length-1;
}
return index;
};
// ====================================================================
// Hash Helpers
/**
* History.getHash()
* @param {Location=} location
* Gets the current document hash
* Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
* @return {string}
*/
History.getHash = function(doc){
var url = History.getLocationHref(doc),
hash;
hash = History.getHashByUrl(url);
return hash;
};
/**
* History.unescapeHash()
* normalize and Unescape a Hash
* @param {String} hash
* @return {string}
*/
History.unescapeHash = function(hash){
// Prepare
var result = History.normalizeHash(hash);
// Unescape hash
result = decodeURIComponent(result);
// Return result
return result;
};
/**
* History.normalizeHash()
* normalize a hash across browsers
* @return {string}
*/
History.normalizeHash = function(hash){
// Prepare
var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
// Return result
return result;
};
/**
* History.setHash(hash)
* Sets the document hash
* @param {string} hash
* @return {History}
*/
History.setHash = function(hash,queue){
// Prepare
var State, pageUrl;
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.setHash: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.setHash,
args: arguments,
queue: queue
});
return false;
}
// Log
//History.debug('History.setHash: called',hash);
// Make Busy + Continue
History.busy(true);
// Check if hash is a state
State = History.extractState(hash,true);
if ( State && !History.emulated.pushState ) {
// Hash is a state so skip the setHash
//History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
// PushState
History.pushState(State.data,State.title,State.url,false);
}
else if ( History.getHash() !== hash ) {
// Hash is a proper hash, so apply it
// Handle browser bugs
if ( History.bugs.setHash ) {
// Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
// Fetch the base page
pageUrl = History.getPageUrl();
// Safari hash apply
History.pushState(null,null,pageUrl+'#'+hash,false);
}
else {
// Normal hash apply
document.location.hash = hash;
}
}
// Chain
return History;
};
/**
* History.escape()
* normalize and Escape a Hash
* @return {string}
*/
History.escapeHash = function(hash){
// Prepare
var result = History.normalizeHash(hash);
// Escape hash
result = window.encodeURIComponent(result);
// IE6 Escape Bug
if ( !History.bugs.hashEscape ) {
// Restore common parts
result = result
.replace(/\%21/g,'!')
.replace(/\%26/g,'&')
.replace(/\%3D/g,'=')
.replace(/\%3F/g,'?');
}
// Return result
return result;
};
/**
* History.getHashByUrl(url)
* Extracts the Hash from a URL
* @param {string} url
* @return {string} url
*/
History.getHashByUrl = function(url){
// Extract the hash
var hash = String(url)
.replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
;
// Unescape hash
hash = History.unescapeHash(hash);
// Return hash
return hash;
};
/**
* History.setTitle(title)
* Applies the title to the document
* @param {State} newState
* @return {Boolean}
*/
History.setTitle = function(newState){
// Prepare
var title = newState.title,
firstState;
// Initial
if ( !title ) {
firstState = History.getStateByIndex(0);
if ( firstState && firstState.url === newState.url ) {
title = firstState.title||History.options.initialTitle;
}
}
// Apply
try {
document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
}
catch ( Exception ) { }
document.title = title;
// Chain
return History;
};
// ====================================================================
// Queueing
/**
* History.queues
* The list of queues to use
* First In, First Out
*/
History.queues = [];
/**
* History.busy(value)
* @param {boolean} value [optional]
* @return {boolean} busy
*/
History.busy = function(value){
// Apply
if ( typeof value !== 'undefined' ) {
//History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
History.busy.flag = value;
}
// Default
else if ( typeof History.busy.flag === 'undefined' ) {
History.busy.flag = false;
}
// Queue
if ( !History.busy.flag ) {
// Execute the next item in the queue
clearTimeout(History.busy.timeout);
var fireNext = function(){
var i, queue, item;
if ( History.busy.flag ) return;
for ( i=History.queues.length-1; i >= 0; --i ) {
queue = History.queues[i];
if ( queue.length === 0 ) continue;
item = queue.shift();
History.fireQueueItem(item);
History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
}
};
History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
}
// Return
return History.busy.flag;
};
/**
* History.busy.flag
*/
History.busy.flag = false;
/**
* History.fireQueueItem(item)
* Fire a Queue Item
* @param {Object} item
* @return {Mixed} result
*/
History.fireQueueItem = function(item){
return item.callback.apply(item.scope||History,item.args||[]);
};
/**
* History.pushQueue(callback,args)
* Add an item to the queue
* @param {Object} item [scope,callback,args,queue]
*/
History.pushQueue = function(item){
// Prepare the queue
History.queues[item.queue||0] = History.queues[item.queue||0]||[];
// Add to the queue
History.queues[item.queue||0].push(item);
// Chain
return History;
};
/**
* History.queue (item,queue), (func,queue), (func), (item)
* Either firs the item now if not busy, or adds it to the queue
*/
History.queue = function(item,queue){
// Prepare
if ( typeof item === 'function' ) {
item = {
callback: item
};
}
if ( typeof queue !== 'undefined' ) {
item.queue = queue;
}
// Handle
if ( History.busy() ) {
History.pushQueue(item);
} else {
History.fireQueueItem(item);
}
// Chain
return History;
};
/**
* History.clearQueue()
* Clears the Queue
*/
History.clearQueue = function(){
History.busy.flag = false;
History.queues = [];
return History;
};
// ====================================================================
// IE Bug Fix
/**
* History.stateChanged
* States whether or not the state has changed since the last double check was initialised
*/
History.stateChanged = false;
/**
* History.doubleChecker
* Contains the timeout used for the double checks
*/
History.doubleChecker = false;
/**
* History.doubleCheckComplete()
* Complete a double check
* @return {History}
*/
History.doubleCheckComplete = function(){
// Update
History.stateChanged = true;
// Clear
History.doubleCheckClear();
// Chain
return History;
};
/**
* History.doubleCheckClear()
* Clear a double check
* @return {History}
*/
History.doubleCheckClear = function(){
// Clear
if ( History.doubleChecker ) {
clearTimeout(History.doubleChecker);
History.doubleChecker = false;
}
// Chain
return History;
};
/**
* History.doubleCheck()
* Create a double check
* @return {History}
*/
History.doubleCheck = function(tryAgain){
// Reset
History.stateChanged = false;
History.doubleCheckClear();
// Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
// Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
if ( History.bugs.ieDoubleCheck ) {
// Apply Check
History.doubleChecker = setTimeout(
function(){
History.doubleCheckClear();
if ( !History.stateChanged ) {
//History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
// Re-Attempt
tryAgain();
}
return true;
},
History.options.doubleCheckInterval
);
}
// Chain
return History;
};
// ====================================================================
// Safari Bug Fix
/**
* History.safariStatePoll()
* Poll the current state
* @return {History}
*/
History.safariStatePoll = function(){
// Poll the URL
// Get the Last State which has the new URL
var
urlState = History.extractState(History.getLocationHref()),
newState;
// Check for a difference
if ( !History.isLastSavedState(urlState) ) {
newState = urlState;
}
else {
return;
}
// Check if we have a state with that url
// If not create it
if ( !newState ) {
//History.debug('History.safariStatePoll: new');
newState = History.createStateObject();
}
// Apply the New State
//History.debug('History.safariStatePoll: trigger');
History.Adapter.trigger(window,'popstate');
// Chain
return History;
};
// ====================================================================
// State Aliases
/**
* History.back(queue)
* Send the browser history back one item
* @param {Integer} queue [optional]
*/
History.back = function(queue){
//History.debug('History.back: called', arguments);
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.back: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.back,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Fix certain browser bugs that prevent the state from changing
History.doubleCheck(function(){
History.back(false);
});
// Go back
history.go(-1);
// End back closure
return true;
};
/**
* History.forward(queue)
* Send the browser history forward one item
* @param {Integer} queue [optional]
*/
History.forward = function(queue){
//History.debug('History.forward: called', arguments);
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.forward: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.forward,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Fix certain browser bugs that prevent the state from changing
History.doubleCheck(function(){
History.forward(false);
});
// Go forward
history.go(1);
// End forward closure
return true;
};
/**
* History.go(index,queue)
* Send the browser history back or forward index times
* @param {Integer} queue [optional]
*/
History.go = function(index,queue){
//History.debug('History.go: called', arguments);
// Prepare
var i;
// Handle
if ( index > 0 ) {
// Forward
for ( i=1; i<=index; ++i ) {
History.forward(queue);
}
}
else if ( index < 0 ) {
// Backward
for ( i=-1; i>=index; --i ) {
History.back(queue);
}
}
else {
throw new Error('History.go: History.go requires a positive or negative integer passed.');
}
// Chain
return History;
};
// ====================================================================
// HTML5 State Support
// Non-Native pushState Implementation
if ( History.emulated.pushState ) {
/*
* Provide Skeleton for HTML4 Browsers
*/
// Prepare
var emptyFunction = function(){};
History.pushState = History.pushState||emptyFunction;
History.replaceState = History.replaceState||emptyFunction;
} // History.emulated.pushState
// Native pushState Implementation
else {
/*
* Use native HTML5 History API Implementation
*/
/**
* History.onPopState(event,extra)
* Refresh the Current State
*/
History.onPopState = function(event,extra){
// Prepare
var stateId = false, newState = false, currentHash, currentState;
// Reset the double check
History.doubleCheckComplete();
// Check for a Hash, and handle apporiatly
currentHash = History.getHash();
if ( currentHash ) {
// Expand Hash
currentState = History.extractState(currentHash||History.getLocationHref(),true);
if ( currentState ) {
// We were able to parse it, it must be a State!
// Let's forward to replaceState
//History.debug('History.onPopState: state anchor', currentHash, currentState);
History.replaceState(currentState.data, currentState.title, currentState.url, false);
}
else {
// Traditional Anchor
//History.debug('History.onPopState: traditional anchor', currentHash);
History.Adapter.trigger(window,'anchorchange');
History.busy(false);
}
// We don't care for hashes
History.expectedStateId = false;
return false;
}
// Ensure
stateId = History.Adapter.extractEventData('state',event,extra) || false;
// Fetch State
if ( stateId ) {
// Vanilla: Back/forward button was used
newState = History.getStateById(stateId);
}
else if ( History.expectedStateId ) {
// Vanilla: A new state was pushed, and popstate was called manually
newState = History.getStateById(History.expectedStateId);
}
else {
// Initial State
newState = History.extractState(History.getLocationHref());
}
// The State did not exist in our store
if ( !newState ) {
// Regenerate the State
newState = History.createStateObject(null,null,History.getLocationHref());
}
// Clean
History.expectedStateId = false;
// Check if we are the same state
if ( History.isLastSavedState(newState) ) {
// There has been no change (just the page's hash has finally propagated)
//History.debug('History.onPopState: no change', newState, History.savedStates);
History.busy(false);
return false;
}
// Store the State
History.storeState(newState);
History.saveState(newState);
// Force update of the title
History.setTitle(newState);
// Fire Our Event
History.Adapter.trigger(window,'statechange');
History.busy(false);
// Return true
return true;
};
History.Adapter.bind(window,'popstate',History.onPopState);
/**
* History.pushState(data,title,url)
* Add a new State to the history object, become it, and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.pushState = function(data,title,url,queue){
//History.debug('History.pushState: called', arguments);
// Check the State
if ( History.getHashByUrl(url) && History.emulated.pushState ) {
throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.pushState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.pushState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Create the newState
var newState = History.createStateObject(data,title,url);
// Check it
if ( History.isLastSavedState(newState) ) {
// Won't be a change
History.busy(false);
}
else {
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Push the newState
history.pushState(newState.id,newState.title,newState.url);
// Fire HTML5 Event
History.Adapter.trigger(window,'popstate');
}
// End pushState closure
return true;
};
/**
* History.replaceState(data,title,url)
* Replace the State and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.replaceState = function(data,title,url,queue){
//History.debug('History.replaceState: called', arguments);
// Check the State
if ( History.getHashByUrl(url) && History.emulated.pushState ) {
throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.replaceState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.replaceState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Create the newState
var newState = History.createStateObject(data,title,url);
// Check it
if ( History.isLastSavedState(newState) ) {
// Won't be a change
History.busy(false);
}
else {
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Push the newState
history.replaceState(newState.id,newState.title,newState.url);
// Fire HTML5 Event
History.Adapter.trigger(window,'popstate');
}
// End replaceState closure
return true;
};
} // !History.emulated.pushState
// ====================================================================
// Initialise
/**
* Load the Store
*/
if ( sessionStorage ) {
// Fetch
try {
History.store = JSON.parse(sessionStorage.getItem('History.store'))||{};
}
catch ( err ) {
History.store = {};
}
// Normalize
History.normalizeStore();
}
else {
// Default Load
History.store = {};
History.normalizeStore();
}
/**
* Clear Intervals on exit to prevent memory leaks
*/
History.Adapter.bind(window,"unload",History.clearAllIntervals);
/**
* Create the initial State
*/
History.saveState(History.storeState(History.extractState(History.getLocationHref(),true)));
/**
* Bind for Saving Store
*/
if ( sessionStorage ) {
// When the page is closed
History.onUnload = function(){
// Prepare
var currentStore, item, currentStoreString;
// Fetch
try {
currentStore = JSON.parse(sessionStorage.getItem('History.store'))||{};
}
catch ( err ) {
currentStore = {};
}
// Ensure
currentStore.idToState = currentStore.idToState || {};
currentStore.urlToId = currentStore.urlToId || {};
currentStore.stateToId = currentStore.stateToId || {};
// Sync
for ( item in History.idToState ) {
if ( !History.idToState.hasOwnProperty(item) ) {
continue;
}
currentStore.idToState[item] = History.idToState[item];
}
for ( item in History.urlToId ) {
if ( !History.urlToId.hasOwnProperty(item) ) {
continue;
}
currentStore.urlToId[item] = History.urlToId[item];
}
for ( item in History.stateToId ) {
if ( !History.stateToId.hasOwnProperty(item) ) {
continue;
}
currentStore.stateToId[item] = History.stateToId[item];
}
// Update
History.store = currentStore;
History.normalizeStore();
// In Safari, going into Private Browsing mode causes the
// Session Storage object to still exist but if you try and use
// or set any property/function of it it throws the exception
// "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
// add something to storage that exceeded the quota." infinitely
// every second.
currentStoreString = JSON.stringify(currentStore);
try {
// Store
sessionStorage.setItem('History.store', currentStoreString);
}
catch (e) {
if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
if (sessionStorage.length) {
// Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
// removing/resetting the storage can work.
sessionStorage.removeItem('History.store');
sessionStorage.setItem('History.store', currentStoreString);
} else {
// Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
}
} else {
throw e;
}
}
};
// For Internet Explorer
History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
// For Other Browsers
History.Adapter.bind(window,'beforeunload',History.onUnload);
History.Adapter.bind(window,'unload',History.onUnload);
// Both are enabled for consistency
}
// Non-Native pushState Implementation
if ( !History.emulated.pushState ) {
// Be aware, the following is only for native pushState implementations
// If you are wanting to include something for all browsers
// Then include it above this if block
/**
* Setup Safari Fix
*/
if ( History.bugs.safariPoll ) {
History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
}
/**
* Ensure Cross Browser Compatibility
*/
if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
/**
* Fix Safari HashChange Issue
*/
// Setup Alias
History.Adapter.bind(window,'hashchange',function(){
History.Adapter.trigger(window,'popstate');
});
// Initialise Alias
if ( History.getHash() ) {
History.Adapter.onDomLoad(function(){
History.Adapter.trigger(window,'hashchange');
});
}
}
} // !History.emulated.pushState
}; // History.initCore
// Try to Initialise History
if (!History.options || !History.options.delayInit) {
History.init();
}
return History;
}); | shovemedia/GigaJS | js/src/lib/History.js | JavaScript | mit | 71,024 |
<?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '« পূর্ববর্তী',
'next' => 'পরবর্তী »',
];
| iluminar/goodwork | resources/lang/bn/pagination.php | PHP | mit | 575 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SamLu.RegularExpression.Extend
{
/// <summary>
/// 包含所有正则复数分支的分支的集合。
/// </summary>
/// <typeparam name="T">正则接受的对象的类型。</typeparam>
public class RegexMultiBranchBranchCollection<T> : IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>, ICollection<RegexMultiBranchBranch<T>>
{
private IDictionary<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>> innerDic;
/// <summary>
/// 初始化 <see cref="RegexMultiBranchBranchCollection{T}"/> 类的新实例。
/// </summary>
public RegexMultiBranchBranchCollection() =>
this.innerDic = new Dictionary<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>>();
public RegexMultiBranchBranchCollection(IEnumerable<RegexMultiBranchBranch<T>> branches) :
this((branches ?? throw new ArgumentNullException(nameof(branches)))
.ToDictionary(branch => branch.Predicate)
)
{ }
public RegexMultiBranchBranchCollection(IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>> dictionary) :
this((dictionary ?? throw new ArgumentNullException(nameof(dictionary)))
.ToDictionary(
(pair => pair.Key),
(pair => new RegexMultiBranchBranch<T>(pair.Key, pair.Value))
)
)
{ }
protected RegexMultiBranchBranchCollection(IDictionary<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>> dictionary) =>
this.innerDic = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
public RegexObject<T> this[RegexMultiBranchBranchPredicate<T> key]
{
get => this.innerDic[key].Pattern;
set => this.innerDic[key].Pattern = value;
}
#region Predicates
/// <summary>
/// 获取 <see cref="RegexMultiBranchBranchCollection{T}"/> 的检测条件集合。
/// </summary>
public ICollection<RegexMultiBranchBranchPredicate<T>> Predicates => this.innerDic.Keys;
ICollection<RegexMultiBranchBranchPredicate<T>> IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>.Keys => this.Predicates;
#endregion
#region Patterns
/// <summary>
/// 获取 <see cref="RegexMultiBranchBranchCollection{T}"/> 的正则模式集合。
/// </summary>
public ICollection<RegexObject<T>> Patterns => new ReadOnlyCollection<RegexObject<T>>(this.innerDic.Values.Select(branch => branch.Pattern).ToList());
ICollection<RegexObject<T>> IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>.Values => this.Patterns;
#endregion
/// <summary>
/// 获取 <see cref="RegexMultiBranchBranchCollection{T}"/> 包含的元素数。
/// </summary>
public int Count => this.innerDic.Count;
#region IsReadOnly
bool ICollection<RegexMultiBranchBranch<T>>.IsReadOnly => this.innerDic.IsReadOnly;
bool ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.IsReadOnly => this.innerDic.IsReadOnly;
#endregion
#region Add
public void Add(RegexMultiBranchBranchPredicate<T> key, RegexObject<T> value) =>
this.innerDic.Add(key, new RegexMultiBranchBranch<T>(key, value));
public void Add(RegexMultiBranchBranch<T> branch) =>
this.innerDic.Add(branch.Predicate, branch);
void ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.Add(KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>> item) =>
this.Add(item.Key, item.Value);
#endregion
public void Clear() => this.innerDic.Clear();
#region Contains
public bool Contains(RegexMultiBranchBranch<T> branch)
{
if (branch == null) throw new ArgumentNullException(nameof(branch));
return this.ContainsPredicate(branch.Predicate) &&
EqualityComparer<RegexMultiBranchBranch<T>>.Default.Equals(branch, this.innerDic[branch.Predicate]);
}
bool ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.Contains(KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>> item) =>
this.ContainsPredicate(item.Key) && EqualityComparer<RegexObject<T>>.Default.Equals(this[item.Key], item.Value);
#endregion
#region ContainsPredicate
public bool ContainsPredicate(RegexMultiBranchBranchPredicate<T> predicate) =>
this.innerDic.ContainsKey(predicate);
bool IDictionary<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>.ContainsKey(RegexMultiBranchBranchPredicate<T> key) =>
this.ContainsPredicate(key);
#endregion
#region CopyTo
public void CopyTo(RegexMultiBranchBranch<T>[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, $"{nameof(arrayIndex)} 的值小于 0 。");
if (array.Length - arrayIndex < this.Count) throw new ArgumentException($"源 {typeof(RegexMultiBranchBranchPredicate<T>).FullName} 中的元素数目大于从目标 {nameof(array)} 的 {nameof(arrayIndex)} 从头到尾的可用空间。");
var pairArray = new KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>>[array.Length];
this.innerDic.CopyTo(pairArray, arrayIndex);
for (int i = arrayIndex; i < array.Length; i++)
array[i] = new RegexMultiBranchBranch<T>(pairArray[i].Key, pairArray[i].Value.Pattern);
}
void ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.CopyTo(KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, $"{nameof(arrayIndex)} 的值小于 0 。");
if (array.Length - arrayIndex < this.Count) throw new ArgumentException($"源 {typeof(RegexMultiBranchBranchPredicate<T>).FullName} 中的元素数目大于从目标 {nameof(array)} 的 {nameof(arrayIndex)} 从头到尾的可用空间。");
var pairArray = new KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexMultiBranchBranch<T>>[array.Length];
this.innerDic.CopyTo(pairArray, arrayIndex);
for (int i = arrayIndex; i < array.Length; i++)
array[i] = new KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>(pairArray[i].Key, pairArray[i].Value.Pattern);
}
#endregion
#region GetEnumerator
/// <summary>
/// 返回一个循环访问集合的枚举器。
/// </summary>
/// <returns>用于循环访问集合的枚举数。</returns>
public IEnumerator<RegexMultiBranchBranch<T>> GetEnumerator()
{
var enumerator = this.innerDic.GetEnumerator();
while (enumerator.MoveNext())
{
var current = enumerator.Current;
yield return new RegexMultiBranchBranch<T>(current.Key, current.Value.Pattern);
}
}
IEnumerator<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>> IEnumerable<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.GetEnumerator()
{
var enumerator = this.innerDic.GetEnumerator();
while (enumerator.MoveNext())
{
var current = enumerator.Current;
yield return new KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>(current.Key, current.Value.Pattern);
}
}
#endregion
#region
public bool Remove(RegexMultiBranchBranchPredicate<T> key) => this.innerDic.Remove(key);
public bool Remove(RegexMultiBranchBranch<T> branch)
{
if (branch == null) throw new ArgumentNullException(nameof(branch));
if (this.Contains(branch))
{
this.Remove(branch.Predicate);
return true;
}
else return false;
}
bool ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>.Remove(KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>> item)
{
if (((ICollection<KeyValuePair<RegexMultiBranchBranchPredicate<T>, RegexObject<T>>>)this).Contains(item))
{
this.Remove(item.Key);
return true;
}
else return false;
}
#endregion
public bool TryGetValue(RegexMultiBranchBranchPredicate<T> key, out RegexObject<T> value)
{
if (this.ContainsPredicate(key))
{
value = this[key];
return true;
}
else
{
value = null;
return false;
}
}
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
}
| lufengfan/SamLu.RegularExpression | src/SamLu.RegularExpression/Extend/RegexMultiBranchBranchCollection.cs | C# | mit | 9,630 |
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Igor Deplano
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
package it.polito.ai.polibox.web.controllers.authentication;
import it.polito.ai.polibox.persistency.model.DeviceLogin;
import it.polito.ai.polibox.persistency.model.dao.DeviceLoginDao;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* questo filtro si occupa di autenticare ogni richiesta che viene fatta per il
* servizio rest.
*
* @author "Igor Deplano"
*
*/
@Component("customSecurityAuthenticationInterceptor")
public class CustomSecurityAuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private DeviceLoginDao deviceLoginDao;
public CustomSecurityAuthenticationInterceptor() {
}
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
DeviceLogin d=deviceLoginDao.authenticateDevice(Integer.parseInt(request.getHeader("user")),
Integer.parseInt(request.getHeader("device")),
request.getHeader("password"));
if(d!=null){
if(d.getUser()==Integer.parseInt(request.getHeader("user")))
return true;
}
return false;
}
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
public DeviceLoginDao getDeviceLoginDao() {
return deviceLoginDao;
}
public void setDeviceLoginDao(DeviceLoginDao deviceLoginDao) {
this.deviceLoginDao = deviceLoginDao;
}
}
| IDepla/polibox | src/main/java/it/polito/ai/polibox/web/controllers/authentication/CustomSecurityAuthenticationInterceptor.java | Java | mit | 3,118 |
//****************************************************************************
// Fichier: GridHelp.cpp
// Classe: CGridHelp
// Usage:
//
// To use CGridHelp. There are 3 steps:
// 1) initialization of the DLL with the method : Initialize
// 2) Open a grid and used it :
// Open
// GetValue
// GetNbCols
// GetNbRows
// 3) Close de grid: Close
//
//****************************************************************************
// 03-04-2006 Rémi Saint-Amant Initial version
//****************************************************************************
#include "stdafx.h"
#include <crtdbg.h>
#include <windows.h>
#include "Basic/UtilStd.h"
#include "ModelBase/GridHelp.h"
namespace WBSF
{
//****************************************************************************
// Summary: Constructor
//
// Description: To Create and initialize an object
//
// Input:
//
// Output:
//
// Note:
//****************************************************************************
CGridHelp::CGridHelp()
{
m_hDll = NULL;
m_OpenFunction = NULL;
m_CloseFunction = NULL;
m_GetNbColsFunction = NULL;
m_GetNbRowsFunction = NULL;
m_GetValueFunction = NULL;
m_GetValueLatLonFunction = NULL;
}
//****************************************************************************
// Summary: Destructor
//
// Description: Destroy and clean memory
//
// Input:
//
// Output:
//
// Note:
//****************************************************************************
CGridHelp::~CGridHelp()
{
if (m_hDll)
{
FreeLibrary((HMODULE)m_hDll);
m_hDll = NULL;
}
m_OpenFunction = NULL;
m_GetNbColsFunction = NULL;
m_GetNbRowsFunction = NULL;
m_GetValueFunction = NULL;
m_GetValueLatLonFunction = NULL;
m_CloseFunction = NULL;
}
//****************************************************************************
// Summary: initialize the class
//
// Description: initialize the dll with file path
//
// Input: DLLFilePath : the file path of the dll (tempGenLib.dll)
//
// Output: ERMsg : error message
//
// Note:
//****************************************************************************
ERMsg CGridHelp::Initialize(const char* DLLFilePath)
{
ERMsg message;
if (m_hDll)
{
//if a dll is loaded : free
FreeLibrary((HMODULE)m_hDll);
m_hDll = NULL;
}
//load dll
m_hDll = LoadLibraryW(convert(DLLFilePath).c_str());
if (m_hDll != NULL)
{
//if loaded : load function
m_OpenFunction = (OpenFunction)GetProcAddress((HMODULE)m_hDll, "Open");
m_CloseFunction = (CloseFunction)GetProcAddress((HMODULE)m_hDll, "Close");
m_GetNbColsFunction = (GetNbColsFunction)GetProcAddress((HMODULE)m_hDll, "GetNbCols");
m_GetNbRowsFunction = (GetNbRowsFunction)GetProcAddress((HMODULE)m_hDll, "GetNbRows");
m_GetValueFunction = (GetValueFunction)GetProcAddress((HMODULE)m_hDll, "GetValue");
m_GetValueLatLonFunction = (GetValueLatLonFunction)GetProcAddress((HMODULE)m_hDll, "GetValueLatLon");
}
else
{
message.asgType(ERMsg::ERREUR);
message.ajoute("error");
}
return message;
}
//****************************************************************************
// Summary: Open a grid
//
// Description: Open a grid for reading
//
// Input: filePath : the file path of the grid
//
// Output: ERMsg : error message
//
// Note:
//****************************************************************************
ERMsg CGridHelp::Open(const char* filePath)
{
_ASSERTE(m_OpenFunction != NULL);
ERMsg message;
char messageOut[1024] = { 0 };
if (!m_OpenFunction(filePath, messageOut))
{
message.asgType(ERMsg::ERREUR);
message.ajoute(messageOut);
}
return message;
}
//****************************************************************************
// Summary: Close a grid
//
// Description: Close a grid
//
// Input:
//
// Output:
//
// Note:
//****************************************************************************
void CGridHelp::Close()
{
_ASSERTE(m_CloseFunction != NULL);
m_CloseFunction();
}
//****************************************************************************
// Summary: Get the number of columns
//
// Description: Get the number of columns of the open grid
//
// Input:
//
// Output: the number of cols
//
// Note:
//****************************************************************************
long CGridHelp::GetNbCols()
{
_ASSERTE(m_GetNbColsFunction != NULL);
ERMsg message;
return m_GetNbColsFunction();
}
//****************************************************************************
// Summary: Get the number of rows
//
// Description: Get the number of rows of the open grid
//
// Input:
//
// Output: the number of rows
//
// Note:
//****************************************************************************
long CGridHelp::GetNbRows()
{
_ASSERTE(m_GetNbRowsFunction != NULL);
return m_GetNbRowsFunction();
}
//****************************************************************************
// Summary: Get the values
//
// Description: Get the value of a cell at the position col, row
//
// Input: col: the columns
// row: the rows
//
// Output: The value of the cell
//
// Note:
//
//****************************************************************************
double CGridHelp::GetValue(long col, long row)
{
_ASSERTE(m_GetValueFunction != NULL);
return m_GetValueFunction(col, row);
}
//****************************************************************************
// Summary: Get the values
//
// Description: Get the value of a cell at the position lat lon in decimal degrre
//
// Input: lat: latitude in degree of the cell. Negatif for southern coord.
// lon: longitude in degree of the cell. Negatif for western coord.
//
// Output: The value of the cell
//
// Note: ever if the grid is projected, the coordinate are always in degree
//
//****************************************************************************
double CGridHelp::GetValueLatLon(const double& lat, const double& lon)
{
_ASSERTE(m_GetValueLatLonFunction != NULL);
return m_GetValueLatLonFunction(lat, lon);
}
} | RNCan/WeatherBasedSimulationFramework | wbs/src/ModelBase/GridHelp.cpp | C++ | mit | 6,502 |
import logging
import time
import os
from fuocore.models import (
BaseModel,
SongModel,
LyricModel,
PlaylistModel,
AlbumModel,
ArtistModel,
SearchModel,
UserModel,
)
from .provider import provider
logger = logging.getLogger(__name__)
MUSIC_LIBRARY_PATH = os.path.expanduser('~') + '/Music'
class NBaseModel(BaseModel):
# FIXME: remove _detail_fields and _api to Meta
_api = provider.api
class Meta:
allow_get = True
provider = provider
class NSongModel(SongModel, NBaseModel):
@classmethod
def get(cls, identifier):
data = cls._api.song_detail(int(identifier))
song, _ = NeteaseSongSchema(strict=True).load(data)
return song
@classmethod
def list(cls, identifiers):
song_data_list = cls._api.songs_detail(identifiers)
songs = []
for song_data in song_data_list:
song, _ = NeteaseSongSchema(strict=True).load(song_data)
songs.append(song)
return songs
def _refresh_url(self):
"""刷新获取 url,失败的时候返回空而不是 None"""
songs = self._api.weapi_songs_url([int(self.identifier)])
if songs and songs[0]['url']:
self.url = songs[0]['url']
else:
self.url = ''
def _find_in_local(self):
# TODO: make this a API in SongModel
path = os.path.join(MUSIC_LIBRARY_PATH, self.filename)
if os.path.exists(path):
logger.debug('find local file for {}'.format(self))
return path
return None
# NOTE: if we want to override model attribute, we must
# implement both getter and setter.
@property
def url(self):
"""
We will always check if this song file exists in local library,
if true, we return the url of the local file.
.. note::
As netease song url will be expired after a period of time,
we can not use static url here. Currently, we assume that the
expiration time is 20 minutes, after the url expires, it
will be automaticly refreshed.
"""
local_path = self._find_in_local()
if local_path:
return local_path
if not self._url:
self._refresh_url()
elif time.time() > self._expired_at:
logger.info('song({}) url is expired, refresh...'.format(self))
self._refresh_url()
return self._url
@url.setter
def url(self, value):
self._expired_at = time.time() + 60 * 20 * 1 # 20 minutes
self._url = value
@property
def lyric(self):
if self._lyric is not None:
assert isinstance(self._lyric, LyricModel)
return self._lyric
data = self._api.get_lyric_by_songid(self.identifier)
lrc = data.get('lrc', {})
lyric = lrc.get('lyric', '')
self._lyric = LyricModel(
identifier=self.identifier,
content=lyric
)
return self._lyric
@lyric.setter
def lyric(self, value):
self._lyric = value
class NAlbumModel(AlbumModel, NBaseModel):
@classmethod
def get(cls, identifier):
album_data = cls._api.album_infos(identifier)
if album_data is None:
return None
album, _ = NeteaseAlbumSchema(strict=True).load(album_data)
return album
@property
def desc(self):
if self._desc is None:
self._desc = self._api.album_desc(self.identifier)
return self._desc
@desc.setter
def desc(self, value):
self._desc = value
class NArtistModel(ArtistModel, NBaseModel):
@classmethod
def get(cls, identifier):
artist_data = cls._api.artist_infos(identifier)
artist = artist_data['artist']
artist['songs'] = artist_data['hotSongs'] or []
artist, _ = NeteaseArtistSchema(strict=True).load(artist)
return artist
@property
def desc(self):
if self._desc is None:
self._desc = self._api.artist_desc(self.identifier)
return self._desc
@desc.setter
def desc(self, value):
self._desc = value
class NPlaylistModel(PlaylistModel, NBaseModel):
class Meta:
fields = ('uid')
@classmethod
def get(cls, identifier):
data = cls._api.playlist_detail(identifier)
playlist, _ = NeteasePlaylistSchema(strict=True).load(data)
return playlist
def add(self, song_id, allow_exist=True):
rv = self._api.op_music_to_playlist(song_id, self.identifier, 'add')
if rv == 1:
song = NSongModel.get(song_id)
self.songs.append(song)
return True
elif rv == -1:
return True
return False
def remove(self, song_id, allow_not_exist=True):
rv = self._api.op_music_to_playlist(song_id, self.identifier, 'del')
if rv != 1:
return False
# XXX: make it O(1) if you want
for song in self.songs:
if song.identifier == song_id:
self.songs.remove(song)
return True
class NSearchModel(SearchModel, NBaseModel):
pass
class NUserModel(UserModel, NBaseModel):
class Meta:
fields = ('cookies', )
fields_no_get = ('cookies', )
@classmethod
def get(cls, identifier):
user = {'id': identifier}
user_brief = cls._api.user_brief(identifier)
user.update(user_brief)
playlists = cls._api.user_playlists(identifier)
user['playlists'] = []
user['fav_playlists'] = []
for pl in playlists:
if pl['userId'] == identifier:
user['playlists'].append(pl)
else:
user['fav_playlists'].append(pl)
user, _ = NeteaseUserSchema(strict=True).load(user)
return user
def search(keyword, **kwargs):
_songs = provider.api.search(keyword)
id_song_map = {}
songs = []
if _songs:
for song in _songs:
id_song_map[str(song['id'])] = song
schema = NeteaseSongSchema(strict=True)
s, _ = schema.load(song)
songs.append(s)
return NSearchModel(q=keyword, songs=songs)
# import loop
from .schemas import (
NeteaseSongSchema,
NeteaseAlbumSchema,
NeteaseArtistSchema,
NeteasePlaylistSchema,
NeteaseUserSchema,
) # noqa
| cosven/feeluown-core | fuocore/netease/models.py | Python | mit | 6,421 |
import deepFreeze from 'deep-freeze';
import article_details from '../../app/assets/javascripts/reducers/article_details';
import { RECEIVE_ARTICLE_DETAILS } from '../../app/assets/javascripts/constants/article_details';
import '../testHelper';
describe('article_details reducer', () => {
it('Should return initial state if no action type matches', () => {
const mockAction = {
type: 'NO_TYPE'
};
const initialState = {};
deepFreeze(initialState);
const result = article_details(undefined, mockAction);
expect(result).to.deep.eq(initialState);
});
it('should reutrn a new state if action type is RECEIVE_ARTICLE_DETAILS', () => {
const mockAction = {
type: RECEIVE_ARTICLE_DETAILS,
articleId: 586,
data: {
article_details: 'best article ever'
}
};
const expectedState = {
586: 'best article ever'
};
expect(article_details(undefined, mockAction)).to.deep.eq(expectedState);
});
});
| sejalkhatri/WikiEduDashboard | test/reducers/article_details.spec.js | JavaScript | mit | 981 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kirppu_project.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| jlaunonen/kirppu | manage.py | Python | mit | 257 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2.Array_Elements_Egual_To_Their_Index
{
class arrElementEgualIndex
{
static void Main(string[] args)
{
int[] array = Console.ReadLine().Split(' ')
.Select(int.Parse).ToArray();
for (int i = 0; i < array.Length; i++)
{
if (array[i] == i)
{
Console.Write(array[i] + " ");
}
}
Console.WriteLine();
}
}
}
| NedkoNedevv/Fundamentals | Arrays - More Exercises/2.Array Elements Egual To Their Index/arrElementEgualIndex.cs | C# | mit | 613 |
extern "C"
{
#include "lualib.h"
#include "lauxlib.h"
}
#include "tconstant.h"
int main (void)
{
int tolua_tconstant_open (lua_State*);
lua_State* L = lua_open();
luaL_openlibs(L);
tolua_tconstant_open(L);
luaL_dofile(L,"tconstant.lua");
lua_close(L);
return 0;
}
| drupalhunter-team/TrackMonitor | ExternalComponents/Tolua/src/tests/tconstant.cpp | C++ | mit | 278 |
require 'test_helper'
class ResubmitTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| garyhsieh/mturk-survey | test/unit/resubmit_test.rb | Ruby | mit | 122 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IWorkbookFunctionsMultiNomialRequestBuilder.
/// </summary>
public partial interface IWorkbookFunctionsMultiNomialRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IWorkbookFunctionsMultiNomialRequest Request(IEnumerable<Option> options = null);
}
}
| garethj-msft/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsMultiNomialRequestBuilder.cs | C# | mit | 1,006 |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using JigLibX.Vehicles;
using JigLibX.Collision;
namespace OurCity.PhysicObjects
{
class CarObject : PhysicObject
{
private Car car;
private Model wheel;
public CarObject(ConceptGameScreen game, Model model, Model wheels, bool FWDrive,
bool RWDrive,
float maxSteerAngle,
float steerRate,
float wheelSideFriction,
float wheelFwdFriction,
float wheelTravel,
float wheelRadius,
float wheelZOffset,
float wheelRestingFrac,
float wheelDampingFrac,
int wheelNumRays,
float driveTorque,
float gravity)
: base(game, model)
{
car = new Car(FWDrive, RWDrive, maxSteerAngle, steerRate,
wheelSideFriction, wheelFwdFriction, wheelTravel, wheelRadius,
wheelZOffset, wheelRestingFrac, wheelDampingFrac,
wheelNumRays, driveTorque, gravity);
this.body = car.Chassis.Body;
this.collision = car.Chassis.Skin;
this.wheel = wheels;
SetCarMass(100.0f);
}
private void DrawWheel(Wheel wh, bool rotated)
{
Camera camera = GameplayScreen.Camera;
foreach (ModelMesh mesh in wheel.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
float steer = wh.SteerAngle;
Matrix rot;
if (rotated) rot = Matrix.CreateRotationY(MathHelper.ToRadians(180.0f));
else rot = Matrix.Identity;
effect.World = rot * Matrix.CreateRotationZ(MathHelper.ToRadians(-wh.AxisAngle)) * // rotate the wheels
Matrix.CreateRotationY(MathHelper.ToRadians(steer)) *
Matrix.CreateTranslation(wh.Pos + wh.Displacement * wh.LocalAxisUp) * car.Chassis.Body.Orientation * // oritentation of wheels
Matrix.CreateTranslation(car.Chassis.Body.Position); // translation
effect.View = camera.View;
effect.Projection = camera.Projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
public override void Draw(GameTime gameTime)
{
DrawWheel(car.Wheels[0], true);
DrawWheel(car.Wheels[1], true);
DrawWheel(car.Wheels[2], false);
DrawWheel(car.Wheels[3], false);
base.Draw(gameTime);
}
public Car Car
{
get { return this.car; }
}
private void SetCarMass(float mass)
{
body.Mass = mass;
Vector3 min, max;
car.Chassis.GetDims(out min, out max);
Vector3 sides = max - min;
float Ixx = (1.0f / 12.0f) * mass * (sides.Y * sides.Y + sides.Z * sides.Z);
float Iyy = (1.0f / 12.0f) * mass * (sides.X * sides.X + sides.Z * sides.Z);
float Izz = (1.0f / 12.0f) * mass * (sides.X * sides.X + sides.Y * sides.Y);
Matrix inertia = Matrix.Identity;
inertia.M11 = Ixx; inertia.M22 = Iyy; inertia.M33 = Izz;
car.Chassis.Body.BodyInertia = inertia;
car.SetupDefaultWheels();
}
public override void ApplyEffects(BasicEffect effect)
{
//
}
}
}
| mrq-cz/ourcity | OurCity/OurCity/OurCity/PhysicObjects/CarObject.cs | C# | mit | 3,827 |
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_AVATOR_DATADetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Register
{
class _AVATOR_DATARegister : public IRegister
{
public:
void Register() override
{
auto& hook_core = CATFCore::get_instance();
for (auto& r : Detail::_AVATOR_DATA_functions)
hook_core.reg_wrapper(r.pBind, r);
}
};
}; // end namespace Register
END_ATF_NAMESPACE
| goodwinxp/Yorozuya | library/ATF/_AVATOR_DATARegister.hpp | C++ | mit | 679 |
var db = require('../models');
exports.checkItemsList = function (req, res, next) {
var data = {
items: []
};
db.Item.findAll().then(function (results) {
for (var i = 0; i < results.length; i++) {
data.items.push(results[i].dataValues);
}
// console.log(data.items);
console.log('items list controller working');
res.locals.items = data.items;
next();
}).catch(function (error) {
console.log(error);
console.log('items list controller error');
next();
});
};
| yoonslee/project2-game | controllers/itemController.js | JavaScript | mit | 522 |
# -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import properties
from datetime import datetime, date
from ..base_model import BaseModel
class Domain(properties.HasProperties):
"""This represents a full search query."""
OR = 'OR'
AND = 'AND'
def __init__(self, queries=None, join_with=AND):
"""Initialize a domain, with optional queries."""
self.query = []
if queries is not None:
for query in queries:
self.add_query(query, join_with)
@classmethod
def from_tuple(cls, queries):
"""Create a ``Domain`` given a set of complex query tuples.
Args:
queries (iter): An iterator of complex queries. Each iteration
should contain either:
* A data-set compatible with :func:`~domain.Domain.add_query`
* A string to switch the join type
Example::
[('subject', 'Test1'),
'OR',
('subject', 'Test2')',
('subject', 'Test3')',
]
# The above is equivalent to:
# subject:'Test1' OR subject:'Test2' OR subject:'Test3'
[('modified_at', datetime(2017, 01, 01)),
('status', 'active'),
]
# The above is equivalent to:
# modified_at:[2017-01-01T00:00:00Z TO *]
# AND status:"active"
Returns:
Domain: A domain representing the input queries.
"""
domain = cls()
join_with = cls.AND
for query in queries:
if query in [cls.OR, cls.AND]:
join_with = query
else:
domain.add_query(query, join_with)
return domain
def add_query(self, query, join_with=AND):
"""Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the interface defined in
:func:`~.domain.DomainCondition.from_tuple`.
join_with (str): The join string to apply, if other queries are
already on the stack.
"""
if not isinstance(query, DomainCondition):
query = DomainCondition.from_tuple(query)
if len(self.query):
self.query.append(join_with)
self.query.append(query)
def __str__(self):
"""Return a string usable as the query in an API request."""
if not self.query:
return '*'
return '(%s)' % ' '.join([str(q) for q in self.query])
class DomainCondition(properties.HasProperties):
"""This represents one condition of a domain query."""
field = properties.String(
'Field to search on',
required=True,
)
value = properties.String(
'String Value',
required=True,
)
@property
def field_name(self):
"""Return the name of the API field."""
return BaseModel._to_camel_case(self.field)
def __init__(self, field, value, **kwargs):
"""Initialize a new generic query condition.
Args:
field (str): Field name to search on. This should be the
Pythonified name as in the internal models, not the
name as provided in the API e.g. ``first_name`` for
the Customer's first name instead of ``firstName``.
value (mixed): The value of the field.
"""
return super(DomainCondition, self).__init__(
field=field, value=value, **kwargs
)
@classmethod
def from_tuple(cls, query):
"""Create a condition from a query tuple.
Args:
query (tuple or list): Tuple or list that contains a query domain
in the format of ``(field_name, field_value,
field_value_to)``. ``field_value_to`` is only applicable in
the case of a date search.
Returns:
DomainCondition: An instance of a domain condition. The specific
type will depend on the data type of the first value provided
in ``query``.
"""
field, query = query[0], query[1:]
try:
cls = TYPES[type(query[0])]
except KeyError:
# We just fallback to the base class if unknown type.
pass
return cls(field, *query)
def __str__(self):
"""Return a string usable as a query part in an API request."""
return '%s:"%s"' % (self.field_name, self.value)
class DomainConditionBoolean(DomainCondition):
"""This represents an integer query."""
value = properties.Bool(
'Boolean Value',
required=True,
)
def __str__(self):
"""Return a string usable as a query part in an API request."""
value = 'true' if self.value else 'false'
return '%s:%s' % (self.field_name, value)
class DomainConditionInteger(DomainCondition):
"""This represents an integer query."""
value = properties.Integer(
'Integer Value',
required=True,
)
def __str__(self):
"""Return a string usable as a query part in an API request."""
return '%s:%d' % (self.field_name, self.value)
class DomainConditionDateTime(DomainCondition):
"""This represents a date time query."""
value = properties.DateTime(
'Date From',
required=True,
)
value_to = properties.DateTime(
'Date To',
)
def __init__(self, field, value_from, value_to=None):
"""Initialize a new datetime query condition.
Args:
field (str): Field name to search on. This should be the
Pythonified name as in the internal models, not the
name as provided in the API e.g. ``first_name`` for
the Customer's first name instead of ``firstName``.
value_from (date or datetime): The start value of the field.
value_to (date or datetime, optional): The ending value for
the field. If omitted, will search to now.
"""
return super(DomainConditionDateTime, self).__init__(
field=field, value=value_from, value_to=value_to,
)
def __str__(self):
"""Return a string usable as a query part in an API request."""
value_to = self.value_to.isoformat() if self.value_to else '*'
return '%s:[%sZ TO %sZ]' % (
self.field_name,
self.value.isoformat(),
value_to,
)
TYPES = {
bool: DomainConditionBoolean,
int: DomainConditionInteger,
date: DomainConditionDateTime,
datetime: DomainConditionDateTime,
}
__all__ = [
'Domain',
'DomainCondition',
'DomainConditionBoolean',
'DomainConditionDateTime',
'DomainConditionInteger',
]
| LasLabs/python-helpscout | helpscout/domain/__init__.py | Python | mit | 7,131 |
/*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The Bitcoin Developers 2011-2012
*/
#include <QApplication>
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "walletframe.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#include "ui_interface.h"
#include "wallet.h"
#include "init.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QTimer>
#include <QDragEnterEvent>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#include <QMimeData>
#include <QStyle>
#include <QSettings>
#include <QDesktopWidget>
#include <QListWidget>
#include <iostream>
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
BitcoinGUI::BitcoinGUI(QWidget *parent) :
QMainWindow(parent),
clientModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0),
prevBlocks(0)
{
restoreWindowGeometry();
setWindowTitle(tr("Woodcoin") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
QApplication::setWindowIcon(QIcon(":icons/bitcoin"));
setWindowIcon(QIcon(":icons/bitcoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Create wallet frame and make it the central widget
walletFrame = new WalletFrame(this);
setCentralWidget(walletFrame);
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon();
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setMinimumWidth(56);
frameBlocks->setMaximumWidth(56);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
rpcConsole = new RPCConsole(this);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
}
BitcoinGUI::~BitcoinGUI()
{
saveWindowGeometry();
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::instance()->setMainWindow(NULL);
#endif
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a Woodcoin address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Addresses"), this);
addressBookAction->setStatusTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setToolTip(addressBookAction->statusTip());
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About Woodcoin"), this);
aboutAction->setStatusTip(tr("Show information about Woodcoin"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for Woodcoin"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your Woodcoin addresses to prove you own them"));
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Woodcoin addresses"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet"));
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
if(trayIcon)
{
// Just attach " [testnet]" to the existing tooltip
trayIcon->setToolTip(trayIcon->toolTip() + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
}
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Receive and report messages from network/worker thread
connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));
rpcConsole->setClientModel(clientModel);
walletFrame->setClientModel(clientModel);
}
}
bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
{
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
{
return walletFrame->setCurrentWallet(name);
}
void BitcoinGUI::removeAllWallets()
{
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
addressBookAction->setEnabled(enabled);
}
void BitcoinGUI::createTrayIcon()
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIcon->setToolTip(tr("Woodcoin client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
trayIcon->show();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon);
}
void BitcoinGUI::createTrayIconMenu()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void BitcoinGUI::saveWindowGeometry()
{
QSettings settings;
settings.setValue("nWindowPos", pos());
settings.setValue("nWindowSize", size());
}
void BitcoinGUI::restoreWindowGeometry()
{
QSettings settings;
QPoint pos = settings.value("nWindowPos").toPoint();
QSize size = settings.value("nWindowSize", QSize(850, 550)).toSize();
if (!pos.x() && !pos.y())
{
QRect screen = QApplication::desktop()->screenGeometry();
pos.setX((screen.width()-size.width())/2);
pos.setY((screen.height()-size.height())/2);
}
resize(size);
move(pos);
}
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::gotoOverviewPage()
{
if (walletFrame) walletFrame->gotoOverviewPage();
}
void BitcoinGUI::gotoHistoryPage()
{
if (walletFrame) walletFrame->gotoHistoryPage();
}
void BitcoinGUI::gotoAddressBookPage()
{
if (walletFrame) walletFrame->gotoAddressBookPage();
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void BitcoinGUI::gotoSendCoinsPage(QString addr)
{
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Woodcoin network", "", count));
}
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
QDateTime currentDate = QDateTime::currentDateTime();
int secs = lastBlockDate.secsTo(currentDate);
if(count < nTotalBlocks)
{
tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks);
}
else
{
tooltip = tr("Processed %1 blocks of transaction history.").arg(count);
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
walletFrame->showOutOfSyncWarning(false);
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
else
{
// Represent time from last generated block in human readable text
QString timeBehindText;
if(secs < 48*60*60)
{
timeBehindText = tr("%n hour(s)","",secs/(60*60));
}
else if(secs < 14*24*60*60)
{
timeBehindText = tr("%n day(s)","",secs/(24*60*60));
}
else
{
timeBehindText = tr("%n week(s)","",secs/(7*24*60*60));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
if(count != prevBlocks)
syncIconMovie->jumpToNextFrame();
prevBlocks = count;
walletFrame->showOutOfSyncWarning(true);
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
{
QString strTitle = tr("Woodcoin"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
// Override title based on style
QString msgType;
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
msgType = title; // Use supplied title
}
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
}
else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
}
else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
QApplication::quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address)
{
// On new transaction, make an info balloon
message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(unit, amount, true))
.arg(type)
.arg(address), CClientUIInterface::MSG_INFORMATION);
}
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (walletFrame->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
walletFrame->gotoSendCoinsPage();
else
message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Woodcoin address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
}
event->acceptProposedAction();
}
bool BitcoinGUI::eventFilter(QObject *object, QEvent *event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip)
{
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
void BitcoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (!walletFrame->handleURI(strURI))
message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Woodcoin address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::detectShutdown()
{
if (ShutdownRequested())
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
| woodedlawn/woodcoin | src/qt/bitcoingui.cpp | C++ | mit | 29,694 |
import $ from 'jquery'
import template from './Loadbox.html'
import Mustache from 'mustache'
import img1 from '../../images/load-circle.png'
import img2 from '../../images/load-bg.png'
import img3 from '../../images/logo.png'
import img4 from '../../images/slogan.png'
import img5 from '../../images/panel-bg.jpg'
import img6 from '../../images/button.png'
import img7 from '../../images/leftnav.png'
import img8 from '../../images/intro_1_pic.png'
import img9 from '../../images/intro_2_pic.png'
import img10 from '../../images/intro_3_pic.png'
import img11 from '../../images/intro_1_txt.png'
import img12 from '../../images/intro_2_txt.png'
import img13 from '../../images/intro_3_txt.png'
import img14 from '../../images/intro_4_txt.png'
import img15 from '../../images/intro_5_txt.png'
import img16 from '../../images/bg.jpg'
export default class Loadbox {
constructor(type) {
this.type = type;
}
render() {
let preload = []
switch(this.type) {
case 'landing':
preload = [img1,img2,img3,img4,img5,img6,img7,img8,img9,img10,img11,img12,img13,img14,img15,img16]
break
default:
preload = []
}
$('#preload').html(
Mustache.render(template, {preload: preload})
);
}
} | RainKolwa/goon_cowala_feb | src/components/Loadbox/Index.js | JavaScript | mit | 1,235 |
const postcss = require('postcss');
const fs = require('fs');
const plugin = require('../index');
const pkg = require('../package.json');
/**
* Runs the plugins process function. Tests whether the given input is equal
* to the expected output with the given options.
*
* @param {string} input Input fixture file name.
* @param {object} opts Options to be used by the plugin.
* @return {function}
*/
function run(input, opts = {}) {
const raw = fs.readFileSync(`./test/fixtures/${input}.css`, 'utf8');
const expected = fs.readFileSync(`./test/fixtures/${input}.expected.css`, 'utf8');
return postcss([plugin(opts)]).process(raw, { from: undefined })
.then(result => {
expect(result.css).toEqual(expected);
expect(result.warnings().length).toBe(0);
});
}
it('Should replace strings in comments and styles.', () => {
return run('basic', { data: pkg });
});
it('Should throw a TypeError if invalid pattern is supplied.', () => {
return run('basic', { data: pkg, pattern: '' }).catch(e =>
expect(e).toBeInstanceOf(TypeError)
)
});
it('Should not replace anything in styles when “commentsOnly” option is set to TRUE.', () => {
return run('commentsOnly', { data: pkg, commentsOnly: true });
});
it('Should not replace anything without data', () => {
return run('noChanges');
});
it('Should not change unknown variables', () => {
return run('noChanges', { data: pkg });
});
it('Should work with deep data objects', () => {
return run('deep', { data: { level1: { level2: 'test' } } });
});
it('Should work with a custom RegEx', () => {
return run('otherRegex', { data: pkg, pattern: /%\s?([^\s]+?)\s?%/gi });
});
it('Should work with a custom RegEx object', () => {
return run('basic', { data: pkg, pattern: new RegExp(/{{\s?([^\s]+?)\s?}}/, 'gi') });
});
it('Should work with a custom RegEx string', () => {
return run('basic', { data: pkg, pattern: '{{\\s?([^\\s]+?)\\s?}}' });
});
it('Should work with another custom RegEx string', () => {
return run('otherRegex', { data: pkg, pattern: '%\\s?([^\\s]+?)\\s?%' });
});
it('Should work with empty string values', () => {
return run('empty', { data: { value: '' } });
});
it('Should work with undefined values', () => {
return run('noChanges', { data: { value: undefined } });
});
it('Should work with null values', () => {
return run('noChanges', { data: { value: null } });
});
it('Should work with null data', () => {
return run('noChanges', { data: null });
});
it('Should not replace multiple times', () => {
return run('noDuplicate', {
pattern: /(a)/g,
data: { a: 'abc'}
});
});
it('Should replace strings in selectors', () => {
return run('selectors', {
pattern: /(foo)/g,
data: { 'foo': 'bar' },
});
});
it('Should replace regex to empty in selectors', () => {
return run('regexEmpty', {
pattern: /\[.*\]:delete\s+/gi,
data: { replaceAll: '' }
});
});
it('Should replace regex to single value in selectors', () => {
return run('regexValue', {
pattern: /\[.*\]:delete/gi,
data: { replaceAll: '.newValue' }
});
});
it('Should work with custom Regex string', () => {
return run('customRegexValue', {
pattern: new RegExp(/%replace_me%/, 'gi'),
data: { replaceAll: 'new awesome string :)' }
});
});
it('Should replace properties and values', () => {
return run('replaceProperties', {
pattern: /##\((.*?)\)/g,
data: {
'prop': 'color',
'name': 'basic',
'key': 'dark',
'value': '#9c9c9c'
},
});
});
| gridonic/postcss-replace | test/index.test.js | JavaScript | mit | 3,694 |
<?php
return array (
'id' => 'htc_desire_500_ver1',
'fallback' => 'generic_android_ver4_1',
'capabilities' =>
array (
'uaprof' => 'http://www.htcmms.com.tw/Android/Vodafone/0P3Z11/ua-profile.xml',
'model_name' => 'Desire 500',
'brand_name' => 'HTC',
'release_date' => '2013_august',
'physical_screen_height' => '94',
'physical_screen_width' => '57',
'resolution_width' => '480',
'resolution_height' => '800',
'max_data_rate' => '7200',
),
);
| cuckata23/wurfl-data | data/htc_desire_500_ver1.php | PHP | mit | 489 |
require 'pry'
module Zephyre
class Controller
attr_reader :request
def initialize(env)
@request ||= Rack::Request.new(env)
end
def params
request.params
end
def response(body, status=200, header={})
@response = Rack::Response.new(body, status, header)
end
def get_response
@response
end
def render(*args)
response(render_template(*args), 200, {"Content-Type" => "text/html"})
end
def render_template(view_name, locals = {})
filename = File.join("app", "views", controller_name, "#{view_name}.erb")
# If we find a file, render it, otherwise just render whatever was passed as a string
template = File.file?(filename) ? File.read(filename) : view_name.to_s
vars = {}
instance_variables.each do |var|
key = var.to_s.gsub("@", "").to_sym
vars[key] = instance_variable_get(var)
end
ERB.new(template).result(binding)
end
def controller_name
self.class.to_s.gsub(/Controller$/, "").to_snake_case
end
def dispatch(action)
content = self.send(action)
if get_response
get_response
else
render(action)
get_response
end
end
def self.action(action_name)
-> (env) { self.new(env).dispatch(action_name) }
end
end
end | alexdovzhanyn/zephyre | lib/zephyre/controller.rb | Ruby | mit | 1,246 |
require 'rails_helper'
RSpec.describe "user_infos/index", type: :view do
before(:each) do
assign(:user_infos, [
UserInfo.create!(
:hometown => "Hometown",
:major => "Major",
:age => "Age",
:description => "MyText",
:show_email => false
),
UserInfo.create!(
:hometown => "Hometown",
:major => "Major",
:age => "Age",
:description => "MyText",
:show_email => false
)
])
end
it "renders a list of user_infos" do
render
assert_select "tr>td", :text => "Hometown".to_s, :count => 2
assert_select "tr>td", :text => "Major".to_s, :count => 2
assert_select "tr>td", :text => "Age".to_s, :count => 2
assert_select "tr>td", :text => "MyText".to_s, :count => 2
assert_select "tr>td", :text => false.to_s, :count => 2
end
end
| code4naropa/ournaropa-forum | spec/views/ournaropa_forum/user_infos/index.html.erb_spec.rb | Ruby | mit | 860 |
package backend
import (
"testing"
"github.com/stretchr/testify/assert"
)
var (
testStartAttributesTestCases = []struct {
A []*StartAttributes
O []*StartAttributes
}{
{
A: []*StartAttributes{
{Language: ""},
{Language: "ruby"},
{Language: "python", Dist: "trusty"},
{Language: "python", Dist: "trusty", Group: "edge"},
{Language: "python", Dist: "frob", Group: "edge", OS: "flob"},
{Language: "python", Dist: "frob", OsxImage: "", Group: "edge", OS: "flob"},
{Language: "python", Dist: "frob", OsxImage: "", Group: "edge", OS: "flob", VMType: "premium"},
},
O: []*StartAttributes{
{Language: "default", Dist: "precise", Group: "stable", OS: "linux", VMType: "default"},
{Language: "ruby", Dist: "precise", Group: "stable", OS: "linux", VMType: "default"},
{Language: "python", Dist: "trusty", Group: "stable", OS: "linux", VMType: "default"},
{Language: "python", Dist: "trusty", Group: "edge", OS: "linux", VMType: "default"},
{Language: "python", Dist: "frob", Group: "edge", OS: "flob", VMType: "default"},
{Language: "python", Dist: "frob", OsxImage: "", Group: "edge", OS: "flob", VMType: "default"},
{Language: "python", Dist: "frob", OsxImage: "", Group: "edge", OS: "flob", VMType: "premium"},
},
},
}
)
func TestStartAttributes(t *testing.T) {
sa := &StartAttributes{}
assert.Equal(t, "", sa.Dist)
assert.Equal(t, "", sa.Group)
assert.Equal(t, "", sa.Language)
assert.Equal(t, "", sa.OS)
assert.Equal(t, "", sa.OsxImage)
assert.Equal(t, "", sa.VMType)
}
func TestStartAttributes_SetDefaults(t *testing.T) {
for _, tc := range testStartAttributesTestCases {
for i, sa := range tc.A {
expected := tc.O[i]
sa.SetDefaults("default", "precise", "stable", "linux", "default")
assert.Equal(t, expected, sa)
}
}
}
| solarce/worker | backend/start_attributes_test.go | GO | mit | 1,823 |
while True:
input_number = int(raw_input())
if input_number == 42:
break
print input_number,
exit() | sandy-8925/codechef | test.py | Python | mit | 112 |
<?php
/*
* This file is part of the zzAgenda package.
*
* (c) OV Corporation SAS <contact@ov-corporation.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ZZFramework\Event;
interface EventSubscriberInterface
{
public function getObservedEvents();
} | croziere/zzAgenda | lib/ZZFramework/Event/EventSubscriberInterface.php | PHP | mit | 374 |
// Import React
import React from "react";
// Import Spectacle Core tags
import {
BlockQuote,
Cite,
CodePane,
Deck,
Heading,
Image,
Link,
Quote,
Slide,
Spectacle,
Text,
Code,
Markdown,
List,
ListItem
} from "spectacle";
import CodeSlide from "spectacle-code-slide";
// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";
// Import theme
import createTheme from "spectacle/lib/themes/default";
// Import custom component
// import Interactive from "../assets/interactive";
// Require CSS
require("normalize.css");
require("spectacle/lib/themes/default/index.css");
const images = {
styleguide: require("../assets/styleguide.png"),
invision: require("../assets/invision_styleguide.png"),
canvas: require("../assets/canvas.png"),
toggle: require("../assets/toggle.png"),
panda: require("../assets/panda.jpg"),
checkbox: require("../assets/checkbox.png"),
happy: require("../assets/happy.jpg"),
button: require("../assets/button.png"),
production: require("../assets/production.png"),
development: require("../assets/development.png"),
initial: require("../assets/initial.png"),
applyTheme: require("../assets/applyTheme.png"),
themed: require("../assets/themed.png"),
zoomed: require("../assets/zoomed.png"),
variableSupport: require("../assets/variableSupport.png"),
holyGrail: require("../assets/holyGrail.jpg"),
microservices: require("../assets/microservices.jpg")
};
preloader(images);
const theme = createTheme({
primary: "#1bb7b6"
}, {
primary: "Lato"
});
export default class Presentation extends React.Component {
render() {
return (
<Spectacle theme={theme}>
<Deck transition={["zoom", "slide"]} transitionDuration={500}>
<Slide transition={["zoom"]} bgColor="primary">
<Heading size={1} fit caps lineHeight={1} textColor="black">
Style Guide Driven Development
</Heading>
<Heading size={1} fit caps>
<i>
<small style={{ paddingRight: "4px", textTransform: "lowercase", fontWeight: "normal" }}>with</small>
</i>
React and CSS Modules
</Heading>
</Slide>
<Slide transition={["slide"]} bgColor="black"
notes={`
A little information about myself: I'm Lead UI Engineer on the UI dev team at Instructure.
We're a cross-functional team made up of designers and engineers and we work closely with
both Engineering and Product Design/UX.
Our goal is to build tools and establish processes that make it easier for our designers and
developers to more easily collaborate.
`}
>
<Heading size={1} fit caps lineHeight={1} textColor="primary">
Jennifer Stern
</Heading>
<Heading size={1} fit caps>
Lead UI Engineer @ <Link href="http://instructure.com" textColor="tertiary">Instructure</Link>
</Heading>
<Text lineHeight={1} textColor="tertiary">
jstern@instructure.com
</Text>
</Slide>
<Slide
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
What's a style guide?
Where application development is concerned:
It's all about better process and communication between designers and developers
(and in a larger org between developers -- reducing duplication of efforts)
To produce a more consistent UX and to be able to build out UI code more efficiently.
`}
>
<Heading size={1} fit caps lineHeight={1}>
What's a Style Guide?
</Heading>
<BlockQuote bgColor="rgba(0, 0, 0, 0.6)" margin="1em 0" padding="1em 1.5em">
<Quote textColor="tertiary" textSize="1em" bold={false} lineHeight={1.5}>
A style guide is a set of standards for the writing and design of documents,
either for general use or for a specific publication, organization, or field....
<Text margin="1em 0px 0px" textSize="1em" textColor="primary" caps bold lineHeight={1.2}>
A style guide establishes and enforces style to improve communication.
</Text>
</Quote>
<Cite textColor="tertiary" textSize="0.5em">
<Link textColor="tertiary" href="https://en.wikipedia.org/wiki/Style_guide">
Wikipedia
</Link>
</Cite>
</BlockQuote>
</Slide>
<Slide
notes={`
Our designers maintain a static style guide in Sketch app and they share it
with us in invision.
This document doesn't really reflect the state of the current application UI
and is time consuming to maintain.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Static Style Guide
</Text>
<div className="browser">
<Image src={images.invision.replace("/", "")} margin="0" height="500px" />
</div>
</Slide>
<Slide
notes={`
vs a "live" style guide...
In recent years it's become pretty standard to build out a "living" style
guide and there are a bunch of open source tools to help you generate documentation
from your Sass or CSS style sheets.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Live Style Guide
</Text>
<Text textSize="3rem" textColor="tertiary">(or pattern library)</Text>
<div className="browser">
<Image src={images.canvas.replace("/", "")} margin="0" height="400px" />
</div>
</Slide>
<Slide
notes={`
We've had one our living style guide for a while now and the documentation looks like this.
When I first starting building out documentation like this, I was thinking...
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
In a Live Style Guide
</Text>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Documentation lives with the source code in the same repository
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/buttons.scss")}
ranges={[
{ loc: [0, 0], title: "buttons.scss" },
{ loc: [0, 21]}
]}
/>
<Slide
bgColor="black"
transition={["slide"]}
notes={`
Is this the holy grail? Can we finally have a 'single source of truth' owned by
both design and engineering and stop manually updating documentation that is usually
out of date as soon as we write it?
`}
>
<Image src={images.holyGrail.replace("/", "")} margin="0" />
</Slide>
<Slide
bgColor="black"
transition={["slide"]}
notes={`
Well... Nope.
As it turns out, our "live" style guide is still out of sync with the application code,
and most designers and developers don't reference it when they are working on new features
(if they know it exists).
Why?
There is a steep learning curve to working in our monolithic code base, and since the old
style guide lives there and is part of that build, it's difficult to set up and
get running. So it's not really fair to ask designers to learn to update the documentation.
In fact, most developers aren't familiar with the style guide part of the build
because our current front end build process and testing setup is confusing and cumbersome.
`}
>
<Image src={images.panda.replace("/", "")} margin="0" />
</Slide>
<Slide
notes={`
So let's take a look at a custom checkbox (toggle) in our sass style guide.
Notice that there is a lot of markup to copy and paste.
Also to make it accessible we need to add some JS behavior to it.
So the documentation doesn't necessarily reflect what's in the application code
in terms of html markup or JS for behavior.
The scss code for this component lives in a common css file that is used across the
application.
Most developers are reluctant to make changes to CSS because they aren't sure what they may
break and so they probably never see the files that have the documentation comment blocks.
This leads to lots of one-off solutions and overrides, duplication of effort and
inconsistency in the UX.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
A custom checkbox in <b>Sass</b>
</Text>
<div className="browser">
<Image src={images.toggle.replace("/", "")} margin="0" height="500px" />
</div>
</Slide>
<Slide
notes={`
Let's compare that Toggle documentation with a custom checkbox (toggle)
in our new React style guide.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
A custom checkbox in <b>React</b>
</Text>
<div className="browser">
<Image src={images.checkbox.replace("/", "")} margin="0" height="500px" />
</div>
</Slide>
<Slide
notes={`
Similar to our old style guide:
the documentation is generated from the source code + markdown in comment blocks.
Examples are generated from code blocks.
Property documentation is generated from code + comment blocks using react-docgen.
But in this case, CSS, JS, HTML and documentation are bundled and documented as one
component.
Notice that here we're encapsulating style, markup and behavior for the component.
And we've replaced all of those lines of code with one.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<b>CSS, JS, HTML</b> & documentation
</Text>
<Text textColor="tertiary" caps fit>
in one place
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/checkbox.js")}
ranges={[
{ loc: [48, 270], title: "checkbox.js" },
{ loc: [21, 24]}
]}
/>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
So that's great, but how do we get designers and developers to share ownership of
our living style guide v2.0 (and actually use it)?
`}
>
<BlockQuote bgColor="rgba(0, 0, 0, 0.6)" margin="1em 0" padding="1em 1.5em">
<Quote textColor="tertiary" textSize="1em" bold={false} lineHeight={1.2}>
Make the right things easy and the wrong things hard.
</Quote>
<Cite textColor="tertiary" textSize="0.5em">
<Link textColor="tertiary" href="https://en.wikipedia.org/wiki/Style_guide">
Jonathan Snook
</Link>
</Cite>
</BlockQuote>
<Text textColor="tertiary" textSize="0.75em">And now I'll attempt to live code...</Text>
</Slide>
<Slide
notes={`
The component library code is in a separate repository and the documentation app
is easy to install and and run locally.
We've spent lots of time on scaffolding and tools to make it super easy to
spin up a new component and write documentation and tests for it.
(webpack dev server + hot reloading, eslint, stylelint)
Now designers can (at minimum) pull down code from a pull request and run it locally.
(We're working on convincing them that they can update it too :) )
The easiest thing used to be to make a one-off solution for the feature, but we've
made it a lot easier to contribute to the shared UI code instead.
`}
>
<Image src={images.happy.replace("/", "")} margin="0" />
</Slide>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
So now that we're bundling JS, CSS and HTML together into a single component, how can we be sure
that it will render the same in the application as it does in our style guide?
Can we take advantage of the fact that we're using JS to render these components?
Should we consider writing our CSS in JS (as inline styles)?
Lots of react component libraries are using frameworks like Radium and Aphrodite to write CSS in JS.
`}
>
<BlockQuote bgColor="rgba(0, 0, 0, 0.6)" margin="1em 0" padding="1em 1.5em">
<Quote textColor="tertiary" textSize="1em" bold={false} lineHeight={1.2}>
CSS in JS?
<Markdown>
{`
1. Global Namespaces
2. Dependencies
3. Dead Code Elimination
4. Minification
5. Sharing Constants
6. Non-Deterministic Resolution
7. Isolation
`}
</Markdown>
</Quote>
<Cite textColor="tertiary" textSize="0.5em">
<Link textColor="tertiary" href="">
Christopher "vjeux" Chedeau
</Link>
</Cite>
</BlockQuote>
</Slide>
<Slide
notes={`
CSS Modules solves 1-6 and half of 7
With CSS modules we can isolate components and make them more durable by
limiting the scope of their CSS.
With CSS modules we can write our class names as if they were only scoped
to the component we're working on without worrying that we'll accidentally
break something somewhere else.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
CSS Modules
</Text>
<Text textColor="tertiary" caps fit>
(isolate component styles <b>without writing CSS in JS</b>)
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/button.css")}
ranges={[
{ loc: [0, 0], title: "button.css" },
{ loc: [274, 280], title: "local classes"}
]}
/>
<Slide
notes={`
CSS Modules
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
CSS Modules
</Text>
<Text textColor="tertiary" caps fit>
loading a CSS file in a JS component
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/button.js")}
ranges={[
{ loc: [0, 0], title: "button.js" },
{ loc: [7, 9], title: "importing styles"},
{ loc: [161, 168], title: "rendering styles"},
{ loc: [184, 195] }
]}
/>
<Slide
notes={`
Generated class names in production
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<small>with</small> production config
</Text>
<div className="browser">
<Image src={images.production.replace("/", "")} margin="0" height="550px" />
</div>
</Slide>
<Slide
notes={`
Generated class names in development
Note that it's pretty similar to the BEM class name format
This makes it easy to debug issues in dev mode.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<small>with</small> development config
</Text>
<div className="browser">
<Image src={images.development.replace("/", "")} margin="0" height="550px" />
</div>
</Slide>
<Slide
notes={`
The other half of #7
Prevent the cascade with all: initial and postcss-initial
We need to roll out these components bit by bit, so they need to work when older
legacy CSS and various versions of Bootstrap CSS.
We want to be pretty sure they'll work the same in the consuming app as they do in
the documentation app.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Prevent the Cascade
</Text>
<Text textColor="tertiary" caps fit>
with <Code textSize="1em" caps={false}>all: initial</Code> and postcss-initial
</Text>
<div className="browser">
<Image src={images.initial.replace("/", "")} margin="0" width="100%" />
</div>
</Slide>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
As it turns out, bundling component JS, CSS and markup together
makes writing accessibile UIs a whole lot easier.
What does it mean for a UI to be accesible?
It's about building your UI so that it works with assistive tech like screen readers,
keyboards (for users who can't use a mouse) and for people who may be color blind or
have partial vision.
`}
>
<Heading size={1} fit caps>Accessibility</Heading>
</Slide>
<Slide
notes={`
A11y benefits (Button and Link components)
In Canvas, we fix a lot of a11y bugs around buttons. Usually
we've added onClick behavior to a div or we've styled a link to look
like a button (or vice versa).
Rule of thumb for keyboard a11y:
If it looks like a button it should behave like a button.
If it looks like a link it should behave like a link.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Accessible Buttons
</Text>
<div className="browser">
<Image src={images.button.replace("/", "")} margin="0" height="500px" />
</div>
</Slide>
<Slide
notes={`
(JS...)
A11y benefits (Button and Link components)
Take a look at the handleKeyDown method
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Adding (JS) behavior to components for <b>accessibility</b>
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/button.js")}
ranges={[
{ loc: [0, 0], title: "button.js" },
{ loc: [113, 134]}
]}
/>
<Slide
notes={`
(html...)
A11y benefits (unit tests)
We can use tools like axe-core and eslint-plugin-jsx-a11y to run unit tests to verify
that the components are accessible and lint for common a11y issues
(e.g. missing alt attributes on images).
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Unit tests for Accessibility using <b>axe-core</b>
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/checkbox.test.js")}
ranges={[
{ loc: [0, 0], title: "checkbox.test.js" },
{ loc: [79, 87]}
]}
/>
<Slide
notes={`
(color variables...)
A11y benefits (color contrast)
Notice the variables are defined in JS...
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Testing <b>color contrast</b> for a11y
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="jsx"
code={require("raw!../assets/button.test.js")}
ranges={[
{ loc: [0, 0], title: "theme.test.js" },
{ loc: [8, 14]}
]}
/>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.50}
notes={`
`}
>
<Heading size={1} caps>Themes</Heading>
</Slide>
<Slide
notes={`
Sass variables
Notice the global (color) variables.
Notice the functional (link) variables.
What's the drawback here?
We need to pre-process all of the variations and custom brands as part of our build.
How can we avoid this?
We can write our variables (not our CSS) in JS.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
SASS variables <b>in the monolith</b>
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="css"
code={require("raw!../assets/variables.scss")}
ranges={[
{ loc: [0, 0], title: "variables.scss" },
{ loc: [186, 188], title: "global variables"},
{ loc: [204, 208], title: "functional variables"}
]}
/>
<Slide
notes={`
Global/Brand JS variables
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<b>Global brand variables</b> defined in JS
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="js"
code={require("raw!../assets/brand.js")}
ranges={[
{ loc: [0, 0], title: "brand.js" },
{ loc: [4, 9], title: "global color variables"}
]}
/>
<Slide
notes={`
Component/functional variables
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
<b>Component variables</b> defined in JS
</Text>
</Slide>
<CodeSlide
transition={["slide"]}
lang="js"
code={require("raw!../assets/theme.js")}
ranges={[
{ loc: [0, 0], title: "theme.js" },
{ loc: [7, 14], title: "component variables"}
]}
/>
<Slide
notes={`
Now these variables are accessible withing our JS code too...
and we can do run time themeing.
Here's the ApplyTheme component.
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Applying themes at run time
</Text>
<div className="browser">
<Image src={images.applyTheme.replace("/", "")} margin="0" width="800px" />
</div>
</Slide>
<Slide
notes={`
How does this work without writing inline styles with JS?
...CSS custom properties
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
CSS custom properties
</Text>
<div className="browser">
<Image src={images.themed.replace("/", "")} margin="0" width="800px" />
</div>
</Slide>
<Slide
notes={`
Setting custom properties with JS
`}
>
<Code textColor="tertiary" fit lineHeight={1}>
CSSStyleDeclaration.setProperty()
</Code>
<CodePane
lang="js"
source={require("raw!../assets/setProperty.js")}
textSize="1em"
margin="1em auto"
/>
</Slide>
<Slide
notes={`
CSS custom properties have pretty good browser support
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
CSS custom properties
</Text>
<Text textSize="2rem" textColor="tertiary" lineHeight={1}>
(we wrote a polyfill for IE)
</Text>
<div className="browser">
<Image src={images.variableSupport.replace("/", "")} margin="0" width="800px" />
</div>
</Slide>
<Slide
transition={["spin", "slide"]}
bgImage={images.microservices.replace("/", "")} bgDarken={0.70}
notes={`
How's it going so far?
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Built to Scale
</Text>
<Text textSize="3rem" textColor="tertiary" bold>
We're using our UI components in multiple applications as we start breaking up the monolith
into microservices
</Text>
<Text textColor="tertiary">
&
</Text>
<Text textSize="3rem" textColor="tertiary" bold>
Our professional services team is using the library to build custom integrations with a seamless UX.
</Text>
</Slide>
<Slide
transition={["spin", "slide"]}
bgImage={images.styleguide.replace("/", "")} bgDarken={0.70}
notes={`
Questions
`}
>
<Heading textColor="tertiary" fit caps lineHeight={1}>
Questions?
</Heading>
<Text fit margin="2em 0" bold textColor="tertiary">
https://github.com/instructure/instructure-ui
</Text>
<Text caps lineHeight={1} textColor="primary" bold margin="1em 0">
We're Hiring!
</Text>
<Text textColor="tertiary">
Contact Ariel: apao@instructure.com
</Text>
</Slide>
<Slide
notes={`
Resources and Links
`}
>
<Text textSize="1rem" textColor="tertiary" fit caps lineHeight={1}>
Resources and Links
</Text>
<List textColor="tertiary">
<ListItem>
<Link textColor="tertiary" href="https://github.com/reactjs/react-docgen">react-docgen</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="http://eslint.org/">eslint</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/stylelint/stylelint">stylelint</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/dequelabs/axe-core">axe-core</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://www.npmjs.com/package/eslint-plugin-jsx-a11y">eslint-plugin-jsx-a11y</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/maximkoretskiy/postcss-initial">postcss-initial</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/css-modules/css-modules">css modules</Link>
</ListItem>
<ListItem>
<Link textColor="tertiary" href="https://github.com/webpack/css-loader">webpack css-loader</Link>
</ListItem>
</List>
</Slide>
</Deck>
</Spectacle>
);
}
}
| junyper/react-meetup | presentation/index.js | JavaScript | mit | 29,727 |
import json
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
def jsonfilter(value):
return mark_safe(json.dumps(value))
register.filter('json', jsonfilter)
| Open511/open511-server | open511_server/templatetags/open511.py | Python | mit | 220 |
<?php
namespace Anroots\Pgca\Test;
use Faker\Factory;
use Faker\Generator;
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
/**
* @return Generator
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function getFaker()
{
return Factory::create();
}
}
| anroots/pgca | tests/Anroots/Pgca/Test/TestCase.php | PHP | mit | 305 |
using System;
using System.Linq;
using FluentAssertions;
using Paster.Specs.Fakes;
using Xbehave;
using xBehave.Paster.Gherkin;
using xBehave.Paster.System;
using Xunit;
namespace Paster.Specs
{
[Trait("Invalid gherkin","")]
public class BadSourceData
{
[Scenario(DisplayName = "Pasting an Empty string")]
public void EmptyString(EnvironmentClipboard clipboard, GherkinPaster sut, TestEnvironment environment)
{
"Given a complete system".Given(() =>
{
environment = FakesLibrary.CreateDefaultEnvironment();
sut = new GherkinPaster(environment);
});
"and a empty string "
.And(() => clipboard = FakesLibrary.CreateShim(String.Empty));
"When the text is pasted"
.Then(() => sut.PasteGherkin(clipboard));
"Then no lines are received by the environment"
.Then(() => environment.LinesWritten.Count()
.Should()
.Be(0));
}
[Scenario(DisplayName = "Pasting invalid gherkin")]
public void InvalidGherkin(EnvironmentClipboard clipboard, GherkinPaster sut, TestEnvironment environment)
{
"Given a complete system".Given(() =>
{
environment = FakesLibrary.CreateDefaultEnvironment();
sut = new GherkinPaster(environment);
});
"and an invalid string of gherkin"
.And(() => clipboard = FakesLibrary.CreateShim("This is not valid gherkin"));
"When the text is pasted"
.Then(() => sut.PasteGherkin(clipboard));
"Then no lines are received by the environment"
.Then(() => environment.LinesWritten.Count()
.Should()
.Be(0));
}
}
} | xbehave/xbehave.net-visual-studio | src/Paster.Specs/BadSourceData.cs | C# | mit | 1,963 |
import { Ng2PopupComponent } from "./ng2-popup.component";
import { Ng2MessagePopupComponent } from "./ng2-message-popup.component";
export { Ng2PopupComponent, Ng2MessagePopupComponent };
export declare class Ng2PopupModule {
}
| salim101/MathQuiz | frontend/node_modules/ng2-popup/dist/ng2-popup.module.d.ts | TypeScript | mit | 229 |
package Movement;
/**
* This is an abstract class ChessUnitMovement.
* It is built to handle chess units movement.
* This class must be implemented to support a units movement.
* @author thapaliya
*/
public abstract class ChessUnitMovement
{
/**
*
* @param currentRow of the unit
* @param currentColum of the unit
* @param desiredRow for the unit
* @param desiredColum for the unit
* @return true if the move of this chess unit from the current position to the
* desired position is valid for this unit.
*/
public abstract boolean acceptMove( int currentRow, int currentColum, int desiredRow, int desiredColum);
}
| thesashi7/SimpleChess | src/Movement/ChessUnitMovement.java | Java | mit | 674 |
package config
const (
// XPathEpisodesOverviewPagePageItems to retrieve pages where videos are schon
XPathEpisodesOverviewPagePageItems = "//a[@class='pageItem']/@href"
// XPathEpisodesItems to retrieve video urls from a page
XPathEpisodesItems = "//div[@class='modCon']/div[@class='mod modD modMini']/div[@class='boxCon']/div[contains(@class, 'box')]/div[contains(@class, 'teaser')]/a[@class='linkAll']/@href"
// XPathVideoPageVideoTags to find all video tags on final video page
XPathVideoPageVideoTags = "//video/@id"
// XPathVideoPageXmlDataTag to find the concrete element where xml url can be extracted, %s is placeholder for video id
XPathVideoPageXmlDataTag = "//a[@id='%s']/@onclick"
// XPathXmlSeriesTitle title of series
XPathXmlSeriesTitle = "//avDocument/topline"
// XPathXmlEpisodeTitle title of episode
XPathXmlEpisodeTitle = "//avDocument/headline"
// XPathXmlEpisodeLanguageCode language of episode
XPathXmlEpisodeLanguageCode = "//avDocument/language"
// XPathXmlEpisodeDescription episodes description
XPathXmlEpisodeDescription = "//avDocument/broadcast/broadcastDescription"
// XPathXmlAssets documents assets where video url can be found
XPathXmlAssets = "//avDocument/assets/asset"
)
| rkl-/kika-downloader | src/kika-downloader/config/xpath.go | GO | mit | 1,236 |
package cz.crcs.ectester.standalone.libs;
import java.security.Provider;
import java.util.Set;
/**
* @author Jan Jancar johny@neuromancer.sk
*/
public class MatrixsslLib extends NativeECLibrary {
public MatrixsslLib() {
super("matrixssl_provider");
}
@Override
native Provider createProvider();
@Override
public native Set<String> getCurves();
}
| petrs/ECTester | src/cz/crcs/ectester/standalone/libs/MatrixsslLib.java | Java | mit | 385 |
// <copyright file="SwitchableSection.cs" company="Cui Ziqiang">
// Copyright (c) 2017 Cui Ziqiang
// </copyright>
namespace CrossCutterN.Weaver.Switch
{
using System;
using System.Collections.Generic;
using Mono.Cecil.Cil;
/// <summary>
/// Switchable section implementation.
/// </summary>
internal sealed class SwitchableSection : ISwitchableSection
{
/// <inheritdoc/>
public int StartIndex { private get; set; }
/// <inheritdoc/>
public int EndIndex { private get; set; }
/// <inheritdoc/>
public Instruction StartInstruction { get; private set; }
/// <inheritdoc/>
public Instruction EndInstruction { get; private set; }
/// <inheritdoc/>
public bool HasSetStartEndInstruction => StartInstruction != null && EndInstruction != null;
/// <inheritdoc/>
public void SetInstructions(IList<Instruction> instructions, Instruction defaultInstruction)
{
if (StartIndex == -1)
{
return;
}
#if DEBUG
if (EndIndex == -1)
{
throw new InvalidOperationException("End index not set yet");
}
if (EndIndex <= StartIndex)
{
throw new InvalidOperationException("End index should be above start index");
}
if (StartIndex >= instructions.Count)
{
throw new ArgumentException("Instruction list not correctly populated");
}
#endif
StartInstruction = instructions[StartIndex];
EndInstruction = EndIndex >= instructions.Count ? defaultInstruction : instructions[EndIndex];
StartIndex = -1;
EndIndex = -1;
}
/// <inheritdoc/>
public void Reset()
{
StartIndex = -1;
EndIndex = -1;
StartInstruction = null;
EndInstruction = null;
}
/// <inheritdoc/>
public void AdjustEndInstruction(Instruction originalEnd, Instruction newEnd)
{
#if DEBUG
if (newEnd == null)
{
throw new ArgumentNullException("newEnd");
}
#endif
if (EndInstruction != null && EndInstruction == originalEnd)
{
EndInstruction = newEnd;
}
}
}
}
| keeper013/CrossCutterN | CrossCutterN.Weaver/Switch/SwitchableSection.cs | C# | mit | 2,421 |
/**
* @file AccessDeniedException.java
* @brief 로그인을 하지 않았거나 세션이 끊긴 경우 발생하는 Exception
* @author 개발3/파트3
* @author 최경진
* @date 생성 : 2014. 4. 17.
* @date 최종수정: 2014. 4. 17.
*/
package com.juseyo.certification.exception;
/**
* @brief AccessDeniedException
* @author 개발3팀/파트3/최경진
* @version 1.0
* @date 생성: 2014. 4. 17.
* @date 최종수정: 2014. 4. 17.
* @remark
*/
public class SessionNotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = -5968061856227840420L;
public SessionNotFoundException() {
super();
}
public SessionNotFoundException(String msg) {
super(msg);
}
}
| zupper77/juseyo | src/main/java/com/juseyo/certification/exception/SessionNotFoundException.java | Java | mit | 778 |
<?php
/* TwigBundle:Exception:traces.xml.twig */
class __TwigTemplate_05a06802ecd3434c77ee29212d49ed457ae32c039667ade3058cbb9e3ff2db70 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo " <traces>
";
// line 2
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()));
foreach ($context['_seq'] as $context["_key"] => $context["trace"]) {
// line 3
echo " <trace>
";
// line 4
$this->env->loadTemplate("TwigBundle:Exception:trace.txt.twig")->display(array("trace" => $context["trace"]));
// line 5
echo "
</trace>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['trace'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 8
echo " </traces>
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:traces.xml.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 39 => 8, 31 => 5, 29 => 4, 26 => 3, 22 => 2, 19 => 1,);
}
}
| thmohd/demo | app/cache/dev/twig/05/a0/6802ecd3434c77ee29212d49ed457ae32c039667ade3058cbb9e3ff2db70.php | PHP | mit | 1,699 |
class CreateApiVerifications < ActiveRecord::Migration
def up
create_table :api_verifications do |t|
t.string :name
t.string :key
t.string :secret
t.timestamps null: false
end
end
def down
drop_table :api_verifications
end
end | Christianjuth/Portfolio | db/migrate/20161104123431_create_api_verifications.rb | Ruby | mit | 273 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kayak;
namespace Pivot.Update.Server
{
class HttpErrorDataProducer : BufferedProducer
{
public HttpErrorDataProducer()
: base("The server did not understand your request.")
{
}
}
}
| hach-que/Pivot.Update | Pivot.Update.Server/HttpErrorDataProducer.cs | C# | mit | 325 |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.text import slugify
from django.contrib.auth.models import (
User
)
from pastryio.models.mixins import ArchiveMixin
class BaseProfile(ArchiveMixin):
user = models.OneToOneField(User)
avatar = models.ImageField(_("avatar"), blank=True)
def __unicode__(self):
return self.user.username
@property
def slug(self):
return slugify(self.user.first_name)
| octaflop/pastryio | apps/profiles/models.py | Python | mit | 496 |
import {
AudioSourceErrorEvent,
AudioSourceInitializingEvent,
AudioSourceOffEvent,
AudioSourceReadyEvent,
AudioStreamNodeAttachedEvent,
AudioStreamNodeAttachingEvent,
AudioStreamNodeDetachedEvent
} from 'microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/AudioSourceEvents';
export {
AudioSourceErrorEvent,
AudioSourceInitializingEvent,
AudioSourceOffEvent,
AudioSourceReadyEvent,
AudioStreamNodeAttachedEvent,
AudioStreamNodeAttachingEvent,
AudioStreamNodeDetachedEvent
};
| billba/botchat | packages/testharness/pre/external/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/AudioSourceEvents.js | JavaScript | mit | 514 |
/*
(c)2014|US-UltimateShip.
Univali - Universidade do Vale do Itajaí.
GeraçãoTec - Projeto Filnal Batalha Final em JAVA.
Criadores:
Alexandre <alexandreess@gmail.com>
Carlos Eduardo Passos de Sousa <carloseduardosousa@gmail.com>
Henrique Wilhelm <henrique.wilhelm@gmail.com>
Jaison dos santos <jaison1906@gmail.com>
Otavio Ribeiro <otavioribeiro@capflorianopolis.org.br>
*/
package br.com.intagrator.cap8;
public class TrabFlowLayout extends java.awt.Frame {
/**
*
*/
private static final long serialVersionUID = 1L;
//Método @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| carlosedusousa/curso-java-fonts | layouts-em-Java/src/br/com/intagrator/cap8/TrabFlowLayout.java | Java | mit | 653 |
package ch11.product_serial;
public class Product
{
private String name;
private double price;
private int quantity;
/**
Constructs a product with empty name and 0 price and
quantity.
*/
public Product()
{
name = "";
price = 0;
quantity = 0;
}
/**
Constructs a product with the given name, price and
quantity.
@param aName product name
@param aPrice product price
@param aQuantity product quantity
*/
public Product(String aName, double aPrice, int aQuantity)
{
name = aName;
price = aPrice;
quantity = aQuantity;
}
/**
Returns the product name.
@return the product name
*/
public String getName()
{
return name;
}
/**
Returns the product price.
@return the product price
*/
public double getPrice()
{
return price;
}
/**
Returns the product quantity.
@return the product quantity
*/
public int getQuantity()
{
return quantity;
}
/**
Sets the product price.
@param newPrice the new product price
*/
public void setPrice(double newPrice)
{
price = newPrice;
}
/**
Sets the product quantity.
@param newQuantity the new product quantity
*/
public void setQuantity(int newQuantity)
{
quantity = newQuantity;
}
public String toString() {
return super.toString()+" : "+ this.name + " (" +this.price+" , "+this.quantity+")";
}
}
| raeffu/prog2 | src/ch11/product_serial/Product.java | Java | mit | 1,562 |
var expect = chai.expect;
var assert = chai.assert;
var Utils = {
elementContainer: undefined,
_init: function(){
this.elementContainer = document.createElement('div');
this.elementContainer.setAttribute('data-element-container', '');
this.elementContainer.style.display = 'none';
document.body.appendChild(this.elementContainer);
return this;
},
append: function(selector, html){
var div = document.createElement('div');
div.innerHTML = html;
var children = Array.prototype.slice.call(div.childNodes);
var length = children.length;
var parents = document.querySelectorAll(selector);
for(var p=0; p<parents.length; p++){
var parent = parents[p];
while(children.length){
var child = children.pop();
parent.appendChild(child);
}
}
},
remove: function(parentSelector, childSelector){
var parents = document.querySelectorAll(parentSelector);
for(var p=0; p<parents.length; p++){
var parent = parents[p];
var children = parent.querySelectorAll(childSelector);
children = Array.prototype.slice.call(children);
while(children.length){
var child = children.pop();
parent.removeChild(child);
}
}
}
}._init(); | hkvalvik/element-observer | test/utils.js | JavaScript | mit | 1,413 |
from django.db import models
from django.core.exceptions import ImproperlyConfigured
from django import forms
from django.conf import settings
import warnings
try:
from keyczar import keyczar
except ImportError:
raise ImportError('Using an encrypted field requires the Keyczar module. '
'You can obtain Keyczar from http://www.keyczar.org/.')
class EncryptionWarning(RuntimeWarning):
pass
class BaseEncryptedField(models.Field):
prefix = 'enc_str:::'
def __init__(self, *args, **kwargs):
if not hasattr(settings, 'ENCRYPTED_FIELD_KEYS_DIR'):
raise ImproperlyConfigured('You must set the ENCRYPTED_FIELD_KEYS_DIR setting to your Keyczar keys directory.')
self.crypt = keyczar.Crypter.Read(settings.ENCRYPTED_FIELD_KEYS_DIR)
# Encrypted size is larger than unencrypted
self.unencrypted_length = max_length = kwargs.get('max_length', None)
if max_length:
max_length = len(self.prefix) + len(self.crypt.Encrypt('x' * max_length))
# TODO: Re-examine if this logic will actually make a large-enough
# max-length for unicode strings that have non-ascii characters in them.
kwargs['max_length'] = max_length
super(BaseEncryptedField, self).__init__(*args, **kwargs)
def to_python(self, value):
if isinstance(self.crypt.primary_key, keyczar.keys.RsaPublicKey):
retval = value
elif value and (value.startswith(self.prefix)):
retval = self.crypt.Decrypt(value[len(self.prefix):])
if retval:
retval = retval.decode('utf-8')
else:
retval = value
return retval
def get_db_prep_value(self, value, connection, prepared=False):
if value and not value.startswith(self.prefix):
# We need to encode a unicode string into a byte string, first.
# keyczar expects a bytestring, not a unicode string.
if type(value) == unicode:
value = value.encode('utf-8')
# Truncated encrypted content is unreadable,
# so truncate before encryption
max_length = self.unencrypted_length
if max_length and len(value) > max_length:
warnings.warn("Truncating field %s from %d to %d bytes" % (
self.name, len(value), max_length), EncryptionWarning
)
value = value[:max_length]
value = self.prefix + self.crypt.Encrypt(value)
return value
class EncryptedTextField(BaseEncryptedField):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return 'TextField'
def formfield(self, **kwargs):
defaults = {'widget': forms.Textarea}
defaults.update(kwargs)
return super(EncryptedTextField, self).formfield(**defaults)
def south_field_triple(self):
"Returns a suitable description of this field for South."
# We'll just introspect the _actual_ field.
from south.modelsinspector import introspector
field_class = "django.db.models.fields.TextField"
args, kwargs = introspector(self)
# That's our definition!
return (field_class, args, kwargs)
class EncryptedCharField(BaseEncryptedField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
super(EncryptedCharField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return "CharField"
def formfield(self, **kwargs):
defaults = {'max_length': self.max_length}
defaults.update(kwargs)
return super(EncryptedCharField, self).formfield(**defaults)
def south_field_triple(self):
"Returns a suitable description of this field for South."
# We'll just introspect the _actual_ field.
from south.modelsinspector import introspector
field_class = "django.db.models.fields.CharField"
args, kwargs = introspector(self)
# That's our definition!
return (field_class, args, kwargs)
| orbitvu/django-extensions | django_extensions/db/fields/encrypted.py | Python | mit | 4,102 |
package de.yellow_ray.bluetoothtest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import de.yellow_ray.bluetoothtest.protocol.Package;
public class BluetoothService<T extends BluetoothClient> {
public static final String TAG = "BluetoothService";
public static final int MESSAGE_DISCONNECTED = 0;
public static final int MESSAGE_CONNECTING = 1;
public static final int MESSAGE_CONNECTING_FAILED = 2;
public static final int MESSAGE_CONNECTED = 3;
private final BluetoothAdapter mBluetoothAdapter;
private final Handler mHandler;
private BluetoothSocket mSocket = null;
private ConnectThread mConnectThread = null;
private TechnoBluetoothClient mClientThread = null;
BluetoothService(final Handler handler) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mHandler = handler;
notifyDisconnected();
}
public void connect(final BluetoothDevice device) {
if (mSocket != null && mSocket.isConnected()) {
closeSocket();
}
notifyConnecting(device);
mConnectThread = new ConnectThread(device);
mConnectThread.start();
}
public void disconnect() {
closeSocket();
}
public void sendPackage(Package pkg) {
if (mClientThread != null) {
mClientThread.sendPackage(pkg);
}
}
public void setParameter(int id, float value) {
if (mClientThread != null) {
mClientThread.setParameter(id, value);
}
}
private void notifyDisconnected() {
notifyDisconnected("");
}
private void notifyDisconnected(final String reason) {
Message msg = mHandler.obtainMessage(MESSAGE_DISCONNECTED);
Bundle bundle = new Bundle();
bundle.putString("reason", reason);
msg.setData(bundle);
msg.sendToTarget();
}
private void notifyConnecting(final BluetoothDevice device) {
Message msg = mHandler.obtainMessage(MESSAGE_CONNECTING);
Bundle bundle = new Bundle();
bundle.putParcelable("device", device);
msg.setData(bundle);
msg.sendToTarget();
}
private void notifyConnectingFailed(final BluetoothDevice device, final String reason) {
Message msg = mHandler.obtainMessage(MESSAGE_CONNECTING_FAILED);
Bundle bundle = new Bundle();
bundle.putParcelable("device", device);
bundle.putString("reason", reason);
msg.setData(bundle);
msg.sendToTarget();
}
private void notifyConnected(final BluetoothDevice device) {
Message msg = mHandler.obtainMessage(MESSAGE_CONNECTED);
Bundle bundle = new Bundle();
bundle.putParcelable("device", device);
msg.setData(bundle);
msg.sendToTarget();
}
public void closeSocketAfterError(final String reason) {
try {
if (mSocket != null) {
mSocket.close();
}
notifyDisconnected(reason);
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
notifyDisconnected("Could not close the client socket: " + e.toString());
}
}
private void closeSocket() {
try {
try {
if (mClientThread != null) {
mClientThread.stopClient();
mClientThread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (mSocket != null) {
mSocket.close();
notifyDisconnected();
}
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
notifyDisconnected("Could not close the client socket: " + e.toString());
}
}
private void handleConnection(final BluetoothSocket socket) {
try {
InputStream input = mSocket.getInputStream();
OutputStream output = mSocket.getOutputStream();
mClientThread = new TechnoBluetoothClient(this, mHandler, input, output);
mClientThread.start();
notifyConnected(socket.getRemoteDevice());
} catch (IOException e) {
Log.w(TAG, e);
notifyConnectingFailed(socket.getRemoteDevice(), e.toString());
closeSocket();
}
}
private class ConnectThread extends Thread {
private BluetoothDevice mDevice = null;
public ConnectThread(BluetoothDevice device) {
mDevice = device;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
mBluetoothAdapter.cancelDiscovery();
try {
mSocket = mDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
notifyConnectingFailed(mDevice, e.toString());
closeSocket();
return;
}
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
Log.w(TAG, "Unable to connect!");
Log.w(TAG, connectException);
try {
Class<?> clazz = mSocket.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[]{Integer.valueOf(1)};
mSocket = (BluetoothSocket) m.invoke(mSocket.getRemoteDevice(), params);
mSocket.connect();
} catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
Log.w(TAG, e);
notifyConnectingFailed(mDevice, e.toString());
closeSocket();
return;
}
}
handleConnection(mSocket);
}
}
}
| m0r13/technoqualle-android | app/src/main/java/de/yellow_ray/bluetoothtest/BluetoothService.java | Java | mit | 6,754 |
/* eslint-disable no-console */
const path = require('path');
const { promisify } = require('util');
const render = require('koa-ejs');
const helmet = require('helmet');
const { Provider } = require('../lib'); // require('oidc-provider');
const Account = require('./support/account');
const configuration = require('./support/configuration');
const routes = require('./routes/koa');
const { PORT = 3000, ISSUER = `http://localhost:${PORT}` } = process.env;
configuration.findAccount = Account.findAccount;
let server;
(async () => {
let adapter;
if (process.env.MONGODB_URI) {
adapter = require('./adapters/mongodb'); // eslint-disable-line global-require
await adapter.connect();
}
const prod = process.env.NODE_ENV === 'production';
const provider = new Provider(ISSUER, { adapter, ...configuration });
const directives = helmet.contentSecurityPolicy.getDefaultDirectives();
delete directives['form-action'];
const pHelmet = promisify(helmet({
contentSecurityPolicy: {
useDefaults: false,
directives,
},
}));
provider.use(async (ctx, next) => {
const origSecure = ctx.req.secure;
ctx.req.secure = ctx.request.secure;
await pHelmet(ctx.req, ctx.res);
ctx.req.secure = origSecure;
return next();
});
if (prod) {
provider.proxy = true;
provider.use(async (ctx, next) => {
if (ctx.secure) {
await next();
} else if (ctx.method === 'GET' || ctx.method === 'HEAD') {
ctx.status = 303;
ctx.redirect(ctx.href.replace(/^http:\/\//i, 'https://'));
} else {
ctx.body = {
error: 'invalid_request',
error_description: 'do yourself a favor and only use https',
};
ctx.status = 400;
}
});
}
render(provider.app, {
cache: false,
viewExt: 'ejs',
layout: '_layout',
root: path.join(__dirname, 'views'),
});
provider.use(routes(provider).routes());
server = provider.listen(PORT, () => {
console.log(`application is listening on port ${PORT}, check its /.well-known/openid-configuration`);
});
})().catch((err) => {
if (server && server.listening) server.close();
console.error(err);
process.exitCode = 1;
});
| panva/node-oidc-provider | example/standalone.js | JavaScript | mit | 2,219 |
package com.instructure.canvasapi.api;
import com.instructure.canvasapi.model.CanvasContext;
import com.instructure.canvasapi.model.NotificationPreferenceResponse;
import com.instructure.canvasapi.utilities.APIHelpers;
import com.instructure.canvasapi.utilities.CanvasCallback;
import com.instructure.canvasapi.utilities.CanvasRestAdapter;
import java.util.ArrayList;
import retrofit.RestAdapter;
import retrofit.http.GET;
import retrofit.http.PUT;
import retrofit.http.Path;
import retrofit.http.Query;
public class NotificationPreferencesAPI {
//Frequency keys
public static final String IMMEDIATELY = "immediately";
public static final String DAILY = "daily";
public static final String WEEKLY = "weekly";
public static final String NEVER = "never";
public interface NotificationPreferencesInterface {
@GET("/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences")
void getNotificationPreferences(@Path("user_id") long userId, @Path("communication_channel_id") long communicationChannelId, CanvasCallback<NotificationPreferenceResponse> callback);
@GET("/users/{user_id}/communication_channels/{type}/{address}/notification_preferences")
void getNotificationPreferencesForType(@Path("user_id") long userId, @Path("type") String type, @Path("address") String address, CanvasCallback<NotificationPreferenceResponse> callback);
@GET("/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences/{notification}")
void getSingleNotificationPreference(@Path("user_id") long userId, @Path("communication_channel_id") long communicationChannelId, @Path("notification") String notification, CanvasCallback<NotificationPreferenceResponse> callback);
@GET("/users/{user_id}/communication_channels/{type}/{address}/notification_preferences/{notification}")
void getSingleNotificationPreferencesForType(@Path("user_id") long userId, @Path("type") String type, @Path("address") String address, @Path("notification") String notification, CanvasCallback<NotificationPreferenceResponse> callback);
@PUT("/users/self/communication_channels/{communication_channel_id}/notification_preferences/{notification}")
void updateSingleNotificationPreference(@Path("communication_channel_id") long communicationChannelId, @Path("notification") String notification, CanvasCallback<NotificationPreferenceResponse> callback);
@PUT("/users/self/communication_channels/{type}/{address}/notification_preferences/{notification}")
void updateSingleNotificationPreferenceForType(@Path("type") String type, @Path("address") String address, @Path("notification") String notification, CanvasCallback<NotificationPreferenceResponse> callback);
@PUT("/users/self/communication_channels/{communication_channel_id}/notification_preferences{notification_preferences}")
void updateMultipleNotificationPreferences(@Path("communication_channel_id") long communicationChannelId, @Path(value = "notification_preferences", encode = false) String notifications, CanvasCallback<NotificationPreferenceResponse> callback);
}
/////////////////////////////////////////////////////////////////////////
// Build Interface Helpers
/////////////////////////////////////////////////////////////////////////
private static NotificationPreferencesInterface buildInterface(CanvasCallback<?> callback, CanvasContext canvasContext) {
RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(callback, canvasContext, false);
return restAdapter.create(NotificationPreferencesInterface.class);
}
public static void getNotificationPreferences(final long userId, final long communicationChannelId, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).getNotificationPreferences(userId, communicationChannelId, callback);
}
public static void getNotificationPreferencesByType(final long userId, final String type, final String address, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).getNotificationPreferencesForType(userId, type, address, callback);
}
public static void getSingleNotificationPreference(final long userId, final long communicationChannelId, final String notification, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).getSingleNotificationPreference(userId, communicationChannelId, notification, callback);
}
public static void getSingleNotificationPreferencesForType(final long userId, final String type, final String address, final String notification, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).getSingleNotificationPreferencesForType(userId, type, address, notification, callback);
}
public static void updateSingleNotificationPreference(final long communicationChannelId, final String notification, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).updateSingleNotificationPreference(communicationChannelId, notification, callback);
}
public static void updateSingleNotificationPreferenceForType(final String type, final String address, final String notification, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).updateSingleNotificationPreferenceForType(type, address, notification, callback);
}
public static void updateMultipleNotificationPreferences(final long communicationChannelId, final ArrayList<String> notifications, final String frequency, final CanvasCallback<NotificationPreferenceResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
buildInterface(callback, null).updateMultipleNotificationPreferences(communicationChannelId, buildNotificationPreferenceList(notifications, frequency), callback);
}
private static String buildNotificationPreferenceList(ArrayList<String> notifications, String frequency) {
StringBuilder builder = new StringBuilder();
builder.append("?");
for(String preference : notifications) {
builder.append("notification_preferences");
builder.append("[");
builder.append(preference);
builder.append("]");
builder.append("[frequency]");
builder.append("=");
builder.append(frequency);
builder.append("&");
}
String notificationsString = builder.toString();
if(notificationsString.endsWith("&")) {
notificationsString = notificationsString.substring(0, notificationsString.length() - 1);
}
return notificationsString;
}
}
| nbutton23/CanvasAPI | src/main/java/com/instructure/canvasapi/api/NotificationPreferencesAPI.java | Java | mit | 7,235 |
// All symbols in the Vertical Forms block as per Unicode v8.0.0:
[
'\uFE10',
'\uFE11',
'\uFE12',
'\uFE13',
'\uFE14',
'\uFE15',
'\uFE16',
'\uFE17',
'\uFE18',
'\uFE19',
'\uFE1A',
'\uFE1B',
'\uFE1C',
'\uFE1D',
'\uFE1E',
'\uFE1F'
]; | mathiasbynens/unicode-data | 8.0.0/blocks/Vertical-Forms-symbols.js | JavaScript | mit | 245 |
require 'erb'
require 'tilt'
require 'rack/mime'
class MailView
autoload :Mapper, 'mail_view/mapper'
class << self
def default_email_template_path
File.expand_path('../mail_view/email.html.erb', __FILE__)
end
def default_index_template_path
File.expand_path('../mail_view/index.html.erb', __FILE__)
end
def call(env)
new.call(env)
end
end
def call(env)
@rack_env = env
path_info = env["PATH_INFO"]
if path_info == "" || path_info == "/"
links = self.actions.map do |action|
[action, "#{env["SCRIPT_NAME"]}/#{action}"]
end
ok index_template.render(Object.new, :links => links)
elsif path_info =~ /([\w_]+)(\.\w+)?$/
name = $1
format = $2 || ".html"
if actions.include?(name)
ok render_mail(name, send(name), format)
else
not_found
end
else
not_found(true)
end
end
protected
def actions
public_methods(false).map(&:to_s) - ['call']
end
def email_template
Tilt.new(email_template_path)
end
def email_template_path
self.class.default_email_template_path
end
def index_template
Tilt.new(index_template_path)
end
def index_template_path
self.class.default_index_template_path
end
private
def ok(body)
[200, {"Content-Type" => "text/html"}, [body]]
end
def not_found(pass = false)
if pass
[404, {"Content-Type" => "text/html", "X-Cascade" => "pass"}, ["Not Found"]]
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
end
def render_mail(name, mail, format = nil)
body_part = mail
if mail.multipart?
content_type = Rack::Mime.mime_type(format)
body_part = mail.parts.find { |part| part.content_type.match(content_type) } || mail.parts.first
end
email_template.render(Object.new, :name => name, :mail => mail, :body_part => body_part)
end
end
| WindStill/mail_view | lib/mail_view.rb | Ruby | mit | 1,999 |
const LOAD = 'lance-web/serviceTypes/LOAD';
const LOAD_SUCCESS = 'lance-web/serviceTypes/LOAD_SUCCESS';
const LOAD_FAIL = 'lance-web/serviceTypes/LOAD_FAIL';
const EDIT_START = 'lance-web/serviceTypes/EDIT_START';
const EDIT_STOP = 'lance-web/serviceTypes/EDIT_STOP';
const SAVE = 'lance-web/serviceTypes/SAVE';
const SAVE_SUCCESS = 'lance-web/serviceTypes/SAVE_SUCCESS';
const SAVE_FAIL = 'lance-web/serviceTypes/SAVE_FAIL';
const REMOVE = 'lance-web/serviceTypes/REMOVE';
const REMOVE_SUCCESS = 'lance-web/serviceTypes/REMOVE_SUCCESS';
const REMOVE_FAIL = 'lance-web/serviceTypes/REMOVE_FAIL';
const CLEAR_ERRORS = 'lance-web/serviceTypes/CLEAR_ERRORS';
const initialState = {
loaded: false,
editing: {},
saveError: {}
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case LOAD:
return {
...state,
loading: true
};
case LOAD_SUCCESS:
return {
...state,
loading: false,
loaded: true,
data: action.result.serviceTypes,
error: null
};
case LOAD_FAIL:
return {
...state,
loading: false,
loaded: false,
data: null,
error: action.error
};
case EDIT_START:
return {
...state,
editing: {
...state.editing,
[action.id]: true
}
};
case EDIT_STOP:
return {
...state,
editing: {
...state.editing,
[action.id]: false
}
};
case SAVE:
return {
...state,
loading: true,
error: null
};
case SAVE_SUCCESS:
return {
...state,
data: [...state.data, action.result.serviceType],
loading: false,
error: null
};
case SAVE_FAIL:
return {
...state,
loading: false,
error: action.error
};
case REMOVE:
return {
...state,
loading: true,
error: null
};
case REMOVE_SUCCESS:
let idx;
for (let jdx = 0; jdx < state.data.length; jdx++) {
if (state.data[jdx].id === action.id) {
idx = jdx;
}
}
return {
...state,
data: [
...state.data.slice(0, idx),
...state.data.slice(idx + 1)],
loading: false,
error: null
};
case REMOVE_FAIL:
return {
...state,
loading: false,
error: action.error
};
case CLEAR_ERRORS:
return {
...state,
error: null
};
default:
return state;
}
}
export function isLoaded(globalState) {
return globalState.serviceTypes && globalState.serviceTypes.loaded;
}
export function filter(term) {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client) => client.post('/serviceType/filter/', {data: {title: term}}) // params not used, just shown as demonstration
};
}
export function load() {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client) => client.get('/serviceType/load') // params not used, just shown as demonstration
};
}
export function save(serviceType) {
return {
types: [SAVE, SAVE_SUCCESS, SAVE_FAIL],
id: serviceType.id,
promise: (client) => client.post('/serviceType/save', {
data: serviceType
})
};
}
export function remove(id) {
return {
types: [REMOVE, REMOVE_SUCCESS, REMOVE_FAIL],
id: id,
promise: (client) => client.post('/serviceType/remove', {data: {id: id}})
};
}
export function clearErrors() {
return {
type: CLEAR_ERRORS
};
}
export function editStart(id) {
return { type: EDIT_START, id };
}
export function editStop(id) {
return { type: EDIT_STOP, id };
}
| jairoandre/lance-web-hot | src/redux/modules/serviceTypes.js | JavaScript | mit | 3,767 |