repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
ejchristie/ejchristie.github.io | src/app/blog/blog-archive/blog-archive.component.ts | 676 | import { Component, OnInit } from '@angular/core';
// import { TreeModule, TreeNode } from "primeng/primeng";
import { BlogPostService } from '../shared/blog-post.service';
import { BlogPostDetails } from '../shared/blog-post.model';
@Component({
selector: 'ejc-blog-archive',
templateUrl: './blog-archive.component.html',
styleUrls: ['./blog-archive.component.scss']
})
export class BlogArchiveComponent implements OnInit {
constructor(
// private postService: BlogPostService
) { }
ngOnInit() {
}
// // it would be best if the data in the blog post details file was already organized into tree nodes
// private buildTreeNodes(): TreeNode[] {}
}
| mit |
sinsoku/banana | lib/banana/migration.rb | 462 | require 'active_record'
module ActiveRecord
class Migration
def migrate_with_multidb(direction)
if defined? self.class::DATABASE_NAME
ActiveRecord::Base.establish_connection(self.class::DATABASE_NAME.to_sym)
migrate_without_multidb(direction)
ActiveRecord::Base.establish_connection(Rails.env.to_sym)
else
migrate_without_multidb(direction)
end
end
alias_method_chain :migrate, :multidb
end
end
| mit |
PeculiarVentures/pvpkcs11 | test/config.js | 742 | const os = require("os");
const fs = require("fs");
const config = {
}
let libs;
switch (os.platform()) {
case "darwin": {
libs = [
"out/Debug_x64/libpvpkcs11.dylib",
"out/Debug/libpvpkcs11.dylib",
"out/Release_x64/libpvpkcs11.dylib",
"out/Release/libpvpkcs11.dylib",
];
break;
}
case "win32": {
libs = [
"out/Debug_x64/pvpkcs11.dll",
"out/Debug/pvpkcs11.dll",
"out/Release_x64/pvpkcs11.dll",
"out/Release/pvpkcs11.dll",
];
break;
}
default:
throw new Error("Cannot get pvpkcs11 compiled library. Unsupported OS");
}
config.lib = libs.find(o => fs.existsSync(o));
if (!config.lib) {
throw new Error("config.lib is empty");
}
module.exports = config; | mit |
miljinx/helpdo-api | db/migrate/20170613234831_rename_members.rb | 114 | class RenameMembers < ActiveRecord::Migration[5.1]
def change
rename_table :members, :memberships
end
end
| mit |
alvachien/achihapi | test/hihapi.test/UnitTests/Finance/Config/FinanceDocumentTypesControllerTest.cs | 4350 | using System;
using Xunit;
using System.Linq;
using hihapi.Models;
using hihapi.Controllers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.OData.Results;
using hihapi.test.common;
namespace hihapi.unittest.Finance
{
[Collection("HIHAPI_UnitTests#1")]
public class FinanceDocumentTypesControllerTest
{
private SqliteDatabaseFixture fixture = null;
public FinanceDocumentTypesControllerTest(SqliteDatabaseFixture fixture)
{
this.fixture = fixture;
}
[Theory]
[InlineData("")]
[InlineData(DataSetupUtility.UserA)]
public async Task TestCase_Read(string strusr)
{
var context = fixture.GetCurrentDataContext();
// 1. Read it without User assignment
var control = new FinanceDocumentTypesController(context);
if (String.IsNullOrEmpty(strusr))
{
var userclaim = DataSetupUtility.GetClaimForUser(strusr);
control.ControllerContext = new ControllerContext()
{
HttpContext = new DefaultHttpContext() { User = userclaim }
};
}
var getresult = control.Get();
Assert.NotNull(getresult);
var getokresult = Assert.IsType<OkObjectResult>(getresult);
var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value);
Assert.NotNull(getqueryresult);
if (String.IsNullOrEmpty(strusr))
{
var dbcategories = (from tt in context.FinDocumentTypes
where tt.HomeID == null
select tt).ToList<FinanceDocumentType>();
Assert.Equal(dbcategories.Count, getqueryresult.Count());
}
await context.DisposeAsync();
}
[Theory]
[InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, "Test 1")]
[InlineData(DataSetupUtility.UserB, DataSetupUtility.Home2ID, "Test 2")]
public async Task TestCase_CRUD(string currentUser, int hid, string name)
{
var context = fixture.GetCurrentDataContext();
// 1. Read it out before insert.
var control = new FinanceDocumentTypesController(context);
var userclaim = DataSetupUtility.GetClaimForUser(currentUser);
control.ControllerContext = new ControllerContext()
{
HttpContext = new DefaultHttpContext() { User = userclaim }
};
var getresult = control.Get();
Assert.NotNull(getresult);
var getokresult = Assert.IsType<OkObjectResult>(getresult);
var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value);
Assert.NotNull(getqueryresult);
// 2. Insert a new one.
FinanceDocumentType ctgy = new FinanceDocumentType();
ctgy.HomeID = hid;
ctgy.Name = name;
ctgy.Comment = name;
var postresult = await control.Post(ctgy);
var createdResult = Assert.IsType<CreatedODataResult<FinanceDocumentType>>(postresult);
Assert.NotNull(createdResult);
short nctgyid = createdResult.Entity.ID;
Assert.Equal(hid, createdResult.Entity.HomeID);
Assert.Equal(ctgy.Name, createdResult.Entity.Name);
Assert.Equal(ctgy.Comment, createdResult.Entity.Comment);
// 3. Read it out
var getsingleresult = control.Get(nctgyid);
Assert.NotNull(getsingleresult);
var getctgy = Assert.IsType<FinanceDocumentType>(getsingleresult);
Assert.Equal(hid, getctgy.HomeID);
Assert.Equal(ctgy.Name, getctgy.Name);
Assert.Equal(ctgy.Comment, getctgy.Comment);
// 4. Change it
getctgy.Comment += "Changed";
var putresult = control.Put(nctgyid, getctgy);
Assert.NotNull(putresult);
// 5. Delete it
var deleteresult = control.Delete(nctgyid);
Assert.NotNull(deleteresult);
await context.DisposeAsync();
}
}
}
| mit |
eazulay/mantis | signup.php | 2896 | <?php
# MantisBT - a php based bugtracking system
# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* @package MantisBT
* @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - [email protected]
* @copyright Copyright (C) 2002 - 2011 MantisBT Team - [email protected]
* @link http://www.mantisbt.org
*/
/**
* MantisBT Core API's
*/
require_once( 'core.php' );
require_once( 'email_api.php' );
form_security_validate( 'signup' );
$f_username = strip_tags( gpc_get_string( 'username' ) );
$f_email = strip_tags( gpc_get_string( 'email' ) );
$f_captcha = gpc_get_string( 'captcha', '' );
$f_public_key = gpc_get_int( 'public_key', '' );
$f_username = trim( $f_username );
$f_email = email_append_domain( trim( $f_email ) );
$f_captcha = utf8_strtolower( trim( $f_captcha ) );
# force logout on the current user if already authenticated
if( auth_is_user_authenticated() ) {
auth_logout();
}
# Check to see if signup is allowed
if ( OFF == config_get_global( 'allow_signup' ) ) {
print_header_redirect( 'login_page.php' );
exit;
}
if( ON == config_get( 'signup_use_captcha' ) && get_gd_version() > 0 &&
helper_call_custom_function( 'auth_can_change_password', array() ) ) {
# captcha image requires GD library and related option to ON
$t_key = utf8_strtolower( utf8_substr( md5( config_get( 'password_confirm_hash_magic_string' ) . $f_public_key ), 1, 5) );
if ( $t_key != $f_captcha ) {
trigger_error( ERROR_SIGNUP_NOT_MATCHING_CAPTCHA, ERROR );
}
}
email_ensure_not_disposable( $f_email );
# notify the selected group a new user has signed-up
if( user_signup( $f_username, $f_email ) ) {
email_notify_new_account( $f_username, $f_email );
}
form_security_purge( 'signup' );
html_page_top1();
html_page_top2a();
?>
<br />
<div align="center">
<table class="width50" cellspacing="1">
<tr>
<td class="center">
<b><?php echo lang_get( 'signup_done_title' ) ?></b><br />
<?php echo "[$f_username - $f_email] " ?>
</td>
</tr>
<tr>
<td>
<br />
<?php echo lang_get( 'password_emailed_msg' ) ?>
<br /><br />
<?php echo lang_get( 'no_reponse_msg') ?>
<br /><br />
</td>
</tr>
</table>
<br />
<?php print_bracket_link( 'login_page.php', lang_get( 'proceed' ) ); ?>
</div>
<?php
html_page_bottom1a( __FILE__ );
| mit |
bairdj/beveridge | src/scrapy/afltables/afltables/common.py | 1563 | team_mapping = {
"SY": "Sydney",
"WB": "Western Bulldogs",
"WC": "West Coast",
"HW": "Hawthorn",
"GE": "Geelong",
"FR": "Fremantle",
"RI": "Richmond",
"CW": "Collingwood",
"CA": "Carlton",
"GW": "Greater Western Sydney",
"AD": "Adelaide",
"GC": "Gold Coast",
"ES": "Essendon",
"ME": "Melbourne",
"NM": "North Melbourne",
"PA": "Port Adelaide",
"BL": "Brisbane Lions",
"SK": "St Kilda"
}
def get_team_name(code):
return team_mapping[code]
def get_team_code(full_name):
for code, name in team_mapping.items():
if name == full_name:
return code
return full_name
def get_match_description(response):
match_container = response.xpath("//td[@colspan = '5' and @align = 'center']")[0]
match_details = match_container.xpath(".//text()").extract()
return {
"round": match_details[1],
"venue": match_details[3],
"date": match_details[6],
"attendance": match_details[8],
"homeTeam": response.xpath("(//a[contains(@href, 'teams/')])[1]/text()").extract_first(),
"awayTeam": response.xpath("(//a[contains(@href, 'teams/')])[2]/text()").extract_first(),
"homeScore": int(response.xpath("//table[1]/tr[2]/td[5]/b/text()").extract_first()),
"awayScore": int(response.xpath("//table[1]/tr[3]/td[5]/b/text()").extract_first())
}
def get_match_urls(response):
for match in response.xpath("//a[contains(@href, 'stats/games/')]/@href").extract():
yield response.urljoin(match) | mit |
SlipknotTN/Dogs-Vs-Cats-Playground | deep_learning/keras/lib/preprocess/preprocess.py | 511 | from keras.applications import imagenet_utils
from keras.applications import mobilenet
def dummyPreprocessInput(image):
image -= 127.5
return image
def getPreprocessFunction(preprocessType):
if preprocessType == "dummy":
return dummyPreprocessInput
elif preprocessType == "mobilenet":
return mobilenet.preprocess_input
elif preprocessType == "imagenet":
return imagenet_utils.preprocess_input
else:
raise Exception(preprocessType + " not supported")
| mit |
teerachail/SoapWithAttachments | JavaWsBinding/TheS.ServiceModel/_Runtime/CallbackException.cs | 874 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace TheS.Runtime
{
internal class CallbackException : FatalException
{
public CallbackException()
{
}
public CallbackException(string message, Exception innerException) : base(message, innerException)
{
// This can't throw something like ArgumentException because that would be worse than
// throwing the callback exception that was requested.
Fx.Assert(innerException != null, "CallbackException requires an inner exception.");
Fx.Assert(!Fx.IsFatal(innerException), "CallbackException can't be used to wrap fatal exceptions.");
}
}
}
| mit |
michaelst/ci | app/Http/Controllers/DashboardController.php | 2283 | <?php
namespace App\Http\Controllers;
use App\Jobs\GetInstance;
use App\Models\Build;
use App\Models\Commit;
use App\Models\Repository;
use App\RepositoryProviders\GitHub;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller
{
public function index()
{
$repositories = Repository::all();
$commits = Commit::select('branch', DB::raw('max(created_at) as created_at'))
->orderBy('created_at', 'desc')
->groupBy('branch')
->get();
$masterInfo = Commit::getBranchInfo('master');
$branches = [];
foreach ($commits as $commit) {
$info = Commit::getBranchInfo($commit->branch);
$branches[] = [
'branch' => $commit->branch,
'status' => $info['status'],
'label' => $info['label'],
'last_commit_id' => $info['last_commit_id'],
];
}
return view('dashboard', compact('repositories', 'branches', 'masterInfo'));
}
public function build(Commit $commit, $attempt = null)
{
$count = Build::where(['commit_id' => $commit->id])->count();
$query = Build::where(['commit_id' => $commit->id])
->orderBy('attempt', 'desc');
if ($attempt) {
$query->where(['attempt' => $attempt]);
}
$build = $query->first();
$logs = json_decode($build->log, true);
$next = $build->attempt < $count ? "/build/$build->id/" . ($build->attempt + 1) : null;
return view('build', compact('build', 'commit', 'attempt', 'logs', 'count', 'next'));
}
public function rebuild(Build $build)
{
$rebuild = new Build();
$rebuild->commit_id = $build->commit_id;
$rebuild->attempt = $build->attempt + 1;
$rebuild->status = 'QUEUED';
$rebuild->save();
$github = new GitHub(
$rebuild->commit->repository->name,
$rebuild->commit->commit_id,
env('PROJECT_URL') . '/build/' . $rebuild->commit_id
);
$github->notifyPendingBuild();
dispatch(new GetInstance($rebuild->id));
return redirect("/build/$rebuild->commit_id");
}
}
| mit |
bluebackblue/brownie | source/bsys/opengl/opengl_impl_actionbatching_shader_load.h | 2340 | #pragma once
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief OpenGL。
*/
/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../types/types.h"
#pragma warning(pop)
/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../actionbatching/actionbatching.h"
#pragma warning(pop)
/** include
*/
#include "./opengl_impl.h"
#include "./opengl_impl_include.h"
/** NBsys::NOpengl
*/
#if(BSYS_OPENGL_ENABLE)
#pragma warning(push)
#pragma warning(disable:4710)
namespace NBsys{namespace NOpengl
{
/** バーテックスバッファ作成。
*/
class Opengl_Impl_ActionBatching_Shader_Load : public NBsys::NActionBatching::ActionBatching_ActionItem_Base
{
private:
/** opengl_impl
*/
Opengl_Impl& opengl_impl;
/** shaderlayout
*/
sharedptr<Opengl_ShaderLayout> shaderlayout;
/** asyncresult
*/
AsyncResult<bool> asyncresult;
public:
/** constructor
*/
Opengl_Impl_ActionBatching_Shader_Load(Opengl_Impl& a_opengl_impl,const sharedptr<Opengl_ShaderLayout>& a_shaderlayout,AsyncResult<bool>& a_asyncresult)
:
opengl_impl(a_opengl_impl),
shaderlayout(a_shaderlayout),
asyncresult(a_asyncresult)
{
}
/** destructor
*/
virtual ~Opengl_Impl_ActionBatching_Shader_Load()
{
}
private:
/** copy constructor禁止。
*/
Opengl_Impl_ActionBatching_Shader_Load(const Opengl_Impl_ActionBatching_Shader_Load& a_this) = delete;
/** コピー禁止。
*/
void operator =(const Opengl_Impl_ActionBatching_Shader_Load& a_this) = delete;
public:
/** アクション開始。
*/
virtual void Start()
{
}
/** アクション中。
*/
virtual s32 Do(f32& a_delta,bool a_endrequest)
{
if(a_endrequest == true){
//中断。
}
if(this->shaderlayout->IsBusy() == true){
//継続。
a_delta -= 1.0f;
return 0;
}
//Render_LoadShader
this->opengl_impl.Render_LoadShader(this->shaderlayout);
//asyncresult
this->asyncresult.Set(true);
//成功。
return 1;
}
};
}}
#pragma warning(pop)
#endif
| mit |
marius1092/test | vendor/bundles/Vich/UploaderBundle/Mapping/PropertyMapping.php | 4671 | <?php
namespace Vich\UploaderBundle\Mapping;
use Vich\UploaderBundle\Naming\NamerInterface;
/**
* PropertyMapping.
*
* @author Dustin Dobervich <[email protected]>
*/
class PropertyMapping
{
/**
* @var \ReflectionProperty $property
*/
protected $property;
/**
* @var \ReflectionProperty $fileNameProperty
*/
protected $fileNameProperty;
/**
* @var NamerInterface $namer
*/
protected $namer;
/**
* @var array $mapping
*/
protected $mapping;
/**
* @var string $mappingName
*/
protected $mappingName;
/**
* Gets the reflection property that represents the
* annotated property.
*
* @return \ReflectionProperty The property.
*/
public function getProperty()
{
return $this->property;
}
/**
* Sets the reflection property that represents the annotated
* property.
*
* @param \ReflectionProperty $property The reflection property.
*/
public function setProperty(\ReflectionProperty $property)
{
$this->property = $property;
$this->property->setAccessible(true);
}
/**
* Gets the reflection property that represents the property
* which holds the file name for the mapping.
*
* @return \ReflectionProperty The reflection property.
*/
public function getFileNameProperty()
{
return $this->fileNameProperty;
}
/**
* Sets the reflection property that represents the property
* which holds the file name for the mapping.
*
* @param \ReflectionProperty $fileNameProperty The reflection property.
*/
public function setFileNameProperty(\ReflectionProperty $fileNameProperty)
{
$this->fileNameProperty = $fileNameProperty;
$this->fileNameProperty->setAccessible(true);
}
/**
* Gets the configured namer.
*
* @return null|NamerInterface The namer.
*/
public function getNamer()
{
return $this->namer;
}
/**
* Sets the namer.
*
* @param \Vich\UploaderBundle\Naming\NamerInterface $namer The namer.
*/
public function setNamer(NamerInterface $namer)
{
$this->namer = $namer;
}
/**
* Determines if the mapping has a custom namer configured.
*
* @return bool True if has namer, false otherwise.
*/
public function hasNamer()
{
return null !== $this->namer;
}
/**
* Sets the configured configuration mapping.
*
* @param array $mapping The mapping;
*/
public function setMapping(array $mapping)
{
$this->mapping = $mapping;
}
/**
* Gets the configured configuration mapping name.
*
* @return string The mapping name.
*/
public function getMappingName()
{
return $this->mappingName;
}
/**
* Sets the configured configuration mapping name.
*
* @param $mappingName The mapping name.
*/
public function setMappingName($mappingName)
{
$this->mappingName = $mappingName;
}
/**
* Gets the name of the annotated property.
*
* @return string The name.
*/
public function getPropertyName()
{
return $this->property->getName();
}
/**
* Gets the value of the annotated property.
*
* @param object $obj The object.
* @return UploadedFile The file.
*/
public function getPropertyValue($obj)
{
return $this->property->getValue($obj);
}
/**
* Gets the configured file name property name.
*
* @return string The name.
*/
public function getFileNamePropertyName()
{
return $this->fileNameProperty->getName();
}
/**
* Gets the configured upload directory.
*
* @return string The configured upload directory.
*/
public function getUploadDir()
{
return $this->mapping['upload_dir'];
}
/**
* Determines if the file should be deleted upon removal of the
* entity.
*
* @return bool True if delete on remove, false otherwise.
*/
public function getDeleteOnRemove()
{
return $this->mapping['delete_on_remove'];
}
/**
* Determines if the uploadable field should be injected with a
* Symfony\Component\HttpFoundation\File\File instance when
* the object is loaded from the datastore.
*
* @return bool True if the field should be injected, false otherwise.
*/
public function getInjectOnLoad()
{
return $this->mapping['inject_on_load'];
}
}
| mit |
cheney247689848/Cloud-edge | Assets/Script_Lua/scene/L_StatePublic.lua | 2033 | -------------------------------------------------------------------
-- The Long night
-- The night gives me black eyes, but I use it to find the light.
-- In 2017
-- 公共状态
-------------------------------------------------------------------
L_StatePublic = {}
setmetatable(L_StatePublic, {__index = _G})
local _this = L_StatePublic
_this.stateNone = function (o , eNtity)
local state = L_State.New(o , eNtity)
function state:Enter()
print("------进入None状态------")
end
function state:Execute(nTime)
--do thing
end
function state:Exit()
print("------退出None状态------")
end
return state
end
_this.stateLoad = function (o , eNtity)
local state = L_State.New(o , eNtity)
function state:Enter()
print("------进入Load状态------")
self.m_nTimer = 0
self.m_nTick = 0
end
function state:Execute(nTime)
--do thing
if 0 == self.m_nTick then
self.m_nTimer = self.m_nTimer + nTime
print(self.m_nTimer)
if self.m_nTimer > 3 then
self.m_eNtity:ChangeToState(self.m_eNtity.stateNone)
end
end
end
function state:Exit()
print("------退出Load状态------")
end
return state
end
_this.stateExit = function (o , eNtity)
local state = L_State.New(o , eNtity)
function state:Enter()
print("------进入Exit状态------")
self.m_nTimer = 0
self.m_nTick = 0
end
function state:Execute(nTime)
--do thing
if 0 == self.m_nTick then
self.m_nTimer = self.m_nTimer + nTime
print(self.m_nTimer)
if self.m_nTimer > 3 then
self.m_eNtity:ChangeToState(self.m_eNtity.stateNone)
end
end
end
function state:Exit()
print("------退出Exit状态------")
end
return state
end
| mit |
simonmysun/praxis | TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/287e3522261d64438d0e0f0d0ab25b1bbc0d4b902207719bf1a7761ee019b24a.html | 550 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./ed6c3fe87a92e6b0939903db98d3209d32dcf2e96bee3586c1c6da3985c58ae4.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | mit |
tanishq-dubey/personalprojects | README.md | 1102 | personalprojects
================
A bunch of little things I made in my freetime
### PyPong
A simple pong game made in Python and Pygame.
**Changes Made**: Made the AI a bit (a lot) worse, you can actually win now.
### Maze Runner
A maze app that uses Deep Field Search (DFS) to make a perfect maze and then uses the same algorithm in reverse to solve. Requires PyGame.
**Usage**: Run it, enter your resolution, and let it run! Press "Escape" at anytime to quit.
**Changes Made**: Exits more elegantly, colors are more visible.
### Find the Cow
A joke of a game inspired by a conversation at dinner with friends. I challenged myself to keep it under 100 lines of code. Requires PyGame.
**Usage**: Click to guess where the cow is. The volume of the "moo" indicates how far away the cow is. Once the cow is found, press spacebar to go to the next level.
**ToDo**: Add a menu, although, I want to keep this under 100 lines of code.
### Binary Clock
Something I thought I would finish, but never had the initative. It was supposed to be a simple 5 row binary clock. Maybe someday it will get a life.
| mit |
zcoinofficial/zcoin | src/elysium/sigmawalletv0.h | 1664 | // Copyright (c) 2020 The Firo Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef FIRO_ELYSIUM_SIGMAWALLETV0_H
#define FIRO_ELYSIUM_SIGMAWALLETV0_H
#include "sigmawallet.h"
namespace elysium {
class SigmaWalletV0 : public SigmaWallet
{
public:
SigmaWalletV0();
protected:
uint32_t BIP44ChangeIndex() const;
SigmaPrivateKey GeneratePrivateKey(uint512 const &seed);
class Database : public SigmaWallet::Database {
public:
Database();
public:
bool WriteMint(SigmaMintId const &id, SigmaMint const &mint, CWalletDB *db = nullptr);
bool ReadMint(SigmaMintId const &id, SigmaMint &mint, CWalletDB *db = nullptr) const;
bool EraseMint(SigmaMintId const &id, CWalletDB *db = nullptr);
bool HasMint(SigmaMintId const &id, CWalletDB *db = nullptr) const;
bool WriteMintId(uint160 const &hash, SigmaMintId const &mintId, CWalletDB *db = nullptr);
bool ReadMintId(uint160 const &hash, SigmaMintId &mintId, CWalletDB *db = nullptr) const;
bool EraseMintId(uint160 const &hash, CWalletDB *db = nullptr);
bool HasMintId(uint160 const &hash, CWalletDB *db = nullptr) const;
bool WriteMintPool(std::vector<MintPoolEntry> const &mints, CWalletDB *db = nullptr);
bool ReadMintPool(std::vector<MintPoolEntry> &mints, CWalletDB *db = nullptr);
void ListMints(std::function<void(SigmaMintId&, SigmaMint&)> const&, CWalletDB *db = nullptr);
};
public:
using SigmaWallet::GeneratePrivateKey;
};
}
#endif // FIRO_ELYSIUM_SIGMAWALLETV0_H | mit |
milesj/gears | docs/usage.md | 6088 | # Gears #
*Documentation may be outdated or incomplete as some URLs may no longer exist.*
*Warning! This codebase is deprecated and will no longer receive support; excluding critical issues.*
A PHP class that loads template files, binds variables to a single file or globally without the need for custom placeholders/variables, allows for parent-child hierarchy and parses the template structure.
Gear is a play on words for: Engine + Gears + Structure.
* Loads any type of file into the system
* Binds variables to a single file or to all files globally
* Template files DO NOT need custom markup and placeholders for variables
* Can access and use variables in a template just as you would a PHP file
* Allows for parent-child hierarchy
* Parse a parent template to parse all children, and their children, and so on
* Can destroy template indexes on the fly
* No eval() or security flaws
* And much more...
## Introduction ##
Most of the template systems today use a very robust setup where the template files contain no server-side code. Instead they use a system where they use custom variables and markup to get the job done. For example, in your template you may have a variable called {pageTitle} and in your code you assign that variable a value of "Welcome". This is all well and good, but to be able to parse this "system", it requires loads of regex and matching/replacing/looping which can be quite slow and cumbersome. It also requires you to learn a new markup language, specific for the system you are using. Why would you want to learn a new markup language and structure simply to do an if statement or go through a loop? In Gears, the goal is to remove all that custom code, separate your markup from your code, allow the use of standard PHP functions, loops, statements, etc within templates, and much more!
## Installation ##
Install by manually downloading the library or defining a [Composer dependency](http://getcomposer.org/).
```javascript
{
"require": {
"mjohnson/gears": "4.0.0"
}
}
```
Once available, instantiate the class and create template files.
```php
// index.php
$temp = new mjohnson\gears\Gears(dirname(__FILE__) . 'templates/');
$temp->setLayout('layouts/default');
// templates/layouts/default.tpl
<!DOCTYPE html>
<html>
<head>
<title><?php echo $pageTitle; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php echo $this->getContent(); ?>
</body>
</html>
```
Within the code block above I am initiating the class by calling `new mjohnson\gears\Gears($path)` (where `$path` is the path to your templates directory) and storing it within a `$temp` variable. Next I am setting the layout I want to use; a layout is the outer HTML that will wrap the inner content pages. Within a layout you can use `getContent()` which will output the inner HTML wherever you please.
## Binding Variables ##
It's now time to bind data to variables within your templates; to do this we use the `bind()` method. The bind method will take an array of key value pairs, or key value arguments.
```php
$temp->bind(array(
'pageTitle' => 'Gears - Template Engine',
'description' => 'A PHP class that loads template files, binds variables, allows for parent-child hierarchy all the while rendering the template structure.'
));
```
The way binding variables works is extremely easy to understand. In the data being binded, the key is the name of the variable within the template, and the value is what the variable will be output. For instance the variable pageTitle (Gears - Template Engine) above will be assigned to the variable `$pageTitle` within the `layouts/default.tpl`.
Variables are binded globally to all templates, includes and the layout.
## Displaying the Templates ##
To render templates, use the `display()` method. The display method takes two arguments, the name of the template you want to display and the key to use for caching.
```php
echo $temp->display('index');
```
The second argument defines the name of the key to use for caching. Generally it will be the same name as the template name, but you do have the option to name it whatever you please.
```php
echo $temp->display('index', 'index');
```
It's also possible to display templates within folders by separating the path with a forward slash.
```php
echo $temp->display('users/login');
```
## Opening a Template ##
To render a template within another template you would use the `open()` method. The `open()` method takes 3 arguments: the path to the template (relative to the templates folder), an array of key value pairs to define as custom scoped variables and an array of cache settings.
```php
echo $this->open('includes/footer', array('date' => date('Y'));
```
By default, includes are not cached but you can enable caching by passing true as the third argument or an array of settings. The viable settings are key and duration, where key is the name of the cached file (usually the path) and duration is the length of the cache.
```php
echo $this->open('includes/footer', array('date' => date('Y')), true);
// Custom settings
echo $this->open('includes/footer', array('date' => date('Y')), array(
'key' => 'cacheKey',
'duration' => '+10 minutes'
));
```
## Caching ##
Gears comes packaged with a basic caching mechanism. By default caching is disabled, but to enable caching you can use `setCaching()`. This method will take the cache location as its 1st argument (best to place it in the same templates folder) and the expiration duration as the 2nd argument (default +1 day).
```php
$temp->setCaching(dirname(__FILE__) . '/templates/cache/');
```
You can customize the duration by using the strtotime() format. You can also pass null as the first argument and the system will place the cache files within your template path.
```php
$temp->setCaching(null, '+15 minutes');
```
To clear all cached files, you can use `flush()`.
```php
$temp->flush();
```
For a better example of how to output cached data, refer to the tests folder within the Gears package.
| mit |
JustinWebb/lightbox-demo | app/js/helpers/view/gallery.js | 3410 | /*
* @Author: justinwebb
* @Date: 2015-09-24 21:08:23
* @Last Modified by: justinwebb
* @Last Modified time: 2015-09-24 22:19:45
*/
(function (window) {
'use strict';
window.JWLB = window.JWLB || {};
window.JWLB.View = window.JWLB.View || {};
//--------------------------------------------------------------------
// Event handling
//--------------------------------------------------------------------
var wallOnClick = function (event) {
if (event.target.tagName.toLowerCase() === 'img') {
var id = event.target.parentNode.dataset.id;
var selectedPhoto = this.photos.filter(function (photo) {
if (photo.id === id) {
photo.portrait.id = id;
return photo;
}
})[0];
this.sendEvent('gallery', selectedPhoto.portrait);
}
};
//--------------------------------------------------------------------
// View overrides
//--------------------------------------------------------------------
var addUIListeners = function () {
this.ui.wall.addEventListener('click', wallOnClick.bind(this));
};
var initUI = function () {
var isUIValid = false;
var comp = document.querySelector(this.selector);
this.ui.wall = comp;
if (this.ui.wall) {
this.reset();
isUIValid = true;
}
return isUIValid;
};
//--------------------------------------------------------------------
// Constructor
//--------------------------------------------------------------------
var Gallery = function (domId) {
// Overriden View class methods
this.initUI = initUI;
this.addUIListeners = addUIListeners;
this.name = 'Gallery';
// Instance properties
this.photos = [];
// Initialize View
JWLB.View.call(this, domId);
};
//--------------------------------------------------------------------
// Inheritance
//--------------------------------------------------------------------
Gallery.prototype = Object.create(JWLB.View.prototype);
Gallery.prototype.constructor = Gallery;
//--------------------------------------------------------------------
// Instance methods
//--------------------------------------------------------------------
Gallery.prototype.addThumb = function (data, id) {
// Store image data for future reference
var photo = {
id: id,
thumb: null,
portrait: data.size[0]
};
data.size.forEach(function (elem) {
if (elem.label === 'Square') {
photo.thumb = elem;
}
if (elem.height > photo.portrait.height) {
photo.portrait = elem;
}
});
this.photos.push(photo);
// Build thumbnail UI
var node = document.createElement('div');
node.setAttribute('data-id', id);
node.setAttribute('class', 'thumb');
var img = document.createElement('img');
img.setAttribute('src', photo.thumb.source);
img.setAttribute('title', 'id: '+ id);
node.appendChild(img);
this.ui.wall.querySelector('article[name=foobar]').appendChild(node);
};
Gallery.prototype.reset = function () {
if (this.ui.wall.children.length > 0) {
var article = this.ui.wall.children.item(0)
article.parentElement.removeChild(article);
}
var article = document.createElement('article');
article.setAttribute('name', 'foobar');
this.ui.wall.appendChild(article);
};
window.JWLB.View.Gallery = Gallery;
})(window);
| mit |
tomas-stefano/infinity_test | lib/infinity_test/core/base.rb | 10064 | module InfinityTest
module Core
class Base
# Specify the Ruby Version Manager to run
cattr_accessor :strategy
# ==== Options
# * :rvm
# * :rbenv
# * :ruby_normal (Use when don't pass any rubies to run)
# * :auto_discover(defaults)
self.strategy = :auto_discover
# Specify Ruby version(s) to test against
#
# ==== Examples
# rubies = %w(ree jruby)
#
cattr_accessor :rubies
self.rubies = []
# Options to include in the command.
#
cattr_accessor :specific_options
self.specific_options = ''
# Test Framework to use Rspec, Bacon, Test::Unit or AutoDiscover(defaults)
# ==== Options
# * :rspec
# * :bacon
# * :test_unit (Test unit here apply to this two libs: test/unit and minitest)
# * :auto_discover(defaults)
#
# This will load a exactly a class constantize by name.
#
cattr_accessor :test_framework
self.test_framework = :auto_discover
# Framework to know the folders and files that need to monitoring by the observer.
#
# ==== Options
# * :rails
# * :rubygems
# * :auto_discover(defaults)
#
# This will load a exactly a class constantize by name.
#
cattr_accessor :framework
self.framework = :auto_discover
# Framework to observer watch the dirs.
#
# ==== Options
# * watchr
#
cattr_accessor :observer
self.observer = :watchr
# Ignore test files.
#
# ==== Examples
# ignore_test_files = [ 'spec/generators/controller_generator_spec.rb' ]
#
cattr_accessor :ignore_test_files
self.ignore_test_files = []
# Ignore test folders.
#
# ==== Examples
# # Imagine that you don't want to run integration specs.
# ignore_test_folders = [ 'spec/integration' ]
#
cattr_accessor :ignore_test_folders
self.ignore_test_folders = []
# Verbose Mode. Print commands before executing them.
#
cattr_accessor :verbose
self.verbose = true
# Set the notification framework to use with Infinity Test.
#
# ==== Options
# * :growl
# * :lib_notify
# * :auto_discover(defaults)
#
# This will load a exactly a class constantize by name.
#
cattr_writer :notifications
self.notifications = :auto_discover
# You can set directory to show images matched by the convention names.
# => http://github.com/tomas-stefano/infinity_test/tree/master/images/ )
#
# Infinity test will work on these names in the notification framework:
#
# * success (png, gif, jpeg)
# * failure (png, gif, jpeg)
# * pending (png, gif, jpeg)
#
cattr_accessor :mode
#
# => This will show images in the folder:
# http://github.com/tomas-stefano/infinity_test/tree/master/images/simpson
#
self.mode = :simpson
# Success Image to show after the tests run.
#
cattr_accessor :success_image
# Pending Image to show after the tests run.
#
cattr_accessor :pending_image
# Failure Image to show after the tests run.
#
cattr_accessor :failure_image
# Use a specific gemset for each ruby.
# OBS.: This only will work for RVM strategy.
#
cattr_accessor :gemset
# InfinityTest try to use bundler if Gemfile is present.
# Set to false if you don't want use bundler.
#
cattr_accessor :bundler
self.bundler = true
# Callbacks accessor to handle before or after all run and for each ruby!
cattr_accessor :callbacks
self.callbacks = []
# Run the observer to monitor files.
# If set to false will just <b>Run tests and exit</b>.
# Defaults to true: run tests and monitoring the files.
#
cattr_accessor :infinity_and_beyond
self.infinity_and_beyond = true
# The extension files that Infinity Test will search.
# You can observe python, erlang, etc files.
#
cattr_accessor :extension
self.extension = :rb
# Setup Infinity Test passing the ruby versions and others setting.
# <b>See the class accessors for more information.</b>
#
# ==== Examples
#
# InfinityTest::Base.setup do |config|
# config.strategy = :rbenv
# config.rubies = %w(ree jruby rbx 1.9.2)
# end
#
def self.setup
yield self
end
# Receives a object that quacks like InfinityTest::Options and do the merge with self(Base class).
#
def self.merge!(options)
ConfigurationMerge.new(self, options).merge!
end
def self.start_continuous_test_server
continuous_test_server.start
end
def self.continuous_test_server
@continuous_test_server ||= ContinuousTestServer.new(self)
end
# Just a shortcut to bundler class accessor.
#
def self.using_bundler?
bundler
end
# Just a shortcut to bundler class accessor.
#
def self.verbose?
verbose
end
# Callback method to handle before all run and for each ruby too!
#
# ==== Examples
#
# before(:all) do
# # ...
# end
#
# before(:each_ruby) do |environment|
# # ...
# end
#
# before do # if you pass not then will use :all option
# # ...
# end
#
def self.before(scope, &block)
# setting_callback(Callbacks::BeforeCallback, scope, &block)
end
# Callback method to handle after all run and for each ruby too!
#
# ==== Examples
#
# after(:all) do
# # ...
# end
#
# after(:each_ruby) do
# # ...
# end
#
# after do # if you pass not then will use :all option
# # ...
# end
#
def self.after(scope, &block)
# setting_callback(Callbacks::AfterCallback, scope, &block)
end
# Clear the terminal (Useful in the before callback)
#
def self.clear_terminal
system('clear')
end
###### This methods will be removed in the Infinity Test v2.0.1 or 2.0.2 ######
# <b>DEPRECATED:</b> Please use <tt>.notification=</tt> instead.
#
def self.notifications(notification_name = nil, &block)
if notification_name.blank?
self.class_variable_get(:@@notifications)
else
message = <<-MESSAGE
.notifications is DEPRECATED.
Use this instead:
InfinityTest.setup do |config|
config.notifications = :growl
end
MESSAGE
ActiveSupport::Deprecation.warn(message)
self.notifications = notification_name
self.instance_eval(&block) if block_given?
end
end
# <b>DEPRECATED:</b> Please use:
# <tt>success_image=</tt> or
# <tt>pending_image=</tt> or
# <tt>failure_image=</tt> or
# <tt>mode=</tt> instead.
#
def self.show_images(options)
message = <<-MESSAGE
.show_images is DEPRECATED.
Use this instead:
InfinityTest.setup do |config|
config.success_image = 'some_image.png'
config.pending_image = 'some_image.png'
config.failure_image = 'some_image.png'
config.mode = 'infinity_test_dir_that_contain_images'
end
MESSAGE
ActiveSupport::Deprecation.warn(message)
self.success_image = options[:success_image] || options[:sucess_image] if options[:success_image].present? || options[:sucess_image].present? # for fail typo in earlier versions.
self.pending_image = options[:pending_image] if options[:pending_image].present?
self.failure_image = options[:failure_image] if options[:failure_image].present?
self.mode = options[:mode] if options[:mode].present?
end
# <b>DEPRECATED:</b> Please use:
# .rubies = or
# .specific_options = or
# .test_framework = or
# .framework = or
# .verbose = or
# .gemset = instead
#
def self.use(options)
message = <<-MESSAGE
.use is DEPRECATED.
Use this instead:
InfinityTest.setup do |config|
config.rubies = %w(2.0 jruby)
config.specific_options = '-J'
config.test_framework = :rspec
config.framework = :padrino
config.verbose = true
config.gemset = :some_gemset
end
MESSAGE
ActiveSupport::Deprecation.warn(message)
self.rubies = options[:rubies] if options[:rubies].present?
self.specific_options = options[:specific_options] if options[:specific_options].present?
self.test_framework = options[:test_framework] if options[:test_framework].present?
self.framework = options[:app_framework] if options[:app_framework].present?
self.verbose = options[:verbose] unless options[:verbose].nil?
self.gemset = options[:gemset] if options[:gemset].present?
end
# <b>DEPRECATED:</b> Please use .clear_terminal instead.
#
def self.clear(option)
message = '.clear(:terminal) is DEPRECATED. Please use .clear_terminal instead.'
ActiveSupport::Deprecation.warn(message)
clear_terminal
end
def self.heuristics(&block)
# There is a spec pending.
end
def self.replace_patterns(&block)
# There is a spec pending.
end
private
# def self.setting_callback(callback_class, scope, &block)
# callback_instance = callback_class.new(scope, &block)
# self.callbacks.push(callback_instance)
# callback_instance
# end
end
end
end | mit |
smukideejeah/GaysonTaxi | cpanel/nuevoCotidiano.php | 822 | <?php
session_start();
require_once('../php/conexion.php');
$conect = connect::conn();
$user = $_SESSION['usuario'];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "insert into cotidiano (dir_origen,dir_destino,semana,hora,usuario,estado) values (?,?,?,?,?,?);";
$favo = sqlsrv_query($conect,$sql,array($_POST['Dir_o'],$_POST['Dir_d'],$_POST['semana'],$_POST['reloj'],$user['usuario'],1));
if($favo){
echo 'Inserccion correcta';
}
else{
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}
}else{
print "aqui la estabas cagando";
}
?>
| mit |
aldarondo/holiwish | README.md | 18 | holiwish
========
| mit |
nrdhm/max_dump | test.sh | 20 | python -m unittest
| mit |
NetOfficeFw/NetOffice | Source/MSProject/Enums/PjMonthLabel.cs | 3276 | using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.MSProjectApi.Enums
{
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff863548(v=office.14).aspx </remarks>
[SupportByVersion("MSProject", 11,12,14)]
[EntityType(EntityType.IsEnum)]
public enum PjMonthLabel
{
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>57</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm = 57,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>86</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm_yy = 86,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>85</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm_yyy = 85,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>11</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_m = 11,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>10</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmm = 10,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>8</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmm_yyy = 8,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>9</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmmm = 9,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>7</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmmm_yyyy = 7,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>59</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_mm = 59,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>58</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_Mmm = 58,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>45</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_Month_mm = 45,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>61</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_mm = 61,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>60</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_Mmm = 60,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>44</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_Month_mm = 44,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>35</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelNoDateFormat = 35
}
} | mit |
frostblooded/TelerikHomework | C# Part 1/ConsoleInputOutput/CircleAreaAndCircumference/Properties/AssemblyInfo.cs | 1428 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CircleAreaAndCircumference")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CircleAreaAndCircumference")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("24a850d9-a2e2-4979-a7f8-47602b439978")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
sharkattack51/GarageKit_for_Unity | UnityProject/Assets/__ProjectName__/Scripts/Utils/CameraContorol/FlyThroughCamera.cs | 13347 | //#define USE_TOUCH_SCRIPT
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
/*
* ドラッグ操作でのカメラの移動コントロールクラス
* マウス&タッチ対応
*/
namespace GarageKit
{
[RequireComponent(typeof(Camera))]
public class FlyThroughCamera : MonoBehaviour
{
public static bool winTouch = false;
public static bool updateEnable = true;
// フライスルーのコントロールタイプ
public enum FLYTHROUGH_CONTROLL_TYPE
{
DRAG = 0,
DRAG_HOLD
}
public FLYTHROUGH_CONTROLL_TYPE controllType;
// 移動軸の方向
public enum FLYTHROUGH_MOVE_TYPE
{
XZ = 0,
XY
}
public FLYTHROUGH_MOVE_TYPE moveType;
public Collider groundCollider;
public Collider limitAreaCollider;
public bool useLimitArea = false;
public float moveBias = 1.0f;
public float moveSmoothTime = 0.1f;
public bool dragInvertX = false;
public bool dragInvertY = false;
public float rotateBias = 1.0f;
public float rotateSmoothTime = 0.1f;
public bool rotateInvert = false;
public OrbitCamera combinationOrbitCamera;
private GameObject flyThroughRoot;
public GameObject FlyThroughRoot { get{ return flyThroughRoot; } }
private GameObject shiftTransformRoot;
public Transform ShiftTransform { get{ return shiftTransformRoot.transform; } }
private bool inputLock;
public bool IsInputLock { get{ return inputLock; } }
private object lockObject;
private Vector3 defaultPos;
private Quaternion defaultRot;
private bool isFirstTouch;
private Vector3 oldScrTouchPos;
private Vector3 dragDelta;
private Vector3 velocitySmoothPos;
private Vector3 dampDragDelta = Vector3.zero;
private Vector3 pushMoveDelta = Vector3.zero;
private float velocitySmoothRot;
private float dampRotateDelta = 0.0f;
private float pushRotateDelta = 0.0f;
public Vector3 currentPos { get{ return flyThroughRoot.transform.position; } }
public Quaternion currentRot { get{ return flyThroughRoot.transform.rotation; } }
void Awake()
{
}
void Start()
{
// 設定ファイルより入力タイプを取得
if(!ApplicationSetting.Instance.GetBool("UseMouse"))
winTouch = true;
inputLock = false;
// 地面上視点位置に回転ルートを設定する
Ray ray = new Ray(this.transform.position, this.transform.forward);
RaycastHit hitInfo;
if(groundCollider.Raycast(ray, out hitInfo, float.PositiveInfinity))
{
flyThroughRoot = new GameObject(this.gameObject.name + " FlyThrough Root");
flyThroughRoot.transform.SetParent(this.gameObject.transform.parent, false);
flyThroughRoot.transform.position = hitInfo.point;
flyThroughRoot.transform.rotation = Quaternion.identity;
shiftTransformRoot = new GameObject(this.gameObject.name + " ShiftTransform Root");
shiftTransformRoot.transform.SetParent(flyThroughRoot.transform, true);
shiftTransformRoot.transform.localPosition = Vector3.zero;
shiftTransformRoot.transform.localRotation = Quaternion.identity;
this.gameObject.transform.SetParent(shiftTransformRoot.transform, true);
}
else
{
Debug.LogWarning("FlyThroughCamera :: not set the ground collider !!");
return;
}
// 初期値を保存
defaultPos = flyThroughRoot.transform.position;
defaultRot = flyThroughRoot.transform.rotation;
ResetInput();
}
void Update()
{
if(!inputLock && ButtonObjectEvent.PressBtnsTotal == 0)
GetInput();
else
ResetInput();
UpdateFlyThrough();
UpdateOrbitCombination();
}
private void ResetInput()
{
isFirstTouch = true;
oldScrTouchPos = Vector3.zero;
dragDelta = Vector3.zero;
}
private void GetInput()
{
// for Touch
if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
if(Input.touchCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.GetTouch(0).position;
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
#if UNITY_STANDALONE_WIN
else if(Application.platform == RuntimePlatform.WindowsPlayer && winTouch)
{
#if !USE_TOUCH_SCRIPT
if(Input.touchCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.touches[0].position;
#else
if(TouchScript.TouchManager.Instance.PressedPointersCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = TouchScript.TouchManager.Instance.PressedPointers[0].Position;
#endif
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
#endif
// for Mouse
else
{
if(Input.GetMouseButton(0))
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.mousePosition;
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
}
/// <summary>
/// Input更新のLock
/// </summary>
public void LockInput(object sender)
{
if(!inputLock)
{
lockObject = sender;
inputLock = true;
}
}
/// <summary>
/// Input更新のUnLock
/// </summary>
public void UnlockInput(object sender)
{
if(inputLock && lockObject == sender)
inputLock = false;
}
/// <summary>
/// フライスルーを更新
/// </summary>
private void UpdateFlyThrough()
{
if(!FlyThroughCamera.updateEnable || flyThroughRoot == null)
return;
// 位置
float dragX = dragDelta.x * (dragInvertX ? -1.0f : 1.0f);
float dragY = dragDelta.y * (dragInvertY ? -1.0f : 1.0f);
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, 0.0f, dragY) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, dragY, 0.0f) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);
flyThroughRoot.transform.Translate(dampDragDelta, Space.Self);
pushMoveDelta = Vector3.zero;
if(useLimitArea)
{
// 移動範囲限界を設定
if(limitAreaCollider != null)
{
Vector3 movingLimitMin = limitAreaCollider.bounds.min + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;
Vector3 movingLimitMax = limitAreaCollider.bounds.max + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
{
float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);
float limitZ = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.z, movingLimitMax.z), movingLimitMin.z);
flyThroughRoot.transform.position = new Vector3(limitX, flyThroughRoot.transform.position.y, limitZ);
}
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
{
float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);
float limitY = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.y, movingLimitMax.y), movingLimitMin.y);
flyThroughRoot.transform.position = new Vector3(limitX, limitY, flyThroughRoot.transform.position.z);
}
}
}
// 方向
dampRotateDelta = Mathf.SmoothDamp(dampRotateDelta, pushRotateDelta * rotateBias, ref velocitySmoothRot, rotateSmoothTime);
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
flyThroughRoot.transform.Rotate(Vector3.up, dampRotateDelta, Space.Self);
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
flyThroughRoot.transform.Rotate(Vector3.forward, dampRotateDelta, Space.Self);
pushRotateDelta = 0.0f;
}
private void UpdateOrbitCombination()
{
// 連携機能
if(combinationOrbitCamera != null && combinationOrbitCamera.OrbitRoot != null)
{
Vector3 lookPoint = combinationOrbitCamera.OrbitRoot.transform.position;
Transform orbitParent = combinationOrbitCamera.OrbitRoot.transform.parent;
combinationOrbitCamera.OrbitRoot.transform.parent = null;
flyThroughRoot.transform.LookAt(lookPoint, Vector3.up);
flyThroughRoot.transform.rotation = Quaternion.Euler(
0.0f, flyThroughRoot.transform.rotation.eulerAngles.y + 180.0f, 0.0f);
combinationOrbitCamera.OrbitRoot.transform.parent = orbitParent;
}
}
/// <summary>
/// 目標位置にカメラを移動させる
/// </summary>
public void MoveToFlyThrough(Vector3 targetPosition, float time = 1.0f)
{
dampDragDelta = Vector3.zero;
flyThroughRoot.transform.DOMove(targetPosition, time)
.SetEase(Ease.OutCubic)
.Play();
}
/// <summary>
/// 指定値でカメラを移動させる
/// </summary>
public void TranslateToFlyThrough(Vector3 move)
{
dampDragDelta = Vector3.zero;
flyThroughRoot.transform.Translate(move, Space.Self);
}
/// <summary>
/// 目標方向にカメラを回転させる
/// </summary>
public void RotateToFlyThrough(float targetAngle, float time = 1.0f)
{
dampRotateDelta = 0.0f;
Vector3 targetEulerAngles = flyThroughRoot.transform.rotation.eulerAngles;
targetEulerAngles.y = targetAngle;
flyThroughRoot.transform.DORotate(targetEulerAngles, time)
.SetEase(Ease.OutCubic)
.Play();
}
/// <summary>
/// 外部トリガーで移動させる
/// </summary>
public void PushMove(Vector3 move)
{
pushMoveDelta = move;
}
/// <summary>
/// 外部トリガーでカメラ方向を回転させる
/// </summary>
public void PushRotate(float rotate)
{
pushRotateDelta = rotate;
}
/// <summary>
/// フライスルーを初期化
/// </summary>
public void ResetFlyThrough()
{
ResetInput();
MoveToFlyThrough(defaultPos);
RotateToFlyThrough(defaultRot.eulerAngles.y);
}
}
}
| mit |
BigstickCarpet/readdir-enhanced | test/specs/stream.spec.js | 7232 | "use strict";
const readdir = require("../../");
const dir = require("../utils/dir");
const { expect } = require("chai");
const through2 = require("through2");
const fs = require("fs");
let nodeVersion = parseFloat(process.version.substr(1));
describe("Stream API", () => {
it("should be able to pipe to other streams as a Buffer", done => {
let allData = [];
readdir.stream("test/dir")
.pipe(through2((data, enc, next) => {
try {
// By default, the data is streamed as a Buffer
expect(data).to.be.an.instanceOf(Buffer);
// Buffer.toString() returns the file name
allData.push(data.toString());
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", err => {
done(err);
});
});
it('should be able to pipe to other streams in "object mode"', done => {
let allData = [];
readdir.stream("test/dir")
.pipe(through2({ objectMode: true }, (data, enc, next) => {
try {
// In "object mode", the data is a string
expect(data).to.be.a("string");
allData.push(data);
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", err => {
done(err);
});
});
it('should be able to pipe fs.Stats to other streams in "object mode"', done => {
let allData = [];
readdir.stream("test/dir", { stats: true })
.pipe(through2({ objectMode: true }, (data, enc, next) => {
try {
// The data is an fs.Stats object
expect(data).to.be.an("object");
expect(data).to.be.an.instanceOf(fs.Stats);
allData.push(data.path);
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", done);
});
it("should be able to pause & resume the stream", done => {
let allData = [];
let stream = readdir.stream("test/dir")
.on("data", data => {
allData.push(data);
// The stream should not be paused
expect(stream.isPaused()).to.equal(false);
if (allData.length === 3) {
// Pause for one second
stream.pause();
setTimeout(() => {
try {
// The stream should still be paused
expect(stream.isPaused()).to.equal(true);
// The array should still only contain 3 items
expect(allData).to.have.lengthOf(3);
// Read the rest of the stream
stream.resume();
}
catch (e) {
done(e);
}
}, 1000);
}
})
.on("end", () => {
expect(allData).to.have.same.members(dir.shallow.data);
done();
})
.on("error", done);
});
it('should be able to use "readable" and "read"', done => {
let allData = [];
let nullCount = 0;
let stream = readdir.stream("test/dir")
.on("readable", () => {
// Manually read the next chunk of data
let data = stream.read();
while (true) { // eslint-disable-line
if (data === null) {
// The stream is done
nullCount++;
break;
}
else {
// The data should be a string (the file name)
expect(data).to.be.a("string").with.length.of.at.least(1);
allData.push(data);
data = stream.read();
}
}
})
.on("end", () => {
if (nodeVersion >= 12) {
// In Node >= 12, the "readable" event fires twice,
// and stream.read() returns null twice
expect(nullCount).to.equal(2);
}
else if (nodeVersion >= 10) {
// In Node >= 10, the "readable" event only fires once,
// and stream.read() only returns null once
expect(nullCount).to.equal(1);
}
else {
// In Node < 10, the "readable" event fires 13 times (once per file),
// and stream.read() returns null each time
expect(nullCount).to.equal(13);
}
expect(allData).to.have.same.members(dir.shallow.data);
done();
})
.on("error", done);
});
it('should be able to subscribe to custom events instead of "data"', done => {
let allFiles = [];
let allSubdirs = [];
let stream = readdir.stream("test/dir");
// Calling "resume" is required, since we're not handling the "data" event
stream.resume();
stream
.on("file", filename => {
expect(filename).to.be.a("string").with.length.of.at.least(1);
allFiles.push(filename);
})
.on("directory", subdir => {
expect(subdir).to.be.a("string").with.length.of.at.least(1);
allSubdirs.push(subdir);
})
.on("end", () => {
expect(allFiles).to.have.same.members(dir.shallow.files);
expect(allSubdirs).to.have.same.members(dir.shallow.dirs);
done();
})
.on("error", done);
});
it('should handle errors that occur in the "data" event listener', done => {
testErrorHandling("data", dir.shallow.data, 7, done);
});
it('should handle errors that occur in the "file" event listener', done => {
testErrorHandling("file", dir.shallow.files, 3, done);
});
it('should handle errors that occur in the "directory" event listener', done => {
testErrorHandling("directory", dir.shallow.dirs, 2, done);
});
it('should handle errors that occur in the "symlink" event listener', done => {
testErrorHandling("symlink", dir.shallow.symlinks, 5, done);
});
function testErrorHandling (eventName, expected, expectedErrors, done) {
let errors = [], data = [];
let stream = readdir.stream("test/dir");
// Capture all errors
stream.on("error", error => {
errors.push(error);
});
stream.on(eventName, path => {
data.push(path);
if (path.indexOf(".txt") >= 0 || path.indexOf("dir-") >= 0) {
throw new Error("Epic Fail!!!");
}
else {
return true;
}
});
stream.on("end", () => {
try {
// Make sure the correct number of errors were thrown
expect(errors).to.have.lengthOf(expectedErrors);
for (let error of errors) {
expect(error.message).to.equal("Epic Fail!!!");
}
// All of the events should have still been emitted, despite the errors
expect(data).to.have.same.members(expected);
done();
}
catch (e) {
done(e);
}
});
stream.resume();
}
});
| mit |
romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/Font/PreferredSubfamily.php | 792 | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Font;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class PreferredSubfamily extends AbstractTag
{
protected $Id = 17;
protected $Name = 'PreferredSubfamily';
protected $FullName = 'Font::Name';
protected $GroupName = 'Font';
protected $g0 = 'Font';
protected $g1 = 'Font';
protected $g2 = 'Document';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Preferred Subfamily';
}
| mit |
tliang1/Java-Practice | Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-12/Chapter12P03/doc/index-files/index-2.html | 5390 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (10.0.2) on Fri Sep 21 22:00:31 PDT 2018 -->
<title>U-Index</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2018-09-21">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
<script type="text/javascript" src="../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="U-Index";
}
}
catch(err) {
}
//-->
var pathtoroot = "../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../main/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../main/package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-1.html">Prev Letter</a></li>
<li>Next Letter</li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li>
<li><a href="index-2.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
<div class="contentContainer"><a href="index-1.html">M</a> <a href="index-2.html">U</a> <a name="I:U">
<!-- -->
</a>
<h2 class="title">U</h2>
<dl>
<dt><a href="../main/UsingTheGridLayout.html" title="class in main"><span class="typeNameLink">UsingTheGridLayout</span></a> - Class in <a href="../main/package-summary.html">main</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../main/UsingTheGridLayout.html#UsingTheGridLayout--">UsingTheGridLayout()</a></span> - Constructor for class main.<a href="../main/UsingTheGridLayout.html" title="class in main">UsingTheGridLayout</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">M</a> <a href="index-2.html">U</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../main/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../main/package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-1.html">Prev Letter</a></li>
<li>Next Letter</li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li>
<li><a href="index-2.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| mit |
selvasingh/azure-sdk-for-java | sdk/synapse/mgmt-v2019_06_01_preview/src/main/java/com/microsoft/azure/management/synapse/v2019_06_01_preview/IntegrationRuntimeState.java | 2607 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.synapse.v2019_06_01_preview;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for IntegrationRuntimeState.
*/
public final class IntegrationRuntimeState extends ExpandableStringEnum<IntegrationRuntimeState> {
/** Static value Initial for IntegrationRuntimeState. */
public static final IntegrationRuntimeState INITIAL = fromString("Initial");
/** Static value Stopped for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STOPPED = fromString("Stopped");
/** Static value Started for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STARTED = fromString("Started");
/** Static value Starting for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STARTING = fromString("Starting");
/** Static value Stopping for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STOPPING = fromString("Stopping");
/** Static value NeedRegistration for IntegrationRuntimeState. */
public static final IntegrationRuntimeState NEED_REGISTRATION = fromString("NeedRegistration");
/** Static value Online for IntegrationRuntimeState. */
public static final IntegrationRuntimeState ONLINE = fromString("Online");
/** Static value Limited for IntegrationRuntimeState. */
public static final IntegrationRuntimeState LIMITED = fromString("Limited");
/** Static value Offline for IntegrationRuntimeState. */
public static final IntegrationRuntimeState OFFLINE = fromString("Offline");
/** Static value AccessDenied for IntegrationRuntimeState. */
public static final IntegrationRuntimeState ACCESS_DENIED = fromString("AccessDenied");
/**
* Creates or finds a IntegrationRuntimeState from its string representation.
* @param name a name to look for
* @return the corresponding IntegrationRuntimeState
*/
@JsonCreator
public static IntegrationRuntimeState fromString(String name) {
return fromString(name, IntegrationRuntimeState.class);
}
/**
* @return known IntegrationRuntimeState values
*/
public static Collection<IntegrationRuntimeState> values() {
return values(IntegrationRuntimeState.class);
}
}
| mit |
beverloo/node-home-server | src/module.js | 981 | // Copyright 2015 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
// Base class for a module. Stores the environment and handles magic such as route annotations.
export class Module {
constructor(env) {
this.env_ = env;
let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_;
if (!decoratedRoutes)
return;
decoratedRoutes.forEach(route => {
env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]);
});
}
};
// Annotation that can be used on modules to indicate that the annotated method is the request
// handler for a |method| (GET, POST) request for |route_path|.
export function route(method, route_path) {
return (target, handler) => {
if (!target.hasOwnProperty('decoratedRoutes_'))
target.decoratedRoutes_ = [];
target.decoratedRoutes_.push({ method, route_path, handler });
};
}
| mit |
cedricleblond35/capvisu-site_supervision | vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php | 1919 | <?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <[email protected]>
* Dariusz Rumiński <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\PhpUnit;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Roland Franssen <[email protected]>
*/
final class PhpUnitFqcnAnnotationFixer extends AbstractFixer
{
/**
* {@inheritdoc}
*/
public function getDefinition()
{
return new FixerDefinition(
'PHPUnit annotations should be a FQCNs including a root namespace.',
array(new CodeSample(
'<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
* @covers Project\NameSpace\Something
* @coversDefaultClass Project\Default
* @uses Project\Test\Util
*/
public function testSomeTest()
{
}
}
'
))
);
}
/**
* {@inheritdoc}
*/
public function getPriority()
{
// should be run before NoUnusedImportsFixer
return -9;
}
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(T_DOC_COMMENT);
}
/**
* {@inheritdoc}
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens)
{
foreach ($tokens as $token) {
if ($token->isGivenKind(T_DOC_COMMENT)) {
$token->setContent(preg_replace(
'~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(\w.*)$~m', '$1\\\\$2',
$token->getContent()
));
}
}
}
}
| mit |
coldxiangyu/coldxiangyu.github.io | _posts/2016-12-20-从头学算法(二、搞算法你必须知道的OJ).md | 2556 | ---
layout: post
title: "从头学算法(二、搞算法你必须知道的OJ)"
date: 2016-12-20 11:36:52
categories: 数据结构及算法
tags: OJ algorithms
mathjax: true
---
在没接触算法之前,我从没听说过OJ这个缩写,没关系,现在开始认识还来得及。等你真正开始研究算法,你才发现你又进入了一个新的世界。
这个世界,你不关注它的时候,它好像并不存在,而一旦你关注它了,每一个花草都让你叹为观止。
来看看百度百科是怎么说的吧:
OJ是Online Judge系统的简称,用来在线检测程序源代码的正确性。著名的OJ有TYVJ、RQNOJ、URAL等。国内著名的题库有北京大学题库、浙江大学题库、电子科技大学题库、杭州电子科技大学等。国外的题库包括乌拉尔大学、瓦拉杜利德大学题库等。
而作为程序员,你必须知道Leetcode这个OJ,相比起国内各大著名高校的OJ,为什么我更推荐程序员们选择LeetCode OJ呢?原因有两点:
第一,大学OJ上的题目一般都是为ACM选手做准备的,难度大,属于竞技范畴;LeetCode的题相对简单,更为实用,更适合以后从事开发等岗位的程序员们。
第二,LeetCode非常流行,用户的量级几乎要比其他OJ高出将近三到五个级别。大量的活跃用户,将会为我们提供数不清的经验交流和可供参考的GitHub源代码。
刷LeetCode不是为了学会某些牛逼的算法,也不是为了突破某道难题而可能获得的智趣上的快感。学习和练习正确的思考方法,锻炼考虑各种条件的能力,在代码实现前就已经尽可能避免大多数常见错误带来的bug,养成简洁代码的审美习惯。
通过OJ刷题,配合算法的相关书籍进行理解,对算法的学习是很有帮助的,作为一个程序员,不刷几道LeetCode,真的说不过去。
最后LeetCode网址:https://leetcode.com/
接下来注册开始搞吧!
![image_1bf90k08d19p01391i8pfvkqhbm.png-65.6kB][1]
![image_1bf90orko1ccn1opj29j93cc7f13.png-91.4kB][2]
LeetCode刷过一阵子之后,发现很多都是收费的,这就很不友好了。本着方便大家的原则,向大家推荐lintcode,题目相对也很全,支持中、英双语,最重要是免费。
[1]: http://static.zybuluo.com/coldxiangyu/j2xlu88omsuprk7c7qinubug/image_1bf90k08d19p01391i8pfvkqhbm.png
[2]: http://static.zybuluo.com/coldxiangyu/fztippzc74u7j9ww7av2vvn3/image_1bf90orko1ccn1opj29j93cc7f13.png
| mit |
kristofersokk/RainControl | src/main/java/com/timotheteus/raincontrol/handlers/GuiHandler.java | 2028 | package com.timotheteus.raincontrol.handlers;
import com.timotheteus.raincontrol.tileentities.IGUITile;
import com.timotheteus.raincontrol.tileentities.TileEntityInventoryBase;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import net.minecraftforge.fml.network.FMLPlayMessages;
import net.minecraftforge.fml.network.NetworkHooks;
import javax.annotation.Nullable;
public class GuiHandler implements IGuiHandler {
public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) {
BlockPos pos = openContainer.getAdditionalData().readBlockPos();
// new GUIChest(type, (IInventory) Minecraft.getInstance().player.inventory, (IInventory) Minecraft.getInstance().world.getTileEntity(pos));
TileEntityInventoryBase te = (TileEntityInventoryBase) Minecraft.getInstance().world.getTileEntity(pos);
if (te != null) {
return te.createGui(Minecraft.getInstance().player);
}
return null;
}
//TODO can remove these, I think
@Nullable
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
TileEntity te = world.getTileEntity(pos);
if (te instanceof IGUITile) {
return ((IGUITile) te).createContainer(player);
}
return null;
}
@Nullable
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
TileEntity te = world.getTileEntity(pos);
if (te instanceof IGUITile) {
return ((IGUITile) te).createGui(player);
}
return null;
}
}
| mit |
dayanstef/perfect-php-framework | index.php | 10005 | <?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2015, British Columbia Institute of Technology
*
* 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 CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
/*
*---------------------------------------------------------------
* APPLICATION ENVIRONMENT
*---------------------------------------------------------------
*
* You can load different configurations depending on your
* current environment. Setting the environment also influences
* things like logging and error reporting.
*
* This can be set to anything, but default usage is:
*
* development
* testing
* production
*
* NOTE: If you change these, also change the error_reporting() code below
*/
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
switch (ENVIRONMENT) {
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
case 'testing':
case 'production':
ini_set('display_errors', 0);
if (version_compare(PHP_VERSION, '5.3', '>=')) {
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
} else {
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
}
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'The application environment is not set correctly.';
exit(1); // EXIT_ERROR
}
/*
*---------------------------------------------------------------
* SYSTEM FOLDER NAME
*---------------------------------------------------------------
*
* This variable must contain the name of your "system" folder.
* Include the path if the folder is not in the same directory
* as this file.
*/
$system_path = 'system';
/*
*---------------------------------------------------------------
* APPLICATION FOLDER NAME
*---------------------------------------------------------------
*
* If you want this front controller to use a different "application"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path. For more info please see the user guide:
* http://codeigniter.com/user_guide/general/managing_apps.html
*
* NO TRAILING SLASH!
*/
$application_folder = 'application';
/*
*---------------------------------------------------------------
* VIEW FOLDER NAME
*---------------------------------------------------------------
*
* If you want to move the view folder out of the application
* folder set the path to the folder here. The folder can be renamed
* and relocated anywhere on your server. If blank, it will default
* to the standard location inside your application folder. If you
* do move this, use the full server path to this folder.
*
* NO TRAILING SLASH!
*/
$view_folder = '';
$templates = $view_folder . '/templates/';
/*
* --------------------------------------------------------------------
* DEFAULT CONTROLLER
* --------------------------------------------------------------------
*
* Normally you will set your default controller in the routes.php file.
* You can, however, force a custom routing by hard-coding a
* specific controller class/function here. For most applications, you
* WILL NOT set your routing here, but it's an option for those
* special instances where you might want to override the standard
* routing in a specific front controller that shares a common CI installation.
*
* IMPORTANT: If you set the routing here, NO OTHER controller will be
* callable. In essence, this preference limits your application to ONE
* specific controller. Leave the function name blank if you need
* to call functions dynamically via the URI.
*
* Un-comment the $routing array below to use this feature
*/
// The directory name, relative to the "controllers" folder. Leave blank
// if your controller is not in a sub-folder within the "controllers" folder
// $routing['directory'] = '';
// The controller class file name. Example: mycontroller
// $routing['controller'] = '';
// The controller function you wish to be called.
// $routing['function'] = '';
/*
* -------------------------------------------------------------------
* CUSTOM CONFIG VALUES
* -------------------------------------------------------------------
*
* The $assign_to_config array below will be passed dynamically to the
* config class when initialized. This allows you to set custom config
* items or override any default config values found in the config.php file.
* This can be handy as it permits you to share one application between
* multiple front controller files, with each file containing different
* config values.
*
* Un-comment the $assign_to_config array below to use this feature
*/
// $assign_to_config['name_of_config_item'] = 'value of config item';
// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------
/*
* ---------------------------------------------------------------
* Resolve the system path for increased reliability
* ---------------------------------------------------------------
*/
// Set the current directory correctly for CLI requests
if (defined('STDIN')) {
chdir(dirname(__FILE__));
}
if (($_temp = realpath($system_path)) !== FALSE) {
$system_path = $_temp . '/';
} else {
// Ensure there's a trailing slash
$system_path = rtrim($system_path, '/') . '/';
}
// Is the system path correct?
if (!is_dir($system_path)) {
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: ' . pathinfo(__FILE__, PATHINFO_BASENAME);
exit(3); // EXIT_CONFIG
}
/*
* -------------------------------------------------------------------
* Now that we know the path, set the main path constants
* -------------------------------------------------------------------
*/
// The name of THIS file
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
// Path to the system folder
define('BASEPATH', str_replace('\\', '/', $system_path));
// Path to the front controller (this file)
define('FCPATH', dirname(__FILE__) . '/');
// Name of the "system folder"
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));
// The path to the "application" folder
if (is_dir($application_folder)) {
if (($_temp = realpath($application_folder)) !== FALSE) {
$application_folder = $_temp;
}
define('APPPATH', $application_folder . DIRECTORY_SEPARATOR);
} else {
if (!is_dir(BASEPATH . $application_folder . DIRECTORY_SEPARATOR)) {
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF;
exit(3); // EXIT_CONFIG
}
define('APPPATH', BASEPATH . $application_folder . DIRECTORY_SEPARATOR);
}
// The path to the "views" folder
if (!is_dir($view_folder)) {
if (!empty($view_folder) && is_dir(APPPATH . $view_folder . DIRECTORY_SEPARATOR)) {
$view_folder = APPPATH . $view_folder;
} elseif (!is_dir(APPPATH . 'views' . DIRECTORY_SEPARATOR)) {
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF;
exit(3); // EXIT_CONFIG
} else {
$view_folder = APPPATH . 'views';
}
}
if (($_temp = realpath($view_folder)) !== FALSE) {
$view_folder = $_temp . DIRECTORY_SEPARATOR;
} else {
$view_folder = rtrim($view_folder, '/\\') . DIRECTORY_SEPARATOR;
}
define('VIEWPATH', $view_folder);
/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------
*
* And away we go...
*/
require_once BASEPATH . 'core/CodeIgniter.php'; | mit |
yogeshsaroya/new-cdnjs | ajax/libs/extjs/4.2.1/src/app/domain/Direct.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:be847f24aac166b803f1ff5ccc7e4d7bc3fb5d960543e35f779068a754294c94
size 1312
| mit |
Matthimatiker/CommandLockingBundle | Locking/FileLockManager.php | 2166 | <?php
namespace Matthimatiker\CommandLockingBundle\Locking;
use Symfony\Component\Filesystem\LockHandler;
/**
* Uses files to create locks.
*
* @see \Symfony\Component\Filesystem\LockHandler
* @see http://symfony.com/doc/current/components/filesystem/lock_handler.html
*/
class FileLockManager implements LockManagerInterface
{
/**
* The directory that contains the lock files.
*
* @var string
*/
private $lockDirectory = null;
/**
* Contains the locks that are currently active.
*
* The name of the lock is used as key.
*
* @var array<string, LockHandler>
*/
private $activeLocksByName = array();
/**
* @param string $lockDirectory Path to the directory that contains the locks.
*/
public function __construct($lockDirectory)
{
$this->lockDirectory = $lockDirectory;
}
/**
* Obtains a lock for the provided name.
*
* The lock must be released before it can be obtained again.
*
* @param string $name
* @return boolean True if the lock was obtained, false otherwise.
*/
public function lock($name)
{
if ($this->isLocked($name)) {
return false;
}
$lock = new LockHandler($name . '.lock', $this->lockDirectory);
if ($lock->lock()) {
// Obtained lock.
$this->activeLocksByName[$name] = $lock;
return true;
}
return false;
}
/**
* Releases the lock with the provided name.
*
* If the lock does not exist, then this method will do nothing.
*
* @param string $name
*/
public function release($name)
{
if (!$this->isLocked($name)) {
return;
}
/* @var $lock LockHandler */
$lock = $this->activeLocksByName[$name];
$lock->release();
unset($this->activeLocksByName[$name]);
}
/**
* Checks if a lock with the given name is active.
*
* @param string $name
* @return boolean
*/
private function isLocked($name)
{
return isset($this->activeLocksByName[$name]);
}
}
| mit |
tyleregeto/8bit-emulator | src/core.js | 1772 | // Core is a collection of helpers
// Nothing specific to the emultor application
"use strict";
// all code is defined in this namespace
window.te = window.te || {};
// te.provide creates a namespace if not previously defined.
// Levels are seperated by a `.` Each level is a generic JS object.
// Example:
// te.provide("my.name.space");
// my.name.foo = function(){};
// my.name.space.bar = function(){};
te.provide = function(ns /*string*/ , root) {
var parts = ns.split('.');
var lastLevel = root || window;
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
if (!lastLevel[p]) {
lastLevel = lastLevel[p] = {};
} else if (typeof lastLevel[p] !== 'object') {
throw new Error('Error creating namespace.');
} else {
lastLevel = lastLevel[p];
}
}
};
// A simple UID generator. Returned UIDs are guaranteed to be unique to the page load
te.Uid = (function() {
var id = 1;
function next() {
return id++;
}
return {
next: next
};
})();
// defaultOptionParse is a helper for functions that expect an options
// var passed in. This merges the passed in options with a set of defaults.
// Example:
// foo function(options) {
// tf.defaultOptionParse(options, {bar:true, fizz:"xyz"});
// }
te.defaultOptionParse = function(src, defaults) {
src = src || {};
var keys = Object.keys(defaults);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (src[k] === undefined) {
src[k] = defaults[k];
}
}
return src;
};
// Simple string replacement, eg:
// tf.sprintf('{0} and {1}', 'foo', 'bar'); // outputs: foo and bar
te.sprintf = function(str) {
for (var i = 1; i < arguments.length; i++) {
var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
str = str.replace(re, arguments[i]);
}
return str;
}; | mit |
dockerizedrupal/backer | src/backer/build/modules/build/files/root/Backup/config.rb | 3832 | ##
# Backup v4.x Configuration
#
# Documentation: http://meskyanichi.github.io/backup
# Issue Tracker: https://github.com/meskyanichi/backup/issues
##
# Config Options
#
# The options here may be overridden on the command line, but the result
# will depend on the use of --root-path on the command line.
#
# If --root-path is used on the command line, then all paths set here
# will be overridden. If a path (like --tmp-path) is not given along with
# --root-path, that path will use it's default location _relative to --root-path_.
#
# If --root-path is not used on the command line, a path option (like --tmp-path)
# given on the command line will override the tmp_path set here, but all other
# paths set here will be used.
#
# Note that relative paths given on the command line without --root-path
# are relative to the current directory. The root_path set here only applies
# to relative paths set here.
#
# ---
#
# Sets the root path for all relative paths, including default paths.
# May be an absolute path, or relative to the current working directory.
#
# root_path 'my/root'
#
# Sets the path where backups are processed until they're stored.
# This must have enough free space to hold apx. 2 backups.
# May be an absolute path, or relative to the current directory or +root_path+.
#
# tmp_path 'my/tmp'
#
# Sets the path where backup stores persistent information.
# When Backup's Cycler is used, small YAML files are stored here.
# May be an absolute path, or relative to the current directory or +root_path+.
#
# data_path 'my/data'
##
# Utilities
#
# If you need to use a utility other than the one Backup detects,
# or a utility can not be found in your $PATH.
#
# Utilities.configure do
# tar '/usr/bin/gnutar'
# redis_cli '/opt/redis/redis-cli'
# end
##
# Logging
#
# Logging options may be set on the command line, but certain settings
# may only be configured here.
#
# Logger.configure do
# console.quiet = true # Same as command line: --quiet
# logfile.max_bytes = 2_000_000 # Default: 500_000
# syslog.enabled = true # Same as command line: --syslog
# syslog.ident = 'my_app_backup' # Default: 'backup'
# end
#
# Command line options will override those set here.
# For example, the following would override the example settings above
# to disable syslog and enable console output.
# backup perform --trigger my_backup --no-syslog --no-quiet
##
# Component Defaults
#
# Set default options to be applied to components in all models.
# Options set within a model will override those set here.
#
# Storage::S3.defaults do |s3|
# s3.access_key_id = "my_access_key_id"
# s3.secret_access_key = "my_secret_access_key"
# end
#
# Notifier::Mail.defaults do |mail|
# mail.from = '[email protected]'
# mail.to = '[email protected]'
# mail.address = 'smtp.gmail.com'
# mail.port = 587
# mail.domain = 'your.host.name'
# mail.user_name = '[email protected]'
# mail.password = 'my_password'
# mail.authentication = 'plain'
# mail.encryption = :starttls
# end
##
# Preconfigured Models
#
# Create custom models with preconfigured components.
# Components added within the model definition will
# +add to+ the preconfigured components.
#
# preconfigure 'MyModel' do
# archive :user_pictures do |archive|
# archive.add '~/pictures'
# end
#
# notify_by Mail do |mail|
# mail.to = '[email protected]'
# end
# end
#
# MyModel.new(:john_smith, 'John Smith Backup') do
# archive :user_music do |archive|
# archive.add '~/music'
# end
#
# notify_by Mail do |mail|
# mail.to = '[email protected]'
# end
# end
| mit |
alexBaizeau/ember-fingerprint-translations | app/services/translation-map.js | 126 | import Ember from 'ember';
let __TRANSLATION_MAP__ = {};
export default Ember.Service.extend({ map: __TRANSLATION_MAP__ });
| mit |
slkjse9/slkjse9.github.io | src/components/Content.js | 2049 | import React from 'react';
<<<<<<< HEAD
import { Switch, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Blog from './Blog';
import Resume from './Resume';
import Error404 from './Error404';
=======
// import GithubForm from './forms/github/GithubForm';
import GithubRecent from './forms/github/RecentList';
import './Content.css';
>>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a
class Content extends React.Component {
render() {
return (
<div className="app-content">
<<<<<<< HEAD
<Switch>
<Route exact path="/" component={Home} />
{/* <Route exact path="/about" component={About} /> */}
<Route component={Error404} />
</Switch>
=======
<div className="content-description">
<br />College Student. Love Coding. Interested in Web and Machine Learning.
</div>
<hr />
<div className="content-list">
<div className="list-projects">
<h3>Recent Projects</h3>
{/* <GithubRecent userName="slkjse9" standardDate={5259492000} /> */}
<GithubRecent userName="hejuby" standardDate={3.154e+10} />
{/* <h2>Activity</h2> */}
<h3>Experience</h3>
<h3>Education</h3>
<ul>
<li><h4>Computer Science</h4>Colorado State University, Fort Collins (2017 -)</li>
</ul>
<br />
</div>
</div>
{/* <div className="content-home-github-recent-title">
<h2>Recent Works</h2>
<h3>updated in 2 months</h3>
</div> */}
{/* <h3>Recent</h3>
<GithubForm contentType="recent"/> */}
{/* <h3>Lifetime</h3>
{/* <GithubForm contentType="life"/> */}
{/* <div className="content-home-blog-recent-title">
<h2>Recent Posts</h2>
<h3>written in 2 months</h3>
</div>
<BlogRecent /> */}
>>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a
</div>
);
}
}
export default Content;
| mit |
plouc/go-gitlab-client | cli/cmd/get_project_var_cmd.go | 873 | package cmd
import (
"github.com/fatih/color"
out "github.com/plouc/go-gitlab-client/cli/output"
"github.com/spf13/cobra"
)
func init() {
getCmd.AddCommand(getProjectVarCmd)
}
var getProjectVarCmd = &cobra.Command{
Use: resourceCmd("project-var", "project-var"),
Aliases: []string{"pv"},
Short: "Get the details of a project's specific variable",
RunE: func(cmd *cobra.Command, args []string) error {
ids, err := config.aliasIdsOrArgs(currentAlias, "project-var", args)
if err != nil {
return err
}
color.Yellow("Fetching project variable (id: %s, key: %s)…", ids["project_id"], ids["var_key"])
loader.Start()
variable, meta, err := client.ProjectVariable(ids["project_id"], ids["var_key"])
loader.Stop()
if err != nil {
return err
}
out.Variable(output, outputFormat, variable)
printMeta(meta, false)
return nil
},
}
| mit |
SimpleCom/simplecom-web | src/interfaces/contacts.interface.ts | 98 | export interface IContact {
id?: number;
email: string;
listName: string;
name: string;
}
| mit |
FacticiusVir/SharpVk | src/SharpVk/Interop/ExternalMemoryImageCreateInfo.gen.cs | 1882 | // The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk.Interop
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct ExternalMemoryImageCreateInfo
{
/// <summary>
/// The type of this structure.
/// </summary>
public SharpVk.StructureType SType;
/// <summary>
/// Null or an extension-specific structure.
/// </summary>
public void* Next;
/// <summary>
///
/// </summary>
public SharpVk.ExternalMemoryHandleTypeFlags HandleTypes;
}
}
| mit |
fvasquezjatar/fermat-unused | DMP/plugin/basic_wallet/fermat-dmp-plugin-basic-wallet-bitcoin-wallet-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/basic_wallet/bitcoin_wallet/developer/bitdubai/version_1/structure/BitcoinWalletBasicWalletAvailableBalance/CreditTest.java | 5641 | package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance;
import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterCreditException;
import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance;
import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord;
import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord;
import static com.googlecode.catchexception.CatchException.catchException;
import static com.googlecode.catchexception.CatchException.caughtException;
import static org.fest.assertions.api.Assertions.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
/**
* Created by jorgegonzalez on 2015.07.14..
*/
@RunWith(MockitoJUnitRunner.class)
public class CreditTest {
@Mock
private Database mockDatabase;
@Mock
private DatabaseTable mockWalletTable;
@Mock
private DatabaseTable mockBalanceTable;
@Mock
private DatabaseTransaction mockTransaction;
private List<DatabaseTableRecord> mockRecords;
private DatabaseTableRecord mockBalanceRecord;
private DatabaseTableRecord mockWalletRecord;
private BitcoinWalletTransactionRecord mockTransactionRecord;
private BitcoinWalletBasicWalletAvailableBalance testBalance;
@Before
public void setUpMocks(){
mockTransactionRecord = new MockBitcoinWalletTransactionRecord();
mockBalanceRecord = new MockDatabaseTableRecord();
mockWalletRecord = new MockDatabaseTableRecord();
mockRecords = new ArrayList<>();
mockRecords.add(mockBalanceRecord);
setUpMockitoRules();
}
public void setUpMockitoRules(){
when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable);
when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable);
when(mockBalanceTable.getRecords()).thenReturn(mockRecords);
when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord);
when(mockDatabase.newTransaction()).thenReturn(mockTransaction);
}
@Before
public void setUpAvailableBalance(){
testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase);
}
@Test
public void Credit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException()).isNull();
}
@Test
public void Credit_OpenDatabaseCantOpenDatabase_ThrowsCantRegisterCreditException() throws Exception{
doThrow(new CantOpenDatabaseException("MOCK", null, null, null)).when(mockDatabase).openDatabase();
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantRegisterCreditException.class);
}
@Test
public void Credit_OpenDatabaseDatabaseNotFound_ThrowsCantRegisterCreditException() throws Exception{
doThrow(new DatabaseNotFoundException("MOCK", null, null, null)).when(mockDatabase).openDatabase();
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantRegisterCreditException.class);
}
@Test
public void Credit_DaoCantCalculateBalanceException_ThrowsCantRegisterCreditException() throws Exception{
doThrow(new CantLoadTableToMemoryException("MOCK", null, null, null)).when(mockWalletTable).loadToMemory();
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantRegisterCreditException.class);
}
@Test
public void Credit_GeneralException_ThrowsCantRegisterCreditException() throws Exception{
when(mockBalanceTable.getRecords()).thenReturn(null);
catchException(testBalance).credit(mockTransactionRecord);
assertThat(caughtException())
.isNotNull()
.isInstanceOf(CantRegisterCreditException.class);
}
}
| mit |
tessellator/sherlock | Sherlock/IPipeReader.cs | 742 | using System;
namespace Sherlock
{
/// <summary>
/// A reader than can read values from a pipe.
/// </summary>
/// <typeparam name="T">The type of value to read.</typeparam>
public interface IPipeReader<T> : IDisposable
{
/// <summary>
/// Attempts to read a value from the pipe.
/// </summary>
/// <param name="item">The read value.</param>
/// <returns>A value indicating success.</returns>
bool Read(out T item);
/// <summary>
/// Closes the reader.
/// </summary>
void Close();
/// <summary>
/// Gets a value indicating whether the reader is closed.
/// </summary>
bool IsClosed { get; }
}
}
| mit |
kbaldyga/Bazy | CHANGELOG.markdown | 5623 | # Nitrogen 2.0 New Features
### New Elements, Actions, and API functions
* wf:wire can now act upon CSS classes or full JQuery Paths, not just Nitrogen elements. For example, wf:wire(".people > .address", Actions) will wire actions to any HTML elements with an "address" class underneath a "people" class. Anything on http://api.jquery.com/category/selectors/ is supported
* Added wf:replace(ID, Elements), remove an element from the page, put new elements in their place.
* Added wf:remove(ID), remove an element from the page.
* New #api{} action allows you to define a javascript method that takes parameters and will trigger a postback. Javascript parameters are automatically translated to Erlang, allowing for pattern matching.
* New #grid{} element provides a Nitrogen interface to the 960 Grid System (http://960.gs) for page layouts.
* The #upload{} event callbacks have changed. Event fires both on start of upload and when upload finishes.
* Upload callbacks take a Node parameter so that file uploads work even when a postback hits a different node.
* Many methods that used to be in 'nitrogen.erl' are now in 'wf.erl'. Also, some method signatures in wf.erl have changed.
* wf:get_page_module changed to wf:page_module
* wf:q(ID) no longer returns a list, just the value.
* wf:qs(ID) returns a list.
* wf:depickle(Data, TTL) returns undefined if expired.
### Comet Pools
* Behind the scenes, combined logic for comet and continue events. This now all goes through the same channel. You can switch async mode between comet and intervalled polling by calling wf:switch_to_comet() or wf:switch_to_polling(IntervalMS), respectively.
* Comet processes can now register in a local pool (for a specific session) or a global pool (across the entire Nitrogen cluster). All other processes in the pool are alerted when a process joins or leaves. The first process in a pool gets a special init message.
* Use wf:send(Pool, Message) or wf:send_global(Pool, Message) to broadcast a message to the entire pool.
* wf:comet_flush() is now wf:flush()
### Architectural Changes
* Nitrogen now runs _under_ other web frameworks (inets, mochiweb, yaws, misultin) using simple_bridge. In other words, you hook into the other frameworks like normal (mochiweb loop, yaws appmod, etc.) and then call nitrogen:run() from within that process.
* Handlers are the new mechanism to extend the inner parts of Nitrogen, such as session storage, authentication, etc.
* New route handler code means that pages can exist in any namespace, don't have to start with /web/... (see dynamic_route_handler and named_route_handler)
* Changed interface to elements and actions, any custom elements and actions will need tweaks.
* sync:go() recompiles any changed files more intelligently by scanning for Emakefiles.
* New ability to package Nitrogen projects as self-contained directories using rebar.
# Nitrogen 1.0 Changelog
2009-05-02
- Added changes and bugfixes by Tom McNulty.
2009-04-05
- Added a templateroot setting in .app file, courtesy of Ville Koivula.
2009-03-28
- Added file upload support.
2009-03-22
- Added alt text support to #image elements by Robert Schonberger.
- Fixed bug, 'nitrogen create (PROJECT)' now does a recursive copy of the Nitrogen support files, by Jay Doane.
- Added radio button support courtesy of Benjamin Nortier and Tom McNulty.
2009-03-16
- Added .app configuration setting to bind Nitrogen to a specific IP address, by Tom McNulty.
2009-03-08
- Added DatePicker element by Torbjorn Tornkvist.
- Upgrade to JQuery 1.3.2 and JQuery UI 1.7.
- Created initial VERSIONS file.
- Added code from Tom McNulty to expose Mochiweb loop.
- Added coverage code from Michael Mullis, including lib/coverize submodule.
- Added wf_platform:get_peername/0 code from Marius A. Eriksen.
2009-03-07
- Added code by Torbjorn Tornkvist: Basic Authentication, Hostname settings, access to HTTP Headers, and a Max Length validator.
2009-01-26
- Added Gravatar support by Dan Bravender.
2009-01-24
- Add code-level documentation around comet.
- Fix bug where comet functions would continue running after a user left the page.
- Apply patch by Tom McNulty to allow request object access within the route/1 function.
- Apply patch by Tom McNulty to correctly bind binaries.
- Apply patch by Tom McNulty for wf_tags library to correctly handle binaries.
2009-01-16
- Clean up code around timeout events. (Events that will start running after X seconds on the browser.)
2009-01-08
- Apply changes by Jon Gretar to support 'nitrogen create PROJECT' and 'nitrogen page /web/page' scripts.
- Finish putting all properties into .app file. Put request/1 into application module file.
- Add ability to route through route/1 in application module file.
- Remove need for wf_global.erl
- Start Yaws process underneath the main Nitrogen supervisor. (Used to be separate.)
2009-01-06
- Make Nitrogen a supervised OTP application, startable and stoppable via nitrogen:start() and nitrogen:stop().
- Apply changes by Dave Peticolas to fix session bugs and turn sessions into supervised processes.
2009-01-04
- Update sync module, add mirror module. These tools allow you to deploy and start applications on a bare remote node.
2009-01-03
- Allow Nitrogen to be run as an OTP application. See Quickstart project for example.
- Apply Tom McNulty's patch to create and implement wf_tags library. Emit html tags more cleanly.
- Change templates to allow multiple callbacks, and use first one that is defined. Basic idea and starter code by Tom McNulty.
- Apply Martin Scholl's patch to optimize copy_to_baserecord in wf_utils.
| mit |
dolab/gogo | response_test.go | 2566 | package gogo
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/golib/assert"
)
func Test_NewResponse(t *testing.T) {
it := assert.New(t)
recorder := httptest.NewRecorder()
response := NewResponse(recorder)
it.Implements((*Responser)(nil), response)
it.Equal(http.StatusOK, response.Status())
it.Equal(nonHeaderFlushed, response.Size())
}
func Test_ResponseWriteHeader(t *testing.T) {
it := assert.New(t)
recorder := httptest.NewRecorder()
response := NewResponse(recorder)
response.WriteHeader(http.StatusRequestTimeout)
it.Equal(http.StatusRequestTimeout, response.Status())
it.Equal(nonHeaderFlushed, response.Size())
}
func Test_ResponseFlushHeader(t *testing.T) {
it := assert.New(t)
recorder := httptest.NewRecorder()
response := NewResponse(recorder)
response.WriteHeader(http.StatusRequestTimeout)
response.FlushHeader()
it.Equal(http.StatusRequestTimeout, recorder.Code)
it.NotEqual(nonHeaderFlushed, response.Size())
// no effect after flushed headers
response.WriteHeader(http.StatusOK)
it.Equal(http.StatusOK, response.Status())
response.FlushHeader()
it.NotEqual(http.StatusOK, recorder.Code)
}
func Test_ResponseWrite(t *testing.T) {
it := assert.New(t)
recorder := httptest.NewRecorder()
hello := []byte("Hello,")
world := []byte("world!")
expected := []byte("Hello,world!")
response := NewResponse(recorder)
response.Write(hello)
response.Write(world)
it.True(response.HeaderFlushed())
it.Equal(len(expected), response.Size())
it.Equal(expected, recorder.Body.Bytes())
}
func Benchmark_ResponseWrite(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
hello := []byte("Hello,")
world := []byte("world!")
recorder := httptest.NewRecorder()
response := NewResponse(recorder)
for i := 0; i < b.N; i++ {
response.Write(hello)
response.Write(world)
}
}
func Test_ResponseHijack(t *testing.T) {
it := assert.New(t)
recorder := httptest.NewRecorder()
expected := []byte("Hello,world!")
response := NewResponse(recorder)
response.Write(expected)
it.True(response.HeaderFlushed())
it.Equal(recorder, response.(*Response).ResponseWriter)
it.Equal(len(expected), response.Size())
response.Hijack(httptest.NewRecorder())
it.False(response.HeaderFlushed())
it.NotEqual(recorder, response.(*Response).ResponseWriter)
it.Equal(nonHeaderFlushed, response.Size())
}
func Benchmark_ResponseHijack(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
recorder := httptest.NewRecorder()
response := NewResponse(recorder)
for i := 0; i < b.N; i++ {
response.Hijack(recorder)
}
}
| mit |
Hao-Wu/MEDA | Dialog3.h | 1146 | #if !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_)
#define AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Dialog3.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CDialog3 dialog
class CDialog3 : public CDialog
{
// Construction
public:
CDialog3(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CDialog3)
enum { IDD = IDD_DIALOG3 };
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDialog3)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CDialog3)
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_)
| mit |
a11ejandro/project_prototype | Capfile.rb | 501 | # Load DSL and set up stages
require 'capistrano/setup'
# Include default deployment tasks
require 'capistrano/deploy'
# Include tasks from other gems included in your Gemfile
require 'capistrano/rvm'
require 'capistrano/bundler'
require 'capistrano/rails'
require 'capistrano/rails/migrations'
require 'capistrano/nginx_unicorn'
require 'capistrano/rails/assets'
# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
| mit |
zymokey/mission-park | models/user/user.js | 541 | var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var saltRounds = 10;
var userSchema = new mongoose.Schema({
email: {
type: String,
index: {unique: true}
},
password: String,
name: String
});
//hash password
userSchema.methods.generateHash = function(password){
return bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds));
}
userSchema.methods.validPassword = function(password){
return bcrypt.compareSync(password, this.password);
}
var User = mongoose.model('User',userSchema);
module.exports = User; | mit |
lezhnev74/wolphy | app/Jobs/Job.php | 538 | <?php
namespace Wolphy\Jobs;
use Illuminate\Bus\Queueable;
abstract class Job
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "queueOn" and "delay" queue helper methods.
|
*/
use Queueable;
}
| mit |
stefanreichhart/tribe | src/scripts/stopServer.sh | 468 | #!/bin/sh
echo "Stopping web-server ..."
COUNT_PROCESS=1
while [ $COUNT_PROCESS -gt 0 ]
do
COUNT_PROCESS=`ps -Aef | grep node | grep -c server.js`
if [ $COUNT_PROCESS -gt 0 ]; then
PID_PROCESS=`ps -Aef | grep node | grep server.js | awk '{print $2}'`
if [ ! -z "$PID_PROCESS" ]; then
echo "Killing web server PID=$PID_PROCESS"
kill "$PID_PROCESS"
fi
fi
echo "Waiting on web-server to stop ..."
sleep 1
done
echo "This web-server is stopped"
exit 0 | mit |
RectorPHP/Rector | vendor/ssch/typo3-rector/stubs/t3lib_collection_StaticRecordCollection.php | 276 | <?php
namespace RectorPrefix20210615;
if (\class_exists('t3lib_collection_StaticRecordCollection')) {
return;
}
class t3lib_collection_StaticRecordCollection
{
}
\class_alias('t3lib_collection_StaticRecordCollection', 't3lib_collection_StaticRecordCollection', \false);
| mit |
Aniel/RedditImageDownloader | RedditImageDownloader.GUI/Properties/AssemblyInfo.cs | 2715 | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("RedditImageDownloader.GUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RedditImageDownloader.GUI")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
//Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie
//<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei
//in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch
//(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung
//des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile,
//sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher
//(wird verwendet, wenn eine Ressource auf der Seite
// oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.)
ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs
//(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem
// designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.)
)]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
SummaLabs/DLS | app/backend/core/models-keras-2x-api/lightweight_layers/layers_pooling.py | 7111 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
from layers_basic import LW_Layer, default_data_format
from layers_convolutional import conv_output_length
###############################################
class _LW_Pooling1D(LW_Layer):
input_dim = 3
def __init__(self, pool_size=2, strides=None, padding='valid'):
if strides is None:
strides = pool_size
assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}'
self.pool_length = pool_size
self.stride = strides
self.border_mode = padding
def get_output_shape_for(self, input_shape):
length = conv_output_length(input_shape[1], self.pool_length, self.border_mode, self.stride)
return (input_shape[0], length, input_shape[2])
class LW_MaxPooling1D(_LW_Pooling1D):
def __init__(self, pool_size=2, strides=None, padding='valid'):
super(LW_MaxPooling1D, self).__init__(pool_size, strides, padding)
class LW_AveragePooling1D(_LW_Pooling1D):
def __init__(self, pool_size=2, strides=None, padding='valid'):
super(LW_AveragePooling1D, self).__init__(pool_size, strides, padding)
###############################################
class _LW_Pooling2D(LW_Layer):
def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'):
if data_format == 'default':
data_format = default_data_format
assert data_format in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}'
self.pool_size = tuple(pool_size)
if strides is None:
strides = self.pool_size
self.strides = tuple(strides)
assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}'
self.border_mode = padding
self.dim_ordering = data_format
def get_output_shape_for(self, input_shape):
if self.dim_ordering == 'channels_first':
rows = input_shape[2]
cols = input_shape[3]
elif self.dim_ordering == 'channels_last':
rows = input_shape[1]
cols = input_shape[2]
else:
raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
rows = conv_output_length(rows, self.pool_size[0], self.border_mode, self.strides[0])
cols = conv_output_length(cols, self.pool_size[1], self.border_mode, self.strides[1])
if self.dim_ordering == 'channels_first':
return (input_shape[0], input_shape[1], rows, cols)
elif self.dim_ordering == 'channels_last':
return (input_shape[0], rows, cols, input_shape[3])
else:
raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
class LW_MaxPooling2D(_LW_Pooling2D):
def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'):
super(LW_MaxPooling2D, self).__init__(pool_size, strides, padding, data_format)
class LW_AveragePooling2D(_LW_Pooling2D):
def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'):
super(LW_AveragePooling2D, self).__init__(pool_size, strides, padding, data_format)
###############################################
class _LW_Pooling3D(LW_Layer):
def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'):
if dim_ordering == 'default':
dim_ordering = default_data_format
assert dim_ordering in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}'
self.pool_size = tuple(pool_size)
if strides is None:
strides = self.pool_size
self.strides = tuple(strides)
assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}'
self.border_mode = border_mode
self.dim_ordering = dim_ordering
def get_output_shape_for(self, input_shape):
if self.dim_ordering == 'channels_first':
len_dim1 = input_shape[2]
len_dim2 = input_shape[3]
len_dim3 = input_shape[4]
elif self.dim_ordering == 'channels_last':
len_dim1 = input_shape[1]
len_dim2 = input_shape[2]
len_dim3 = input_shape[3]
else:
raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
len_dim1 = conv_output_length(len_dim1, self.pool_size[0], self.border_mode, self.strides[0])
len_dim2 = conv_output_length(len_dim2, self.pool_size[1], self.border_mode, self.strides[1])
len_dim3 = conv_output_length(len_dim3, self.pool_size[2], self.border_mode, self.strides[2])
if self.dim_ordering == 'channels_first':
return (input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3)
elif self.dim_ordering == 'channels_last':
return (input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4])
else:
raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
class LW_MaxPooling3D(_LW_Pooling3D):
def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'):
super(LW_MaxPooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering)
class LW_AveragePooling3D(_LW_Pooling3D):
def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'):
super(LW_AveragePooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering)
###############################################
class _LW_GlobalPooling1D(LW_Layer):
def __init__(self):
pass
def get_output_shape_for(self, input_shape):
return (input_shape[0], input_shape[2])
class LW_GlobalAveragePooling1D(_LW_GlobalPooling1D):
pass
class LW_GlobalMaxPooling1D(_LW_GlobalPooling1D):
pass
###############################################
class _LW_GlobalPooling2D(LW_Layer):
def __init__(self, data_format='default'):
if data_format == 'default':
data_format = default_data_format
self.dim_ordering = data_format
def get_output_shape_for(self, input_shape):
if self.dim_ordering == 'channels_last':
return (input_shape[0], input_shape[3])
else:
return (input_shape[0], input_shape[1])
class LW_GlobalAveragePooling2D(_LW_GlobalPooling2D):
pass
class LW_GlobalMaxPooling2D(_LW_GlobalPooling2D):
pass
###############################################
class _LW_GlobalPooling3D(LW_Layer):
def __init__(self, data_format='default'):
if data_format == 'default':
data_format = default_data_format
self.dim_ordering = data_format
def get_output_shape_for(self, input_shape):
if self.dim_ordering == 'channels_last':
return (input_shape[0], input_shape[4])
else:
return (input_shape[0], input_shape[1])
class LW_GlobalAveragePooling3D(_LW_GlobalPooling3D):
pass
class LW_GlobalMaxPooling3D(_LW_GlobalPooling3D):
pass
###############################################
if __name__ == '__main__':
pass | mit |
nac13k/iAdmin | db/migrate/20140408042944_create_event_types.rb | 172 | class CreateEventTypes < ActiveRecord::Migration
def change
create_table :event_types do |t|
t.string :name, :limit => 80
t.timestamps
end
end
end
| mit |
kangseung/JSTrader | include/mongoc-win/libbson/bson-compat.h | 3827 | /*
* Copyright 2013 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BSON_COMPAT_H
#define BSON_COMPAT_H
#if !defined (BSON_INSIDE) && !defined (BSON_COMPILATION)
# error "Only <bson.h> can be included directly."
#endif
#if defined(__MINGW32__)
# if defined(__USE_MINGW_ANSI_STDIO)
# if __USE_MINGW_ANSI_STDIO < 1
# error "__USE_MINGW_ANSI_STDIO > 0 is required for correct PRI* macros"
# endif
# else
# define __USE_MINGW_ANSI_STDIO 1
# endif
#endif
#include "bson-config.h"
#include "bson-macros.h"
#ifdef BSON_OS_WIN32
# if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600)
# undef _WIN32_WINNT
# endif
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0600
# endif
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <winsock2.h>
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# undef WIN32_LEAN_AND_MEAN
# else
# include <windows.h>
# endif
#include <direct.h>
#include <io.h>
#endif
#ifdef BSON_OS_UNIX
# include <unistd.h>
# include <sys/time.h>
#endif
#include "bson-macros.h"
#include <errno.h>
#include <ctype.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
BSON_BEGIN_DECLS
#ifdef _MSC_VER
# include "bson-stdint-win32.h"
# ifndef __cplusplus
/* benign redefinition of type */
# pragma warning (disable :4142)
# ifndef _SSIZE_T_DEFINED
# define _SSIZE_T_DEFINED
typedef SSIZE_T ssize_t;
# endif
typedef SIZE_T size_t;
# pragma warning (default :4142)
# else
/*
* MSVC++ does not include ssize_t, just size_t.
* So we need to synthesize that as well.
*/
# pragma warning (disable :4142)
# ifndef _SSIZE_T_DEFINED
# define _SSIZE_T_DEFINED
typedef SSIZE_T ssize_t;
# endif
# pragma warning (default :4142)
# endif
# define PRIi32 "d"
# define PRId32 "d"
# define PRIu32 "u"
# define PRIi64 "I64i"
# define PRId64 "I64i"
# define PRIu64 "I64u"
#else
# include "bson-stdint.h"
# include <inttypes.h>
#endif
#if defined(__MINGW32__) && ! defined(INIT_ONCE_STATIC_INIT)
# define INIT_ONCE_STATIC_INIT RTL_RUN_ONCE_INIT
typedef RTL_RUN_ONCE INIT_ONCE;
#endif
#ifdef BSON_HAVE_STDBOOL_H
# include <stdbool.h>
#elif !defined(__bool_true_false_are_defined)
# ifndef __cplusplus
typedef signed char bool;
# define false 0
# define true 1
# endif
# define __bool_true_false_are_defined 1
#endif
#if defined(__GNUC__)
# if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
# define bson_sync_synchronize() __sync_synchronize()
# elif defined(__i386__ ) || defined( __i486__ ) || defined( __i586__ ) || \
defined( __i686__ ) || defined( __x86_64__ )
# define bson_sync_synchronize() asm volatile("mfence":::"memory")
# else
# define bson_sync_synchronize() asm volatile("sync":::"memory")
# endif
#elif defined(_MSC_VER)
# define bson_sync_synchronize() MemoryBarrier()
#endif
#if !defined(va_copy) && defined(__va_copy)
# define va_copy(dst,src) __va_copy(dst, src)
#endif
#if !defined(va_copy)
# define va_copy(dst,src) ((dst) = (src))
#endif
BSON_END_DECLS
#endif /* BSON_COMPAT_H */
| mit |
walf443/empty_port | lib/empty_port.rb | 1760 | require "empty_port/version"
require 'socket'
require 'timeout'
# ## Example
# require 'empty_port'
# class YourServerTest < Test::Unit::TestCase
# def setup
# @port = EmptyPort.get
# @server_pid = Process.fork do
# server = TCPServer.open('localhost', @port)
# end
# EmptyPort.wait(@port)
# end
#
# def test_something_with_server
# end
#
# def teardown
# Process.kill(@server_pid)
# end
# end
#
module EmptyPort
class NotFoundException < Exception; end
module ClassMethods
# SEE http://www.iana.org/assignments/port-numbers
MIN_PORT_NUMBER = 49152
MAX_PORT_NUMBER = 65535
# get an empty port except well-known-port.
def get
random_port = MIN_PORT_NUMBER + ( rand() * 1000 ).to_i
while random_port < MAX_PORT_NUMBER
begin
sock = TCPSocket.open('localhost', random_port)
sock.close
rescue Errno::ECONNREFUSED => e
return random_port
end
random_port += 1
end
raise NotFoundException
end
def listened?(port)
begin
sock = TCPSocket.open('localhost', port)
sock.close
return true
rescue Errno::ECONNREFUSED
return false
end
end
DEFAULT_TIMEOUT = 2
DEFAULT_INTERVAL = 0.1
def wait(port, options={})
options[:timeout] ||= DEFAULT_TIMEOUT
options[:interval] ||= DEFAULT_INTERVAL
timeout(options[:timeout]) do
start = Time.now
loop do
if self.listened?(port)
finished = Time.now
return finished - start
end
sleep(options[:interval])
end
end
end
end
extend ClassMethods
end
| mit |
wunderlist/bilder-aws | lib/defaults.js | 133 | module.exports = {
'throttle': 10,
'hash': true,
'gzip': false,
'baseDir': 'public',
'buildDir': 'build',
'prefix': ''
}; | mit |
antodoms/beaconoid | app/assets/stylesheets/admin.css | 3884 | .vertical-center {
min-height: 100%; /* Fallback for browsers do NOT support vh unit */
min-height: 100vh; /* These two lines are counted as one :-) */
display: flex;
align-items: center;
}
@media (min-width: 768px){
#wrapper {/*padding-right: 225px;*/ padding-left: 0;}
.side-nav{right: 0;left: auto;}
}
/*!
* Start Bootstrap - SB Admin (http://startbootstrap.com/)
* Copyright 2013-2016 Start Bootstrap
* Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE)
*/
/* Global Styles */
body {
background-color: #222;
}
#wrapper {
padding-left: 0;
}
#page-wrapper {
width: 100%;
padding: 0;
background-color: #fff;
}
.huge {
font-size: 50px;
line-height: normal;
}
@media(min-width:768px) {
#wrapper {
padding-left: 225px;
}
#page-wrapper {
padding: 10px;
margin-top: 20px;
}
}
/* Top Navigation */
.top-nav {
padding: 0 15px;
}
.top-nav>li {
display: inline-block;
float: left;
}
.top-nav>li>a {
padding-top: 15px;
padding-bottom: 15px;
line-height: 20px;
color: #999;
}
.top-nav>li>a:hover,
.top-nav>li>a:focus,
.top-nav>.open>a,
.top-nav>.open>a:hover,
.top-nav>.open>a:focus {
color: #fff;
background-color: #000;
}
.top-nav>.open>.dropdown-menu {
float: left;
position: absolute;
margin-top: 0;
border: 1px solid rgba(0,0,0,.15);
border-top-left-radius: 0;
border-top-right-radius: 0;
background-color: #fff;
-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
.top-nav>.open>.dropdown-menu>li>a {
white-space: normal;
}
ul.message-dropdown {
padding: 0;
max-height: 250px;
overflow-x: hidden;
overflow-y: auto;
}
li.message-preview {
width: 275px;
border-bottom: 1px solid rgba(0,0,0,.15);
}
li.message-preview>a {
padding-top: 15px;
padding-bottom: 15px;
}
li.message-footer {
margin: 5px 0;
}
ul.alert-dropdown {
width: 200px;
}
.alert-danger {
margin-top: 50px;
}
/* Side Navigation */
@media(min-width:768px) {
.side-nav {
position: fixed;
top: 51px;
/* left: 225px;*/
left: 0px;
width: 225px;
/* margin-left: -225px;*/
border: none;
border-radius: 0;
overflow-y: auto;
background-color: #222;
bottom: 0;
overflow-x: hidden;
padding-bottom: 40px;
}
.side-nav>li>a {
width: 225px;
}
.side-nav li a:hover,
.side-nav li a:focus {
outline: none;
background-color: #000 !important;
}
}
.side-nav>li>ul {
padding: 0;
}
.side-nav>li>ul>li>a {
display: block;
padding: 10px 15px 10px 38px;
text-decoration: none;
color: #999;
}
.side-nav>li>ul>li>a:hover {
color: #fff;
}
/* Flot Chart Containers */
.flot-chart {
display: block;
height: 400px;
}
.flot-chart-content {
width: 100%;
height: 100%;
}
/* Custom Colored Panels */
.huge {
font-size: 40px;
}
.panel-green {
border-color: #5cb85c;
}
.panel-green > .panel-heading {
border-color: #5cb85c;
color: #fff;
background-color: #5cb85c;
}
.panel-green > a {
color: #5cb85c;
}
.panel-green > a:hover {
color: #3d8b3d;
}
.panel-red {
border-color: #d9534f;
}
.panel-red > .panel-heading {
border-color: #d9534f;
color: #fff;
background-color: #d9534f;
}
.panel-red > a {
color: #d9534f;
}
.panel-red > a:hover {
color: #b52b27;
}
.panel-yellow {
border-color: #f0ad4e;
}
.panel-yellow > .panel-heading {
border-color: #f0ad4e;
color: #fff;
background-color: #f0ad4e;
}
.panel-yellow > a {
color: #f0ad4e;
}
.panel-yellow > a:hover {
color: #df8a13;
}
.navbar-nav > li > ul > li.active {
background: rgba(9, 9, 9, 0.57);
} | mit |
llinmeng/learn-fe | src/ex/crazy-fe-book/2017/H5/03/3-1-4.html | 351 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用 button 定义按钮</title>
</head>
<body>
<form action="http://www.baidu.com" method="get">
<button type="button"><b>提交</b></button><br/>
<button type="submit"><img sec="./img/3.jpg" alt="图片"></button><br/>
</form>
</body>
</html>
| mit |
alexlitel/congresstweets | _posts/2019-08-08--tweets.md | 115 | ---
layout: post
title: Tweets
date: 2019-08-08
summary: These are the tweets for August 8, 2019.
categories:
---
| mit |
date-fns/date-fns | src/locale/te/_lib/formatRelative/index.ts | 557 | import type { FormatRelativeFn } from '../../../types'
// Source: https://www.unicode.org/cldr/charts/32/summary/te.html
const formatRelativeLocale = {
lastWeek: "'గత' eeee p", // CLDR #1384
yesterday: "'నిన్న' p", // CLDR #1393
today: "'ఈ రోజు' p", // CLDR #1394
tomorrow: "'రేపు' p", // CLDR #1395
nextWeek: "'తదుపరి' eeee p", // CLDR #1386
other: 'P',
}
const formatRelative: FormatRelativeFn = (token, _date, _baseDate, _options) =>
formatRelativeLocale[token]
export default formatRelative
| mit |
afh/yabab | pre-populate.sql | 238 | INSERT INTO customers(id, name)
VALUES (1, 'Jane Woods');
INSERT INTO customers(id, name)
VALUES (2, 'Michael Li');
INSERT INTO customers(id, name)
VALUES (3, 'Heidi Hasselbach');
INSERT INTO customers(id, name)
VALUES (4, 'Rahul Pour');
| mit |
LedgerHQ/lib-ledger-core | core/src/wallet/bitcoin/keychains/BitcoinLikeKeychain.hpp | 4962 | /*
*
* BitcoinLikeKeychain
* ledger-core
*
* Created by Pierre Pollastri on 17/01/2017.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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.
*
*/
#ifndef LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP
#define LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP
#include "../../../bitcoin/BitcoinLikeExtendedPublicKey.hpp"
#include <string>
#include <vector>
#include <utils/DerivationScheme.hpp>
#include "../../../utils/Option.hpp"
#include "../../../preferences/Preferences.hpp"
#include "../../../api/Configuration.hpp"
#include "../../../api/DynamicObject.hpp"
#include <api/Currency.hpp>
#include <api/AccountCreationInfo.hpp>
#include <api/ExtendedKeyAccountCreationInfo.hpp>
#include <api/Keychain.hpp>
#include <bitcoin/BitcoinLikeAddress.hpp>
namespace ledger {
namespace core {
class BitcoinLikeKeychain: public api::Keychain {
public:
enum KeyPurpose {
RECEIVE, CHANGE
};
public:
using Address = std::shared_ptr<BitcoinLikeAddress>;
BitcoinLikeKeychain(
const std::shared_ptr<api::DynamicObject>& configuration,
const api::Currency& params,
int account,
const std::shared_ptr<Preferences>& preferences);
virtual bool markAsUsed(const std::vector<std::string>& addresses);
virtual bool markAsUsed(const std::string& address, bool needExtendKeychain = true);
virtual bool markPathAsUsed(const DerivationPath& path, bool needExtendKeychain = true) = 0;
virtual std::vector<Address> getAllObservableAddresses(uint32_t from, uint32_t to) = 0;
virtual std::vector<std::string> getAllObservableAddressString(uint32_t from, uint32_t to) = 0;
virtual std::vector<Address> getAllObservableAddresses(KeyPurpose purpose, uint32_t from, uint32_t to) = 0;
virtual Address getFreshAddress(KeyPurpose purpose) = 0;
virtual std::vector<Address> getFreshAddresses(KeyPurpose purpose, size_t n) = 0;
virtual Option<KeyPurpose> getAddressPurpose(const std::string& address) const = 0;
virtual Option<std::string> getAddressDerivationPath(const std::string& address) const = 0;
virtual bool isEmpty() const = 0;
int getAccountIndex() const;
const api::BitcoinLikeNetworkParameters& getNetworkParameters() const;
const api::Currency& getCurrency() const;
virtual Option<std::vector<uint8_t>> getPublicKey(const std::string& address) const = 0;
std::shared_ptr<api::DynamicObject> getConfiguration() const;
const DerivationScheme& getDerivationScheme() const;
const DerivationScheme& getFullDerivationScheme() const;
std::string getKeychainEngine() const;
bool isSegwit() const;
bool isNativeSegwit() const;
virtual std::string getRestoreKey() const = 0;
virtual int32_t getObservableRangeSize() const = 0;
virtual bool contains(const std::string& address) const = 0;
virtual std::vector<Address> getAllAddresses() = 0;
virtual int32_t getOutputSizeAsSignedTxInput() const = 0;
static bool isSegwit(const std::string &keychainEngine);
static bool isNativeSegwit(const std::string &keychainEngine);
std::shared_ptr<Preferences> getPreferences() const;
protected:
DerivationScheme& getDerivationScheme();
private:
const api::Currency _currency;
DerivationScheme _scheme;
DerivationScheme _fullScheme;
int _account;
std::shared_ptr<Preferences> _preferences;
std::shared_ptr<api::DynamicObject> _configuration;
};
}
}
#endif //LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP
| mit |
asimo124/MLSSite | src/AppBundle/Repository/Buyers_PropertiesRepository.php | 257 | <?php
namespace AppBundle\Repository;
/**
* Buyers_PropertiesRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class Buyers_PropertiesRepository extends \Doctrine\ORM\EntityRepository
{
}
| mit |
spruceboy/jays_geo_tools | examples/sample_handler_for_do_several_at_once.rb | 210 | #!/usr/bin/env ruby
#Example handler file..
infile = ARGV.first
outfile = File.basename(infile, ".tif") + ".jpg.tif"
system("~/cm/processing_scripts/rgb_to_jpeg_tif.rb --internal-mask #{infile} #{outfile}")
| mit |
inlinevoid/Overust | Steam/Models/PlayerBans.cs | 2083 | using Newtonsoft.Json;
using ProtoBuf;
using ITK.ModelManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Steam.Models
{
[Model("SteamPlayerBans")]
[ProtoContract]
[JsonObject(MemberSerialization.OptIn)]
public class PlayerBans
{
/// <summary>
/// A string containing the player's 64 bit ID.
/// </summary>
[JsonProperty("SteamID")]
[ProtoMember(1, IsRequired = true)]
public ulong SteamId {get; set;}
/// <summary>
/// Boolean indicating whether or not the player is banned from Community
/// </summary>
[JsonProperty("CommunityBanned")]
[ProtoMember(2)]
public bool IsCommunityBanned {get; set;}
/// <summary>
/// Boolean indicating whether or not the player has VAC bans on record.
/// </summary>
[JsonProperty("VACBanned")]
[ProtoMember(3)]
public bool IsVACBanned {get; set;}
/// <summary>
/// Amount of VAC bans on record.
/// </summary>
[JsonProperty("NumberOfVACBans")]
[ProtoMember(4)]
public int VACBanCount {get; set;}
/// <summary>
/// Amount of days since last ban.
/// </summary>
[JsonProperty("DaysSinceLastBan")]
[ProtoMember(5)]
public int DaysSinceLastBan {get; set;}
/// <summary>
/// String containing the player's ban status in the economy. If the player has no bans on record the string will be "none", if the player is on probation it will say "probation", and so forth.
/// </summary>
[JsonProperty("EconomyBan")]
[ProtoMember(6)]
public string EconomyBan {get; set;}
public override int GetHashCode()
{
return SteamId.GetHashCode();
}
public override bool Equals(object obj)
{
var other = obj as PlayerBans;
return other != null && SteamId.Equals(other.SteamId);
}
}
} | mit |
bluecitymoon/demo-swift-ios | demo-swift/Quickblox.framework/Versions/A/Headers/QBUsersBusiness.h | 128 | /*
* Business.h
* UsersService
*
* Copyright 2011 QuickBlox team. All rights reserved.
*
*/
#import "QBUsersModels.h" | mit |
samervin/blog.samerv.in | _posts/link/2013-09-17-espn-picture.md | 332 | ---
layout: post
title: ESPN took a picture of me
categories: link
---
Check [this link](http://espn.go.com/college-football/story/_/id/9685394/how-do-nebraska-fans-feel-bo-pelini-recent-behavior) for some story about Bo Pelini's goofing off, and -- look there in the last photo! -- it's some goofball in a Nebraska trilby.
| mit |
firemuzzy/GFChaos | TestChaosApp/TestChaosApp/GFTestAppDelegate.h | 294 | //
// GFTestAppDelegate.h
// TestChaosApp
//
// Created by Michael Charkin on 2/26/14.
// Copyright (c) 2014 GitFlub. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GFTestAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| mit |
chinakite/wukong | data/datas/modules.js | 545 | var modules = {
"success" : [
{id: 1, name:"控制台", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'},
{id: 2, name:"服务中心", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}
],
"error" : {
code : "0200-ERROR", msg : "There are some errors occured."
}
}
module.exports = {
"modules": modules
}
| mit |
billba/botchat | packages/embed/hostDevServer.js | 1094 | const {
createServer,
plugins: { queryParser, serveStatic }
} = require('restify');
const { join } = require('path');
const fetch = require('node-fetch');
const proxy = require('http-proxy-middleware');
const { PORT = 5000 } = process.env;
const server = createServer();
server.use(queryParser());
server.get('/', async (req, res, next) => {
if (!req.query.b) {
const tokenRes = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', {
headers: {
origin: 'http://localhost:5000'
},
method: 'POST'
});
if (!tokenRes.ok) {
return res.send(500);
}
const { token } = await tokenRes.json();
return res.send(302, null, {
location: `/?b=webchat-mockbot&t=${encodeURIComponent(token)}`
});
}
return serveStatic({
directory: join(__dirname, 'dist'),
file: 'index.html'
})(req, res, next);
});
server.get('/embed/*/config', proxy({ changeOrigin: true, target: 'https://webchat.botframework.com/' }));
server.listen(PORT, () => console.log(`Embed dev server is listening to port ${PORT}`));
| mit |
huangfeng19820712/hfast | example/view/tree/treeAndTable.js | 2606 | /**
* @author: * @date: 2016/1/21
*/
define(["core/js/layout/Panel"],
function (Panel) {
var view = Panel.extend({
/*Panel的配置项 start*/
title:"表单-",
help:"内容",
brief:"摘要",
/*Panel 配置 End*/
oninitialized:function(triggerEvent){
this._super();
this.mainRegion={
comXtype:$Component.TREE,
comConf:{
data:[this.getModuleTree("core/js/base/AbstractView")],
}
};
var that = this;
this.footerRegion = {
comXtype: $Component.TOOLSTRIP,
comConf: {
/*Panel的配置项 start*/
textAlign: $TextAlign.RIGHT,
items: [{
text: "展开所有节点",
onclick: function (e) {
that.getMainRegionRef().getComRef().expandAll();
},
},{
text: "折叠所有节点",
onclick: function (e) {
that.getMainRegionRef().getComRef().collapseAll();
},
}]
/*Panel 配置 End*/
}
};
},
getModuleTree:function(moduleName,arr){
var va = window.rtree.tree[moduleName];
var tree = {title: moduleName};
if(!arr){
arr = [];
}else{
if(_.contains(arr,moduleName)){
return false;
}
}
arr.push(moduleName);
if(va&&va.deps&&va.deps.length>0){
tree.children = [];
tree.folder=true;
for(var i=0;i<va.deps.length;i++){
var newTree = this.getModuleTree(va.deps[i],arr);
if(newTree){
tree.children.push(newTree);
}else{
if(!tree.count){
tree.count = 0;
}
tree.count++;
}
}
}
return tree;
}
});
return view;
});
| mit |
VelocityWebworks/django-media-albums | README.md | 6320 | # Django Media Albums
[](https://travis-ci.org/VelocityWebworks/django-media-albums)
This app is used to create albums consisting of any combination of the
following:
* Photos
* Video files
* Audio files
This app also optionally allows regular (non-staff) users to upload photos.
This app requires Django 1.8, 1.9, 1.10, or 1.11.
## Installation
### Step 1 of 5: Install the required packages
Install using pip:
```bash
pip install django-media-albums
```
If you will be using the templates that come with this app, also install these
packages using pip:
```bash
pip install django-bootstrap-pagination sorl-thumbnail
```
If you will be allowing regular (non-staff) users to upload photos and will be
using the `upload.html` template that comes with this app, also install the
`django-crispy-forms` package using pip:
```bash
pip install django-crispy-forms
```
### Step 2 of 5: Update `settings.py`
Make sure the following settings are all configured the way you want them in
your `settings.py`:
```
MEDIA_ROOT
MEDIA_URL
STATIC_ROOT
STATIC_URL
```
If you will be allowing regular (non-staff) users to upload photos, you will
also need to have the `DEFAULT_FROM_EMAIL` setting present in your
`settings.py` (for the notification email that gets sent out when a user
uploads a photo).
Add `'media_albums'` to your `settings.py` INSTALLED_APPS:
```python
INSTALLED_APPS = (
...
'media_albums',
...
)
```
If you will be using the templates that come with this app, also add the
following to your `settings.py` INSTALLED_APPS:
```python
INSTALLED_APPS = (
...
'bootstrap_pagination',
'sorl.thumbnail',
...
)
```
If you will be allowing regular (non-staff) users to upload photos and will be
using the `upload.html` template that comes with this app, also add
`'crispy_forms'` to your `settings.py` INSTALLED_APPS and make sure the
`CRISPY_TEMPLATE_PACK` setting is configured the way you want it:
```python
INSTALLED_APPS = (
...
'crispy_forms',
...
)
CRISPY_TEMPLATE_PACK = 'bootstrap3'
```
If you will be enabling audio and/or video and will be using the templates that
come with this app, also enable the
`'django.template.context_processors.media'` context processor:
```python
TEMPLATES = [
...
{
...
'OPTIONS': {
...
'context_processors': [
...
'django.template.context_processors.media',
...
],
...
},
...
},
...
]
```
### Step 3 of 5: Update `urls.py`
Create a URL pattern in your `urls.py`:
```python
from django.conf.urls import include, url
urlpatterns = [
...
url(r'^media-albums/', include('media_albums.urls')),
...
]
```
### Step 4 of 5: Add the database tables
Run the following command:
```bash
python manage.py migrate
```
### Step 5 of 5: Update your project's `base.html` template (if necessary)
If you will be using the templates that come with this app, make sure your
project has a `base.html` template and that it has these blocks:
```
content
extra_styles
```
## Configuration
To override any of the default settings, create a dictionary named
`MEDIA_ALBUMS` in your `settings.py` with each setting you want to override.
For example, if you wanted to enable audio and video, but leave all of the
other settings alone, you would add this to your `settings.py`:
```python
MEDIA_ALBUMS = {
'audio_files_enabled': True,
'video_files_enabled': True,
}
```
These are the settings:
### `photos_enabled` (default: `True`)
When set to `True`, albums may contain photos.
### `audio_files_enabled` (default: `False`)
When set to `True`, albums may contain audio files.
### `audio_files_format1_extension` (default: `'mp3'`)
When an audio file is uploaded, the "Audio file 1" field must have this
extension. This setting is only relevant if `audio_files_enabled` is set to
`True`.
### `audio_files_format2_extension` (default: `'ogg'`)
When an audio file is uploaded, the "Audio file 2" field must have this
extension. This setting is only relevant if `audio_files_enabled` is set to
`True`.
### `audio_files_format2_required` (default: `False`)
When set to `True`, the "Audio file 2" field will be marked as required. This
setting is only relevant if `audio_files_enabled` is set to `True`.
### `video_files_enabled` (default: `False`)
When set to `True`, albums may contain video files.
### `video_files_format1_extension` (default: `'mp4'`)
When an video file is uploaded, the "Video file 1" field must have this
extension. This setting is only relevant if `video_files_enabled` is set to
`True`.
### `video_files_format2_extension` (default: `'webm'`)
When an video file is uploaded, the "Video file 2" field must have this
extension. This setting is only relevant if `video_files_enabled` is set to
`True`.
### `video_files_format2_required` (default: `False`)
When set to `True`, the "Video file 2" field will be marked as required. This
setting is only relevant if `video_files_enabled` is set to `True`.
### `user_uploaded_photos_enabled` (default: `False`)
When set to `True`, regular (non-staff) users may upload photos. However, they
still must be approved by a staff user.
### `user_uploaded_photos_login_required` (default: `True`)
When set to `True`, regular (non-staff) users may only upload photos if they
are logged in. This setting is only relevant if `user_uploaded_photos_enabled`
is set to `True`.
### `user_uploaded_photos_album_name` (default: `'User Photos'`)
When a staff user approves a photo uploaded by a regular (non-staff) user, the
photo will be added to the album with this name. This setting is only relevant
if `user_uploaded_photos_enabled` is set to `True`.
### `user_uploaded_photos_album_slug` (default: `'user-photos'`)
When a staff user approves a photo uploaded by a regular (non-staff) user, the
photo will be added to the album with this slug. This setting is only relevant
if `user_uploaded_photos_enabled` is set to `True`.
### `paginate_by` (default: `10`)
This setting determines how many items can be on a single page. This applies to
the list of albums as well as the list of items within albums.
| mit |
stivalet/PHP-Vulnerability-test-suite | XSS/CWE_79/safe/CWE_79__array-GET__CAST-func_settype_float__Unsafe_use_untrusted_data-comment.php | 1367 | <!--
Safe sample
input : get the $_GET['userData'] in an array
sanitize : settype (float)
File : unsafe, use of untrusted data in a comment
-->
<!--Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.-->
<!DOCTYPE html>
<html>
<head>
<!--
<?php
$array = array();
$array[] = 'safe' ;
$array[] = $_GET['userData'] ;
$array[] = 'safe' ;
$tainted = $array[1] ;
if(settype($tainted, "float"))
$tainted = $tainted ;
else
$tainted = 0.0 ;
echo $tainted ;
?>
-->
</head>
<body>
<h1>Hello World!</h1>
</body>
</html> | mit |
walalm/MVC-Azure-Explorer | MVC_Azure_Explorer/MVC_Azure_Explorer/Scripts/UtilsFileManager.js | 2111 | $('#modalUploader').on('show.bs.modal', function (event) {
var uploader = new qq.FileUploaderBasic({
element: document.getElementById('file-uploader-demo1'),
button: document.getElementById('areaSubir'),
action: '/Files/Upload',
params: { ruta: $('#RutaActual').val() },
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'],
multiple: false,
onComplete: function (id, fileName, responseJSON) {
$.gritter.add({
title: 'Upload file',
text: responseJSON.message
});
},
onSubmit: function (id, fileName) {
var strHtml = "<li>" + fileName + "</li>";
$("#dvxArchivos").append(strHtml);
}
});
});
$('#modalUploader').on('hidden.bs.modal', function () {
RecargarRuta();
})
function AbrirCarpeta(pCarpeta) {
$("#RutaSolicitada").val(pCarpeta);
$("#frmMain").submit();
}
function AbrirRuta(pCarpeta) {
$("#RutaSolicitada").val(pCarpeta);
$("#frmMain").submit();
}
function RecargarRuta() {
AbrirCarpeta($("#RutaActual").val());
}
function EliminarArchivo(pRuta) {
if (confirm("Are you sure that want to delete this file?")) {
$.gritter.add({
title: 'Delete file',
text: "File deleted"
});
$("#ArchivoParaEliminar").val(pRuta);
AbrirCarpeta($("#RutaActual").val());
}
}
function SubirNivel() {
if ($("#TieneSuperior").val() == "1") {
var strRutaAnterior = $("#RutaSuperior").val();
AbrirRuta(strRutaAnterior);
}
}
function IrInicio() {
AbrirRuta($("#RutaRaiz").val());
}
function AbrirDialogoArchivo() {
$("#modalUploader").modal();
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
| mit |
meteorhacks/sikka | lib/client/core.js | 631 | // setToken when re-connecting
var originalReconnect = Meteor.connection.onReconnect;
Meteor.connection.onReconnect = function() {
setToken();
if(originalReconnect) {
originalReconnect();
}
};
if(Meteor.status().connected) {
setToken();
}
function setToken() {
var firewallHumanToken = Cookie.get('sikka-human-token');
Meteor.call('setSikkaHumanToken', firewallHumanToken);
}
// reloading the page
window.sikkaCommands = sikkaCommands = new Mongo.Collection('sikka-commands');
sikkaCommands.find({}).observe({
added: function(command) {
if(command._id === "reload") {
location.reload();
}
}
}); | mit |
yorthehunter/humblekit | vendor/assets/bower_components/Cortana/_footer.html | 2093 | <% nameScope = @config['name_scope'] %>
</div>
</div>
</div>
<footer class="cortana-footer">
Build with love using Trulia's <a href="https://github.com/trulia/hologram">Hologram</a> and <a href="https://github.com/Yago/Cortana">Cortana</a> !
</footer>
</div>
<script src="theme-build/js/vendors.min.js"></script>
<script type="text/javascript">
var jQuery_no_conflict = $.noConflict(true);
</script>
<script src="theme-build/js/main.js"></script>
<script type="text/javascript">
function TypeaheadCtrl($scope) {
$scope.selected = undefined;
$scope.searchData =
<%= "[" %>
<% @pages.each do |file_name, page| %>
<% if not page[:blocks].empty? %>
<% page[:blocks].each do |block| %>
<% file_path = block[:categories][0].to_s.gsub(' ', '_').downcase + '.html' %>
<% file_id = "#"+block[:name].to_s %>
<%= "{" %>
<%= "\"title\": \""+block[:title].to_s+"\"," %>
<%= "\"breadcrumb\": \""+block[:categories][0].to_s+" > "+block[:title]+"\"," %>
<%= "\"path\": \""+file_path+file_id+"\"" %>
<%= "}," %>
<% end %>
<% end %>
<% end %>
<%= "{}]" %>;
$scope.onSelect = function ($item, $model, $label) {
window.location.replace($item.path);
};
}
</script>
<script type="text/ng-template" id="customTemplate.html">
<a href="{{match.model.path}}">
<p class="cortana-search-title">{{match.model.title}}</p>
<p class="cortana-search-path">{{match.model.breadcrumb}}</p>
</a>
</script>
<% if @config['js_include'].to_s.strip.length != 0 %>
<% @config['js_include'].each do |js| %>
<script type="text/javascript" src="<%= js %>"></script>
<% end %>
<% end %>
<!-- Source Components -->
<% if @config['components_include'].to_s.strip.length != 0 %>
<% @config['components_include'].each do |component| %>
<link rel="import" href="<%= component %>">
<% end %>
<% end %>
</body>
</html>
| mit |
rrbemo/cppLinkedList | ccpLinkedList/rbLinkedList.h | 835 | //
// rbLinkedList.h
// rbLinkedList
//
// Created by Ryan Bemowski on 4/6/15.
//
#pragma once
#include <string>
struct Node
{
int key;
Node *next;
};
class rbLinkedList
{
public:
/** Constructor for the rbLinkedList class.
*/
rbLinkedList();
/** Deconstructor for the rbLinkedList class.
*/
~rbLinkedList();
/** Determine if the collection is empty or not.
* @return: A bool that will be true if the collection is empty and false
* otherwise.
*/
bool IsEmpty();
/** Determine the number of nodes within the linked list.
* @return: An integer that represents the number of nodes between the head
* and tail nodes.
*/
int Size();
void AddKey(int key);
void RemoveKey(int key);
std::string ToString();
private:
Node *h_;
Node *z_;
};
| mit |
podkovyrin/UIViewController-KeyboardAdditions | Example/UIViewController-KeyboardAdditions/KAAppDelegate.h | 315 | //
// KAAppDelegate.h
// UIViewController-KeyboardAdditions
//
// Created by CocoaPods on 02/03/2015.
// Copyright (c) 2014 Andrew Podkovyrin. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface KAAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| mit |
MR03/exercise-test-demo | demo/demo004/003.html | 921 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Example</title>
<link rel="stylesheet" href="css/base.css" />
<script src="../../asset/react/react.js"></script>
<script src="../../asset/react/react-dom.js"></script>
<script src="../../asset/react/browser.min.js"></script>
<script src="js/app/index.jsx" type="text/babel"></script>
</head>
<body>
<h1>React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。React.createClass 方法就用于生成一个组件类</h1>
<h1>组件的属性可以在组件类的 this.props 对象上获取</h1>
<h1>添加组件属性,有一个地方需要注意,就是 class 属性需要写成 className ,for 属性需要写成 htmlFor ,这是因为 class 和 for 是 JavaScript 的保留字。</h1>
<div id="message"></div>
</body>
</html>
| mit |
treehopper-electronics/treehopper-sdk | NET/Demos/WPF/DeviceManager/ViewModels/ISelectorViewModel.cs | 2665 | using System.Collections.ObjectModel;
using System.ComponentModel;
using GalaSoft.MvvmLight.Command;
namespace Treehopper.Mvvm.ViewModels
{
/// <summary>
/// A delegate called when the selected board changes
/// </summary>
/// <param name="sender">The caller</param>
/// <param name="e">The new selected board</param>
public delegate void SelectedBoardChangedEventHandler(object sender, SelectedBoardChangedEventArgs e);
/// <summary>
/// A delegate called when the selected board has connected
/// </summary>
/// <param name="sender">The caller</param>
/// <param name="e">The connected board</param>
public delegate void BoardConnectedEventHandler(object sender, BoardConnectedEventArgs e);
/// <summary>
/// A delegate called when the selected board has disconnected
/// </summary>
/// <param name="sender">The caller</param>
/// <param name="e">The disconnected board</param>
public delegate void BoardDisconnectedEventHandler(object sender, BoardDisconnectedEventArgs e);
/// <summary>
/// Base interface for the selector view model
/// </summary>
public interface ISelectorViewModel : INotifyPropertyChanged
{
/// <summary>
/// Get the collection of boards
/// </summary>
ObservableCollection<TreehopperUsb> Boards { get; }
/// <summary>
/// Whether the board selection can be changed
/// </summary>
bool CanChangeBoardSelection { get; set; }
/// <summary>
/// The currently selected board
/// </summary>
TreehopperUsb SelectedBoard { get; set; }
/// <summary>
/// Occurs when the window closes
/// </summary>
RelayCommand WindowClosing { get; set; }
/// <summary>
/// Occurs when the connection occurs
/// </summary>
RelayCommand ConnectCommand { get; set; }
/// <summary>
/// Connect button text
/// </summary>
string ConnectButtonText { get; set; }
/// <summary>
/// Close command
/// </summary>
RelayCommand CloseCommand { get; set; }
/// <summary>
/// Board selection changed
/// </summary>
event SelectedBoardChangedEventHandler OnSelectedBoardChanged;
/// <summary>
/// Board connected
/// </summary>
event BoardConnectedEventHandler OnBoardConnected;
/// <summary>
/// Board disconnected
/// </summary>
event BoardDisconnectedEventHandler OnBoardDisconnected;
}
} | mit |
HPate-Riptide/react-overlays | src/Portal.js | 3227 | import React from 'react';
import ReactDOM from 'react-dom';
import componentOrElement from 'react-prop-types/lib/componentOrElement';
import ownerDocument from './utils/ownerDocument';
import getContainer from './utils/getContainer';
/**
* The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy.
* You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`.
* The children of `<Portal/>` component will be appended to the `container` specified.
*/
let Portal = React.createClass({
displayName: 'Portal',
propTypes: {
/**
* A Node, Component instance, or function that returns either. The `container` will have the Portal children
* appended to it.
*/
container: React.PropTypes.oneOfType([
componentOrElement,
React.PropTypes.func
]),
/**
* Classname to use for the Portal Component
*/
className: React.PropTypes.string
},
componentDidMount() {
this._renderOverlay();
},
componentDidUpdate() {
this._renderOverlay();
},
componentWillReceiveProps(nextProps) {
if (this._overlayTarget && nextProps.container !== this.props.container) {
this._portalContainerNode.removeChild(this._overlayTarget);
this._portalContainerNode = getContainer(nextProps.container, ownerDocument(this).body);
this._portalContainerNode.appendChild(this._overlayTarget);
}
},
componentWillUnmount() {
this._unrenderOverlay();
this._unmountOverlayTarget();
},
_mountOverlayTarget() {
if (!this._overlayTarget) {
this._overlayTarget = document.createElement('div');
if (this.props.className) {
this._overlayTarget.className = this.props.className;
}
this._portalContainerNode = getContainer(this.props.container, ownerDocument(this).body);
this._portalContainerNode.appendChild(this._overlayTarget);
}
},
_unmountOverlayTarget() {
if (this._overlayTarget) {
this._portalContainerNode.removeChild(this._overlayTarget);
this._overlayTarget = null;
}
this._portalContainerNode = null;
},
_renderOverlay() {
let overlay = !this.props.children
? null
: React.Children.only(this.props.children);
// Save reference for future access.
if (overlay !== null) {
this._mountOverlayTarget();
this._overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer(
this, overlay, this._overlayTarget
);
} else {
// Unrender if the component is null for transitions to null
this._unrenderOverlay();
this._unmountOverlayTarget();
}
},
_unrenderOverlay() {
if (this._overlayTarget) {
ReactDOM.unmountComponentAtNode(this._overlayTarget);
this._overlayInstance = null;
}
},
render() {
return null;
},
getMountNode(){
return this._overlayTarget;
},
getOverlayDOMNode() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
if (this._overlayInstance) {
return ReactDOM.findDOMNode(this._overlayInstance);
}
return null;
}
});
export default Portal;
| mit |
agua/aguadev | html/plugins/dijit/SyncDialog.js | 5315 | dojo.provide("plugins.dijit.SyncDialog");
// HAS A
dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ValidationTextBox");
// INHERITS
dojo.require("plugins.core.Common");
dojo.declare( "plugins.dijit.SyncDialog",
[ dijit._Widget, dijit._Templated, plugins.core.Common ], {
//Path to the template of this widget.
templatePath: dojo.moduleUrl("plugins", "dijit/templates/syncdialog.html"),
// OR USE @import IN HTML TEMPLATE
cssFiles : [
dojo.moduleUrl("plugins", "dijit/css/syncdialog.css")
],
// Calls dijit._Templated.widgetsInTemplate
widgetsInTemplate : true,
// PARENT plugins.workflow.Apps WIDGET
parentWidget : null,
// DISPLAYED MESSAGE
message : null,
//////}}
constructor : function(args) {
console.log("SyncDialog.constructor args:");
console.dir({args:args});
// LOAD CSS
this.loadCSS();
},
postCreate : function() {
//////console.log("SyncDialog.postCreate plugins.dijit.SyncDialog.postCreate()");
this.startup();
},
startup : function () {
////console.log("SyncDialog.startup plugins.dijit.SyncDialog.startup()");
////console.log("SyncDialog.startup this.parentWidget: " + this.parentWidget);
this.inherited(arguments);
// SET UP DIALOG
this.setDialogue();
// SET KEY LISTENER
this.setKeyListener();
// ADD CSS NAMESPACE CLASS FOR TITLE CSS STYLING
this.setNamespaceClass("syncDialog");
},
setKeyListener : function () {
dojo.connect(this.dialog, "onkeypress", dojo.hitch(this, "handleOnKeyPress"));
},
handleOnKeyPress: function (event) {
var key = event.charOrCode;
console.log("SyncDialog.handleOnKeyPress key: " + key);
if ( key == null ) return;
event.stopPropagation();
if ( key == dojo.keys.ESCAPE ) this.hide();
},
setNamespaceClass : function (ccsClass) {
// ADD CSS NAMESPACE CLASS
dojo.addClass(this.dialog.domNode, ccsClass);
dojo.addClass(this.dialog.titleNode, ccsClass);
dojo.addClass(this.dialog.closeButtonNode, ccsClass);
},
show: function () {
// SHOW THE DIALOGUE
this.dialog.show();
this.message.focus();
},
hide: function () {
// HIDE THE DIALOGUE
this.dialog.hide();
},
doEnter : function(type) {
// RUN ENTER CALLBACK IF 'ENTER' CLICKED
console.log("SyncDialog.doEnter plugins.dijit.SyncDialog.doEnter()");
var inputs = this.validateInputs(["message", "details"]);
console.log("SyncDialog.doEnter inputs:");
console.dir({inputs:inputs});
if ( ! inputs ) {
console.log("SyncDialog.doEnter inputs is null. Returning");
return;
}
// RESET
this.message.set('value', "");
this.details.value = "";
// HIDE
this.hide();
// DO CALLBACK
this.dialog.enterCallback(inputs);
},
validateInputs : function (keys) {
console.log("Hub.validateInputs keys: ");
console.dir({keys:keys});
var inputs = new Object;
this.isValid = true;
for ( var i = 0; i < keys.length; i++ ) {
console.log("Hub.validateInputs Doing keys[" + i + "]: " + keys[i]);
inputs[keys[i]] = this.verifyInput(keys[i]);
}
console.log("Hub.validateInputs inputs: ");
console.dir({inputs:inputs});
if ( ! this.isValid ) return null;
return inputs;
},
verifyInput : function (input) {
console.log("Aws.verifyInput input: ");
console.dir({this_input:this[input]});
var value = this[input].value;
console.log("Aws.verifyInput value: " + value);
var className = this.getClassName(this[input]);
console.log("Aws.verifyInput className: " + className);
if ( className ) {
console.log("Aws.verifyInput this[input].isValid(): " + this[input].isValid());
if ( ! value || ! this[input].isValid() ) {
console.log("Aws.verifyInput input " + input + " value is empty. Adding class 'invalid'");
dojo.addClass(this[input].domNode, 'invalid');
this.isValid = false;
}
else {
console.log("SyncDialog.verifyInput value is NOT empty. Removing class 'invalid'");
dojo.removeClass(this[input].domNode, 'invalid');
return value;
}
}
else {
if ( input.match(/;/) || input.match(/`/) ) {
console.log("SyncDialog.verifyInput value is INVALID. Adding class 'invalid'");
dojo.addClass(this[input], 'invalid');
this.isValid = false;
return null;
}
else {
console.log("SyncDialog.verifyInput value is VALID. Removing class 'invalid'");
dojo.removeClass(this[input], 'invalid');
return value;
}
}
return null;
},
doCancel : function() {
// RUN CANCEL CALLBACK IF 'CANCEL' CLICKED
////console.log("SyncDialog.doCancel plugins.dijit.SyncDialog.doCancel()");
this.dialog.cancelCallback();
this.dialog.hide();
},
setDialogue : function () {
// APPEND DIALOG TO DOCUMENT
document.body.appendChild(this.dialog.domNode);
this.dialog.parentWidget = this;
// AVOID this._fadeOutDeferred NOT DEFINED ERROR
this._fadeOutDeferred = function () {};
},
load : function (args) {
console.log("SyncDialog.load args:");
console.dir({args:args});
if ( args.title ) {
console.log("SyncDialog.load SETTING TITLE: " + args.title);
this.dialog.set('title', args.title);
}
this.headerNode.innerHTML = args.header;
if (args.message) this.message.set('value', args.message);
if (args.details) this.details.value = args.details;
//if (args.details) this.details.innerHTML(args.details);
this.dialog.enterCallback = args.enterCallback;
this.show();
}
});
| mit |
henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Basic/Json/Factories/CommentLikeJsonIOFactory.cs | 583 | namespace TraktApiSharp.Objects.Basic.Json.Factories
{
using Objects.Basic.Json.Reader;
using Objects.Basic.Json.Writer;
using Objects.Json;
internal class CommentLikeJsonIOFactory : IJsonIOFactory<ITraktCommentLike>
{
public IObjectJsonReader<ITraktCommentLike> CreateObjectReader() => new CommentLikeObjectJsonReader();
public IArrayJsonReader<ITraktCommentLike> CreateArrayReader() => new CommentLikeArrayJsonReader();
public IObjectJsonWriter<ITraktCommentLike> CreateObjectWriter() => new CommentLikeObjectJsonWriter();
}
}
| mit |
sdl/Testy | src/main/java/com/sdl/selenium/extjs3/button/DownloadLink.java | 1642 | package com.sdl.selenium.extjs3.button;
import com.sdl.selenium.bootstrap.button.Download;
import com.sdl.selenium.extjs3.ExtJsComponent;
import com.sdl.selenium.web.SearchType;
import com.sdl.selenium.web.WebLocator;
public class DownloadLink extends ExtJsComponent implements Download {
public DownloadLink() {
setClassName("DownloadLink");
setTag("a");
}
public DownloadLink(WebLocator container) {
this();
setContainer(container);
}
public DownloadLink(WebLocator container, String text) {
this(container);
setText(text, SearchType.EQUALS);
}
/**
* Wait for the element to be activated when there is deactivation mask on top of it
*
* @param seconds time
*/
@Override
public boolean waitToActivate(int seconds) {
return getXPath().contains("ext-ux-livegrid") || super.waitToActivate(seconds);
}
/**
* if WebDriverConfig.isSilentDownload() is true, se face silentDownload, is is false se face download with AutoIT.
* Download file with AutoIT, works only on FireFox. SilentDownload works FireFox and Chrome
* Use only this: button.download("C:\\TestSet.tmx");
* return true if the downloaded file is the same one that is meant to be downloaded, otherwise returns false.
*
* @param fileName e.g. "TestSet.tmx"
*/
@Override
public boolean download(String fileName) {
openBrowse();
return executor.download(fileName, 10000L);
}
private void openBrowse() {
executor.browse(this);
}
}
| mit |
vjuylov/percapita-mobile | www/js/controllers/controllers.js | 8105 | angular.module('perCapita.controllers', [])
.controller('AppCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$localStorage', '$ionicPlatform', 'AuthService',
function ($scope, $rootScope, $ionicModal, $timeout, $localStorage, $ionicPlatform, AuthService) {
$scope.loginData = $localStorage.getObject('userinfo', '{}');
$scope.reservation = {};
$scope.registration = {};
$scope.loggedIn = false;
if (AuthService.isAuthenticated()) {
$scope.loggedIn = true;
$scope.username = AuthService.getUsername();
}
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function (modal) {
$scope.modal = modal;
});
// Triggered in the login modal to close it
$scope.closeLogin = function () {
$scope.modal.hide();
};
// Open the login modal
$scope.login = function () {
$scope.modal.show();
};
// Perform the login action when the user submits the login form
$scope.doLogin = function () {
console.log('Doing login', $scope.loginData);
$localStorage.storeObject('userinfo', $scope.loginData);
AuthService.login($scope.loginData);
$scope.closeLogin();
};
$scope.logOut = function () {
AuthService.logout();
$scope.loggedIn = false;
$scope.username = '';
};
$rootScope.$on('login:Successful', function () {
$scope.loggedIn = AuthService.isAuthenticated();
$scope.username = AuthService.getUsername();
});
$ionicModal.fromTemplateUrl('templates/register.html', {
scope: $scope
}).then(function (modal) {
$scope.registerform = modal;
});
$scope.closeRegister = function () {
$scope.registerform.hide();
};
$scope.register = function () {
$scope.registerform.show();
};
$scope.doRegister = function () {
console.log('Doing registration', $scope.registration);
$scope.loginData.username = $scope.registration.username;
$scope.loginData.password = $scope.registration.password;
AuthService.register($scope.registration);
$timeout(function () {
$scope.closeRegister();
}, 1000);
};
$rootScope.$on('registration:Successful', function () {
$localStorage.storeObject('userinfo', $scope.loginData);
});
}])
.controller('FavoriteDetailsController', ['$scope', '$rootScope', '$state', '$stateParams', 'Favorites', function ($scope, $rootScope, $state, $stateParams, Favorites) {
$scope.showFavButton = false;
// Lookup favorites for a given user id
Favorites.findById({id: $stateParams.id})
.$promise.then(
function (response) {
$scope.city = response;
},
function (response) {
$scope.message = "Error: " + response.status + " " + response.statusText;
}
);
}])
.controller('HomeController', ['$scope', 'perCapitaService', '$stateParams', '$rootScope', 'Favorites', '$ionicPlatform', '$cordovaLocalNotification', '$cordovaToast', function ($scope, perCapitaService, $stateParams, $rootScope, Favorites, $ionicPlatform, $cordovaLocalNotification, $cordovaToast) {
$scope.showFavButton = $rootScope.currentUser;
$scope.controlsData = {skills: $rootScope.skills};
// Look up jobs data
$scope.doLookup = function () {
$rootScope.skills = $scope.controlsData.skills;
perCapitaService.lookup($scope.controlsData.skills);
};
// Post process the jobs data, by adding Indeeds link and calculating jobsPer1kPeople and jobsRank
$scope.updatePerCapitaData = function () {
$scope.cities = perCapitaService.response.data.docs;
var arrayLength = $scope.cities.length;
for (var i = 0; i < arrayLength; i++) {
var obj = $scope.cities[i];
obj.jobsPer1kPeople = Math.round(obj.totalResults / obj.population * 1000);
obj.url = "https://www.indeed.com/jobs?q=" + $scope.controlsData.skills + "&l=" + obj.city + ", " + obj.state;
}
// rank jobs
var sortedObjs;
if (perCapitaService.isSkills) {
sortedObjs = _.sortBy($scope.cities, 'totalResults').reverse();
} else {
sortedObjs = _.sortBy($scope.cities, 'jobsPer1kPeople').reverse();
}
$scope.cities.forEach(function (element) {
element.jobsRank = sortedObjs.indexOf(element) + 1;
});
if (!$scope.$$phase) {
$scope.$apply();
}
$rootScope.cities = $scope.cities;
console.log("Loaded " + arrayLength + " results.")
};
perCapitaService.registerObserverCallback($scope.updatePerCapitaData);
$scope.addToFavorites = function () {
delete $scope.city._id;
delete $scope.city._rev;
$scope.city.customerId = $rootScope.currentUser.id
Favorites.create($scope.city);
$ionicPlatform.ready(function () {
$cordovaLocalNotification.schedule({
id: 1,
title: "Added Favorite",
text: $scope.city.city
}).then(function () {
console.log('Added Favorite ' + $scope.city.city);
},
function () {
console.log('Failed to add Favorite ');
});
$cordovaToast
.show('Added Favorite ' + $scope.city.city, 'long', 'center')
.then(function (success) {
// success
}, function (error) {
// error
});
});
}
if ($stateParams.id) {
console.log("param " + $stateParams.id);
$scope.city = $rootScope.cities.filter(function (obj) {
return obj._id === $stateParams.id;
})[0];
console.log($scope.city);
} else {
$scope.doLookup();
}
}])
.controller('AboutController', ['$scope', function ($scope) {
}])
.controller('FavoritesController', ['$scope', '$rootScope', '$state', 'Favorites', '$ionicListDelegate', '$ionicPopup', function ($scope, $rootScope, $state, Favorites, $ionicListDelegate, $ionicPopup) {
$scope.shouldShowDelete = false;
/*$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
console.log("State changed: ", toState);
if(toState.name === "app.favorites") $scope.refreshItems();
});*/
$scope.refreshItems = function () {
if ($rootScope.currentUser) {
Favorites.find({
filter: {
where: {
customerId: $rootScope.currentUser.id
}
}
}).$promise.then(
function (response) {
$scope.favorites = response;
console.log("Got favorites");
},
function (response) {
console.log(response);
});
}
else {
$scope.message = "You are not logged in"
}
}
$scope.refreshItems();
$scope.toggleDelete = function () {
$scope.shouldShowDelete = !$scope.shouldShowDelete;
console.log($scope.shouldShowDelete);
}
$scope.deleteFavorite = function (favoriteid) {
var confirmPopup = $ionicPopup.confirm({
title: '<h3>Confirm Delete</h3>',
template: '<p>Are you sure you want to delete this item?</p>'
});
confirmPopup.then(function (res) {
if (res) {
console.log('Ok to delete');
Favorites.deleteById({id: favoriteid}).$promise.then(
function (response) {
$scope.favorites = $scope.favorites.filter(function (el) {
return el.id !== favoriteid;
});
$state.go($state.current, {}, {reload: false});
// $window.location.reload();
},
function (response) {
console.log(response);
$state.go($state.current, {}, {reload: false});
});
} else {
console.log('Canceled delete');
}
});
$scope.shouldShowDelete = false;
}
}])
;
| mit |
GustavBrock/VBA.ModernTheme | README.md | 1060 | # VBA.ModernTheme
### Windows Phone Colour Palette and<p>Colour Selector using WithEvents
Version 1.0.1
The *Windows Phone Theme Colours* is a tight, powerful, and well balanced palette.
This tiny Microsoft Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing *WithEvents*, one of Access' hidden gems.

Full documentation is found here:

[Create Windows Phone Colour Palette and Selector using WithEvents](https://www.experts-exchange.com/articles/29554/Create-Windows-Phone-Colour-Palette-and-Selector-using-WithEvents.html?preview=yawJg2wkMzc%3D)
<hr>
*If you wish to support my work or need extended support or advice, feel free to:*
<p>
[<img src="https://raw.githubusercontent.com/GustavBrock/VBA.ModernTheme/master/images/BuyMeACoffee.png">](https://www.buymeacoffee.com/gustav/) | mit |
RazarDessun/fastProxy | test/test_timeout2.js | 11087 | var http = require("http");
var querystring = require("querystring"); // 核心模块
var SBuffer=require("../tools/SBuffer");
var common=require("../tools/common");
var zlib=require("zlib");
var redis_pool=require("../tools/connection_pool");
var events = require('events');
var util = require('util');
function ProxyAgent(preHeaders,preAnalysisFields,logName){
this.headNeeds = preHeaders||"";
this.preAnalysisFields = preAnalysisFields||"";
this.AnalysisFields = {};
this.logName=logName||"";
this.response=null;
this.reqConf={};
this.retData=[];
this.redis =null; // redis {} redis_key
events.EventEmitter.call(this);
}
/**
* 获取服务配置信息
* @param 服务名
* @return object
*/
ProxyAgent.prototype.getReqConfig = function(logName){
var _self=this;
var Obj={};
Obj=Config[logName];
Obj.logger=Analysis.getLogger(logName);
Obj.name=logName;
return Obj;
}
ProxyAgent.prototype.doRequest=function(_req,_res){
var _self=this;
_self.reqConf=_self.getReqConfig(this.logName);
logger.debug('进入'+_self.reqConf.desc+"服务");
var header_obj =this.packageHeaders(_req.headers,this.headNeeds);
var url_obj = url.parse(request.url, true);
var query_obj = url_obj.query;
var postData = request.body|| ""; // 获取请求参数
_res.setHeader("Content-Type", config.contentType);
_res.setHeader(config.headerkey, config.headerval);
var opts=_self.packData(header_obj,query_obj,postData);
logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]);
if(typeof(postData) =="object" && postData.redis_key.length>0){
this.getRedis(opts[0],opts[1]);
}
else{
this.httpProxy(opts[0],opts[1]);
}
}
/**
* 封装get post接口
* @param headers
* @param query
* @param body
* @return []
*/
ProxyAgent.prototype.packData=function(headers,query,body){
var _self=this;
//resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据
var type=_self.reqConf.resType || "";
body = body || "";
var len=0;
var query_str="";
var body_str="";
if(type==""){
query=common.extends(query,headers);
query_str = querystring.stringify(query, '&', '=');
}
else if(type=="body"){
body=common.extends(body,headers);
body_str = querystring.stringify(body, '&', '=');
len=body_str.length;
if(body.redis_key){
this.redis={};
this.redis.redis_key=body.redis_key;
}
}
else if(type=="json"){
query=common.extends(query,headers);
query_str = 'json='+querystring.stringify(query, '&', '=');
}
else if(type=="raw"){
len=body.length;
body_str=body;
}
var actionlocation = headers.actionlocation || "";
if(actionlocation==""){
actionlocation=query.actionlocation||"";
}
var opts=_self.getRequestOptions(len,actionlocation);
opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str;
return [opts,body_str];
}
/**
* 获取请求头信息
* @param len数据长度
* @param actiontion 通用访问地址
* @return object 头信息
*/
ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){
var _self=this;
var options = { //http请求参数设置
host: _self.reqConf.host, // 远端服务器域名
port: _self.reqConf.port, // 远端服务器端口号
path: _self.reqConf.path||"",
headers : {'Connection' : 'keep-alive'}
};
if(actionlocation.length>0){
options.path=actionlocation;
}
var rtype= _self.reqConf.reqType || "";
if(rtype.length>0){
options.headers['Content-Type']=rtype;
}
if(len>0){
options.headers['Content-Length']=len;
}
return options;
}
ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){
var obj={};
return obj;
}
/**
* 获取头部信息进行封装
* @param request.headers
* @param need fields ;split with ','
* @return object headers
*/
ProxyAgent.prototype.packageHeaders = function(headers) {
var fields=arguments[1]||"";
var query_obj = {};
var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址
var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源
var osversion = headers['osversion'] || '0';// 客户端系统
var devicemodel = headers['devicemodel'] || '0';// 客户端型号
var manufacturername = headers['manufacturername'] || '0';// 制造厂商
var actionlocation = headers['actionlocation']; // 请求后台地址
var dpi = headers['dpi'] || '2.0';// 密度
var imsi = headers['imsi'] || '0'; // 客户端imsi
var mobileid = headers['mobileid'] || '0'; // 客户端mibileid
var version = headers['version'] || '0';// 客户端版本version
var selflon = headers['selflon'] || '0';// 经度
var selflat = headers['selflat'] || '0';// 维度
var uid = headers['uid'] || '0'; // 犬号
var radius=headers['radius']||'0';//误差半径
var platform=headers['platform']||"";//平台 ios ,android
var gender= headers['gender'] || '0';
query_obj.gender = gender;
query_obj.reqip = reqip;
query_obj.forward = forward;
query_obj.osversion = osversion;
query_obj.devicemodel = devicemodel;
query_obj.manufacturername = manufacturername;
query_obj.actionlocation = actionlocation;
query_obj.dpi = dpi;
query_obj.imsi = imsi;
query_obj.mobileid = mobileid;
query_obj.version = version;
query_obj.selflon = selflon;
query_obj.selflat = selflat;
query_obj.uid = uid;
query_obj.radius=radius;
query_obj.platform=platform;
if(fields.length > 0){
var afields = fields.split(",");
var newObj = {};
for(var i = 0; i < afields.length ; i ++){
newObj[afields[i]] = query_obj[afields[i]] || "";
}
return newObj;
}
else{
return query_obj;
}
}
/**
* http 请求代理
* @param options 远程接口信息
* @param reqData 请求内容 req.method== get时一般为空
*/
ProxyAgent.prototype.httpProxy = function (options,reqData){
var _self=this;
var TongjiObj={};
var req = http.request(options, function(res) {
TongjiObj.statusCode = res.statusCode ||500;
var tmptime=Date.now();
TongjiObj.restime = tmptime;
TongjiObj.resEnd =tmptime;
TongjiObj.ends = tmptime;
TongjiObj.length = 0;
TongjiObj.last = tmptime;
var sbuffer=new SBuffer();
res.setEncoding("utf-8");
res.on('data', function (trunk) {
sbuffer.append(trunk);
});
res.on('end', function () {
TongjiObj.resEnd = Date.now();
//doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt);
_self.emmit("onDone",sbuffer,TongjiObj);
});
});
req.setTimeout(timeout,function(){
req.emit('timeOut',{message:'have been timeout...'});
});
req.on('error', function(e) {
TongjiObj.statusCode=500;
_self.emmit("onDone","",500,TongjiObj);
});
req.on('timeOut', function(e) {
req.abort();
TongjiObj.statusCode=500;
TongjiObj.last = Date.now();
_self.emmit("onDone","",500,TongjiObj);
});
req.end(reqData);
}
/**
* 设置缓存
* @param redis_key
* @param redis_time
* @param resultBuffer
*/
ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) {
redis_pool.acquire(function(err, client) {
if (!err) {
client.setex(redis_key, redis_time, resultBuffer, function(err,
repliy) {
redis_pool.release(client); // 链接使用完毕释放链接
});
logger.debug(redis_key + '设置缓存数据成功!');
} else {
writeLogs.logs(Analysis.getLogger('error'), 'error', {
msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常',
err : 14
});
logger.debug(redis_key + '设置缓存数据失败!');
}
});
}
/**
* 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存
* redis_key通过self变量中取
* @param options
* @param reqData
*/
ProxyAgent.prototype.getRedis = function ( options, reqData) {
var _self=this;
var redis_key=this.redis.redis_key || "";
redis_pool.acquire(function(err, client) {
if (!err) {
client.get(redis_key, function(err, date) {
redis_pool.release(client) // 用完之后释放链接
if (!err && date != null) {
var resultBuffer = new Buffer(date);
_self.response.statusCode = 200;
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
logger.debug(redis_key + '通用接口下行缓存数据:' + date);
} else {
_self.httpProxy(options, reqData);
}
});
} else {
_self.httpProxy(options, reqData);
}
});
}
/**
* 输出gzip数据
* response 内置
* @param resultBuffer
*/
ProxyAgent.prototype.gzipOutPut = function (resultBuffer){
var _self=this;
zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩
if (code != null) { // 如果正常结束
logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length);
_self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志
} else {
buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}');
_self.response.statusCode=500;
}
_self.response.setHeader("Content-Length", buffer.length);
_self.response.write(buffer);
_self.response.end();
});
}
/**
* 请求完毕处理
* @param buffer type buffer/string
* @param status 请求http状态
* @param tongji object统计对象
*/
ProxyAgent.prototype.onDone =function(buffer,status){
var tongji=arguments[2] ||"";
var _self=this;
var resultStr = typeof(buffer)=="object"?buffer.toString():buffer;
if(this.reqConf.isjson==1){
var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式
if (resultObj) { // 返回结果是json格式
resultStr = JSON.stringify(resultObj);
_self.response.statusCode = status;
} else {
resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}';
_self.response.statusCode = 500;
}
}
else{
_self.response.statusCode = status;
}
var resultBuffer = new Buffer(resultStr);
if(tongji!=""){
tongji.ends = Date.now();
tongji.length = resultBuffer.length;
}
if(resultBuffer.length > 500 ){
//压缩输出
_self.gzipOutPut(resultBuffer);
}else{
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
}
if(tongji!=""){
tongji.last= Date.now();
tongji=common.extends(tongji,_self.preAnalysisFields);
logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status);
writeLogs.logs(poiDetailServer,'poiDetailServer',obj);
}
});
ProxyAgent.prototype.onDones =function(buffer,status){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
ProxyAgent.prototype.dealDones =function(){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
//ProxyAgent 从event 集成
//utils.inherit(ProxyAgent,event);
exports.ProxyAgent=ProxyAgent;
| mit |
carelvwyk/carelvwyk.github.io | _posts/2016-09-19-hello-world.markdown | 3210 | ---
layout: post
title: "Hello World"
image:
feature: nomadsland.jpg
date: 2016-09-19 20:24:11 +0200
categories: personal, coding
---
I enjoy tinkering - building little electronic gadgets and apps - especially if it has something to do with [cryptocurrencies]. Currently my day-job is building Bitcoin infrastructure. The purpose of this weblog is to record the progress on various projects outside my normal scope of work. Working with software, I seem to hit a lot of **"Hmmm, I wonder how this works?"** moments. Hopefully these pages provide some useful information to somebody working on and wondering about the same things.
## Begin
I'm a fan of the maxim "Done is better than perfect" so my current goal is to get this blog up and running as quickly as possible. Instead of wondering about which software or host to use, I decided to power it with [Jekyll] and host it on [Github pages]. I already have a code/text editor I like using and git is already part of my daily workflow so it seemed like a natural fit. I picked a theme I liked but just as I got something that looked vaguely OK, I ran into the first **"Hmmm, I wonder"** moment.
It turns out Jekyll/Github pages deployments are not intuitive.
[Jekyll's Basic Usage Guide] does a pretty good job of explaining how to get up and running locally, but trying to find GH-Pages deployment instructions (and failing miserably) made me realise things don't work as I'd expect.
## Jekyll & Github
Jekyll uses plugins and templates to help authors perform dynamic blog-related things like themeing, categorising and indexing posts, generating "about" pages and more.
`jekyll build` produces a static "render" of the blog at the time it is called so that you can just upload the HTML/JS/CSS contents of the generated `_site` directory to a server that serves static content. You could host it on dropbox if you wanted to, there's no server-side scripts like PHP or Rails to generate content from data stored in a database.
`_site` gets destroyed and re-created every time you call `jekyll build` and it is listed in `.gitignore` so it's not part of the repo, so how in the world do you tell Github to serve the contents of `_site`? Am I supposed to create a manual deploy script that adds `_site` to a repo and push that?
## Hmmm, I wonder...
So which is it?
Turns out you simply push your jekyll source repo to `master`. You don't even need to call `jekyll build`. Your site just magically appears on Github. That leaves only two possibilities:
1. Either Github calls `jekyll build` and serves the `_site` directory after each push, or
2. Github is running `jekyll serve` to generate content every request.
Turns out it's the latter. Github actually runs Jekyll, and supports [some Jekyll plugins].
## Done
So, one "git push" later and these pages should be live!
*"Done is better than perfect"*
[BitX]: https://www.bitx.co/
[cryptocurrencies]: https://en.wikipedia.org/wiki/Cryptocurrency
[jekyll]: https://jekyllrb.com
[Jekyll's Basic Usage Guide]: https://jekyllrb.com/docs/usage/
[Github pages]: https://pages.github.com/
[some Jekyll plugins]: https://help.github.com/articles/adding-jekyll-plugins-to-a-github-pages-site/ | mit |
bopoda/robots-txt-parser | tests/RobotsTxtParser/CommentsTest.php | 1834 | <?php
namespace RobotsTxtParser;
class CommentsTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider generateDataForTest
*/
public function testRemoveComments($robotsTxtContent)
{
$parser = new RobotsTxtParser($robotsTxtContent);
$rules = $parser->getRules('*');
$this->assertEmpty($rules, 'expected remove comments');
}
/**
* @dataProvider generateDataFor2Test
*/
public function testRemoveCommentsFromValue($robotsTxtContent, $expectedDisallowValue)
{
$parser = new RobotsTxtParser($robotsTxtContent);
$rules = $parser->getRules('*');
$this->assertNotEmpty($rules, 'expected data');
$this->assertArrayHasKey('disallow', $rules);
$this->assertNotEmpty($rules['disallow'], 'disallow expected');
$this->assertEquals($expectedDisallowValue, $rules['disallow'][0]);
}
/**
* Generate test case data
* @return array
*/
public function generateDataForTest()
{
return array(
array(
"
User-agent: *
#Disallow: /tech
"
),
array(
"
User-agent: *
Disallow: #/tech
"
),
array(
"
User-agent: *
Disal # low: /tech
"
),
array(
"
User-agent: *
Disallow#: /tech # ds
"
),
);
}
/**
* Generate test case data
* @return array
*/
public function generateDataFor2Test()
{
return array(
array(
"User-agent: *
Disallow: /tech #comment",
'disallowValue' => '/tech',
),
);
}
}
| mit |
njacinto/Utils | src/main/java/org/nfpj/utils/arrays/ArrayFilterIterator.java | 3840 | /*
* The MIT License
*
* Copyright 2016 njacinto.
*
* 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 org.nfpj.utils.arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import org.nfpj.utils.predicates.TruePredicate;
/**
*
* @author njacinto
* @param <T> the type of object being returned by this iterator
*/
public class ArrayFilterIterator<T> implements Iterator<T> {
protected static final int END_OF_ITERATION = -2;
//
private int nextIndex;
//
protected final T[] array;
protected final Predicate<T> predicate;
// <editor-fold defaultstate="expanded" desc="Constructors">
/**
* Creates an instance of this class
*
* @param array the array from where this instance will extract the elements
* @param predicate the filter to be applied to the elements
*/
public ArrayFilterIterator(T[] array, Predicate<T> predicate) {
this(array, predicate, -1);
}
/**
*
* @param array
* @param predicate
* @param prevIndex
*/
protected ArrayFilterIterator(T[] array, Predicate<T> predicate, int prevIndex) {
this.array = array!=null ? array : ArrayUtil.empty();
this.predicate = predicate!=null ? predicate : TruePredicate.getInstance();
this.nextIndex = getNextIndex(prevIndex);
}
// </editor-fold>
// <editor-fold defaultstate="expanded" desc="Public methods">
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
return nextIndex != END_OF_ITERATION;
}
/**
* {@inheritDoc}
*/
@Override
public T next() {
if(nextIndex==END_OF_ITERATION){
throw new NoSuchElementException("The underline collection has no elements.");
}
int index = nextIndex;
nextIndex = getNextIndex(nextIndex);
return array[index];
}
/**
* {@inheritDoc}
*/
@Override
public void remove() {
throw new UnsupportedOperationException("The iterator doesn't allow changes.");
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Protected methods">
/**
* Searches for the next element that matches the filtering conditions and
* returns it.
*
* @param currIndex
* @return the next element that matches the filtering conditions or null
* if no more elements are available
*/
protected int getNextIndex(int currIndex){
if(currIndex!=END_OF_ITERATION){
for(int i=currIndex+1; i<array.length; i++){
if(predicate.test(array[i])){
return i;
}
}
}
return END_OF_ITERATION;
}
// </editor-fold>
}
| mit |
hyesun03/hyesun03.github.io | _posts/2016-10-08-slackbot.md | 4664 | ---
layout: post
title: slacker로 slack bot 만들기
comments: true
tags:
- python
- slack
- 봇
- slacker
---
멘토님께서 라인의 `notification`을 이용해서 봇 만든것을 보고 따라 만들었다. 봇 만들고 싶은데 핑계가 없어서 고민하다가 동아리에서 `slack`을 쓰기 때문에 슬랙봇을 만들어보기로 했다. 스터디하는 사람들을 대상으로 커밋한지 얼마나 되었는지 알려주는 용도로 만들었다. 결과물은 아래와 같다.
<img src="/images/commit-bell.jpeg" alt="클린 코드를 위한 테스트 주도 개발" style="width: 480px; margin-left: auto; margin-right: auto; "/>
먼저 봇을 등록해야한다. [Slack Apps](https://studytcp.slack.com/apps)의 우측 상단에 `Build`를 눌러서 등록을 한다. 아래와 같은 화면이 나온다. 다른 팀에게 공개하지 않을 것이라서 `Something just for my team`을 선택했다.

두 번째 `Bots`를 선택한다.

적절한 설정을 하고 `token`을 꼭 기억(복사)해 두자.
pip로 필요한 것을 설치하자. [github3.py](https://github3py.readthedocs.io/en/master/), [slacker](https://pypi.python.org/pypi/slacker/), datetime, pytz를 사용했다.
<pre>$ pip install slacker
$ pip install github3.py
$ pip install datetime
$ pip install pytz</pre>
전체 코드는 아래와 같다.
```python
from slacker import Slacker
import github3
import datetime
import pytz
local_tz = pytz.timezone('Asia/Seoul')
token = 'xoxb-발급받은-토큰'
slack = Slacker(token)
channels = ['#채널1', '#채널2']
def post_to_channel(message):
slack.chat.post_message(channels[0], message, as_user=True)
def get_repo_last_commit_delta_time(owner, repo):
repo = github3.repository(owner, repo)
return repo.pushed_at.astimezone(local_tz)
def get_delta_time(last_commit):
now = datetime.datetime.now(local_tz)
delta = now - last_commit
return delta.days
def main():
members = (
# (git 계정 이름, repo 이름, 이름),
# [...]
)
reports = []
for owner, repo, name in members:
last_commit = get_repo_last_commit_delta_time(owner, repo)
delta_time = get_delta_time(last_commit)
if(delta_time == 0):
reports.append('*%s* 님은 오늘 커밋을 하셨어요!' % (name))
else:
reports.append('*%s* 님은 *%s* 일이나 커밋을 안하셨어요!' % (name, delta_time))
post_to_channel('\n 안녕 친구들! 과제 점검하는 커밋벨이야 호호 \n' + '\n'.join(reports))
if __name__ == '__main__':
main()
```
## **해결하지 못한 것**
* **X-RateLimit-Limit 올리기**
테스트 때문에 꽤 많이 돌리다 보니까 횟수제한에 걸렸다. 에러 메시지는 아래와 같다.
<pre>github3.models.GitHubError: 403 API rate limit exceeded for 106.246.181.100. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)</pre>
찾아보니까 하나의 IP당 한 시간에 보낼 수 있는 횟수가 정해져 있다고 한다. 출력해 보면 아래와 같다. `X-RateLimit-Limit`은 기본이 60이고 최대 5000으로 올릴 수 있다는데 헤더 수정을 어떻게 해야할지 모르겠다. 사실 이거 해결한다고 시간이 꽤 지나버려서 해결(?)이 되었다.
<pre>[...]
Status: 403 Forbidden
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1475913003
[...]</pre>
* **이 코드를 어디서 돌려야 하는가.**
하루에 2-3번? 정도 해당 채널에 알림을 보낼 것이다. 사실 동아리 서버 쓰면 된다고는 하는데.. 개인 서버를 쓰고는 싶고 그렇다고 AWS 쓰자니 별로 하는것도 없는데 달마다 치킨 값을 헌납해야해서 고민이다.
## **참고자료**
* [https://corikachu.github.io/articles/python/python-slack-bot-slacker](https://corikachu.github.io/articles/python/python-slack-bot-slacker)
* [https://www.fullstackpython.com/blog/build-first-slack-bot-python.html](https://www.fullstackpython.com/blog/build-first-slack-bot-python.html)
* [https://godoftyping.wordpress.com/2015/04/19/python-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84%EA%B4%80%EB%A0%A8-%EB%AA%A8%EB%93%88/](https://godoftyping.wordpress.com/2015/04/19/python-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84%EA%B4%80%EB%A0%A8-%EB%AA%A8%EB%93%88/)
| mit |
fbfeix/react-icons | src/icons/IosHeart.js | 1031 | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosHeart extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779
c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564
c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path>
</g>;
} return <IconBase>
<path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779
c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564
c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path>
</IconBase>;
}
};IosHeart.defaultProps = {bare: false} | mit |
gliss/oscommerce-bootstrap | catalog/specials.php | 3956 | <?php
/*
$Id$
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2010 osCommerce
Released under the GNU General Public License
*/
require('includes/application_top.php');
require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_SPECIALS);
$breadcrumb->add(NAVBAR_TITLE, tep_href_link(FILENAME_SPECIALS));
require(DIR_WS_INCLUDES . 'template_top.php');
?>
<h1><?php echo HEADING_TITLE; ?></h1>
<div class="contentContainer">
<div class="contentText">
<?php
// BOF Enable & Disable Categories
$specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, p.products_image, s.specials_new_products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_SPECIALS . " s, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where c.categories_status='1' and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and p.products_status = '1' and p.products_id = s.products_id and pd.products_id = s.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC";
// EOF Enable & Disable Categories
//$specials_query_raw = "select p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, p.products_image, s.specials_new_products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_SPECIALS . " s where p.products_status = '1' and s.products_id = p.products_id and p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and s.status = '1' order by s.specials_date_added DESC";
$specials_split = new splitPageResults($specials_query_raw, MAX_DISPLAY_SPECIAL_PRODUCTS);
if (($specials_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '1') || (PREV_NEXT_BAR_LOCATION == '3'))) {
?>
<div>
<span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span>
<span><?php echo $specials_split->display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?></span>
</div>
<br />
<?php
}
?>
<table border="0" width="100%" cellspacing="0" cellpadding="2">
<tr>
<?php
$row = 0;
$specials_query = tep_db_query($specials_split->sql_query);
while ($specials = tep_db_fetch_array($specials_query)) {
$row++;
echo '<td align="center" width="33%"><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $specials['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $specials['products_image'], $specials['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a><br /><a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $specials['products_id']) . '">' . $specials['products_name'] . '</a><br /><del>' . $currencies->display_price($specials['products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '</del><br /><span class="productSpecialPrice">' . $currencies->display_price($specials['specials_new_products_price'], tep_get_tax_rate($specials['products_tax_class_id'])) . '</span></td>' . "\n";
if ((($row / 3) == floor($row / 3))) {
?>
</tr>
<tr>
<?php
}
}
?>
</tr>
</table>
<?php
if (($specials_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '2') || (PREV_NEXT_BAR_LOCATION == '3'))) {
?>
<br />
<div>
<span style="float: right;"><?php echo TEXT_RESULT_PAGE . ' ' . $specials_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></span>
<span><?php echo $specials_split->display_count(TEXT_DISPLAY_NUMBER_OF_SPECIALS); ?></span>
</div>
<?php
}
?>
</div>
</div>
<?php
require(DIR_WS_INCLUDES . 'template_bottom.php');
require(DIR_WS_INCLUDES . 'application_bottom.php');
?>
| mit |
jarvars/jarvars.github.io | index.html | 52 | ---
layout: home
title: JARVARS
comments: false
---
| mit |
graik/labhamster | site_templates/admin/base_site.html | 256 | {% extends "admin/base.html" %}
{% load i18n %}
{% block title %}{{ title }} | {% trans 'lab purchase management' %}{% endblock %}
{% block branding %}
<h1 id="site-name">{% trans 'LabHamster' %}</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
| mit |
ze-pequeno/mockito | src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java | 3400 | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockitousage.verification;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.atMostOnce;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.List;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.verification.MoreThanAllowedActualInvocations;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockitoutil.TestBase;
public class AtMostXVerificationTest extends TestBase {
@Mock private List<String> mock;
@Test
public void shouldVerifyAtMostXTimes() throws Exception {
mock.clear();
mock.clear();
verify(mock, atMost(2)).clear();
verify(mock, atMost(3)).clear();
try {
verify(mock, atMostOnce()).clear();
fail();
} catch (MoreThanAllowedActualInvocations e) {
}
}
@Test
public void shouldWorkWithArgumentMatchers() throws Exception {
mock.add("one");
verify(mock, atMost(5)).add(anyString());
try {
verify(mock, atMost(0)).add(anyString());
fail();
} catch (MoreThanAllowedActualInvocations e) {
}
}
@Test
public void shouldNotAllowNegativeNumber() throws Exception {
try {
verify(mock, atMost(-1)).clear();
fail();
} catch (MockitoException e) {
assertEquals("Negative value is not allowed here", e.getMessage());
}
}
@Test
public void shouldPrintDecentMessage() throws Exception {
mock.clear();
mock.clear();
try {
verify(mock, atMostOnce()).clear();
fail();
} catch (MoreThanAllowedActualInvocations e) {
assertEquals("\nWanted at most 1 time but was 2", e.getMessage());
}
}
@Test
public void shouldNotAllowInOrderMode() throws Exception {
mock.clear();
InOrder inOrder = inOrder(mock);
try {
inOrder.verify(mock, atMostOnce()).clear();
fail();
} catch (MockitoException e) {
assertEquals("AtMost is not implemented to work with InOrder", e.getMessage());
}
}
@Test
public void shouldMarkInteractionsAsVerified() throws Exception {
mock.clear();
mock.clear();
verify(mock, atMost(3)).clear();
verifyNoMoreInteractions(mock);
}
@Test
public void shouldDetectUnverifiedInMarkInteractionsAsVerified() throws Exception {
mock.clear();
mock.clear();
undesiredInteraction();
verify(mock, atMost(3)).clear();
try {
verifyNoMoreInteractions(mock);
fail();
} catch (NoInteractionsWanted e) {
assertThat(e).hasMessageContaining("undesiredInteraction(");
}
}
private void undesiredInteraction() {
mock.add("");
}
}
| mit |
atk4/ui | demos/_unit-test/lookup.php | 709 | <?php
declare(strict_types=1);
namespace Atk4\Ui\Demos;
use Atk4\Ui\Crud;
use Atk4\Ui\UserAction\ExecutorFactory;
// Test for hasOne Lookup as dropdown control.
/** @var \Atk4\Ui\App $app */
require_once __DIR__ . '/../init-app.php';
$model = new Product($app->db);
$model->addCondition($model->fieldName()->name, '=', 'Mustard');
// use default.
$app->getExecutorFactory()->useTriggerDefault(ExecutorFactory::TABLE_BUTTON);
$edit = $model->getUserAction('edit');
$edit->callback = function (Product $model) {
return $model->product_category_id->getTitle() . ' - ' . $model->product_sub_category_id->getTitle();
};
$crud = Crud::addTo($app);
$crud->setModel($model, [$model->fieldName()->name]);
| mit |
Subsets and Splits