answer stringlengths 15 1.25M |
|---|
(function() {
define("kopi/tests/utils", function(require, exports, module) {
var q, utils;
q = require("qunit");
utils = require("kopi/utils");
q.module("kopi/utils");
q.test("guid", function() {
q.equal(utils.guid(), "kopi-0");
return q.equal(utils.guid("prefix"), "prefix-1");
});
return q.test("is regexp", function() {
return q.equal(utils.isRegExp(/^reg/), true);
});
});
}).call(this); |
layout: post
date: 2017-10-20
title: "Jovani Cap Sleeve Cocktail Dress 20303 Sleeveless Short/Mini Sheath/Column"
category: Jovani
tags: [Jovani ,Jovani,Sheath/Column,Bateau,Short/Mini,Sleeveless]
Jovani Cap Sleeve Cocktail Dress 20303
Just **$419.98**
Sleeveless Short/Mini Sheath/Column
<table><tr><td>BRANDS</td><td>Jovani</td></tr><tr><td>Silhouette</td><td>Sheath/Column</td></tr><tr><td>Neckline</td><td>Bateau</td></tr><tr><td>Hemline/Train</td><td>Short/Mini</td></tr><tr><td>Sleeve</td><td>Sleeveless</td></tr></table>
<a href="https:
<!-- break --><a href="https:
<a href="https:
<a href="https:
<a href="https:
Buy it: [https: |
package main
import (
//"fmt"
"github.com/rwcarlsen/goexif/exif"
"github.com/zepouet/exif-extractor/api"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
// TODO
func avian_carrier(res chan api.ExifInfo, wg *sync.WaitGroup) {
defer wg.Done()
defer log.Println("3 :: wg.done")
for e := range res {
log.Println("3 :: telegraf the data : ", e)
}
}
func converter(inChan chan string, outChan chan api.ExifInfo, wg *sync.WaitGroup) {
defer wg.Done()
defer log.Println("2 :: wg.done")
for file := range inChan {
log.Println("2 :: convert file to exif : ", file)
f, err := os.Open(file)
if err != nil {
log.Fatal(err)
}
exif, err := exif.Decode(f)
if err != nil {
log.Fatal(err)
}
info := api.ExifInfo{FileName: file}
info.Decode(exif)
outChan <- info
}
}
func main() {
t0 := time.Now()
// halt and catch fire
runtime.GOMAXPROCS(runtime.NumCPU())
// worker wait group
var wgConvert sync.WaitGroup
var wgTelegraf sync.WaitGroup
workers := 12
wgConvert.Add(workers)
wgTelegraf.Add(workers)
// Convert FileInfo into exif struct
filesChannel := make(chan string, workers*2)
exifChannel := make(chan api.ExifInfo, workers)
// number of photos
var n api.AtomicInt
// start in background the converter worker (from file to exif)
for i := 0; i < workers; i++ {
go converter(filesChannel, exifChannel, &wgConvert)
}
// start in background the avian carrier for dropping exif to telegraf
for i := 0; i < workers; i++ {
go avian_carrier(exifChannel, &wgTelegraf)
}
// Callback method for each resource (file or directory)
callback := func(path string, f os.FileInfo, err error) error {
// TODO : if file is an image (known format)
if err == nil && !f.IsDir() &&
(strings.HasSuffix(f.Name(), ".jpg") || strings.HasSuffix(f.Name(), ".nef") || strings.HasSuffix(f.Name(), ".png")) {
log.Printf("1 :: Walking in the trees : %s with %d bytes\n", path, f.Size())
n.Add(1)
filesChannel <- path
}
return nil
}
// walk into the tree in a dark forest
for _, p := range os.Args[1:] {
filepath.Walk(p, callback)
}
// we can close the channel because filepath.Walk is blocking
// do not run 'filepath.Walk' into a goroutine
// else you could not know when it ends to close the channel
log.Println("Close Files Channel")
close(filesChannel)
// signals the end of last worker
log.Println("Waiting for last worker converter..")
wgConvert.Wait()
log.Println("Last worker converter is dead")
// all the converter have done their job to push exif into outchan.
// so we can close outchan
close(exifChannel)
// signals the end of last worker
log.Println("Waiting for last worker emetter..")
wgTelegraf.Wait()
log.Println("Last worker emetter is dead")
// success
log.Printf("Exit %v\n", time.Since(t0))
//os.Exit(0)
} |
# <API key>: true
module Renalware
module ClinicalHelper
def <API key>(patient)
breadcrumb_for("Clinical Profile", <API key>(patient))
end
end
end |
#!/usr/bin/env python
from setuptools import setup
setup(name='RQ-Cron',
version='1.0.2',
description='RQ Cron',
author='Andrii Kostenko',
author_email='andrey@kostenko.name',
packages=['rq_cron', 'rq_cron.scripts'],
install_requires=['rq>=0.3.5', 'croniter'],
entry_points='''\
[console_scripts]
rq-cron = rq_cron.scripts.rq_cron:run_scheduler
''',
url='https://github.com/Healthjoy/rq-cron',
) |
local keys = require 'posts.repository.keys'
local cache
local cached
do
local config = require 'config'
cache = config.cache
cached = require 'caching.cached'
cached = cached.new {cache = cache, time = 3600}
end
-- region: posts repository
local function search_posts(self, q, page)
return self.inner:search_posts(q, page)
end
local function get_post_id(self, slug)
return self.inner:get_post_id(slug)
end
local function get_post(self, slug)
return self.inner:get_post(slug)
end
local function list_comments(self, post_id, author_id)
return self.inner:list_comments(post_id, author_id)
end
local function <API key>(self, user_id, limit)
return self.inner:<API key>(user_id, limit)
end
local function add_post_comment(self, post_id, author_id, message)
local ok = self.inner:add_post_comment(post_id, author_id, message)
if ok then
cache:delete(keys.list_comments(post_id, author_id))
cache:delete(keys.<API key>(author_id))
end
return ok
end
return {
posts = {
search_posts = cached:get_or_set(keys.search_posts, search_posts),
get_post_id = cached:get_or_set(keys.get_post_id, get_post_id),
get_post = cached:get_or_set(keys.get_post, get_post),
list_comments = cached:get_or_set(keys.list_comments, list_comments),
<API key> = cached:get_or_set(
keys.<API key>,
<API key>),
add_post_comment = add_post_comment
}
} |
"use strict";var l={"FLK":["FLK","Falklandeilanden"],"CHL":["CHL","Chili"],"TTO":["TTO","Trinidad en Tobago"],"GUF":["GUF","Frans-Guyana"],"BRA":["BRA","Brazili\u00EB"],"ARG":["ARG","Argentini\u00EB"]};(this?this:window)['DvtBaseMapManager']['_UNPROCESSED_MAPS'][2].push(["southAmerica","countries",l]); |
.app-header {
background-image: -webkit-gradient(linear,50% 0,50% 100%,color-stop(0%,#8fc33a),color-stop(100%,#739b2e));
background-image: -<API key>(top,#8fc33a,#739b2e);
background-image: -moz-linear-gradient(top,#8fc33a,#739b2e);
background-image: -o-linear-gradient(top,#8fc33a,#739b2e);
background-image: linear-gradient(top,#8fc33a,#739b2e);
border-bottom: 1px solid #567422;
}
.app-header-title {
padding: 15px 10px 10px 31px;
background: url(images/logo.png) no-repeat 10px 11px;
color: white;
font-size: 18px;
font-weight: bold;
text-shadow: 0 1px 0 #4e691f;
} |
package seedu.task.storage;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import seedu.task.commons.events.model.<API key>;
import seedu.task.commons.events.storage.<API key>;
import seedu.task.model.ReadOnlyTaskList;
import seedu.task.model.TaskList;
import seedu.task.model.UserPrefs;
import seedu.task.testutil.EventsCollector;
import seedu.task.testutil.TypicalTestTasks;
public class StorageManagerTest {
private StorageManager storageManager;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Before
public void setUp() {
storageManager = new StorageManager(getTempFilePath("ab"), getTempFilePath("prefs"));
}
private String getTempFilePath(String fileName) {
return testFolder.getRoot().getPath() + fileName;
}
@Test
public void prefsReadSave() throws Exception {
/*
* Note: This is an integration test that verifies the StorageManager is properly wired to the
* {@link <API key>} class.
* More extensive testing of UserPref saving/reading is done in {@link <API key>} class.
*/
UserPrefs original = new UserPrefs();
original.setGuiSettings(300, 600, 4, 6);
storageManager.saveUserPrefs(original);
UserPrefs retrieved = storageManager.readUserPrefs().get();
assertEquals(original, retrieved);
}
@Test
public void addressBookReadSave() throws Exception {
/*
* Note: This is an integration test that verifies the StorageManager is properly wired to the
* {@link <API key>} class.
* More extensive testing of UserPref saving/reading is done in {@link <API key>} class.
*/
TaskList original = new TypicalTestTasks().<API key>();
storageManager.saveTaskList(original);
ReadOnlyTaskList retrieved = storageManager.readTaskList().get();
assertEquals(original, new TaskList(retrieved));
}
@Test
public void <API key>() {
assertNotNull(storageManager.getTaskListFilePath());
}
@Test
public void <API key>() throws IOException {
// Create a StorageManager while injecting a stub that throws an exception when the save method is called
Storage storage = new StorageManager(new <API key>("dummy"),
new <API key>("dummy"));
EventsCollector eventCollector = new EventsCollector();
storage.<API key>(new <API key>(new TaskList()));
assertTrue(eventCollector.get(0) instanceof <API key>);
}
/**
* A Stub class to throw an exception when the save method is called
*/
class <API key> extends XmlTaskListStorage {
public <API key>(String filePath) {
super(filePath);
}
@Override
public void saveTaskList(ReadOnlyTaskList taskList, String filePath) throws IOException {
throw new IOException("dummy exception");
}
}
} |
# telerobot
Telepresence robot server prototype written in Go and running on Revel. To be used in conjunction with a differential wheeled robot powered by a Particle Photon (or Core) microcontroller.
## Configuration
Copy `telerobot_conf.json.sample` to `~/.telerobot_conf.json` and update with the device id and access token of the particle microcontroller.
Start the web server:
revel run github.com/kldavis4/telerobot
Run with <tt>--help</tt> for options.
Go to http://localhost:9000/
This page allows control via the virtual joystick. There is a device status indicator at the top left (green = connected, red = not connected, purple = web application error).
Got to http://localhost:9000/program
This page allows control via a list of motion commands. |
import * as Scrivito from 'scrivito'
Scrivito.<API key>('FactCounterWidget', {
title: 'Fact Counter',
attributes: {
key: {
title: 'Key'
},
value: {
title: 'Value'
},
postfix: {
title: 'Postfix'
},
speed: {
title: 'Speed',
values: [
{ value: '150', title: 'Normal' },
{ value: '200', title: 'Slow' },
{ value: '100', title: 'Fast' }
]
},
animation: {
title: 'Animation',
description: 'The animation to perform as this image becomes visible. Default: None',
values: [
{ value: 'none', title: 'None' },
{ value: 'fadeInLeft', title: 'Left to center' },
{ value: 'fadeInRight', title: 'Right to center' },
{ value: 'fadeInDown', title: 'Top to center' },
{ value: 'fadeInUp', title: 'Bottom to center' },
{ value: 'zoomIn', title: 'Zoom in' }
]
}
},
properties: [
'key',
'value',
'postfix',
'speed',
'animation'
],
initialContent: {
key: 'Lorem ipsum',
value: '12',
postfix: 'Jahre',
animation: 'none'
}
}) |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using TankStudios.Interfaces;
using TankStudios.Models;
namespace TankStudios.Controllers
{
public class HomeController : Controller
{
private IContactService _contactService;
public HomeController(IContactService contactService)
{
_contactService = contactService;
}
public ActionResult Index()
{
return View();
}
[HttpPost]
[<API key>]
public async Task<ActionResult> Contact(ContactModel model)
{
await _contactService.SendContactMessage(model.FirstName, model.LastName, model.Email, model.Message);
return RedirectToAction("Index");
}
}
} |
The MIT License (MIT)
Copyright (c) 2014 codemix ltd.
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. |
from nltk.tokenize import word_tokenize
from nltk.stem.snowball import EnglishStemmer
from nltk.corpus import stopwords
from collections import defaultdict
from search_backend.search_index import searchIndex
import operator
#from iRnWsLeo.search_backend.search_index import searchIndex
#from search_backend.create_index import index_files
#from iRnWsLeo.search_backend.create_index import index_files
#nltk.download('stopwords')
stemmer = EnglishStemmer()
stopwords = set(stopwords.words('english'))
searchIndex = searchIndex()
#index = index_files()
def search(query_string, database):
result_list = []
term_list = []
for term in word_tokenize(query_string):
term.lower()
term = stemmer.stem(term)
if term in stopwords:
continue
term_list.append(term)
if searchIndex.searchDoc != None:
context_list, ranking_list = searchIndex.ranking_and(term_list, database)
search_results = sorted(ranking_list.items(), key=lambda kv: (-kv[1], kv[0]), reverse=True)
#for key, value in sorted(docs.items(), key=lambda kv: (-kv[1], kv[0])):
if (context_list == []) or (context_list == None) or (context_list == defaultdict(None, {})):
result_list.append({
'title': 'Failed search',
'snippet': 'You will not find "{}"'
' here, try our competitor'.format(query_string),
'href': 'http:
})
else:
for key in search_results:
result_list.append({
'title': '{}'.format(key[0]),
'snippet': '<b>Context</b>: ...{}...<br/><b>Summary</b>: '
'{}<br/>ranking: {}'.format(
context_list[key[0]]['snippet'],
context_list[key[0]]['summary'],
context_list[key[0]]['bm25']),
'href': 'http:
})
return result_list |
module Logchange
# Store configuration for this gem.
class Configuration
attr_accessor :changelog_directory
attr_accessor :root_path
def initialize
@changelog_directory = 'changelog'
@root_path = Dir.pwd
end
def <API key>
File.join(@root_path, @changelog_directory)
end
end
end |
public class _69Sqrt_x {
public int mySqrt(int x) {
if (x <= 0 ) return 0;
int start =1;
int end = x;
while (true){
int mid = start + (end - start)/2;
if (x/mid < mid){
end = mid - 1;
}else{
if (x /(mid + 1) < mid + 1){
return mid;
}else{
start = mid +1;
}
}
}//while
}
public static void main(String[] args) {
// TODO Auto-generated method stub
_69Sqrt_x A = new _69Sqrt_x();
System.out.println(A.mySqrt(24));
}
}
//question:
//Implement int sqrt(int x).
//Compute and return the square root of x. |
var path = require('path')
, assert = require('assert')
, Mincer = require('mincer');
describe('Mincer', function() {
var templateProjectPath = path.resolve(__dirname, '../templates/project');
var mincer = {};
before(function(done) {
mincer.environment = new Mincer.Environment();
mincer.assets_prefix = '/assets';
mincer.environment.appendPath(templateProjectPath + '/assets/javascripts');
mincer.environment.appendPath(templateProjectPath + '/assets/stylesheets');
mincer.environment.appendPath(templateProjectPath + '/assets/fonts');
mincer.environment.appendPath(templateProjectPath + '/assets/images');
mincer.environment.appendPath(templateProjectPath + '/widgets');
mincer.environment.appendPath(path.resolve(__dirname, '../javascripts'));
done();
});
/*
it('should compile "application.js" without errors', function(done) {
mincer.environment.findAsset('application.js').compile(function(err, asset) {
done();
});
});
it('should compile "application.css" without errors', function(done) {
mincer.environment.findAsset('application.css').compile(function(err, asset) {
done();
});
});
*/
/* Mincer 0.5.x */
it('should compile "application.js" without errors', function(done) {
if (mincer.environment.findAsset('application.coffee')) {
done();
}
});
it('should compile "application.css" without errors', function(done) {
if (mincer.environment.findAsset('application.scss')) {
done();
}
});
}); |
<?php
namespace Idealspoon\FrontendBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class <API key> extends Bundle
{
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { <API key> } from './groups-edit-page.component';
describe('<API key>', () => {
let component: <API key>;
let fixture: ComponentFixture<<API key>>;
beforeEach(async(() => {
TestBed.<API key>({
declarations: [ <API key> ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(<API key>);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
}); |
import { FieldConfig, Field } from 'formik';
import * as React from 'react';
import InlineErrorView from 'shared/view/elements/Errors/InlineErrorView/InlineErrorView';
import MuiTextInput from 'shared/view/elements/MuiTextInput/MuiTextInput';
type AllProps = FieldConfig &
Omit<
React.ComponentProps<typeof MuiTextInput>,
'value' | 'onChange' | 'onBlur' | 'name' | 'error'
> & {
hint?: React.ReactNode;
dataTestError?: string;
isClerableInput?: boolean;
};
export default class MuiTextInputField extends React.Component<AllProps> {
public render() {
return (
<Field {...this.props}>
{({ field, meta, form }: any) => {
const isShowError = meta.touched && meta.error;
return (
<div>
<div style={{ position: 'relative' }}>
<MuiTextInput
multiline={this.props.multiline}
size={this.props.size}
rows={this.props.rows}
value={field.value}
name={field.name}
disabled={this.props.disabled}
label={this.props.label}
dataTest={this.props.dataTest}
error={Boolean(this.props.isClerableInput && isShowError)}
resetValueControl={
(this.props.isClerableInput &&
form.initialValues[this.props.name] !== field.value) ||
isShowError
? {
onReset: () => {
form.resetForm();
setTimeout(() => {
form.validateForm();
}, 0);
},
}
: undefined
}
placeholder={this.props.placeholder}
onChange={field.onChange}
onBlur={field.onBlur}
/>
</div>
{isShowError ? (
<InlineErrorView
error={meta.error}
dataTest={this.props.dataTestError}
/>
) : (
this.props.hint || null
)}
</div>
);
}}
</Field>
);
}
} |
local lib = require"log4l"
assert(lib.tostring{1, 2, 3, 4, 5, 6, 7, 8, 9} == "{1, 2, 3, 4, 5, 6, 7, 8, 9}", "test is incorrect")
assert(lib.tostring{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} == "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}", "numbers were reordered")
assert(lib.tostring{[45] = 1, 5} == "{5, [45] = 1}", "out-of-order numbers did not sort")
local self_ref = {}
self_ref[self_ref] = self_ref
lib.tostring(self_ref)
local normal = {}
assert(lib.tostring{normal} == '{{}}', "simple case incorrect")
assert(lib.tostring{normal, normal} == '{{}, {}}', "non-nested case incorrect") |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class templateWA extends MX_Controller {
public function __construct(){
parent::__construct();
}
public function getmenucategorias(){
$this->load->model('getmenucategorias');
$u = $this->getmenucategorias->getmenucategorias();
$u->where("ativado", true);
$u->order_by("position", "ASC");
$a = $u->get();
foreach ($a->all as $MenuCategoria)
{
if($MenuCategoria->acess > $this->session->userdata('login_acess')){
continue;
}
if($MenuCategoria->acess < '99'){
$categorias[] = array($MenuCategoria->id => array('categoria' => $this->lang->line($MenuCategoria->categoria), 'acess' => $MenuCategoria->acess, 'img_icon' => $MenuCategoria->img_icon));
}
}
return $categorias;
}
public function getlangs(){
$u = new getlangs();
$u->where("ativado", true);
$u->order_by("nome", "ASC");
$a = $u->get();
foreach ($a->all as $Lang)
{
$arr[] = array('lang_prefix' => $Lang->lang_prefix, 'lang_nome' => $Lang->nome);
}
return $arr;
}
public function getmenu(){
$this->load->model('getmenulinks');
$u = new getmenulinks();
$u->where("ativado", true);
$u->order_by("position", "ASC");
$a = $u->get();
foreach ($a->all as $MenuLink)
{
$a->get_by_categoria($MenuLink->categoria);
if($MenuLink->logged == '1')
{
if(!modules::run('account/_needlogin', FALSE))
{
continue;
}
}
if($MenuLink->logged == '2')
{
if(modules::run('account/_needlogin', FALSE))
{
continue;
}
}
if($MenuLink->acess > $this->session->userdata('login_acess')){
continue;
}
if(isset($arr[$a->categoria]) and is_array($arr[$a->categoria]))
{
if(!strstr($MenuLink->link_href, 'http:
$MenuLink->link_href = site_url($MenuLink->link_href);
}
$arr[$a->categoria] = array_merge($arr[$a->categoria], array($MenuLink->id => array('link_href' => $MenuLink->link_href, 'link_title' => $this->lang->line($MenuLink->link_title), 'acess' => $MenuLink->acess, 'img_icon' => $MenuLink->img_icon)));
}
else
{
if(!strstr($MenuLink->link_href, 'http:
$MenuLink->link_href = site_url($MenuLink->link_href);
}
$arr[$a->categoria] = array($MenuLink->id => array('link_href' => $MenuLink->link_href, 'link_title' => $this->lang->line($MenuLink->link_title), 'acess' => $MenuLink->acess, 'img_icon' => $MenuLink->img_icon));
}
}
return $arr;
}
}
/* End of file templateWA.php */
/* Location: ./modules/statistic/controllers/templateWA.php */ |
require 'rack/utils'
module Rack
# Middleware that enables conditional GET using If-None-Match and
# If-Modified-Since. The application should set either or both of the
# Last-Modified or Etag response headers according to RFC 2616. When
# either of the conditions is met, the response body is set to be zero
# length and the response status is set to 304 Not Modified.
# Applications that defer response body generation until the body's each
# message is received will avoid response body generation completely when
# a conditional GET matches.
# Adapted from Michael Klishin's Merb implementation:
class ConditionalGet
def initialize(app)
@app = app
end
def call(env)
case env['REQUEST_METHOD']
when "GET", "HEAD"
status, headers, body = @app.call(env)
headers = Utils::HeaderHash.new(headers)
if status == 200 && fresh?(env, headers)
status = 304
headers.delete('Content-Type')
headers.delete('Content-Length')
body = []
end
[status, headers, body]
else
@app.call(env)
end
end
private
def fresh?(env, headers)
modified_since = env['<API key>']
none_match = env['HTTP_IF_NONE_MATCH']
return false unless modified_since || none_match
success = true
success &&= modified_since?(to_rfc2822(modified_since), headers) if modified_since
success &&= etag_matches?(none_match, headers) if none_match
success
end
def etag_matches?(none_match, headers)
etag = headers['ETag'] and etag == none_match
end
def modified_since?(modified_since, headers)
last_modified = to_rfc2822(headers['Last-Modified']) and
modified_since and
modified_since >= last_modified
end
def to_rfc2822(since)
# shortest possible valid date is the obsolete: 1 Nov 97 09:55 A
# anything shorter is invalid, this avoids exceptions for common cases
# most common being the empty string
if since && since.length >= 16
# NOTE: there is no trivial way to write this in a non execption way
# _rfc2822 returns a hash but is not that usable
Time.rfc2822(since) rescue nil
else
nil
end
end
end
end |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Solution
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine()); // the number of temperatures to analyse
string temps = Console.ReadLine(); // the n temperatures expressed as integers ranging from -273 to 5526
if (n == 0)
{
Console.WriteLine("0");
}
else
{
var temperatures = temps.Split(' ').Select(x => int.Parse(x));
var closestT = temperatures
.Select(x => new { t = x, absT = Math.Abs(x) })
.OrderBy(x => x.absT)
.ThenByDescending(x => x.t)
.First()
.t;
Console.WriteLine(closestT.ToString());
}
}
} |
import { <API key> } from '../creative/creative_linear';
import { <API key> } from '../closed_caption_file';
import { createIcon } from '../icon';
import { <API key> } from '../<API key>';
import { createMediaFile } from '../media_file';
import { createMezzanine } from '../mezzanine';
import { parserUtils } from './parser_utils';
/**
* This module provides methods to parse a VAST Linear Element.
*/
/**
* Parses a Linear element.
* @param {Object} creativeElement - The VAST Linear element to parse.
* @param {any} creativeAttributes - The attributes of the Linear (optional).
* @return {Object} creative - The creativeLinear object.
*/
export function parseCreativeLinear(creativeElement, creativeAttributes) {
let offset;
const creative = <API key>(creativeAttributes);
creative.duration = parserUtils.parseDuration(
parserUtils.parseNodeText(
parserUtils.childByName(creativeElement, 'Duration')
)
);
const skipOffset = creativeElement.getAttribute('skipoffset');
if (typeof skipOffset === 'undefined' || skipOffset === null) {
creative.skipDelay = null;
} else if (
skipOffset.charAt(skipOffset.length - 1) === '%' &&
creative.duration !== -1
) {
const percent = parseInt(skipOffset, 10);
creative.skipDelay = creative.duration * (percent / 100);
} else {
creative.skipDelay = parserUtils.parseDuration(skipOffset);
}
const videoClicksElement = parserUtils.childByName(
creativeElement,
'VideoClicks'
);
if (videoClicksElement) {
const <API key> = parserUtils.childByName(
videoClicksElement,
'ClickThrough'
);
if (<API key>) {
creative.<API key> = {
id: <API key>.getAttribute('id') || null,
url: parserUtils.parseNodeText(<API key>),
};
} else {
creative.<API key> = null;
}
parserUtils
.childrenByName(videoClicksElement, 'ClickTracking')
.forEach((<API key>) => {
creative.<API key>.push({
id: <API key>.getAttribute('id') || null,
url: parserUtils.parseNodeText(<API key>),
});
});
parserUtils
.childrenByName(videoClicksElement, 'CustomClick')
.forEach((customClickElement) => {
creative.<API key>.push({
id: customClickElement.getAttribute('id') || null,
url: parserUtils.parseNodeText(customClickElement),
});
});
}
const adParamsElement = parserUtils.childByName(
creativeElement,
'AdParameters'
);
if (adParamsElement) {
creative.adParameters = parserUtils.parseNodeText(adParamsElement);
}
parserUtils
.childrenByName(creativeElement, 'TrackingEvents')
.forEach((<API key>) => {
parserUtils
.childrenByName(<API key>, 'Tracking')
.forEach((trackingElement) => {
let eventName = trackingElement.getAttribute('event');
const trackingURLTemplate =
parserUtils.parseNodeText(trackingElement);
if (eventName && trackingURLTemplate) {
if (eventName === 'progress') {
offset = trackingElement.getAttribute('offset');
if (!offset) {
return;
}
if (offset.charAt(offset.length - 1) === '%') {
eventName = `progress-${offset}`;
} else {
eventName = `progress-${Math.round(
parserUtils.parseDuration(offset)
)}`;
}
}
if (!Array.isArray(creative.trackingEvents[eventName])) {
creative.trackingEvents[eventName] = [];
}
creative.trackingEvents[eventName].push(trackingURLTemplate);
}
});
});
parserUtils
.childrenByName(creativeElement, 'MediaFiles')
.forEach((mediaFilesElement) => {
parserUtils
.childrenByName(mediaFilesElement, 'MediaFile')
.forEach((mediaFileElement) => {
creative.mediaFiles.push(parseMediaFile(mediaFileElement));
});
const <API key> = parserUtils.childByName(
mediaFilesElement,
'<API key>'
);
if (<API key>) {
creative.<API key> = <API key>(
<API key>
);
}
const <API key> = parserUtils.childByName(
mediaFilesElement,
'ClosedCaptionFiles'
);
if (<API key>) {
parserUtils
.childrenByName(<API key>, 'ClosedCaptionFile')
.forEach((<API key>) => {
const closedCaptionFile = <API key>(
parserUtils.parseAttributes(<API key>)
);
closedCaptionFile.fileURL =
parserUtils.parseNodeText(<API key>);
creative.closedCaptionFiles.push(closedCaptionFile);
});
}
const mezzanineElement = parserUtils.childByName(
mediaFilesElement,
'Mezzanine'
);
const requiredAttributes = <API key>(mezzanineElement, [
'delivery',
'type',
'width',
'height',
]);
if (requiredAttributes) {
const mezzanine = createMezzanine();
mezzanine.id = mezzanineElement.getAttribute('id');
mezzanine.fileURL = parserUtils.parseNodeText(mezzanineElement);
mezzanine.delivery = requiredAttributes.delivery;
mezzanine.codec = mezzanineElement.getAttribute('codec');
mezzanine.type = requiredAttributes.type;
mezzanine.width = parseInt(requiredAttributes.width, 10);
mezzanine.height = parseInt(requiredAttributes.height, 10);
mezzanine.fileSize = parseInt(
mezzanineElement.getAttribute('fileSize'),
10
);
mezzanine.mediaType =
mezzanineElement.getAttribute('mediaType') || '2D';
creative.mezzanine = mezzanine;
}
});
const iconsElement = parserUtils.childByName(creativeElement, 'Icons');
if (iconsElement) {
parserUtils.childrenByName(iconsElement, 'Icon').forEach((iconElement) => {
creative.icons.push(parseIcon(iconElement));
});
}
return creative;
}
/**
* Parses the MediaFile element from VAST.
* @param {Object} mediaFileElement - The VAST MediaFile element.
* @return {Object} - Parsed mediaFile object.
*/
function parseMediaFile(mediaFileElement) {
const mediaFile = createMediaFile();
mediaFile.id = mediaFileElement.getAttribute('id');
mediaFile.fileURL = parserUtils.parseNodeText(mediaFileElement);
mediaFile.deliveryType = mediaFileElement.getAttribute('delivery');
mediaFile.codec = mediaFileElement.getAttribute('codec');
mediaFile.mimeType = mediaFileElement.getAttribute('type');
mediaFile.mediaType = mediaFileElement.getAttribute('mediaType') || '2D';
mediaFile.apiFramework = mediaFileElement.getAttribute('apiFramework');
mediaFile.fileSize = parseInt(mediaFileElement.getAttribute('fileSize') || 0);
mediaFile.bitrate = parseInt(mediaFileElement.getAttribute('bitrate') || 0);
mediaFile.minBitrate = parseInt(
mediaFileElement.getAttribute('minBitrate') || 0
);
mediaFile.maxBitrate = parseInt(
mediaFileElement.getAttribute('maxBitrate') || 0
);
mediaFile.width = parseInt(mediaFileElement.getAttribute('width') || 0);
mediaFile.height = parseInt(mediaFileElement.getAttribute('height') || 0);
const scalable = mediaFileElement.getAttribute('scalable');
if (scalable && typeof scalable === 'string') {
mediaFile.scalable = parserUtils.parseBoolean(scalable);
}
const maintainAspectRatio = mediaFileElement.getAttribute(
'maintainAspectRatio'
);
if (maintainAspectRatio && typeof maintainAspectRatio === 'string') {
mediaFile.maintainAspectRatio =
parserUtils.parseBoolean(maintainAspectRatio);
}
return mediaFile;
}
/**
* Parses the <API key> element from VAST MediaFiles node.
* @param {Object} <API key> - The VAST <API key> element.
* @return {Object} - Parsed <API key> object.
*/
function <API key>(<API key>) {
const <API key> = <API key>(
parserUtils.parseAttributes(<API key>)
);
<API key>.fileURL = parserUtils.parseNodeText(
<API key>
);
return <API key>;
}
/**
* Parses the Icon element from VAST.
* @param {Object} iconElement - The VAST Icon element.
* @return {Object} - Parsed icon object.
*/
function parseIcon(iconElement) {
const icon = createIcon(iconElement);
icon.program = iconElement.getAttribute('program');
icon.height = parseInt(iconElement.getAttribute('height') || 0);
icon.width = parseInt(iconElement.getAttribute('width') || 0);
icon.xPosition = parseXPosition(iconElement.getAttribute('xPosition'));
icon.yPosition = parseYPosition(iconElement.getAttribute('yPosition'));
icon.apiFramework = iconElement.getAttribute('apiFramework');
icon.pxratio = iconElement.getAttribute('pxratio') || '1';
icon.offset = parserUtils.parseDuration(iconElement.getAttribute('offset'));
icon.duration = parserUtils.parseDuration(
iconElement.getAttribute('duration')
);
parserUtils
.childrenByName(iconElement, 'HTMLResource')
.forEach((htmlElement) => {
icon.type = htmlElement.getAttribute('creativeType') || 'text/html';
icon.htmlResource = parserUtils.parseNodeText(htmlElement);
});
parserUtils
.childrenByName(iconElement, 'IFrameResource')
.forEach((iframeElement) => {
icon.type = iframeElement.getAttribute('creativeType') || 0;
icon.iframeResource = parserUtils.parseNodeText(iframeElement);
});
parserUtils
.childrenByName(iconElement, 'StaticResource')
.forEach((staticElement) => {
icon.type = staticElement.getAttribute('creativeType') || 0;
icon.staticResource = parserUtils.parseNodeText(staticElement);
});
const iconClicksElement = parserUtils.childByName(iconElement, 'IconClicks');
if (iconClicksElement) {
icon.<API key> = parserUtils.parseNodeText(
parserUtils.childByName(iconClicksElement, 'IconClickThrough')
);
parserUtils
.childrenByName(iconClicksElement, 'IconClickTracking')
.forEach((<API key>) => {
icon.<API key>.push({
id: <API key>.getAttribute('id') || null,
url: parserUtils.parseNodeText(<API key>),
});
});
}
icon.<API key> = parserUtils.parseNodeText(
parserUtils.childByName(iconElement, 'IconViewTracking')
);
return icon;
}
/**
* Parses an horizontal position into a String ('left' or 'right') or into a Number.
* @param {String} xPosition - The x position to parse.
* @return {String|Number}
*/
function parseXPosition(xPosition) {
if (['left', 'right'].indexOf(xPosition) !== -1) {
return xPosition;
}
return parseInt(xPosition || 0);
}
/**
* Parses an vertical position into a String ('top' or 'bottom') or into a Number.
* @param {String} yPosition - The x position to parse.
* @return {String|Number}
*/
function parseYPosition(yPosition) {
if (['top', 'bottom'].indexOf(yPosition) !== -1) {
return yPosition;
}
return parseInt(yPosition || 0);
}
/**
* Getting required attributes from element
* @param {Object} element - DOM element
* @param {Array} attributes - list of attributes
* @return {Object|null} null if a least one element not present
*/
function <API key>(element, attributes) {
const values = {};
let error = false;
attributes.forEach((name) => {
if (!element || !element.getAttribute(name)) {
error = true;
} else {
values[name] = element.getAttribute(name);
}
});
return error ? null : values;
} |
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css">
<title>favourite app</title>
</head>
<body>
<h1 class = "title">My app</h1>
<div class="app">
<div class="image"><img src = "images/app.png" alt="app image"></div>
<div class="description">Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem.s Donec rutrum congue leo eget malesuada. Sed porttitor lectus nibh. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis lorem ut libero malesuada feugiat.</div>
</div>
</body>
</html> |
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
<!--Coment
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]
<!-- Add your site or application content here -->
<p>Hello world! This is HTML5 Boilerplate.</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.<API key>=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.<API key>(i)[0];
e.src='
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X');ga('send','pageview');
</script>
</body>
</html> |
import { Battle, Game, Suit, Card, PlayersBid, Player, TrumpAnnouncement, CardPattern } from '../game.interfaces';
import { getNextTurn, getPlayerById, <API key> } from './players.helpers';
import * as _ from 'lodash';
import { getHighestBid } from './bid.helpers';
import { getPointsByCard, <API key>, areCardsEqual, getCardsByColor, <API key>, <API key>, toCard } from './cards.helpers';
export function getNextTrickTurn(state: Game, player: string = state.battle.leadPlayer): string {
const gamePlayers = state.players;
const { battle } = state;
return _.reduce(battle.trickCards, (nextPlayer) => getNextTurn(gamePlayers, nextPlayer), player);
}
export function getTrumpSuit(battle: Battle): Suit | null {
return battle.trumpAnnouncements.length > 0 ? battle.trumpAnnouncements[0].suit : null;
}
export function isTrumpAnnounced(battle: Battle): boolean {
return !!getTrumpSuit(battle);
}
export function isTableEmpty(battle: Battle): boolean {
return battle.trickCards.length === 0;
}
export function getLeadCard(battle: Battle): CardPattern {
return battle.trickCards[0];
}
export function getCardSuit(card: CardPattern): Suit {
return toCard(card).suit;
}
export function roundPoints(points: number): number {
const minor = (points % 10);
const major = points - minor;
return minor >= 5 ? major + 10 : major;
}
export function <API key>(state: Game, player: string): number {
return _.chain(state.battle.trumpAnnouncements)
.filter((trumpAnnouncement: TrumpAnnouncement) => trumpAnnouncement.player === player)
.map('suit')
.map(<API key>)
.sum()
.value();
}
export function <API key>(state: Game, player: string): number {
return _.chain(state.battle.wonCards[player])
.map(toCard)
.map(getPointsByCard)
.sum()
.value();
}
export function getTotalWonCards(state: Game): number {
return _.reduce(state.battle.wonCards, (totalCards, cards) => {
return totalCards + cards.length;
}, 0);
}
export function <API key>(state: Game, player: string): number {
const {player: leadPlayer, bid: leadBidValue}: PlayersBid = getHighestBid(state.bid);
const playerPoints = <API key>(getPlayerById(state.players, player));
const trumpPoints = <API key>(state, player);
const cardPoints = <API key>(state, player);
const totalPoints = trumpPoints + cardPoints;
if (leadPlayer === player) {
return (totalPoints >= leadBidValue) ? leadBidValue : -leadBidValue
} else {
return playerPoints >= state.settings.barrelPointsLimit ? 0 : roundPoints(totalPoints);
}
}
export function <API key>(trickCard: CardPattern, state: Game): string {
const { battle: { leadPlayer, trickCards }, players } = state;
return _.chain(trickCards)
.dropRightWhile(card => !areCardsEqual(card, trickCard))
.reduce((player: string) => player ? getNextTurn(players, player) : leadPlayer, null)
.value();
}
export function getTrickWinner(state: Game): string {
const { battle } = state;
const { trickCards } = battle;
const leadCard: CardPattern = getLeadCard(battle);
let winnerPlayerId = null;
console.log('test!')
if(isTrumpAnnounced(battle)) {
console.log('test2!')
const trumpSuit: Suit = getTrumpSuit(battle);
if (<API key>(trickCards, trumpSuit)) {
console.log('test3!')
matchBySuit(trumpSuit);
} else {
//no trump cards taking part in the trick, so ordinary color matching flow:
matchBySuit(getCardSuit(leadCard));
}
} else {
matchBySuit(getCardSuit(leadCard));
}
return winnerPlayerId;
function matchBySuit(suit: Suit) {
const cardsMatchedByColor = getCardsByColor(trickCards, suit);
const highestRankedCard = <API key>(cardsMatchedByColor);
winnerPlayerId = <API key>(highestRankedCard, state);
}
} |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-25 18:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('transcript', '<API key>'),
]
operations = [
migrations.AddField(
model_name='transcript',
name='active',
field=models.BooleanField(default=True),
),
] |
using System;
namespace csCommon.Types.DataServer.PoI
{
// TODO Add the code to parse CSV files.
// TODO Check whether we already have a DS that represents a CSV
// TODO See csDataServerPlugin.DataServerPlugin.InitShapeLayers to instantiate the Csv
// TODO Watch the folders for new shape files or CSVs
// TODO Generate a CSV from a layer
public abstract class CsvService : ExtendedPoiService // TODO Review: made abstract so it is not used.
{
public new static CsvService CreateService(string name, Guid id, string folder = "", string relativeFolder = "")
{
throw new <API key>("CsvService implementation requires a lot of reviewing & may not be needed anymore.");
return ExtendedPoiService.CreateService(name, id, folder, relativeFolder) as CsvService;
}
protected override Exception ProcessFile()
{
return base.ProcessFile();
// TODO Add the code to process the CSV
}
}
} |
package com.winterwell.web.fields;
import com.winterwell.utils.web.WebUtils;
/**
* A field with a fixed value.
*
* @author Daniel
*/
public class UnmodifiableField<X> extends AField<X> {
private static final long serialVersionUID = 1L;
private String displayValue;
private X value;
/**
*
* @param field
* @param value
* The text will be blank if this is null
*/
public UnmodifiableField(AField<X> field, X value) {
this(field, value, value == null ? "" : field.toString(value));
}
public UnmodifiableField(AField<X> field, X value, String displayValue) {
this(field.getName(), value, displayValue);
}
public UnmodifiableField(String fieldName, X value, String displayValue) {
super(fieldName, "hidden");
this.value = value;
this.displayValue = displayValue;
}
public void appendHtmlTo(StringBuilder page, X ignoreMe) {
super.appendHtmlTo(page, value);
// some sort of container element?
page.append("<input type='text' disabled='true' value='"
+ WebUtils.attributeEncode(displayValue) + "'>");
}
@Override
public Class<X> getValueClass() {
return value==null? null : (Class<X>) value.getClass();
}
} |
/* eslint no-undef: "off" */
import delay from 'api/__mocks__/delay';
import breadcrumbs from 'api/__fakeData__/breadcrumbs';
class BreadcrumbsApi {
static getForumBreadcrumbs(forumId) {
let result;
if (!forumId) {
result = [];
}
else if(parseInt(forumId)<10){
result = [
breadcrumbs[0],
{path: `/Conference/Forum/${forumId}`, title: `Forum id #${forumId}`, level: 2}
];
}
else if(parseInt(forumId)>=10 && parseInt(forumId)<100 ){
result = [
breadcrumbs[0],
{path: `/Conference/Forum/${Math.floor(parseInt(forumId)/10)}`, title: `Forum id #${Math.floor(parseInt(forumId)/10)}`, level: 2},
{path: `/Conference/Forum/${forumId}`, title: `Forum id #${forumId}`, level: 3}
];
}
return new Promise((resolve)=>{
setTimeout(() => {
resolve(Object.assign([], result));
}, delay);
});
}
static getTopicBreadcrumbs(topicId) {
let result;
if (!topicId) {
result = [];
}
else if(parseInt(topicId)<10){
result = [
breadcrumbs[0],
{path: `/Conference/Forum/${topicId}`, title: `Forum id #${topicId}`, level: 2},
{path: `/Conference/Topic/${topicId}`, title: `Topic id #${topicId}`, level: 3}
];
}
else if(parseInt(topicId)>=10 && parseInt(topicId)<100 ){
result = [
breadcrumbs[0],
{path: `/Conference/Forum/${Math.floor(parseInt(topicId)/10)}`, title: `Forum id #${Math.floor(parseInt(topicId)/10)}`, level: 2},
{path: `/Conference/Forum/${topicId}`, title: `Forum id #${topicId}`, level: 3},
{path: `/Conference/Topic/${topicId}`, title: `Topic id #${topicId}`, level: 4}
];
}
return new Promise((resolve)=>{
setTimeout(() => {
resolve(Object.assign([], result));
}, delay);
});
}
}
export default BreadcrumbsApi; |
class Thor
module Actions
# Creates an empty directory.
# destination<String>:: the relative path to the destination root.
# config<Hash>:: give :verbose => false to not log the status.
# empty_directory "doc"
def empty_directory(destination, config={})
action EmptyDirectory.new(self, destination, config)
end
# Class which holds create directory logic. This is the base class for
# other actions like create_file and directory.
class EmptyDirectory #:nodoc:
attr_reader :base, :destination, :given_destination, :<API key>, :config
# Initializes given the source and destination.
# base<Thor::Base>:: A Thor::Base instance
# source<String>:: Relative path to the source of this file
# destination<String>:: Relative path to the destination of this file
# config<Hash>:: give :verbose => false to not log the status.
def initialize(base, destination, config={})
@base, @config = base, { :verbose => true }.merge(config)
self.destination = destination
end
# Checks if the destination file already exists.
# Boolean:: true if the file exists, false otherwise.
def exists?
::File.exists?(destination)
end
def invoke!
<API key> do
::FileUtils.mkdir_p(destination)
end
end
def revoke!
say_status :remove, :red
::FileUtils.rm_rf(destination) if !pretend? && exists?
end
protected
# Shortcut for pretend.
def pretend?
base.options[:pretend]
end
# Sets the absolute destination value from a relative destination value.
# It also stores the given and relative destination. Let's suppose our
# script is being executed on "dest", it sets the destination root to
# "dest". The destination, given_destination and <API key>
# are related in the following way:
# inside "bar" do
# empty_directory "baz"
# end
# destination #=> dest/bar/baz
# <API key> #=> bar/baz
# given_destination #=> baz
def destination=(destination)
if destination
@given_destination = <API key>(destination.to_s)
@destination = ::File.expand_path(@given_destination, base.destination_root)
@<API key> = base.<API key>(@destination)
end
end
# Filenames in the encoded form are converted. If you have a file:
# %class_name%.rb
# It gets the class name from the base and replace it:
# user.rb
def <API key>(filename)
filename.gsub(/%(.*?)%/) do |string|
instruction = $1.strip
base.respond_to?(instruction) ? base.send(instruction) : string
end
end
# Receives a hash of options and just execute the block if some
# conditions are met.
def <API key>(&block)
if exists?
<API key>(&block)
else
say_status :create, :green
block.call unless pretend?
end
destination
end
# What to do when the destination file already exists.
def <API key>(&block)
say_status :exist, :blue
end
# Shortcut to say_status shell method.
def say_status(status, color)
base.shell.say_status status, <API key>, color if config[:verbose]
end
end
end
end |
import resource from '<API key>';
import readError from '../lib/read-error';
import Block from '../models/block';
import { knownPublicKeys, knownAddresses } from '../lib/knowns';
const addressRegex = /^[0-9]{15,21}[L]$/;
export default () => resource({
id : 'block',
/** GET / - List all entities */
index({ query }, res) {
let status;
let response;
// define response and status
if (typeof query.height === 'string' && query.height > 0 && !addressRegex.test(query.height)) {
status = 200;
response = { blocks: [Block({ height: query.height, i: 0 })], count: 1 };
} else if (typeof query.blockId === 'string' && query.blockId.length > 10 && !addressRegex.test(query.blockId)) {
status = 200;
response = { blocks: [Block({ blockId: query.blockId })], count: 1 };
} else if (query.sort === 'height:desc') {
status = 200;
const limit = query.limit || 1;
const offset = query.offset || 0;
const blockList = [];
const max = parseInt(limit) + parseInt(offset);
console.log('From ', offset, ' to ', max);
for (let i = offset; i < max; i++) {
blockList.push(Block({ i, publicKey: query.publicKey }));
}
response = { blocks: blockList, count: limit };
// getting top accounts
} else if (typeof query.blockId === 'string' || typeof query.height === 'string') {
status = 204;
} else if (query.blockId === 'invalid_blockId' || query.blockId == undefined) {
status = 400;
} else if (query.blockId instanceof Array || query.blockId.constructor === Array) {
status = 409;
} else {
status = 404;
}
res.status(status);
if (status === 200) {
res.json(response);
} else {
readError(status, (err, data) => {
res.json(data);
});
}
},
}); |
using CK.Glouton.Model.Server.Handlers.Implementation;
using CK.Glouton.Model.Server.Sender;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Text;
namespace CK.Glouton.AlertSender.Sender
{
public class MailSender : IAlertSender
{
private readonly MailboxAddress _from;
private readonly List<MailboxAddress> _to = new List<MailboxAddress>();
private readonly <API key> _configuration;
public string SenderType { get; set; } = "Mail";
public MailSender( <API key> configuration )
{
if( !configuration.Validate() )
throw new ArgumentException( nameof( configuration ) );
_configuration = configuration;
_from = new MailboxAddress( _configuration.Name, _configuration.Email );
foreach( var mail in configuration.Contacts )
{
_to.Add( new MailboxAddress( mail ) );
}
}
public void AddReceiver( string name, string email )
{
_to.Add( new MailboxAddress( name, email ) );
}
public bool Match( <API key> configuration )
{
return _configuration.Equals( configuration );
}
public void Send( AlertEntry logEntry )
{
using( var client = new SmtpClient() )
{
client.Connect( _configuration.SmtpAddress, _configuration.SmtpPort, SecureSocketOptions.Auto );
client.Authenticate( _configuration.SmtpUsername, _configuration.SmtpPassword );
client.Send( ConstructMail( logEntry ) );
client.Disconnect( true );
}
}
private MimeMessage ConstructMail( AlertEntry logEntry )
{
var message = new MimeMessage();
message.From.Add( _from );
foreach( var to in _to )
{
message.To.Add( to );
}
message.Subject = $"CK-Glouton Automatic Alert.";
message.Body = new TextPart( "plain" )
{
Text = ConstructTextBody( logEntry )
};
return message;
}
private static string ConstructTextBody( AlertEntry logEntry )
{
var builder = new StringBuilder();
builder.AppendLine( "Hi," );
builder.AppendLine( $"File : {logEntry.FileName} : {logEntry.LineNumber}" );
builder.AppendLine( $"LogLevel : {logEntry.LogLevel}" );
builder.AppendLine( $"At time : {logEntry.LogTime}" );
if( logEntry.Tags != null )
{
builder.AppendLine( $"Tags : {logEntry.Tags}" );
}
builder.AppendLine( $"Message : {logEntry.Text}" );
if( logEntry.Conclusions != null )
{
builder.AppendLine( $"Conclusion : {logEntry.Conclusions}" );
}
if( logEntry.Exception != null )
{
builder.AppendLine( "Exception: " );
logEntry.Exception.ToStringBuilder( builder, "" );
}
builder.AppendLine();
builder.AppendLine( "Automatic message of CK-Glouton" );
builder.AppendLine( "A problem ? https://github.com/ZooPin/ck-glouton/issues" );
return builder.ToString();
}
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="Shift_JIS" />
</head>
<body>
<form action="api/sample" method="POST" enctype="multipart/form-data">
<input type="file" name="myFile" />
<input type="text" name="text" />
<input type="submit" value="Upload" />
</form>
<a href="api/sample/download">download</a>
</body>
</html> |
'use strict';
/*
* Defining the Package
*/
var Module = require('meanio').Module;
var Core = new Module('core');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
Core.register(function(app, auth, database) {
//We enable routing. By default the Package Object is passed to the routes
Core.routes(app, auth, database);
/**
//Uncomment to use. Requires meanio@0.3.7 or above
// Save settings with callback
// Use this for saving data from administration pages
Core.settings({
'someSetting': 'some value'
}, function(err, settings) {
//you now have the settings object
});
// Another save settings example this time with no callback
// This writes over the last settings.
Core.settings({
'anotherSettings': 'some value'
});
// Get settings. Retrieves latest saved settigns
Core.settings(function(err, settings) {
//you now have the settings object
});
*/
return Core;
}); |
module BFLib.BrainfuchFollow where
import Control.Monad.State
import Control.Monad.Writer
import System.IO
import BFLib.Brainfuch (Code
, Stack
, bfTail
, emptyStack
, incPtr
, decPtr
, incCell
, decCell
, bfGetLoop
, bfDropLoop)
{-
- Syntax
> Increment pointer
< Decrement pointer
+ Increment contents
- Decrement contents
. Put cell content
, Read cell content
[ ] Loop ([ - Skip following part if content == 0; ] go to last [ if content != 0)
-}
type StackCode = (Stack,Char)
-- As function: Stack -> IO ((a,[StackCode]),Stack)
type BFFState = WriterT [StackCode] (StateT Stack IO)
-- monadic ops
bffTell :: StackCode -> BFFState ()
bffTell sc = tell [sc]
mIncPtr :: BFFState ()
mIncPtr = WriterT . StateT $ \s -> let s' = incPtr s
in return (((),[(s','>')]),s')
mDecPtr :: BFFState ()
mDecPtr = WriterT . StateT $ \s -> let s' = decPtr s
in return (((),[(s','<')]),s')
mIncCell :: BFFState ()
mIncCell = WriterT . StateT $ \s -> let s' = incCell s
in return (((),[(s','+')]),s')
mDecCell :: BFFState ()
mDecCell = WriterT . StateT $ \s -> let s' = decCell s
in return (((),[(s','-')]),s')
mPrintContent :: BFFState ()
mPrintContent = WriterT . StateT $ \s@(_,e,_) -> (putStrLn . show) e >> hFlush stdout >> return (((),[(s,'.')]),s)
mReadContent :: BFFState ()
mReadContent = WriterT . StateT $ \(xs,_,ys) -> readLn >>= \e -> let s' = (xs,e,ys)
in return (((),[(s',',')]),s')
mIsZero :: BFFState Bool
mIsZero = WriterT . StateT $ \s@(_,e,_) -> return ((e == 0,[]),s)
-- Interpreter
bfInt :: Code -> BFFState ()
bfInt [] = return ()
bfInt allc@(c:cs) = case c of
'>' -> mIncPtr >> bfInt cs
'<' -> mDecPtr >> bfInt cs
'+' -> mIncCell >> bfInt cs
'-' -> mDecCell >> bfInt cs
'.' -> mPrintContent >> bfInt cs
',' -> mReadContent >> bfInt cs
'[' -> do
p <- mIsZero
if p
then bfInt . bfDropLoop $ allc
else let loopcode = bfGetLoop allc in do
bfInt loopcode
bfInt (c:cs)
_ -> bfInt cs |
var path = require("path");
var webpack = require("webpack");
var rootSourcePath = __dirname;
var rootAssetsPath = __dirname;
module.exports = {
context: rootSourcePath,
resolve: {
root: [path.join(__dirname, "bower_components")]
},
entry: {
index: [
rootSourcePath + '/js/app.jsx'
]
},
output: {
path: rootAssetsPath + '/js',
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.html$/, loader: "html" },
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel'
}
]
},
plugins: [
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.<API key>("bower.json", ["main"])
)
]
}; |
/**
Import general dependencies here so webpack will kindly bundle them for us
*/
import '../styles/common.scss'; |
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('TypeaheadCtrl', function($scope, $http) {
$scope.selected = undefined;
// Any function returning a promise object can be used to load values asynchronously
$scope.getLocation = function(val) {
return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
params: {
address: val,
sensor: false
}
}).then(function(response){
return response.data.results.map(function(item){
return item.formatted_address;
});
});
};
}); |
<html>
<head>
<title>User agent detail - Mozilla/5.0 (Linux; Android 4.2.2; Lenovo S6000L-F Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.94 Safari/537.36</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Mozilla/5.0 (Linux; Android 4.2.2; Lenovo S6000L-F Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.94 Safari/537.36
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>browscap/browscap<br /><small>/tests/fixtures/issues/issue-523.php</small></td><td>Chrome 28.0</td><td>Android 4.2</td><td>unknown </td><td style="border-left: 1px solid #555">Lenovo</td><td>IdeaTab S6000-F Wi-Fi, 16GB</td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a>
<!-- Modal Structure -->
<div id="modal-test" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Testsuite result detail</h4>
<p><pre><code class="php">Array
(
[Browser] => Chrome
[Browser_Type] => Browser
[Browser_Bits] => 32
[Browser_Maker] => Google Inc
[Version] => 28.0
[MajorVer] => 28
[MinorVer] => 0
[Platform] => Android
[Platform_Version] => 4.2
[Platform_Bits] => 32
[Platform_Maker] => Google Inc
[isMobileDevice] => 1
[isTablet] => 1
[Crawler] =>
[JavaScript] => 1
[Cookies] => 1
[Frames] => 1
[IFrames] => 1
[Tables] => 1
[Device_Name] => IdeaTab S6000-F Wi-Fi, 16GB
[Device_Maker] => Lenovo
[Device_Type] => Tablet
[<API key>] => touchscreen
[Device_Code_Name] => S6000L-F
[Device_Brand_Name] => Lenovo
[<API key>] => Blink
[<API key>] => unknown
[<API key>] => Google Inc
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Chrome 28.0</td><td>Blink </td><td>Android 4.2</td><td style="border-left: 1px solid #555">Lenovo</td><td>IdeaTab S6000-F Wi-Fi, 16GB</td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.082</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#<API key>">Detail</a>
<!-- Modal Structure -->
<div id="<API key>" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapPhp result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.2.*lenovo s6000l\-f build\/.*\) applewebkit\/.* \(khtml, like gecko\) chrome\/28\..*safari\/.*$/ |
The MIT License (MIT)
Copyright (c) 2016 - Allysson dos Santos
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. |
// Assembly : NRTyler.CodeLibrary
// Author : Nicholas Tyler
// Created : 10-01-2017
using System;
namespace NRTyler.CodeLibrary.Attributes
{
<summary>
An <see cref="Attribute"/> that allows a member to be referenced by or assigned a label that's held as a <see cref="string"/> value.
</summary>
<seealso cref="System.Attribute" />
public sealed class <API key> : Attribute
{
<summary>
Initializes a new instance of the <see cref="<API key>"/> class.
</summary>
<param name="label">The label that you want to be applied to an item.</param>
public <API key>(string label)
{
Label = label;
}
<summary>
Gets the label that was applied to the member.
</summary>
public string Label { get; }
}
} |
package form
import (
"regexp"
"github.com/ewhal/nyaa/util/log"
)
const EMAIL_REGEX = `(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})`
const USERNAME_REGEX = `(\W)`
func EmailValidation(email string, err map[string][]string) (bool, map[string][]string) {
exp, errorRegex := regexp.Compile(EMAIL_REGEX)
if regexpCompiled := log.CheckError(errorRegex); regexpCompiled {
if exp.MatchString(email) {
return true, err
}
}
err["email"] = append(err["email"], "Email Address is not valid")
return false, err
}
func ValidateUsername(username string, err map[string][]string) (bool, map[string][]string) {
exp, errorRegex := regexp.Compile(USERNAME_REGEX)
if regexpCompiled := log.CheckError(errorRegex); regexpCompiled {
if exp.MatchString(username) {
err["username"] = append(err["username"], "Username contains illegal characters")
return false, err
}
} else {
return false, err
}
return true, err
}
func NewErrors() map[string][]string {
err := make(map[string][]string)
return err
}
func NewInfos() map[string][]string {
infos := make(map[string][]string)
return infos
}
func IsAgreed(termsAndConditions string) bool { // TODO: Inline function
return termsAndConditions == "1"
}
// RegistrationForm is used when creating a user.
type RegistrationForm struct {
Username string `form:"username" needed:"true" len_min:"3" len_max:"20"`
Email string `form:"email" needed:"true"`
Password string `form:"password" needed:"true" len_min:"6" len_max:"25" equalInput:"ConfirmPassword"`
ConfirmPassword string `form:"<API key>" omit:"true" needed:"true"`
CaptchaID string `form:"captchaID" omit:"true" needed:"true"`
TermsAndConditions bool `form:"t_and_c" omit:"true" needed:"true" equal:"true" hum_name:"Terms and Conditions"`
}
// LoginForm is used when a user logs in.
type LoginForm struct {
Username string `form:"username" needed:"true"`
Password string `form:"password" needed:"true"`
}
// UserForm is used when updating a user.
type UserForm struct {
Username string `form:"username" needed:"true" len_min:"3" len_max:"20"`
Email string `form:"email" needed:"true"`
Language string `form:"language" default:"en-us"`
CurrentPassword string `form:"password" len_min:"6" len_max:"25" omit:"true"`
Password string `form:"password" len_min:"6" len_max:"25" equalInput:"ConfirmPassword"`
ConfirmPassword string `form:"<API key>" omit:"true"`
Status int `form:"language" default:"0"`
}
// PasswordForm is used when updating a user password.
type PasswordForm struct {
CurrentPassword string `form:"currentPassword"`
Password string `form:"newPassword"`
}
// <API key> is used when sending a password reset token.
type <API key> struct {
Email string `form:"email"`
}
// PasswordResetForm is used when reseting a password.
type PasswordResetForm struct {
PasswordResetToken string `form:"token"`
Password string `form:"newPassword"`
} |
# Changelog
# Changed the variables to include the header file directory
# Added global var for the XTENSA tool root
# This make file still needs some work.
# Output directors to store intermediate compiled files
# relative to the project directory
BUILD_BASE = build
FW_BASE = firmware
ESPTOOL = tools/esptool.py
# name for the target project
TARGET = app
# linker script used for the above linkier step
LD_SCRIPT = eagle.app.v6.ld
# we create two different files for uploading into the flash
# these are the names and options to generate them
FW_1 = 0x00000
FW_2 = 0x40000
ifndef FLAVOR
FLAVOR = release
else
FLAVOR = $(FLAVOR)
endif
# Select compile
ifeq ($(OS),Windows_NT)
# WIN32
# We are under windows.
ifeq ($(XTENSA_CORE),lx106)
# It is xcc
AR = xt-ar
CC = xt-xcc
LD = xt-xcc
NM = xt-nm
CPP = xt-cpp
OBJCOPY = xt-objcopy
#MAKE = xt-make
CCFLAGS += -Os --rename-section .text=.irom0.text --rename-section .literal=.irom0.literal
else
# It is gcc, may be cygwin
# Can we use -fdata-sections?
CCFLAGS += -Os -ffunction-sections -fno-jump-tables
AR = xtensa-lx106-elf-ar
CC = <API key>
LD = <API key>
NM = xtensa-lx106-elf-nm
CPP = <API key>
OBJCOPY = <API key>
endif
ESPPORT ?= com1
SDK_BASE ?= c:/Espressif/ESP8266_SDK
ifeq ($(<API key>),AMD64)
# ->AMD64
endif
ifeq ($(<API key>),x86)
# ->IA32
endif
else
# We are under other system, may be Linux. Assume using gcc.
ESPPORT ?= /dev/ttyUSB0
SDK_BASE ?= /esptools/esp-open-sdk/sdk
CCFLAGS += -Os -ffunction-sections -fno-jump-tables
AR = xtensa-lx106-elf-ar
CC = <API key>
LD = <API key>
NM = xtensa-lx106-elf-nm
CPP = <API key>
OBJCOPY = <API key>
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
# LINUX
endif
ifeq ($(UNAME_S),Darwin)
# OSX
endif
UNAME_P := $(shell uname -p)
ifeq ($(UNAME_P),x86_64)
# ->AMD64
endif
ifneq ($(filter %86,$(UNAME_P)),)
# ->IA32
endif
ifneq ($(filter arm%,$(UNAME_P)),)
# ->ARM
endif
endif
# which modules (subdirectories) of the project to include in compiling
MODULES = driver modules/mqtt/mqtt user modules
EXTRA_INCDIR = include $(SDK_BASE)/../include
# libraries used in this project, mainly provided by the SDK
LIBS = c gcc hal phy pp net80211 lwip wpa main ssl
# compiler flags using during compilation of source files
CFLAGS = -Os -Wpointer-arith -Wundef -Wno-error -Wl,-EL -<API key> -nostdlib -mlongcalls -<API key> -D__ets__ -DICACHE_FLASH
# linker flags used to generate the main object file
LDFLAGS = -nostdlib -Wl,--no-check-sections -u call_user_start -Wl,-static
ifeq ($(FLAVOR),debug)
CFLAGS += -g -O0
LDFLAGS += -g -O0
endif
ifeq ($(FLAVOR),release)
CFLAGS += -g -O2
LDFLAGS += -g -O2
endif
# various paths from the SDK used in this project
SDK_LIBDIR = lib
SDK_LDDIR = ld
SDK_INCDIR = include include/json
# no user configurable options below here
FW_TOOL ?= $(ESPTOOL)
SRC_DIR := $(MODULES)
BUILD_DIR := $(addprefix $(BUILD_BASE)/,$(MODULES))
SDK_LIBDIR := $(addprefix $(SDK_BASE)/,$(SDK_LIBDIR))
SDK_INCDIR := $(addprefix -I$(SDK_BASE)/,$(SDK_INCDIR)) |
#ifndef COINCONTROLDIALOG_H
#define COINCONTROLDIALOG_H
#include <QAbstractButton>
#include <QAction>
#include <QDialog>
#include <QList>
#include <QMenu>
#include <QPoint>
#include <QString>
#include <QTreeWidgetItem>
namespace Ui {
class CoinControlDialog;
}
class WalletModel;
class CCoinControl;
class CoinControlDialog : public QDialog
{
Q_OBJECT
public:
explicit CoinControlDialog(QWidget *parent = 0);
~CoinControlDialog();
void setModel(WalletModel *model);
// static because also called from sendcoinsdialog
static void updateLabels(WalletModel*, QDialog*);
static QString getPriorityLabel(double);
static QList<qint64> payAmounts;
static CCoinControl *coinControl;
private:
Ui::CoinControlDialog *ui;
WalletModel *model;
int sortColumn;
Qt::SortOrder sortOrder;
QMenu *contextMenu;
QTreeWidgetItem *contextMenuItem;
QAction *<API key>;
QAction *lockAction;
QAction *unlockAction;
QString strPad(QString, int, QString);
void sortView(int, Qt::SortOrder);
void updateView();
enum
{
COLUMN_CHECKBOX,
COLUMN_AMOUNT,
COLUMN_LABEL,
COLUMN_ADDRESS,
COLUMN_DATE,
<API key>,
COLUMN_PRIORITY,
COLUMN_TXHASH,
COLUMN_VOUT_INDEX,
COLUMN_AMOUNT_INT64,
<API key>
};
private slots:
void showMenu(const QPoint &);
void copyAmount();
void copyLabel();
void copyAddress();
void copyTransactionHash();
void lockCoin();
void unlockCoin();
void clipboardQuantity();
void clipboardAmount();
void clipboardFee();
void clipboardAfterFee();
void clipboardBytes();
void clipboardPriority();
void clipboardLowOutput();
void clipboardChange();
void radioTreeMode(bool);
void radioListMode(bool);
void viewItemChanged(QTreeWidgetItem*, int);
void <API key>(int);
void buttonBoxClicked(QAbstractButton*);
void <API key>();
void updateLabelLocked();
};
#endif // COINCONTROLDIALOG_H |
<?php
/* @WebProfiler/Profiler/base_js.html.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<script type=\"text/javascript\">/*<![CDATA[*/
Sfjs = (function() {
\"use strict\";
var noop = function() {},
profilerStorageKey = 'sf2/profiler/',
request = function(url, onSuccess, onError, payload, options) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
options = options || {};
xhr.open(options.method || 'GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(state) {
if (4 === xhr.readyState && 200 === xhr.status) {
(onSuccess || noop)(xhr);
} else if (4 === xhr.readyState && xhr.status != 200) {
(onError || noop)(xhr);
}
};
xhr.send(payload || '');
},
hasClass = function(el, klass) {
return el.className.match(new RegExp('\\\\b' + klass + '\\\\b'));
},
removeClass = function(el, klass) {
el.className = el.className.replace(new RegExp('\\\\b' + klass + '\\\\b'), ' ');
},
addClass = function(el, klass) {
if (!hasClass(el, klass)) { el.className += \" \" + klass; }
},
getPreference = function(name) {
if (!window.localStorage) {
return null;
}
return localStorage.getItem(profilerStorageKey + name);
},
setPreference = function(name, value) {
if (!window.localStorage) {
return null;
}
localStorage.setItem(profilerStorageKey + name, value);
};
return {
hasClass: hasClass,
removeClass: removeClass,
addClass: addClass,
getPreference: getPreference,
setPreference: setPreference,
request: request,
load: function(selector, url, onSuccess, onError, options) {
var el = document.getElementById(selector);
if (el && el.getAttribute('data-sfurl') !== url) {
request(
url,
function(xhr) {
el.innerHTML = xhr.responseText;
el.setAttribute('data-sfurl', url);
removeClass(el, 'loading');
(onSuccess || noop)(xhr, el);
},
function(xhr) { (onError || noop)(xhr, el); },
options
);
}
return this;
},
toggle: function(selector, elOn, elOff) {
var i,
style,
tmp = elOn.style.display,
el = document.getElementById(selector);
elOn.style.display = elOff.style.display;
elOff.style.display = tmp;
if (el) {
el.style.display = 'none' === tmp ? 'none' : 'block';
}
return this;
}
}
})();
</script>
";
}
public function getTemplateName()
{
return "@WebProfiler/Profiler/base_js.html.twig";
}
public function getDebugInfo()
{
return array ( 91 => 35, 83 => 30, 79 => 29, 75 => 28, 70 => 26, 66 => 25, 62 => 24, 50 => 15, 26 => 3, 24 => 2, 19 => 1, 98 => 40, 93 => 9, 46 => 14, 44 => 9, 40 => 8, 32 => 6, 27 => 4, 22 => 1, 120 => 20, 117 => 19, 110 => 22, 108 => 19, 105 => 18, 102 => 17, 94 => 34, 90 => 32, 88 => 6, 84 => 29, 82 => 28, 78 => 40, 73 => 16, 64 => 13, 61 => 12, 56 => 11, 53 => 10, 47 => 8, 41 => 5, 33 => 3, 158 => 79, 139 => 63, 135 => 62, 131 => 61, 127 => 28, 123 => 59, 106 => 45, 101 => 43, 97 => 41, 85 => 32, 80 => 41, 76 => 17, 74 => 27, 63 => 19, 58 => 17, 48 => 9, 45 => 8, 42 => 12, 36 => 7, 30 => 5,);
}
} |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_13) on Fri Mar 28 18:34:14 EDT 2008 -->
<TITLE>
Uses of Package org.jbox2d.collision
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Package org.jbox2d.collision";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/jbox2d/collision/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Package<br>org.jbox2d.collision</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../org/jbox2d/collision/package-summary.html">org.jbox2d.collision</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.jbox2d.collision"><B>org.jbox2d.collision</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.jbox2d.dynamics"><B>org.jbox2d.dynamics</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.jbox2d.dynamics.contacts"><B>org.jbox2d.dynamics.contacts</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.jbox2d.testbed"><B>org.jbox2d.testbed</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.jbox2d.collision"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../org/jbox2d/collision/package-summary.html">org.jbox2d.collision</A> used by <A HREF="../../../org/jbox2d/collision/package-summary.html">org.jbox2d.collision</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/AABB.html#org.jbox2d.collision"><B>AABB</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/Bound.html#org.jbox2d.collision"><B>Bound</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/BroadPhase.html#org.jbox2d.collision"><B>BroadPhase</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/BufferedPair.html#org.jbox2d.collision"><B>BufferedPair</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/CircleShape.html#org.jbox2d.collision"><B>CircleShape</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/ContactID.html#org.jbox2d.collision"><B>ContactID</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/ContactID.Features.html#org.jbox2d.collision"><B>ContactID.Features</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/Manifold.html#org.jbox2d.collision"><B>Manifold</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/ManifoldPoint.html#org.jbox2d.collision"><B>ManifoldPoint</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/MassData.html#org.jbox2d.collision"><B>MassData</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/OBB.html#org.jbox2d.collision"><B>OBB</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/Pair.html#org.jbox2d.collision"><B>Pair</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/PairCallback.html#org.jbox2d.collision"><B>PairCallback</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/PairManager.html#org.jbox2d.collision"><B>PairManager</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/PolygonShape.html#org.jbox2d.collision"><B>PolygonShape</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/Proxy.html#org.jbox2d.collision"><B>Proxy</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/Shape.html#org.jbox2d.collision"><B>Shape</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/ShapeDef.html#org.jbox2d.collision"><B>ShapeDef</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/ShapeType.html#org.jbox2d.collision"><B>ShapeType</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/<API key>.html#org.jbox2d.collision"><B><API key></B></A></B>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="org.jbox2d.dynamics"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../org/jbox2d/collision/package-summary.html">org.jbox2d.collision</A> used by <A HREF="../../../org/jbox2d/dynamics/package-summary.html">org.jbox2d.dynamics</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/AABB.html#org.jbox2d.dynamics"><B>AABB</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/BroadPhase.html#org.jbox2d.dynamics"><B>BroadPhase</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/MassData.html#org.jbox2d.dynamics"><B>MassData</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/PairCallback.html#org.jbox2d.dynamics"><B>PairCallback</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/Shape.html#org.jbox2d.dynamics"><B>Shape</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/ShapeDef.html#org.jbox2d.dynamics"><B>ShapeDef</B></A></B>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="org.jbox2d.dynamics.contacts"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../org/jbox2d/collision/package-summary.html">org.jbox2d.collision</A> used by <A HREF="../../../org/jbox2d/dynamics/contacts/package-summary.html">org.jbox2d.dynamics.contacts</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/ContactID.html#org.jbox2d.dynamics.contacts"><B>ContactID</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/Manifold.html#org.jbox2d.dynamics.contacts"><B>Manifold</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/Shape.html#org.jbox2d.dynamics.contacts"><B>Shape</B></A></B>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/ShapeType.html#org.jbox2d.dynamics.contacts"><B>ShapeType</B></A></B>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="org.jbox2d.testbed"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../org/jbox2d/collision/package-summary.html">org.jbox2d.collision</A> used by <A HREF="../../../org/jbox2d/testbed/package-summary.html">org.jbox2d.testbed</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../org/jbox2d/collision/class-use/AABB.html#org.jbox2d.testbed"><B>AABB</B></A></B>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/jbox2d/collision/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML> |
class <API key> < ActiveRecord::Migration[5.0]
def change
create_table :<API key> do |t|
t.belongs_to :api_client, foreign_key: true, index: true
t.integer :calls_count, null: false
t.datetime :at, null: false
t.timestamps
end
end
end |
"""Run commands in a new terminal window."""
from __future__ import annotations
import logging
import os
import shlex
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from tkinter import messagebox
from porcupine import get_main_window, utils
log = logging.getLogger(__name__)
_this_dir = Path(__file__).absolute().parent
if sys.platform == "win32":
run_script = _this_dir / "windows_run.py"
else:
run_script = _this_dir / "bash_run.sh"
# getting this to work in powershell turned out to be hard :(
def _run_in_windows_cmd(command: str, cwd: Path) -> None:
log.debug("using Windows command prompt")
real_command = [str(utils.python_executable), str(run_script), str(cwd), command]
if not utils.running_pythonw:
# windows wants to run python in the same terminal that
# Porcupine was started from, this is the only way to open a
# new command prompt i found and it works :) we need cmd
# because start is built in to cmd (lol)
real_command = ["cmd", "/c", "start"] + real_command
subprocess.Popen(real_command)
def <API key>(command: str, cwd: Path) -> None:
log.debug("using MacOS terminal.app")
assert shutil.which("bash") is not None
with tempfile.NamedTemporaryFile("w", delete=False, prefix="porcupine-run-") as file:
print("#!/usr/bin/env bash", file=file)
print("rm", shlex.quote(file.name), file=file) # runs even if command is interrupted
print(
shlex.quote(str(run_script)),
"--dont-wait",
shlex.quote(str(cwd)),
shlex.quote(command),
file=file,
)
os.chmod(file.name, 0o755)
subprocess.Popen(["open", "-a", "Terminal.app", file.name])
# the terminal might be still opening when we get here, that's why
# the file deletes itself
# right now the file removes itself before it runs the actual command so
# it's removed even if the command is interrupted
def <API key>(command: str, cwd: Path) -> None:
terminal: str = os.environ.get("TERMINAL", "x-terminal-emulator")
# to config what x-terminal-emulator is:
# $ sudo update-alternatives --config x-terminal-emulator
# TODO: document this
if terminal == "x-terminal-emulator":
log.debug("using x-terminal-emulator")
terminal_or_none = shutil.which(terminal)
if terminal_or_none is None:
log.warning("x-terminal-emulator not found")
# Ellusion told me on irc that porcupine didn't find his
# xfce4-terminal, and turned out he had no x-terminal-emulator...
# i'm not sure why, but this should work
# well, turns out he's using arch, so... anything could be wrong
terminal_or_none = shutil.which("xfce4-terminal")
if terminal_or_none is None:
# not much more can be done
messagebox.showerror(
"x-terminal-emulator not found",
"Cannot find x-terminal-emulator in $PATH. "
"Are you sure that you have a terminal installed?",
)
return
terminal_path = Path(terminal_or_none)
log.info(f"found a terminal: {terminal_path}")
terminal_path = terminal_path.resolve()
log.debug(f"absolute path to terminal: {terminal_path}")
# sometimes x-terminal-emulator points to mate-terminal.wrapper,
# it's a python script that changes some command line options
# and runs mate-terminal but it breaks passing arguments with
# the -e option for some reason
if terminal_path.name == "mate-terminal.wrapper":
log.info("using mate-terminal instead of mate-terminal.wrapper")
terminal = "mate-terminal"
else:
terminal = str(terminal_path)
else:
log.debug(f"using $TERMINAL or fallback 'x-terminal-emulator', got {terminal!r}")
if shutil.which(terminal) is None:
messagebox.showerror(
f"{terminal!r} not found",
f"Cannot find {terminal!r} in $PATH. Try setting $TERMINAL to a path to a working"
" terminal program.",
)
return
real_command = [str(run_script), str(cwd), command]
real_command.extend(map(str, command))
subprocess.Popen([terminal, "-e", " ".join(map(shlex.quote, real_command))])
# this figures out which terminal to use every time the user wants to run
# something but it doesn't really matter, this way the user can install a
# terminal while porcupine is running without restarting porcupine
def run_command(command: str, cwd: Path) -> None:
log.info(f"Running {command} in {cwd}")
widget = get_main_window() # any tkinter widget works
windowingsystem = widget.tk.call("tk", "windowingsystem")
if windowingsystem == "win32":
_run_in_windows_cmd(command, cwd)
elif windowingsystem == "aqua" and not os.environ.get("TERMINAL", ""):
<API key>(command, cwd)
else:
<API key>(command, cwd) |
// <API key>.h
// Offline Surveys
#import <MessageUI/MessageUI.h>
#import <UIKit/UIKit.h>
@interface <API key> : UIViewController <<API key>, UIAlertViewDelegate>
- (IBAction)crossButtonTouched:(id)sender;
- (IBAction)emailButtonTouched:(id)sender;
- (IBAction)clearButtonTouched:(id)sender;
@end |
.rpd-patch {
font-family: 'PT Mono', 'Andale Mono', 'Fira mono', 'Menlo', sans-serif;
font-size: 9px;
}
.rpd-background {
fill: transparent;
}
.rpd-link {
stroke: black;
}
.rpd-link.rpd-disabled {
stroke: rgba(250,250,250,0.8);
stroke-width: 1;
}
.rpd-link:hover {
cursor: crosshair;
}
.rpd-link.rpd-disabled:hover {
cursor: cell;
}
.rpd-header {
fill: transparent;
}
.rpd-name-holder text {
fill: lightgray;
font-weight: bold;
}
.rpd-body {
stroke: black;
stroke-width: 1px;
fill: white;
}
.rpd-node.rpd-dragging .rpd-body {
stroke: darkblue;
}
.rpd-node .rpd-remove-button {
cursor: pointer;
display: none;
}
.rpd-node:hover .rpd-remove-button {
display: block;
}
.rpd-remove-button text {
alignment-baseline: hanging;
text-anchor: end;
}
.rpd-remove-button:hover text {
fill: red;
}
.<API key> {
fill: transparent;
}
text.rpd-value {
font-size: 0.6em;
fill: deepskyblue;
}
.rpd-value-holder .rpd-value-editor {
display: none;
}
.rpd-value-holder.rpd-editor-enabled .rpd-value-editor {
display: block;
}
.rpd-inlet .rpd-name,
.rpd-outlet .rpd-name {
font-size: 0.9em;
}
.rpd-connector {
cursor: pointer;
} |
#ifndef _SNF_CRT_H_
#define _SNF_CRT_H_
#include <string>
#include <vector>
#include "file.h"
#include "sslfcn.h"
namespace snf {
namespace ssl {
/*
* Encapsulates OpenSSL X509 Certificate (X509).
* - The certificate can be in der or pem format.
* - A type operator is provided to get the raw certificate.
*/
class x509_certificate
{
public:
struct altname {
std::string type;
std::string name;
};
x509_certificate(data_fmt, const std::string &, const char *passwd = nullptr);
x509_certificate(data_fmt, const uint8_t *, size_t, const char *passwd = nullptr);
x509_certificate(X509 *);
x509_certificate(const x509_certificate &);
x509_certificate(x509_certificate &&);
~x509_certificate();
const x509_certificate &operator=(const x509_certificate &);
x509_certificate &operator=(x509_certificate &&);
operator X509* () { return m_crt; }
const std::string &subject();
const std::string &issuer();
const std::string &common_name();
const std::string &serial();
const std::vector<x509_certificate::altname> &alternate_names();
const std::vector<std::string> &<API key>();
const std::vector<std::string> &ocsp_end_points();
bool matches(const std::string &);
private:
X509 *m_crt = nullptr;
std::string m_subject;
std::string m_issuer;
std::string m_cn;
std::string m_serial;
std::vector<altname> m_alt_names;
std::vector<std::string> m_crl_dps;
std::vector<std::string> m_ocsp_eps;
void init_der(snf::file_ptr &);
void init_der(const uint8_t *, size_t);
void init_pem(snf::file_ptr &, const char *);
void init_pem(const uint8_t *, size_t, const char *);
std::string gn_2_str(const GENERAL_NAME *);
bool equal(const std::string &, const std::string &);
};
} // namespace ssl
} // namespace snf
#endif // _SNF_CRT_H_ |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>raytracer: raytracer/source/common/Ray.cpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">raytracer
</div>
<div id="projectbrief"><API key></div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.5 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html">raytracer</a></li><li class="navelem"><a class="el" href="<API key>.html">source</a></li><li class="navelem"><a class="el" href="<API key>.html">common</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Ray.cpp File Reference</div> </div>
</div><!--header
<div class="contents">
<div class="textblock"><code>#include <<a class="el" href="_ray_8h_source.html">Ray.h</a>></code><br/>
</div></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Thu Jul 23 2015 12:10:20 for raytracer by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.5
</small></address>
</body>
</html> |
module Rules
class AllowedKeywordsRule
def initialize(<API key>)
@allowed_keywords = <API key>.to_s.split(/[.,;]\s*/)
end
def match?(torrent_attributes)
@allowed_keywords.any? { |w| torrent_attributes[:title].to_s =~ Regexp.new(w, :case_sensitive => false) }
end
end
end |
<?php
//Start session
session_start();
//Reward
if (isset($_GET['amt'])) {
$reward = $_GET['amt'];
$totReward = $_GET['total'];
}
//Init Config
$GLOBALS['cfg'] = array();
# Things you may want to change in a hurry
$GLOBALS['cfg']['site_url'] = 'http://my.website.com]';
$GLOBALS['cfg']['site_title'] = 'Donation Credits - Web Application';
$GLOBALS['cfg']['environment'] = 'sandbox'; //Please use 'sandbox' or 'live' for PayPal environment
#Paypal Sandbox API Keys (Get yours on developer.paypal.com after registering and creating a REST API Application)
$GLOBALS['cfg']['sandboxAPIKey'] = 'sandboxAPIKey';
$GLOBALS['cfg']['sandboxClientId'] = 'sandboxClientId';
#Paypal Live API Keys (Get yours on developer.paypal.com after registering and creating a REST API Application)
$GLOBALS['cfg']['liveAPIKey'] = 'liveAPIKey';
$GLOBALS['cfg']['liveClientId'] = 'liveClientId';
$GLOBALS['cfg']['steamAPIKey'] = 'steamAPIKey';
#MySQL Database Info
$GLOBALS['cfg']['hostname'] = '127.0.0.1';
$GLOBALS['cfg']['username'] = 'username';
$GLOBALS['cfg']['password'] = 'password';
$GLOBALS['cfg']['dbname'] = 'db1234_database';
#Reward Amount (Economy Credits on server per Reward Conversion below)
$GLOBALS['cfg']['rewardAmount'] = 160;
#Reward Conversion (Rewards the player with the defined Reward amount above for Every THIS amount of dollars, eg 160 for every 1 dollar EX: $1.00 = 1)
$GLOBALS['cfg']['rewardConversion'] = 1;
#Suggested Donation Amount (Default/Suggested value on the donation form EX: $5.00 = 5)
$GLOBALS['cfg']['suggestedDonation'] = 5;
//Messaging Users
$GLOBALS['cfg']['greetingMsgLoggedIn'] = "Hello {$_SESSION['T2SteamUser']}, you are currently logged in with Steam! To logout click the button to the right. Use the form below to make a donation.";
$GLOBALS['cfg']['<API key>'] = 'Welcome to the Donation Credits web application demo!<br><br>First, configure your website by editting the app_config.php file. Use the form below to test your settings:';
$GLOBALS['cfg']['donationSucess'] = "<p class='alert'>{$_SESSION['T2SteamUser']}!!<br>Thank you so much for donating! You have been awarded <span class='highlight-text'>{$reward}</span> Credits towards the server's Blueprint Shop! Connect to the server to claim your reward.</p>";
$GLOBALS['cfg']['donationNotLoggedIn'] = 'You need to log in to your Steam account before donating.'; |
import React, { Component } from 'react'
import Header from '../components/Header'
import Footer from '../components/Footer'
class App extends Component {
render() {
return [
<Header key="header" />,
<div className="main-box" key="main">{this.props.children}</div>,
<Footer key="footer" />
]
}
}
export default App |
<md-content ng-controller="MemoryController as vm" layout="row">
<button ng-click="vm.getChartData()">
click here to load data
</button>
<button ng-click="vm.add()">
Increment
</button>
<span>
count: {{vm.count}}
</span>
<div ng-repeat="data in vm.chartData.data">
<li> {{data.SEX}}</li>
<br>
</div>
<button ng-click="onSubmit" ng-class="{stop: run, start: !run}">
<!--<button ng-click="run=!run" ng-class="{stop: run, start: !run}">-->
<span ng-show="!run">Start</span>
<span ng-show="run">Stop</span>
</button>
<h3>Data Set: {{ dataSet }}</h3>
<nvd3 options="options" data="data" config="{refreshDataOnly: true}"></nvd3>
<p>Data: {{ data }}</p>
</md-content> |
// CoreAutoFunctions
// Basic Autonomous functions used by higher level functions
*******************************************************************************
// Global Configuration Items
// These setting enable special behaviors for debugging, prototyping, and test purposes
// Guards used as they could be overriden in harnesses
*******************************************************************************
// delays used for motor movements, etc. when using PC emulator
#ifndef MOCK_DELAYS
#define MOCK_DELAYS
int mockDelays = 3000;
#endif
// Manual MOTORS! If set to "false" let's people have the fun of moving robot!
#ifndef REAL_MOTORS
#define REAL_MOTORS
bool areMotorsEnabled = true;
#endif
// Manual SENSORS! If set to "false" let's people have the fun of triggering sensor events remote!
#ifndef SENSOR_TYPE
#define SENSOR_TYPE
int useSensorType = 0; // 0 = Real Sensors, 1 = Manual Triggers, 2 = Mock Sensors
#endif
// SENSOR LOGGING! allows various levels to sensor logging.
#ifndef SENSOR_LOGGING
#define SENSOR_LOGGING
bool logAllSensors = false;
bool logActiveSensor = false;
#endif |
<?php
// start all the functions
add_action('after_setup_theme','reverie_startup');
function reverie_startup() {
// launching operation cleanup
add_action('init', '<API key>');
// remove WP version from RSS
add_filter('the_generator', 'reverie_rss_version');
// remove pesky injected css for recent comments widget
add_filter( 'wp_head', '<API key>', 1 );
// clean up comment styles in the head
add_action('wp_head', '<API key>', 1);
// clean up gallery output in wp
add_filter('gallery_style', '<API key>');
// enqueue base scripts and styles
add_action('wp_enqueue_scripts', '<API key>', 999);
// ie conditional wrapper
add_filter( 'style_loader_tag', '<API key>', 10, 2 );
// additional post related cleaning
add_filter( '<API key>', '<API key>', 10, 3 );
add_filter('get_image_tag_class', '<API key>', 0, 4);
add_filter('get_image_tag', '<API key>', 0, 4);
add_filter( 'the_content', 'reverie_img_unautop', 30 );
} /* end reverie_startup */
function <API key>() {
// category feeds
remove_action( 'wp_head', 'feed_links_extra', 3 );
// post and comment feeds
remove_action( 'wp_head', 'feed_links', 2 );
// EditURI link
remove_action( 'wp_head', 'rsd_link' );
// windows live writer
remove_action( 'wp_head', 'wlwmanifest_link' );
// index link
remove_action( 'wp_head', 'index_rel_link' );
// previous link
remove_action( 'wp_head', '<API key>', 10, 0 );
// start link
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
// links for adjacent posts
remove_action( 'wp_head', '<API key>', 10, 0 );
// WP version
remove_action( 'wp_head', 'wp_generator' );
// remove WP version from css
add_filter( 'style_loader_src', '<API key>', 9999 );
// remove Wp version from scripts
add_filter( 'script_loader_src', '<API key>', 9999 );
} /* end head cleanup */
// remove WP version from RSS
function reverie_rss_version() { return ''; }
// remove WP version from scripts
function <API key>( $src ) {
if ( strpos( $src, 'ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
// remove injected CSS for recent comments widget
function <API key>() {
if ( has_filter('wp_head', '<API key>') ) {
remove_filter('wp_head', '<API key>' );
}
}
// remove injected CSS from recent comments widget
function <API key>() {
global $wp_widget_factory;
if (isset($wp_widget_factory->widgets['<API key>'])) {
remove_action('wp_head', array($wp_widget_factory->widgets['<API key>'], '<API key>'));
}
}
// remove injected CSS from gallery
function <API key>($css) {
return preg_replace("!<style type='text/css'>(.*?)</style>!s", '', $css);
}
// loading modernizr and jquery, and reply script
function <API key>() {
if (!is_admin()) {
// modernizr (without media query polyfill)
wp_register_script( 'reverie-modernizr', <API key>() . '/js/vendor/custom.modernizr.js', array(), '2.6.2', false );
// ie-only style sheet
wp_register_style( 'reverie-ie-only', <API key>() . '/css/ie.css', array(), '' );
// comment reply script for threaded comments
if( get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); }
// adding Foundation scripts file in the footer
wp_register_script( 'imageload-js', <API key>() . '/js/vendor/imagesloaded.pkgd.min.js', array( 'jquery' ), '', true );
wp_register_script( 'fotorama-js', <API key>() . '/js/vendor/fotorama.js', array( 'jquery' ), '', true );
wp_register_script( 'velocity-js', <API key>() . '/js/vendor/velocity.min.js', array( 'jquery' ), '', true );
wp_register_script( 'velocity-ui-js', <API key>() . '/js/vendor/velocity.ui.min.js', array( 'jquery' ), '', true );
wp_register_script( 'isotop-js', <API key>() . '/js/vendor/isotope.pkgd.min.js', array( 'jquery' ), '', true );
wp_register_script( 'modal-js', <API key>() . '/js/vendor/jquery.magnific-popup.min.js', array( 'jquery' ), '', true );
wp_register_script( 'headroom-js', <API key>() . '/js/vendor/headroom.min.js', array( 'jquery' ), '', true );
wp_register_script( 'main-js', <API key>() . '/js/main.js', array( 'jquery' ), '', true );
global $is_IE;
if ($is_IE) {
wp_register_script ( 'html5shiv', "http://html5shiv.googlecode.com/svn/trunk/html5.js" , false, true);
}
// enqueue styles and scripts
wp_enqueue_script( 'reverie-modernizr' );
wp_enqueue_style('reverie-ie-only');
/*
I recommend using a plugin to call jQuery
using the google cdn. That way it stays cached
and your site will load faster.
*/
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'html5shiv' );
wp_enqueue_script( 'imageload-js' );
wp_enqueue_script( 'fotorama-js' );
wp_enqueue_script( 'velocity-js' );
wp_enqueue_script( 'velocity-ui-js' );
wp_enqueue_script( 'isotop-js' );
wp_enqueue_script( 'modal-js' );
wp_enqueue_script( 'headroom-js' );
wp_enqueue_script( 'main-js' );
}
}
// adding the conditional wrapper around ie stylesheet
function <API key>( $tag, $handle ) {
if ( 'reverie-ie-only' == $handle )
$tag = '<!--[if lt IE 9]>' . "\n" . $tag . '<![endif]-->' . "\n";
return $tag;
}
function <API key>( $output, $attr, $content ) {
/* We're not worried abut captions in feeds, so just return the output here. */
if ( is_feed() )
return $output;
/* Set up the default arguments. */
$defaults = array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'caption' => ''
);
/* Merge the defaults with user input. */
$attr = shortcode_atts( $defaults, $attr );
/* If the width is less than 1 or there is no caption, return the content wrapped between the [caption]< tags. */
if ( 1 > $attr['width'] || empty( $attr['caption'] ) )
return $content;
/* Set up the attributes for the caption <div>. */
$attributes = ' class="figure ' . esc_attr( $attr['align'] ) . '"';
/* Open the caption <div>. */
$output = '<figure' . $attributes .'>';
/* Allow shortcodes for the content the caption was created for. */
$output .= do_shortcode( $content );
/* Append the caption text. */
$output .= '<figcaption>' . $attr['caption'] . '</figcaption>';
/* Close the caption </div>. */
$output .= '</figure>';
/* Return the formatted, clean caption. */
return $output;
} /* end <API key> */
function <API key>($class, $id, $align, $size) {
$align = 'align' . esc_attr($align);
return $align;
} /* end <API key> */
// Remove width and height in editor, for a better responsive world.
function <API key>($html, $id, $alt, $title) {
return preg_replace(array(
'/\s+width="\d+"/i',
'/\s+height="\d+"/i',
'/alt=""/i'
),
array(
'',
'',
'',
'alt="' . $title . '"'
),
$html);
} /* end <API key> */
function reverie_img_unautop($pee) {
$pee = preg_replace('/<p>\\s*?(<a .*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', '<figure>$1</figure>', $pee);
return $pee;
} /* end reverie_img_unautop */
?> |
package edu.cshl.schatz.jnomics.manager.client.compute;
import edu.cshl.schatz.jnomics.manager.api.JnomicsThriftJobID;
import edu.cshl.schatz.jnomics.manager.api.<API key>;
import edu.cshl.schatz.jnomics.manager.client.Utility;
import edu.cshl.schatz.jnomics.manager.client.ann.Flag;
import edu.cshl.schatz.jnomics.manager.client.ann.Parameter;
import java.util.List;
import java.util.Properties;
/**
* User: james
*/
public class JobStatus extends ComputeBase{
@Flag(shortForm = "-h",longForm = "--help")
public boolean help;
@Parameter(shortForm="-job", longForm = "--job", description = "job id")
public String job;
@Override
public void handle(List<String> remainingArgs, Properties properties) throws Exception {
super.handle(remainingArgs, properties);
if(help){
System.out.println(Utility.helpFromParameters(this.getClass()));
return;
}else if(null == job){
System.out.println("Missing -job parameter");
}else{
<API key> status = client.getJobStatus(new JnomicsThriftJobID(job), auth);
System.out.printf("%30s %30s\n","ID:",status.getJob_id());
System.out.printf("%30s %30s\n","Username:",status.getUsername());
System.out.printf("%30s %30s\n","Complete:",status.isComplete());
System.out.printf("%30s %30s\n","Running State:",status.getRunning_state());
System.out.printf("%30s %30s\n","Map Progress:",status.getMapProgress());
System.out.printf("%30s %30s\n","Reduce Progress:",status.getReduceProgress());
return;
}
System.out.println(Utility.helpFromParameters(this.getClass()));
}
} |
import { Component, OnInit } from '@angular/core';
import { PredictionParams } from './prediction';
import { PredictionService } from './prediction.service';
@Component({
selector: 'predictions',
templateUrl: './predictions.component.html'
})
export class <API key> implements OnInit {
predictionsList: PredictionParams[];
constructor(private predictionService: PredictionService) {}
ngOnInit(): void {
this.predictionService
.<API key>()
.then(pList => this.predictionsList = pList);
}
} |
--TEST
Test for timecop_idate
--SKIPIF
<?php
$required_func = array("timecop_freeze", "timecop_idate");
include(__DIR__."/tests-skipcheck.inc.php");
--INI
date.timezone=America/Los_Angeles
timecop.func_override=0
--FILE
<?php
timecop_freeze(strtotime("2012-02-29 01:23:45"));
var_dump(timecop_idate("Y").timecop_idate("m").timecop_idate("d").timecop_idate("H").timecop_idate("i").timecop_idate("s"));
--EXPECT
string(12) "201222912345" |
cop.gaia
===
My repository for learning game development. |
var seneca = require('seneca')();
var config = require('./seneca.config.js');
seneca
.use('<API key>')
.add('role:test,cmd:echo',
function (args, done) {
var serverMessage = "Echo from server: " + args.clientMessage;
var serverTimestamp = Date.now();
console.log('Processing messageId: %j', args.messageId);
// Use the log line below to show information on the calling client if running multiple
// client.js instances.
//console.log('Processing messageId: %j from client %s', args.messageId, args.clientId);
done(null, {
messageId: args.messageId,
clientTimestamp: args.clientTimestamp,
clientMessage: args.clientMessage,
serverMessage: serverMessage,
serverTimestamp: serverTimestamp
});
}
)
.listen({
type: "redis-queue",
pin: 'role:test,cmd:*',
timeout: config["redis-queue"].timeout,
host: config["redis-queue"].host,
port: config["redis-queue"].port
})
.ready(function () {
console.log('role:test server is ready and listening');
}); |
<?php
namespace React\Tests\Http;
use Clue\React\Block;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\<API key>;
use React\EventLoop\Loop;
use React\Http\HttpServer;
use React\Http\Message\Response;
use React\Http\Middleware\<API key>;
use React\Http\Middleware\<API key>;
use React\Http\Middleware\<API key>;
use React\Socket\ConnectionInterface;
use React\Socket\Connector;
use React\Socket\SocketServer;
use React\Promise;
use React\Promise\Stream;
use React\Stream\ThroughStream;
class <API key> extends TestCase
{
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('http://' . noScheme($socket->getAddress()) . '/', $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(
function () {
return new Response(404);
}
);
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 404 Not Found", $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('http://' . noScheme($socket->getAddress()) . '/', $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: localhost:1000\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('http://localhost:1000/', $response);
$socket->close();
}
public function <API key>()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Not supported on HHVM');
}
$connector = new Connector(array(
'tls' => array('verify_peer' => false)
));
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$socket = new SocketServer('tls://127.0.0.1:0', array('tls' => array(
'local_cert' => __DIR__ . '/../examples/localhost.pem'
)));
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('https://' . noScheme($socket->getAddress()) . '/', $response);
$socket->close();
}
public function <API key>()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Not supported on HHVM');
}
$http = new HttpServer(function (RequestInterface $request) {
return new Response(
200,
array(),
str_repeat('.', 33000)
);
});
$socket = new SocketServer('tls://127.0.0.1:0', array('tls' => array(
'local_cert' => __DIR__ . '/../examples/localhost.pem'
)));
$http->listen($socket);
$connector = new Connector(array(
'tls' => array('verify_peer' => false)
));
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>("\r\nContent-Length: 33000\r\n", $response);
$this-><API key>("\r\n". str_repeat('.', 33000), $response);
$socket->close();
}
public function <API key>()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Not supported on HHVM');
}
$connector = new Connector(array(
'tls' => array('verify_peer' => false)
));
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$socket = new SocketServer('tls://127.0.0.1:0', array('tls' => array(
'local_cert' => __DIR__ . '/../examples/localhost.pem'
)));
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('https://' . noScheme($socket->getAddress()) . '/', $response);
$socket->close();
}
public function <API key>()
{
try {
$socket = new SocketServer('127.0.0.1:80');
} catch (\RuntimeException $e) {
$this->markTestSkipped('Listening on port 80 failed (root and unused?)');
}
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('http://127.0.0.1/', $response);
$socket->close();
}
public function <API key>()
{
try {
$socket = new SocketServer('127.0.0.1:80');
} catch (\RuntimeException $e) {
$this->markTestSkipped('Listening on port 80 failed (root and unused?)');
}
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('http://127.0.0.1/', $response);
$socket->close();
}
public function <API key>()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Not supported on HHVM');
}
try {
$socket = new SocketServer('tls://127.0.0.1:443', array('tls' => array(
'local_cert' => __DIR__ . '/../examples/localhost.pem'
)));
} catch (\RuntimeException $e) {
$this->markTestSkipped('Listening on port 443 failed (root and unused?)');
}
$connector = new Connector(array(
'tls' => array('verify_peer' => false)
));
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('https://127.0.0.1/', $response);
$socket->close();
}
public function <API key>()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Not supported on HHVM');
}
try {
$socket = new SocketServer('tls://127.0.0.1:443', array('tls' => array(
'local_cert' => __DIR__ . '/../examples/localhost.pem'
)));
} catch (\RuntimeException $e) {
$this->markTestSkipped('Listening on port 443 failed (root and unused?)');
}
$connector = new Connector(array(
'tls' => array('verify_peer' => false)
));
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('https://127.0.0.1/', $response);
$socket->close();
}
public function <API key>()
{
try {
$socket = new SocketServer('127.0.0.1:443');
} catch (\RuntimeException $e) {
$this->markTestSkipped('Listening on port 443 failed (root and unused?)');
}
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri());
});
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('http://127.0.0.1:443/', $response);
$socket->close();
}
public function <API key>()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Not supported on HHVM');
}
try {
$socket = new SocketServer('tls://127.0.0.1:80', array('tls' => array(
'local_cert' => __DIR__ . '/../examples/localhost.pem'
)));
} catch (\RuntimeException $e) {
$this->markTestSkipped('Listening on port 80 failed (root and unused?)');
}
$connector = new Connector(array(
'tls' => array('verify_peer' => false)
));
$http = new HttpServer(function (RequestInterface $request) {
return new Response(200, array(), (string)$request->getUri() . 'x' . $request->getHeaderLine('Host'));
});
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>('https://127.0.0.1:80/', $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$stream = new ThroughStream();
$stream->close();
$http = new HttpServer(function (RequestInterface $request) use ($stream) {
return new Response(200, array(), $stream);
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\n\r\n");
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.0 200 OK", $response);
$this-><API key>("\r\n\r\n", $response);
$socket->close();
}
public function testRequestHandlerWithStreamingRequestWillReceiveCloseEventIfConnectionClosesWhileSendingBody()
{
$connector = new Connector();
$once = $this->expectCallableOnce();
$http = new HttpServer(
new <API key>(),
function (RequestInterface $request) use ($once) {
$request->getBody()->on('close', $once);
}
);
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nContent-Length: 100\r\n\r\n");
Loop::addTimer(0.001, function() use ($conn) {
$conn->end();
});
});
Block\sleep(0.1);
$socket->close();
}
public function testStreamFromRequestHandlerWillBeClosedIfConnectionClosesWhileSendingStreamingRequestBody()
{
$connector = new Connector();
$stream = new ThroughStream();
$http = new HttpServer(
new <API key>(),
function (RequestInterface $request) use ($stream) {
return new Response(200, array(), $stream);
}
);
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\nContent-Length: 100\r\n\r\n");
Loop::addTimer(0.001, function() use ($conn) {
$conn->end();
});
});
// stream will be closed within 0.1s
$ret = Block\await(Stream\first($stream, 'close'), null, 0.1);
$socket->close();
$this->assertNull($ret);
}
public function <API key>()
{
$connector = new Connector();
$stream = new ThroughStream();
$http = new HttpServer(function (RequestInterface $request) use ($stream) {
return new Response(200, array(), $stream);
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.0\r\n\r\n");
Loop::addTimer(0.1, function () use ($conn) {
$conn->close();
});
});
// await response stream to be closed
$ret = Block\await(Stream\first($stream, 'close'), null, 1.0);
$socket->close();
$this->assertNull($ret);
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
$stream = new ThroughStream();
Loop::addTimer(0.1, function () use ($stream) {
$stream->end();
});
return new Response(101, array('Upgrade' => 'echo'), $stream);
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("GET / HTTP/1.1\r\nHost: example.com:80\r\nUpgrade: echo\r\n\r\n");
$conn->once('data', function () use ($conn) {
$conn->write('hello');
$conn->write('world');
});
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.1 101 Switching Protocols\r\n", $response);
$this-><API key>("\r\n\r\nhelloworld", $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
$stream = new ThroughStream();
Loop::addTimer(0.1, function () use ($stream) {
$stream->end();
});
return new Response(101, array('Upgrade' => 'echo'), $stream);
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("POST / HTTP/1.1\r\nHost: example.com:80\r\nUpgrade: echo\r\nContent-Length: 3\r\n\r\n");
$conn->write('hoh');
$conn->once('data', function () use ($conn) {
$conn->write('hello');
$conn->write('world');
});
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.1 101 Switching Protocols\r\n", $response);
$this-><API key>("\r\n\r\nhelloworld", $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
$stream = new ThroughStream();
Loop::addTimer(0.1, function () use ($stream) {
$stream->end();
});
return new Response(200, array(), $stream);
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("CONNECT example.com:80 HTTP/1.1\r\nHost: example.com:80\r\nConnection: close\r\n\r\n");
$conn->once('data', function () use ($conn) {
$conn->write('hello');
$conn->write('world');
});
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.1 200 OK\r\n", $response);
$this-><API key>("\r\n\r\nhelloworld", $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
$stream = new ThroughStream();
Loop::addTimer(0.1, function () use ($stream) {
$stream->end();
});
return new Promise\Promise(function ($resolve) use ($stream) {
Loop::addTimer(0.001, function () use ($resolve, $stream) {
$resolve(new Response(200, array(), $stream));
});
});
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("CONNECT example.com:80 HTTP/1.1\r\nHost: example.com:80\r\nConnection: close\r\n\r\n");
$conn->once('data', function () use ($conn) {
$conn->write('hello');
$conn->write('world');
});
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.1 200 OK\r\n", $response);
$this-><API key>("\r\n\r\nhelloworld", $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(function (RequestInterface $request) {
$stream = new ThroughStream();
$stream->close();
return new Response(200, array(), $stream);
});
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write("CONNECT example.com:80 HTTP/1.1\r\nHost: example.com:80\r\nConnection: close\r\n\r\n");
$conn->once('data', function () use ($conn) {
$conn->write('hello');
$conn->write('world');
});
return Stream\buffer($conn);
});
$response = Block\await($result, null, 1.0);
$this-><API key>("HTTP/1.1 200 OK\r\n", $response);
$this-><API key>("\r\n\r\n", $response);
$socket->close();
}
public function <API key>()
{
$connector = new Connector();
$http = new HttpServer(
new <API key>(5),
new <API key>(16 * 1024 * 1024), // 16 MiB
function (<API key> $request, $next) {
return new Promise\Promise(function ($resolve) use ($request, $next) {
Loop::addTimer(0.1, function () use ($request, $resolve, $next) {
$resolve($next($request));
});
});
},
function (<API key> $request) {
return new Response(200, array(), (string)strlen((string)$request->getBody()));
}
);
$socket = new SocketServer('127.0.0.1:0');
$http->listen($socket);
$result = array();
for ($i = 0; $i < 6; $i++) {
$result[] = $connector->connect($socket->getAddress())->then(function (ConnectionInterface $conn) {
$conn->write(
"GET / HTTP/1.0\r\nContent-Length: 1024\r\nHost: " . noScheme($conn->getRemoteAddress()) . "\r\n\r\n" .
str_repeat('a', 1024) .
"\r\n\r\n"
);
return Stream\buffer($conn);
});
}
$responses = Block\await(Promise\all($result), null, 1.0);
foreach ($responses as $response) {
$this-><API key>("HTTP/1.0 200 OK", $response, $response);
$this->assertTrue(substr($response, -4) == 1024, $response);
}
$socket->close();
}
}
function noScheme($uri)
{
$pos = strpos($uri, ':
if ($pos !== false) {
$uri = substr($uri, $pos + 3);
}
return $uri;
} |
# CHANGELOG
This file is a manually maintained list of changes for each release. Feel free
to add your changes here when sending pull requests. Also send corrections if
you spot any mistakes.
## 0.2.0 (2014-07-21)
* BC break: Rename namespace to `Clue\React\Icmp` and use PSR-4 layout
([
## 0.1.0 (2014-03-18)
* First tagged release
* Send and receive arbitrary ICMP messages
* Promise-based `Icmp::ping()` method (ICMP echo request and echo reply)
* Event-driven access to incoming ICMP messages
## 0.0.0 (2013-04-14)
* Initial concept |
<?php
namespace BardisCMS\ContentBlockBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\<API key>;
class Configuration implements <API key> {
/**
* {@inheritDoc}
*/
public function <API key>() {
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('content_block');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
$rootNode
->children()
->booleanNode('loadservices')->defaultFalse()->end()
->arrayNode('mediasizes')
->isRequired()
-><API key>()
->useAttributeAsKey('name')
->prototype('scalar')->defaultValue(null)->end()
->end()
->arrayNode('contenttypes')
->isRequired()
-><API key>()
->useAttributeAsKey('name')
->prototype('scalar')->defaultValue(null)->end()
->end()
->arrayNode('contentsizes')
->isRequired()
-><API key>()
->useAttributeAsKey('name')
->prototype('scalar')->defaultValue(null)->end()
->end()
->end();
return $treeBuilder;
}
} |
#include <ui_client/tag/tag_handler_widget.h>
#include <functional>
#include <QDebug>
#include <QEvent>
#include <QKeyEvent>
#include <core/utils/string_utils.h>
#include <core/debug/Debug.h>
#include <ui_client/tag/<API key>.h>
#include <ui_client/utils/<API key>.h>
#include "<API key>.h"
void
TagHandlerWidget::removeCurrentSelTag(void)
{
if (!selected_tags_->hasSelection()) {
return;
}
TagWidget* current = selected_tags_->selected();
selected_tags_->popTag(current);
emit tagRemoved(current->tag());
freeWidget(current);
}
void
TagHandlerWidget::selectNextTag(TagListHandler* tag_handler, bool left_dir, bool only_if_selected, bool emit_signal)
{
if (!tag_handler->hasSelection() && only_if_selected) {
return;
}
if (left_dir) {
emit_signal = tag_handler->selectPrev() && emit_signal;
} else {
emit_signal = tag_handler->selectNext() && emit_signal;
}
if (emit_signal && tag_handler->hasSelection()) {
emit tagSelected(tag_handler->selected()->tag());
}
}
TagWidget*
TagHandlerWidget::getWidget(Tag::ConstPtr& tag)
{
TagWidget* result = nullptr;
if (widgets_queue_.empty()) {
result = new TagWidget;
} else {
result = widgets_queue_.back();
widgets_queue_.pop_back();
}
result->configure(tag);
return result;
}
void
TagHandlerWidget::freeWidget(TagWidget* widget)
{
ASSERT_PTR(widget);
widget->setParent(nullptr);
widget->clear();
widgets_queue_.push_back(widget);
}
TagWidget*
TagHandlerWidget::getOrCreateTag(const std::string& text, bool <API key>)
{
Tag::ConstPtr tag;
if (<API key>) {
tag = service_api_->addTag(text);
ASSERT_PTR(tag.get());
} else {
tag = service_api_->getTagByText(text);
}
return tag.get() != nullptr ? getWidget(tag) : nullptr;
}
void
TagHandlerWidget::<API key>(TagListHandler* handler)
{
std::vector<TagWidget*> tags;
handler->popAllTags(tags);
for (TagWidget* w : tags) {
freeWidget(w);
}
}
std::vector<TagWidget*>
TagHandlerWidget::toTagWidgets(const std::set<Tag::ConstPtr>& tags)
{
std::vector<TagWidget*> result;
for (Tag::ConstPtr t : tags) {
result.push_back(getWidget(t));
}
return result;
}
void
TagHandlerWidget::addSimpleKeyTrigger(Qt::Key key, QEvent::Type type, bool (TagHandlerWidget::* fun)(QKeyEvent* key_event))
{
KeyTrigger::Configuration config(key);
config.event_type = type;
FunctionKeyTrigger* key_trigger = new FunctionKeyTrigger(config, std::bind(fun, this, std::placeholders::_1));
key_triggers_.push_back(KeyTrigger::Ptr(key_trigger));
}
void
TagHandlerWidget::buildKeyTriggers(void)
{
addSimpleKeyTrigger(Qt::Key_Tab, QEvent::KeyPress, &TagHandlerWidget::onTabPressed);
addSimpleKeyTrigger(Qt::Key_Backspace, QEvent::KeyRelease, &TagHandlerWidget::onBackspacePressed);
addSimpleKeyTrigger(Qt::Key_Escape, QEvent::KeyRelease, &TagHandlerWidget::onEscapePressed);
addSimpleKeyTrigger(Qt::Key_Return, QEvent::KeyRelease, &TagHandlerWidget::onReturnPressed);
addSimpleKeyTrigger(Qt::Key_Space, QEvent::KeyRelease, &TagHandlerWidget::onSpacePressed);
}
bool
TagHandlerWidget::onTabPressed(QKeyEvent* key_event)
{
const bool shift_pressed = key_event->modifiers() & Qt::ShiftModifier;
if (selected_tags_->hasSelection() || suggested_tags_->hasSelection()) {
selectNextTag(selected_tags_, shift_pressed, true);
selectNextTag(suggested_tags_, shift_pressed, true, false);
} else {
// autocomplete?
const std::string current_text = ui->lineEdit->text().toStdString();
const std::string expanded = core::StringUtils::<API key>(suggestedTagsTexts(), current_text);
qDebug() << "current_text: " << current_text.c_str() << " expanded: " << expanded.c_str();
if (expanded == current_text) {
// we need to jump to the suggested tags to select one
selectNextTag(suggested_tags_, shift_pressed, false, false);
} else {
ui->lineEdit->setText(expanded.c_str());
}
}
key_event->accept();
qDebug() << "accepting event tab";
ui->lineEdit->setFocus();
return true;
}
bool
TagHandlerWidget::onBackspacePressed(QKeyEvent* key_event)
{
// Check if we need to select / remove tag when empty text
if (ui->lineEdit->text().isEmpty()) {
if (selected_tags_->hasSelection()) {
removeCurrentSelTag();
} else if (selected_tags_->hasTags()){
selected_tags_->select(selected_tags_->last());
emit tagSelected(selected_tags_->selected()->tag());
}
}
return false;
}
bool
TagHandlerWidget::onEscapePressed(QKeyEvent* key_event)
{
selected_tags_->unselect(selected_tags_->selected());
suggested_tags_->unselect(suggested_tags_->selected());
return false;
}
bool
TagHandlerWidget::onReturnPressed(QKeyEvent* key_event)
{
if (suggested_tags_->hasSelection()) {
TagWidget* sel_tag = suggested_tags_->selected();
suggested_tags_->popTag(sel_tag);
selected_tags_->addTag(sel_tag);
ui->lineEdit->clear();
<API key>(suggested_tags_);
emit tagSelected(sel_tag->tag());
key_event->accept();
return true;
}
return false;
}
bool
TagHandlerWidget::onSpacePressed(QKeyEvent* key_event)
{
if (!ui->lineEdit->text().isEmpty()) {
const std::string& tag_text = ServiceAPI::normalizeTagText(ui->lineEdit->text().toStdString());
if (!selected_tags_->hasTagWithText(tag_text)) {
TagWidget* new_tag = getOrCreateTag(tag_text, can_add_flag_);
if (new_tag != nullptr) {
selected_tags_->addTag(new_tag);
emit tagSelected(new_tag->tag());
ui->lineEdit->clear();
}
}
}
key_event->accept();
return true;
}
bool
TagHandlerWidget::lineEditEventFilter(QEvent *event)
{
if (event->type() != QEvent::KeyPress && event->type() != QEvent::KeyRelease) {
return false;
}
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
for (KeyTrigger::Ptr& kt : key_triggers_) {
if (kt->shouldTrigger(ke)) {
if (kt->trigger(ke)) {
return true;
}
}
}
if (ke->type() == QEvent::KeyRelease) {
emit someKeyPressed(ke);
}
return false;
}
void
TagHandlerWidget::lineEditTextChanged(const QString& text)
{
selected_tags_->unselect(selected_tags_->selected());
emit inputTextChanged(text);
}
TagHandlerWidget::TagHandlerWidget(QWidget *parent, ServiceAPI* service_api) :
QWidget(parent),
ui(new Ui::TagHandlerWidget),
service_api_(service_api),
can_add_flag_(false)
{
ASSERT_PTR(service_api);
ui->setupUi(this);
selected_tags_ = new TagListHandler;
suggested_tags_ = new TagListHandler;
selected_tags_->setFocusPolicy(Qt::FocusPolicy::NoFocus);
suggested_tags_->setFocusPolicy(Qt::FocusPolicy::NoFocus);
ui->verticalLayout->addWidget(selected_tags_);
ui->verticalLayout->addWidget(suggested_tags_);
installEventFilter(this);
InputTextValidator* validator = new InputTextValidator(this);
ui->lineEdit->setValidator(validator);
ui->lineEdit->installEventFilter(this);
QObject::connect(ui->lineEdit, &QLineEdit::textChanged, this, &TagHandlerWidget::lineEditTextChanged);
buildKeyTriggers();
}
TagHandlerWidget::~TagHandlerWidget()
{
clear();
delete ui;
}
void
TagHandlerWidget::setAddTagsFlag(bool can_add_flag)
{
can_add_flag_ = can_add_flag;
}
void
TagHandlerWidget::setSuggestedTags(const std::set<Tag::ConstPtr>& tags)
{
<API key>(suggested_tags_);
suggested_tags_->setTags(toTagWidgets(tags));
}
void
TagHandlerWidget::setSelectedTags(const std::set<Tag::ConstPtr>& tags)
{
<API key>(selected_tags_);
selected_tags_->setTags(toTagWidgets(tags));
}
bool
TagHandlerWidget::eventFilter(QObject *object, QEvent *event)
{
if (object == ui->lineEdit) {
return lineEditEventFilter(event);
}
return false;
}
std::vector<std::string>
TagHandlerWidget::suggestedTagsTexts(void) const
{
std::vector<std::string> tags_text;
const std::vector<TagWidget*>& tags = suggested_tags_->tags();
for (const TagWidget* tag : tags) {
ASSERT_PTR(tag);
ASSERT_PTR(tag->tag().get());
tags_text.push_back(tag->tag()->text());
}
return tags_text;
}
std::vector<std::string>
TagHandlerWidget::selectedTagsTexts(void) const
{
std::vector<std::string> tags_text;
const std::vector<TagWidget*>& tags = selected_tags_->tags();
for (const TagWidget* tag : tags) {
tags_text.push_back(tag->tag()->text());
}
return tags_text;
}
bool
TagHandlerWidget::hasSelectedTags(void) const
{
return selected_tags_->hasTags();
}
QString
TagHandlerWidget::currentText(void) const
{
return ui->lineEdit->text();
}
void
TagHandlerWidget::clear(void)
{
<API key>(selected_tags_);
<API key>(suggested_tags_);
ui->lineEdit->clear();
}
void
TagHandlerWidget::activate(void)
{
setFocus();
ui->lineEdit->setFocus();
} |
#ifndef <API key>
#define <API key>
/*
* These are changed sproadically to test that the
* values assigned here propogate through the project.
* Setting the pressure to zero effectively turns off
* atmospheric refraction.
*
* The canonical values are:
* DEFAULT_PRESSURE = 1010.;
* DEFAULT_TEMPERATURE = 10.;
*/
namespace <API key>{
inline constexpr double F_to_C( double F ){
return (F - 32.0)*5.0/9.0;
}
constexpr float DEFAULT_PRESSURE = 1010; /* mb (millibars) */
constexpr float DEFAULT_TEMPERATURE = 10; /* Celsius */
// constexpr float DEFAULT_TEMPERATURE = F_to_C( -3.0 );
}
#endif /* <API key> */ |
package com.alorma.github.bean;
import com.alorma.github.sdk.bean.dto.response.Notification;
public class ClearNotification {
private Notification notification;
private boolean allRepository;
public ClearNotification(Notification notification, boolean allRepository) {
this.notification = notification;
this.allRepository = allRepository;
}
public Notification getNotification() {
return notification;
}
public void setNotification(Notification notification) {
this.notification = notification;
}
public boolean isAllRepository() {
return allRepository;
}
public void setAllRepository(boolean allRepository) {
this.allRepository = allRepository;
}
} |
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'starter.templatesComponent', 'ngCordova'])
.run(function($ionicPlatform, $cordovaStatusbar) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.<API key>(true);
}
if(window.StatusBar) {
// org.apache.cordova.statusbar required
$cordovaStatusbar.styleColor('white');
//StatusBar.styleDefault();
}
});
})
.constant('APPID', 'obeynets')
.constant('APIKEY','<SHA256-like>')
.constant('BASEURL', 'http:
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: "/tab",
abstract: true,
templateUrl: "templates/tabs.html",
resolve: {
category: function (Category) {
return Category.getPromise();
},
areas : function(Area){
return Area.getPromise();
},
items : function(Item){
return Item.getPromise();
}
},
})
// Each tab has its own nav history stack:
.state('tab.item', {
url: '/item',
views: {
'tab-item': {
templateUrl: 'templates/tab-item.html',
controller: 'FindCtrl'
}
},
})
.state('tab.item-view', {
url: '/item/:itemId',
views: {
'tab-item': {
templateUrl: 'templates/item-view.html',
controller: 'ItemCtrl'
}
}
})
.state('tab.publish', {
url: '/publish',
views: {
'tab-publish': {
templateUrl: 'templates/tab-publish.html',
controller: 'PublishCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
})
.state('tab.settings', {
url: '/settings',
views: {
'tab-settings': {
templateUrl: 'templates/tab-settings.html',
controller: 'SettingsCtrl'
}
}
})
.state('tab.login', {
url: '/settings/login',
views: {
'tab-settings': {
templateUrl: 'templates/login-view.html',
controller: 'LoginCtrl'
}
}
})
.state('tab.signup', {
url: '/settings/signup',
views: {
'tab-settings': {
templateUrl: 'templates/signup-view.html',
controller: 'LoginCtrl'
}
}
})
.state('tab.contact', {
url: '/settings/contact',
views: {
'tab-settings': {
templateUrl: 'templates/contact-view.html',
controller: 'SettingsCtrl'
}
}
})
.state('tab.terms', {
url: '/settings/terms',
views: {
'tab-settings': {
templateUrl: 'templates/terms-view.html',
controller: 'SettingsCtrl'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/item');
}); |
var app = require('app');
var BrowserWindow = require('browser-window');
require('crash-reporter').start();
var win;
app.on('window-all-closed', function () {
console.log('window-all-closed!');
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function () {
win = new BrowserWindow({width: 800, height: 480});
win.loadUrl('file://' + __dirname + '/index.html');
win.on('closed', function () {
console.log('closed!');
win = null;
});
}); |
<?php
declare(strict_types=1);
namespace Funivan\PhpTokenizer\Strategy;
use Funivan\PhpTokenizer\Token;
class StrategyResult
{
/**
* @var Token
*/
private $token = null;
/**
* @var int|null
*/
private $nexTokenIndex = null;
/**
* @var bool
*/
private $valid = false;
/**
* @return Token|null
*/
public function getToken()
{
return $this->token;
}
/**
* @return boolean
*/
public function isValid()
{
return ($this->valid === true);
}
/**
* @param boolean $valid
* @return $this
*/
public function setValid($valid)
{
$this->valid = (boolean)$valid;
return $this;
}
/**
* @param Token $token
* @return $this
*/
public function setToken(Token $token)
{
$this->token = $token;
return $this;
}
/**
* @param int $nexTokenIndex
* @return $this
*/
public function setNexTokenIndex($nexTokenIndex)
{
$this->nexTokenIndex = $nexTokenIndex;
return $this;
}
/**
* @return int|null
*/
public function getNexTokenIndex()
{
return $this->nexTokenIndex;
}
} |
The MIT License
Copyright (c) 2008 Christian Bryan
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. |
var facebookComments = angular.module('facebookComments', []);
facebookComments.directive('dynFbCommentBox', function () {
function createHTML(href, numposts, progwidth) {
return '<div class="fb-comments" ' +
'data-href="' + href + '" ' +
'data-numposts="' + numposts + '" ' +
'data-width="' + progwidth + '">' +
'</div>';
}
return {
restrict: 'A',
scope: {},
link: function postLink(scope, elem, attrs) {
attrs.$observe('pageHref', function (newValue) {
var href = newValue;
var numposts = attrs.numposts || 5;
var progwidth = attrs.progwidth;
elem.html(createHTML(href, numposts, progwidth));
FB.XFBML.parse(elem[0]);
});
}
};
}); |
window.semantic = {
handler: {}
};
semantic.ready = function () {
var menu = {};
menu = {
mouseenter: function () {
$(this).stop().animate({
width: '155px'
}, 300, function () {
$(this).find('.text').show();
});
},
mouseleave: function (event) {
$(this).find('.text').hide();
$(this).stop().animate({
width: '70px'
}, 300);
}
};
var $sidebarButton = $("#showSidBtn"),
$uiSidebar = $(".ui header .sidebar");
$sidebarButton.on('mouseenter', menu.mouseenter).on('mouseleave', menu.mouseleave);
$uiSidebar.sidebar('attach events', '#showSidBtn,.showAll');
}
$(function () {
semantic.ready();
}) |
import React from 'react';
import { Col, Icon, Row } from '<API key>';
import styles from './styles.module.scss';
export default class IconsExample extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
}
componentDidMount() {
// Get the icons from the asset map
const url = 'https://aa-fonts.s3.amazonaws.com/app-arena/app-arena.json';
fetch(url)
.then(res => res.json())
.then((rows) => {
this.setState({ data: rows });
});
}
render() {
return (
<div>
<h3>Sizes</h3>
<Row>
<Col xs="2" key="atoms-l" className={styles.iconColumn}>
<Icon name="atoms-l" />
<p>
<code><Icon name="atoms-l" /></code>
</p>
</Col>
<Col xs="2" key="atoms-l" className={styles.iconColumn}>
<Icon name="atoms-l" size="2x" />
<p>
<code><Icon name="atoms-l" size="2x" /></code>
</p>
</Col>
<Col xs="2" key="atoms-l" className={styles.iconColumn}>
<Icon name="atoms-l" size="3x" />
<p>
<code><Icon name="atoms-l" size="3x" /></code>
</p>
</Col>
<Col xs="2" key="atoms-l" className={styles.iconColumn}>
<Icon name="atoms-l" size="4x" />
<p>
<code><Icon name="atoms-l" size="4x" /></code>
</p>
</Col>
<Col xs="2" key="atoms-l" className={styles.iconColumn}>
<Icon name="atoms-l" size="5x" />
<p>
<code><Icon name="atoms-l" size="5x" /></code>
</p>
</Col>
</Row>
<h3>Fixed width</h3>
<ul>
<li>
<Icon name="chevron-o-right" fixedWidth size="1x" />
{' '}
Fixed width
</li>
<li>
<Icon name="close" fixedWidth size="1x" />
{' '}
Fixed width
</li>
<li>
<Icon name="users" fixedWidth size="1x" />
{' '}
Fixed width
</li>
<li>
<Icon name="chevron-o-right" fixedWidth size="2x" />
{' '}
Fixed width
</li>
<li>
<Icon name="close" fixedWidth size="2x" />
{' '}
Fixed width
</li>
<li>
<Icon name="users" fixedWidth size="2x" />
{' '}
Fixed width
</li>
<li>
<Icon name="chevron-o-right" fixedWidth size="3x" />
{' '}
Fixed width
</li>
<li>
<Icon name="close" fixedWidth size="3x" />
{' '}
Fixed width
</li>
<li>
<Icon name="users" fixedWidth size="3x" />
{' '}
Fixed width
</li>
</ul>
<ul>
<li>
<Icon name="chevron-o-right" size="2x" />
{' '}
Without fixed width
</li>
<li>
<Icon name="close" size="2x" />
{' '}
Without fixed width
</li>
<li>
<Icon name="users" size="2x" />
{' '}
Without fixed width
</li>
</ul>
<h3>Animations</h3>
<Row>
<Col xs="2" key="atoms-l" className={styles.iconColumn}>
<Icon name="atoms-l" pulse size="3x" />
<p>
<code><Icon name="atoms-l" pulse /></code>
</p>
</Col>
<Col xs="2" key="atoms-l" className={styles.iconColumn}>
<Icon name="atoms-l" spin size="3x" />
<p>
<code><Icon name="atoms-l" spin /></code>
</p>
</Col>
</Row>
<h3>Available icons</h3>
<Row>
{Object.keys(this.state.data)
.sort()
.map((key, index) => (
<Col xs="2" key={key} className={styles.iconColumn}>
<Icon name={key} size="2x" />
<p>
<code>
<Icon name="
{key}
" />
</code>
</p>
</Col>
))}
</Row>
</div>
);
}
} |
package pl.edu.bogdan.training.di.annotation;
public class CsvReportFormatter implements IReportFormatter {
public void format() {
System.out.println("CSV FORMATTER");
}
} |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "<>", Scope = "member", Target = "~M:Hprose.RPC.Owin.OwinHttpHandler.GetOutputStream(System.Collections.Generic.IDictionary{System.String,System.Object})~System.IO.Stream")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "<>", Scope = "member", Target = "~M:Hprose.RPC.Owin.OwinHttpHandler.<API key>(System.Collections.Generic.IDictionary{System.String,System.Object})~System.Threading.Tasks.Task{System.Boolean}")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "<>", Scope = "member", Target = "~M:Hprose.RPC.Owin.OwinHttpHandler.<API key>(System.Collections.Generic.IDictionary{System.String,System.Object})~System.Threading.Tasks.Task{System.Boolean}")] |
<div>
{/* <!-- title -->*/}
<h1 className={css.title}>
Excel Merge Tool
</h1>
{/* <!-- dropZone -->*/}
<Dropzone className={css.dropzone} onDrop={this.onDrop}>
{ files.map((file, index) => <img key={index} src={file.preview} width={200} />)}
{/* <!-- dropItem -->*/}
<div className={css.dropItem}>
<div><img className={css.xlsxImg} src='./xlsxImg.png'/></div>
<label className={css.fileName}>
test.xlsx
</label>
</div>
</Dropzone>
{/* <!-- optionTab -->*/}
<div className={css.tabWrapper}>
<div className={css.tabHeader}>
<div className={cx(css.optionTabTitle, css.isOn)}>
MERGE
</div>
<div className={css.optionTabTitle}>
LIST
</div>
</div>
<div className={css.tabBody}>
<div className={cx(css.optionTa, css.isOn)}>
<div>
<label></label>
<input type='radio' name='mode'>ALL</input>
<input type='radio' name='mode'>NONE</input>
<input type='radio' name='mode'>CONFLICT</input>
</div>
<div>
<label></label>
<input type='text' />
</div>
<div>
<label></label>
<input type='checkbox' />
</div>
</div>
<div className='css.optionTab'>
<div>
<label></label>
<input type='checkbox' />
</div>
<div>
<label></label>
<input type='text' />
</div>
<div>
<label></label>
<input type='checkbox' />
</div>
</div>
<div className={css.tabFooter}>
<button onClick={this.openFile}></button>
</div>
</div>
</div>
{/* <!-- tip gif -->*/}
<div className={css.tipGif}>
</div>
</div> |
class Array
def quicksort(list = self)
return list if list.nil? or list.size <= 1
less, more = list[1..-1].partition { |i| i < list[0] }
quicksort(less) + [list[0]] + quicksort(more)
end
def bubblesort(list = self)
slist = list.clone
for i in 0..(slist.length - 1)
for j in 0..(slist.length - i - 2)
if ( slist[j + 1] <=> slist[j] ) == -1
slist[j], slist[j + 1] = slist[j + 1], slist[j]
end
end
end
slist
end
end
Viiite.bench do |b|
b.variation_point :ruby, Viiite.which_ruby
b.range_over([100, 200, 300, 400, 500], :size) do |size|
b.range_over(1..5, :i) do
bench_case = Array.new(size) { rand }
b.report(:quicksort) { bench_case.quicksort }
b.report(:bubblesort){ bench_case.bubblesort }
end
end
end |
<?php
class <API key> extends <API key>
{
public function start()
{
if (<API key>::SQUARE == $this->_config->getSor()) {
return false;
}
if (false === $this->_config->getEnableImages() || false === $this->_config->isCatalogEnabled()) {
return false;
}
Mage::getModel('squareup_omni/catalog_images')->start();
return true;
}
}
/* Filename: Images.php */
/* Location: app/code/community/Squareup/Omni/Model/Images.php */ |
import React, {Component} from 'react';
import {
Dimensions,
Responder,
View
} from 'react-native';
import Svg,{
Defs,
G,
LinearGradient,
Path,
Stop,
Text
} from 'react-native-svg';
import {Spring,EasingFunctions} from '../timing-functions';
import {polarToCartesian, computeChartSum, Tweener, makeCircle, <API key>, complement} from '.';
const AXIS_TICKS = 5;
const MARKER_RADIUS = 5;
const <API key> = 1500;
const PADDING_TOP = 20;
class ArtyChartyRadar extends Component {
constructor(props) {
super(props);
this.state = {
t: 0,
path: ''
};
}
componentWillMount() {
this.computeChartStats();
this.polarGrid = this.makePolarGrid(AXIS_TICKS);
this.axisLabel = this.makeAxisLabel(AXIS_TICKS)
this.initPanHandler();
this.animateChartTweener = new Tweener(<API key>, t => {
this.setState({t});
}, EasingFunctions.easeOutQuint, false);
}
componentDidMount() {
this.animateChartTweener.resetAndPlay();
}
<API key>(nextProps) {
}
<API key>() {
this.animateChartTweener.stop();
}
computeChartStats() {
this.maxVal = Math.max.apply(null,this.props.data.reduce((a, b) => {return a.concat(b.data);}, []));
this.size = this.props.size || Dimensions.get('window').width;
this.center = this.size / 2;
this.sizeScaler = this.center / this.maxVal;
this.angleStepSize = 360 / this.props.data[0].data.length;
}
makeCoords(data) {
return coords = data.map((d, idx) => {
let coords = polarToCartesian(this.center, this.center, d*this.sizeScaler * this.state.t, this.angleStepSize*idx);
return {
x: coords.x,
y: coords.y + PADDING_TOP
};
});
}
makeChartPath(data) {
let path = ['M'];
data.map((d, idx) => {
path.push(d.x);
path.push(d.y);
path.push(idx < this.props.data[0].data.length-1 ? 'L' : 'Z');
return {
x: d.x,
y: d.y
};
});
return path;
}
initPanHandler() {
this._responder =
{
<API key>: (evt) => true,
onResponderRelease: (evt) => {
let clickedMarker, clickedChart;
this.coords.some((cords, idx) => {
clickedMarker =
<API key>(cords, evt.nativeEvent.locationX, evt.nativeEvent.locationY, MARKER_RADIUS*2);
if (clickedMarker > -1) {
clickedChart = idx;
return true;
}
});
this.setState({
selectedMarker: clickedMarker,
clickedChart: clickedChart
});
if (this.props.onMarkerClick) {
this.props.onMarkerClick(clickedMarker, clickedChart);
}
}
}
}
makePolarGrid(num) {
let i, j, path = [], coords;
let stepSize = this.center / num;
for (i = 0; i < num+1; i++) {
for (j = 0; j < this.props.data[0].data.length; j++) {
path.push(j > 0 ? 'L' : 'M');
coords = polarToCartesian(this.center, this.center + PADDING_TOP, stepSize * i, this.angleStepSize*j);
path.push(coords.x);
path.push(coords.y);
}
path.push('Z');
}
for (j = 0; j < this.props.data[0].data.length; j++) {
path.push('M');
path.push(this.center);
path.push(this.center + PADDING_TOP);
path.push('L');
coords = polarToCartesian(this.center, this.center + PADDING_TOP, this.center, this.angleStepSize*j);
path.push(coords.x);
path.push(coords.y);
}
return <Path strokeDash={this.props.gridStrokeDash || []} stroke={this.props.gridColor} strokeWidth={this.props.gridLineWidth || 1} d={path} fill={this.props.fill || 'rgba(0,0,0,.1)'} />
}
makeAxisLabel(num) {
let texts = [];
let stepSize = this.center / num;
for (i = 1; i < num+1; i++) {
texts.push(<Text
key={i}
fill={this.props.gridTextColor || 'black'}
strokeWidth={.25}
stroke={complement(this.props.gridTextColor || 'black')}
font={`${this.props.gridTextSize || 12}px Arial`}
x={this.center}
y={stepSize*(i-1) - (this.props.gridTextSize ? this.props.gridTextSize * .7 : 12) + PADDING_TOP}>
{'—'+(this.maxVal/num * (num-i+1)).toFixed(2)}
</Text>);
}
return texts;
}
makeOuterLabel() {
let stepSize = this.center / this.props.labels.length;
let texts = this.props.labels.map((label, j) => {
let coords = polarToCartesian(this.center, this.center, this.center + (this.props.labelsTextSize*.25 || 12*.25), this.angleStepSize*j + this.angleStepSize/2);
return (<Text
key={j}
fill={this.props.labelsTextColor || 'black'}
strokeWidth={.25}
stroke={complement(this.props.labelsTextColor || 'black')}
font={`${this.props.labelsTextSize || 12}px Arial`}
transform={new Transform().rotate(this.angleStepSize*j + this.angleStepSize/2)}
alignment="center"
x={coords.x}
y={coords.y + PADDING_TOP}>
{label}
</Text>);
});
return texts;
}
render() {
this.coords =
this.props.data.map((d,idx) => {
return this.makeCoords(d.data);
});
let lines = this.coords.map((data, idx) => {
return (
<Path key={idx} stroke={this.props.data[idx].lineColor || 'red'} strokeWidth={this.props.data[idx].lineWidth || 3} strokeDash={this.props.data[idx].strokeDash || []} strokeJoin={this.props.data[idx].lineCap || 'square'} strokeCap={this.props.data[idx].lineCap || 'square'} fill={this.props.data[idx].fill || 'rgba(0,255,0,.2)'} d={this.makeChartPath(data)} />
)
});
let markers = this.coords.map((data, idx) => {
return (
data.map((d,idx2)=> {
return <Path key={idx2} fill={this.props.data[idx].markerColor || 'red'} stroke={this.props.data[idx].markerColor || 'red'} strokeWidth={this.state.clickedChart === idx && this.state.selectedMarker === idx2 ? 8 : 0} d={makeCircle(d.x,d.y,MARKER_RADIUS)} />
})
)
});
return(
<View {...this._responder} ref="chart" style={{overflow: 'visible'}}>
<Svg width={this.size} height={this.size + PADDING_TOP*2} style={{overflow: 'visible'}} >
{this.polarGrid}
{lines}
{markers}
{this.axisLabel}
{this.makeOuterLabel()}
</Svg>
</View>
);
}
}
export default ArtyChartyRadar; |
namespace JustinCredible.TheWeek.Directives {
export class OnLoadDirective implements ng.IDirective {
//#region Injection
public static ID = "onLoad";
public static get $inject(): string[] {
return ["$parse"];
}
constructor(
private $parse: ng.IParseService) {
// Ensure that the link function is bound to this instance so we can
// access instance variables like $parse. AngularJs normally executes
// the link function in the context of the global scope.
this.link = _.bind(this.link, this);
}
//#endregion
public restrict = "A";
public link(scope: ng.IScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes, controller: any, transclude: ng.ITranscludeFunction): void {
// Parse the value of the on-load property; this will be a function
// that the user has set on the element for example: <img on-load="load()"/>
/* tslint:disable:no-string-literal */
var fn = this.$parse(attributes["onLoad"]);
/* tslint:enable:no-string-literal */
// Subscribe to the load event of the image element.
element.on("load", (event) => {
// When the load event occurs, execute the user defined load function.
scope.$apply(() => {
fn(scope, { $event: event });
});
});
}
}
} |
table {
table-layout: fixed;
}
td p {
overflow-wrap: break-word;
}
.header {
position: relative;
box-sizing: border-box;
margin-bottom: 20px;
border-radius: 4px;
border: 1px solid transparent;
border-color: #e7e7e7;
min-height: 50px;
background-image: linear-gradient(to bottom,#fff 0,#f8f8f8 100%);
background-repeat: repeat-x;
background-color: #f8f8f8;
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.15),0 1px 5px rgba(0,0,0,0.075);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.15),0 1px 5px rgba(0,0,0,0.075);
}
.header h3 {
box-sizing: border-box;
margin-top: 0;
margin-bottom: 0;
padding-top: 15px;
padding-bottom: 15px;
line-height: 20px;
font-size: 18px;
font-weight: normal;
color: black;
}
.report-creator {
box-sizing: border-box;
margin-top: 15px;
margin-bottom: 15px;
border: 1px solid #CCCCCC;
padding-top: 10px;
padding-bottom: 10px;
}
.report-creator .col-md-2 {
height: 30px;
}
.report-creator .btn {
width: 100%;
}
.report-creator input {
display: inline-block;
padding-top: 5px;
padding-bottom: 5px;
width: 140px;
line-height: 1.5;
height: 30px;
}
.report-creator select {
display: inline-block;
padding-top: 5px;
padding-bottom: 5px;
line-height: 1.5;
height: 30px;
width: 80px;
}
.row {
padding-top: 5px;
padding-bottom: 5px;
margin: 0;
}
label {
margin-left: 10px;
margin-right: 10px;
margin-top: 0;
margin-bottom: 0;
}
.col-md-12 {
padding-left: 5px;
padding-right: 5px;
}
tbody td:hover {
background-color: #f5f5f5;
}
pre {
background-color: white;
}
.expanded {
background-color: #f5f5f5;
}
.bar rect {
fill: steelblue;
shape-rendering: crispEdges;
}
.bar text {
fill: #fff;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
svg {
height: 200px;
} |
/* lexer_save_lchevr.c :+: :+: :+: */
/* By: gmange <gmange@student.42.fr> +#+ +:+ +#+ */
/* Created: 2014/03/05 15:14:34 by gmange #+# #+# */
#include "tokens.h"
#include "ft_exit.h"
#include "debug.h"
#include "lexer.h"
/*
** could replace token.value = dup("_hardcoded symbol_") with:
** token.value = NULL;
** if (prepare_token(line, len, &token.value) != EXIT_SUCCESS)
** return (NULL);
** > and merge 4/6 files in one...
*/
int lexer_save_lchevr(
const int len,
const char *line,
t_list **lexed,
const int next)
{
t_lexed token;
debug_stdout(__FILE__, __LINE__, __func__, "INIT\n");
(void)len;
(void)line;
(void)next;
token.type = e_tok_lchevr;
if (!(token.value = ft_strdup("<")))
return (EXIT_FAILURE);
if (!((*lexed)->next = ft_lstnew(&token, sizeof(token))))
return (EXIT_FAILURE);
*lexed = (*lexed)->next;
debug_stdout(__FILE__, __LINE__, __func__, "END\n");
return (EXIT_SUCCESS);
} |
#ifndef <API key>
#define <API key>
#define <API key> SYSCLK_SRC_RC2MHZ
#define <API key> SYSCLK_PSADIV_1
#define <API key> SYSCLK_PSBCDIV_1_1
#endif /* <API key> */ |
# <API key>: true
require 'spec_helper'
describe <API key> do
let!(:badge) { build(:badge, link_url: 'http:
subject { validator.validate(badge) }
include_examples 'url validator examples', described_class::DEFAULT_OPTIONS[:schemes]
describe 'validations' do
include_context 'invalid urls'
let(:validator) { described_class.new(attributes: [:link_url]) }
it 'returns error when url is nil' do
expect(validator.validate_each(badge, :link_url, nil)).to be_falsey
expect(badge.errors.first[1]).to eq validator.options.fetch(:message)
end
it 'returns error when url is empty' do
expect(validator.validate_each(badge, :link_url, '')).to be_falsey
expect(badge.errors.first[1]).to eq validator.options.fetch(:message)
end
it 'does not allow urls with CR or LF characters' do
aggregate_failures do
urls_with_CRLF.each do |url|
expect(validator.validate_each(badge, :link_url, url)[0]).to eq 'is blocked: URI is invalid'
end
end
end
it 'provides all arguments to UrlBlock validate' do
expect(Gitlab::UrlBlocker)
.to receive(:validate!)
.with(badge.link_url, described_class::<API key>)
.and_return(true)
subject
expect(badge.errors).to be_empty
end
end
context 'by default' do
let(:validator) { described_class.new(attributes: [:link_url]) }
it 'does not block urls pointing to localhost' do
badge.link_url = 'https://127.0.0.1'
subject
expect(badge.errors).to be_empty
end
it 'does not block urls pointing to the local network' do
badge.link_url = 'https://192.168.1.1'
subject
expect(badge.errors).to be_empty
end
it 'does block nil urls' do
badge.link_url = nil
subject
expect(badge.errors).to be_present
end
it 'does block blank urls' do
badge.link_url = '\n\r \n'
subject
expect(badge.errors).to be_present
end
it 'strips urls' do
badge.link_url = "\n\r\n\nhttps://127.0.0.1\r\n\r\n\n\n\n"
# It's unusual for a validator to modify its arguments. Some extensions,
# such as attr_encrypted, freeze the string to signal that modifications
# will not be persisted, so freeze this string to ensure the scheme is
# compatible with them.
badge.link_url.freeze
subject
expect(badge.errors).to be_empty
expect(badge.link_url).to eq('https://127.0.0.1')
end
it 'allows urls that cannot be resolved' do
stub_env('<API key>', 'false')
badge.link_url = 'http://foobar.x'
subject
expect(badge.errors).to be_empty
end
end
context 'when message is set' do
let(:message) { 'is blocked: test message' }
let(:validator) { described_class.new(attributes: [:link_url], allow_nil: false, message: message) }
it 'does block nil url with provided error message' do
expect(validator.validate_each(badge, :link_url, nil)).to be_falsey
expect(badge.errors.first[1]).to eq message
end
end
context 'when allow_nil is set to true' do
let(:validator) { described_class.new(attributes: [:link_url], allow_nil: true) }
it 'does not block nil urls' do
badge.link_url = nil
subject
expect(badge.errors).to be_empty
end
end
context 'when allow_blank is set to true' do
let(:validator) { described_class.new(attributes: [:link_url], allow_blank: true) }
it 'does not block blank urls' do
badge.link_url = "\n\r \n"
subject
expect(badge.errors).to be_empty
end
end
context 'when allow_localhost is set to false' do
let(:validator) { described_class.new(attributes: [:link_url], allow_localhost: false) }
it 'blocks urls pointing to localhost' do
badge.link_url = 'https://127.0.0.1'
subject
expect(badge.errors).to be_present
end
context 'when <API key> is set to true' do
it 'does not block urls pointing to localhost' do
expect(described_class)
.to receive(:<API key>?)
.and_return(true)
badge.link_url = 'https://127.0.0.1'
subject
expect(badge.errors).to be_empty
end
end
end
context 'when allow_local_network is set to false' do
let(:validator) { described_class.new(attributes: [:link_url], allow_local_network: false) }
it 'blocks urls pointing to the local network' do
badge.link_url = 'https://192.168.1.1'
subject
expect(badge.errors).to be_present
end
context 'when <API key> is set to true' do
it 'does not block urls pointing to local network' do
expect(described_class)
.to receive(:<API key>?)
.and_return(true)
badge.link_url = 'https://192.168.1.1'
subject
expect(badge.errors).to be_empty
end
end
end
context 'when ports is' do
let(:validator) { described_class.new(attributes: [:link_url], ports: ports) }
context 'empty' do
let(:ports) { [] }
it 'does not block any port' do
subject
expect(badge.errors).to be_empty
end
end
context 'set' do
let(:ports) { [443] }
it 'blocks urls with a different port' do
subject
expect(badge.errors).to be_present
end
end
end
context 'when enforce_user is' do
let(:url) { 'http://$user@example.com'}
let(:validator) { described_class.new(attributes: [:link_url], enforce_user: enforce_user) }
context 'true' do
let(:enforce_user) { true }
it 'checks user format' do
badge.link_url = url
subject
expect(badge.errors).to be_present
end
end
context 'false (default)' do
let(:enforce_user) { false }
it 'does not check user format' do
badge.link_url = url
subject
expect(badge.errors).to be_empty
end
end
end
context 'when ascii_only is' do
let(:url) { 'https:
let(:validator) { described_class.new(attributes: [:link_url], ascii_only: ascii_only) }
context 'true' do
let(:ascii_only) { true }
it 'prevents unicode characters' do
badge.link_url = url
subject
expect(badge.errors).to be_present
end
end
context 'false (default)' do
let(:ascii_only) { false }
it 'does not prevent unicode characters' do
badge.link_url = url
subject
expect(badge.errors).to be_empty
end
end
end
context 'when <API key> is' do
let(:validator) { described_class.new(attributes: [:link_url], <API key>: <API key>) }
let(:unsafe_url) { "https://replaceme.com/'><script>alert(document.cookie)</script>" }
let(:safe_url) { 'https://replaceme.com/path/to/somewhere' }
let(:unsafe_internal_url) do
Gitlab.config.gitlab.protocol + '://' + Gitlab.config.gitlab.host +
"/'><script>alert(document.cookie)</script>"
end
context 'true' do
let(:<API key>) { true }
it 'prevents unsafe urls' do
badge.link_url = unsafe_url
subject
expect(badge.errors).to be_present
end
it 'prevents unsafe internal urls' do
badge.link_url = unsafe_internal_url
subject
expect(badge.errors).to be_present
end
it 'allows safe urls' do
badge.link_url = safe_url
subject
expect(badge.errors).to be_empty
end
end
context 'false' do
let(:<API key>) { false }
it 'allows unsafe urls' do
badge.link_url = unsafe_url
subject
expect(badge.errors).to be_empty
end
end
end
context 'when <API key> is' do
let(:not_resolvable_url) { 'http://foobar.x' }
let(:validator) { described_class.new(attributes: [:link_url], <API key>: dns_value) }
before do
stub_env('<API key>', 'false')
badge.link_url = not_resolvable_url
subject
end
context 'true' do
let(:dns_value) { true }
it 'raises error' do
expect(badge.errors).to be_present
end
end
context 'false' do
let(:dns_value) { false }
it 'allows urls that cannot be resolved' do
expect(badge.errors).to be_empty
end
end
end
end |
Era::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.<API key> = "public, max-age=3600"
# Show full error reports and disable caching.
config.<API key> = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.<API key> = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end |
import Toolbar from './toolbar';
export { Toolbar as Toolbar };
export default Toolbar; |
const {resultSet, println, target} = require("rec");
const format = java.lang.String.format;
const handle = net.kimleo.dblite.DB.connect("jdbc:postgresql://localhost/test", "postgres", "").handle();
resultSet(handle.query("select * from simple_sql_test"))
.to(target(function ({id, name}) {
println(format("%s => %s", id, name));
})); |
var glob = require('glob');
var path = require('path');
var fs = require('fs');
var resolve = require('resolve').sync;
var findRoot = require('./find-root');
var extractImports = require('./extract-imports');
module.exports = function (filePath, callback) {
var root = findRoot(filePath);
if (!root) {
callback([]);
}
glob('/!(node_modules)*.js', {root: root}, function (err, files) {
if (err) throw err;
var dependants = [];
files.forEach(function (file) {
var src = fs.readFileSync(file, 'utf8');
try {
var dependencies = extractImports(src);
dependencies.forEach(function (dependency) {
if (dependency[0] === '.') {
var fullPath = resolve(dependency, {basedir: path.dirname(file)});
if (fullPath.toLowerCase() === filePath.toLowerCase()) {
dependants.push(file);
}
}
});
} catch (e) {
console.log('Failed for', file, e);
}
});
callback && callback(dependants);
});
} |
#include "pidMotion.h"
#include <stdbool.h>
#include "../../common/eeprom/eeprom.h"
#include "../../common/error/error.h"
#include "../../robot/kinematics/robotKinematics.h"
#include "../../robot/kinematics/<API key>.h"
#include "pidTimer.h"
#include "parameters/<API key>.h"
#include "<API key>.h"
#include "../../motion/parameters/<API key>.h"
bool <API key>(const PidMotion* pidMotion) {
if (pidMotion == NULL) {
writeError(PID_MOTION_NULL);
return false;
}
return true;
}
bool <API key>(const PidMotion* pidMotion) {
if (!<API key>(pidMotion)) {
return false;
}
return pidMotion->motionLength > 0;
}
void <API key>(PidMotionDefinition* pidMotionDefinition) {
pidMotionDefinition->motionType = <API key>;
pidMotionDefinition->computeU = NULL;
pidMotionDefinition-><API key> = NULL;
pidMotionDefinition->state = <API key>;
}
void clearPidMotion(PidMotion* pidMotion) {
if (!<API key>(pidMotion)) {
return;
}
pidMotion->motionWriteIndex = 0;
pidMotion->motionReadIndex = 0;
unsigned int i;
PidMotionDefinition* pidMotionDefinition = (PidMotionDefinition*) pidMotion->motionDefinitions;
// Reinit all values to make the Debug more easy
for (i = 0; i < pidMotion->motionLength; i++) {
<API key>(pidMotionDefinition);
pidMotionDefinition++;
}
<API key>(&(pidMotion->computationValues));
}
bool isPidMotionFull(const PidMotion* pidMotion) {
if (!<API key>(pidMotion)) {
return false;
}
return ((pidMotion->motionWriteIndex + 1) % pidMotion->motionLength) == pidMotion->motionReadIndex;
}
bool isPidMotionEmpty(const PidMotion* pidMotion) {
if (!<API key>(pidMotion)) {
return true;
}
return pidMotion->motionReadIndex == pidMotion->motionWriteIndex;
}
unsigned int <API key>(const PidMotion* pidMotion) {
if (!<API key>(pidMotion)) {
return 0;
}
int result = pidMotion->motionWriteIndex - pidMotion->motionReadIndex;
if (result < 0) {
result += pidMotion->motionLength;
}
return result;
}
unsigned int <API key>(const PidMotion* pidMotion) {
if (!<API key>(pidMotion)) {
return 0;
}
return pidMotion->motionLength - 1;
}
PidMotionDefinition* <API key>(PidMotion* pidMotion, bool errorIfEndOfList) {
if (!<API key>(pidMotion)) {
return NULL;
}
bool isEmpty = isPidMotionEmpty(pidMotion);
if (!isEmpty) {
PidMotionDefinition* result = (PidMotionDefinition*) pidMotion->motionDefinitions;
// Shift to the right cell index
result += pidMotion->motionReadIndex;
pidMotion->motionReadIndex++;
pidMotion->motionReadIndex %= pidMotion->motionLength;
return result;
} else {
if (errorIfEndOfList) {
// We must log the problem
writeError(PID_MOTION_EMPTY);
}
return NULL;
}
}
PidMotionDefinition* <API key>(PidMotion* pidMotion) {
if (!<API key>(pidMotion)) {
return NULL;
}
// If we stack or if the pidMotion is Empty, we add a new definition !
if (pidMotion-><API key> || isPidMotionEmpty(pidMotion)) {
bool isFull = isPidMotionFull(pidMotion);
if (!isFull) {
PidMotionDefinition* result = (PidMotionDefinition*) pidMotion->motionDefinitions;
// Shift to the right cell index
result += pidMotion->motionWriteIndex;
// For next time
pidMotion->motionWriteIndex++;
pidMotion->motionWriteIndex %= pidMotion->motionLength;
return result;
} else {
// We must log the problem
writeError(PID_MOTION_FULL);
return NULL;
}
}
// We overwrite on the read Index
PidMotionDefinition* result = (PidMotionDefinition*) pidMotion->motionDefinitions;
// Shift to the right cell index
result += pidMotion->motionReadIndex;
// We overwrite the writeIndex to the next one to avoid inconsistency
pidMotion->motionWriteIndex = (pidMotion->motionReadIndex + 1) % pidMotion->motionLength;
return result;
}
PidMotionDefinition* <API key>(PidMotion* pidMotion) {
if (!<API key>(pidMotion)) {
return NULL;
}
unsigned int size = <API key>(pidMotion);
if (size <= 0) {
return NULL;
}
PidMotionDefinition* result = (PidMotionDefinition*) pidMotion->motionDefinitions;
// Shift to the right cell index
result += pidMotion->motionReadIndex;
return result;
}
PidMotionDefinition* getMotionDefinition(PidMotion* pidMotion, unsigned int index) {
unsigned int size = <API key>(pidMotion);
if (index < size) {
PidMotionDefinition* result = (PidMotionDefinition*) pidMotion->motionDefinitions;
// Shift to the right cell index
result += ((pidMotion->motionReadIndex + index) % pidMotion->motionLength);
return result;
} else {
// We must log the problem
writeError(<API key>);
}
return NULL;
}
// STACK / REPLACE MODE
void setMotionModeAdd(PidMotion* pidMotion) {
pidMotion-><API key> = true;
}
void <API key>(PidMotion* pidMotion) {
pidMotion-><API key> = false;
}
bool <API key>(PidMotion* pidMotion) {
return pidMotion-><API key>;
}
// MOTION PARAMETERS
<API key>* <API key>(PidMotion* pidMotion) {
return &(pidMotion->globalParameters.<API key>);
}
// INIT
void initPidMotion(PidMotion* pidMotion,
DualHBridgeMotor* dualHBridgeMotor,
Eeprom* _eeprom,
PidMotionDefinition(*array)[],
unsigned int length) {
if (!<API key>(pidMotion)) {
return;
}
if (_eeprom == NULL) {
writeError(EEPROM_NULL);
return;
}
pidMotion->dualHBridgeMotor = dualHBridgeMotor;
pidMotion->motionDefinitions = array;
pidMotion->motionLength = length;
pidMotion-><API key> = _eeprom;
// We load the values from the eeprom, but we don't load default values unless the eeprom is a memory type
loadPidParameters(pidMotion, _eeprom->eepromType == EEPROM_TYPE_MEMORY);
if (_eeprom->eepromType == EEPROM_TYPE_MEMORY) {
loadPidParameters(pidMotion, true);
// We store to do as it was already previously store !
savePidParameters(pidMotion);
} else {
loadPidParameters(pidMotion, false);
}
// Load the kinematics by calling the singleton
getRobotKinematics();
initPidTimer();
} |
This is a Ruby implementation of Redis for machines without Redis or development/test environments. In short, it emulates a fully functional Redis server, so you don't need to install a truly Redis. It's like a SQLite equivalent for Redis.
## Why use this instead a real Redis?
Try to answer this question: why some developers use SQLite? Why Apple, Google, Microsoft and many others big software companies use SQLite, a weak and fragile database, in their products? Mozilla Firefox, Google Chrome, Apple Safari all theses products use SQLite. Why if there is a myriad of good and free databases? There are some answers for why use SQLite which are valid for redis-file too.
1. your software will store few data. Safari, FF, Chrome uses SQLite to store the user's preferences - why use some Mysql, PostgreSQL to just store a single table with few records? At the same way, why use a full Redis to store few keys?
2. your hosting provider charges you to use Redis and you want to save some money. redis-file is slow, because is written in Ruby (unlike Redis, which is written in C), it loads an entire Rails environment, and use disk. But for a small amount of data and/or a limited budget it can be better than use Redis.
3. you are developing some projects which uses Redis and you don't want the data of one project conflit with other.
These are some appropriate uses for redis-file, but for the most cases (namely for very large datasets) you have to use a true Redis server.
## Installation
Install the gem:
gem install redis-file
Add it to your Gemfile:
gem "redis-file"
## Versions
redis-file follow the same version number of the [fakeredis](https://github.com/guilleiguaran/fakeredis) project. Changes at fakeredis will be adopted by this project.
[ documentation and
[Redis](http://redis.io) homepage for more info about commands
## Usage with RSpec
Require this either in your Gemfile or in RSpec's support scripts. So either:
# Gemfile
group :test do
gem "rspec"
gem "redis-file", :require => "redis-file/rspec"
end
Or:
# spec/support/redis-file.rb
require 'redis-file/rspec'
## Acknowledgements
* [guilleiguaran](https://github.com/guilleiguaran): The creator of Fakeredis, which this project is based on
* [dim](https://github.com/dim)
* [czarneckid](https://github.com/czarneckid)
* [obrie](https://github.com/obrie)
* [jredville](https://github.com/jredville)
* [redsquirrel](https://github.com/redsquirrel)
* [dpick](https://github.com/dpick)
* [caius](https://github.com/caius)
* [Travis-CI](http://travis-ci.org/)
## Contributing to redis-file
* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
* Fork the project
* Start a feature/bugfix branch
* Commit and push until you are happy with your contribution
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
Public Domain - 2013 Daniel Loureiro (heavily based on the work of Guillermo Iguaran). See LICENSE for
further details. |
""" Utilities """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Logging
import logging
import os, os.path
from colorlog import ColoredFormatter
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = ColoredFormatter(
"%(log_color)s[%(asctime)s] %(message)s",
# datefmt='%H:%M:%S.%f',
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'white,bold',
'INFOV': 'cyan,bold',
'WARNING': 'yellow',
'ERROR': 'red,bold',
'CRITICAL': 'red,bg_white',
},
<API key>={},
style='%'
)
ch.setFormatter(formatter)
log = logging.getLogger('AVH')
log.setLevel(logging.DEBUG)
log.handlers = [] # No duplicated handlers
log.propagate = False # workaround for duplicated logs in ipython
log.addHandler(ch)
logging.addLevelName(logging.INFO + 1, 'INFOV')
def _infov(self, msg, *args, **kwargs):
self.log(logging.INFO + 1, msg, *args, **kwargs)
logging.Logger.infov = _infov |
#ifndef _DIFONT_FONT_H_
#define _DIFONT_FONT_H_
#include <difont/difont.h>
/**
* Font is the public interface for the FTGL library.
*
* Specific font classes are derived from this class. It uses the helper
* classes Face and difont::Size to access the Freetype library. This class
* is abstract and deriving classes must implement the protected
* <code>MakeGlyph</code> function to create glyphs of the
* appropriate type.
*
* It is good practice after using these functions to test the error
* code returned. <code>FT_Error Error()</code>. Check the freetype file
* fterrdef.h for error definitions.
*
* @see Face
* @see difont::Size
*/
namespace difont {
class FontImpl;
class Font {
protected:
/**
* Open and read a font file. Sets Error flag.
*
* @param fontFilePath font file path.
*/
Font(char const *fontFilePath);
/**
* Open and read a font from a buffer in memory. Sets Error flag.
* The buffer is owned by the client and is NOT copied by FTGL. The
* pointer must be valid while using FTGL.
*
* @param pBufferBytes the in-memory buffer
* @param bufferSizeInBytes the length of the buffer in bytes
*/
Font(const unsigned char *pBufferBytes, size_t bufferSizeInBytes);
private:
/* Allow our internal subclasses to access the private constructor */
friend class BitmapFont;
friend class BufferFont;
friend class ExtrudeFont;
friend class OutlineFont;
friend class PixmapFont;
friend class PolygonFont;
friend class TextureFont;
/**
* Internal FTGL Font constructor. For private use only.
*
* @param pImpl Internal implementation object. Will be destroyed
* upon Font deletion.
*/
Font(FontImpl *pImpl);
public:
virtual ~Font();
/**
* Attach auxilliary file to font e.g font metrics.
*
* Note: not all font formats implement this function.
*
* @param fontFilePath auxilliary font file path.
* @return <code>true</code> if file has been attached
* successfully.
*/
virtual bool Attach(const char* fontFilePath);
/**
* Attach auxilliary data to font e.g font metrics, from memory.
*
* Note: not all font formats implement this function.
*
* @param pBufferBytes the in-memory buffer.
* @param bufferSizeInBytes the length of the buffer in bytes.
* @return <code>true</code> if file has been attached
* successfully.
*/
virtual bool Attach(const unsigned char *pBufferBytes,
size_t bufferSizeInBytes);
/**
* Set the glyph loading flags. By default, fonts use the most
* sensible flags when loading a font's glyph using FT_Load_Glyph().
* This function allows to override the default flags.
*
* @param flags The glyph loading flags.
*/
virtual void GlyphLoadFlags(FT_Int flags);
/**
* Set the character map for the face.
*
* @param encoding Freetype enumerate for char map code.
* @return <code>true</code> if charmap was valid and
* set correctly.
*/
virtual bool CharMap(FT_Encoding encoding);
/**
* Get the number of character maps in this face.
*
* @return character map count.
*/
virtual unsigned int CharMapCount() const;
/**
* Get a list of character maps in this face.
*
* @return pointer to the first encoding.
*/
virtual FT_Encoding* CharMapList();
/**
* Set the char size for the current face.
*
* @param size the face size in points (1/72 inch)
* @param res the resolution of the target device.
* @return <code>true</code> if size was set correctly
*/
virtual bool FaceSize(const unsigned int size,
const unsigned int res = 72);
/**
* Get the current face size in points (1/72 inch).
*
* @return face size
*/
virtual unsigned int FaceSize() const;
/**
* Set the extrusion distance for the font. Only implemented by
* ExtrudeFont
*
* @param depth The extrusion distance.
*/
virtual void Depth(float depth);
/**
* Set the outset distance for the font. Only implemented by
* OutlineFont, PolygonFont and ExtrudeFont
*
* @param outset The outset distance.
*/
virtual void Outset(float outset);
/**
* Set the front and back outset distances for the font. Only
* implemented by ExtrudeFont
*
* @param front The front outset distance.
* @param back The back outset distance.
*/
virtual void Outset(float front, float back);
/**
* Enable or disable the use of Display Lists inside FTGL
*
* @param useList <code>true</code> turns ON display lists.
* <code>false</code> turns OFF display lists.
*/
virtual void UseDisplayList(bool useList);
/**
* Get the global ascender height for the face.
*
* @return Ascender height
*/
virtual float Ascender() const;
/**
* Gets the global descender height for the face.
*
* @return Descender height
*/
virtual float Descender() const;
/**
* Gets the line spacing for the font.
*
* @return Line height
*/
virtual float LineHeight() const;
/**
* Get the bounding box for a string.
*
* @param string A char buffer.
* @param len The length of the string. If < 0 then all characters
* will be checked until a null character is encountered
* (optional).
* @param position The pen position of the first character (optional).
* @param spacing A displacement vector to add after each character
* has been checked (optional).
* @return The corresponding bounding box.
*/
virtual difont::BBox BBox(const char *string, const int len = -1,
difont::Point position = difont::Point(),
difont::Point spacing = difont::Point());
/**
* Get the bounding box for a string (deprecated).
*
* @param string A char buffer.
* @param llx Lower left near x coordinate.
* @param lly Lower left near y coordinate.
* @param llz Lower left near z coordinate.
* @param urx Upper right far x coordinate.
* @param ury Upper right far y coordinate.
* @param urz Upper right far z coordinate.
*/
void BBox(const char* string, float& llx, float& lly, float& llz,
float& urx, float& ury, float& urz)
{
difont::BBox b = BBox(string);
llx = b.Lower().Xf(); lly = b.Lower().Yf(); llz = b.Lower().Zf();
urx = b.Upper().Xf(); ury = b.Upper().Yf(); urz = b.Upper().Zf();
}
/**
* Get the bounding box for a string.
*
* @param string A wchar_t buffer.
* @param len The length of the string. If < 0 then all characters
* will be checked until a null character is encountered
* (optional).
* @param position The pen position of the first character (optional).
* @param spacing A displacement vector to add after each character
* has been checked (optional).
* @return The corresponding bounding box.
*/
virtual difont::BBox BBox(const wchar_t *string, const int len = -1,
difont::Point position = difont::Point(),
difont::Point spacing = difont::Point());
/**
* Get the bounding box for a string (deprecated).
*
* @param string A wchar_t buffer.
* @param llx Lower left near x coordinate.
* @param lly Lower left near y coordinate.
* @param llz Lower left near z coordinate.
* @param urx Upper right far x coordinate.
* @param ury Upper right far y coordinate.
* @param urz Upper right far z coordinate.
*/
void BBox(const wchar_t* string, float& llx, float& lly, float& llz,
float& urx, float& ury, float& urz)
{
difont::BBox b = BBox(string);
llx = b.Lower().Xf(); lly = b.Lower().Yf(); llz = b.Lower().Zf();
urx = b.Upper().Xf(); ury = b.Upper().Yf(); urz = b.Upper().Zf();
}
/**
* Get the advance for a string.
*
* @param string 'C' style string to be checked.
* @param len The length of the string. If < 0 then all characters
* will be checked until a null character is encountered
* (optional).
* @param spacing A displacement vector to add after each character
* has been checked (optional).
* @return The string's advance width.
*/
virtual float Advance(const char* string, const int len = -1,
difont::Point spacing = difont::Point());
/**
* Get the advance for a string.
*
* @param string A wchar_t string
* @param len The length of the string. If < 0 then all characters
* will be checked until a null character is encountered
* (optional).
* @param spacing A displacement vector to add after each character
* has been checked (optional).
* @return The string's advance width.
*/
virtual float Advance(const wchar_t* string, const int len = -1,
difont::Point spacing = difont::Point());
/**
* Render a string of characters.
*
* @param string 'C' style string to be output.
* @param len The length of the string. If < 0 then all characters
* will be displayed until a null character is encountered
* (optional).
* @param position The pen position of the first character (optional).
* @param spacing A displacement vector to add after each character
* has been displayed (optional).
* @param renderMode Render mode to use for display (optional).
* @return The new pen position after the last character was output.
*/
virtual difont::Point Render(const char* string, const int len = -1,
difont::Point position = difont::Point(),
difont::Point spacing = difont::Point(),
int renderMode = difont::RENDER_ALL);
/**
* Render a string of characters
*
* @param string wchar_t string to be output.
* @param len The length of the string. If < 0 then all characters
* will be displayed until a null character is encountered
* (optional).
* @param position The pen position of the first character (optional).
* @param spacing A displacement vector to add after each character
* has been displayed (optional).
* @param renderMode Render mode to use for display (optional).
* @return The new pen position after the last character was output.
*/
virtual difont::Point Render(const wchar_t *string, const int len = -1,
difont::Point position = difont::Point(),
difont::Point spacing = difont::Point(),
int renderMode = difont::RENDER_ALL);
virtual void PreRender();
virtual void PostRender();
/**
* Queries the Font for errors.
*
* @return The current error code.
*/
virtual FT_Error Error() const;
protected:
/* Allow impl to access MakeGlyph */
friend class FontImpl;
virtual Glyph* MakeGlyph(FT_GlyphSlot slot) = 0;
private:
/**
* Internal FTGL Font implementation object. For private use only.
*/
FontImpl *impl;
};
}
#endif // __Font__ |
<?php
abstract class <API key> extends <API key>
{
public function setup()
{
$this->setWidgets(array(
'cliente' => new <API key>(array('with_empty' => false)),
'situacion' => new <API key>(array('with_empty' => false)),
'observacion' => new <API key>(array('with_empty' => false)),
'fecha' => new <API key>(array('from_date' => new sfWidgetFormDate(array('format' => 'd/m/Y')), 'to_date' => new sfWidgetFormDate(), 'with_empty' => false)),
'factura' => new <API key>(array('with_empty' => false)),
'articulo' => new <API key>(array('with_empty' => false)),
'estado' => new <API key>(array('with_empty' => false)),
));
$this->setValidators(array(
'cliente' => new sfValidatorPass(array('required' => false)),
'situacion' => new sfValidatorPass(array('required' => false)),
'observacion' => new sfValidatorPass(array('required' => false)),
'fecha' => new <API key>(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))),
'factura' => new <API key>('text', new sfValidatorInteger(array('required' => false))),
'articulo' => new sfValidatorPass(array('required' => false)),
'estado' => new sfValidatorPass(array('required' => false)),
));
$this->widgetSchema->setNameFormat('servicios_filters[%s]');
$this->errorSchema = new <API key>($this->validatorSchema);
$this->setupInheritance();
parent::setup();
}
public function getModelName()
{
return 'Servicios';
}
public function getFields()
{
return array(
'cliente' => 'Text',
'situacion' => 'Text',
'observacion' => 'Text',
'fecha' => 'Date',
'id' => 'Number',
'factura' => 'Number',
'articulo' => 'Text',
'estado' => 'Text',
);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Better Files</title>
<script language="JavaScript">
function doRedirect() {
window.location.replace("latest/api/better/files/File.html");
}
doRedirect();
</script>
</head>
<body>
<a href="latest/api/better/files/File.html">ScalaDoc</a>
</body>
</html> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.