code
stringlengths
4
1.01M
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>unimath-substitution-systems: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.0 / unimath-substitution-systems - 0.1.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> unimath-substitution-systems <small> 0.1.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-11 02:59:41 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-11 02:59:41 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.13.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.13.1 Official release 4.13.1 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;opam@clarus.me&quot; homepage: &quot;https://github.com/UniMath/UniMath&quot; dev-repo: &quot;git+https://github.com/UniMath/UniMath.git&quot; bug-reports: &quot;https://github.com/UniMath/UniMath/issues&quot; license: &quot;Kind of MIT&quot; authors: [&quot;The UniMath Development Team&quot;] build: [ [&quot;coq_makefile&quot; &quot;-f&quot; &quot;Make&quot; &quot;-o&quot; &quot;Makefile&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5.0&quot; &amp; &lt; &quot;8.6&quot;} &quot;coq-unimath-category-theory&quot; &quot;coq-unimath-foundations&quot; ] synopsis: &quot;Aims to formalize a substantial body of mathematics using the univalent point of view&quot; extra-files: [&quot;Make&quot; &quot;md5=8606de3f7fc761f04872219361ba9c7d&quot;] url { src: &quot;https://github.com/UniMath/UniMath/archive/v0.1.tar.gz&quot; checksum: &quot;md5=1ed57c1028e227a309f428a6dc5f0866&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-unimath-substitution-systems.0.1.0 coq.8.13.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0). The following dependencies couldn&#39;t be met: - coq-unimath-substitution-systems -&gt; coq &lt; 8.6 -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-unimath-substitution-systems.0.1.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
package me.lachlanap.dropunit.world /** * An action to perform on the world, an area, a block, or an entity. */ trait Transform { def applyTo(world: World): World = world } case class SpawnEntity(entity: (Id) => Entity) extends Transform { override def applyTo(world: World): World = { new World(world.config, world.blueprints, world.leftPlayer, world.rightPlayer, entity(world.entityIdGenerator.next()) :: world.entities) } } case class DestroyEntity(entity: Entity) extends Transform { override def applyTo(world: World): World = { new World(world.config, world.blueprints, world.leftPlayer, world.rightPlayer, world.entities.filterNot(_.id == entity.id)) } } case class DamageBlock(block: Block, amount: Double) extends Transform { override def applyTo(world: World): World = { new World(world.config, world.blueprints, world.leftPlayer.damage(block, amount), world.rightPlayer.damage(block, amount), world.entities) } }
<html> <head> <title>基础搜索学习</title> <link rel="stylesheet" type="text/css" href="./prism.css"> <link rel="stylesheet" type="text/css" href="./button.css"> <meta charset="utf-8" /> <style> body { font-size: 20px; } .wall, .blink, .visited, .road, .tmp { width: 20px; height: 20px; overflow: hidden; } .wall { background: rgb(95, 99, 119); box-shadow: 2px 2px 3px #aaa; } tr:nth-child(odd) td:nth-child(odd) .wall { background: rgb(72, 89, 105) } #mazeBody { border-collapse: separate; font-size: 12px; margin:auto; } .test_box { min-width: 400px; height: 740px; display: flex; } pre { word-wrap: normal; height: 700px; width: 600px; border: 1px solid black; padding: 5px; overflow: auto; display: block; } #result { flex: 1; height: 100%; border: solid 1px #bbbbbb; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ } .blink { animation-iteration-count: 1; animation: blink 1s linear; } .visited { background: #fffd93; } @-webkit-keyframes blink { 0% { background: #f35626; } 50% { background: #feab3a; } 100% { background: #fffd93; } } div .highlight{ animation-iteration-count: 1; animation: highlight 2s linear; background: #44f6fc; } @-webkit-keyframes highlight { 0% { background: #fffd93; } 50% { background: #1ff8ff; } 100% { background: #44f6fc; } } </style> </head> <body> <div class="test_box line-numbers"> <div id="code"> <pre id="pre" contenteditable class="language-js"> </pre> </div> <div id="result"> <table id="mazeBody"> </table> </div> </div> <div class="settings"> <br/> 迷宫长:<input type="number" min = '5' max = '31' value='13' id='X' onchange="init()"> 迷宫宽:<input type="number" min = '5' max = '31' value='13' id='Y' onchange="init()"> 动画间隔: <input type="number" min = '10' max = '1000' value='50' id='speed'> <br/> <div class="button button-green" onClick="runCode()">运行</div> <div class="button button-blue" onclick="init()">重新生成</div> <div class="button button-red"onclick="reset()">清除路线</div> <div class="button" onclick="addDFSCode()">深搜框架</div> <div class="button" onclick="addBFSCode()">广搜框架</div> <div class="button" onclick="addDFSCode2()">深搜带路径显示</div> <div> 标记自己来到的坐标: visit(x,y);</br> 高亮搜索结果: highlight([{x,y},{x2,y2},...]);</br> 创建一个队列:var queue = new Queue();</br> queue可用方法:isEmpty dequeue enqueue(T)</br> </div> </div> </body> <script> var time = 0; var timer = []; init(); function dfs(x, y, wall) { let pos = [{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 0, y: -1 }]; if (x < 0 || x > X || y < 0 || y > Y) { return; } var now = getP(x, y); if (!now || now.className === 'road') { return; } wall.className = now.className = 'road'; shuffleArray(pos); pos.forEach(p => { dfs(x + p.x * 2, y + p.y * 2, getP(x + p.x, y + p.y)); }); } function id(x, y) { return x + '_' + y; } function getP(x, y) { return document.getElementById(id(x, y)); } function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } function getType(x, y) { let el = getP(x,y); if(el)return getP(x, y).className; return 'null'; } function setType(x, y, type) { if(getP(x,y)) getP(x, y).className = type; } function visit(x, y) { getP(x, y).className = 'tmp'; time += parseInt(document.getElementById('speed').value); timer.push(setTimeout(() => { if(getType(x, y) !== 'hightlight') setType(x, y, 'blink'); }, time)); timer.push(setTimeout(() => { if(getType(x, y)!== 'hightlight') setType(x, y, 'visited'); } , time + 1000)); } function init() { let X = document.getElementById('X').value; let Y = document.getElementById('Y').value; X = Math.min(31 ,Math.max(X, 5)); Y = Math.min(31 ,Math.max(Y, 5)); if(X%2 == 0)X++; if(Y%2 == 0)Y++; reset(); var table = document.getElementById('mazeBody'); table.innerHTML = ''; for (var i = 0; i < X; i++) { var tr = document.createElement("tr"); for (var j = 0; j < Y; j++) { var td = document.createElement("td"); var btn = document.createElement("div"); btn.setAttribute('id', id(i, j)); btn.setAttribute('class', 'wall'); td.appendChild(btn); tr.appendChild(td); } table.appendChild(tr); } dfs(1, 1, getP(1, 1)) start = getP(1, 0); start.className = 'start'; start.innerHTML = '🙄'; end = getP(X - 2, Y - 1); end.className = 'end'; end.innerHTML = '⛳'; } function reset() { timer.forEach(t => { clearInterval(t); }); for (var i = 0; i < 31; i++) { for (var j = 0; j < 31; j++) { if (['wall', 'start', 'end'].indexOf(getType(i, j)) == -1) { setType(i, j, 'road'); } } } time = 0; timer = []; } function keyDown(el,keyCode){ event.initKeyboardEvent("keydown",true,true,document.defaultView,"a",0,keyCode,0); el.dispatchEvent(event); } function addDFSCode() { code = document.getElementById('pre'); code.innerHTML = '\ dfs(1,1);\n\ function dfs(x,y){\n\ if(getType(x,y)!==\'road\'){\n\ return;\n\ }\n\ visit(x,y);\n\ dfs(x-1,y);\n\ dfs(x+1,y);\n\ dfs(x,y-1);\n\ dfs(x,y+1);\n\ }'; bililiteRange.fancyText(ret._el, Prism.highlightElement); } function addBFSCode() { code = document.getElementById('pre'); code.innerHTML = '\ bfs(1,1);\n\ function bfs(x,y){\n\ var queue = new Queue();\n\ queue.enqueue({x:1,y:1});\n\ while(!queue.isEmpty()){\n\ var t = queue.dequeue();\n\ if(getType(t.x,t.y)!==\'road\'){\n\ continue;\n\ }\n\ visit(t.x,t.y);\n\ queue.enqueue({x:(t.x)-1,y:t.y});\n\ queue.enqueue({x:t.x+1,y:t.y});\n\ queue.enqueue({x:t.x,y:t.y-1});\n\ queue.enqueue({x:t.x,y:t.y+1});\n\ }\n\ }'; bililiteRange.fancyText(ret._el, Prism.highlightElement); } function addDFSCode2() { code = document.getElementById('pre'); code.innerHTML = '\ let path = [];\n\ let stop = false;\n\ dfs(1,1,path);\n\ function dfs(x,y,path){\n\ if(getType(x,y)===\'end\'){\n\ highlight(path);\n\ stop = true;\n\ }\n\ if(stop || getType(x,y)!==\'road\'){\n\ return;\n\ }\n\ path.push({x,y});\n\ visit(x,y);\n\ dfs(x-1,y,path);\n\ dfs(x+1,y,path);\n\ dfs(x,y-1,path);\n\ dfs(x,y+1,path);\n\ if(!stop)path.pop();\n\ }'; bililiteRange.fancyText(ret._el, Prism.highlightElement); } function runCode() { reset(); var code = document.querySelector('pre').innerText; console.log(code); eval(code); } // highlight some blocks, it only can use once when the algorithm finished because i havn't fix it. function highlight(pos) { //remove all highLight before next highlight for (var i = 0; i < 31; i++) { for (var j = 0; j < 31; j++) { if (getType(i, j) === 'visited highlight') { setType(i, j, 'visited'); } if (getType(i, j) === 'blink highlight') { setType(i, j, 'visited'); } if (getType(i, j) === 'road highlight') { setType(i, j, 'road'); } } } timer.push(setTimeout( ()=> { pos.forEach( p => { setType(p.x, p.y, getType(p.x, p.y) +' highlight'); }) }, time+1200)); } </script> <script src="./prism.js" data-manual=""></script> <script src="./Prism Editor_files/prism.linenumber.js"></script> <script src="./Prism Editor_files/bililiteRange.js"></script> <script src="./Prism Editor_files/bililiteRange.undo.js"></script> <script src="./Prism Editor_files/bililiteRange.util.js"></script> <script src="./Prism Editor_files/bililiteRange.fancytext.js"></script> <script src="./Queue.js"></script> <script> var editor = document.querySelector('pre'); const ret = bililiteRange(editor) bililiteRange.fancyText(ret._el, Prism.highlightElement); // add the undo's ret.undo(0).data().autoindent = true; // init ret._el.addEventListener('keydown', function (evt) { // control z if (evt.ctrlKey && evt.which == 90) bililiteRange.undo(evt); // control y if (evt.ctrlKey && evt.which == 89) bililiteRange.redo(evt); // tab if (evt.which == 9) { ret.sendkeys('{tab}'); var b = ret.bounds(); ret.bounds([b[0],b[1]]).select(); evt.returnValue = false; } }); </script> </html>
<html> <head></head> <body> <center> <a href="{{next_page}}"> <img src="{{ prototypes_asset_path }}images/email.png"> </a> </center> </body> </html>
import { Inject, Injectable } from '@angular/core'; import { CanActivate, Router } from "@angular/router"; import { AuthService } from "../services/auth.service"; @Injectable() export class AuthGuard implements CanActivate { constructor(private _auth: AuthService, private _router: Router) { } canActivate(): boolean { if (!this._auth.isLoggedIn()) { this._router.navigate(['/login']); return false; } return true; } }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | https://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'pages'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE; $route['materials/(:num)'] = 'materials/show/$1'; $route['sections/show'] = 'pages/show/index'; $route['materials/show'] = 'pages/show/index'; $route['pages/show'] = "pages/show/index"; $route['pages/contact'] = 'pages/show/contact'; $route['sections/articles'] = 'sections/show/articles'; $route['sections/html'] = 'sections/show/html'; $route['sections/php'] = 'sections/show/php'; $route['sections/css'] = 'sections/show/css';
<!DOCTYPE html style="height:100%"> <!--[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,chrome=1"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=100, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, minimal-ui"> <meta name="mobile-web-app-capable" content="yes"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="icon" href="favicon.ico" type="image/x-icon"/> <link href='http://fonts.googleapis.com/css?family=Permanent+Marker' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/jquery-1.10.2.min.js"></script> <script src="js/vendor/modernizr-2.6.2.min.js"></script> <script type="text/javascript" src="js/greensock/TweenMax.js"></script> <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script> <script type="text/javascript" src="js/createjs/easeljs-0.7.0.min.js"></script> <script type="text/javascript" src="js/createjs/preloadjs-0.4.0.min.js"></script> <script type="text/javascript" src="js/createjs/soundjs-0.5.0.min.js"></script> <script src="js/ads.js"></script> <script src="js/riff.js"></script> <script src="js/gamePlay.js"></script> <script src="js/AudioPunk.js"></script> <script src="js/loaderAudio.js"></script> <script src="js/assets.js"></script> <script src="js/Utils.js"></script> <script src="js/Pulso.js"></script> <script src="js/touchEvents.js"></script> <script src="js/main.js"></script> <script src="js/menu.js"></script> <script src="js/loader.js"></script> <script type="text/javascript"> function init2() { Loader.initLoad(); } </script> </head> <body onload="javascript:init2();"> <script type="text/javascript"> document.write('<div class="canvasHolder"><canvas id="mainCanvas" width="100px" height="100px"></canvas></div>'); </script> <script language="javascript" type="text/javascript"> var _sa = _sa || []; _sa.push(['initialize', 'e159be60-c55a-449e-9293-2aecca195237']); _sa.push(['displayAd']); </script> </body> </html>
(window.webpackJsonp=window.webpackJsonp||[]).push([[88],{499:function(t,e,s){"use strict";s.r(e);var a=s(0),n=Object(a.a)({},(function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h2",{attrs:{id:"examples"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#examples"}},[t._v("#")]),t._v(" Examples")]),t._v(" "),s("p",[t._v("Spreadsheets: Edit a cell in the sheet")]),t._v(" "),s("h2",{attrs:{id:"solutions"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#solutions"}},[t._v("#")]),t._v(" Solutions")]),t._v(" "),s("p",[s("strong",[t._v("Data Curator")]),s("br"),t._v("\nEdit CSV and XLS files without unintentionally changing the raw data. Also, automatically detects the schema for every file.")]),t._v(" "),s("p",[s("strong",[t._v("Delimiter")]),s("br"),t._v("\nEdit and sync CSV files with GitHub directly in the browser.")])])}),[],!1,null,null,null);e.default=n.exports}}]);
<?php namespace Artesaos\Defender\Testing; use Illuminate\View\View; /** * Class JavascriptTest. */ class JavascriptTest extends AbstractTestCase { /** * Array of service providers. * @var array */ protected $providers = ['Artesaos\Defender\Providers\DefenderServiceProvider']; /** * New defender instance. * @var Defender */ protected $defender; /** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->migrate([ $this->stubsPath('database/migrations'), $this->resourcePath('migrations'), ]); $this->seed([ 'UserTableSeeder', ]); $this->app->singleton('Illuminate\Contracts\Debug\ExceptionHandler', 'Orchestra\Testbench\Exceptions\Handler'); $this->defender = new Defender($this->app, $this->app['defender.permission']); $this->defender->setUser(User::first()); } /** * Asserting rended blade view. */ public function testShouldRenderJavascript() { $javascript = $this->defender->javascript(); /* @var View $script */ $view = $javascript->render(); $viewContent = $view->render(); $data = $view->getData(); $this->assertArrayHasKey('permissions', $data); $this->assertTrue(is_string($data['permissions'])); /* * Not empty string, it could be a empty json array string */ $this->assertNotEmpty($data['permissions']); $this->assertJson($data['permissions']); $this->assertStringMatchesFormatFile( $this->stubsPath('views/javascript.blade.output.txt'), $viewContent ); } /** * Asserting created permission and rendered properly. */ public function testShouldRenderUserPermissions() { $user = $this->defender->getUser(); $permission = $this->defender->createPermission('js.permission'); $user->attachPermission($permission); /** @var View $view */ $view = $this->defender->javascript()->render(); $data = $view->getData(); $this->assertArrayHasKey('permissions', $data); $this->assertFalse('[]' == $data['permissions']); $this->assertStringMatchesFormatFile( $this->stubsPath('views/javascript-with-permission.blade.output.txt'), $view->render() ); } }
'use strict'; const async = require('async'); const getApp = require('../utils/utils.js').getApp; module.exports = function(Worker) { //Worker.validatesPresenceOf('title'); Worker.upsertItem = (data, cb) => { let res = {}; getApp(Worker) .then((app) => { if (!!!data.person) cb({errCode: 'ERR_WORKER_NO_PERSON'}); if (!!!data.cargos || data.cargos.length === 0 ) cb({errCode: 'ERR_WORKER_NO_CARGO'}); console.log(data); return (!!!data.person.id ? app.models.person.create(data.person) : Promise.resolve(data.person) ) .then((result) => { res.person = result; return app.models.worker.upsert({ personId: res.person.id }); }) .then(results => { res.worker = results; res.cargoMapping = []; return new Promise((resolve, reject) => async.each(data.cargos, (cargoId, cbInner) => app.models.cargoMapping.create({ cargoId: cargoId, workerId: res.worker.id }) .then(r => cbInner(null, res.cargoMapping.push(r))) .catch(err => async.each(res.cargoMapping, (itemInner, cbInner2) => cbInner2(null, itemInner.destroy()), err => cbInner({ errCode: 'ERR_WORKER_FAIL_CARGOS', message: 'problem to save cargo in worker' }) )), err => !!err ? reject(err) : resolve(res) )); }) .then(res => { cb(null, res); }) .catch(err => { if (!!res.person) res.person.destroy(); if (!!res.worker) res.worker.destroy(); cb({errCode: 'ERR_WORKER_NO_SAVE'}); }); }); }; Worker.remoteMethod('upsertItem', { description: 'upsert client ', http: {verb: 'post'}, accepts: { arg: 'data', type: 'object', description: 'data from form to upsert client', http: {source: 'body'}, required: true }, returns: { arg: 'res', type: 'object', root: true } }); };
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("pract-1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("pract-1")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4d7f27a2-b9f4-457c-9ed3-4b248b1d57a3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" /> <title>תהילים 28 (WLC)</title> <link href="../../../build/mobile.css" rel="stylesheet" /> <script src="../../../build/mobile.js"></script> </head> <body dir="rtl" class="section-document"> <div class="header"><div class="nav"> <a class="name" href="PS.html">Westminster Leningrad Codex</a><a class="location" href="PS.html">תהילים 28</a><a class="prev" href="PS27.html">&lt;</a> <a class="home" href="index.html">=</a> <a class="next" href="PS29.html">&gt;</a> </div></div> <div class="section chapter PS PS28 heb_wlc heb " dir="rtl" lang="he" data-id="PS28" data-nextid="PS29" data-previd="PS27"> <div class="c">28</div> <div class="p"> <span class="v-num v-1">1</span><span class="v PS28_1" data-id="PS28_1"> <l s="H1732">לְדָוִ֡ד</l> <l s="H413">אֵ֘לֶ֤יךָ</l> <l s="H3068">יְהוָ֨ה</l> ׀ <l s="H7121">אֶקְרָ֗א</l> <l s="H6697">צוּרִי֮</l> <l s="H408">אַֽל</l>־<l s="H2790">תֶּחֱרַ֪שׁ</l> <l s="H4480">מִ֫מֶּ֥נִּי</l> <l s="H6435">פֶּן</l>־<l s="H2814">תֶּֽחֱשֶׁ֥ה</l> <l s="H4480">מִמֶּ֑נִּי</l> <l s="H4911">וְ֝נִמְשַׁ֗לְתִּי</l> <l s="H5973">עִם</l>־<l s="H3381">י֥וֹרְדֵי</l> <l s="H953">בֽוֹר</l>׃ </span> <span class="v-num v-2">2</span><span class="v PS28_2" data-id="PS28_2"> <l s="H8085">שְׁמַ֤ע</l> <l s="H6963">ק֣וֹל</l> <l s="H8469">תַּ֭חֲנוּנַי</l> <l s="H7768">בְּשַׁוְּעִ֣י</l> <l s="H413">אֵלֶ֑יךָ</l> <l s="H5375">בְּנָשְׂאִ֥י</l> <l s="H3027">יָ֝דַ֗י</l> <l s="H413">אֶל</l>־<l s="H1687">דְּבִ֥יר</l> <l s="H6944">קָדְשֶֽׁךָ</l>׃ </span> <span class="v-num v-3">3</span><span class="v PS28_3" data-id="PS28_3"> <l s="H408">אַל</l>־<l s="H4900">תִּמְשְׁכֵ֣נִי</l> <l s="H5973">עִם</l>־<l s="H7563">רְשָׁעִים֮</l> <l s="H5973">וְעִם</l>־<l s="H6466">פֹּ֪עֲלֵ֫י</l> <l s="H205">אָ֥וֶן</l> <l s="H1696">דֹּבְרֵ֣י</l> <l s="H7965">שָׁ֭לוֹם</l> <l s="H5973">עִם</l>־<l s="H7453">רֵֽעֵיהֶ֑ם</l> <l s="H7451">וְ֝רָעָ֗ה</l> <l s="H3824">בִּלְבָבָֽם</l>׃ </span> <span class="v-num v-4">4</span><span class="v PS28_4" data-id="PS28_4"> <l s="H5414">תֶּן</l>־<l s="H1992">לָהֶ֣ם</l> <l s="H6467">כְּפָעֳלָם֮</l> <l s="H7455">וּכְרֹ֪עַ</l> <l s="H4611">מַֽעַלְלֵ֫יהֶ֥ם</l> <l s="H4639">כְּמַעֲשֵׂ֣ה</l> <l s="H3027">יְ֭דֵיהֶם</l> <l s="H5414">תֵּ֣ן</l> <l s="H1992">לָהֶ֑ם</l> <l s="H7725">הָשֵׁ֖ב</l> <l s="H1576">גְּמוּלָ֣ם</l> <l s="H1992">לָהֶֽם</l>׃ </span> <span class="v-num v-5">5</span><span class="v PS28_5" data-id="PS28_5"> <l s="H3588">כִּ֤י</l> <l s="H3808">לֹ֤א</l> <l s="H995">יָבִ֡ינוּ</l> <l s="H413">אֶל</l>־<l s="H6468">פְּעֻלֹּ֣ת</l> <l s="H3068">יְ֭הוָה</l> <l s="H413">וְאֶל</l>־<l s="H4639">מַעֲשֵׂ֣ה</l> <l s="H3027">יָדָ֑יו</l> <l s="H2040">יֶ֝הֶרְסֵ֗ם</l> <l s="H3808">וְלֹ֣א</l> <l s="H1129">יִבְנֵֽם</l>׃ </span> <span class="v-num v-6">6</span><span class="v PS28_6" data-id="PS28_6"> <l s="H1288">בָּר֥וּךְ</l> <l s="H3068">יְהוָ֑ה</l> <l s="H3588">כִּי</l>־<l s="H8085">שָׁ֝מַע</l> <l s="H6963">ק֣וֹל</l> <l s="H8469">תַּחֲנוּנָֽי</l>׃ </span> <span class="v-num v-7">7</span><span class="v PS28_7" data-id="PS28_7"> <l s="H3068">יְהוָ֤ה</l> ׀ <l s="H5797">עֻזִּ֥י</l> <l s="H4043">וּמָגִנִּי֮</l> <l s="H">בּ֤וֹ</l> <l s="H982">בָטַ֥ח</l> <l s="H3820">לִבִּ֗י</l> <l s="H5826">וְֽנֶ֫עֱזָ֥רְתִּי</l> <l s="H5937">וַיַּעֲלֹ֥ז</l> <l s="H3820">לִבִּ֑י</l> <l s="H7892">וּֽמִשִּׁירִ֥י</l> <l s="H3034">אֲהוֹדֶֽנּוּ</l>׃ </span> <span class="v-num v-8">8</span><span class="v PS28_8" data-id="PS28_8"> <l s="H3068">יְהוָ֥ה</l> <l s="H5797">עֹֽז</l>־<l s="H">לָ֑מוֹ</l> <l s="H4581">וּמָ֘ע֤וֹז</l> <l s="H3444">יְשׁוּע֖וֹת</l> <l s="H4899">מְשִׁיח֣וֹ</l> <l s="H1931">הֽוּא</l>׃ </span> <span class="v-num v-9">9</span><span class="v PS28_9" data-id="PS28_9"> <l s="H3467">הוֹשִׁ֤יעָה</l> ׀ <l s="H853">אֶת</l>־<l s="H5971">עַמֶּ֗ךָ</l> <l s="H1288">וּבָרֵ֥ךְ</l> <l s="H853">אֶת</l>־<l s="H5159">נַחֲלָתֶ֑ךָ</l> <l s="H7462">וּֽרְעֵ֥ם</l> <l s="H5375">וְ֝נַשְּׂאֵ֗ם</l> <l s="H5704">עַד</l>־<l s="H5769">הָעוֹלָֽם</l>׃ </span> </div> </div> <div class="footer"><div class="nav"> <a class="prev" href="PS27.html">&lt;</a> <a class="home" href="index.html">=</a> <a class="next" href="PS29.html">&gt;</a> </div></div> </body> </html>
import { combineReducers } from 'redux' import auth from './auth' import watt from './watt' import locations from './locations' export default combineReducers({ auth, watt, locations })
'use strict'; require('./components/dropdown'); require('./components/active-link');
# coding: utf-8 # # bmp.rb -- a toolkit for bitmap(BMP) image # # Copyright (c) 2014 Yoichi Yokogawa # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php # # ※ BMPファイルのファイルフォーマットについては、 # http://www.kk.iij4u.or.jp/~kondo/bmp/ を参考にしました class BitMap def initialize(width, height, dpi = 96) @width = width @height = height @line_size = width * 3 + (4 - (width * 3) % 4) % 4 @buf_size = @line_size * height @buf = ("\000" * @buf_size).encode('BINARY') @bit_count = 24 @compression = 0 # 圧縮無し @size_image = 0 @x_pix_per_meter = (39.375 * dpi).round @y_pix_per_meter = (39.375 * dpi).round @clr_used = 0 @cir_important = 0 end def clear(r = 255, g = 255, b = 255) line = b.chr * @line_size @width.times do |x| line[x * 3 + 1] = g.chr line[x * 3 + 2] = r.chr end @buf = line * @height end attr_writer :buf attr_reader :width, :height # BMPファイルを出力する def write(filename) file_size = 14 + 40 + @buf_size data_offset = 14 + 40 open(filename, "wb") do |f| f.print 'BM' f.print [file_size, 0, data_offset].pack("l*") f.print [40, @width, @height].pack("l*") f.print [1, @bit_count].pack("S*") f.print [@compression, @size_image, @x_pix_per_meter, @y_pix_per_meter, @clr_used, @cir_important].pack("l*") f.print @buf end end # BMPファイルを読み込む def BitMap.read(filename) buf = nil open(filename, "rb") do |f| buf = f.read end if buf[0] != ?B or buf[1] != ?M raise '[Error] read: Invalid Header' end real_buf_size = buf.size buf_size = (buf[2, 4].unpack("l*"))[0] if buf_size > real_buf_size raise '[Error] read: Invalid Buffer Size' end data_offset = (buf[10, 4].unpack("l*"))[0] if data_offset != 54 raise '[Error] read: Invalid Data Offset' end width = (buf[18, 4].unpack("l*"))[0] height = (buf[22, 4].unpack("l*"))[0] bit_count = (buf[28, 2].unpack("s*"))[0] if bit_count != 24 raise '[Error] read: Unsupported Color Depth' end compression = (buf[30, 4].unpack("l*"))[0] if compression != 0 raise '[Error] read: Compression Not Supported' end pix_per_meter = (buf[38, 4].unpack("l*"))[0] dpi = pix_per_meter / 39.375 image_buf = buf[54, buf_size] image = BitMap.new(width, height, dpi) image.buf = image_buf return image end # (x1, y1) - (x2, y2)の部分画像を取り出す def clip(x1, y1, x2, y2) return if x1 > x2 return if y1 > y2 return if x2 < 0 return if y2 < 0 return if x1 >= @width return if y1 >= @height x1 = 0 if x1 < 0 y1 = 0 if y1 < 0 x2 = @width - 1 if x2 >= @width y2 = @height - 1 if y2 >= @height clip_width = x2 - x1 + 1 clip_height = y2 - y1 + 1 clip_image = BitMap.new(clip_width, clip_height, self.get_dpi) for y in 0 .. (clip_height - 1) for x in 0 .. (clip_width - 1) color = self.pget(x1 + x, y1 + y) clip_image.pset(x, y, color[0], color[1], color[2]) end end return clip_image end # 1ピクセル描画 # x, y, r, g, b は整数であることを期待している def pset(x, y, r, g, b) return if x < 0 or @width <= x return if y < 0 or @height <= y r = 0 if r < 0 g = 0 if g < 0 b = 0 if b < 0 r = 255 if r > 255 g = 255 if g > 255 b = 255 if b > 255 @buf[(@height - 1 - y) * @line_size + x * 3 ] = b.chr @buf[(@height - 1 - y) * @line_size + x * 3 + 1] = g.chr @buf[(@height - 1 - y) * @line_size + x * 3 + 2] = r.chr end # 1ピクセル読み取り # x, yは整数であることを期待している # 戻り値は[r, g, b]な配列 def pget(x, y) x = 0 if x < 0 x = @width - 1 if x >= @width y = 0 if y < 0 y = @height - 1 if y >= @height addr = (@height - 1 - y) * @line_size + x * 3 b = @buf[addr ].ord g = @buf[addr + 1].ord r = @buf[addr + 2].ord return [r, g, b] end def get_dpi() return (@x_pix_per_meter / 39.375).round end def set_dpi(dpi) @x_pix_per_meter = (39.375 * dpi).round @y_pix_per_meter = @x_pix_per_meter end # BMP画像の貼り付け # x0, y0 は、貼り付ける始点(左上)の座標 def paste(image, x0 = 0, y0 = 0) return if image == nil image.height.times do |from_y| y = y0 + from_y next if y < 0 or @height <= y image.width.times do |from_x| x = x0 + from_x next if x < 0 or @width <= x color = image.pget(from_x, from_y) self.pset(x, y, color[0], color[1], color[2]) end end end end
namespace ExpectedObjects { public class UnexpectedElement : IUnexpectedElement { public UnexpectedElement(object element) { Element = element; } public object Element { get; set; } } }
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ "use strict"; /* Copyright 2013 jQuery Foundation and other contributors Released under the MIT license. http://jquery.org/license */ define(["ojs/ojcore","jquery","ojdnd","ojs/ojlistview"],function(a,g){a.jb=function(a){this.Ja=a};o_("ListViewDndContext",a.jb,a);a.f.xa(a.jb,a.f,"oj.ListViewDndContext");a.jb.nra=67;a.jb.rT=86;a.jb.tT=88;a.jb.prototype.reset=function(){this.t1();this.un=this.SI=this.XI=this.jR=null};a.jb.prototype.CX=function(a){var b=this.Ja.Jd("dnd");return null!=b&&b[a]?b[a].items:null};a.jb.prototype.WM=function(){return this.CX("drag")};a.jb.prototype.DX=function(){return this.CX("drop")};a.jb.prototype.ps= function(){return"enabled"==this.CX("reorder")};a.jb.prototype.Vg=function(a){return this.Ja.On(a)};a.jb.prototype.sN=function(){var a,b,d,e;a=[];if(this.Ja.Pc())for(b=this.Ja.Jd("selection"),d=0;d<b.length;d++)e=this.Ja.Se(b[d]),null==e||this.Ja.vj(g(e))||a.push(e);else e=this.dca(),null!=e&&a.push(e);null!=this.kz&&0<this.kz.length&&-1==a.indexOf(this.kz.get(0))&&a.push(this.kz.get(0));return a};a.jb.prototype.dca=function(){return null==this.Ja.V?null:this.Ja.V.elem[0]};a.jb.prototype.hz=function(a){var b; g(a).hasClass(this.Ja.eg())||(a=a.firstElementChild);a=g(a).find(".oj-listview-drag-handle");null!=a&&0<a.length&&(b=a.attr("aria-labelledby"),null==b?a.attr("aria-labelledby",this.Ja.qx("instr")):a.attr("aria-labelledby",b+" "+this.Ja.qx("instr")),this.Ja.Um()&&a.attr("draggable","true"))};a.jb.prototype.t1=function(){this.ooa&&g.each(this.ooa,function(a,b){g(b).removeClass("oj-draggable")})};a.jb.prototype.CTa=function(){var a=[],b,d,e;this.t1();b=this.Ja.Jd("selection");for(d=0;d<b.length;d++)e= this.Ja.Se(b[d]),null==e||this.Ja.vj(g(e))||(a.push(e),g(e).addClass("oj-draggable"));this.ooa=a};a.jb.prototype.Wia=function(a){var b;b=a.find(".oj-listview-drag-handle");if(null!=b&&0<b.length)return!0;a.addClass("oj-draggable");return!1};a.jb.prototype.WMa=function(a){a.removeClass("oj-draggable")};a.jb.prototype.Sia=function(a){var b,d;if(null!=this.WM()||this.ps()){if(a.hasClass("oj-listview-drag-handle"))b=g(a);else{a=this.Vg(a);if(null!=a&&(d=this.Wia(a)))return;d=this.sN();0<d.length&&(null!= a&&-1<d.indexOf(a[0])?b=a:g(d[0]).removeClass("oj-draggable"))}null!=b&&b.attr("draggable",!0)}};a.jb.prototype.uka=function(a){if(null!=this.WM()||this.ps())a=a.hasClass("oj-listview-drag-handle")?g(a):this.Vg(a),null!=a&&a.removeAttr("draggable")};a.jb.prototype.wo=function(c,b,d,e){var f;if(c="drag"===c?this.WM():this.DX())if((b=c[b])&&"function"==typeof b)try{d.dataTransfer=d.originalEvent.dataTransfer,f=b(d,e)}catch(g){a.F.error("Error: "+g)}else return-1;return f};a.jb.prototype.ZKa=function(a, b,d){var e,f=[],g;for(e=0;e<d.length;e++)(g=this.Ja.tca(d[e]))&&(g.innerHTML&&g.tagName&&"LI"==g.tagName?f.push(g.innerHTML):f.push(g));return 0<f.length?(this.YKa(a.originalEvent,b,f),this.$Ka(a.originalEvent,d),{items:f}):null};a.jb.prototype.YKa=function(a,b,d){var e;a=a.dataTransfer;d=JSON.stringify(d);if("string"==typeof b)a.setData(b,d);else if(b)for(e=0;e<b.length;e++)a.setData(b[e],d);a.setData("text/ojlistview-dragsource-id",this.Ja.element.get(0).id)};a.jb.prototype.$Ka=function(a,b){var d, e,f=Number.MAX_VALUE,h,k,l,m=0,p=0;d=a.target;if(1<b.length){d=g(document.createElement("ul"));d.get(0).className=this.Ja.element.get(0).className;d.addClass("oj-listview-drag-image").css({width:this.Ja.element.css("width"),height:this.Ja.element.css("height")});for(e=0;e<b.length;e++)f=Math.min(f,b[e].offsetTop);for(e=0;e<b.length;e++)h=b[e].offsetTop-f,k=b[e].offsetWidth,l=g(b[e].cloneNode(!0)),l.removeClass("oj-selected oj-focus oj-hover").css({position:"absolute",top:h,width:k}),d.append(l)}else g(d).hasClass("oj-listview-drag-handle")&& (h=0,g.contains(b[0],d.offsetParent)&&(h=d.offsetTop),m=Math.max(0,d.offsetLeft-b[0].offsetLeft)+d.offsetWidth/2,p=h+d.offsetHeight/2),l=g(b[0].cloneNode(!0)),l.removeClass("oj-selected oj-focus oj-hover").addClass("oj-drag"),d=g(document.createElement("ul")),d.get(0).className=this.Ja.element.get(0).className,d.addClass("oj-listview-drag-image").css({width:this.Ja.element.css("width"),height:2*b[0].offsetHeight}).append(l);g("body").append(d);this.XI=d;a.dataTransfer.setDragImage(d.get(0),m,p)}; a.jb.prototype.OY=function(a){var b,d,e;b=this.WM();if(null!=b||this.ps())if(d=null!=b?b.dataTypes:"text/ojlistview-items-data",g(a.target).hasClass("oj-listview-drag-handle")?(e=[],e.push(this.Vg(a.target)[0])):e=this.sN(),0<e.length){if(null==b&&1<e.length)return!1;this.un=e;this.SI=g(e[0]);if(b=this.ZKa(a,d,e)){if(a=this.wo("drag","dragStart",a,b),-1!==a)return a}else return!1}};a.jb.prototype.EDa=function(a){return this.wo("drag","drag",a)};a.jb.prototype.oM=function(){null!=this.XI&&(this.XI.remove(), this.XI=null)};a.jb.prototype.KY=function(a){var b;if(null!=this.SI&&null!=this.un)for(this.SI.find(".oj-listview-drag-handle").removeAttr("draggable"),this.SI.removeClass("oj-drag oj-draggable").removeAttr("draggable"),b=0;b<this.un.length;b++)g(this.un[b]).removeClass("oj-listview-drag-item");this.lF();this.oM();this.t1();this.wo("drag","dragEnd",a);this.jR=this.un;this.un=this.SI=this.XI=null};a.jb.prototype.WZ=function(a){var b,d;b=this.DX();if(this.ps()&&null==b)return!0;if(b&&b.dataTypes)for(b= b.dataTypes,b="string"==typeof b?[b]:b,a=a.originalEvent.dataTransfer.types,d=0;d<a.length;d++)if(0<=b.indexOf(a[d]))return!0;return!1};a.jb.prototype.xo=function(a,b,d){a=this.wo("drop",a,b,d);(void 0===a||-1===a)&&this.WZ(b)&&b.preventDefault();return a};a.jb.prototype.vaa=function(a){var b;null==this.Sj&&(b=g(a.get(0).cloneNode(!1)),b.addClass("oj-drop").removeClass("oj-drag oj-draggable oj-hover oj-focus oj-selected").css({display:"block",height:a.outerHeight()}),this.Sj=b);return this.Sj};a.jb.prototype.R$= function(){null!=this.cj&&-1===this.pD&&this.cj.children("."+this.Ja.dg()).removeClass("oj-drop")};a.jb.prototype.Q$=function(){null!=this.cj&&this.cj.hasClass("oj-listview-no-data-message")&&(this.cj.removeClass("oj-drop"),this.cj.get(0).textContent=this.Ja.zca())};a.jb.prototype.lF=function(){null!=this.Sj&&(this.Sj.css("height","0"),this.Sj.remove(),this.Sj=null);this.Q$();this.R$()};a.jb.prototype.LY=function(a){var b;b=this.Vg(a.target);a=this.xo("dragEnter",a,{item:b.get(0)});if(-1!=a)return a}; a.jb.prototype.l0=function(a){null!=this.cj&&this.cj.removeClass("oj-valid-drop oj-invalid-drop");this.cj=a;this.cj.addClass("oj-valid-drop")};a.jb.prototype.Iia=function(a,b){var d;d=a.attr("aria-label");null==d&&(d=a.text());d=this.Ja.ea.R("accessibleReorder"+b.charAt(0).toUpperCase()+b.substr(1)+"Item",{item:d});this.Ja.Ch(d)};a.jb.prototype.owa=function(){null==this.Koa&&this.Ja.Um()&&(this.Ja.element.find("ul."+this.Ja.fh()).each(function(){g(this).attr("oldMaxHeight",g(this).css("maxHeight").toString()); g(this).css("maxHeight",1E4)}),this.Koa="adjusted")};a.jb.prototype.uia=function(){this.Ja.Um()&&this.Ja.element.find("ul."+this.Ja.fh()).each(function(){g(this).css("maxHeight",parseInt(g(this).attr("oldMaxHeight"),10));g(this).removeAttr("oldMaxHeight")});this.Koa=null};a.jb.prototype.NY=function(a){var b,d,e,f;if(null!=this.DX()||this.ps()){this.owa();if(null!=this.un&&"none"!=g(this.un[0]).css("display")){b=g(this.un[0]);d=this.vaa(b);for(a=0;a<this.un.length;a++)g(this.un[a]).addClass("oj-listview-drag-item"); d.insertBefore(b);this.pD=d.index()}else b=this.Vg(a.target),null!=b&&0<b.length?(e=this.xo("dragOver",a,{item:b.get(0)}),-1===e&&this.ps()||!1===e||a.isDefaultPrevented()?(b.hasClass(this.Ja.eg())?(this.R$(),b.hasClass("oj-drop")||(d=this.vaa(b),f=b.index(),null==this.pD||this.pD<f?(d.insertAfter(b),this.oD="after"):(d.insertBefore(b),this.oD="before"),this.Iia(b,this.oD),this.l0(b),this.pD=d.index())):(this.lF(),b.children("."+this.Ja.dg()).addClass("oj-drop"),this.l0(b),this.pD=-1,this.oD="inside", this.Iia(b,this.oD)),a.preventDefault()):g(a.target).hasClass(this.Ja.fh())||(b.addClass("oj-invalid-drop"),this.lF())):(b=this.Ja.element.children(".oj-listview-no-data-message"),null!=b&&0<b.length&&(b.addClass("oj-drop"),b.get(0).textContent="",this.l0(b),a.preventDefault()));return e}};a.jb.prototype.ZN=function(a,b){var d,e;d=b.getBoundingClientRect();e=a.originalEvent;return e.clientX>=d.left&&e.clientX<d.right&&e.clientY>=d.top&&e.clientY<d.bottom};a.jb.prototype.MY=function(a){var b,d;if(null!= this.cj&&(b=this.Vg(a.target),null!=b&&0<b.length?(b.removeClass("oj-valid-drop oj-invalid-drop"),d=this.xo("dragLeave",a,{item:b.get(0)}),this.ZN(a,a.currentTarget)||(this.lF(),this.uia())):this.ZN(a,a.currentTarget)||this.Q$(),-1!=d))return d};a.jb.prototype.PY=function(a){var b,d;if(null!=this.cj&&(b=a.originalEvent.dataTransfer.getData("text/ojlistview-dragsource-id"),d=this.cj.hasClass("oj-listview-no-data-message")?{}:{item:this.cj.get(0),position:this.oD},this.ps()&&b===this.Ja.element.get(0).id? d.reorder=!0:d.reorder=!1,b=this.xo("drop",a,d),d.reorder&&(d.items=null==this.jR?this.un:this.jR,d.reference=d.item,this.Ja.Bl("reorder",a,d),a.preventDefault()),null!=this.cj&&this.cj.removeClass("oj-valid-drop"),this.lF(),this.uia(),this.oM(),this.cj=null,this.pD=-1,this.jR=this.oD=null,-1!==b))return b};a.jb.prototype.ANa=function(a){var b=this,d,e;this.ps()&&(void 0==a&&(a=this.Ja.Jd("contextMenu")),null!=a&&(null==this.xn&&(this.xn=[]),a=g(a),d=a.find("[data-oj-command]"),e=[],d.each(function(){var a, c;0===g(this).children("a").length?0==g(this).attr("data-oj-command").indexOf("oj-listview-")&&(a=g(this).attr("data-oj-command").substring(12),c=b.tk(a),c.get(0).className=g(this).get(0).className,g(this).replaceWith(c)):(a=g(this).attr("data-oj-command"),"pasteBefore"==a?a="paste-before":"pasteAfter"==a&&(a="paste-after"));null!=a&&e.push(a)}),this.xn=e,0<e.length&&(a.data("oj-ojMenu")&&a.ojMenu("refresh"),a.on("ojbeforeopen",this.vDa.bind(this)),a.on("ojselect",this.Vl.bind(this)))))};a.jb.prototype.tk= function(a){return"paste-before"===a?this.Sg("pasteBefore"):"paste-after"===a?this.Sg("pasteAfter"):this.Sg(a)};a.jb.prototype.Sg=function(a){var b=g("\x3cli\x3e\x3c/li\x3e");b.attr("data-oj-command",a);b.append(this.fF(a));return b};a.jb.prototype.fF=function(a){a="label"+a.charAt(0).toUpperCase()+a.slice(1);return g('\x3ca href\x3d"#"\x3e\x3c/a\x3e').text(this.Ja.ea.R(a))};a.jb.prototype.iG=function(a){var b;null!=this.Yo&&g(this.Yo).removeClass("oj-listview-cut");b=this.sN();g(b).addClass("oj-listview-cut"); this.Yo=b;this.Ja.Bl("cut",a,{items:b})};a.jb.prototype.dea=function(a){var b;null!=this.Yo&&g(this.Yo).removeClass("oj-listview-cut");this.Yo=b=this.sN();this.Ja.Bl("copy",a,{items:b})};a.jb.prototype.kG=function(a,b,d){this.Ja.Bl("paste",a,{item:b.get(0)});g(this.Yo).removeClass("oj-listview-cut");this.Ja.Bl("reorder",a,{items:this.Yo,position:d,reference:b.get(0)});this.Yo=null};a.jb.prototype.Vl=function(a,b){if(null!=this.kz)switch(b.item.attr("data-oj-command")){case "cut":this.iG(a);break; case "copy":this.dea(a);break;case "paste":var d=!0;case "pasteBefore":var e=!0;case "pasteAfter":var f="after";d?f="inside":e&&(f="before");this.kG(a,this.kz,f);this.kz=null}};a.jb.prototype.XE=function(a,b){null!=this.xn&&("paste-before"==b?b="pasteBefore":"paste-after"==b&&(b="pasteAfter"),a.find("[data-oj-command\x3d'"+b+"']").removeClass("oj-disabled"))};a.jb.prototype.vDa=function(a,b){var d,e;d=g(a.target);d.find("[data-oj-command]").addClass("oj-disabled");e=b.openOptions.launcher;null==e|| null==this.xn||0==this.xn.length?d.ojMenu("refresh"):(e.children().first().hasClass(this.Ja.dg())?null!=this.Yo&&this.XE(d,"paste"):(this.XE(d,"cut"),this.XE(d,"copy"),null!=this.Yo&&(this.XE(d,"paste-before"),this.XE(d,"paste-after"))),d.ojMenu("refresh"),this.kz=e)};a.jb.prototype.SJ=function(c){var b,d;if(!this.ps()||null==this.xn||0==this.xn.length)return!1;if(c.ctrlKey||c.metaKey){b=c.keyCode;if(b===a.jb.tT&&-1<this.xn.indexOf("cut"))return this.iG(c),!0;if(b===a.jb.nra&&-1<this.xn.indexOf("copy"))return this.dea(c), !0;if(b===a.jb.rT&&null!=this.Yo&&(b=g(this.dca()),b.children().first().hasClass(this.Ja.dg())?-1<this.xn.indexOf("paste")&&(d="inside"):-1<this.xn.indexOf("paste-before")?d="before":-1<this.xn.indexOf("paste-after")&&(d="after"),null!=d))return this.kG(c,b,d),!0}return!1}});
// // UIControl+YYAdd.h // YYCategories <https://github.com/ibireme/YYCategories> // // Created by ibireme on 13/4/5. // Copyright (c) 2015 ibireme. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** Provides extensions for `UIControl`. UIControl的扩展 */ @interface UIControl (YYAdd) /** Removes all targets and actions for a particular event (or events) from an internal dispatch table. 移除所有的对象和action */ - (void)removeAllTargets; /** Adds or replaces a target and action for a particular event (or events) to an internal dispatch table. 设置或者替换 @param target The target object—that is, the object to which the action message is sent. If this is nil, the responder chain is searched for an object willing to respond to the action message. @param action A selector identifying an action message. It cannot be NULL. @param controlEvents A bitmask specifying the control events for which the action message is sent. */ - (void)setTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents; /** Adds a block for a particular event (or events) to an internal dispatch table. It will cause a strong reference to @a block. block 方式添加事件回调,强引用 @param block The block which is invoked then the action message is sent (cannot be nil). The block is retained. @param controlEvents A bitmask specifying the control events for which the action message is sent. */ - (void)addBlockForControlEvents:(UIControlEvents)controlEvents block:(void (^)(id sender))block; /** Adds or replaces a block for a particular event (or events) to an internal dispatch table. It will cause a strong reference to @a block. 增加或者替换 @param block The block which is invoked then the action message is sent (cannot be nil). The block is retained. @param controlEvents A bitmask specifying the control events for which the action message is sent. */ - (void)setBlockForControlEvents:(UIControlEvents)controlEvents block:(void (^)(id sender))block; /** Removes all blocks for a particular event (or events) from an internal dispatch table. 移除所有的block方式的回调 @param controlEvents A bitmask specifying the control events for which the action message is sent. */ - (void)removeAllBlocksForControlEvents:(UIControlEvents)controlEvents; @end NS_ASSUME_NONNULL_END
/* eslint-env mocha */ 'use strict' const chai = require('chai') chai.use(require('dirty-chai')) const expect = chai.expect const parallel = require('async/parallel') const createNode = require('./utils/create-node.js') const echo = require('./utils/echo') describe('ping', () => { let nodeA let nodeB before((done) => { parallel([ (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeA = node node.handle('/echo/1.0.0', echo) node.start(cb) }), (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeB = node node.handle('/echo/1.0.0', echo) node.start(cb) }) ], done) }) after((done) => { parallel([ (cb) => nodeA.stop(cb), (cb) => nodeB.stop(cb) ], done) }) it('should be able to ping another node', (done) => { nodeA.ping(nodeB.peerInfo, (err, ping) => { expect(err).to.not.exist() ping.once('ping', (time) => { expect(time).to.exist() ping.stop() done() }) ping.start() }) }) it('should be not be able to ping when stopped', (done) => { nodeA.stop(() => { nodeA.ping(nodeB.peerInfo, (err) => { expect(err).to.exist() done() }) }) }) })
<?php /** * @copyright Bluz PHP Team * @link https://github.com/bluzphp/skeleton */ declare(strict_types=1); namespace Application\Pages; /** * Table of Pages * * @package Application\Pages * * @method static ?Row findRow($primaryKey) * @see \Bluz\Db\Table::findRow() * @method static ?Row findRowWhere($whereList) * @see \Bluz\Db\Table::findRowWhere() */ class Table extends \Bluz\Db\Table { /** * Table * * @var string */ protected $name = 'pages'; /** * Primary key(s) * * @var array */ protected $primary = ['id']; /** * Get page by Alias * * @param $alias * * @return Row * @throws \Bluz\Db\Exception\DbException */ public function getByAlias($alias): ?Row { return static::findRowWhere(['alias' => $alias]); } /** * Init table relations * * @return void */ public function init(): void { $this->linkTo('userId', 'Users', 'id'); } }
package edu.utah.nanofab.coralapiserver.core; public class EnableRequest { private String item; private String member; public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getMember() { return member; } public void setMember(String member) { this.member = member; } public String getProject() { return project; } public void setProject(String project) { this.project = project; } private String project; }
package edu.hm.hafner.analysis.parser; import org.junit.jupiter.api.Test; import edu.hm.hafner.analysis.Issue; import edu.hm.hafner.analysis.Issues; import edu.hm.hafner.analysis.Priority; import static edu.hm.hafner.analysis.assertj.IssuesAssert.*; import static edu.hm.hafner.analysis.assertj.SoftAssertions.*; /** * Tests the class {@link LinuxKernelOutputParser}. * * @author Benedikt Spranger */ public class LinuxKernelOutputParserTest extends ParserTester { /** * Parse a kernel log file. */ @Test public void testWarningsParser() { Issues<Issue> warnings = new LinuxKernelOutputParser().parse(openFile()); assertThat(warnings).hasSize(26); assertSoftly(softly -> { softly.assertThat(warnings.get(0)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: RSDP 0x00000000000F68D0 000014 (v00 BOCHS )") .hasFileName("Nil"); softly.assertThat(warnings.get(1)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: RSDT 0x0000000007FE18DC 000030 (v01 BOCHS BXPCRSDT 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(2)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: FACP 0x0000000007FE17B8 000074 (v01 BOCHS BXPCFACP 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(3)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: DSDT 0x0000000007FE0040 001778 (v01 BOCHS BXPCDSDT 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(4)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: FACS 0x0000000007FE0000 000040") .hasFileName("Nil"); softly.assertThat(warnings.get(5)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: APIC 0x0000000007FE182C 000078 (v01 BOCHS BXPCAPIC 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(6)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: HPET 0x0000000007FE18A4 000038 (v01 BOCHS BXPCHPET 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(7)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: 1 ACPI AML tables successfully acquired and loaded") .hasFileName("Nil"); softly.assertThat(warnings.get(8)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("kworker/u2:0 (32) used greatest stack depth: 14256 bytes left") .hasFileName("Nil"); softly.assertThat(warnings.get(9)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("kworker/u2:0 (26) used greatest stack depth: 13920 bytes left") .hasFileName("Nil"); softly.assertThat(warnings.get(10)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("acpi PNP0A03:00: fail to add MMCONFIG information, can't access extended PCI configuration space under this bridge.") .hasFileName("Nil"); softly.assertThat(warnings.get(11)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: Enabled 3 GPEs in block 00 to 0F") .hasFileName("Nil"); softly.assertThat(warnings.get(12)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: PCI Interrupt Link [LNKC] enabled at IRQ 11") .hasFileName("Nil"); softly.assertThat(warnings.get(13)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("mdev (949) used greatest stack depth: 13888 bytes left") .hasFileName("Nil"); softly.assertThat(warnings.get(14)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: WARNING") .hasFileName("Nil"); softly.assertThat(warnings.get(15)) .hasPriority(Priority.NORMAL) .hasCategory("WARNING") .hasLineStart(26) .hasLineEnd(26) .hasMessage("WARNING in kaboom_init()") .hasFileName("/home/bene/work/rtl/test-description/tmp/linux-stable-rt/drivers/misc/kaboom.c"); softly.assertThat(warnings.get(16)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: ERR") .hasFileName("Nil"); softly.assertThat(warnings.get(17)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: CRIT") .hasFileName("Nil"); softly.assertThat(warnings.get(18)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: ALERT") .hasFileName("Nil"); softly.assertThat(warnings.get(19)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: EMERG") .hasFileName("Nil"); softly.assertThat(warnings.get(20)) .hasPriority(Priority.HIGH) .hasCategory("BUG") .hasLineStart(39) .hasLineEnd(39) .hasMessage("BUG in ()") .hasFileName("/home/bene/work/rtl/test-description/tmp/linux-stable-rt/drivers/misc/kaboom.c"); softly.assertThat(warnings.get(21)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("sysrq: SysRq : Emergency Sync") .hasFileName("Nil"); softly.assertThat(warnings.get(22)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("sysrq: SysRq : Emergency Remount R/O") .hasFileName("Nil"); }); } @Override protected String getWarningsFile() { return "kernel.log"; } }
# MeanShiftGPU OpenCL implementation of mean shift clustering
.mod_clear:after { content: "."; display: block; height: 0; clear: both; visibility: hidden } .mod_ver{ display: inline-block; *display: inline; *zoom: 1; height: 100%; vertical-align: middle; width: 0; font-size: 0; } .mod_container{ min-width: 1200px; font: 14px/1.5 \5FAE\8F6F\96C5\9ED1, \5B8B\4F53, "Hiragino Sans GB", STHeiti, "WenQuanYi Micro Hei", "Droid Sans Fallback", SimSun, sans-serif; -webkit-font-smoothing: antialiased; } .mod_container h1, .mod_container h2, .mod_container h3, .mod_container h4, .mod_container h5, .mod_container h6{ font-weight: normal; } .mod_container img{ vertical-align: top; } .mod_container a{ cursor: pointer; } .mod_hd { height: 40px; background: #fff; border-bottom: 1px solid #666; } .mod_hd .mod_main { overflow: hidden; width: 1200px; margin: 0 auto; } .mod_hd_lk { float: left; padding: 0 60px; height: 40px; line-height: 40px; font-size: 14px; text-align: center; color: #666; } .mod_hd_lk:hover { color: #fe575f; } .mod_hd .on { color: #fff; background-color: #333; } .mod_hd .on:hover { color: #fff; } .index_mod_hang { position: fixed; left: 50%; bottom: 20px; z-index: 100; width: 60px; visibility: visible; margin: 0 0 0 320px; } .index_mod_hang_mini { left: auto; right: 0; margin: 0; } .index_mod_hang_col { margin-top: 3px; border: 3px solid #fe575f; background: #fff; } .index_mod_hang_col a { display: block; height: 54px; -webkit-transition: all 0.25s ease; transition: all 0.25s ease; cursor: pointer; } .index_mod_hang_col .index_mod_iconfont { font-size: 20px; color: #fff; -webkit-transition: color 0.25s ease; transition: color 0.25s ease; } .index_mod_hang_item { border-bottom: 1px solid #fe575f; font-size: 0; text-align: center; } .index_mod_hang_item_main { display: inline-block; vertical-align: middle; font-size: 14px; color: #222; } .index_mod_hang_item_main .index_mod_iconfont { display: block; height: 40px; line-height: 40px; overflow: hidden; } .index_mod_hang_item_main span { display: block; margin-top: -1px; -webkit-transition: all 0.25s ease; transition: all 0.25s ease; } .index_mod_hang_item:hover { background: #fe575f; } .index_mod_hang_item:hover .index_mod_hang_item_main { color: #fff; } .index_mod_hang_item_on { background: #fe575f; } .index_mod_hang_item_on .index_mod_hang_item_main { color: #fff; } .index_mod_hang_item_on .index_mod_hang_item_main .index_mod_iconfont { color: #fff; } .index_mod_hang .index_mod_hang_top { background: #fe575f; color: #fff; font-size: 16px; line-height: 54px; text-align: center; } .index_mod_hang .index_mod_hang_top:hover { color: #fff; } .index_mod_hang_car { position: relative; line-height: 54px; text-align: center; } .index_mod_hang_car .index_mod_iconfont { color: #fe575f; } .index_mod_hang_car span { position: absolute; right: 4px; top: 4px; height: 20px; min-width: 1em; _width: 1em; padding: 0 5px; border-radius: 10px; text-align: center; line-height: 20px; background: #ff5745; color: #fff; font-size: 14px; font-family: Arial, Helvetica, sans-serif; white-space: nowrap; -webkit-transition: all 0.25s ease; transition: all 0.25s ease; } .index_mod_hang_car:hover { background: #fe575f; } .index_mod_hang_car:hover .index_mod_iconfont { color: #fff; } .index_mod_hang_car:hover span { color: #fe575f; background: #fff; } .index_mod_hang_like { position: relative; line-height: 60px; text-align: center; } .index_mod_hang_like:hover { background: #fce5ae; } .index_mod_hang_like:hover .index_mod_iconfont { color: #683e10; } .floor{ height: 800px; margin: 20px 0 0; text-align: center; font-size: 20px; line-height: 800px; background: #fce5ae; } .box{ height: 800px; margin: 20px 0 0; text-align: center; font-size: 20px; line-height: 800px; background: #fce5ae; } .box2{ height: 300px; line-height: 300px; }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebApiTemplate.Api { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { DatabaseConfig.Initialize(); AutoMapperConfig.RegisterMappings(Assembly.Load("WebApiTemplate.Api")); GlobalConfiguration.Configure(WebApiConfig.Register); } } }
\hypertarget{classtesting__1__1internal__1__1__listener__test_8js}{}\section{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test.js File Reference} \label{classtesting__1__1internal__1__1__listener__test_8js}\index{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test.\+js@{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test.\+js}} \subsection*{Variables} \begin{DoxyCompactItemize} \item var \hyperlink{classtesting__1__1internal__1__1__listener__test_8js_aedb6804ec013c7c30b92ea657a64463c}{classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test} \end{DoxyCompactItemize} \subsection{Variable Documentation} \index{classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test.\+js@{classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test.\+js}!classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test@{classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test}} \index{classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test@{classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test}!classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test.\+js@{classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test.\+js}} \subsubsection[{\texorpdfstring{classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test}{classtesting_1_1internal_1_1_listener_test}}]{\setlength{\rightskip}{0pt plus 5cm}var classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test}\hypertarget{classtesting__1__1internal__1__1__listener__test_8js_aedb6804ec013c7c30b92ea657a64463c}{}\label{classtesting__1__1internal__1__1__listener__test_8js_aedb6804ec013c7c30b92ea657a64463c} {\bfseries Initial value\+:} \begin{DoxyCode} = [ [ \textcolor{stringliteral}{"SetUp"}, \textcolor{stringliteral}{"classtesting\_1\_1internal\_1\_1\_listener\_test.html#ace3dbe36b705ddf320518e6cdd919bc8"}, null ], [ \textcolor{stringliteral}{"TearDown"}, \textcolor{stringliteral}{"classtesting\_1\_1internal\_1\_1\_listener\_test.html#ad112535025d668e3ea14e71d8741c810"}, null ] ] \end{DoxyCode} Definition at line 1 of file classtesting\+\_\+1\+\_\+1internal\+\_\+1\+\_\+1\+\_\+listener\+\_\+test.\+js.
<?php namespace Brick\Routing; use Symfony\Component\Routing\RouteCollection; class NullLoader extends \Symfony\Component\Config\Loader\Loader { public function load($resource, $type = null) { return new RouteCollection; } public function supports($resource, $type = null) { return is_null($resource); } }
'use strict'; angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', function($scope, $stateParams, $location, Authentication, Articles) { $scope.authentication = Authentication; $scope.create = function() { var article = new Articles({ title: this.title, content: this.content }); article.$save(function(response) { $location.path('articles/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); this.title = ''; this.content = ''; }; $scope.remove = function(article) { if (article) { article.$remove(); for (var i in $scope.articles) { if ($scope.articles[i] === article) { $scope.articles.splice(i, 1); } } } else { $scope.article.$remove(function() { $location.path('articles'); }); } }; $scope.update = function() { var article = $scope.article; article.$update(function() { $location.path('articles/' + article._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.find = function() { $scope.articles = Articles.query(); }; $scope.findOne = function () { $scope.article = Articles.get({ articleId: $stateParams.articleId }); }; } ]);
require('..').config({namespace:'NVM'}) .read({}) .on('read', function(ENV){ console.log(JSON.stringify(ENV, null, 4)); });
import { browser, Config } from 'protractor'; import { reporter } from './helpers/reporter'; export const config: Config = { framework: 'jasmine', SELENIUM_PROMISE_MANAGER: true, specs: ['../test/**/*.spec.js'], noGlobals: true, onPrepare: () => { browser.manage().timeouts().implicitlyWait(0) browser.ignoreSynchronization = true; reporter(); }, getPageTimeout: 30000, jasmineNodeOpts: { defaultTimeoutInterval: 120000 }, capabilities: { browserName: 'chrome', chromeOptions: { args: ['disable-infobars=true --window-size=800,600'], prefs: { credentials_enable_service: false } } } }
using System; using CoreGraphics; using UIKit; using Foundation; namespace MonoTouch.Dialog { public class ActivityElement : Element { public ActivityElement():base(""){ } UIActivityIndicatorView indicator; public bool Animating { get { return indicator.IsAnimating; } set { if (value) indicator.StartAnimating (); else indicator.StopAnimating (); } } static NSString ikey = new NSString ("ActivityElement"); protected override NSString CellKey { get { return ikey; } } public override UITableViewCell GetCell (UITableView tv) { var cell = tv.DequeueReusableCell (CellKey); if (cell == null){ cell = new UITableViewCell (UITableViewCellStyle.Default, CellKey); } indicator = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray); var sbounds = tv.Frame; var vbounds = indicator.Bounds; indicator.Frame = new CGRect((sbounds.Width-vbounds.Width)/2, 12, vbounds.Width, vbounds.Height); indicator.StartAnimating (); cell.Add (indicator); return cell; } protected override void Dispose (bool disposing) { if (disposing){ if (indicator != null){ indicator.Dispose (); indicator = null; } } base.Dispose (disposing); } } }
#!/bin/bash # first steps sudo dnf -y install dnf-plugins-core sudo dnf config-manager \ --add-repo \ https://download.docker.com/linux/fedora/docker-ce.repo sudo dnf -y install docker-ce # post installation sudo groupadd docker sudo usermod -aG docker $USER sudo systemctl enable docker # test sudo systemctl start docker.service #docker run hello-world
#include <rte_config.h> #include <rte_ethdev.h> #include <rte_mempool.h> #include <rte_ether.h> #include <rte_cycles.h> #include <rte_mbuf.h> #include <ixgbe_type.h> #include <rte_mbuf.h> #include "device.h" #include <rte_power.h> // default descriptors per queue #define DEFAULT_RX_DESCS 512 #define DEFAULT_TX_DESCS 256 // values taken from the DPDK-L2FWD example, optimized for 82599 chips #define RX_PTHRESH 8 #define RX_HTHRESH 8 #define RX_WTHRESH 4 #define TX_PTHRESH 36 #define TX_HTHRESH 0 #define TX_WTHRESH 0 #define DEFAULT_MTU 8000 static volatile uint8_t* registers[RTE_MAX_ETHPORTS]; uint32_t read_reg32(uint8_t port, uint32_t reg) { return *(volatile uint32_t*)(registers[port] + reg); } void write_reg32(uint8_t port, uint32_t reg, uint32_t val) { *(volatile uint32_t*)(registers[port] + reg) = val; } static inline volatile uint32_t* get_reg_addr(uint8_t port, uint32_t reg) { return (volatile uint32_t*)(registers[port] + reg); } int configure_device_part1(int port, int rx_queues, int tx_queues, int tx_descs, uint16_t link_speed, uint8_t rss_enable, struct mg_rss_hash_mask * hash_functions) { //printf("configure device: rxqueues = %d, txdevs = %d, port = %d\n", rx_queues, tx_queues, port); if (port >= RTE_MAX_ETHPORTS) { printf("error: Maximum number of supported ports is %d\n This can be changed with the DPDK compile-time configuration variable RTE_MAX_ETHPORTS\n", RTE_MAX_ETHPORTS); return -1; } // FIXME: this is a workaround to force the linking of the power module rte_power_init(3); uint64_t rss_hash_functions = 0; if(rss_enable && hash_functions != NULL){ // configure the selected hash functions: if(hash_functions->ipv4){ rss_hash_functions |= ETH_RSS_IPV4; //printf("ipv4\n"); } if(hash_functions->udp_ipv4){ rss_hash_functions |= ETH_RSS_IPV4_UDP; //printf("ipv4 udp\n"); } if(hash_functions->tcp_ipv4){ rss_hash_functions |= ETH_RSS_IPV4_TCP; //printf("ipv4 tcp\n"); } if(hash_functions->ipv6){ rss_hash_functions |= ETH_RSS_IPV6; //printf("ipv6\n"); } if(hash_functions->udp_ipv6){ rss_hash_functions |= ETH_RSS_IPV6_TCP; //printf("ipv6 udp\n"); } if(hash_functions->tcp_ipv6){ rss_hash_functions |= ETH_RSS_IPV6_UDP; //printf("ipv6 tcp\n"); } } // TODO: enable other FDIR filter types struct rte_fdir_conf fdir_conf = { .mode = RTE_FDIR_MODE_PERFECT, .pballoc = RTE_FDIR_PBALLOC_64K, .status = RTE_FDIR_REPORT_STATUS_ALWAYS, .flexbytes_offset = 21, // TODO support other values .drop_queue = 63, // TODO: support for other NICs }; struct rte_eth_rss_conf rss_conf = { .rss_key = NULL, .rss_key_len = 0, .rss_hf = rss_hash_functions, }; struct rte_eth_conf port_conf = { .rxmode = { .mq_mode = rss_enable ? ETH_MQ_RX_RSS : ETH_MQ_RX_NONE, .split_hdr_size = 0, .header_split = 0, .hw_ip_checksum = 1, .hw_vlan_filter = 0, .jumbo_frame = 0, .hw_strip_crc = 1, }, .txmode = { .mq_mode = ETH_MQ_TX_NONE, }, .fdir_conf = fdir_conf, .link_speed = link_speed, .rx_adv_conf.rss_conf = rss_conf, }; int rc = rte_eth_dev_configure(port, rx_queues, tx_queues, &port_conf); if (rc) return rc; // DPDK documentation suggests that the tx queues should be set up before the rx queues struct rte_eth_txconf tx_conf = { // TODO: this should use different values for older GbE NICs .tx_thresh = { .pthresh = TX_PTHRESH, .hthresh = TX_HTHRESH, .wthresh = TX_WTHRESH, }, .tx_free_thresh = 0, // 0 = default .tx_rs_thresh = 0, // 0 = default .txq_flags = ETH_TXQ_FLAGS_NOMULTSEGS, }; for (int i = 0; i < tx_queues; i++) { // TODO: get socket id for the NIC rc = rte_eth_tx_queue_setup(port, i, tx_descs ? tx_descs : DEFAULT_TX_DESCS, SOCKET_ID_ANY, &tx_conf); if (rc) { printf("could not configure tx queue %d\n", i); return rc; } } return 0; } int configure_rxQueue(int port, int queueNr, int rx_descs, struct rte_mempool* mempool, bool drop_en) { int rc = 0; struct rte_eth_rxconf rx_conf = { .rx_drop_en = drop_en, // TODO: make this configurable per queue .rx_thresh = { .pthresh = RX_PTHRESH, .hthresh = RX_HTHRESH, .wthresh = RX_WTHRESH, }, }; // TODO: get socket id for the NIC //printf("setting up queue nr %d !\n", i); rc = rte_eth_rx_queue_setup(port, queueNr, rx_descs ? rx_descs : DEFAULT_RX_DESCS, SOCKET_ID_ANY, &rx_conf, mempool); if (rc != 0) { printf("could not configure rx queue %d\n", queueNr); return rc; } return rc; } int configure_device_part2(int port){ int rc = 0; rte_eth_promiscuous_enable(port); rc = rte_eth_dev_start(port); // save memory address of the register file struct rte_eth_dev_info dev_info; rte_eth_dev_info_get(port, &dev_info); registers[port] = (uint8_t*) dev_info.pci_dev->mem_resource[0].addr; // allow sending large and small frames rte_eth_dev_set_mtu(port, DEFAULT_MTU); uint32_t hlReg0 = read_reg32(port, 0x4240); hlReg0 &= ~(1 << 10); // TXPADEN hlReg0 |= (1 << 2); // JUMBOEN write_reg32(port, 0x4240, hlReg0); uint32_t tctl = read_reg32(port, 0x0400); tctl &= ~(1 << 3); // PSP write_reg32(port, 0x0400, tctl); return rc; } // XXX: @paul: do you think this is ok? It is still ugly code, but a little bit // more flexible. Maybe a complete reimplementation of device initialization // should be done in the future. // this function is not used anymore, as it was split up in three parts. // see above: configure_device_part1, configure_rxQueue and configure_device_part2 // This allows a more flexible rx queue configuration // // int configure_device(int port, int rx_queues, int tx_queues, int rx_descs, int tx_descs, uint16_t link_speed, struct rte_mempool* mempool, bool drop_en, uint8_t rss_enable, struct mg_rss_hash_mask * hash_functions) { // //printf("configure device: rxqueues = %d, txdevs = %d, port = %d\n", rx_queues, tx_queues, port); // if (port >= RTE_MAX_ETHPORTS) { // printf("error: Maximum number of supported ports is %d\n This can be changed with the DPDK compile-time configuration variable RTE_MAX_ETHPORTS\n", RTE_MAX_ETHPORTS); // return -1; // } // // FIXME: this is a workaround to force the linking of the power module // rte_power_init(3); // // uint64_t rss_hash_functions = 0; // if(rss_enable && hash_functions != NULL){ // // configure the selected hash functions: // if(hash_functions->ipv4){ // rss_hash_functions |= ETH_RSS_IPV4; // //printf("ipv4\n"); // } // if(hash_functions->udp_ipv4){ // rss_hash_functions |= ETH_RSS_IPV4_UDP; // //printf("ipv4 udp\n"); // } // if(hash_functions->tcp_ipv4){ // rss_hash_functions |= ETH_RSS_IPV4_TCP; // //printf("ipv4 tcp\n"); // } // if(hash_functions->ipv6){ // rss_hash_functions |= ETH_RSS_IPV6; // //printf("ipv6\n"); // } // if(hash_functions->udp_ipv6){ // rss_hash_functions |= ETH_RSS_IPV6_TCP; // //printf("ipv6 udp\n"); // } // if(hash_functions->tcp_ipv6){ // rss_hash_functions |= ETH_RSS_IPV6_UDP; // //printf("ipv6 tcp\n"); // } // } // // // // TODO: enable other FDIR filter types // struct rte_fdir_conf fdir_conf = { // .mode = RTE_FDIR_MODE_PERFECT, // .pballoc = RTE_FDIR_PBALLOC_64K, // .status = RTE_FDIR_REPORT_STATUS_ALWAYS, // .flexbytes_offset = 21, // TODO support other values // .drop_queue = 63, // TODO: support for other NICs // }; // // struct rte_eth_rss_conf rss_conf = { // .rss_key = NULL, // .rss_key_len = 0, // .rss_hf = rss_hash_functions, // }; // struct rte_eth_conf port_conf = { // .rxmode = { // .mq_mode = rss_enable ? ETH_MQ_RX_RSS : ETH_MQ_RX_NONE, // .split_hdr_size = 0, // .header_split = 0, // .hw_ip_checksum = 1, // .hw_vlan_filter = 0, // .jumbo_frame = 0, // .hw_strip_crc = 1, // }, // .txmode = { // .mq_mode = ETH_MQ_TX_NONE, // }, // .fdir_conf = fdir_conf, // .link_speed = link_speed, // .rx_adv_conf.rss_conf = rss_conf, // }; // int rc = rte_eth_dev_configure(port, rx_queues, tx_queues, &port_conf); // if (rc) return rc; // // DPDK documentation suggests that the tx queues should be set up before the rx queues // struct rte_eth_txconf tx_conf = { // // TODO: this should use different values for older GbE NICs // .tx_thresh = { // .pthresh = TX_PTHRESH, // .hthresh = TX_HTHRESH, // .wthresh = TX_WTHRESH, // }, // .tx_free_thresh = 0, // 0 = default // .tx_rs_thresh = 0, // 0 = default // .txq_flags = ETH_TXQ_FLAGS_NOMULTSEGS, // }; // for (int i = 0; i < tx_queues; i++) { // // TODO: get socket id for the NIC // rc = rte_eth_tx_queue_setup(port, i, tx_descs ? tx_descs : DEFAULT_TX_DESCS, SOCKET_ID_ANY, &tx_conf); // if (rc) { // printf("could not configure tx queue %d\n", i); // return rc; // } // } // struct rte_eth_rxconf rx_conf = { // .rx_drop_en = drop_en, // TODO: make this configurable per queue // .rx_thresh = { // .pthresh = RX_PTHRESH, // .hthresh = RX_HTHRESH, // .wthresh = RX_WTHRESH, // }, // }; // for (int i = 0; i < rx_queues; i++) { // // TODO: get socket id for the NIC // //printf("setting up queue nr %d !\n", i); // rc = rte_eth_rx_queue_setup(port, i, rx_descs ? rx_descs : DEFAULT_RX_DESCS, SOCKET_ID_ANY, &rx_conf, mempool); // if (rc != 0) { // printf("could not configure rx queue %d\n", i); // return rc; // } // } // rte_eth_promiscuous_enable(port); // rc = rte_eth_dev_start(port); // // save memory address of the register file // struct rte_eth_dev_info dev_info; // rte_eth_dev_info_get(port, &dev_info); // registers[port] = (uint8_t*) dev_info.pci_dev->mem_resource[0].addr; // // allow sending large and small frames // rte_eth_dev_set_mtu(port, DEFAULT_MTU); // uint32_t hlReg0 = read_reg32(port, 0x4240); // hlReg0 &= ~(1 << 10); // TXPADEN // hlReg0 |= (1 << 2); // JUMBOEN // write_reg32(port, 0x4240, hlReg0); // uint32_t tctl = read_reg32(port, 0x0400); // tctl &= ~(1 << 3); // PSP // write_reg32(port, 0x0400, tctl); // return rc; // } uint64_t get_mac_addr(int port, char* buf) { struct ether_addr addr; rte_eth_macaddr_get(port, &addr); if (buf) { sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", addr.addr_bytes[0], addr.addr_bytes[1], addr.addr_bytes[2], addr.addr_bytes[3], addr.addr_bytes[4], addr.addr_bytes[5]); } return addr.addr_bytes[0] | (addr.addr_bytes[1] << 8) | (addr.addr_bytes[2] << 16) | ((uint64_t) addr.addr_bytes[3] << 24) | ((uint64_t) addr.addr_bytes[4] << 32) | ((uint64_t) addr.addr_bytes[5] << 40); } uint32_t get_pci_id(uint8_t port) { struct rte_eth_dev_info dev_info; rte_eth_dev_info_get(port, &dev_info); return dev_info.pci_dev->id.vendor_id << 16 | dev_info.pci_dev->id.device_id; } uint8_t get_socket(uint8_t port) { struct rte_eth_dev_info dev_info; rte_eth_dev_info_get(port, &dev_info); int node = dev_info.pci_dev->numa_node; if (node == -1) { node = 0; } return (uint8_t) node; } // FIXME: doesn't support syncing between different NIC families (e.g. GbE vs. 10 GBE) // this is somewhat tricky because they use a different timer granularity void sync_clocks(uint8_t port1, uint8_t port2, uint32_t timh, uint32_t timl, uint32_t adjl, uint32_t adjh) { // resetting SYSTIML twice prevents a race-condition when SYSTIML is just about to overflow into SYSTIMH write_reg32(port1, timl, 0); write_reg32(port2, timl, 0); write_reg32(port1, timh, 0); write_reg32(port2, timh, 0); if (port1 == port2) { // just reset timers if port1 == port2 return; } volatile uint32_t* port1time = get_reg_addr(port1, timl); volatile uint32_t* port2time = get_reg_addr(port2, timl); const int num_runs = 7; // must be odd int32_t offsets[num_runs]; *port1time = 0; *port2time = 0; // the clocks now differ by offs, the time for the write access which is calculated in the following loop for (int i = 0; i < num_runs; i++) { uint32_t x1 = *port1time; uint32_t x2 = *port2time; uint32_t y1 = *port2time; uint32_t y2 = *port1time; int32_t delta_t = abs(((int64_t) x1 - x2 - ((int64_t) y2 - y1)) / 2); // time between two reads int32_t offs = delta_t + x1 - x2; offsets[i] = offs; //printf("%d: delta_t: %d\toffs: %d\n", i, delta_t, offs); } int cmp(const void* e1, const void* e2) { int32_t offs1 = *(int32_t*) e1; int32_t offs2 = *(int32_t*) e2; return offs1 < offs2 ? -1 : offs1 > offs2 ? 1 : 0; } // use the median offset qsort(offsets, num_runs, sizeof(int32_t), &cmp); int32_t offs = offsets[num_runs / 2]; if (offs) { // offs of 0 is not supported write_reg32(port2, adjl, offs < 0 ? (uint32_t) -offs : (uint32_t) offs); write_reg32(port2, adjh, offs < 0 ? 1 << 31 : 0); // verification that the clocks are synced: the two clocks should only differ by a constant caused by the read operation // i.e. x2 - x1 = y2 - y1 iff clock1 == clock2 /*uint32_t x1 = *port1time; uint32_t x2 = *port2time; uint32_t y1 = *port2time; uint32_t y2 = *port1time; printf("%d %d\n", x2 - x1, y2 - y1);*/ } } // for calibration uint32_t get_clock_difference(uint8_t port1, uint8_t port2) { // TODO: this should take the delay between reading the two registers into account // however, this is not necessary for the current use case (measuring clock drift) volatile uint32_t p1time = read_reg32(port1, IXGBE_SYSTIML); volatile uint32_t p2time = read_reg32(port2, IXGBE_SYSTIML); volatile uint32_t p1timeh = read_reg32(port1, IXGBE_SYSTIMH); volatile uint32_t p2timeh = read_reg32(port2, IXGBE_SYSTIMH); return (((int64_t) p1timeh << 32) | p1time) - (((int64_t) p2timeh << 32) | p2time); } void send_all_packets(uint8_t port_id, uint16_t queue_id, struct rte_mbuf** pkts, uint16_t num_pkts) { uint32_t sent = 0; while (1) { sent += rte_eth_tx_burst(port_id, queue_id, pkts + sent, num_pkts - sent); if (sent >= num_pkts) { return; } } return; } // software rate control static uint64_t bad_pkts_sent[RTE_MAX_ETHPORTS]; static uint64_t bad_bytes_sent[RTE_MAX_ETHPORTS]; uint64_t get_bad_pkts_sent(uint8_t port_id) { return __sync_fetch_and_and(&bad_pkts_sent[port_id], 0); } uint64_t get_bad_bytes_sent(uint8_t port_id) { return __sync_fetch_and_and(&bad_bytes_sent[port_id], 0); } // TODO: figure out which NICs can actually transmit short frames, currently tested: // NIC Min Frame Length (including CRC, preamble, SFD, and IFG, i.e. a regular Ethernet frame would be 84 bytes) // X540 76 // 82599 76 // TODO: does not yet work with jumboframe-enabled DuTs, use a different delay mechanism for this use case static struct rte_mbuf* get_delay_pkt_invalid_size(struct rte_mempool* pool, uint32_t* rem_delay) { uint32_t delay = *rem_delay; // TODO: this is actually wrong for most NICs, fix this if (delay < 25) { // smaller than the smallest packet we can send // (which is preamble + SFD + CRC + IFG + 1 byte) // the CRC cannot be avoided since the CRC offload cannot be disabled on a per-packet basis // TODO: keep a counter of the error so that the average rate is correct *rem_delay = 25; // will be set to 0 at the end of the function delay = 25; } // calculate the optimimum packet size if (delay < 84) { // simplest case: requested gap smaller than the minimum allowed size // nothing to do } else if (delay > 1542) { // includes vlan tag to play it safe // remaining delay larger than the maximum frame size if (delay >= 1543 * 2) { // we could use even larger frames but this would be annoying (chained buffers or larger mbufs required) delay = 1543; // remaining size after this packet is still > 1514 } else { // remaining size can be sent in a single packet } } else { // valid packet size, use lots of small packets if (delay - 83 < 25) { // next packet would be too small, i.e. remaining delay is between 64 and 89 bytes // this means we can just send two packets with remaining_delay/2 size delay = delay / 2; } else { delay = 83; } } *rem_delay -= delay; // TODO: consider allocating these packets at the beginning for performance reasons struct rte_mbuf* pkt = rte_pktmbuf_alloc(pool); // account for CRC offloading pkt->pkt.data_len = delay - 24; pkt->pkt.pkt_len = delay - 24; //printf("%d\n", delay - 24); return pkt; } void send_all_packets_with_delay_invalid_size(uint8_t port_id, uint16_t queue_id, struct rte_mbuf** load_pkts, uint16_t num_pkts, struct rte_mempool* pool) { const int BUF_SIZE = 128; struct rte_mbuf* pkts[BUF_SIZE]; int send_buf_idx = 0; uint32_t num_bad_pkts = 0; uint32_t num_bad_bytes = 0; for (uint16_t i = 0; i < num_pkts; i++) { struct rte_mbuf* pkt = load_pkts[i]; // desired inter-frame spacing is encoded in the hash field (not used on TX packets) // it would also be possible to use the buffer's headroom but this is ugly from Lua // TODO: this can be changed to the new userdata or udata64 fields in DPDK 1.8 uint32_t delay = pkt->pkt.hash.rss; // step 1: generate delay-packets while (delay > 0) { struct rte_mbuf* pkt = get_delay_pkt_invalid_size(pool, &delay); if (pkt) { num_bad_pkts++; // packet size: [MAC, CRC] to be consistent with HW counters num_bad_bytes += pkt->pkt.pkt_len + 4; pkts[send_buf_idx++] = pkt; } if (send_buf_idx >= BUF_SIZE) { send_all_packets(port_id, queue_id, pkts, send_buf_idx); send_buf_idx = 0; } } // step 2: send the packet pkts[send_buf_idx++] = pkt; if (send_buf_idx >= BUF_SIZE || i + 1 == num_pkts) { // don't forget to send the last batch send_all_packets(port_id, queue_id, pkts, send_buf_idx); send_buf_idx = 0; } } __sync_fetch_and_add(&bad_pkts_sent[port_id], num_bad_pkts); __sync_fetch_and_add(&bad_bytes_sent[port_id], num_bad_bytes); return; } // FIXME: not thread safe! static struct rte_mbuf* get_delay_pkt_bad_crc(struct rte_mempool* pool, uint32_t* rem_delay) { // FIXME: these should be thread-local static uint32_t target = 0; static uint32_t current = 0; uint32_t delay = *rem_delay; target += delay; if (target < current) { // don't add a delay *rem_delay = 0; return NULL; } // add delay target -= current; current = 0; if (delay < 76) { // TODO: figure out min sizes for different NICs, this is tested for X540 and 82599 // smaller than the smallest packet we can send *rem_delay = 76; // will be set to 0 at the end of the function delay = 76; } // calculate the optimimum packet size if (delay < 1538) { delay = delay; } else if (delay > 2000) { // 2000 is an arbitrary chosen value as it doesn't really matter // we just need to avoid doing something stupid for packet sizes that are just over 1538 bytes delay = 1538; } else { // delay between 1538 and 2000 delay = delay / 2; } *rem_delay -= delay; struct rte_mbuf* pkt = rte_pktmbuf_alloc(pool); // account for preamble, sfd, and ifg (CRC is disabled) pkt->pkt.data_len = delay - 20; pkt->pkt.pkt_len = delay - 20; pkt->ol_flags |= PKT_TX_NO_CRC_CSUM; current += delay; return pkt; } // NOTE: this function only works on ixgbe-based NICs as it relies on a driver modification allow disabling CRC on a per-packet basis void send_all_packets_with_delay_bad_crc(uint8_t port_id, uint16_t queue_id, struct rte_mbuf** load_pkts, uint16_t num_pkts, struct rte_mempool* pool) { const int BUF_SIZE = 128; struct rte_mbuf* pkts[BUF_SIZE]; int send_buf_idx = 0; uint32_t num_bad_pkts = 0; uint32_t num_bad_bytes = 0; for (uint16_t i = 0; i < num_pkts; i++) { struct rte_mbuf* pkt = load_pkts[i]; // desired inter-frame spacing is encoded in the hash field (not used on TX packets) // it would also be possible to use the buffer's headroom but this is ugly from Lua // TODO: this can be changed to the new userdata or udata64 fields in DPDK 1.8 uint32_t delay = pkt->pkt.hash.rss; // step 1: generate delay-packets while (delay > 0) { struct rte_mbuf* pkt = get_delay_pkt_bad_crc(pool, &delay); if (pkt) { num_bad_pkts++; // packet size: [MAC, CRC] to be consistent with HW counters num_bad_bytes += pkt->pkt.pkt_len; pkts[send_buf_idx++] = pkt; } if (send_buf_idx >= BUF_SIZE) { send_all_packets(port_id, queue_id, pkts, send_buf_idx); send_buf_idx = 0; } } // step 2: send the packet pkts[send_buf_idx++] = pkt; if (send_buf_idx >= BUF_SIZE || i + 1 == num_pkts) { // don't forget to send the last batch send_all_packets(port_id, queue_id, pkts, send_buf_idx); send_buf_idx = 0; } } // atomic as multiple threads may use the same stats register from multiple queues __sync_fetch_and_add(&bad_pkts_sent[port_id], num_bad_pkts); __sync_fetch_and_add(&bad_bytes_sent[port_id], num_bad_bytes); return; } // registers all libraries // this should be done on startup via a __attribute__((__constructor__)) function // however, there seems to be a bug: the init functions don't seem to work if called in the wrong order (note that the order depends on the linker) // calling devinitfn_bond_drv() last causes problems // so we just add them here again in an order that actually works independent from the link order void devinitfn_rte_vmxnet3_driver(); void devinitfn_rte_virtio_driver(); void devinitfn_pmd_ring_drv(); void devinitfn_rte_ixgbe_driver(); void devinitfn_rte_ixgbevf_driver(); void devinitfn_rte_i40evf_driver(); void devinitfn_rte_i40e_driver(); void devinitfn_pmd_igb_drv(); void devinitfn_pmd_igbvf_drv(); void devinitfn_em_pmd_drv(); void devinitfn_bond_drv(); void devinitfn_pmd_xenvirt_drv(); void devinitfn_pmd_pcap_drv(); void register_pmd_drivers() { devinitfn_bond_drv(); devinitfn_rte_vmxnet3_driver(); devinitfn_rte_virtio_driver(); devinitfn_pmd_ring_drv(); devinitfn_rte_ixgbevf_driver(); devinitfn_rte_ixgbe_driver(); devinitfn_rte_i40evf_driver(); devinitfn_rte_i40e_driver(); devinitfn_pmd_igb_drv(); devinitfn_pmd_igbvf_drv(); devinitfn_em_pmd_drv(); // TODO: what's wrong with these two? //devinitfn_pmd_xenvirt_drv(); //devinitfn_pmd_pcap_drv(); } // the following functions are static inline function in header files // this is the easiest/least ugly way to make them available to luajit (#defining static before including the header breaks stuff) uint16_t rte_eth_rx_burst_export(uint8_t port_id, uint16_t queue_id, void* rx_pkts, uint16_t nb_pkts) { return rte_eth_rx_burst(port_id, queue_id, rx_pkts, nb_pkts); } uint16_t rte_eth_tx_burst_export(uint8_t port_id, uint16_t queue_id, void* tx_pkts, uint16_t nb_pkts) { return rte_eth_tx_burst(port_id, queue_id, tx_pkts, nb_pkts); } void rte_pktmbuf_free_export(void* m) { rte_pktmbuf_free(m); } void rte_delay_ms_export(uint32_t ms) { rte_delay_ms(ms); } void rte_delay_us_export(uint32_t us) { rte_delay_us(us); } // This is a workaround, because lua can not do good 64bit operations. // so this function wraps the dpdk one, but is always setting the mask to all 1 int mg_rte_eth_dev_rss_reta_update ( uint8_t port, struct rte_eth_rss_reta * reta_conf ){ //printf("reta port = %u\n", port); //uint8_t i; //for(i = 0; i<128; i++){ // printf(" i = %u, reta = %u\n", i, reta_conf->reta[i]); //} reta_conf->mask_lo = 0xffffffffffffffffULL; reta_conf->mask_hi = 0xffffffffffffffffULL; return rte_eth_dev_rss_reta_update(port, reta_conf); }
''' This module corresponds to ARDroneLib/Soft/Common/navdata_common.h ''' import ctypes import functools from pyardrone.utils.structure import Structure uint8_t = ctypes.c_uint8 uint16_t = ctypes.c_uint16 uint32_t = ctypes.c_uint32 int16_t = ctypes.c_int16 int32_t = ctypes.c_int32 bool_t = ctypes.c_uint32 # ARDroneTool's bool is 4 bytes char = ctypes.c_char float32_t = ctypes.c_float NB_GYROS = 3 NB_ACCS = 3 NB_NAVDATA_DETECTION_RESULTS = 4 NB_CORNER_TRACKERS_WIDTH = 5 NB_CORNER_TRACKERS_HEIGHT = 4 DEFAULT_NB_TRACKERS_WIDTH = NB_CORNER_TRACKERS_WIDTH + 1 DEFAULT_NB_TRACKERS_HEIGHT = NB_CORNER_TRACKERS_HEIGHT + 1 NAVDATA_MAX_CUSTOM_TIME_SAVE = 20 _vector31_t = float32_t * 3 _velocities_t = _vector31_t _vector21_t = float32_t * 2 _screen_point_t = int32_t * 2 _matrix33_t = float32_t * 3 * 3 class OptionHeader(dict): def register(self, tag): return functools.partial(self._register, tag) def _register(self, tag, function): if tag in self: raise KeyError('Key {!r} conflict with existing item {}'.format( tag, self[tag])) self[tag] = function return function index = OptionHeader() class Metadata(Structure): ''' Header of :py:class:`~pyardrone.navdata.NavData`. Available via :py:class:`~pyardrone.navdata.NavData`.metadata Corresponds to C struct ``navdata_t``. ''' _pack_ = 1 _attrname = 'metadata' header = uint32_t #: Should be 0x55667788 #: raw drone state, #: see also: :py:class:`~pyardrone.navdata.states.DroneState` state = uint32_t sequence_number = uint32_t #: vision_flag = uint32_t #: class OptionHeader(Structure): _pack_ = 1 tag = uint16_t size = uint16_t @index.register(0) class Demo(OptionHeader): ''' Minimal navigation data for all flights. Corresponds to C struct ``navdata_demo_t``. ''' _attrname = 'demo' #: Flying state (landed, flying, hovering, etc.) #: defined in CTRL_STATES enum. ctrl_state = uint32_t vbat_flying_percentage = uint32_t #: battery voltage filtered (mV) theta = float32_t #: UAV's pitch in milli-degrees phi = float32_t #: UAV's roll in milli-degrees psi = float32_t #: UAV's yaw in milli-degrees altitude = int32_t #: UAV's altitude in centimeters vx = float32_t #: UAV's estimated linear velocity vy = float32_t #: UAV's estimated linear velocity vz = float32_t #: UAV's estimated linear velocity #: streamed frame index Not used -> To integrate in video stage. num_frames = uint32_t # Camera parameters compute by detection detection_camera_rot = _matrix33_t #: Deprecated ! Don't use ! detection_camera_trans = _vector31_t #: Deprecated ! Don't use ! detection_tag_index = uint32_t #: Deprecated ! Don't use ! detection_camera_type = uint32_t #: Type of tag searched in detection # Camera parameters compute by drone drone_camera_rot = _matrix33_t #: Deprecated ! Don't use ! drone_camera_trans = _vector31_t #: Deprecated ! Don't use ! @index.register(1) class Time(OptionHeader): ''' Timestamp Corresponds to C struct ``navdata_time_t``. ''' _attrname = 'time' #: 32 bit value where the 11 most significant bits represents the seconds, #: and the 21 least significant bits are the microseconds. time = uint32_t @index.register(2) class RawMeasures(OptionHeader): ''' Raw sensors measurements Corresponds to C struct ``navdata_raw_measures_t``. ''' _attrname = 'raw_measures' # +12 bytes raw_accs = uint16_t * NB_ACCS #: filtered accelerometers raw_gyros = int16_t * NB_GYROS #: filtered gyrometers raw_gyros_110 = int16_t * 2 #: gyrometers x/y 110 deg/s vbat_raw = uint32_t #: battery voltage raw (mV) us_debut_echo = uint16_t us_fin_echo = uint16_t us_association_echo = uint16_t us_distance_echo = uint16_t us_courbe_temps = uint16_t us_courbe_valeur = uint16_t us_courbe_ref = uint16_t flag_echo_ini = uint16_t # TODO: uint16_t frame_number from ARDrone_Magneto nb_echo = uint16_t sum_echo = uint32_t alt_temp_raw = int32_t gradient = int16_t @index.register(21) class PressureRaw(OptionHeader): 'Corresponds to C struct ``navdata_pressure_raw_t``.' _attrname = 'pressure_raw' up = int32_t ut = int16_t Temperature_meas = int32_t Pression_meas = int32_t @index.register(22) class Magneto(OptionHeader): 'Corresponds to C struct ``navdata_magneto_t``.' _attrname = 'magneto' mx = int16_t my = int16_t mz = int16_t magneto_raw = _vector31_t #: magneto in the body frame, in mG magneto_rectified = _vector31_t magneto_offset = _vector31_t heading_unwrapped = float32_t heading_gyro_unwrapped = float32_t heading_fusion_unwrapped = float32_t magneto_calibration_ok = char magneto_state = uint32_t magneto_radius = float32_t error_mean = float32_t error_var = float32_t @index.register(23) class WindSpeed(OptionHeader): 'Corresponds to C struct ``navdata_wind_speed_t``.' _attrname = 'wind_speed' wind_speed = float32_t #: estimated wind speed [m/s] #: estimated wind direction in North-East frame [rad] e.g. #: if wind_angle is pi/4, wind is from South-West to North-East wind_angle = float32_t wind_compensation_theta = float32_t wind_compensation_phi = float32_t state_x1 = float32_t state_x2 = float32_t state_x3 = float32_t state_x4 = float32_t state_x5 = float32_t state_x6 = float32_t magneto_debug1 = float32_t magneto_debug2 = float32_t magneto_debug3 = float32_t @index.register(24) class KalmanPressure(OptionHeader): 'Corresponds to C struct ``navdata_kalman_pressure_t``.' _attrname = 'kalman_pressure' offset_pressure = float32_t est_z = float32_t est_zdot = float32_t est_bias_PWM = float32_t est_biais_pression = float32_t offset_US = float32_t prediction_US = float32_t cov_alt = float32_t cov_PWM = float32_t cov_vitesse = float32_t bool_effet_sol = bool_t somme_inno = float32_t flag_rejet_US = bool_t u_multisinus = float32_t gaz_altitude = float32_t Flag_multisinus = bool_t Flag_multisinus_debut = bool_t @index.register(27) class Zimmu3000(OptionHeader): 'Corresponds to C struct ``navdata_zimmu_3000_t``.' _attrname = 'zimmu_3000' vzimmuLSB = int32_t vzfind = float32_t @index.register(3) class PhysMeasures(OptionHeader): 'Corresponds to C struct ``navdata_phys_measures_t``.' _attrname = 'phys_measures' accs_temp = float32_t gyro_temp = uint16_t phys_accs = float32_t * NB_ACCS phys_gyros = float32_t * NB_GYROS alim3V3 = uint32_t #: 3.3volt alim [LSB] vrefEpson = uint32_t #: ref volt Epson gyro [LSB] vrefIDG = uint32_t #: ref volt IDG gyro [LSB] @index.register(4) class GyrosOffsets(OptionHeader): 'Corresponds to C struct ``navdata_gyros_offsets_t``.' _attrname = 'gyros_offsets' offset_g = float32_t * NB_GYROS @index.register(5) class EulerAngles(OptionHeader): 'Corresponds to C struct ``navdata_euler_angles_t``.' _attrname = 'eular_angles' theta_a = float32_t phi_a = float32_t @index.register(6) class References(OptionHeader): 'Corresponds to C struct ``navdata_references_t``.' _attrname = 'references' ref_theta = int32_t ref_phi = int32_t ref_theta_I = int32_t ref_phi_I = int32_t ref_pitch = int32_t ref_roll = int32_t ref_yaw = int32_t ref_psi = int32_t vx_ref = float32_t vy_ref = float32_t theta_mod = float32_t phi_mod = float32_t k_v_x = float32_t k_v_y = float32_t k_mode = uint32_t ui_time = float32_t ui_theta = float32_t ui_phi = float32_t ui_psi = float32_t ui_psi_accuracy = float32_t ui_seq = int32_t @index.register(7) class Trims(OptionHeader): 'Corresponds to C struct ``navdata_trims_t``.' _attrname = 'trims' angular_rates_trim_r = float32_t euler_angles_trim_theta = float32_t euler_angles_trim_phi = float32_t @index.register(8) class RcReferences(OptionHeader): 'Corresponds to C struct ``navdata_rc_references_t``.' _attrname = 'rc_references' rc_ref_pitch = int32_t rc_ref_roll = int32_t rc_ref_yaw = int32_t rc_ref_gaz = int32_t rc_ref_ag = int32_t @index.register(9) class Pwm(OptionHeader): 'Corresponds to C struct ``navdata_pwm_t``.' _attrname = 'pwm' motor1 = uint8_t motor2 = uint8_t motor3 = uint8_t motor4 = uint8_t sat_motor1 = uint8_t sat_motor2 = uint8_t sat_motor3 = uint8_t sat_motor4 = uint8_t gaz_feed_forward = float32_t gaz_altitude = float32_t altitude_integral = float32_t vz_ref = float32_t u_pitch = int32_t u_roll = int32_t u_yaw = int32_t yaw_u_I = float32_t u_pitch_planif = int32_t u_roll_planif = int32_t u_yaw_planif = int32_t u_gaz_planif = float32_t current_motor1 = uint16_t current_motor2 = uint16_t current_motor3 = uint16_t current_motor4 = uint16_t # WARNING: new navdata (FC 26/07/2011) altitude_prop = float32_t altitude_der = float32_t @index.register(10) class Altitude(OptionHeader): 'Corresponds to C struct ``navdata_altitude_t``.' _attrname = 'altitude' altitude_vision = int32_t altitude_vz = float32_t altitude_ref = int32_t altitude_raw = int32_t obs_accZ = float32_t obs_alt = float32_t obs_x = _vector31_t obs_state = uint32_t est_vb = _vector21_t est_state = uint32_t @index.register(11) class VisionRaw(OptionHeader): 'Corresponds to C struct ``navdata_vision_raw_t``.' _attrname = 'vision_raw' vision_tx_raw = float32_t vision_ty_raw = float32_t vision_tz_raw = float32_t @index.register(13) class Vision(OptionHeader): 'Corresponds to C struct ``navdata_vision_t``.' _attrname = 'vision' vision_state = uint32_t vision_misc = int32_t vision_phi_trim = float32_t vision_phi_ref_prop = float32_t vision_theta_trim = float32_t vision_theta_ref_prop = float32_t new_raw_picture = int32_t theta_capture = float32_t phi_capture = float32_t psi_capture = float32_t altitude_capture = int32_t time_capture = uint32_t #: time in TSECDEC format (see config.h) body_v = _velocities_t delta_phi = float32_t delta_theta = float32_t delta_psi = float32_t gold_defined = uint32_t gold_reset = uint32_t gold_x = float32_t gold_y = float32_t @index.register(14) class VisionPerf(OptionHeader): 'Corresponds to C struct ``navdata_vision_perf_t``.' _attrname = 'vision_perf' time_szo = float32_t time_corners = float32_t time_compute = float32_t time_tracking = float32_t time_trans = float32_t time_update = float32_t time_custom = float32_t * NAVDATA_MAX_CUSTOM_TIME_SAVE @index.register(15) class TrackersSend(OptionHeader): 'Corresponds to C struct ``navdata_trackers_send_t``.' _attrname = 'trackers_send' locked = int32_t * (DEFAULT_NB_TRACKERS_WIDTH * DEFAULT_NB_TRACKERS_HEIGHT) point = _screen_point_t * ( DEFAULT_NB_TRACKERS_WIDTH * DEFAULT_NB_TRACKERS_HEIGHT ) @index.register(16) class VisionDetect(OptionHeader): 'Corresponds to C struct ``navdata_vision_detect_t``.' # Change the function 'navdata_server_reset_vision_detect()' # if this structure is modified _attrname = 'vision_detect' nb_detected = uint32_t type = uint32_t * NB_NAVDATA_DETECTION_RESULTS xc = uint32_t * NB_NAVDATA_DETECTION_RESULTS yc = uint32_t * NB_NAVDATA_DETECTION_RESULTS width = uint32_t * NB_NAVDATA_DETECTION_RESULTS height = uint32_t * NB_NAVDATA_DETECTION_RESULTS dist = uint32_t * NB_NAVDATA_DETECTION_RESULTS orientation_angle = float32_t * NB_NAVDATA_DETECTION_RESULTS rotation = _matrix33_t * NB_NAVDATA_DETECTION_RESULTS translation = _vector31_t * NB_NAVDATA_DETECTION_RESULTS camera_source = uint32_t * NB_NAVDATA_DETECTION_RESULTS @index.register(12) class VisionOf(OptionHeader): 'Corresponds to C struct ``navdata_vision_of_t``.' _attrname = 'vision_of' of_dx = float32_t * 5 of_dy = float32_t * 5 @index.register(17) class Watchdog(OptionHeader): 'Corresponds to C struct ``navdata_watchdog_t``.' _attrname = 'watchdog' # +4 bytes watchdog = int32_t @index.register(18) class AdcDataFrame(OptionHeader): 'Corresponds to C struct ``navdata_adc_data_frame_t``.' _attrname = 'adc_data_frame' version = uint32_t data_frame = uint8_t * 32 @index.register(19) class VideoStream(OptionHeader): 'Corresponds to C struct ``navdata_video_stream_t``.' _attrname = 'video_stream' quant = uint8_t #: quantizer reference used to encode frame [1:31] frame_size = uint32_t #: frame size (bytes) frame_number = uint32_t #: frame index atcmd_ref_seq = uint32_t #: atmcd ref sequence number #: mean time between two consecutive atcmd_ref (ms) atcmd_mean_ref_gap = uint32_t atcmd_var_ref_gap = float32_t atcmd_ref_quality = uint32_t #: estimator of atcmd link quality # drone2 #: measured out throughput from the video tcp socket out_bitrate = uint32_t #: last frame size generated by the video encoder desired_bitrate = uint32_t # misc temporary data data1 = int32_t data2 = int32_t data3 = int32_t data4 = int32_t data5 = int32_t # queue usage tcp_queue_level = uint32_t fifo_queue_level = uint32_t @index.register(25) class HdvideoStream(OptionHeader): 'Corresponds to C struct ``navdata_hdvideo_stream_t``.' _attrname = 'hdvideo_stream' hdvideo_state = uint32_t storage_fifo_nb_packets = uint32_t storage_fifo_size = uint32_t usbkey_size = uint32_t #: USB key in kbytes - 0 if no key present #: USB key free space in kbytes - 0 if no key present usbkey_freespace = uint32_t #: 'frame_number' PaVE field of the frame starting to be encoded for the #: HD stream frame_number = uint32_t usbkey_remaining_time = uint32_t #: time in seconds @index.register(20) class Games(OptionHeader): 'Corresponds to C struct ``navdata_games_t``.' _attrname = 'games' double_tap_counter = uint32_t finish_line_counter = uint32_t @index.register(26) class Wifi(OptionHeader): 'Corresponds to C struct ``navdata_wifi_t``.' _attrname = 'wifi' link_quality = uint32_t @index.register(0xFFFF) class Cks(OptionHeader): 'Corresponds to C struct ``navdata_cks_t``.' _attrname = 'cks' value = uint32_t #: Value of the checksum
#pragma once #include <string> #include <functional> #include <net/asio/http/uri.h> namespace net { namespace http { /** * Represents an endpoint with distinct connection * characteristics. * * Details may include: * * Hostname, IP or vhost * * Port * * SSL certificate */ class details { public: details( const net::http::uri &u ):host_{ u.host() }, port_{ u.port() }, tls_{ u.scheme() == "https" } { // std::cout << " hd => " << string() << "\n"; } details() = delete; virtual ~details() { // std::cout << "~hd\n"; } /** Our hashing function is currently based on the stringified value */ class hash { public: std::size_t operator()(details const &hd) const { return std::hash<std::string>()(hd.string()); } }; /** Equality operator is, again, based on stringified value */ class equal { public: bool operator()(details const &src, details const &dst) const { return src.string() == dst.string(); } }; /** * Stringified value for this endpoint. * Currently takes the form host:port */ std::string string() const { return (tls_ ? "https://" : "http://") + host_ + std::string { ":" } + std::to_string(port_); } const std::string &host() const { return host_; } uint16_t port() const { return port_; } bool tls() const { return tls_; } private: std::string host_; uint16_t port_; bool tls_; }; }; };
const express = require("express"); const app = express(); app.set('port', (process.env.PORT || 3000)); const getData = require('./src/server/api/getData'); const setup = require('./src/server/api/setupApi'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use('/assets', express.static('build')); app.use('/', require('./src/server/routers/index')); app.get('/api/:chrom', getData); const server = app.listen(app.get('port')); setup(server);
.slideshow { position: relative; float: left; } .slideshow__item { position: absolute; top: 0; left: 0; right: 0; width: 100%; } .slideshow__prev, .slideshow__next { position: absolute; top: 0; bottom: 0; } .slideshow__prev { left: 0; right: 50%; } .slideshow__prev:hover { background: rgba(0,0,0,0.2); background: -moz-linear-gradient(left, rgba(0,0,0,0.2) 0%, rgba(231,56,39,0) 100%); background: -webkit-gradient(left top, right top, color-stop(0%, rgba(0,0,0,0.2)), color-stop(100%, rgba(231,56,39,0))); background: -webkit-linear-gradient(left, rgba(0,0,0,0.2) 0%, rgba(231,56,39,0) 100%); background: -o-linear-gradient(left, rgba(0,0,0,0.2) 0%, rgba(231,56,39,0) 100%); background: -ms-linear-gradient(left, rgba(0,0,0,0.2) 0%, rgba(231,56,39,0) 100%); background: linear-gradient(to right, rgba(0,0,0,0.2) 0%, rgba(231,56,39,0) 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#000000', endColorstr='#e73827', GradientType=1 ); } .slideshow__next { left: 50%; right: 0; } .slideshow__next:hover { background: rgba(231,56,39,0); background: -moz-linear-gradient(left, rgba(231,56,39,0) 0%, rgba(231,56,39,0) 0%, rgba(0,0,0,0.2) 100%); background: -webkit-gradient(left top, right top, color-stop(0%, rgba(231,56,39,0)), color-stop(0%, rgba(231,56,39,0)), color-stop(100%, rgba(0,0,0,0.2))); background: -webkit-linear-gradient(left, rgba(231,56,39,0) 0%, rgba(231,56,39,0) 0%, rgba(0,0,0,0.2) 100%); background: -o-linear-gradient(left, rgba(231,56,39,0) 0%, rgba(231,56,39,0) 0%, rgba(0,0,0,0.2) 100%); background: -ms-linear-gradient(left, rgba(231,56,39,0) 0%, rgba(231,56,39,0) 0%, rgba(0,0,0,0.2) 100%); background: linear-gradient(to right, rgba(231,56,39,0) 0%, rgba(231,56,39,0) 0%, rgba(0,0,0,0.2) 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e73827', endColorstr='#000000', GradientType=1 ); } .slideshow__dots { position: absolute; bottom: 0; left: 0; right: 0; height: 30px; text-align: center; } .slideshow__dot { display: inline-block; width: 10px; height: 10px; margin: 0 5px; border-radius: 50%; background-color: #fff; cursor: pointer; } .slideshow__dot.active { background-color: #606060; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace N64Track { public static class CustomFontEffect { public static readonly BindableProperty FontFileNameProperty = BindableProperty.CreateAttached("FontFileName", typeof(string), typeof(CustomFontEffect), "", propertyChanged: OnFileNameChanged); public static string GetFontFileName(BindableObject view) { return (string)view.GetValue(FontFileNameProperty); } /// <summary> /// Set Font binding based on File Name provided /// </summary> /// <param name="view"></param> /// <param name="value"></param> public static void SetFontFileName(BindableObject view, string value) { view.SetValue(FontFileNameProperty, value); } static void OnFileNameChanged(BindableObject bindable, object oldValue, object newValue) { var view = bindable as View; if (view == null) { return; } view.Effects.Add(new FontEffect()); } class FontEffect : RoutingEffect { public FontEffect() : base("Xamarin.FontEffect") { } } } }
#### 函数 ```js function add(x, y) { return x + y } // arrow function const add = (x, y) => x + y const setDetail = (name, age) => ({ name, age }) setDetail('lizhuo', 24) // { name: 'lizhuo', age:24 } function add(y, x = 5) { return x + y } ```
CREATE TABLE Users( User_ID SERIAL NOT NULL PRIMARY KEY, Username VARCHAR(32) NOT NULL, Password VARCHAR(60) NOT NULL, Email VARCHAR(60) NOT NULL );
package com.jetbrains.ther.lexer; import com.google.common.collect.ImmutableMap; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.jetbrains.ther.psi.TheRElementType; //deprecated // DO NOT USE public class TheRTokenTypes { /* * There are five types of constants: integer, logical, numeric, complex and string. */ // integer constants public static final IElementType INTEGER_LITERAL = new TheRElementType("INTEGER_LITERAL"); // logical constants public static final IElementType TRUE_KEYWORD = new TheRElementType("TRUE_KEYWORD"); public static final IElementType FALSE_KEYWORD = new TheRElementType("FALSE_KEYWORD"); // numeric constants public static final IElementType NUMERIC_LITERAL = new TheRElementType("NUMERIC_LITERAL"); // complex constants public static final IElementType COMPLEX_LITERAL = new TheRElementType("COMPLEX_LITERAL"); // string constants public static final IElementType STRING_LITERAL = new TheRElementType("STRING_LITERAL"); /* * In addition, there are four special constants */ public static final IElementType NULL_KEYWORD = new TheRElementType("NULL_KEYWORD"); // empty object public static final IElementType INF_KEYWORD = new TheRElementType("INF_KEYWORD"); // infinity public static final IElementType NAN_KEYWORD = new TheRElementType("NAN_KEYWORD"); // not-a-number in the IEEE floating point calculus (results of the operations respectively 1/0 and 0/0, for instance). public static final IElementType NA_KEYWORD = new TheRElementType("NA_KEYWORD"); // absent (“Not Available”) data values /* The following identifiers have a special meaning and cannot be used for object names if else repeat while function for in next break TRUE FALSE NULL Inf NaN NA NA_integer_ NA_real_ NA_complex_ NA_character_ ... ..1 ..2 etc. */ // keywords public static final IElementType NA_INTEGER_KEYWORD = new TheRElementType("NA_INTEGER_KEYWORD"); public static final IElementType NA_REAL_KEYWORD = new TheRElementType("NA_REAL_KEYWORD"); public static final IElementType NA_COMPLEX_KEYWORD = new TheRElementType("NA_COMPLEX_KEYWORD"); public static final IElementType NA_CHARACTER_KEYWORD = new TheRElementType("NA_CHARACTER_KEYWORD"); public static final IElementType TRIPLE_DOTS = new TheRElementType("TRIPLE_DOTS"); public static final IElementType IF_KEYWORD = new TheRElementType("IF_KEYWORD"); public static final IElementType ELSE_KEYWORD = new TheRElementType("ELSE_KEYWORD"); public static final IElementType REPEAT_KEYWORD = new TheRElementType("REPEAT_KEYWORD"); public static final IElementType WHILE_KEYWORD = new TheRElementType("WHILE_KEYWORD"); public static final IElementType FUNCTION_KEYWORD = new TheRElementType("FUNCTION_KEYWORD"); public static final IElementType FOR_KEYWORD = new TheRElementType("FOR_KEYWORD"); public static final IElementType IN_KEYWORD = new TheRElementType("IN_KEYWORD"); public static final IElementType NEXT_KEYWORD = new TheRElementType("NEXT_KEYWORD"); public static final IElementType BREAK_KEYWORD = new TheRElementType("BREAK_KEYWORD"); /* R contains a number of operators. They are listed in the table below. - Minus, can be unary or binary + Plus, can be unary or binary ! Unary not ~ Tilde, used for model formulae, can be either unary or binary ? Help : Sequence, binary (in model formulae: interaction) * Multiplication, binary / Division, binary ^ Exponentiation, binary %x% Special binary operators, x can be replaced by any valid name %% Modulus, binary %/% Integer divide, binary %*% Matrix product, binary %o% Outer product, binary %x% Kronecker product, binary %in% Matching operator, binary (in model formulae: nesting) < Less than, binary > Greater than, binary == Equal to, binary >= Greater than or equal to, binaryChapter 3: Evaluation of expressions 11 <= Less than or equal to, binary & And, binary, vectorized && And, binary, not vectorized | Or, binary, vectorized || Or, binary, not vectorized <- Left assignment, binary -> Right assignment, binary $ List subset, binary */ public static final IElementType MINUS = new TheRElementType("MINUS"); // - public static final IElementType PLUS = new TheRElementType("PLUS"); // + public static final IElementType NOT = new TheRElementType("NOT"); // ! public static final IElementType TILDE = new TheRElementType("TILDE"); // ~ public static final IElementType HELP = new TheRElementType("HELP"); // ? public static final IElementType COLON = new TheRElementType("COLON"); // : public static final IElementType MULT = new TheRElementType("MULT"); // * public static final IElementType DIV = new TheRElementType("DIV"); // / public static final IElementType EXP = new TheRElementType("EXP"); // ^ public static final IElementType MODULUS = new TheRElementType("MODULUS"); // %% public static final IElementType INT_DIV = new TheRElementType("INT_DIV"); // %/% public static final IElementType MATRIX_PROD = new TheRElementType("MATRIX_PROD"); // %*% public static final IElementType OUTER_PROD = new TheRElementType("OUTER_PROD"); // %o% public static final IElementType MATCHING = new TheRElementType("MATCHING"); // %in% public static final IElementType KRONECKER_PROD = new TheRElementType("MATCHING"); // %x% public static final IElementType INFIX_OP = new TheRElementType("INFIX_OP"); // %{character}+% public static final IElementType LT = new TheRElementType("LT"); // < public static final IElementType GT = new TheRElementType("GT"); // > public static final IElementType EQEQ = new TheRElementType("EQEQ"); // == public static final IElementType GE = new TheRElementType("GE"); // >= public static final IElementType LE = new TheRElementType("LE"); // <= public static final IElementType AND = new TheRElementType("AND"); // & public static final IElementType ANDAND = new TheRElementType("ANDAND"); // && public static final IElementType OR = new TheRElementType("OR"); // | public static final IElementType OROR = new TheRElementType("OROR"); // || public static final IElementType LEFT_ASSIGN = new TheRElementType("LEFT_ASSIGN"); // <- public static final IElementType RIGHT_ASSIGN = new TheRElementType("RIGHT_ASSIGN"); // -> public static final IElementType LIST_SUBSET = new TheRElementType("LIST_SUBSET"); // $ public static final IElementType TICK = new TheRElementType("TICK"); // ` public static final IElementType AT = new TheRElementType("AT"); // @ public static final IElementType DOUBLECOLON = new TheRElementType("DOUBLECOLON"); // :: public static final IElementType TRIPLECOLON = new TheRElementType("TRIPLECOLON"); // ::: public static final IElementType NOTEQ = new TheRElementType("NOTEQ"); // != public static final IElementType RIGHT_COMPLEX_ASSING = new TheRElementType("RIGHT_COMPLEX_ASSING"); // ->> public static final IElementType LEFT_COMPLEX_ASSING = new TheRElementType("LEFT_COMPLEX_ASSING"); // <<- public static final IElementType LPAR = new TheRElementType("LPAR"); // ( public static final IElementType RPAR = new TheRElementType("RPAR"); // ) public static final IElementType LBRACKET = new TheRElementType("LBRACKET"); // [ public static final IElementType LDBRACKET = new TheRElementType("LDBRACKET"); // [[ public static final IElementType RBRACKET = new TheRElementType("RBRACKET"); // ] public static final IElementType RDBRACKET = new TheRElementType("RDBRACKET"); // ]] public static final IElementType LBRACE = new TheRElementType("LBRACE"); // { public static final IElementType RBRACE = new TheRElementType("RBRACE"); // } public static final IElementType COMMA = new TheRElementType("COMMA"); // , public static final IElementType DOT = new TheRElementType("DOT"); // . public static final IElementType EQ = new TheRElementType("EQ"); // = public static final IElementType SEMICOLON = new TheRElementType("SEMICOLON"); // ; public static final IElementType UNDERSCORE = new TheRElementType("UNDERSCORE"); // _ public static final IElementType BAD_CHARACTER = TokenType.BAD_CHARACTER; public static final IElementType IDENTIFIER = new TheRElementType("IDENTIFIER"); public static final IElementType LINE_BREAK = new TheRElementType("LINE_BREAK"); public static final IElementType SPACE = new TheRElementType("SPACE"); public static final IElementType TAB = new TheRElementType("TAB"); public static final IElementType FORMFEED = new TheRElementType("FORMFEED"); public static final IElementType END_OF_LINE_COMMENT = new TheRElementType("END_OF_LINE_COMMENT"); public static final TokenSet RESERVED_WORDS = TokenSet .create(IF_KEYWORD, ELSE_KEYWORD, REPEAT_KEYWORD, WHILE_KEYWORD, FUNCTION_KEYWORD, FOR_KEYWORD, IN_KEYWORD, NEXT_KEYWORD, BREAK_KEYWORD); public static final TokenSet ASSIGNMENTS = TokenSet.create(LEFT_ASSIGN, LEFT_COMPLEX_ASSING, RIGHT_ASSIGN, RIGHT_COMPLEX_ASSING, EQ); public static final TokenSet LEFT_ASSIGNMENTS = TokenSet.create(LEFT_ASSIGN, LEFT_COMPLEX_ASSING, EQ); public static final TokenSet RIGHT_ASSIGNMENTS = TokenSet.create(RIGHT_ASSIGN, RIGHT_COMPLEX_ASSING); public static final TokenSet OPERATORS = TokenSet .create(MINUS, PLUS, NOT, TILDE, HELP, COLON, MULT, DIV, EXP, MODULUS, INT_DIV, MATRIX_PROD, OUTER_PROD, MATCHING, KRONECKER_PROD, INFIX_OP, LT, GT, EQEQ, GE, LE, AND, ANDAND, OR, OROR, LEFT_ASSIGN, RIGHT_ASSIGN, LIST_SUBSET, AT, TICK); public static final TokenSet KEYWORDS = TokenSet.create(NA_INTEGER_KEYWORD, NA_REAL_KEYWORD, NA_COMPLEX_KEYWORD, NA_CHARACTER_KEYWORD, TRIPLE_DOTS, IF_KEYWORD, ELSE_KEYWORD, REPEAT_KEYWORD, WHILE_KEYWORD, FUNCTION_KEYWORD, FOR_KEYWORD, IN_KEYWORD, NEXT_KEYWORD, BREAK_KEYWORD); public static final TokenSet STATEMENT_START_TOKENS = TokenSet.create(IF_KEYWORD, WHILE_KEYWORD, FOR_KEYWORD, REPEAT_KEYWORD, BREAK_KEYWORD, NEXT_KEYWORD, LBRACE, FUNCTION_KEYWORD, HELP); public static final TokenSet COMPARISON_OPERATIONS = TokenSet.create(LT, GT, EQEQ, GE, LE, NOTEQ, MATCHING); public static final TokenSet NA_KEYWORDS = TokenSet.create(NA_KEYWORD, NA_CHARACTER_KEYWORD, NA_COMPLEX_KEYWORD, NA_INTEGER_KEYWORD, NA_REAL_KEYWORD); public static final TokenSet ADDITIVE_OPERATIONS = TokenSet.create(PLUS, MINUS); public static final TokenSet MULTIPLICATIVE_OPERATIONS = TokenSet.create(MULT, DIV, INT_DIV, MATRIX_PROD, KRONECKER_PROD, OUTER_PROD); public static final TokenSet POWER_OPERATIONS = TokenSet.create(EXP, MODULUS); public static final TokenSet UNARY_OPERATIONS = TokenSet.create(PLUS, MINUS, TILDE, NOT); public static final TokenSet EQUALITY_OPERATIONS = TokenSet.create(EQEQ, NOTEQ); public static final TokenSet OR_OPERATIONS = TokenSet.create(OR, OROR); public static final TokenSet AND_OPERATIONS = TokenSet.create(AND, ANDAND); public static final TokenSet SPECIAL_CONSTANTS = TokenSet.create(NA_KEYWORD, NAN_KEYWORD, INF_KEYWORD, NULL_KEYWORD, TRUE_KEYWORD, FALSE_KEYWORD); public static final TokenSet WHITESPACE_OR_LINEBREAK = TokenSet.create(SPACE, TAB, FORMFEED, LINE_BREAK); public static final TokenSet WHITESPACE = TokenSet.create(SPACE, TAB, FORMFEED); public static final TokenSet OPEN_BRACES = TokenSet.create(LBRACKET, LDBRACKET, LBRACE, LPAR); public static final TokenSet CLOSE_BRACES = TokenSet.create(RBRACKET, RDBRACKET, RBRACE, RPAR); public static final TokenSet OPEN_BRACKETS = TokenSet.create(LBRACKET, LDBRACKET); public static final ImmutableMap<IElementType, IElementType> BRACKER_PAIRS = ImmutableMap.<IElementType, IElementType>builder().put(LBRACKET, RBRACKET).put(LDBRACKET, RDBRACKET).build(); public static final TokenSet NAMESPACE_ACCESS = TokenSet.create(DOUBLECOLON, TRIPLECOLON); }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Category Schema */ var CategorySchema = new Schema({ name: { type: String, default: '', required: 'Please fill Category name', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Category', CategorySchema);
import Configuration = require('../../../lib/Configuration'); import overrides = require('../../../lib/overrides/all'); import Rule = require('../../../lib/Rule'); import s = require('../../../lib/helpers/string'); import sinonChai = require('../../sinon-chai'); var expect = sinonChai.expect; // ReSharper disable WrongExpressionStatement describe('overrides', () => { var config = new Configuration(); describe('background', () => { it('generates shorthand declaration for provided properties', () => { var result = overrides.background({ attachment: 'a', clip: 'c1', color: 'c2', image: 'i', origin: 'o', position: 'p', repeat: 'r', size: 's' })(config); expect(result).to.deep.equal([ ['background', 'a c1 c2 i o p r s'] ]); result = overrides.background({ clip: 'c1', image: 'i', repeat: 'r', size: 's' })(config); expect(result).to.deep.equal([ ['background', 'c1 i r s'] ]); }); it('generates no declarations when no options are provided', () => { var result = overrides.background()(config); expect(result).to.be.empty; }); }); describe('clearfix', () => { it('generates clearfix declarations inside :after pseudo-selector', () => { var rule = new Rule('foo', { clearfix: true }); expect(rule.resolve(config)).to.deep.equal([ [['foo:after'], [ ['content', s.repeat(config.quote, 2)], ['display', 'table'], ['clear', 'both'] ]] ]); }); it('generates no declarations when value is false', () => { expect(overrides.clearfix(false)(config)).to.be.empty; }); }); describe('fill', () => { it('generates fill declarations when value is true', () => { expect(overrides.fill(true)(config)).to.deep.equal([ ['position', 'absolute'], ['top', '0'], ['right', '0'], ['bottom', '0'], ['left', '0'] ]); }); it('generates no declarations when value is false', () => { expect(overrides.fill(false)(config)).to.be.empty; }); }); });
// CVDemo.Image.Overlay.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/videoio.hpp> #include <opencv2/video.hpp> #include <stdio.h> #include <sstream> #include <stdexcept> // #include <boost/program_options.hpp> // #include <boost/filesystem.hpp> #include "CVDemo.Image.ProgramOptions.hpp" #include "CVDemo.Image.OverlayProcessor.hpp" // temporary #include <Windows.h> using namespace cv; using namespace std; using namespace cvdemo::image; // namespace po = boost::program_options; // using namespace boost::filesystem; // temporary vector<string> get_all_file_names_within_folder(string folder) { vector<string> names; // ???? string search_path = folder + "/*.png"; WIN32_FIND_DATAA fd; HANDLE hFind = ::FindFirstFileA(search_path.c_str(), &fd); // ???? if (hFind != INVALID_HANDLE_VALUE) { do { // read all (real) files in current folder // , delete '!' read other 2 default folder . and .. if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { // names.push_back(fd.cFileName); // ???? names.push_back(folder + "/" + fd.cFileName); // ???? } } while (::FindNextFileA(hFind, &fd)); ::FindClose(hFind); } //for (auto i = directory_iterator(folder); i != directory_iterator(); i++) //{ // if (!is_directory(i->path())) // { // names.push_back(i->path().filename().string()); // } //} return names; } int main(int argc, const char* argv[]) { // testing... string configFile = "../cvdemo.image.overlay.cfg"; ProgramOptions options = ProgramOptions(argc, argv, configFile); if (options.IsForUsageInfo()) { options.DisplayUsageInfo(cout); system("pause"); return -1; } if (options.IsForVersionInfo()) { cout << "Version = 0.0.1" << endl; system("pause"); return -1; } if (options.IsForOptionsDisplay()) { options.DisplayInputOptions(cout); system("pause"); return -1; } if (!options.IsValid()) { cerr << ">>> Invalid input options." << endl; options.DisplayUnrecognizedArgs(cerr); options.DisplayOutputImageType(cerr); options.DisplayForegroundImageFile(cerr); options.DisplayForegroundImageFolder(cerr); options.DisplayBackgroundImageFile(cerr); options.DisplayBackgroundImageFolder(cerr); options.DisplayOutputImageFolder(cerr); options.DisplayUsageInfo(cerr); system("pause"); return EXIT_FAILURE; } if (options.GetForegroundImageFile() != "" && options.GetBackgroundImageFile() != "") { OverlayProcessor::overlayImages(options.GetForegroundImageFile(), options.GetBackgroundImageFile(), options.GetOutputImageFolder()); } else { if (options.GetForegroundImageFolder() != "" && options.GetBackgroundImageFile() != "") { auto fgFolder = options.GetForegroundImageFolder(); vector<string> fgFiles = get_all_file_names_within_folder(fgFolder); OverlayProcessor::overlayImages(fgFiles, options.GetBackgroundImageFile(), options.GetOutputImageFolder()); } else if (options.GetForegroundImageFile() != "" && options.GetBackgroundImageFolder() != "") { auto bgFolder = options.GetBackgroundImageFolder(); vector<string> bgFiles = get_all_file_names_within_folder(bgFolder); OverlayProcessor::overlayImages(options.GetForegroundImageFile(), bgFiles, options.GetOutputImageFolder()); } else { // ???? } } system("pause"); return EXIT_SUCCESS; }
#/bin/bash BASE=$(dirname $0) export PYTHONPATH=$PYTHONPATH:$BASE/../scripts/:$BASE/../ python3 $BASE/args.py
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>My First React App With Create-React-App tool</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html>
<?php // autoload_real.php generated by Composer class ComposerAutoloaderInite79f08d1f5e17ddf5b6a007e748fcd03 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInite79f08d1f5e17ddf5b6a007e748fcd03', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInite79f08d1f5e17ddf5b6a007e748fcd03', 'loadClassLoader')); $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } $loader->register(true); $includeFiles = require __DIR__ . '/autoload_files.php'; foreach ($includeFiles as $file) { require $file; } return $loader; } }
# Defining middleware All middleware is defined in files under the `src/support/middleware` path. If you write your own middleware it should also be stored under this path. Each middleware file is expected to expose a single _initializer_ function which, when called, will return a generator function which is the actual middleware function. For example: ```javascript // file: <project folder>/src/support/middleware/example.js module.exports = function(App, options) { return function*(next) { // do nothing and pass through yield next; }; }; ``` The above middleware doesn't do anything and simply passes control to the next handler in the current request's middleware chain. If we wanted to catch and handle any errors thrown by subsequent handlers in the chain we could do: ```javascript module.exports = function(App, options) { return function*(next) { try { yield next; } catch (err) { console.error(err); } }; }; ``` Middleware functions in Waigo work in the same way as ones in Koa, in that they have a defined context and associated `request` and `response` objects: ```javascript module.exports = function(App, options) { return function*(next) { console.log(`URL: ${this.request.url}`); this.response.body = 'Hello world!'; }; }; ``` Thus, existing Koa middleware functions can be re-used very easily within Waigo. ## App object Middleware functions in Waigo also have access to your application's `App` object, which is set on the context as well as being passed in during the construction phase: ```javascript module.exports = function(App, options) { return function*(next) { console.log(`Running in mode: ${this.App.config.mode}`); yield next; }; }; ```
using System; using System.Diagnostics.CodeAnalysis; using SFA.DAS.EmployerUsers.Application.Commands.ActivateUser; using SFA.DAS.EmployerUsers.Domain; namespace SFA.DAS.EmployerUsers.Application.UnitTests.CommandsTests.ActivateUserTests.ActivateUserCommandValidatorTests { [ExcludeFromCodeCoverage] public class ActivateUserCommandBuilder { private string _accessCode = "AccessCode"; private string _userId = Guid.NewGuid().ToString(); private User _user; public ActivateUserCommandBuilder WithAccessCode(string code) { _accessCode = code; return this; } public ActivateUserCommandBuilder WithValidUser() { _user = new User { SecurityCodes = new[] { new SecurityCode { Code = "ACCESSCODE", CodeType = SecurityCodeType.AccessCode, ExpiryTime = DateTime.MaxValue } } }; return this; } public ActivateUserCommandBuilder WithNullAccessCode() { _accessCode = null; return this; } public ActivateUserCommand Build() { return new ActivateUserCommand { AccessCode = _accessCode, UserId = _userId, User = _user }; } } }
#include "texture.h" using namespace gl; /** * Constructs a new Texture object, storing the specified textureID for binding * @param textureID the Integer representing the texture that can be bound */ Texture::Texture(std::string associatedFileName, gl::GLuint textureID) : textureID(textureID), associatedFileName(associatedFileName) { } /** * Binds the texture using GL11. The texture will remain bound until the next bind() call of a different * texture object, or manual call to GL11.glBindTexture(...) */ void Texture::bind() { glBindTexture(GL_TEXTURE_2D, textureID); }
package hammer import ( "context" "log" "github.com/antihax/evedata/internal/datapackages" ) func init() { registerConsumer("killmail", killmailConsumer) } func killmailConsumer(s *Hammer, parameter interface{}) { parameters := parameter.([]interface{}) hash := parameters[0].(string) id := int32(parameters[1].(int)) known := s.inQueue.CheckWorkCompleted("evedata_known_kills", id) if known { return } kill, _, err := s.esi.ESI.KillmailsApi.GetKillmailsKillmailIdKillmailHash(context.Background(), hash, id, nil) if err != nil { log.Println(err) return } s.inQueue.SetWorkCompleted("evedata_known_kills", id) if err != nil { log.Println(err) return } // Send out the result, but ignore DUST stuff. if kill.Victim.ShipTypeId < 65535 { err = s.QueueResult(&datapackages.Killmail{Hash: hash, Kill: kill}, "killmail") if err != nil { log.Println(err) return } } err = s.AddCharacter(kill.Victim.CharacterId) if err != nil { log.Println(err) return } err = s.AddAlliance(kill.Victim.AllianceId) if err != nil { log.Println(err) return } err = s.AddCorporation(kill.Victim.CorporationId) if err != nil { log.Println(err) return } for _, a := range kill.Attackers { err = s.AddCharacter(a.CharacterId) if err != nil { log.Println(err) return } err = s.AddAlliance(a.AllianceId) if err != nil { log.Println(err) return } err = s.AddCorporation(a.CorporationId) if err != nil { log.Println(err) return } } }
<div ng-if="pageCtrl.hasData"> <markdown data="pageCtrl.pageData"></markdown> </div>
var searchData= [ ['index',['index',['../d8/d33/structsvm__sample.html#a008f6b24c7c76af103e84245fb271506',1,'svm_sample']]], ['initlibirwls',['initLIBIRWLS',['../d4/d54/pythonmodule_8c.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void):&#160;pythonmodule.c'],['../d0/da7/pythonmodule_8h.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void):&#160;pythonmodule.c']]], ['initmemory',['initMemory',['../d0/d98/ParallelAlgorithms_8h.html#aa6df8c3f4f455d5692b3cb220fc205c7',1,'ParallelAlgorithms.h']]], ['iostructures_2ec',['IOStructures.c',['../dc/dfc/IOStructures_8c.html',1,'']]], ['iostructures_2eh',['IOStructures.h',['../de/d79/IOStructures_8h.html',1,'']]], ['irwlspar',['IRWLSpar',['../d4/d49/budgeted-train_8h.html#ad51d9a46645ad0b0bedb1113a3807d24',1,'budgeted-train.h']]] ];
module.exports = { options: { templateCompilerPath: 'bower_components/ember/ember-template-compiler.js', handlebarsPath: 'bower_components/handlebars/handlebars.js', preprocess: function (source) { return source.replace(/\s+/g, ' '); }, templateName: function (sourceFile) { /* These are how templates will be named based on their folder structure. components/[name].hbs ==> components/[name] partials/[name].hbs ==> _[name] modules/application/templates/[name].hbs ==> [name] modules/application/partials/[name].hbs ==> _[name] modules/[moduleName]/templates/[moduleName].hbs ==> [moduleName] modules/[moduleName]/templates/[name].hbs ==> [moduleName]/[name] modules/[moduleName]/partials/[name].hbs ==> [moduleName]/_[name] Additionally any template that is nested deeper will have that structure added as well. modules/[moduleName]/templates/[folder1]/[folder2]/[name] ==> [moduleName]/[folder1]/[folder2]/[name] */ var matches = sourceFile.match(new RegExp('(?:app/modules/(.*?)/|app/)(templates|partials)?/?(.*)')), moduleName = matches[1], isAppModule = (moduleName === 'application'), isPartial = (matches[2] === 'partials'), fileName = matches[3], prefix = (isPartial ? '_' : ''), templateName = ''; if (moduleName && !isAppModule) { if (fileName === moduleName) { templateName = moduleName; } else { templateName = moduleName + '/' + prefix + fileName; } } else { templateName = prefix + fileName; } console.log('Compiling ' + sourceFile.blue + ' to ' + templateName.green); return templateName; } }, compile: { files: { 'tmp/compiled-templates.js': ['templates/**/*.{hbs,handlebars}', 'app/**/*.{hbs,handlebars}'] } } };
# installPrinterFromWindowsPrintServer.sh This script takes arguments 4-11 to install a printer from a designated print server. If anything is passed to $6 (Driver Policy Trigger), it will be used as a custom trigger for a Jamf policy designated to install the driver. Using normal Jamf scoping mechanisms, you can avoid this policy being re-run when it is not necessary. Also, make sure to set printserver_protocol, printserver_name, and printserver_fqdn (lines 41-43) to correspond to your print server. Jamf doesn't give enough parameters, so if you have more than 1 print server, duplicate this script for each server. | Arg | Parameter Label | Example Policy Values | |-----|-----------------------|-----------------------------------------------------------------| | $4 | Printer Name | ITS-Printer1 | | $5 | Printer Location | 5127 OWP | | $6 | Driver Policy Trigger | printDrivers-Bizhub_C224_C284_C364_C454_C554 | | $7 | Driver PPD Path | /Library/Printers/PPDs/Contents/Resources/KONICAMINOLTAC224e.gz | | $8 | Option 1 | PaperSources=PC204 | | $9 | Option 2 | Finisher=FS519 | | $10 | Option 3 | SelectColor=Grayscale | | $11 | Option 4 | ColorModel=Gray |
class WorkflowSweeper < ActionController::Caching::Sweeper include InterfaceUtils::Extensions::Sweeper include Rails.application.routes.url_helpers include ActionController::Caching::Pages observe Workflow def after_save(workflow) expire_cache(workflow) end def after_destroy(workflow) expire_cache(workflow) end def expire_cache(workflow) expire_full_path_page medium_workflow_url(workflow.medium, :only_path => true, :format => :xml) end end
Note=I'm borrowing from the Polish work generously contributed. I'm improvising. Please help! Can be viewed at <a href="http://commonaccord.org/index.php?action=doc&file=G/CmA_F_Agt-Base/PL-v0.md">http://commonaccord.org/index.php?action=doc&file=G/CmA_Form-Agt/PL-v0.md</a> Head.EffectiveDate.sec={_Effective_Date}: {EffectiveDate.YMD} Note=Parties. Is there a distinction in the language for 2 parties, 3 parties, 4 parties? Among.Ti/2=Umowa zawarta pomiędzy: Among.Ti/3=Umowa zawarta pomiędzy: Among.secs/2=<ul type="none" style="padding-left: 0"><li>{P1.PL.Frame.Among.Sec}</li><li>{P2.PL.Frame.Among.Sec}</li></ul> Among.secs/3=<ul type="none" style="padding-left: 0"><li>{P1.PL.Frame.Among.Sec}</li><li>{P2.PL.Frame.Among.Sec}</li><li>{P3.PL.Frame.Among.Sec}</li></ul> Among.secs/4=<ul type="none" style="padding-left: 0"><li>{P1.PL.Frame.Among.Sec}</li><li>{P2.PL.Frame.Among.Sec}</li><li>{P3.PL.Frame.Among.Sec}</li><li>{P4.PL.Frame.Among.Sec}</li></ul> Among.Def.sec=Indywidualnie zwane «{_stroną}», a łącznie «{_stronami}». Note=Friends.Div is for the relatively rare agreements that need to specifically list other persons, for instance affiliates of one of the parties. Defaults to null. To use it, define a paragraph with the desired number of referenced persons in the format "Friend.=[G/Z/ol/s*]" where * is the number of persons, e.g, "Friend.=[G/Z/ol/s3]". This uses the common paragraph format widget. Friend.Ti=Affiliated persons referenced in this {_Agreement}: Friend.Def.sec=Each a "{_Named_Third_Party}" and collectively the "{_Named_Third_Parties}." This.sec/2=This {Doc.Ti} (this "{_Agreement}") is made as of {EffectiveDate.YMD} ("{_Effective_Date}"), by and between the {_parties}. This.sec/3=This {Doc.Ti} (this "{_Agreement}") is made as of {EffectiveDate.YMD} ("{_Effective_Date}"), by and among the {_parties}. Why.Ti=Recitals Note=That - is the part that transitions from the introduction into the sections of the agreement. This is a heavy-duty version, intended to be good in most jurisdictions, at the (slight) cost of having a bit of surplusage for some jurisdictions. That.sec=In consideration of the mutual promises contained in {_this_Agreement} and other good and valuable consideration, the receipt and sufficiency of which is hereby acknowledged, the {_parties} agree as follows: By.Ti=Signature By.0.sec=Strony poświadczają zawarcie {_this_Agreement} od dnia {_Effective_Date}. By.secs/2=<table><tr><td valign=top>{P1.PL.Frame.By.Sec}</td><td valign=top>   </td><td valign=top>{P2.PL.Frame.By.Sec}</td></tr></table> By.secs/3=<table><tr><td valign=top>{P1.PL.Frame.By.Sec}</td><td valign=top>   </td><td valign=top>{P2.PL.Frame.By.Sec}</td></tr><tr><td valign=top>{P3.PL.Frame.By.Sec}</td><td valign=top>   </td><td valign=top></td></tr></table> By.secs/4=<table><tr><td valign=top>{P1.PL.Frame.By.Sec}</td><td valign=top>   </td><td valign=top>{P2.PL.Frame.By.Sec}</td></tr><tr><td valign=top>{P3.PL.Frame.By.Sec}</td><td valign=top>   </td><td valign=top>{P4.PL.Frame.By.Sec}</td></tr></table> Annex.Ti=Annexes Note=The Oxford comma is preferred by some and eschewed by others. If you write your text like this: one, two, three{q} and four, then the user can make the choice. Here we default to no Oxford comma: q=</i> _stroną=<a href="" class="definedterm" >stroną</a> _stronami=<a a href="" class="definedterm">stronami</a> _party={_stroną} _parties={_stronami} Note=The common frame: =[G/Agt-Form-CmA/00/0.md]
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highmaps]] */ package com.highmaps.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>series&lt;funnel&gt;-data-dragDrop-guideBox-default</code> */ @js.annotation.ScalaJSDefined class SeriesFunnelDataDragDropGuideBoxDefault extends com.highcharts.HighchartsGenericObject { /** * <p>CSS class name of the guide box in this state. Defaults to * <code>highcharts-drag-box-default</code>.</p> * @since 6.2.0 */ val className: js.UndefOr[String] = js.undefined /** * <p>Width of the line around the guide box.</p> * @since 6.2.0 */ val lineWidth: js.UndefOr[Double] = js.undefined /** * <p>Color of the border around the guide box.</p> * @since 6.2.0 */ val lineColor: js.UndefOr[String | js.Object] = js.undefined /** * <p>Guide box fill color.</p> * @since 6.2.0 */ val color: js.UndefOr[String | js.Object] = js.undefined /** * <p>Guide box cursor.</p> * @since 6.2.0 */ val cursor: js.UndefOr[String] = js.undefined /** * <p>Guide box zIndex.</p> * @since 6.2.0 */ val zIndex: js.UndefOr[Double] = js.undefined } object SeriesFunnelDataDragDropGuideBoxDefault { /** * @param className <p>CSS class name of the guide box in this state. Defaults to. <code>highcharts-drag-box-default</code>.</p> * @param lineWidth <p>Width of the line around the guide box.</p> * @param lineColor <p>Color of the border around the guide box.</p> * @param color <p>Guide box fill color.</p> * @param cursor <p>Guide box cursor.</p> * @param zIndex <p>Guide box zIndex.</p> */ def apply(className: js.UndefOr[String] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, cursor: js.UndefOr[String] = js.undefined, zIndex: js.UndefOr[Double] = js.undefined): SeriesFunnelDataDragDropGuideBoxDefault = { val classNameOuter: js.UndefOr[String] = className val lineWidthOuter: js.UndefOr[Double] = lineWidth val lineColorOuter: js.UndefOr[String | js.Object] = lineColor val colorOuter: js.UndefOr[String | js.Object] = color val cursorOuter: js.UndefOr[String] = cursor val zIndexOuter: js.UndefOr[Double] = zIndex com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesFunnelDataDragDropGuideBoxDefault { override val className: js.UndefOr[String] = classNameOuter override val lineWidth: js.UndefOr[Double] = lineWidthOuter override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter override val color: js.UndefOr[String | js.Object] = colorOuter override val cursor: js.UndefOr[String] = cursorOuter override val zIndex: js.UndefOr[Double] = zIndexOuter }) } }
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> <meta charset="utf-8"> <title>_personal</title> <meta name="description" content="Giovanni Belloni personal website"> <meta name="keywords" content="software, developer, belloni, blog, website"> <!-- Twitter Cards --> <meta name="twitter:title" content="_personal"> <meta name="twitter:description" content="Giovanni Belloni personal website"> <meta name="twitter:site" content="@gio_bll"> <meta name="twitter:creator" content="@gio_bll"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:image" content="http://giovanni-bb.github.io/images/image-bar-5.jpg"> <!-- Open Graph --> <meta property="og:locale" content="en_US"> <meta property="og:type" content="article"> <meta property="og:title" content="_personal"> <meta property="og:description" content="Giovanni Belloni personal website"> <meta property="og:url" content="http://giovanni-bb.github.io/"> <meta property="og:site_name" content="_personal"> <link rel="canonical" href="http://giovanni-bb.github.io/"> <link href="http://giovanni-bb.github.io/feed.xml" type="application/atom+xml" rel="alternate" title="_personal Feed"> <!-- http://t.co/dKP3o1e --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- For all browsers --> <link rel="stylesheet" href="http://giovanni-bb.github.io/assets/css/main.css"> <meta http-equiv="cleartype" content="on"> <!-- HTML5 Shiv and Media Query Support --> <!--[if lt IE 9]> <script src="http://giovanni-bb.github.io/assets/js/vendor/html5shiv.min.js"></script> <script src="http://giovanni-bb.github.io/assets/js/vendor/respond.min.js"></script> <![endif]--> <!-- Modernizr --> <script src="http://giovanni-bb.github.io/assets/js/vendor/modernizr-2.7.1.custom.min.js"></script> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700%7CPT+Serif:400,700,400italic' rel='stylesheet' type='text/css'> <!-- Icons --> <!-- 16x16 --> <link rel="shortcut icon" href="http://giovanni-bb.github.io/favicon.ico"> <!-- 32x32 --> <link rel="shortcut icon" href="http://giovanni-bb.github.io/favicon.png"> <!-- 57x57 (precomposed) for iPhone 3GS, pre-2011 iPod Touch and older Android devices --> <link rel="apple-touch-icon-precomposed" href="http://giovanni-bb.github.io/images/apple-touch-icon-precomposed.png"> <!-- 72x72 (precomposed) for 1st generation iPad, iPad 2 and iPad mini --> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://giovanni-bb.github.io/images/apple-touch-icon-72x72-precomposed.png"> <!-- 114x114 (precomposed) for iPhone 4, 4S, 5 and post-2011 iPod Touch --> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://giovanni-bb.github.io/images/apple-touch-icon-114x114-precomposed.png"> <!-- 144x144 (precomposed) for iPad 3rd and 4th generation --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://giovanni-bb.github.io/images/apple-touch-icon-144x144-precomposed.png"> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-61191254-1', 'auto'); ga('send', 'pageview'); </script> </head> <body class="home"> <!--[if lt IE 9]><div class="browser-upgrade alert alert-info">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</div><![endif]--> <div class="navigation-wrapper"> <div class="site-name"> <a href="http://giovanni-bb.github.io/">_personal</a> </div><!-- /.site-name --> <div class="top-navigation"> <nav role="navigation" id="site-nav" class="nav"> <ul> <li><a href="http://giovanni-bb.github.io/about/" >About</a></li> <li><a href="http://giovanni-bb.github.io/posts/" >Posts</a></li> <li><a href="http://giovanni-bb.github.io/projects/" >Projects</a></li> <li><a href="http://giovanni-bb.github.io/cv/" >C.V.</a></li> </ul> </nav> </div><!-- /.top-navigation --> </div><!-- /.navigation-wrapper --> <div class="image-wrap"> <img src= "http://giovanni-bb.github.io/images/image-bar-5.jpg" alt=" giovanni belloni"> </div><!-- /.image-wrap --> <div id="main" role="main"> <div class="article-author-side"> <div itemscope itemtype="http://schema.org/Person"> <img src="http://giovanni-bb.github.io/images/foto_l1.jpg" class="bio-photo" alt="Giovanni Belloni bio photo"> <h3 itemprop="name">Giovanni Belloni</h3> <p>Software Developer</p> <a href="mailto:belloni.giovanni@gmail.com" class="author-social" target="_blank"><i class="fa fa-fw fa-envelope-square"></i> Email</a> <a href="http://twitter.com/gio_bll" class="author-social" target="_blank"><i class="fa fa-fw fa-twitter-square"></i> Twitter</a> <a href="http://facebook.com/giovanni.belloni.3990" class="author-social" target="_blank"><i class="fa fa-fw fa-facebook-square"></i> Facebook</a> <a href="http://plus.google.com/+GiovanniBB" class="author-social" target="_blank"><i class="fa fa-fw fa-google-plus-square"></i> Google+</a> <a href="http://linkedin.com/pub/giovanni-belloni/31/346/b83/it" class="author-social" target="_blank"><i class="fa fa-fw fa-linkedin-square"></i> LinkedIn</a> <a href="http://github.com/giovanni-bb" class="author-social" target="_blank"><i class="fa fa-fw fa-github"></i> Github</a> <a href="https://youtube.com/channel/UCgptGQQOxE_2pWBC7UpV0AQ" class="author-social" target="_blank"><i class="fa fa-fw fa-youtube-square"></i> Youtube</a> </div> </div> <div id="index"> <h3><a href="http://giovanni-bb.github.io/posts/">Recent Posts</a></h3> <article> <h2><a href="http://giovanni-bb.github.io/fuoco-egress/" title="Modello d'incendio ed evacuazione - un esempio">Modello d'incendio ed evacuazione - un esempio</a></h2> <p>Un semplice esempio di modellazione di fuoco ed evacuazione</p> </article> <article> <h2><a href="http://giovanni-bb.github.io/settimana-londra/" title="Fire Modeling training a Londra">Fire Modeling training a Londra</a></h2> <p>Una settimana di corsi su FDS, Pyrosim e Pathfinder</p> </article> <article> <h2><a href="http://giovanni-bb.github.io/first-post/" title="First post">First post</a></h2> <p>A little shout out</p> </article> </div><!-- /#index --> </div><!-- /#main --> <div class="footer-wrap"> <footer> <span>&copy; 2015 Giovanni Belloni. Powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll</a> using the <a href="http://mademistakes.com/minimal-mistakes/" rel="nofollow">Minimal Mistakes</a> theme.</span> </footer> </div><!-- /.footer-wrap --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="http://giovanni-bb.github.io/assets/js/vendor/jquery-1.9.1.min.js"><\/script>')</script> <script src="http://giovanni-bb.github.io/assets/js/scripts.min.js"></script> </body> </html>
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * 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. */ #include "uv.h" #include "internal.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/uio.h> #include <sys/un.h> #include <unistd.h> #include <limits.h> /* IOV_MAX */ #if defined(__APPLE__) # include <sys/event.h> # include <sys/time.h> # include <sys/select.h> /* Forward declaration */ typedef struct uv__stream_select_s uv__stream_select_t; struct uv__stream_select_s { uv_stream_t* stream; uv_thread_t thread; uv_sem_t close_sem; uv_sem_t async_sem; uv_async_t async; int events; int fake_fd; int int_fd; int fd; }; #endif /* defined(__APPLE__) */ static void uv__stream_connect(uv_stream_t*); static void uv__write(uv_stream_t* stream); static void uv__read(uv_stream_t* stream); static void uv__stream_io(uv_loop_t* loop, uv__io_t* w, unsigned int events); static size_t uv__write_req_size(uv_write_t* req); void uv__stream_init(uv_loop_t* loop, uv_stream_t* stream, uv_handle_type type) { int err; uv__handle_init(loop, (uv_handle_t*)stream, type); stream->read_cb = NULL; stream->alloc_cb = NULL; stream->close_cb = NULL; stream->connection_cb = NULL; stream->connect_req = NULL; stream->shutdown_req = NULL; stream->accepted_fd = -1; stream->queued_fds = NULL; stream->delayed_error = 0; QUEUE_INIT(&stream->write_queue); QUEUE_INIT(&stream->write_completed_queue); stream->write_queue_size = 0; if (loop->emfile_fd == -1) { err = uv__open_cloexec("/", O_RDONLY); if (err >= 0) loop->emfile_fd = err; } #if defined(__APPLE__) stream->select = NULL; #endif /* defined(__APPLE_) */ uv__io_init(&stream->io_watcher, uv__stream_io, -1); } static void uv__stream_osx_interrupt_select(uv_stream_t* stream) { #if defined(__APPLE__) /* Notify select() thread about state change */ uv__stream_select_t* s; int r; s = stream->select; if (s == NULL) return; /* Interrupt select() loop * NOTE: fake_fd and int_fd are socketpair(), thus writing to one will * emit read event on other side */ do r = write(s->fake_fd, "x", 1); while (r == -1 && errno == EINTR); assert(r == 1); #else /* !defined(__APPLE__) */ /* No-op on any other platform */ #endif /* !defined(__APPLE__) */ } #if defined(__APPLE__) static void uv__stream_osx_select(void* arg) { uv_stream_t* stream; uv__stream_select_t* s; char buf[1024]; fd_set sread; fd_set swrite; int events; int fd; int r; int max_fd; stream = arg; s = stream->select; fd = s->fd; if (fd > s->int_fd) max_fd = fd; else max_fd = s->int_fd; while (1) { /* Terminate on semaphore */ if (uv_sem_trywait(&s->close_sem) == 0) break; /* Watch fd using select(2) */ FD_ZERO(&sread); FD_ZERO(&swrite); if (uv__io_active(&stream->io_watcher, UV__POLLIN)) FD_SET(fd, &sread); if (uv__io_active(&stream->io_watcher, UV__POLLOUT)) FD_SET(fd, &swrite); FD_SET(s->int_fd, &sread); /* Wait indefinitely for fd events */ r = select(max_fd + 1, &sread, &swrite, NULL, NULL); if (r == -1) { if (errno == EINTR) continue; /* XXX: Possible?! */ abort(); } /* Ignore timeouts */ if (r == 0) continue; /* Empty socketpair's buffer in case of interruption */ if (FD_ISSET(s->int_fd, &sread)) while (1) { r = read(s->int_fd, buf, sizeof(buf)); if (r == sizeof(buf)) continue; if (r != -1) break; if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (errno == EINTR) continue; abort(); } /* Handle events */ events = 0; if (FD_ISSET(fd, &sread)) events |= UV__POLLIN; if (FD_ISSET(fd, &swrite)) events |= UV__POLLOUT; assert(events != 0 || FD_ISSET(s->int_fd, &sread)); if (events != 0) { ACCESS_ONCE(int, s->events) = events; uv_async_send(&s->async); uv_sem_wait(&s->async_sem); /* Should be processed at this stage */ assert((s->events == 0) || (stream->flags & UV_CLOSING)); } } } static void uv__stream_osx_select_cb(uv_async_t* handle) { uv__stream_select_t* s; uv_stream_t* stream; int events; s = container_of(handle, uv__stream_select_t, async); stream = s->stream; /* Get and reset stream's events */ events = s->events; ACCESS_ONCE(int, s->events) = 0; uv_sem_post(&s->async_sem); assert(events != 0); assert(events == (events & (UV__POLLIN | UV__POLLOUT))); /* Invoke callback on event-loop */ if ((events & UV__POLLIN) && uv__io_active(&stream->io_watcher, UV__POLLIN)) uv__stream_io(stream->loop, &stream->io_watcher, UV__POLLIN); if ((events & UV__POLLOUT) && uv__io_active(&stream->io_watcher, UV__POLLOUT)) uv__stream_io(stream->loop, &stream->io_watcher, UV__POLLOUT); } static void uv__stream_osx_cb_close(uv_handle_t* async) { uv__stream_select_t* s; s = container_of(async, uv__stream_select_t, async); free(s); } int uv__stream_try_select(uv_stream_t* stream, int* fd) { /* * kqueue doesn't work with some files from /dev mount on osx. * select(2) in separate thread for those fds */ struct kevent filter[1]; struct kevent events[1]; struct timespec timeout; uv__stream_select_t* s; int fds[2]; int err; int ret; int kq; int old_fd; kq = kqueue(); if (kq == -1) { perror("(libuv) kqueue()"); return -errno; } EV_SET(&filter[0], *fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, 0); /* Use small timeout, because we only want to capture EINVALs */ timeout.tv_sec = 0; timeout.tv_nsec = 1; ret = kevent(kq, filter, 1, events, 1, &timeout); uv__close(kq); if (ret == -1) return -errno; if (ret == 0 || (events[0].flags & EV_ERROR) == 0 || events[0].data != EINVAL) return 0; /* At this point we definitely know that this fd won't work with kqueue */ s = malloc(sizeof(*s)); if (s == NULL) return -ENOMEM; s->events = 0; s->fd = *fd; err = uv_async_init(stream->loop, &s->async, uv__stream_osx_select_cb); if (err) { free(s); return err; } s->async.flags |= UV__HANDLE_INTERNAL; uv__handle_unref(&s->async); if (uv_sem_init(&s->close_sem, 0)) goto fatal1; if (uv_sem_init(&s->async_sem, 0)) goto fatal2; /* Create fds for io watcher and to interrupt the select() loop. */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds)) goto fatal3; s->fake_fd = fds[0]; s->int_fd = fds[1]; old_fd = *fd; s->stream = stream; stream->select = s; *fd = s->fake_fd; if (uv_thread_create(&s->thread, uv__stream_osx_select, stream)) goto fatal4; return 0; fatal4: s->stream = NULL; stream->select = NULL; *fd = old_fd; uv__close(s->fake_fd); uv__close(s->int_fd); s->fake_fd = -1; s->int_fd = -1; fatal3: uv_sem_destroy(&s->async_sem); fatal2: uv_sem_destroy(&s->close_sem); fatal1: uv_close((uv_handle_t*) &s->async, uv__stream_osx_cb_close); return -errno; } #endif /* defined(__APPLE__) */ int uv__stream_open(uv_stream_t* stream, int fd, int flags) { assert(fd >= 0); stream->flags |= flags; if (stream->type == UV_TCP) { if ((stream->flags & UV_TCP_NODELAY) && uv__tcp_nodelay(fd, 1)) return -errno; /* TODO Use delay the user passed in. */ if ((stream->flags & UV_TCP_KEEPALIVE) && uv__tcp_keepalive(fd, 1, 60)) return -errno; } stream->io_watcher.fd = fd; return 0; } void uv__stream_destroy(uv_stream_t* stream) { uv_write_t* req; QUEUE* q; assert(!uv__io_active(&stream->io_watcher, UV__POLLIN | UV__POLLOUT)); assert(stream->flags & UV_CLOSED); if (stream->connect_req) { uv__req_unregister(stream->loop, stream->connect_req); stream->connect_req->cb(stream->connect_req, -ECANCELED); stream->connect_req = NULL; } while (!QUEUE_EMPTY(&stream->write_queue)) { q = QUEUE_HEAD(&stream->write_queue); QUEUE_REMOVE(q); req = QUEUE_DATA(q, uv_write_t, queue); uv__req_unregister(stream->loop, req); if (req->bufs != req->bufsml) free(req->bufs); req->bufs = NULL; if (req->cb != NULL) req->cb(req, -ECANCELED); } while (!QUEUE_EMPTY(&stream->write_completed_queue)) { q = QUEUE_HEAD(&stream->write_completed_queue); QUEUE_REMOVE(q); req = QUEUE_DATA(q, uv_write_t, queue); uv__req_unregister(stream->loop, req); if (req->bufs != NULL) { stream->write_queue_size -= uv__write_req_size(req); if (req->bufs != req->bufsml) free(req->bufs); req->bufs = NULL; } if (req->cb) req->cb(req, req->error); } if (stream->shutdown_req) { /* The ECANCELED error code is a lie, the shutdown(2) syscall is a * fait accompli at this point. Maybe we should revisit this in v0.11. * A possible reason for leaving it unchanged is that it informs the * callee that the handle has been destroyed. */ uv__req_unregister(stream->loop, stream->shutdown_req); stream->shutdown_req->cb(stream->shutdown_req, -ECANCELED); stream->shutdown_req = NULL; } } /* Implements a best effort approach to mitigating accept() EMFILE errors. * We have a spare file descriptor stashed away that we close to get below * the EMFILE limit. Next, we accept all pending connections and close them * immediately to signal the clients that we're overloaded - and we are, but * we still keep on trucking. * * There is one caveat: it's not reliable in a multi-threaded environment. * The file descriptor limit is per process. Our party trick fails if another * thread opens a file or creates a socket in the time window between us * calling close() and accept(). */ static int uv__emfile_trick(uv_loop_t* loop, int accept_fd) { int err; int emfile_fd; if (loop->emfile_fd == -1) return -EMFILE; uv__close(loop->emfile_fd); loop->emfile_fd = -1; do { err = uv__accept(accept_fd); if (err >= 0) uv__close(err); } while (err >= 0 || err == -EINTR); emfile_fd = uv__open_cloexec("/", O_RDONLY); if (emfile_fd >= 0) loop->emfile_fd = emfile_fd; return err; } #if defined(UV_HAVE_KQUEUE) # define UV_DEC_BACKLOG(w) w->rcount--; #else # define UV_DEC_BACKLOG(w) /* no-op */ #endif /* defined(UV_HAVE_KQUEUE) */ void uv__server_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) { uv_stream_t* stream; int err; stream = container_of(w, uv_stream_t, io_watcher); assert(events == UV__POLLIN); assert(stream->accepted_fd == -1); assert(!(stream->flags & UV_CLOSING)); uv__io_start(stream->loop, &stream->io_watcher, UV__POLLIN); /* connection_cb can close the server socket while we're * in the loop so check it on each iteration. */ while (uv__stream_fd(stream) != -1) { assert(stream->accepted_fd == -1); #if defined(UV_HAVE_KQUEUE) if (w->rcount <= 0) return; #endif /* defined(UV_HAVE_KQUEUE) */ err = uv__accept(uv__stream_fd(stream)); if (err < 0) { if (err == -EAGAIN || err == -EWOULDBLOCK) return; /* Not an error. */ if (err == -ECONNABORTED) continue; /* Ignore. Nothing we can do about that. */ if (err == -EMFILE || err == -ENFILE) { err = uv__emfile_trick(loop, uv__stream_fd(stream)); if (err == -EAGAIN || err == -EWOULDBLOCK) break; } stream->connection_cb(stream, err); continue; } UV_DEC_BACKLOG(w) stream->accepted_fd = err; stream->connection_cb(stream, 0); if (stream->accepted_fd != -1) { /* The user hasn't yet accepted called uv_accept() */ uv__io_stop(loop, &stream->io_watcher, UV__POLLIN); return; } if (stream->type == UV_TCP && (stream->flags & UV_TCP_SINGLE_ACCEPT)) { /* Give other processes a chance to accept connections. */ struct timespec timeout = { 0, 1 }; nanosleep(&timeout, NULL); } } } #undef UV_DEC_BACKLOG int uv_accept(uv_stream_t* server, uv_stream_t* client) { int err; /* TODO document this */ assert(server->loop == client->loop); if (server->accepted_fd == -1) return -EAGAIN; err = 0; switch (client->type) { case UV_NAMED_PIPE: case UV_TCP: err = uv__stream_open(client, server->accepted_fd, UV_STREAM_READABLE | UV_STREAM_WRITABLE); if (err) { /* TODO handle error */ uv__close(server->accepted_fd); goto done; } break; case UV_UDP: err = uv_udp_open((uv_udp_t*) client, server->accepted_fd); if (err) { uv__close(server->accepted_fd); goto done; } break; default: assert(0); } done: /* Process queued fds */ if (server->queued_fds != NULL) { uv__stream_queued_fds_t* queued_fds; queued_fds = server->queued_fds; /* Read first */ server->accepted_fd = queued_fds->fds[0]; /* All read, free */ assert(queued_fds->offset > 0); if (--queued_fds->offset == 0) { free(queued_fds); server->queued_fds = NULL; } else { /* Shift rest */ memmove(queued_fds->fds, queued_fds->fds + 1, queued_fds->offset * sizeof(*queued_fds->fds)); } } else { server->accepted_fd = -1; if (err == 0) uv__io_start(server->loop, &server->io_watcher, UV__POLLIN); } return err; } int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) { int err; err = -EINVAL; switch (stream->type) { case UV_TCP: err = uv_tcp_listen((uv_tcp_t*)stream, backlog, cb); break; case UV_NAMED_PIPE: err = uv_pipe_listen((uv_pipe_t*)stream, backlog, cb); break; default: assert(0); } if (err == 0) uv__handle_start(stream); return err; } static void uv__drain(uv_stream_t* stream) { uv_shutdown_t* req; int err; assert(QUEUE_EMPTY(&stream->write_queue)); uv__io_stop(stream->loop, &stream->io_watcher, UV__POLLOUT); uv__stream_osx_interrupt_select(stream); /* Shutdown? */ if ((stream->flags & UV_STREAM_SHUTTING) && !(stream->flags & UV_CLOSING) && !(stream->flags & UV_STREAM_SHUT)) { assert(stream->shutdown_req); req = stream->shutdown_req; stream->shutdown_req = NULL; stream->flags &= ~UV_STREAM_SHUTTING; uv__req_unregister(stream->loop, req); err = 0; if (shutdown(uv__stream_fd(stream), SHUT_WR)) err = -errno; if (err == 0) stream->flags |= UV_STREAM_SHUT; if (req->cb != NULL) req->cb(req, err); } } static size_t uv__write_req_size(uv_write_t* req) { size_t size; assert(req->bufs != NULL); size = uv__count_bufs(req->bufs + req->write_index, req->nbufs - req->write_index); assert(req->handle->write_queue_size >= size); return size; } static void uv__write_req_finish(uv_write_t* req) { uv_stream_t* stream = req->handle; /* Pop the req off tcp->write_queue. */ QUEUE_REMOVE(&req->queue); /* Only free when there was no error. On error, we touch up write_queue_size * right before making the callback. The reason we don't do that right away * is that a write_queue_size > 0 is our only way to signal to the user that * they should stop writing - which they should if we got an error. Something * to revisit in future revisions of the libuv API. */ if (req->error == 0) { if (req->bufs != req->bufsml) free(req->bufs); req->bufs = NULL; } /* Add it to the write_completed_queue where it will have its * callback called in the near future. */ QUEUE_INSERT_TAIL(&stream->write_completed_queue, &req->queue); uv__io_feed(stream->loop, &stream->io_watcher); } static int uv__handle_fd(uv_handle_t* handle) { switch (handle->type) { case UV_NAMED_PIPE: case UV_TCP: return ((uv_stream_t*) handle)->io_watcher.fd; case UV_UDP: return ((uv_udp_t*) handle)->io_watcher.fd; default: return -1; } } static int uv__getiovmax() { #if defined(IOV_MAX) return IOV_MAX; #elif defined(_SC_IOV_MAX) static int iovmax = -1; if (iovmax == -1) iovmax = sysconf(_SC_IOV_MAX); return iovmax; #else return 1024; #endif } static void uv__write(uv_stream_t* stream) { struct iovec* iov; QUEUE* q; uv_write_t* req; int iovmax; int iovcnt; ssize_t n; start: assert(uv__stream_fd(stream) >= 0); if (QUEUE_EMPTY(&stream->write_queue)) return; q = QUEUE_HEAD(&stream->write_queue); req = QUEUE_DATA(q, uv_write_t, queue); assert(req->handle == stream); /* * Cast to iovec. We had to have our own uv_buf_t instead of iovec * because Windows's WSABUF is not an iovec. */ assert(sizeof(uv_buf_t) == sizeof(struct iovec)); iov = (struct iovec*) &(req->bufs[req->write_index]); iovcnt = req->nbufs - req->write_index; iovmax = uv__getiovmax(); /* Limit iov count to avoid EINVALs from writev() */ if (iovcnt > iovmax) iovcnt = iovmax; /* * Now do the actual writev. Note that we've been updating the pointers * inside the iov each time we write. So there is no need to offset it. */ if (req->send_handle) { struct msghdr msg; char scratch[64]; struct cmsghdr *cmsg; int fd_to_send = uv__handle_fd((uv_handle_t*) req->send_handle); assert(fd_to_send >= 0); msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_iov = iov; msg.msg_iovlen = iovcnt; msg.msg_flags = 0; msg.msg_control = (void*) scratch; msg.msg_controllen = CMSG_SPACE(sizeof(fd_to_send)); cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(fd_to_send)); /* silence aliasing warning */ { void* pv = CMSG_DATA(cmsg); int* pi = pv; *pi = fd_to_send; } do { n = sendmsg(uv__stream_fd(stream), &msg, 0); } while (n == -1 && errno == EINTR); } else { do { if (iovcnt == 1) { n = write(uv__stream_fd(stream), iov[0].iov_base, iov[0].iov_len); } else { n = writev(uv__stream_fd(stream), iov, iovcnt); } } while (n == -1 && errno == EINTR); } if (n < 0) { if (errno != EAGAIN && errno != EWOULDBLOCK) { /* Error */ req->error = -errno; uv__write_req_finish(req); uv__io_stop(stream->loop, &stream->io_watcher, UV__POLLOUT); if (!uv__io_active(&stream->io_watcher, UV__POLLIN)) uv__handle_stop(stream); uv__stream_osx_interrupt_select(stream); return; } else if (stream->flags & UV_STREAM_BLOCKING) { /* If this is a blocking stream, try again. */ goto start; } } else { /* Successful write */ while (n >= 0) { uv_buf_t* buf = &(req->bufs[req->write_index]); size_t len = buf->len; assert(req->write_index < req->nbufs); if ((size_t)n < len) { buf->base += n; buf->len -= n; stream->write_queue_size -= n; n = 0; /* There is more to write. */ if (stream->flags & UV_STREAM_BLOCKING) { /* * If we're blocking then we should not be enabling the write * watcher - instead we need to try again. */ goto start; } else { /* Break loop and ensure the watcher is pending. */ break; } } else { /* Finished writing the buf at index req->write_index. */ req->write_index++; assert((size_t)n >= len); n -= len; assert(stream->write_queue_size >= len); stream->write_queue_size -= len; if (req->write_index == req->nbufs) { /* Then we're done! */ assert(n == 0); uv__write_req_finish(req); /* TODO: start trying to write the next request. */ return; } } } } /* Either we've counted n down to zero or we've got EAGAIN. */ assert(n == 0 || n == -1); /* Only non-blocking streams should use the write_watcher. */ assert(!(stream->flags & UV_STREAM_BLOCKING)); /* We're not done. */ uv__io_start(stream->loop, &stream->io_watcher, UV__POLLOUT); /* Notify select() thread about state change */ uv__stream_osx_interrupt_select(stream); } static void uv__write_callbacks(uv_stream_t* stream) { uv_write_t* req; QUEUE* q; while (!QUEUE_EMPTY(&stream->write_completed_queue)) { /* Pop a req off write_completed_queue. */ q = QUEUE_HEAD(&stream->write_completed_queue); req = QUEUE_DATA(q, uv_write_t, queue); QUEUE_REMOVE(q); uv__req_unregister(stream->loop, req); if (req->bufs != NULL) { stream->write_queue_size -= uv__write_req_size(req); if (req->bufs != req->bufsml) free(req->bufs); req->bufs = NULL; } /* NOTE: call callback AFTER freeing the request data. */ if (req->cb) req->cb(req, req->error); } assert(QUEUE_EMPTY(&stream->write_completed_queue)); /* Write queue drained. */ if (QUEUE_EMPTY(&stream->write_queue)) uv__drain(stream); } uv_handle_type uv__handle_type(int fd) { struct sockaddr_storage ss; socklen_t len; int type; memset(&ss, 0, sizeof(ss)); len = sizeof(ss); if (getsockname(fd, (struct sockaddr*)&ss, &len)) return UV_UNKNOWN_HANDLE; len = sizeof type; if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &len)) return UV_UNKNOWN_HANDLE; if (type == SOCK_STREAM) { switch (ss.ss_family) { case AF_UNIX: return UV_NAMED_PIPE; case AF_INET: case AF_INET6: return UV_TCP; } } if (type == SOCK_DGRAM && (ss.ss_family == AF_INET || ss.ss_family == AF_INET6)) return UV_UDP; return UV_UNKNOWN_HANDLE; } static void uv__stream_eof(uv_stream_t* stream, const uv_buf_t* buf) { stream->flags |= UV_STREAM_READ_EOF; uv__io_stop(stream->loop, &stream->io_watcher, UV__POLLIN); if (!uv__io_active(&stream->io_watcher, UV__POLLOUT)) uv__handle_stop(stream); uv__stream_osx_interrupt_select(stream); stream->read_cb(stream, UV_EOF, buf); } static int uv__stream_queue_fd(uv_stream_t* stream, int fd) { uv__stream_queued_fds_t* queued_fds; unsigned int queue_size; queued_fds = stream->queued_fds; if (queued_fds == NULL) { queue_size = 8; queued_fds = malloc((queue_size - 1) * sizeof(*queued_fds->fds) + sizeof(*queued_fds)); if (queued_fds == NULL) return -ENOMEM; queued_fds->size = queue_size; queued_fds->offset = 0; stream->queued_fds = queued_fds; /* Grow */ } else if (queued_fds->size == queued_fds->offset) { queue_size = queued_fds->size + 8; queued_fds = realloc(queued_fds, (queue_size - 1) * sizeof(*queued_fds->fds) + sizeof(*queued_fds)); /* * Allocation failure, report back. * NOTE: if it is fatal - sockets will be closed in uv__stream_close */ if (queued_fds == NULL) return -ENOMEM; queued_fds->size = queue_size; stream->queued_fds = queued_fds; } /* Put fd in a queue */ queued_fds->fds[queued_fds->offset++] = fd; return 0; } #define UV__CMSG_FD_COUNT 64 #define UV__CMSG_FD_SIZE (UV__CMSG_FD_COUNT * sizeof(int)) static int uv__stream_recv_cmsg(uv_stream_t* stream, struct msghdr* msg) { struct cmsghdr* cmsg; for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg)) { char* start; char* end; int err; void* pv; int* pi; unsigned int i; unsigned int count; if (cmsg->cmsg_type != SCM_RIGHTS) { fprintf(stderr, "ignoring non-SCM_RIGHTS ancillary data: %d\n", cmsg->cmsg_type); continue; } /* silence aliasing warning */ pv = CMSG_DATA(cmsg); pi = pv; /* Count available fds */ start = (char*) cmsg; end = (char*) cmsg + cmsg->cmsg_len; count = 0; while (start + CMSG_LEN(count * sizeof(*pi)) < end) count++; assert(start + CMSG_LEN(count * sizeof(*pi)) == end); for (i = 0; i < count; i++) { /* Already has accepted fd, queue now */ if (stream->accepted_fd != -1) { err = uv__stream_queue_fd(stream, pi[i]); if (err != 0) { /* Close rest */ for (; i < count; i++) uv__close(pi[i]); return err; } } else { stream->accepted_fd = pi[i]; } } } return 0; } static void uv__read(uv_stream_t* stream) { uv_buf_t buf; ssize_t nread; struct msghdr msg; char cmsg_space[CMSG_SPACE(UV__CMSG_FD_SIZE)]; int count; int err; int is_ipc; stream->flags &= ~UV_STREAM_READ_PARTIAL; /* Prevent loop starvation when the data comes in as fast as (or faster than) * we can read it. XXX Need to rearm fd if we switch to edge-triggered I/O. */ count = 32; is_ipc = stream->type == UV_NAMED_PIPE && ((uv_pipe_t*) stream)->ipc; /* XXX: Maybe instead of having UV_STREAM_READING we just test if * tcp->read_cb is NULL or not? */ while (stream->read_cb && (stream->flags & UV_STREAM_READING) && (count-- > 0)) { assert(stream->alloc_cb != NULL); stream->alloc_cb((uv_handle_t*)stream, 64 * 1024, &buf); if (buf.len == 0) { /* User indicates it can't or won't handle the read. */ stream->read_cb(stream, UV_ENOBUFS, &buf); return; } assert(buf.base != NULL); assert(uv__stream_fd(stream) >= 0); if (!is_ipc) { do { nread = read(uv__stream_fd(stream), buf.base, buf.len); } while (nread < 0 && errno == EINTR); } else { /* ipc uses recvmsg */ msg.msg_flags = 0; msg.msg_iov = (struct iovec*) &buf; msg.msg_iovlen = 1; msg.msg_name = NULL; msg.msg_namelen = 0; /* Set up to receive a descriptor even if one isn't in the message */ msg.msg_controllen = sizeof(cmsg_space); msg.msg_control = cmsg_space; do { nread = uv__recvmsg(uv__stream_fd(stream), &msg, 0); } while (nread < 0 && errno == EINTR); } if (nread < 0) { /* Error */ if (errno == EAGAIN || errno == EWOULDBLOCK) { /* Wait for the next one. */ if (stream->flags & UV_STREAM_READING) { uv__io_start(stream->loop, &stream->io_watcher, UV__POLLIN); uv__stream_osx_interrupt_select(stream); } stream->read_cb(stream, 0, &buf); } else { /* Error. User should call uv_close(). */ stream->read_cb(stream, -errno, &buf); assert(!uv__io_active(&stream->io_watcher, UV__POLLIN) && "stream->read_cb(status=-1) did not call uv_close()"); } return; } else if (nread == 0) { uv__stream_eof(stream, &buf); return; } else { /* Successful read */ ssize_t buflen = buf.len; if (is_ipc) { err = uv__stream_recv_cmsg(stream, &msg); if (err != 0) { stream->read_cb(stream, err, &buf); return; } } stream->read_cb(stream, nread, &buf); /* Return if we didn't fill the buffer, there is no more data to read. */ if (nread < buflen) { stream->flags |= UV_STREAM_READ_PARTIAL; return; } } } } #undef UV__CMSG_FD_COUNT #undef UV__CMSG_FD_SIZE int uv_shutdown(uv_shutdown_t* req, uv_stream_t* stream, uv_shutdown_cb cb) { assert((stream->type == UV_TCP || stream->type == UV_NAMED_PIPE) && "uv_shutdown (unix) only supports uv_handle_t right now"); if (!(stream->flags & UV_STREAM_WRITABLE) || stream->flags & UV_STREAM_SHUT || stream->flags & UV_STREAM_SHUTTING || stream->flags & UV_CLOSED || stream->flags & UV_CLOSING) { return -ENOTCONN; } assert(uv__stream_fd(stream) >= 0); /* Initialize request */ uv__req_init(stream->loop, req, UV_SHUTDOWN); req->handle = stream; req->cb = cb; stream->shutdown_req = req; stream->flags |= UV_STREAM_SHUTTING; uv__io_start(stream->loop, &stream->io_watcher, UV__POLLOUT); uv__stream_osx_interrupt_select(stream); return 0; } static void uv__stream_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) { uv_stream_t* stream; stream = container_of(w, uv_stream_t, io_watcher); assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE || stream->type == UV_TTY); assert(!(stream->flags & UV_CLOSING)); if (stream->connect_req) { uv__stream_connect(stream); return; } assert(uv__stream_fd(stream) >= 0); /* Ignore POLLHUP here. Even it it's set, there may still be data to read. */ if (events & (UV__POLLIN | UV__POLLERR)) uv__read(stream); if (uv__stream_fd(stream) == -1) return; /* read_cb closed stream. */ /* Short-circuit iff POLLHUP is set, the user is still interested in read * events and uv__read() reported a partial read but not EOF. If the EOF * flag is set, uv__read() called read_cb with err=UV_EOF and we don't * have to do anything. If the partial read flag is not set, we can't * report the EOF yet because there is still data to read. */ if ((events & UV__POLLHUP) && (stream->flags & UV_STREAM_READING) && (stream->flags & UV_STREAM_READ_PARTIAL) && !(stream->flags & UV_STREAM_READ_EOF)) { uv_buf_t buf = { NULL, 0 }; uv__stream_eof(stream, &buf); } if (uv__stream_fd(stream) == -1) return; /* read_cb closed stream. */ if (events & (UV__POLLOUT | UV__POLLERR | UV__POLLHUP)) { uv__write(stream); uv__write_callbacks(stream); } } /** * We get called here from directly following a call to connect(2). * In order to determine if we've errored out or succeeded must call * getsockopt. */ static void uv__stream_connect(uv_stream_t* stream) { int error; uv_connect_t* req = stream->connect_req; socklen_t errorsize = sizeof(int); assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE); assert(req); if (stream->delayed_error) { /* To smooth over the differences between unixes errors that * were reported synchronously on the first connect can be delayed * until the next tick--which is now. */ error = stream->delayed_error; stream->delayed_error = 0; } else { /* Normal situation: we need to get the socket error from the kernel. */ assert(uv__stream_fd(stream) >= 0); getsockopt(uv__stream_fd(stream), SOL_SOCKET, SO_ERROR, &error, &errorsize); error = -error; } if (error == -EINPROGRESS) return; stream->connect_req = NULL; uv__req_unregister(stream->loop, req); uv__io_stop(stream->loop, &stream->io_watcher, UV__POLLOUT); if (req->cb) req->cb(req, error); } int uv_write2(uv_write_t* req, uv_stream_t* stream, const uv_buf_t bufs[], unsigned int nbufs, uv_stream_t* send_handle, uv_write_cb cb) { int empty_queue; assert(nbufs > 0); assert((stream->type == UV_TCP || stream->type == UV_NAMED_PIPE || stream->type == UV_TTY) && "uv_write (unix) does not yet support other types of streams"); if (uv__stream_fd(stream) < 0) return -EBADF; if (send_handle) { if (stream->type != UV_NAMED_PIPE || !((uv_pipe_t*)stream)->ipc) return -EINVAL; /* XXX We abuse uv_write2() to send over UDP handles to child processes. * Don't call uv__stream_fd() on those handles, it's a macro that on OS X * evaluates to a function that operates on a uv_stream_t with a couple of * OS X specific fields. On other Unices it does (handle)->io_watcher.fd, * which works but only by accident. */ if (uv__handle_fd((uv_handle_t*) send_handle) < 0) return -EBADF; } /* It's legal for write_queue_size > 0 even when the write_queue is empty; * it means there are error-state requests in the write_completed_queue that * will touch up write_queue_size later, see also uv__write_req_finish(). * We chould check that write_queue is empty instead but that implies making * a write() syscall when we know that the handle is in error mode. */ empty_queue = (stream->write_queue_size == 0); /* Initialize the req */ uv__req_init(stream->loop, req, UV_WRITE); req->cb = cb; req->handle = stream; req->error = 0; req->send_handle = send_handle; QUEUE_INIT(&req->queue); req->bufs = req->bufsml; if (nbufs > ARRAY_SIZE(req->bufsml)) req->bufs = malloc(nbufs * sizeof(bufs[0])); if (req->bufs == NULL) return -ENOMEM; memcpy(req->bufs, bufs, nbufs * sizeof(bufs[0])); req->nbufs = nbufs; req->write_index = 0; stream->write_queue_size += uv__count_bufs(bufs, nbufs); /* Append the request to write_queue. */ QUEUE_INSERT_TAIL(&stream->write_queue, &req->queue); /* If the queue was empty when this function began, we should attempt to * do the write immediately. Otherwise start the write_watcher and wait * for the fd to become writable. */ if (stream->connect_req) { /* Still connecting, do nothing. */ } else if (empty_queue) { uv__write(stream); } else { /* * blocking streams should never have anything in the queue. * if this assert fires then somehow the blocking stream isn't being * sufficiently flushed in uv__write. */ assert(!(stream->flags & UV_STREAM_BLOCKING)); uv__io_start(stream->loop, &stream->io_watcher, UV__POLLOUT); uv__stream_osx_interrupt_select(stream); } return 0; } /* The buffers to be written must remain valid until the callback is called. * This is not required for the uv_buf_t array. */ int uv_write(uv_write_t* req, uv_stream_t* handle, const uv_buf_t bufs[], unsigned int nbufs, uv_write_cb cb) { return uv_write2(req, handle, bufs, nbufs, NULL, cb); } void uv_try_write_cb(uv_write_t* req, int status) { /* Should not be called */ abort(); } int uv_try_write(uv_stream_t* stream, const uv_buf_t bufs[], unsigned int nbufs) { int r; int has_pollout; size_t written; size_t req_size; uv_write_t req; /* Connecting or already writing some data */ if (stream->connect_req != NULL || stream->write_queue_size != 0) return -EAGAIN; has_pollout = uv__io_active(&stream->io_watcher, UV__POLLOUT); r = uv_write(&req, stream, bufs, nbufs, uv_try_write_cb); if (r != 0) return r; /* Remove not written bytes from write queue size */ written = uv__count_bufs(bufs, nbufs); if (req.bufs != NULL) req_size = uv__write_req_size(&req); else req_size = 0; written -= req_size; stream->write_queue_size -= req_size; /* Unqueue request, regardless of immediateness */ QUEUE_REMOVE(&req.queue); uv__req_unregister(stream->loop, &req); if (req.bufs != req.bufsml) free(req.bufs); req.bufs = NULL; /* Do not poll for writable, if we wasn't before calling this */ if (!has_pollout) { uv__io_stop(stream->loop, &stream->io_watcher, UV__POLLOUT); uv__stream_osx_interrupt_select(stream); } if (written == 0) return -EAGAIN; else return written; } int uv_read_start(uv_stream_t* stream, uv_alloc_cb alloc_cb, uv_read_cb read_cb) { assert(stream->type == UV_TCP || stream->type == UV_NAMED_PIPE || stream->type == UV_TTY); if (stream->flags & UV_CLOSING) return -EINVAL; /* The UV_STREAM_READING flag is irrelevant of the state of the tcp - it just * expresses the desired state of the user. */ stream->flags |= UV_STREAM_READING; /* TODO: try to do the read inline? */ /* TODO: keep track of tcp state. If we've gotten a EOF then we should * not start the IO watcher. */ assert(uv__stream_fd(stream) >= 0); assert(alloc_cb); stream->read_cb = read_cb; stream->alloc_cb = alloc_cb; uv__io_start(stream->loop, &stream->io_watcher, UV__POLLIN); uv__handle_start(stream); uv__stream_osx_interrupt_select(stream); return 0; } int uv_read_stop(uv_stream_t* stream) { /* Sanity check. We're going to stop the handle unless it's primed for * writing but that means there should be some kind of write action in * progress. */ assert(!uv__io_active(&stream->io_watcher, UV__POLLOUT) || !QUEUE_EMPTY(&stream->write_completed_queue) || !QUEUE_EMPTY(&stream->write_queue) || stream->shutdown_req != NULL || stream->connect_req != NULL); stream->flags &= ~UV_STREAM_READING; uv__io_stop(stream->loop, &stream->io_watcher, UV__POLLIN); if (!uv__io_active(&stream->io_watcher, UV__POLLOUT)) uv__handle_stop(stream); uv__stream_osx_interrupt_select(stream); stream->read_cb = NULL; stream->alloc_cb = NULL; return 0; } int uv_is_readable(const uv_stream_t* stream) { return !!(stream->flags & UV_STREAM_READABLE); } int uv_is_writable(const uv_stream_t* stream) { return !!(stream->flags & UV_STREAM_WRITABLE); } #if defined(__APPLE__) int uv___stream_fd(const uv_stream_t* handle) { const uv__stream_select_t* s; assert(handle->type == UV_TCP || handle->type == UV_TTY || handle->type == UV_NAMED_PIPE); s = handle->select; if (s != NULL) return s->fd; return handle->io_watcher.fd; } #endif /* defined(__APPLE__) */ void uv__stream_close(uv_stream_t* handle) { unsigned int i; uv__stream_queued_fds_t* queued_fds; #if defined(__APPLE__) /* Terminate select loop first */ if (handle->select != NULL) { uv__stream_select_t* s; s = handle->select; uv_sem_post(&s->close_sem); uv_sem_post(&s->async_sem); uv__stream_osx_interrupt_select(handle); uv_thread_join(&s->thread); uv_sem_destroy(&s->close_sem); uv_sem_destroy(&s->async_sem); uv__close(s->fake_fd); uv__close(s->int_fd); uv_close((uv_handle_t*) &s->async, uv__stream_osx_cb_close); handle->select = NULL; } #endif /* defined(__APPLE__) */ uv__io_close(handle->loop, &handle->io_watcher); uv_read_stop(handle); uv__handle_stop(handle); if (handle->io_watcher.fd != -1) { /* Don't close stdio file descriptors. Nothing good comes from it. */ if (handle->io_watcher.fd > STDERR_FILENO) uv__close(handle->io_watcher.fd); handle->io_watcher.fd = -1; } if (handle->accepted_fd != -1) { uv__close(handle->accepted_fd); handle->accepted_fd = -1; } /* Close all queued fds */ if (handle->queued_fds != NULL) { queued_fds = handle->queued_fds; for (i = 0; i < queued_fds->offset; i++) uv__close(queued_fds->fds[i]); free(handle->queued_fds); handle->queued_fds = NULL; } assert(!uv__io_active(&handle->io_watcher, UV__POLLIN | UV__POLLOUT)); } int uv_stream_set_blocking(uv_stream_t* handle, int blocking) { return UV_ENOSYS; }
// Copyright 2016 David Lavieri. All rights reserved. // Use of this source code is governed by a MIT License // License that can be found in the LICENSE file. package main import ( "fmt" "github.com/falmar/goradix" ) func main() { radix := goradix.New(false) radix.Insert("romanus", 1) radix.Insert("romane", 100) radix.Insert("romulus", 1000) value, err := radix.LookUp("romane") if err != nil { // No Match Found return } // Output: Found node, Value: 100 fmt.Println("Found node, Value: ", value) }
module.exports = api => { api.cache(true); return { presets: [ [ '@babel/preset-env', { targets: { node: '12' } } ] ] }; };
@echo off .paket\paket.bootstrapper.exe if errorlevel 1 ( exit /b %errorlevel% ) .paket\paket.exe restore -v if errorlevel 1 ( exit /b %errorlevel% )
<?php /* * This file is part of HabitRPG-GitHub. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace tests; require_once(__DIR__.'/../scripts/session.php'); require_once(__DIR__.'/../scripts/serviceFunctions.php'); /** * This class tests the HabitRPGAPI class. * * To run: * phpunit --bootstrap tests/bootstrap.php tests/serviceFunctionsTest * * @author Bradley Wogsland <bradley@wogsland.org> */ class serviceFunctionsTest extends \PHPUnit_Framework_TestCase { /** * Tests the newCommit function. */ public function test_newCommit () { $repoName = 'wogsland/HabitRPG-GitHub'; $user = 'wogsland'; $count = 2; $token = 'cLFWwvNKC2exK'; newCommit($repoName, $user, $count, $token); //$this->assertEquals($test_name, $test->userId); //$this->assertEquals($test_token, $test->apiToken); //$this->assertEquals('https://habitrpg.com/api/v2/', $test->apiURL); } }
cask 'font-monoid-loose-large-dollar-l' do version :latest sha256 :no_check # github.com/larsenwork/monoid was verified as official when first introduced to the cask url 'https://github.com/larsenwork/monoid/blob/release/Monoid-Loose-Large-Dollar-l.zip?raw=true' name 'Monoid-Loose-Large-Dollar-l' homepage 'http://larsenwork.com/monoid/' font 'Monoid-Bold-Loose-Large-Dollar-l.ttf' font 'Monoid-Italic-Loose-Large-Dollar-l.ttf' font 'Monoid-Regular-Loose-Large-Dollar-l.ttf' font 'Monoid-Retina-Loose-Large-Dollar-l.ttf' caveats <<~EOS #{token} is dual licensed with MIT and OFL licenses. https://github.com/larsenwork/monoid/tree/master#license EOS end
/* * Copyright (c) 2017-2018 Arm Limited. * * SPDX-License-Identifier: MIT * * 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. */ #include "GEMM.h" #include "arm_compute/core/Types.h" namespace arm_compute { namespace test { namespace validation { namespace reference { template <typename T> SimpleTensor<T> gemm_interleave_4x4(const SimpleTensor<T> &in, SimpleTensor<T> &out) { const T *mtx_in = reinterpret_cast<const T *>(in.data()); T *mtx_ref = reinterpret_cast<T *>(out.data()); const int32_t in_rows = in.shape().y(); const int32_t in_cols = in.shape().x(); const int32_t out_stride = out.shape().x(); int32_t y = 0; for(; y <= (in_rows - 4); y += 4) { const T *in_ptr = &mtx_in[y * in_cols]; for(int32_t x = 0; x < in_cols; x++) { const T tmp[4] = { in_ptr[x + 0 * in_cols], in_ptr[x + 1 * in_cols], in_ptr[x + 2 * in_cols], in_ptr[x + 3 * in_cols] }; T *dst = &mtx_ref[static_cast<size_t>(x * 4.f) + static_cast<size_t>(std::ceil(y / 4.f)) * out_stride]; memcpy(dst, tmp, sizeof(T) * 4); } } // Leftover along the Y direction const int32_t leftover_y = in_rows - y; if(leftover_y != 0) { const T *in_ptr = &mtx_in[y * in_cols]; for(int32_t x = 0; x < in_cols; x++) { T tmp[4] = { 0, 0, 0, 0 }; for(int32_t k = 0; k < leftover_y; k++) { tmp[k] = in_ptr[k * in_cols + x]; } T *dst = &mtx_ref[static_cast<size_t>(x * 4.f) + static_cast<size_t>(std::ceil(y / 4.f)) * out_stride]; memcpy(dst, tmp, sizeof(T) * 4); } } return out; } } // namespace reference } // namespace validation } // namespace test } // namespace arm_compute
Code-signing private key notes == The private keys for these certificates were generated on Gavin's main work machine, following the certificate authoritys' recommendations for generating certificate signing requests. For OSX, the private key was generated by Keychain.app on Gavin's main work machine. The key and certificate is in a separate, passphrase-protected keychain file that is unlocked to sign the Titcoin-Qt.app bundle. For Windows, the private key was generated by Firefox running on Gavin's main work machine. The key and certificate were exported into a separate, passphrase-protected PKCS#12 file, and then deleted from Firefox's keystore. The exported file is used to sign the Windows setup.exe. Threat analysis -- Gavin is a single point of failure. He could be coerced to divulge the secret signing keys, allowing somebody to distribute a Titcoin-Qt.app or bitcoin-qt-setup.exe with a valid signature but containing a malicious binary. Or the machine Gavin uses to sign the binaries could be compromised, either remotely or by breaking in to his office, allowing the attacker to get the private key files and then install a keylogger to get the passphrase that protects them. Threat Mitigation -- "Air gapping" the machine used to do the signing will not work, because the signing process needs to access a timestamp server over the network. And it would not prevent the "rubber hose cryptography" threat (coercing Gavin to sign a bad binary or divulge the private keys). Windows binaries are reproducibly 'gitian-built', and the setup.exe file created by the NSIS installer system is a 7zip archive, so you could check to make sure that the titcoin-qt.exe file inside the installer had not been tampered with. However, an attacker could modify the installer's code, so when the setup.exe was run it compromised users' systems. A volunteer to write an auditing tool that checks the setup.exe for tampering, and checks the files in it against the list of gitian signatures, is needed. The long-term solution is something like the 'gitian downloader' system, which uses signatures from multiple developers to determine whether or not a binary should be trusted. However, that just pushes the problem to "how will non-technical users securely get the gitian downloader code to start?"
# -*- coding: utf-8 -*- #!/usr/bin/python import numpy as np import scipy from sklearn import preprocessing from sklearn.feature_extraction import DictVectorizer from sklearn.cross_validation import train_test_split from sklearn.metrics import classification_report, confusion_matrix from collections import Counter from scipy.stats.stats import pearsonr import data_readers import feature_extractors as fe import label_transformers as lt import training_functions as training import utils def build_dataset(reader, phi_list, class_func, vectorizer=None, verbose=False): """Core general function for building experimental hand-generated feature datasets. Parameters ---------- reader : iterator Should follow the format of data_readers. This is the dataset we'll be featurizing. phi_list : array of feature functions (default: [`manual_content_flags`]) Any function that takes a string as input and returns a bool/int/float-valued dict as output. class_func : function on the labels A function that modifies the labels based on the experimental design. If `class_func` returns None for a label, then that item is ignored. vectorizer : sklearn.feature_extraction.DictVectorizer If this is None, then a new `DictVectorizer` is created and used to turn the list of dicts created by `phi` into a feature matrix. This happens when we are training. If this is not None, then it's assumed to be a `DictVectorizer` and used to transform the list of dicts. This happens in assessment, when we take in new instances and need to featurize them as we did in training. Returns ------- dict A dict with keys 'X' (the feature matrix), 'y' (the list of labels), 'vectorizer' (the `DictVectorizer`), and 'raw_examples' (the example strings, for error analysis). """ labels = [] feat_dicts = [] raw_examples = [] rows = [] for i, (paragraph, parse, label) in enumerate(reader()): if i % 100 == 0: print " Starting feature extraction for unit #%d " % (i+1) cls = class_func(label) #print label, cls if cls != None: labels.append(cls) raw_examples.append(paragraph) if verbose: print cls, ":", paragraph features = Counter() for phi in phi_list: cur_feats = phi(paragraph, parse) if cur_feats is None: continue # If we won't accidentally blow away data, merge 'em. overlap_feature_names = features.viewkeys() & cur_feats.viewkeys() if verbose and len(overlap_feature_names) > 0: print "Note: Overlap features are ", overlap_feature_names features |= cur_feats rows.append(cur_feats['row']) feat_dicts.append(features) if verbose: print features print print "Completed all feature extraction: %d units" % (i+1) # In training, we want a new vectorizer, but in # assessment, we featurize using the existing vectorizer: feat_matrix = None if vectorizer == None: vectorizer = DictVectorizer(sparse=True) feat_matrix = vectorizer.fit_transform(feat_dicts) else: feat_matrix = vectorizer.transform(feat_dicts) return {'X': feat_matrix, 'y': labels, 'vectorizer': vectorizer, 'raw_examples': raw_examples} def experiment_features( train_reader=data_readers.toy, assess_reader=None, train_size=0.7, phi_list=[fe.manual_content_flags], class_func=lt.identity_class_func, train_func=training.fit_logistic_at_with_crossvalidation, score_func=scipy.stats.stats.pearsonr, verbose=True): """Generic experimental framework for hand-crafted features. Either assesses with a random train/test split of `train_reader` or with `assess_reader` if it is given. Parameters ---------- train_reader : data iterator (default: `train_reader`) Iterator for training data. assess_reader : iterator or None (default: None) If None, then the data from `train_reader` are split into a random train/test split, with the the train percentage determined by `train_size`. If not None, then this should be an iterator for assessment data (e.g., `dev_reader`). train_size : float (default: 0.7) If `assess_reader` is None, then this is the percentage of `train_reader` devoted to training. If `assess_reader` is not None, then this value is ignored. phi_list : array of feature functions (default: [`manual_content_flags`]) Any function that takes a string as input and returns a bool/int/float-valued dict as output. class_func : function on the labels A function that modifies the labels based on the experimental design. If `class_func` returns None for a label, then that item is ignored. train_func : model wrapper (default: `fit_logistic_at_with_crossvalidation`) Any function that takes a feature matrix and a label list as its values and returns a fitted model with a `predict` function that operates on feature matrices. score_metric : function name (default: `utils.safe_weighted_f1`) This should be an `sklearn.metrics` scoring function. The default is weighted average F1. verbose : bool (default: True) Whether to print out the model assessment to standard output. Prints ------- To standard output, if `verbose=True` Model confusion matrix and a model precision/recall/F1 report. Returns ------- float The overall scoring metric for assess set as determined by `score_metric`. float The overall Cronbach's alpha for assess set np.array The confusion matrix (rows are truth, columns are predictions) list of dictionaries A list of {truth:_ , prediction:_, example:_} dicts on the assessment data """ # Train dataset: train = build_dataset(train_reader, phi_list, class_func, vectorizer=None, verbose=verbose) # Manage the assessment set-up: indices = np.arange(0, len(train['y'])) X_train = train['X'] y_train = np.array(train['y']) train_examples = np.array(train['raw_examples']) X_assess = None y_assess = None assess_examples = None if assess_reader == None: print " Raw y training distribution:" print " ", np.bincount(y_train)[1:] indices_train, indices_assess, y_train, y_assess = train_test_split( indices, y_train, train_size=train_size, stratify=y_train) X_assess = X_train[indices_assess] assess_examples = train_examples[indices_assess] X_train = X_train[indices_train] train_examples = train_examples[indices_train] print " Train y distribution:" print " ", np.bincount(y_train)[1:] print " Test y distribution:" print " ", np.bincount(y_assess)[1:] else: assess = build_dataset( assess_reader, phi_list, class_func, vectorizer=train['vectorizer']) X_assess, y_assess, assess_examples = assess['X'], assess['y'], np.array(assess['raw_examples']) # Normalize: nonzero_cells = len(X_train.nonzero()[0]) total_cells = 1.*X_train.shape[0] * X_train.shape[1] proportion_nonzero = nonzero_cells/total_cells print "sparsity: %g/1 are nonzero" % proportion_nonzero if proportion_nonzero > 0.5: # if dense matrix X_train = X_train.toarray() X_assess = X_assess.toarray() scaler = preprocessing.StandardScaler().fit(X_train) X_train = scaler.transform(X_train) X_assess = scaler.transform(X_assess) else: scaler = preprocessing.MaxAbsScaler().fit(X_train) X_train = scaler.transform(X_train) X_assess = scaler.transform(X_assess) # Train: mod = train_func(X_train, y_train) # Predictions: predictions_on_assess = mod.predict(X_assess) assess_performance = get_score_example_pairs(y_assess, predictions_on_assess, assess_examples) predictions_on_train = mod.predict(X_train) train_performance = get_score_example_pairs(y_train, predictions_on_train, train_examples) # Report: if verbose: print "\n-- TRAINING RESULTS --" print_verbose_overview(y_train, predictions_on_train) print "\n-- ASSESSMENT RESULTS --" print_verbose_overview(y_assess, predictions_on_assess) try: the_score = score_func(y_assess, predictions_on_assess) except: the_score = (0,0) # Return the overall results on the assessment data: return the_score, \ utils.cronbach_alpha(y_assess, predictions_on_assess), \ confusion_matrix(y_assess, predictions_on_assess), \ assess_performance def get_score_example_pairs(y, y_hat, examples): """ Return a list of dicts: {truth score, predicted score, example} """ paired_results = sorted(zip(y, y_hat), key=lambda x: x[0]-x[1]) performance = [] for i, (truth, prediction) in enumerate(paired_results): performance.append({"truth": truth, "prediction": prediction, "example": examples[i]}) return performance def print_verbose_overview(y, yhat): """ Print a performance overview """ print "Correlation: ", pearsonr(y, yhat)[0] print "Alpha: ", utils.cronbach_alpha(y, yhat) print "Classification report:" print classification_report(y, yhat, digits=3) print "Confusion matrix:" print confusion_matrix(y, yhat) print " (Rows are truth; columns are predictions)" def experiment_features_iterated( train_reader=data_readers.toy, assess_reader=None, train_size=0.7, phi_list=[fe.manual_content_flags], class_func=lt.identity_class_func, train_func=training.fit_logistic_at_with_crossvalidation, score_func=utils.safe_weighted_f1, verbose=True, iterations=1): """ Generic iterated experimental framework for hand-crafted features. """ correlation_overall = [] cronbach_overall = [] conf_matrix_overall = None assess_performance = [] while len(correlation_overall) < iterations: print "\nStarting iteration: %d/%d" % (len(correlation_overall)+1, iterations) try: correlation_local, cronbach_local, conf_matrix_local, perf_local = experiment_features( train_reader=train_reader, assess_reader=assess_reader, train_size=train_size, phi_list=phi_list, class_func=class_func, train_func=train_func, score_func=score_func, verbose=verbose) correlation_overall.append(correlation_local[0]) cronbach_overall.append(cronbach_local) assess_performance.extend(perf_local) if conf_matrix_overall is None: conf_matrix_overall = conf_matrix_local else: conf_matrix_overall += conf_matrix_local except (ValueError,UserWarning) as e: print e if verbose: print "\n-- OVERALL --" print correlation_overall print cronbach_overall print conf_matrix_overall return correlation_overall, cronbach_overall, conf_matrix_overall, assess_performance
package com.artbeatte.launchpad; import com.google.common.collect.ImmutableMap; import io.dropwizard.Configuration; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.db.DataSourceFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.Map; /** * @author art.beatte * @version 7/14/15 */ public class LaunchpadConfiguration extends Configuration { @Valid @NotNull private DataSourceFactory database = new DataSourceFactory(); @NotNull private Map<String, Map<String, String>> viewRendererConfiguration = Collections.emptyMap(); @JsonProperty("database") public DataSourceFactory getDataSourceFactory() { return database; } @JsonProperty("database") public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { this.database = dataSourceFactory; } @JsonProperty("viewRendererConfiguration") public Map<String, Map<String, String>> getViewRendererConfiguration() { return viewRendererConfiguration; } @JsonProperty("viewRendererConfiguration") public void setViewRendererConfiguration(Map<String, Map<String, String>> viewRendererConfiguration) { ImmutableMap.Builder<String, Map<String, String>> builder = ImmutableMap.builder(); for (Map.Entry<String, Map<String, String>> entry : viewRendererConfiguration.entrySet()) { builder.put(entry.getKey(), ImmutableMap.copyOf(entry.getValue())); } this.viewRendererConfiguration = builder.build(); } }
require 'net/http' require 'uri' require 'nokogiri' module Discover class Device attr_reader :ip attr_reader :port attr_reader :description_url attr_reader :server attr_reader :service_type attr_reader :usn attr_reader :url_base attr_reader :name attr_reader :manufacturer attr_reader :manufacturer_url attr_reader :model_name attr_reader :model_number attr_reader :model_description attr_reader :model_url attr_reader :serial_number attr_reader :software_version attr_reader :hardware_version def initialize(info) headers = {} info[0].split("\r\n").each do |line| matches = line.match(/^([\w\-]+):(?:\s)*(.*)$/) next unless matches headers[matches[1].upcase] = matches[2] end @description_url = headers['LOCATION'] @server = headers['SERVER'] @service_type = headers['ST'] @usn = headers['USN'] info = info[1] @port = info[1] @ip = info[2] get_description end protected def get_description response = Net::HTTP.get_response(URI.parse(description_url)) doc = Nokogiri::XML(response.body) map = { name: 'friendlyName', manufacturer: 'manufacturer', model_name: 'modelName', model_number: 'modelNumber', model_description: 'modelDescription', model_url: 'modelURL', software_version: 'softwareVersion', hardware_version: 'hardwareVersion' } map.each do |key, xml_key| next unless node = doc.css("/root/device/#{xml_key}").first instance_variable_set("@#{key}".to_sym, node.inner_text) end @serial_number = (doc.css('/root/device/serialNumber').first || doc.css('/root/device/serialNum').first).inner_text end end end
/** * This is a generated file. Do not edit or your changes will be lost */ @interface ComPlainprogramsStreamingmetadataModuleAssets : NSObject { } - (NSData*) moduleAsset; @end
'use strict'; function UserListController(userList) { var vm = this; console.log('UserListController'); vm.userList = userList; } module.exports = UserListController;
using myOC_WebApp.IoC; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace myOC_WebApp.Controllers { public class HomeController : Controller, IHomeController { private readonly ILogger _logger; public HomeController(ILogger logger) { this._logger = logger; _logger.Log("======== Started using injected constructor"); } public HomeController() : this((ILogger)MyIoC.Resolve(typeof(ILogger))){ } public ActionResult Index() { ViewBag.Message = "The All-Glorious Index Page"; _logger.Log("Visited the index through home controller"); return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; _logger.Log("Visited the About page through home controller"); return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
import sys, os, fabric class PiServicePolicies: @staticmethod def is_local(): return (not fabric.api.env.hosts or fabric.api.env.hosts[0] in ['localhost', '127.0.0.1', '::1']) @staticmethod def is_pi(): return os.path.isdir('/home/pi') @staticmethod def check_local_or_exit(): if not PiServicePolicies.is_local(): print "...only callable on localhost!!!" sys.exit(-1) @staticmethod def check_remote_or_exit(): if PiServicePolicies.is_local(): print "...only callable on remote host!!!" sys.exit(-1) def check_installed_or_exit(self): if not PiServicePolicies.installed(self): print "...first you have to install this service! fab pi %s:install" sys.exit(-1) def installed(self): ret = self.file_exists('__init__.py') if not ret: print self.name+' not installed' return ret
#include "Core.h" #include "Async/ActionGraph.h" #include "ActionGraphImplementation.h" std::shared_ptr<ActionGraphInterface> ActionGraphInterface::c_graphImp = nullptr; std::weak_ptr<ActionGraphInterface> ActionGraphInterface::Get() { // if it`s not init, just crash. check(c_graphImp != nullptr); return c_graphImp; } void ActionGraphInterface::Init(const unsigned int& inWorkThreadNum) { c_graphImp = std::shared_ptr<ActionGraphInterface>(new ActionGraphImplementation()); c_graphImp->ConstructWorkThread(inWorkThreadNum); }
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <div class="container"> <div class="row margin-bottom-10"> <div class="col-md-4 col-sm-6"> <div class="servive-block servive-block-grey"> <i class="icon-2x color-light fa fa-bell-o"></i> <h2 class="heading-md">Grey Box</h2> <p>Donec id elit non mi porta gravida at eget metus id elit mi egetine. Fusce dapibus</p> </div> </div> <div class="col-md-4 col-sm-6"> <div class="servive-block servive-block-yellow"> <i class="icon-2x color-light fa fa-envelope"></i> <h2 class="heading-md">Yellow Box</h2> <p>Donec id elit non mi porta gravida at eget metus id elit mi egetine usce dapibus elit nondapibus</p> </div> </div> <div class="col-md-4 col-sm-12"> <div class="servive-block servive-block-dark-blue"> <i class="icon-2x color-light fa fa-gift"></i> <h2 class="heading-md">Dark Blue Box</h2> <p>Donec id elit non mi porta gravida at eget metus id elit mi egetine. Fusce dapibus</p> </div> </div> </div> <div class="row margin-bottom-10"> <div class="col-sm-6"> <div class="servive-block servive-block-purple"> <i class="icon-2x color-light fa fa-globe"></i> <h2 class="heading-md">Purple Box</h2> <p>Donec id elit non mi porta gravida at eget metus id elit mi egetine. Fusce dapibus. At vero eos et accusamus et iusto odio dignissimos ducimus qui.</p> </div> </div> <div class="col-sm-6"> <div class="servive-block rounded servive-block-aqua"> <i class="icon-2x color-light fa fa-taxi"></i> <h2 class="heading-md">Aqua Box</h2> <p>Donec id elit non mi porta gravida at eget metus id elit mi egetine. Fusce dapibus. At vero eos et accusamus et iusto odio dignissimos ducimus qui.</p> </div> </div> </div> </div>
import cv2, numpy as np from dolphintracker.singlecam_tracker.camera_filter.FindDolphin import SearchBlobs from dolphintracker.singlecam_tracker.camera_filter.BackGroundDetector import BackGroundDetector import datetime class PoolCamera(object): def __init__(self, videofile, name, scene, maskObjectsNames, filters, frames_range=None): self.name = name self.videoCap = cv2.VideoCapture(videofile) self.scene = scene self.filters = filters self.mask = self.create_mask(maskObjectsNames) self.frames_range = frames_range self._searchblobs = SearchBlobs() self._backgrounds = [] self._last_centroid = None if self.frames_range is not None: self.videoCap.set(cv2.CAP_PROP_POS_FRAMES, self.frames_range[0]) print('set first frame', self.frames_range) self._total_frames = self.videoCap.get(7) self._colors = [(255,0,0),(0,255,0),(0,0,255)] def create_mask(self, objectsNames): mask = np.zeros((self.img_height,self.img_width), np.uint8) for objname in objectsNames: obj = self.scene.getObject(objname) ptsProjection = self.points_projection( [p for p in obj.points if p[2]<0.2] ) hull = cv2.convexHull(np.int32(ptsProjection)) cv2.fillPoly(mask, np.int32([hull]), 255) return mask def read(self): res, self.frame = self.videoCap.read() if res: self.originalFrame = self.frame.copy() else: self.originalFrame = None return res def process(self): if len(self._backgrounds)==0: for i, colorFilter in enumerate(self.filters): firstFrame = self.frame_index bgDetector = BackGroundDetector(capture=self.videoCap, filterFunction=colorFilter.process) print('Background detection parameters', self._total_frames*0.04, self._total_frames*0.03) last_frame = self.frames_range[1] if self.frames_range is not None else None bg = bgDetector.detect(int(self._total_frames*0.04), int(self._total_frames*0.03), 180, last_frame) bg = cv2.dilate( bg, kernel=cv2.getStructuringElement( cv2.MORPH_RECT, (5,5) ), iterations=2 ) bg = 255-bg bg[bg<255]=0 self._backgrounds.append( cv2.bitwise_and(bg, self.mask) ) self.frame_index = firstFrame result = [] for i, colorFilter in enumerate(self.filters): filterResult = colorFilter.filter(self.frame, self._backgrounds[i]) blobs = self._searchblobs.process(filterResult) res = blobs[0] if len(blobs)>=1 else None result.append(res) return result def create_empty_mask(self): return np.zeros( (self.img_height, self.img_width), np.uint8 ) def points_projection(self, points): cam = self.scene_camera; return [cam.calcPixel(*p) for p in points] @property def scene_camera(self): return self.scene.getCamera(self.name) @property def img_width(self): return int( self.videoCap.get(cv2.CAP_PROP_FRAME_WIDTH) ) @property def img_height(self): return int( self.videoCap.get(cv2.CAP_PROP_FRAME_HEIGHT) ) @property def fps(self): return int( self.videoCap.get(cv2.CAP_PROP_FPS) ) @property def frame_index(self): return int( self.videoCap.get(cv2.CAP_PROP_POS_FRAMES) ) @frame_index.setter def frame_index(self, value): self.videoCap.set(cv2.CAP_PROP_POS_FRAMES, value) @property def currentTime(self): milli = self.videoCap.get(cv2.CAP_PROP_POS_MSEC) return datetime.timedelta(milliseconds=milli) @property def totalFrames(self): return self.videoCap.get(cv2.CAP_PROP_FRAME_COUNT)
import log from 'log'; import Ember from 'ember'; import {registerComponent} from 'ember-utils'; import layout from './confirm-toolbar.hbs!'; export var RheaConfirmToolbar = Ember.Component.extend({ layout, tagName: '', actions: { confirm: function(opID) { this.sendAction('confirm'); }, cancel: function(opID) { this.sendAction('cancel'); } } }); registerComponent('rhea-confirm-toolbar', RheaConfirmToolbar);
--- title: Réflexion avancée date: 10/12/2021 --- « Ceci [Michée 6:1-8] est l’un des grands passages de l’Ancient Testament. Il incarne, tout comme Amos 5:24 et osée. 6:6, le message des prophètes du VIIIe siècle. Le passage s’ouvre sur un bel exemple d’un procès d’alliance dans lequel le prophète convoque le peuple pour entendre l’accusation que Yahvé a contre eux. Les montagnes et les collines sont les jurys parce qu’ils existaient depuis longtemps et étaient témoins de l’histoire de Dieu avec Israël. Plutôt que d’accuser directement Israël de rompre l’alliance, Dieu demande à Israël s’il a des accusations contre Lui. ‘‘Que t’ai-je fait? En quoi t’ai-je fatigué?’’ Face à l’injustice, certains pauvres étaient peut-être devenus ‘‘fatigués de faire le bien’’. Face aux possibilités de s’enrichir rapidement, certains propriétaires de terres s’étaient peut-être lassés de respecter les lois de l’alliance. » (Ralph L. Smith, Word Biblical Commentary, Micah-Malachi, Grand Rapids, MI: Word Books, 1984, vol. 32, p. 50.) « Par la réforme qui s’ensuivit, le roi s’appliqua à détruire tout vestige d’idolâtrie. Les habitants du pays avaient suivi si longtemps les coutumes des nations voisines en se prosternant devant des statues de bois et de pierre qu’il semblait presque impossible à un homme de supprimer toute trace de paganisme. Mais Josias était résolu à persévérer dans sa tentative de purifier le royaume. » Ellen G. White, Prophètes et rois, p. 553. **Discussion:** `1. Bien sûr, nous sommes Adventistes du Septième Jour, et avec notre message de vérité actuel, nous nous voyons (et à juste titre) au même niveau que l’ancien Israël qui avait des vérités que le monde autour de lui avait besoin d’entendre. C’est un grand privilège pour nous. Dans quelle mesure, cependant, pensez-vous que nous sommes à la hauteur des responsabilités qu’exige un tel privilège?` `2. Imaginez-vous être Daniel, et voir votre nation envahie et vaincue, et savoir que le temple, le centre de toute votre foi religieuse, a été détruit par des païens idolâtres. Comment, cependant, la connaissance du livre de Deutéronome pourrait-elle être très agréable pour lui (ou tout autre Juif) en ce moment? C’est-à-dire, comment le livre l’a-t-il aidé à comprendre tout ce qui se passait et sa cause? De la même manière, comment notre compréhension de l’Écriture dans son ensemble nous aide-t-elle à faire face à des temps et des évènements éprouvants qui, autrement, sans notre connaissance de l’Écriture, pourraient vraiment nous décourager? Que devrait nous apprendre la réponse sur la façon dont la Bible doit être centrale à notre foi?` `3. En classe parcourez la prophétie de 70 semaines de Daniel 9:24-27. Quel rôle l’alliance joue-t-elle dans cette prophétie, et pourquoi l’idée d’alliance est-elle si importante pour elle et pour nous?`
class WelcomeController < ApplicationController def index @game=Game.new end def update_cards_per_player @max_cards_per_player = Game.get_maximun_cards_per_player(params[:players]) respond_to do |format| format.js end end def update_game puts params[:cards_per_players] @game=Game.new(params[:players],params[:cards_per_player]) render "index" end end
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Worldpay\Payments\Test\Unit\Controller\Apm; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; class RedirectTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->checkoutSessionMock = $this->getMockBuilder('\Magento\Checkout\Model\Session') ->disableOriginalConstructor() ->setMethods( [ 'clearHelperData', 'getQuote', 'setLastQuoteId', 'setLastSuccessQuoteId', 'setLastOrderId', 'setLastRealOrderId', ] ) ->getMock(); $this->checkoutFactoryMock = $this->getMockBuilder('\Magento\Braintree\Model\CheckoutFactory') ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); $this->messageManager = $this->getMock('\Magento\Framework\Message\ManagerInterface'); $this->checkoutMock = $this->getMockBuilder('\Magento\Braintree\Model\Checkout') ->disableOriginalConstructor() ->getMock(); $this->requestMock = $this->getMock('\Magento\Framework\App\Request\Http', [], [], '', '', false); $this->resultFactoryMock = $this->getMockBuilder('\Magento\Framework\Controller\ResultFactory') ->disableOriginalConstructor() ->getMock(); $contextMock = $this->getMockBuilder('\Magento\Framework\App\Action\Context') ->disableOriginalConstructor() ->getMock(); $contextMock->expects($this->any()) ->method('getResultFactory') ->willReturn($this->resultFactoryMock); $contextMock->expects($this->any()) ->method('getRequest') ->willReturn($this->requestMock); $contextMock->expects($this->any()) ->method('getMessageManager') ->willReturn($this->messageManager); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->validatorMock = $this->getMock('Magento\Checkout\Api\AgreementsValidatorInterface'); $this->controller = $this->objectManagerHelper->getObject( '\Magento\Braintree\Controller\PayPal\PlaceOrder', [ 'context' => $contextMock, 'checkoutSession' => $this->checkoutSessionMock, 'checkoutFactory' => $this->checkoutFactoryMock, 'agreementsValidator' => $this->validatorMock ] ); $this->paymentMock = $this->getMockBuilder('\Magento\Quote\Model\Quote') ->disableOriginalConstructor() ->setMethods(['getMethod']) ->getMock(); $this->paymentMock->expects($this->once()) ->method('getMethod') ->willReturn('worldpay_payments_paypal'); } protected function setupCart() { $quoteMock = $this->getMockBuilder('\Magento\Quote\Model\Quote') ->disableOriginalConstructor() ->setMethods(['hasItems', 'getHasError', 'getPayment', 'getId']) ->getMock(); $quoteMock->expects($this->any()) ->method('hasItems') ->willReturn(true); $quoteMock->expects($this->any()) ->method('getHasError') ->willReturn(false); $this->checkoutSessionMock->expects($this->any()) ->method('getQuote') ->willReturn($quoteMock); $this->checkoutSessionMock->expects($this->any()) ->method('getPayment') ->willReturn($this->paymentMock); $this->checkoutFactoryMock->expects($this->any()) ->method('create') ->willReturn($this->checkoutMock); $this->requestMock->expects($this->any())->method('getPost')->willReturn([]); return $quoteMock; } public function testExecute() { $quoteId = 123; $orderId = 'orderId'; $orderIncrementId = 125; $quoteMock = $this->setupCart(); // $this->validatorMock->expects($this->once())->method('isValid')->willReturn(true); $quoteMock->expects($this->once()) ->method('getPayment') ->willReturn($this->paymentMock); $this->paymentMock->expects($this->once()) ->method('getMethod') ->willReturn('worldpay_payments_paypal'); // $this->checkoutMock->expects($this->once()) // ->method('place') // ->with(null); $this->checkoutSessionMock->expects($this->once()) ->method('clearHelperData'); $quoteMock->expects($this->once()) ->method('getId') ->willReturn($quoteId); $this->checkoutSessionMock->expects($this->once()) ->method('setLastQuoteId') ->with($quoteId) ->willReturnSelf(); $this->checkoutSessionMock->expects($this->once()) ->method('setLastSuccessQuoteId') ->with($quoteId) ->willReturnSelf(); $orderMock = $this->getMockBuilder('\Magento\Sales\Model\Order') ->disableOriginalConstructor() ->getMock(); $orderMock->expects($this->once()) ->method('getId') ->willReturn($orderId); $orderMock->expects($this->once()) ->method('getIncrementId') ->willReturn($orderIncrementId); $this->checkoutMock->expects($this->once()) ->method('getOrder') ->willReturn($orderMock); $this->checkoutSessionMock->expects($this->once()) ->method('setLastOrderId') ->with($orderId) ->willReturnSelf(); $this->checkoutSessionMock->expects($this->once()) ->method('setLastRealOrderId') ->with($orderIncrementId) ->willReturnSelf(); $resultRedirect = $this->getMockBuilder('\Magento\Framework\Controller\Result\Redirect') ->disableOriginalConstructor() ->getMock(); $resultRedirect->expects($this->once()) ->method('setPath') ->with('checkout/onepage/success') ->willReturnSelf(); $this->resultFactoryMock->expects($this->once()) ->method('create') ->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT) ->willReturn($resultRedirect); $this->assertEquals($resultRedirect, $this->controller->execute()); } }
#!/bin/sh while true; do /usr/bin/inotifywait *.f90 && make && notify-send 'Recompiled' || notify-send 'Error in compilation' && sleep 10 done
using System; using wallabag.Common; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace wallabag.Views { public sealed partial class AddLink : ContentDialog { public ApplicationSettings AppSettings { get { return ApplicationSettings.Instance; } } public AddLink() { this.InitializeComponent(); } private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { } } }
/** * 乘法操作符 */ define( function ( require, exports, modules ) { var kity = require( "kity" ); return kity.createClass( 'MultiplicationOperator', { base: require( "operator/binary-opr/left-right" ), constructor: function () { var ltr = new kity.Rect( 0, 20, 43, 3, 3 ).fill( "black"), rtl = new kity.Rect( 20, 0, 3, 43, 3 ).fill( "black" ); this.callBase( "Multiplication" ); this.addOperatorShape( ltr.setAnchor( 22, 22 ).rotate( 45 ) ); this.addOperatorShape( rtl.setAnchor( 22, 22 ).rotate( 45 ) ); } } ); } );
// stdafx.cpp : Ç¥ÁØ Æ÷ÇÔ ÆÄÀϸ¸ µé¾î ÀÖ´Â ¼Ò½º ÆÄÀÏÀÔ´Ï´Ù. // SampleClient.pch´Â ¹Ì¸® ÄÄÆÄÀÏµÈ Çì´õ°¡ µË´Ï´Ù. // stdafx.obj¿¡´Â ¹Ì¸® ÄÄÆÄÀÏµÈ Çü½Ä Á¤º¸°¡ Æ÷ÇԵ˴ϴÙ. #include "stdafx.h" // TODO: ÇÊ¿äÇÑ Ãß°¡ Çì´õ´Â // ÀÌ ÆÄÀÏÀÌ ¾Æ´Ñ STDAFX.H¿¡¼­ ÂüÁ¶ÇÕ´Ï´Ù.
require 'test_helper' class OpinionsControllerTest < ActionDispatch::IntegrationTest test "should get show" do get opinions_show_url assert_response :success end end
/* * Copyright (c), NXP Semiconductors Gratkorn / Austria * * (C)NXP Semiconductors * All rights are reserved. Reproduction in whole or in part is * prohibited without the written consent of the copyright owner. * NXP reserves the right to make changes without notice at any time. * NXP makes no warranty, expressed, implied or statutory, including but * not limited to any implied warranty of merchantability or fitness for any *particular purpose, or that the use will not infringe any third party patent, * copyright or trademark. NXP must not be liable for any loss or damage * arising from its use. */ /** \file * Software Keystore Component of Reader Library Framework. * $Author: nxp13887 $ * $Revision: 1.43 $ * $Date: Thu Dec 16 08:45:40 2010 $ * * History: * CHu: Generated 29. May 2009 * */ #include <ph_Status.h> #include <phKeyStore.h> #include <ph_RefDefs.h> #ifdef NXPBUILD__PH_KEYSTORE_SW #include "phKeyStore_Sw.h" #include "phKeyStore_Sw_Int.h" #include "../phKeyStore_Int.h" phStatus_t phKeyStore_Sw_Init( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wSizeOfDataParams, phKeyStore_Sw_KeyEntry_t * pKeyEntries, uint16_t wNoOfKeyEntries, phKeyStore_Sw_KeyVersionPair_t * pKeyVersionPairs, uint16_t wNoOfVersionPairs, phKeyStore_Sw_KUCEntry_t * pKUCEntries, uint16_t wNoOfKUCEntries ) { uint16_t i; uint16_t j; phStatus_t statusTmp; phKeyStore_Sw_KeyVersionPair_t * pKeyVersion; if (sizeof(phKeyStore_Sw_DataParams_t) != wSizeOfDataParams) { return PH_ADD_COMPCODE(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_KEYSTORE); } PH_ASSERT_NULL (pDataParams); PH_ASSERT_NULL (pKeyEntries); PH_ASSERT_NULL (pKeyVersionPairs); PH_ASSERT_NULL (pKUCEntries); /* Init private data */ pDataParams->wId = PH_COMP_KEYSTORE | PH_KEYSTORE_SW_ID; pDataParams->pKeyEntries = pKeyEntries; pDataParams->pKeyVersionPairs = pKeyVersionPairs; pDataParams->wNoOfKeyEntries = wNoOfKeyEntries; pDataParams->wNoOfVersions = wNoOfVersionPairs; pDataParams->pKUCEntries = pKUCEntries; pDataParams->wNoOfKUCEntries = wNoOfKUCEntries; for (i = 0; i < pDataParams->wNoOfKeyEntries; i++) { pDataParams->pKeyEntries[i].wKeyType = PH_KEYSTORE_INVALID_ID; pDataParams->pKeyEntries[i].wRefNoKUC = PH_KEYSTORE_INVALID_ID; for (j = 0; j < pDataParams->wNoOfVersions; j++) { PH_CHECK_SUCCESS_FCT(statusTmp, phKeyStore_Sw_GetKeyValuePtrPos(pDataParams, i, j, &pKeyVersion)); pKeyVersion->wVersion = PH_KEYSTORE_DEFAULT_ID; } } for (i = 0; i < pDataParams->wNoOfKUCEntries; i++) { pDataParams->pKUCEntries[i].dwLimit = 0xFFFFFFFF; pDataParams->pKUCEntries[i].dwCurVal = 0; } return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_FormatKeyEntry( phKeyStore_Sw_DataParams_t * pDataParams, /**< [In] Pointer to this layer's parameter structure. */ uint16_t wKeyNo, /**< [In] KeyEntry number to be Formatted (0x00 to F0). */ uint16_t wNewKeyType /**< [In] New Key type of the KeyEntry (predefined type of KeyType).*/ ) { phStatus_t statusTmp; uint8_t i; phKeyStore_Sw_KeyVersionPair_t * pKeyVersion; /* Overflow checks */ if (wKeyNo >= pDataParams->wNoOfKeyEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } switch(wNewKeyType) { case PH_KEYSTORE_KEY_TYPE_AES128: case PH_KEYSTORE_KEY_TYPE_DES: case PH_KEYSTORE_KEY_TYPE_2K3DES: case PH_KEYSTORE_KEY_TYPE_MIFARE: case PH_KEYSTORE_KEY_TYPE_AES192: case PH_KEYSTORE_KEY_TYPE_3K3DES: case PH_KEYSTORE_KEY_TYPE_AES256: break; default: return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } pDataParams->pKeyEntries[wKeyNo].wKeyType = wNewKeyType; /* Reset CEK to master Key */ pDataParams->pKeyEntries[wKeyNo].wRefNoKUC = PH_KEYSTORE_INVALID_ID; /* Reset all keys to 0x00*/ for (i = 0; i < pDataParams->wNoOfVersions; ++i) { PH_CHECK_SUCCESS_FCT(statusTmp, phKeyStore_Sw_GetKeyValuePtrPos(pDataParams,wKeyNo,i,&pKeyVersion)); pKeyVersion->wVersion = 0; memset(pKeyVersion->pKey, 0x00, PH_KEYSTORE_SW_MAX_KEY_SIZE); /* PRQA S 3200 */ } return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_SetKey( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wKeyNo, uint16_t wKeyVersion, uint16_t wKeyType, uint8_t * pNewKey, uint16_t wNewKeyVersion ) { phStatus_t statusTmp; phKeyStore_Sw_KeyVersionPair_t * pKeyVersion; PH_CHECK_SUCCESS_FCT(statusTmp, phKeyStore_Sw_GetKeyValuePtrVersion(pDataParams,wKeyNo,wKeyVersion,&pKeyVersion)); /* Check that Key type matches with current Key Type format */ if (pDataParams->pKeyEntries[wKeyNo].wKeyType != wKeyType) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } /* copy the key and version */ memcpy(pKeyVersion->pKey, pNewKey, phKeyStore_GetKeySize(wKeyType)); /* PRQA S 3200 */ pKeyVersion->wVersion = wNewKeyVersion; return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_SetKeyAtPos( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wKeyNo, uint16_t wPos, uint16_t wKeyType, uint8_t * pNewKey, uint16_t wNewKeyVersion ) { phStatus_t statusTmp; phKeyStore_Sw_KeyVersionPair_t * pKeyVersion; PH_CHECK_SUCCESS_FCT(statusTmp, phKeyStore_Sw_GetKeyValuePtrPos(pDataParams,wKeyNo,wPos,&pKeyVersion)); /* Check that Key type matches with current Key Type format */ if (pDataParams->pKeyEntries[wKeyNo].wKeyType != wKeyType) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } /* copy the key and version */ memcpy(pKeyVersion->pKey, pNewKey, phKeyStore_GetKeySize(wKeyType)); /* PRQA S 3200 */ pKeyVersion->wVersion = wNewKeyVersion; return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_SetKUC( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wKeyNo, uint16_t wRefNoKUC ) { /* Overflow checks */ if (wKeyNo >= pDataParams->wNoOfKeyEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } /* Check for a valid KUC entry */ if (wRefNoKUC >= pDataParams->wNoOfKUCEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } pDataParams->pKeyEntries[wKeyNo].wRefNoKUC = wRefNoKUC; return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_SetFullKeyEntry( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wNoOfKeys, uint16_t wKeyNo, uint16_t wNewRefNoKUC, uint16_t wNewKeyType, uint8_t * pNewKeys, uint16_t * pNewKeyVersionList ) { phStatus_t statusTmp; uint8_t i; uint8_t bKeyLength; phKeyStore_Sw_KeyVersionPair_t * pKeyVersion; /* Overflow checks */ if (wKeyNo >= pDataParams->wNoOfKeyEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } /* Check for a valid KUC entry */ if (wNewRefNoKUC >= pDataParams->wNoOfKUCEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } /* Overflow checks */ if (wNoOfKeys > pDataParams->wNoOfVersions) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } switch(wNewKeyType) { case PH_KEYSTORE_KEY_TYPE_AES128: case PH_KEYSTORE_KEY_TYPE_2K3DES: case PH_KEYSTORE_KEY_TYPE_AES192: case PH_KEYSTORE_KEY_TYPE_3K3DES: case PH_KEYSTORE_KEY_TYPE_AES256: case PH_KEYSTORE_KEY_TYPE_DES: case PH_KEYSTORE_KEY_TYPE_MIFARE: bKeyLength = (uint8_t)phKeyStore_GetKeySize(wNewKeyType); break; default: return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } pDataParams->pKeyEntries[wKeyNo].wKeyType = wNewKeyType; /* Reset KUC to master Key */ pDataParams->pKeyEntries[wKeyNo].wRefNoKUC = wNewRefNoKUC; /* Reset all keys to 0x00*/ for (i=0; i < wNoOfKeys ; i++) { PH_CHECK_SUCCESS_FCT(statusTmp, phKeyStore_Sw_GetKeyValuePtrPos(pDataParams,wKeyNo,i,&pKeyVersion)); pKeyVersion->wVersion = pNewKeyVersionList[i]; memcpy(pKeyVersion->pKey, &pNewKeys[i*bKeyLength], bKeyLength); /* PRQA S 3200 */ } return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_GetKeyEntry( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wKeyNo, uint16_t wKeyVersionBufSize, uint16_t * wKeyVersion, uint16_t * wKeyVersionLength, uint16_t * pKeyType ) { phStatus_t statusTmp; uint16_t i; phKeyStore_Sw_KeyVersionPair_t * pKeyVersion; /* Check for overflow */ if (wKeyVersionBufSize < (sizeof(uint16_t) * pDataParams->wNoOfVersions)) { return PH_ADD_COMPCODE(PH_ERR_BUFFER_OVERFLOW, PH_COMP_KEYSTORE); } for (i = 0; i < pDataParams->wNoOfVersions; i++) { PH_CHECK_SUCCESS_FCT(statusTmp, phKeyStore_Sw_GetKeyValuePtrPos(pDataParams,wKeyNo,i,&pKeyVersion)); wKeyVersion[i] = pKeyVersion->wVersion; } *wKeyVersionLength = pDataParams->wNoOfVersions; *pKeyType = pDataParams->pKeyEntries[wKeyNo].wKeyType; return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_GetKey( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wKeyNo, uint16_t wKeyVersion, uint8_t bKeyBufSize, uint8_t * pKey, uint16_t * pKeyType ) { phStatus_t statusTmp; uint16_t wKeySize; phKeyStore_Sw_KeyVersionPair_t * pKeyVersion; PH_CHECK_SUCCESS_FCT(statusTmp, phKeyStore_Sw_GetKeyValuePtrVersion(pDataParams,wKeyNo,wKeyVersion,&pKeyVersion)); /* Check for Counter overflow */ PH_CHECK_SUCCESS_FCT(statusTmp, phKeyStore_Sw_CheckUpdateKUC(pDataParams,pDataParams->pKeyEntries[wKeyNo].wRefNoKUC)); /* check buffer size */ wKeySize = phKeyStore_GetKeySize(pDataParams->pKeyEntries[wKeyNo].wKeyType); if (bKeyBufSize < wKeySize) { return PH_ADD_COMPCODE(PH_ERR_BUFFER_OVERFLOW, PH_COMP_KEYSTORE); } /* copy the key */ memcpy(pKey, pKeyVersion->pKey, wKeySize); /* PRQA S 3200 */ *pKeyType = pDataParams->pKeyEntries[wKeyNo].wKeyType; return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_SetConfig( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wConfig, uint16_t wValue ) { /* satisfy compiler */ if (pDataParams || wConfig || wValue); return PH_ADD_COMPCODE(PH_ERR_UNSUPPORTED_PARAMETER, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_SetConfigStr( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wConfig, uint8_t *pBuffer, uint16_t wBufferLength ) { /* satisfy compiler */ if (pDataParams || wConfig || pBuffer || wBufferLength); return PH_ADD_COMPCODE(PH_ERR_UNSUPPORTED_PARAMETER, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_GetConfig( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wConfig, uint16_t * pValue ) { /* satisfy compiler */ if (pDataParams || wConfig || pValue); return PH_ADD_COMPCODE(PH_ERR_UNSUPPORTED_PARAMETER, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_GetConfigStr( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wConfig, uint8_t ** ppBuffer, uint16_t * pBufferLength ) { /* satisfy compiler */ if (pDataParams || wConfig || ppBuffer || pBufferLength); return PH_ADD_COMPCODE(PH_ERR_UNSUPPORTED_PARAMETER, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_GetKeyValuePtrPos( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wKeyNumber, uint16_t wPos, phKeyStore_Sw_KeyVersionPair_t ** pKeyVersion ) { *pKeyVersion = NULL; /* Overflow checks */ if (wKeyNumber >= pDataParams->wNoOfKeyEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } /* Overflow checks */ if (wPos >= pDataParams->wNoOfVersions) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } *pKeyVersion = &pDataParams->pKeyVersionPairs[wKeyNumber * pDataParams->wNoOfVersions + wPos]; return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_GetKeyValuePtrVersion( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wKeyNumber, uint16_t wKeyVersion, phKeyStore_Sw_KeyVersionPair_t ** pKeyVersion ) { uint16_t i; *pKeyVersion = NULL; /* Overflow checks */ if (wKeyNumber >= pDataParams->wNoOfKeyEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } for (i=0;i<pDataParams->wNoOfVersions; i++) { *pKeyVersion = &pDataParams->pKeyVersionPairs[wKeyNumber * pDataParams->wNoOfVersions + i]; if ((*pKeyVersion)->wVersion == wKeyVersion) { break; } } /* No entry found */ if (i == pDataParams->wNoOfVersions) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_CheckUpdateKUC( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wKeyUsageCtrNumber ) { if (wKeyUsageCtrNumber != PH_KEYSTORE_INVALID_ID) { /* Check for a valid KUC entry */ if (wKeyUsageCtrNumber >= pDataParams->wNoOfKUCEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } /* Now let's check the limit*/ if (pDataParams->pKUCEntries[wKeyUsageCtrNumber].dwCurVal >= pDataParams->pKUCEntries[wKeyUsageCtrNumber].dwLimit) { return PH_ADD_COMPCODE(PH_ERR_KEY, PH_COMP_KEYSTORE); } pDataParams->pKUCEntries[wKeyUsageCtrNumber].dwCurVal++; } return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_ChangeKUC( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wRefNoKUC, uint32_t dwLimit ) { /* Overflow checks */ if (wRefNoKUC >= pDataParams->wNoOfKUCEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } pDataParams->pKUCEntries[wRefNoKUC].dwLimit = dwLimit; return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } phStatus_t phKeyStore_Sw_GetKUC( phKeyStore_Sw_DataParams_t * pDataParams, uint16_t wRefNoKUC, uint32_t * pdwLimit, uint32_t * pdwCurVal ) { /* Overflow checks */ if (wRefNoKUC >= pDataParams->wNoOfKUCEntries) { return PH_ADD_COMPCODE(PH_ERR_INVALID_PARAMETER, PH_COMP_KEYSTORE); } *pdwLimit = pDataParams->pKUCEntries[wRefNoKUC].dwLimit; *pdwCurVal = pDataParams->pKUCEntries[wRefNoKUC].dwCurVal; return PH_ADD_COMPCODE(PH_ERR_SUCCESS, PH_COMP_KEYSTORE); } #endif /* NXPBUILD__PH_KEYSTORE_SW */
package com.edinubuntu.petlove.fragment; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.actionbarsherlock.app.SherlockFragment; import com.activeandroid.query.Select; import com.edinubuntu.petlove.PetLove; import com.edinubuntu.petlove.R; import com.edinubuntu.petlove.adapter.MarketSuggestionsPagerAdapter; import com.edinubuntu.petlove.object.Event; import com.edinubuntu.petlove.object.Pet; import com.edinubuntu.petlove.object.Record; import com.edinubuntu.petlove.object.User; import com.edinubuntu.petlove.util.manager.DisplayTextManager; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by edward_chiang on 13/10/4. */ public class MarketSuggestionFragment extends SherlockFragment { private List<Record> recordList; private Map<String, String> queryMap; private ViewPager suggestionsViewPager; private MarketSuggestionsPagerAdapter marketSuggestionsPagerAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_market_suggestion, container, false); suggestionsViewPager = (ViewPager)rootView.findViewById(R.id.market_record_content_pager); marketSuggestionsPagerAdapter = new MarketSuggestionsPagerAdapter(getFragmentManager()); suggestionsViewPager.setAdapter(marketSuggestionsPagerAdapter); Button choicePetButton = (Button)rootView.findViewById(R.id.market_record_pick_button); choicePetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(getSherlockActivity()) .setTitle(getSherlockActivity().getString(R.string.market_suggestion_choice_title)) .setMessage(getSherlockActivity().getString(R.string.market_suggestion_choice_message)) .setPositiveButton(getString(R.string.dialog_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Record currentRecord = recordList.get(suggestionsViewPager.getCurrentItem()); // Save record to pet Pet adaptPet = new Pet(); adaptPet.setName(currentRecord.getName()); adaptPet.setProfile(currentRecord); // Get Current Player Profile User currentPlayer = new Select().from(User.class).where("Type = '" + User.Type.PLAYER + "'").executeSingle(); adaptPet.setOwner(currentPlayer); adaptPet.save(); Event adaptEvent = new Event(Event.Action.PET_ADAPT_SUCCESS); adaptEvent.setMessage(getString(R.string.event_message_pet_name_begin) + adaptPet.getName() + getString(R.string.event_message_pet_name_end) ); adaptEvent.save(); // Finish and back getSherlockActivity().setResult(Activity.RESULT_OK, new Intent()); getSherlockActivity().finish(); } }) .setNegativeButton(getString(R.string.dialog_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } }); return rootView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); new Event(Event.Action.VISIT_MARKET_SUGGESTIONS).save(); StringBuffer whereBuffer = new StringBuffer(); if (queryMap != null) { Iterator it = queryMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); whereBuffer.append(pairs.getKey() + "= '"+pairs.getValue()+"'"); if (it.hasNext()) { whereBuffer.append(" and "); } } recordList = new Select().from(Record.class) .where(whereBuffer.toString()) .orderBy("RANDOM()") .limit(10) .execute(); Log.d(PetLove.TAG, "Number suggest :" + recordList.size()); Log.d(PetLove.TAG, "We suggest :" + recordList.toString()); marketSuggestionsPagerAdapter.setRecords(recordList); marketSuggestionsPagerAdapter.notifyDataSetChanged(); new AlertDialog.Builder(getSherlockActivity()) .setTitle(getString(R.string.alert_suit_title) + DisplayTextManager.newInstance(getSherlockActivity()).getType(queryMap.get("Type"))) .setMessage(getString(R.string.alert_suit_message_1) + recordList.size() + getString(R.string.alert_suit_message_2)) .setPositiveButton(getString(R.string.dialog_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } } public void setQueryMap(Map<String, String> queryMap) { this.queryMap = queryMap; } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <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.9.1"/> <title>utf8rewind: Examples</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/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </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">utf8rewind &#160;<span id="projectnumber">1.4.1</span> </div> <div id="projectbrief">System library for processing UTF-8 encoded text</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <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>Overview</span></a></li> <li><a href="utf8rewind_8h.html"><span>Interface</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li><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> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">Examples </div> </div> </div><!--header--> <div class="contents"> <div class="toc"><h3>Table of Contents</h3> <ul><li class="level1"><a href="#example-changes">Changes to existing code</a></li> <li class="level1"><a href="#example-user-input">Dealing with user input</a></li> <li class="level1"><a href="#example-display">Displaying Unicode text</a></li> <li class="level1"><a href="#example-users">Comparing usernames in a case-insensitive manner</a></li> </ul> </div> <div class="textblock"><h1><a class="anchor" id="example-changes"></a> Changes to existing code</h1> <p>Suppose you maintain a client-server application written in C. The client connects to a central server and allows the user to manipulate the database in some way. In order for clients to login, the server needs to check their credentials. This is accomplished by the client hashing the specified password with a salt before sending it over to the server:</p> <div class="fragment"><div class="line">uint8_t Login_CheckCredentials(<span class="keyword">const</span> <span class="keywordtype">char</span>* username, <span class="keyword">const</span> <span class="keywordtype">char</span>* password)</div> <div class="line">{</div> <div class="line"> <span class="keyword">const</span> <span class="keywordtype">char</span>* salt;</div> <div class="line"> <span class="keyword">const</span> <span class="keywordtype">char</span>* hashed_password;</div> <div class="line"> <span class="keywordtype">char</span> verify_password[256];</div> <div class="line"> <span class="keywordtype">char</span> hashed_verify_password[256];</div> <div class="line"></div> <div class="line"> <span class="comment">// For the purposes of brevity, ignore the fact that this is a</span></div> <div class="line"> <span class="comment">// terrible way of generating a salt.</span></div> <div class="line"> memset(verify_password, 0, <span class="keyword">sizeof</span>(verify_password));</div> <div class="line"> strcpy(verify_password, md5(password));</div> <div class="line"> strcat(verify_password, md5(username));</div> <div class="line"></div> <div class="line"> memset(hashed_verify_password, 0, <span class="keyword">sizeof</span>(hashed_verify_password));</div> <div class="line"> strcpy(hashed_verify_password, md5(verify_password));</div> <div class="line"></div> <div class="line"> <span class="keywordflow">return</span> Database_CheckLogin(username, hashed_verify_password);</div> <div class="line">}</div> </div><!-- fragment --><p>We want to improve the security of the application by allowing the full range of Unicode code points in the passwords. We can accomplish this by encoding the code points using UTF-8. The beauty of this change is that the password algorithm does <em>not</em> have to be modified. Because all functions already work on <code>char</code> arrays, we can encode Unicode as UTF-8, but treat the string as valid ASCII.</p> <p>A password like "M&ocirc;ntiPyth&ocirc;nikdenH&ocirc;lieGr&acirc;ilen" would be encoded as </p><pre class="fragment">"M\xC3\xB4Pyth\xC3\xB4" "denH\xC3\xB4Gr\xC3\xA2" "en" </pre><p>which is backwards-compatible with ASCII. Calls to <code>strcpy</code> and <code>strcat</code> still work as expected, because the string does not contain NUL-terminators (<code>\0</code>), except to signify the end of data.</p> <p>When converting your project to work with UTF-8 encoded text, there are only two surface areas you will have to concern yourself with: input and display.</p> <p>We'll look at these individually.</p> <h1><a class="anchor" id="example-user-input"></a> Dealing with user input</h1> <p>Continuing with our previous example, the password field in the client application only accepted ASCII. This is how the password field is currently implemented:</p> <div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keywordtype">size_t</span> g_PasswordInputMaximum = 255;</div> <div class="line"><span class="keyword">static</span> <span class="keywordtype">char</span> g_PasswordInput[256];</div> <div class="line"></div> <div class="line">uint8_t PasswordField_EnterCharacter(<span class="keywordtype">char</span> input)</div> <div class="line">{</div> <div class="line"> <span class="keywordtype">char</span> text_input[2];</div> <div class="line"></div> <div class="line"> <span class="keywordflow">if</span> ((strlen(g_PasswordInput) + 1) &gt; g_PasswordInputMaximum)</div> <div class="line"> {</div> <div class="line"> <span class="keywordflow">return</span> 0;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> text_input[0] = input;</div> <div class="line"> text_input[1] = 0;</div> <div class="line"></div> <div class="line"> strcat(g_PasswordInput, text_input);</div> <div class="line"></div> <div class="line"> <span class="keywordflow">return</span> 1;</div> <div class="line">}</div> </div><!-- fragment --><p>What we want to do is make sure the password field can accept Unicode input. To that end, we'll change the input type to <a class="el" href="utf8rewind_8h.html#ae128fe5bd9e57be736e64d3638229988" title="UTF-32 encoded code point. ">unicode_t</a>, which can encode every valid Unicode code point.</p> <div class="fragment"><div class="line">uint8_t PasswordField_EnterCharacter(<a class="code" href="utf8rewind_8h.html#ae128fe5bd9e57be736e64d3638229988">unicode_t</a>* input, <span class="keywordtype">size_t</span> inputSize)</div> </div><!-- fragment --><p>Something that surprises many people working with Unicode is that although UTF-32 can contain all possible valid code points, Unicode <em>itself</em> is a variable-length encoding! For instance, consider a string like "U+0399 U+0308" (GREEK CAPITAL LETTER IOTA and COMBINING DIAERESIS). Although each encodes a separate code point, they can be combined (normalized) into U+03AA (GREEK CAPITAL LETTER IOTA WITH DIALYTIKA). This means that splitting the string after U+0399 is not valid, as it would change the meaning of the encoded text.</p> <p>There are also many instances of code points that can be combined when rendering, but aren't explicitly listed in the Unicode code point. This allowed the Unicode Consortium to encode many more characters without taking up space in the database. The downside for developers is of course that it can be difficult to anticipate how much space will be required to store any particular amount of text.</p> <p>Back to our example.</p> <p>Every location that calls <code>PasswordField_EnterCharacter</code> will have to cast the parameter to <a class="el" href="utf8rewind_8h.html#ae128fe5bd9e57be736e64d3638229988" title="UTF-32 encoded code point. ">unicode_t</a>, but luckily this is backwards-compatible. All ASCII code points (0x00 to 0x7F) are valid in Unicode as well.</p> <p>Inside the function, we'll want to convert the UTF-32 code point to UTF-8. To that end, we'll use <a class="el" href="utf8rewind_8h.html#a325b2612f0a2afdacb81d5e6831bd43b" title="Convert a UTF-32 encoded string to a UTF-8 encoded string. ">utf32toutf8</a>.</p> <div class="fragment"><div class="line"><span class="keywordtype">char</span>* text_input = NULL;</div> <div class="line"><span class="keywordtype">size_t</span> text_input_size;</div> <div class="line"><span class="keywordtype">size_t</span> converted_size;</div> <div class="line">int32_t errors = <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>;</div> <div class="line"></div> <div class="line">text_input_size = <a class="code" href="utf8rewind_8h.html#a325b2612f0a2afdacb81d5e6831bd43b">utf32toutf8</a>(input, inputSize, NULL, 0, &amp;errors);</div> <div class="line"><span class="keywordflow">if</span> (text_input_size == 0 ||</div> <div class="line"> errors != <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>)</div> <div class="line">{</div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line">}</div> <div class="line"></div> <div class="line">text_input = (<span class="keywordtype">char</span>*)malloc(text_input_size + 1);</div> <div class="line"><span class="keywordflow">if</span> (text_input == NULL)</div> <div class="line">{</div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line">}</div> <div class="line">text_input[text_input_size] = 0;</div> <div class="line"></div> <div class="line"><a class="code" href="utf8rewind_8h.html#a325b2612f0a2afdacb81d5e6831bd43b">utf32toutf8</a>(input, inputSize, text_input, text_input_size, &amp;errors);</div> <div class="line"><span class="keywordflow">if</span> (errors != <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>)</div> <div class="line">{</div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line">}</div> </div><!-- fragment --><p>We first determine the length of the input before we allocate memory for it. This way, we ensure that we're protected from buffer-overflow attacks. If you're not too keen on dynamic memory allocations, you could limit the input sequence to six code points, which would require a maximum of four bytes each to encode.</p> <p>It's good practice to always check the error code after each call. However, never explicitly check for any particular error code! <code>utf8rewind</code> may introduce new error codes on every release, so you should check if the error code does <em>not</em> equal <code>UTF8_ERR_NONE</code>.</p> <p>Because the converted string can now consist of more than one byte, we'll have to change the check to see if we're out of bounds of the password input array.</p> <div class="fragment"><div class="line"><span class="keywordflow">if</span> ((strlen(g_PasswordInput) + strlen(text_input)) &gt; g_PasswordInputMaximum)</div> <div class="line">{</div> <div class="line"> <span class="keywordflow">return</span> 0;</div> <div class="line">}</div> </div><!-- fragment --><p>The rewritten version is now fully compatible with Unicode.</p> <div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keywordtype">size_t</span> g_PasswordInputMaximum = 255;</div> <div class="line"><span class="keyword">static</span> <span class="keywordtype">char</span> g_PasswordInput[256];</div> <div class="line"></div> <div class="line">uint8_t PasswordField_EnterCharacter(<a class="code" href="utf8rewind_8h.html#ae128fe5bd9e57be736e64d3638229988">unicode_t</a> input)</div> <div class="line">{</div> <div class="line"> uint8_t result = 1;</div> <div class="line"> <span class="keywordtype">char</span>* text_input = NULL;</div> <div class="line"> <span class="keywordtype">size_t</span> text_input_size;</div> <div class="line"> <span class="keywordtype">size_t</span> converted_size;</div> <div class="line"> int32_t errors = <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>;</div> <div class="line"></div> <div class="line"> text_input_size = <a class="code" href="utf8rewind_8h.html#a325b2612f0a2afdacb81d5e6831bd43b">utf32toutf8</a>(input, inputSize, NULL, 0, &amp;errors);</div> <div class="line"> <span class="keywordflow">if</span> (text_input_size == 0 ||</div> <div class="line"> errors != <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>)</div> <div class="line"> {</div> <div class="line"> result = 0;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> text_input = (<span class="keywordtype">char</span>*)malloc(text_input_size + 1);</div> <div class="line"> <span class="keywordflow">if</span> (text_input == NULL)</div> <div class="line"> {</div> <div class="line"> result = 0;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line"> }</div> <div class="line"> text_input[text_input_size] = 0;</div> <div class="line"></div> <div class="line"> <a class="code" href="utf8rewind_8h.html#a325b2612f0a2afdacb81d5e6831bd43b">utf32toutf8</a>(input, inputSize, text_input, text_input_size, &amp;errors);</div> <div class="line"> <span class="keywordflow">if</span> (errors != <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>)</div> <div class="line"> {</div> <div class="line"> result = 0;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> <span class="keywordflow">if</span> ((strlen(g_PasswordInput) + strlen(text_input)) &gt; g_PasswordInputMaximum)</div> <div class="line"> {</div> <div class="line"> result = 0;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> strcat(g_PasswordInput, text_input);</div> <div class="line"></div> <div class="line">cleanup:</div> <div class="line"> <span class="keywordflow">if</span> (text_input != NULL)</div> <div class="line"> {</div> <div class="line"> free(text_input);</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> <span class="keywordflow">return</span> result;</div> <div class="line">}</div> </div><!-- fragment --><p>With only a few changes, we've upgraded a text field that previously only accepted ASCII to accept the full range of Unicode. And we didn't even have to change the actual algorithm.</p> <h1><a class="anchor" id="example-display"></a> Displaying Unicode text</h1> <p>Even though the user is now able to enter Unicode text, it won't show up right on her screen. That's because the font rendering implementation expects ASCII instead of Unicode.</p> <p>Let's take a look at the offending function:</p> <div class="fragment"><div class="line"><span class="keywordtype">void</span> InputField_Draw(<span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y, <span class="keyword">const</span> <span class="keywordtype">char</span>* text)</div> <div class="line">{</div> <div class="line"> <span class="keyword">const</span> <span class="keywordtype">char</span>* src = text;</div> <div class="line"> <span class="keywordtype">size_t</span> i;</div> <div class="line"></div> <div class="line"> FontBatch_Start(<span class="stringliteral">&quot;Arial20&quot;</span>);</div> <div class="line"></div> <div class="line"> <span class="keywordflow">for</span> (i = 0; i &lt; strlen(text); ++i)</div> <div class="line"> {</div> <div class="line"> FontBatch_AddCharacter(*src);</div> <div class="line"></div> <div class="line"> src++;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> FontBatch_End();</div> <div class="line"> FontBatch_Draw(x, y);</div> <div class="line">}</div> </div><!-- fragment --><p>The issue here is that <code>FontBatch_AddCharacter</code> expects code points encoded as one byte per code point. Because UTF-8 is a variable-length encoding, this isn't necessarily true anymore.</p> <p>In order for the font renderer to display Unicode text, we'll need to convert the UTF-8 encoded text to UTF-32. To that end, we'll use <a class="el" href="utf8rewind_8h.html#a353e5c4a977a630d154db221d6c36159" title="Convert a UTF-8 encoded string to a UTF-32 encoded string. ">utf8toutf32</a>.</p> <div class="fragment"><div class="line"><span class="keywordtype">void</span> InputField_Draw(<span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y, <span class="keyword">const</span> <span class="keywordtype">char</span>* text)</div> <div class="line">{</div> <div class="line"> <span class="keywordtype">size_t</span> text_size = strlen(text);</div> <div class="line"> <a class="code" href="utf8rewind_8h.html#ae128fe5bd9e57be736e64d3638229988">unicode_t</a>* converted = NULL;</div> <div class="line"> <span class="keywordtype">size_t</span> converted_size;</div> <div class="line"> int32_t errors = <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>;</div> <div class="line"> <span class="keywordtype">size_t</span> i;</div> <div class="line"> <a class="code" href="utf8rewind_8h.html#ae128fe5bd9e57be736e64d3638229988">unicode_t</a>* src;</div> <div class="line"></div> <div class="line"> converted_size = <a class="code" href="utf8rewind_8h.html#a353e5c4a977a630d154db221d6c36159">utf8toutf32</a>(text, text_size, NULL, 0, &amp;errors);</div> <div class="line"> <span class="keywordflow">if</span> (converted_size == 0 ||</div> <div class="line"> errors != <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>)</div> <div class="line"> {</div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> converted = (<a class="code" href="utf8rewind_8h.html#ae128fe5bd9e57be736e64d3638229988">unicode_t</a>*)malloc(converted_size);</div> <div class="line"></div> <div class="line"> <a class="code" href="utf8rewind_8h.html#a353e5c4a977a630d154db221d6c36159">utf8toutf32</a>(text, text_size, converted, converted_size, &amp;errors);</div> <div class="line"> <span class="keywordflow">if</span> (errors != <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>)</div> <div class="line"> {</div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> FontBatch_Start(<span class="stringliteral">&quot;Arial20&quot;</span>);</div> <div class="line"></div> <div class="line"> src = decoded;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">for</span> (i = 0; i &lt; decoded_size / <span class="keyword">sizeof</span>(<a class="code" href="utf8rewind_8h.html#ae128fe5bd9e57be736e64d3638229988">unicode_t</a>); ++i)</div> <div class="line"> {</div> <div class="line"> FontBatch_AddCharacter(*src);</div> <div class="line"></div> <div class="line"> src++;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> FontBatch_End();</div> <div class="line"> FontBatch_Draw(x, y);</div> <div class="line"></div> <div class="line">cleanup:</div> <div class="line"> <span class="keywordflow">if</span> (converted != NULL)</div> <div class="line"> {</div> <div class="line"> free(converted);</div> <div class="line"> converted = NULL;</div> <div class="line"> }</div> <div class="line">}</div> </div><!-- fragment --><p>After this conversion, the <code>FontBatch_AddCharacter</code> function would have to be modified in order to handle Unicode code points. Fortunately this is a string handling library, not a font rendering one, so I can get away with saying I'm leaving it as an exercise to the reader.</p> <p>One thing to keep in mind is that even though we convert the entire input string to UTF-32 before rendering it in this example, it's equally valid to read only one codepoint at a time. However, you'll need to use <a class="el" href="utf8rewind_8h.html#ace07c42b3b5031414ceed1f78055242f" title="Seek into a UTF-8 encoded string. ">utf8seek</a> to move the cursor to the next codepoint.</p> <h1><a class="anchor" id="example-users"></a> Comparing usernames in a case-insensitive manner</h1> <p>After the user has entered their username and password, we'll need to verify their identity. This is done on the back-end, with a straightforward function:</p> <div class="fragment"><div class="line"><span class="keyword">typedef</span> <span class="keyword">struct </span>UserData_ {</div> <div class="line"> <span class="keyword">const</span> <span class="keywordtype">char</span>* username;</div> <div class="line"> <span class="keyword">const</span> <span class="keywordtype">char</span>* passwordHash;</div> <div class="line">} UserData;</div> <div class="line"></div> <div class="line"><span class="keyword">static</span> <span class="keyword">const</span> UserData Users[] = {</div> <div class="line"> { <span class="stringliteral">&quot;qlansu&quot;</span>, <span class="stringliteral">&quot;11111&quot;</span> },</div> <div class="line"> { <span class="stringliteral">&quot;Admin&quot;</span>, <span class="stringliteral">&quot;asfasdf&quot;</span> },</div> <div class="line"> { <span class="stringliteral">&quot;User1&quot;</span>, <span class="stringliteral">&quot;u99123&quot;</span> }</div> <div class="line">};</div> <div class="line"></div> <div class="line">uint8_t Database_IsUserValid(<span class="keyword">const</span> <span class="keywordtype">char</span>* username, <span class="keyword">const</span> <span class="keywordtype">char</span>* passwordHash)</div> <div class="line">{</div> <div class="line"> <span class="keywordtype">size_t</span> i;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">for</span> (i = 0; i &lt; <span class="keyword">sizeof</span>(Users) / <span class="keyword">sizeof</span>(UserData); ++i)</div> <div class="line"> {</div> <div class="line"> <span class="keywordflow">if</span> (!strcmp(Users[i].username, username) &amp;&amp;</div> <div class="line"> !strcmp(Users[i].passwordHash, passwordHash))</div> <div class="line"> {</div> <div class="line"> <span class="keywordflow">return</span> 1;</div> <div class="line"> }</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> <span class="keywordflow">return</span> 0;</div> <div class="line">}</div> </div><!-- fragment --><p>Unfortunately, users being users, they end up forgetting the exact combination of upper- and lowercase characters they used for their username.</p> <p>Luckily, we can use <a class="el" href="utf8rewind_8h.html#af60cc918c7dec97b3472b40fbafc8900" title="Remove case distinction from UTF-8 encoded text. ">utf8casefold</a> to do case-insensitive text comparison. Case folding is an operation that erases case distinction between code points. This process allows you to compare and match strings that wouldn't be considered equivalent otherwise.</p> <p>First, we ensure that the usernames stored in our "database" are casefolded:</p> <div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keyword">const</span> Users[] = {</div> <div class="line"> { <span class="stringliteral">&quot;qlansu&quot;</span>, <span class="stringliteral">&quot;11111&quot;</span> },</div> <div class="line"> { <span class="stringliteral">&quot;admin&quot;</span>, <span class="stringliteral">&quot;asfasdf&quot;</span> },</div> <div class="line"> { <span class="stringliteral">&quot;user1&quot;</span>, <span class="stringliteral">&quot;u99123&quot;</span> }</div> <div class="line">};</div> </div><!-- fragment --><p>Next, we casefold the incoming string before we compare it to the username:</p> <div class="fragment"><div class="line">uint8_t Database_IsUserValid(<span class="keyword">const</span> <span class="keywordtype">char</span>* username, <span class="keyword">const</span> <span class="keywordtype">char</span>* passwordHash)</div> <div class="line">{</div> <div class="line"> uint8_t result;</div> <div class="line"> <span class="keywordtype">char</span>* compare_username = NULL;</div> <div class="line"> <span class="keywordtype">size_t</span> compare_username_size = 0;</div> <div class="line"> int32_t errors;</div> <div class="line"> <span class="keywordtype">size_t</span> i;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">if</span> ((compare_username_size = <a class="code" href="utf8rewind_8h.html#af60cc918c7dec97b3472b40fbafc8900">utf8casefold</a>(username, strlen(username), NULL, 0, &amp;errors)) == 0 ||</div> <div class="line"> errors != <a class="code" href="utf8rewind_8h.html#ac7f8a18ca0ca9ebb357b2e7b9c527cc3">UTF8_ERR_NONE</a>)</div> <div class="line"> {</div> <div class="line"> result = 0;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> compare_username = (<span class="keywordtype">char</span>*)malloc(compare_username_size + 1);</div> <div class="line"> <a class="code" href="utf8rewind_8h.html#af60cc918c7dec97b3472b40fbafc8900">utf8casefold</a>(username, strlen(username), compare_username, compare_username_size, &amp;errors);</div> <div class="line"> compare_username[compare_username_size] = 0;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">for</span> (i = 0; i &lt; <span class="keyword">sizeof</span>(Users) / <span class="keyword">sizeof</span>(UserData); ++i)</div> <div class="line"> {</div> <div class="line"> <span class="keywordflow">if</span> (!strcmp(Users[i].username, compare_username) &amp;&amp;</div> <div class="line"> !strcmp(Users[i].passwordHash, passwordHash))</div> <div class="line"> {</div> <div class="line"> result = 1;</div> <div class="line"></div> <div class="line"> <span class="keywordflow">goto</span> cleanup;</div> <div class="line"> }</div> <div class="line"> }</div> <div class="line"></div> <div class="line">cleanup:</div> <div class="line"> <span class="keywordflow">if</span> (compare_username != NULL)</div> <div class="line"> {</div> <div class="line"> free(compare_username);</div> <div class="line"> }</div> <div class="line"></div> <div class="line"> <span class="keywordflow">return</span> result;</div> <div class="line">}</div> </div><!-- fragment --> </div></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
import * as Debug from 'debug'; import * as Models from '../models'; const debug = Debug('neeo:device:ComponentFactory'); // TODO declare types in models/components to use here and in requestHandler. const TYPE_BUTTON = 'button'; const TYPE_SWITCH = 'switch'; const TYPE_SLIDER = 'slider'; const TYPE_SENSOR = 'sensor'; const TYPE_TEXTLABEL = 'textlabel'; const TYPE_IMAGEURL = 'imageurl'; const TYPE_DIRECTORY = 'directory'; const TYPE_DISCOVER_ROUTE = 'discover'; const TYPE_REGISTER_ROUTE = 'register'; const TYPE_DEVICE_SUBSCRIPTION_ROUTE = 'devicesubscription'; const TYPE_FAVORITE_HANDLER_ROUTE = 'favoritehandler'; export const SENSOR_TYPE_ARRAY = 'array'; export const SENSOR_TYPE_BINARY = 'binary'; export const SENSOR_TYPE_CUSTOM = 'custom'; export const SENSOR_TYPE_POWER = 'power'; export const SENSOR_TYPE_RANGE = 'range'; export const SENSOR_TYPE_STRING = 'string'; const SENSOR_SUFFIX = '_SENSOR'; const SENSOR_DEFAULT_TYPE = SENSOR_TYPE_RANGE; const SENSOR_TYPES = [ SENSOR_TYPE_ARRAY, SENSOR_TYPE_BINARY, SENSOR_TYPE_CUSTOM, SENSOR_TYPE_POWER, SENSOR_TYPE_RANGE, SENSOR_TYPE_STRING, ]; const SLIDER_TYPE_RANGE = 'range'; const SLIDER_DEFAULT_RANGE = [0, 100]; const SLIDER_DEFAULT_UNIT = '%'; const VALID_IMAGEURL_SIZES = ['small', 'large']; export function buildButton( pathPrefix: string, param: Models.ButtonDescriptor ) { validateParameter(pathPrefix, param); const name = encodeURIComponent(param.name); const path = pathPrefix + name; const label = param.label ? encodeURIComponent(param.label) : name; return { type: TYPE_BUTTON, name, label, path, }; } export function buildDirectory( pathPrefix: string, param: Models.Directory.Descriptor ) { validateParameter(pathPrefix, param); const name = encodeURIComponent(param.name); const path = pathPrefix + name; return { type: TYPE_DIRECTORY, label: encodeURIComponent(param.label || ''), name, path, role: param.role, identifier: param.identifier, }; } export function buildSwitch( pathPrefix: string, param: Models.Descriptor ) { validateParameter(pathPrefix, param); const name = encodeURIComponent(param.name); const path = pathPrefix + name; return { type: TYPE_SWITCH, name, label: encodeURIComponent(param.label || ''), path, sensor: getSensorNameIfNeeded(name), }; } function validateRange(param?: ReadonlyArray<number>) { const range = param || SLIDER_DEFAULT_RANGE; if (!range || !Array.isArray(range)) { throw new Error(`INVALID_SLIDER_RANGE ${JSON.stringify(range)}, range must be an array`); } if (range.length !== 2 || typeof range[0] !== 'number' || typeof range[1] !== 'number') { throw new Error(`INVALID_SLIDER_RANGE: ${JSON.stringify(range)}, range must include 2 numbers`); } return range; } function buildPowerSensor( pathPrefix: string, param: Models.Sensor.Descriptor ) { const component = buildSensorHelper(pathPrefix, param, SENSOR_TYPE_POWER); // Power state sensors are added by addPowerStateSensor with the name // powerstate, for backward compatibility we need to avoid changing it // to POWERSTATE_SENSOR. const legacyNoSuffixName = encodeURIComponent(param.name); component.name = legacyNoSuffixName; component.path = pathPrefix + legacyNoSuffixName; return component; } export function buildSensor( pathPrefix: string, param: Models.Sensor.Descriptor ) { if (param.type === SENSOR_TYPE_POWER) { return buildPowerSensor(pathPrefix, param); } if (param.type && SENSOR_TYPES.includes(param.type)) { return buildSensorHelper(pathPrefix, param, param.type); } return buildLegacyFallbackSensor(pathPrefix, param); } export function buildRangeSlider( pathPrefix: string, param: Models.Slider.Descriptor ) { validateParameter(pathPrefix, param); const name = encodeURIComponent(param.name); const path = pathPrefix + name; const range = validateRange(param.range); const unit = param.unit ? encodeURIComponent(param.unit) : SLIDER_DEFAULT_UNIT; const label = param.label ? encodeURIComponent(param.label) : name; return { type: TYPE_SLIDER, name, label, path, slider: { type: SLIDER_TYPE_RANGE, sensor: getSensorNameIfNeeded(name), range, unit, }, }; } function buildSensorHelper( pathPrefix: string, param: Models.Sensor.Descriptor, type = SENSOR_DEFAULT_TYPE ) { validateParameter(pathPrefix, param); const name = getSensorNameIfNeeded(encodeURIComponent(param.name)); const path = pathPrefix + name; const label = encodeURIComponent(param.sensorlabel || param.label || param.name); if (type === SENSOR_TYPE_CUSTOM) { debug('Warning: sensor of type custom is not recommended.', param.name); } const component = { type: TYPE_SENSOR, name, label, path, sensor: { type, ...(type === SENSOR_TYPE_RANGE ? { range: validateRange(param.range), unit: param.unit ? encodeURIComponent(param.unit) : SLIDER_DEFAULT_UNIT, } : {}), }, }; return component; } function buildLegacyFallbackSensor(pathPrefix: string, param: Models.Sensor.Descriptor) { debug( 'Warning: no type for sensor %s, using default. ' + 'This fallback will be removed in a future version.', param.name ); const component = buildSensorHelper(pathPrefix, param, SENSOR_TYPE_RANGE); // To avoid breaking changes we keep the non standard no suffix name const legacyNoSuffixName = encodeURIComponent(param.name); component.name = legacyNoSuffixName; component.path = pathPrefix + legacyNoSuffixName; return component; } export function buildTextLabel( pathPrefix: string, param: Models.TextLabel.Descriptor ) { validateParameter(pathPrefix, param); const name = encodeURIComponent(param.name); const path = pathPrefix + name; const label = param.label ? encodeURIComponent(param.label) : name; return { type: TYPE_TEXTLABEL, name, label, path, sensor: getSensorNameIfNeeded(name), isLabelVisible: param.isLabelVisible, }; } function validateImageSize(size: string) { if (!VALID_IMAGEURL_SIZES.includes(size)) { throw new Error('INVALID_IMAGEURL_SIZE'); } } export function buildImageUrl( pathPrefix: string, param: Models.Image.Descriptor ) { validateParameter(pathPrefix, param); const name = encodeURIComponent(param.name); const path = pathPrefix + name; const imageUri = param.uri || null; const label = param.label ? encodeURIComponent(param.label) : name; const size = param.size || 'large'; if (!param.size) { debug('warning, no size definition found for image, use large'); } validateImageSize(size); return { type: TYPE_IMAGEURL, name, label, imageUri, size, path, sensor: getSensorNameIfNeeded(name), }; } export function buildDiscovery(pathPrefix: string) { return getRouteFor(pathPrefix, TYPE_DISCOVER_ROUTE); } export function buildRegister(pathPrefix: string) { return getRouteFor(pathPrefix, TYPE_REGISTER_ROUTE); } export function buildDeviceSubscription(pathPrefix: string) { return getRouteFor(pathPrefix, TYPE_DEVICE_SUBSCRIPTION_ROUTE); } export function buildFavoritesHandler(pathPrefix: string) { return getRouteFor(pathPrefix, TYPE_FAVORITE_HANDLER_ROUTE); } function validateParameter(pathPrefix: string, param: { name: string }) { if (!pathPrefix) { throw new Error('INVALID_PATHPREFIX'); } if (!param || !param.name) { throw new Error('INVALID_BUILD_PARAMETER'); } } function getRouteFor(pathPrefix: string, route: string) { if (!pathPrefix) { throw new Error('INVALID_PATHPREFIX'); } const path = pathPrefix + route; return { type: route, name: route, path, }; } function getSensorNameIfNeeded(name: string) { const alreadySensorName = name.endsWith(SENSOR_SUFFIX); if (alreadySensorName) { return name; } return name.toUpperCase() + SENSOR_SUFFIX; }
{% extends path2+"/_layout.html" %} {% block scoring_content %} <h3 class="heading-large mt10">Moving around and using steps</h3> <div class="evidence__box citizen"> <div class="evidence__label">Claimant statements</div> <div class="evidence__content"> <p>Tony says he can move safely and repeatedly on level ground without needing to stop for: <span class="bold-small">100 metres</span> </p> <h3 class="heading-small mt5 mb0">Moving around and using steps</h3> {# <p class="mb0"><span class="bold-small">Tony says:</span></p> #} <p class="mt0 quote">“I have arthritis in my right knee and hip, and also in both wrists. On a good day I can walk 100m slowly - I'd have to rest a couple of times though, as I'd be in pain. I can't use a stick or crutches or a wheelchair because the arthritis in my wrists means I can't grip and don't have much strength. On a bad day, I can just about get around my flat but would usually stay in bed so I don't have to move much.”</p> <h3 class="heading-small mt5 mb0">Going up or down 2 steps</h3> {# <p class="mb0"><span class="bold-small">Tony says:</span></p> #} <p class="mt0 quote mb0"> “I am not able to {{ 1 | lorum | safe }}” </p> </div> </div> <div class="evidence__box med_records"> <div class="evidence__label">Medical Records</div> <div class="evidence__content"> Automated records check confirmed that {{ firstname }} has: <span class="bold-small">Anxiety and depression</span>, <span class="bold-small">Autism</span> and <span class="bold-small">Fibromyalgia</span>. </div> </div> <div class="evidence__box gp_report"> <div class="evidence__label">GP Report</div> <div class="evidence__content"> <h4 class="heading-small mt5">Dr. Sheila Makeyouwell</h4> <p>Suronge Surgery, Wimbledon, Hertfordshire</p> <p class="mt0 quote mb0"> “I can confirm that the level and progression of {{ firstname }}'s arthritis is such that he cannot {{ 10 | lorumwords | safe }}” </p> </div> </div> {{ data | log }} {% if data.withdesc %} <div class="evidence__box assessment"> <div class="evidence__label">Medical assessment</div> <div class="evidence__content"> <h4 class="heading-small mt5 mb20">Mandy Potemkin (Tresco House Assessment Centre )</h4> {% set nuggets = data.nuggets | pickDescriptor('Moving around and using steps') %} <p>{% for item in nuggets | sortBy("time",false) %} {{ item.text }}.&nbsp; {% endfor %}</p> </div> </div> {% endif %} {# <div id="been_scored"> <hr /> <h2 class="heading-large">Moving around and using steps score: 9</h2> <p class="form-hint">You can change this is if you need to.</p> <button class="button" id="change_score">Change score</button> </div> #} {% include path2 + "/_mobility_score.html" %} <div class="form-group"> <p><label class="form-label" for="justificaiton">Justification</label> <textarea class="form-control form-control-3-4" name="justificaiton" id="justificaiton" rows="5"></textarea></p> </div><!-- .form-group --> <div class="form-group"> <input class="button" type="submit" value="Continue" /> </div><!-- form-group --> {# <div class="" id="rescore"> <h3 class="heading-large">Can you make a recommendation now?</h3> <form class="form" action="/{{path2}}/" method="get"> {% block case_form %} {% include path2+"/_form_ask.html" %} {% endblock %} <div class="js-hidden panel panel-indent mt20" id="scorenow"> {% include path2 + "/_mobility_score.html" %} </div><!-- #scorenow --> <div class="form-group"> <input class="button" type="submit" value="Continue" /> </div><!-- form-group --> </form> </div> #} {% endblock %} {% block page_scripts %} {{ super() }} <script type="text/javascript"> $(document).on('ready',function() { $('#change_score').on('click',function(e) { e.preventDefault(); console.log('got here') $('#been_scored').addClass('js-hidden'); $('#rescore').removeClass('js-hidden'); }); // highlight the right left nav link. $($(".nav")[0]).children(":nth-child(1)").addClass('active') }); </script> {% endblock %}
package storage // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // OperationsClient is the the Azure Storage Management API. type OperationsClient struct { BaseClient } // NewOperationsClient creates an instance of the OperationsClient client. func NewOperationsClient(subscriptionID string) OperationsClient { return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this // when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} } // List lists all of the available Storage Rest API operations. func (client OperationsClient) List(ctx context.Context) (result OperationListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "storage.OperationsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "storage.OperationsClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "storage.OperationsClient", "List", resp, "Failure responding to request") return } return } // ListPreparer prepares the List request. func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { const APIVersion = "2017-06-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPath("/providers/Microsoft.Storage/operations"), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
--- layout: post title: "NodeJS - Testing your Nodejs application with Mocha" date: 2017-12-07 10:00:00 categories: nodejs tags: nodejs js javascript mocha comments: true logo: coffee --- [Mocha](http://mochajs.org/) is a simple, flexible, fun JavaScript test framework for node.js and the browser. ``` npm init npm install mocha --save-dev # this will install mocha as developer dependencies. ``` Here is the file which we'll be testing. ```javascript // utils.js module.exports.add = (a, b) => a + b; module.exports.square = (a) => a * a; ``` Here is the file which covers code for testing. ```javascript // utils.test.js const utils = require('./utils'); it('should add two numbers', () => { var result = utils.add(10, 20); if (result !== 30) { throw new Error(`Expected 30, got ${result}`); } }); it('should square a number', () => { var result = utils.square(10); if (result !== 100) { throw new Error(`Expected 100, got ${result}`); } }); ``` Here is the partial code of `package.json` file. ```json { "name": "node-web-server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "mocha **/*.test.js" // this command will run mocha to test our test cases }, "author": "", "license": "ISC", "dependencies": { "express": "^4.16.2", "hbs": "^4.0.1" }, "devDependencies": { // dev-specific dependencies "mocha": "^4.0.1" } } ``` To start executing test cases, run following command from `terminal`. ``` npm test # which will run "mocha **/*.test.js" command ``` Here is the example output of above command. ```sh node-web-server$ npm test > node-web-server@1.0.0 test /Users/sagar/LearnNodeJS/node-web-server > mocha **/*.test.js ✓ should add two numbers ✓ should square a number 2 passing (8ms) node-web-server$ ```
--- title: syeca author: alba layout: post permalink: /2005/06/02/614/ categories: - asides tags: - asides - del.icio.us - design - quicklinks --- [SYECA� &#8211; motion design][1] [1]: http://www.syeca.com/ "SYECA� - motion design and identity"
/** xxHash64 implementation in pure Javascript Copyright (C) 2016, Pierre Curto MIT license */ var UINT64 = require('cuint').UINT64 /* * Constants */ var PRIME64_1 = UINT64( '11400714785074694791' ) var PRIME64_2 = UINT64( '14029467366897019727' ) var PRIME64_3 = UINT64( '1609587929392839161' ) var PRIME64_4 = UINT64( '9650029242287828579' ) var PRIME64_5 = UINT64( '2870177450012600261' ) /** * Convert string to proper UTF-8 array * @param str Input string * @returns {Uint8Array} UTF8 array is returned as uint8 array */ function toUTF8Array (str) { var utf8 = [] for (var i=0, n=str.length; i < n; i++) { var charcode = str.charCodeAt(i) if (charcode < 0x80) utf8.push(charcode) else if (charcode < 0x800) { utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f)) } else if (charcode < 0xd800 || charcode >= 0xe000) { utf8.push(0xe0 | (charcode >> 12), 0x80 | ((charcode>>6) & 0x3f), 0x80 | (charcode & 0x3f)) } // surrogate pair else { i++; // UTF-16 encodes 0x10000-0x10FFFF by // subtracting 0x10000 and splitting the // 20 bits of 0x0-0xFFFFF into two halves charcode = 0x10000 + (((charcode & 0x3ff)<<10) | (str.charCodeAt(i) & 0x3ff)) utf8.push(0xf0 | (charcode >>18), 0x80 | ((charcode>>12) & 0x3f), 0x80 | ((charcode>>6) & 0x3f), 0x80 | (charcode & 0x3f)) } } return new Uint8Array(utf8) } /** * XXH64 object used as a constructor or a function * @constructor * or * @param {Object|String} input data * @param {Number|UINT64} seed * @return ThisExpression * or * @return {UINT64} xxHash */ function XXH64 () { if (arguments.length == 2) return new XXH64( arguments[1] ).update( arguments[0] ).digest() if (!(this instanceof XXH64)) return new XXH64( arguments[0] ) init.call(this, arguments[0]) } /** * Initialize the XXH64 instance with the given seed * @method init * @param {Number|Object} seed as a number or an unsigned 32 bits integer * @return ThisExpression */ function init (seed) { this.seed = seed instanceof UINT64 ? seed.clone() : UINT64(seed) this.v1 = this.seed.clone().add(PRIME64_1).add(PRIME64_2) this.v2 = this.seed.clone().add(PRIME64_2) this.v3 = this.seed.clone() this.v4 = this.seed.clone().subtract(PRIME64_1) this.total_len = 0 this.memsize = 0 this.memory = null return this } XXH64.prototype.init = init /** * Add data to be computed for the XXH64 hash * @method update * @param {String|Buffer|ArrayBuffer} input as a string or nodejs Buffer or ArrayBuffer * @return ThisExpression */ XXH64.prototype.update = function (input) { var isArrayBuffer // Convert all strings to utf-8 first (issue #5) if (typeof input == 'string') { input = toUTF8Array(input) isArrayBuffer = true } if (typeof ArrayBuffer !== "undefined" && input instanceof ArrayBuffer) { isArrayBuffer = true input = new Uint8Array(input); } var p = 0 var len = input.length var bEnd = p + len if (len == 0) return this this.total_len += len if (this.memsize == 0) { if (isArrayBuffer) { this.memory = new Uint8Array(32) } else { this.memory = new Buffer(32) } } if (this.memsize + len < 32) // fill in tmp buffer { // XXH64_memcpy(this.memory + this.memsize, input, len) if (isArrayBuffer) { this.memory.set( input.subarray(0, len), this.memsize ) } else { input.copy( this.memory, this.memsize, 0, len ) } this.memsize += len return this } if (this.memsize > 0) // some data left from previous update { // XXH64_memcpy(this.memory + this.memsize, input, 16-this.memsize); if (isArrayBuffer) { this.memory.set( input.subarray(0, 32 - this.memsize), this.memsize ) } else { input.copy( this.memory, this.memsize, 0, 32 - this.memsize ) } var p64 = 0 var other other = UINT64( (this.memory[p64+1] << 8) | this.memory[p64] , (this.memory[p64+3] << 8) | this.memory[p64+2] , (this.memory[p64+5] << 8) | this.memory[p64+4] , (this.memory[p64+7] << 8) | this.memory[p64+6] ) this.v1.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p64 += 8 other = UINT64( (this.memory[p64+1] << 8) | this.memory[p64] , (this.memory[p64+3] << 8) | this.memory[p64+2] , (this.memory[p64+5] << 8) | this.memory[p64+4] , (this.memory[p64+7] << 8) | this.memory[p64+6] ) this.v2.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p64 += 8 other = UINT64( (this.memory[p64+1] << 8) | this.memory[p64] , (this.memory[p64+3] << 8) | this.memory[p64+2] , (this.memory[p64+5] << 8) | this.memory[p64+4] , (this.memory[p64+7] << 8) | this.memory[p64+6] ) this.v3.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p64 += 8 other = UINT64( (this.memory[p64+1] << 8) | this.memory[p64] , (this.memory[p64+3] << 8) | this.memory[p64+2] , (this.memory[p64+5] << 8) | this.memory[p64+4] , (this.memory[p64+7] << 8) | this.memory[p64+6] ) this.v4.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 32 - this.memsize this.memsize = 0 } if (p <= bEnd - 32) { var limit = bEnd - 32 do { var other other = UINT64( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) this.v1.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 8 other = UINT64( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) this.v2.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 8 other = UINT64( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) this.v3.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 8 other = UINT64( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) this.v4.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 8 } while (p <= limit) } if (p < bEnd) { // XXH64_memcpy(this.memory, p, bEnd-p); if (isArrayBuffer) { this.memory.set( input.subarray(p, bEnd), this.memsize ) } else { input.copy( this.memory, this.memsize, p, bEnd ) } this.memsize = bEnd - p } return this } /** * Finalize the XXH64 computation. The XXH64 instance is ready for reuse for the given seed * @method digest * @return {UINT64} xxHash */ XXH64.prototype.digest = function () { var input = this.memory var p = 0 var bEnd = this.memsize var h64, h var u = new UINT64 if (this.total_len >= 32) { h64 = this.v1.clone().rotl(1) h64.add( this.v2.clone().rotl(7) ) h64.add( this.v3.clone().rotl(12) ) h64.add( this.v4.clone().rotl(18) ) h64.xor( this.v1.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) ) h64.multiply(PRIME64_1).add(PRIME64_4) h64.xor( this.v2.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) ) h64.multiply(PRIME64_1).add(PRIME64_4) h64.xor( this.v3.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) ) h64.multiply(PRIME64_1).add(PRIME64_4) h64.xor( this.v4.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) ) h64.multiply(PRIME64_1).add(PRIME64_4) } else { h64 = this.seed.clone().add( PRIME64_5 ) } h64.add( u.fromNumber(this.total_len) ) while (p <= bEnd - 8) { u.fromBits( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) u.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) h64 .xor(u) .rotl(27) .multiply( PRIME64_1 ) .add( PRIME64_4 ) p += 8 } if (p + 4 <= bEnd) { u.fromBits( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , 0 , 0 ) h64 .xor( u.multiply(PRIME64_1) ) .rotl(23) .multiply( PRIME64_2 ) .add( PRIME64_3 ) p += 4 } while (p < bEnd) { u.fromBits( input[p++], 0, 0, 0 ) h64 .xor( u.multiply(PRIME64_5) ) .rotl(11) .multiply(PRIME64_1) } h = h64.clone().shiftRight(33) h64.xor(h).multiply(PRIME64_2) h = h64.clone().shiftRight(29) h64.xor(h).multiply(PRIME64_3) h = h64.clone().shiftRight(32) h64.xor(h) // Reset the state this.init( this.seed ) return h64 } module.exports = XXH64
'use strict'; var _ = require('underscore'); module.exports = _.extend( require('./env/all'), require('./env/' + process.env.NODE_ENV) || {} );
require File.expand_path(File.dirname(__FILE__) + '/../../test_config.rb') context "DevHelpController" do context "description here" do setup do get "/" end asserts("the response body") { last_response.body }.equals "Hello World" end end
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import {CustomerModule} from './Binder/CustomerModule'; platformBrowserDynamic().bootstrapModule(CustomerModule);
module powerbi.visuals { export class ForceGraph implements IVisual { public static capabilities: VisualCapabilities = { dataRoles: [ { name: 'Values', kind: VisualDataRoleKind.GroupingOrMeasure, }, ], objects: { general: { properties: { formatString: { type: { formatting: { formatString: true } }, }, }, } }, dataViewMappings: [{ table: { rows: { for: { in: 'Values' }, dataReductionAlgorithm: { window: {} } }, rowCount: { preferred: { min: 1 } } }, }], suppressDefaultTitle: true, }; private root: D3.Selection; private dataView: DataView; // converts data from Values to two dimensional array // expected order: MemberFrom MemberTo Value Valu2 (optional - for coloring) public static converter(dataView: DataView): any { var nodes = {}; var minFiles = Number.MAX_VALUE; var maxFiles = 0; var linkedByName = {}; //var links = [ // { "source": "john", "target": "joe", "filecount": 50 }, // { "source": "john", "target": "bob", "filecount": 150 }, // { "source": "mary", "target": "joe", "filecount": 80 }, // { "source": "bob", "target": "mary", "filecount": 70 }, // { "source": "joe", "target": "bob", "filecount": 20 }, //]; //links.forEach(function (link) { // link.source = nodes[link.source] || // (nodes[link.source] = { name: link.source }); // link.target = nodes[link.target] || // (nodes[link.target] = { name: link.target }); // //link.value = +link.filecount; // if (link.filecount < minFiles) { minFiles = link.filecount }; // if (link.filecount > maxFiles) { maxFiles = link.filecount }; // linkedByName[link.source.name + "," + link.target.name] = 1; //}); var links = []; //var rows = [ // ["Harry", "Sally", 4631], // ["Harry", "Mario", 4018] //]; if (dataView && dataView.table) { var rows = dataView.table.rows; rows.forEach(function (item) { linkedByName[item[0] + "," + item[1]] = 1; var link = { "source": nodes[item[0]] || (nodes[item[0]] = { name: item[0] }), "target": nodes[item[1]] || (nodes[item[1]] = { name: item[1] }), "filecount": item[2] }; if (link.filecount < minFiles) { minFiles = link.filecount }; if (link.filecount > maxFiles) { maxFiles = link.filecount }; links.push(link); }); }; var data = { "nodes": nodes, "links": links, "minFiles": minFiles, "maxFiles": maxFiles, "linkedByName": linkedByName }; return data; } public init(options: VisualInitOptions): void { this.root = d3.select(options.element.get(0)); } public update(options: VisualUpdateOptions) { if (!options.dataViews || (options.dataViews.length < 1)) return; var data = ForceGraph.converter(this.dataView = options.dataViews[0]); var viewport = options.viewport; var w = viewport.width, h = viewport.height; var k = Math.sqrt(Object.keys(data.nodes).length / (w * h)); this.root.selectAll("svg").remove(); var svg = this.root .append("svg") .attr("width", w) .attr("height", h); var force = d3.layout.force() .gravity(100 * k) .nodes(d3.values(data.nodes)) .links(data.links) .size([w, h]) .linkDistance(100) .charge(-15 / k) .on("tick", tick) .start(); var scale0to100 = d3.scale.linear().domain([data.minFiles, data.maxFiles]).range([2, 10]).clamp(true); var path = svg.selectAll(".link") .data(force.links()) .enter().append("path") .attr("class", "link") .attr("stroke-width", function (d) { return scale0to100(d.filecount); }) .on("mouseover", fadePath(.3)) .on("mouseout", fadePath(1)) ; path.append("title") .text(function (d) { return d.source.name + "-" + d.target.name + ":" + d.filecount }); // define the nodes var node = svg.selectAll(".node") .data(force.nodes()) .enter().append("g") .attr("class", "node") .call(force.drag) .on("mouseover", fadeNode(.3)) .on("mouseout", fadeNode(1)) .on("mousedown", function () { d3.event.stopPropagation(); }) ; // add the nodes node.append("circle") .attr("r", function (d) { return d.weight < 10 ? 10 : d.weight; }); // add the text node.append("text") .attr("x", 12) .attr("dy", ".35em") .text(function (d) { return d.name; }); function isConnected(a, b) { return data.linkedByName[a.name + "," + b.name] || data.linkedByName[b.name + "," + a.name] || a.name == b.name; } // add the curvy lines function tick() { path.each(function () { this.parentNode.insertBefore(this, this); }); path.attr("d", function (d) { var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, dr = Math.sqrt(dx * dx + dy * dy); return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y; }); node .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; }); }; function fadeNode(opacity) { return function (d) { node.style("stroke-opacity", function (o) { var thisOpacity = isConnected(d, o) ? 1 : opacity; this.setAttribute('fill-opacity', thisOpacity); return thisOpacity; }); path.style("stroke-opacity", function (o) { return o.source === d || o.target === d ? 1 : opacity; }); path.style("stroke", function (o) { return o.source === d || o.target === d ? "#f00" : "#bbb"; }); }; } function fadePath(opacity) { return function (d) { path.style("stroke-opacity", function (o) { return o.source === d.source && o.target === d.target ? 1 : opacity; }); path.style("stroke", function (o) { return o.source === d.source && o.target === d.target ? "#f00" : "#bbb"; }); }; } } public destroy(): void { this.root = null; } } }
using System; using System.Globalization; using NLog; using NLog.Mustache; using NUnit.Framework; using Should; namespace Tests { [TestFixture] public class LogEventInfoModelTests { [Test] public void should_map_log_event_info_and_exceptions() { var logEventInfo = new LogEventInfo( LogLevel.Fatal, "TestLogger", new CultureInfo("en-US"), "Error", new object[] {}, new Exception("bad", new Exception("things"))); var model = new LogEventInfoModel(logEventInfo); model.SequenceID.ShouldEqual(logEventInfo.SequenceID); model.TimeStamp.ShouldEqual(logEventInfo.TimeStamp); model.Level.ShouldEqual(logEventInfo.Level); model.HasStackTrace.ShouldEqual(logEventInfo.HasStackTrace); model.UserStackFrame.ShouldEqual(logEventInfo.UserStackFrame); model.UserStackFrameNumber.ShouldEqual(logEventInfo.UserStackFrameNumber); model.StackTrace.ShouldEqual(logEventInfo.StackTrace); model.LoggerName.ShouldEqual(logEventInfo.LoggerName); model.LoggerShortName.ShouldEqual(logEventInfo.LoggerShortName); model.Message.ShouldEqual(logEventInfo.Message); model.Parameters.ShouldEqual(logEventInfo.Parameters); model.FormatProvider.ShouldEqual(logEventInfo.FormatProvider); model.FormattedMessage.ShouldEqual(logEventInfo.FormattedMessage); model.Properties.ShouldEqual(logEventInfo.Properties); model.Exception.Message.ShouldEqual(logEventInfo.Exception.Message); model.Exceptions.Count.ShouldEqual(2); model.Exceptions[0].Number.ShouldEqual(1); model.Exceptions[0].Message.ShouldEqual(logEventInfo.Exception.Message); model.Exceptions[1].Number.ShouldEqual(2); model.Exceptions[1].Message.ShouldEqual(logEventInfo.Exception.InnerException.Message); } [Test] public void should_not_fail_if_no_exception() { var logEventInfo = new LogEventInfo(); var model = new LogEventInfoModel(logEventInfo); model.Exception.ShouldBeNull(); model.Exceptions.ShouldBeEmpty(); } } }