code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#include "ToolbarPanel.h" #include "StagePanel.h" #include "SelectSpritesOP.h" #include "Context.h" namespace coceditor { ToolbarPanel::ToolbarPanel(wxWindow* parent) : ee::ToolbarPanel(parent, Context::Instance()->stage) { Context* context = Context::Instance(); // addChild(new ee::UniversalCMPT(this, wxT("paste"), context->stage, // new ee::ArrangeSpriteOP<ee::SelectSpritesOP>(context->stage, context->stage))); addChild(new ee::UniversalCMPT(this, wxT("paste"), context->stage, new ee::ArrangeSpriteOP<SelectSpritesOP>(context->stage, context->stage, context->property))); SetSizer(initLayout()); } wxSizer* ToolbarPanel::initLayout() { wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL); topSizer->Add(initChildrenLayout()); return topSizer; } } // coceditor
xzrunner/easyeditor
coceditor/src/coceditor/ToolbarPanel.cpp
C++
mit
785
using System.IO; using System.Diagnostics; using NDepend.Path; namespace NDepend.Test.Unit { public static class DirForTest { public static IAbsoluteDirectoryPath ExecutingAssemblyDir { get { // If this following line doesn't work, it is because of ShadowCopyCache with NUnit return System.Reflection.Assembly.GetExecutingAssembly().Location.ToAbsoluteFilePath().ParentDirectoryPath; } } public static IAbsoluteFilePath ExecutingAssemblyFilePath { get { return ExecutingAssemblyDir.GetChildFileWithName(ExecutingAssemblyFileName); } } private static string ExecutingAssemblyFileName { get { string executingAssemblyFileLocation = System.Reflection.Assembly.GetExecutingAssembly().Location; return System.IO.Path.GetFileName(executingAssemblyFileLocation); } } public static IAbsoluteDirectoryPath DirAbsolute { get { return Dir.ToAbsoluteDirectoryPath(); } } public static string Dir { get { return ExecutingAssemblyDir.GetChildDirectoryWithName("DirForTest").ToString(); } } public static IAbsoluteDirectoryPath GetDirOfUnitTestWithName(string unitTestName) { IAbsoluteDirectoryPath ndependRootPath = ExecutingAssemblyDir.ParentDirectoryPath; IAbsoluteDirectoryPath unitTestPath = ndependRootPath.GetChildDirectoryWithName("NDepend.Test.Dirs"); IAbsoluteDirectoryPath result = unitTestPath.GetChildDirectoryWithName(unitTestName); Debug.Assert(result.Exists); return result; } public static IAbsoluteDirectoryPath GetBinDebugDir() { IAbsoluteDirectoryPath binDebug = DirAbsolute.ParentDirectoryPath.GetChildDirectoryWithName("Debug"); Debug.Assert(binDebug.Exists); return binDebug; } public static void EnsureDirForTestExistAndEmpty() { string dir = Dir; RETRY: // 29Nov2010: retry until it is ok!! try { // Clear the older dir if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } else { var subDirs = Directory.GetDirectories(dir); var subFiles = Directory.GetFiles(dir); if (subFiles.Length > 0) { foreach (var filePath in subFiles) { File.Delete(filePath); } } if (subDirs.Length > 0) { foreach (var dirPath in subDirs) { Directory.Delete(dirPath, true); } } } if (!Directory.Exists(dir)) { goto RETRY; } if (Directory.GetDirectories(dir).Length > 0) { goto RETRY; } if (Directory.GetFiles(dir).Length > 0) { goto RETRY; } } catch { goto RETRY; } var dirInfo = new DirectoryInfo(dir); Debug.Assert(dirInfo.Exists); Debug.Assert(dirInfo.GetFiles().Length == 0); Debug.Assert(dirInfo.GetDirectories().Length == 0); } public static void Delete() { string dir = Dir; if (Directory.Exists(dir)) { Directory.Delete(dir, true); } } public static string ExecutingAssemblyFilePathInDirForTest { get { return Dir.ToAbsoluteDirectoryPath().GetChildFileWithName(ExecutingAssemblyFileName).ToString(); } } public static void CopyExecutingAssemblyFileInDirForTest() { File.Copy(ExecutingAssemblyDir.GetChildFileWithName(ExecutingAssemblyFileName).ToString(), ExecutingAssemblyFilePathInDirForTest); } } }
psmacchia/NDepend.Path
NDepend.Path.Tests/DirForTest.cs
C#
mit
3,806
--- layout: page title: php 文件管理 category: blog description: --- # Preface 以下是php文件管理函数归纳 # 文件属性(file attribute) filetype($path) block(块设备:分区,软驱,光驱) char(字符设备键盘打打印机) dir file fifo (命名管道,用于进程之间传递信息) link unknown file_exits() 文件存在性 filesize() 返回文件大小(字节数,用pow()去转化 为MB吧) is_readable()检查是否可读 is_writeable()检查是否可写 is_excuteable()检查是否可执行 filectime()检查文件创建的时间 filemtime()检查文件的修改时间 fileatime()检查文件访问时间 stat()获取文件的属性值 0 dev device number - 设备名 1 ino inode number - inode 号码 2 mode inode protection mode - inode 保护模式 3 nlink number of links - 被连接数目 4 uid userid of owner - 所有者的用户 id 5 gid groupid of owner- 所有者的组 id 6 rdev device type, if inode device * - 设备类型,如果是 inode 设备的话 7 size size in bytes - 文件大小的字节数 8 atime time of last access (unix timestamp) - 上次访问时间(Unix 时间戳) 9 mtime time of last modification (unix timestamp) - 上次修改时间(Unix 时间戳) 10 ctime time of last change (unix timestamp) - 上次改变时间(Unix 时间戳) 11 blksize blocksize of filesystem IO * - 文件系统 IO 的块大小 12 blocks number of blocks allocated - 所占据块的数目 # Dir, 文件目录 ## Path ### Pathinfo pathinfo()返回一个数组‘dirname’,'basename’,'filename', 'extension’ realpath('.'); dirname() basename();filename+.+extension ### File location __DIR__ //脚本目录 getcwd();//当前目录 __FILE__ realpath($file); //获取链接文件的绝对路径 #### _SERVER中的path: http://localhost/a/b/c/?var1=val1 #按脚本 **************** SCRIPT_FILENAME = DOCUMENT_ROOT + truePath /data1/www/htdocs/912/hilo/1/phpinfo.php DOCUMENT_ROOT /data1/www/htdocs/912/hilo/1 #按url path: SCRIPT_NAME /PHP_SELF / DOCUMENT_URI (nginx: SCRIPT_URL 默认是空的) nginx: $fastcgi_script_name , 这可以被 rewrite 改写, 以上path 都会变 /a/b/c/ SCRIPT_URI = HTTP_HOST+path 可能为空 http://hilojack.com/a/b/c/ REQUEST_URI = path + QUERY_STRING nginx: $request_uri /a/b/c/?test=1 Refer to: [](/p/linux-nginx) 其它: $_SERVER['OLDPWD'] The definition of OLDPWD is the *p*revious *w*orking *d*irectory as set by the cd command ## Dir Access $dirp=opendir() readdir($dirp);结尾时返回false rewinddir($dirp);返回目录开头 closedir($dirp); ### Match file 用`glob` 代替`opendir` foreach (glob("*.txt") as $filename) { echo "$filename size " . filesize($filename) . "\n"; } ## Dir Operation mkdir ( string $pathname [, int $mode [, bool $recursive [, resource $context ]]] ) rmdir($pathname);必须为空 # Upload File move_uploaded_file($_FILES['userfile']['tmp_name'], $dir.$file)) # File Operation ## Open: fopen ( string $filename , string $mode [, bool $use_include_path [, resource $zcontext ]] ) ‘r’ 只读方式打开,将文件指针指向文件头。 ‘r+’ 读写方式打开,将文件指针指向文件头。 ‘w’ 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 ‘w+’ 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 ‘a’ 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 ‘a+’ 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 ‘x’ 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 ‘x+’ 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 Windows 下提供了一个文本转换标记(’t')可以透明地将 \n 转换为 \r\n。与此对应还可以使用 ‘b’ 来强制使用二进制模式,这样就不会转换数据。要使用这些标记,要么用 ‘b’ 或者用 ‘t’ 作为 mode 参数的最后一个字符。 ## Close fclose($fp); ## File:read - write fread ( int $handle , int $length )最长8192 –fwrite ( resource $handle , string $string [, int $length ] ) fgets ( int $handle [, int $length=1024 ] ) 读取一行 fgetss ( resource $handle [, int $length])读取一行并且去掉html+php标记 fgetc();读取一个字符 //格式化 while($log = fscanf($handler, '%s-%d-%d')){ list($name, $uid, $phone) = $log; } //csv fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]]] ); 读入一行并解析csv 其它: 获取内容 file_get_contents() —file_put_contents() 返回行数组 file ( string $filename [, int $use_include_path [, resource $context ]] ) 输出一个文件 readfile ( string $filename [, bool $use_include_path [, resource $context ]] ) 文件截取 ftruncate ( resource $handle , int $size ),当$size=0,文件就变为空 文件删除 unlink(); 文件复制 copy($src,$dst); Access a.php , a.php include ../b.php, b.php include htm/c.php, in c.php file_put_contents('a.txt', 'a');// write to ./a.txt not to ../htm/a.txt ## 指针移动 ftell($fp);//Returns the current position of the file read/write pointer fseek($fp,$offset[,SEEK_CUR OR SEEK_END OR SEEK_SET),SEEK_SET是默认值,SEEK_END时offset应该为负值 可选。可能的值: SEEK_SET - 设定位置等于 offset 字节。默认。 SEEK_CUR - 设定位置为当前位置加上 offset。 SEEK_END - 设定位置为文件末尾加上 offset (要移动到文件尾之前的位置,offset 必须是一个负值)。 # 并发访问中的文件锁 flock ( int $handle , int $operation [, int &$wouldblock ] ) $operation flock($f, LOCK_SH); 默认值, 没有意义? 不是的,当LOCK_EX 时,这句会返回失败 flock($f, LOCK_EX) 独占锁,带阻塞等待 flock($f, LOCK_EX | LOCK_NB) or die('Another process is running!'); 独占锁,不阻塞 flock($f, LOCK_UN); 释锁 $wouldblock 遇到阻塞时会被设为1 可以用`php -a` 开两个进程测试a.txt # 上传下载 ## 上传 1.1表单:enctype="multipart/form-data" array(1) { ["upload"]=>array(5) { ["name"]=>array(3) { [0]=>string(9)"file0.txt" [1]=>string(9)"file1.txt" [2]=>string(9)"file2.txt" } ["type"]=>array(3) { [0]=>string(10)"text/plain" [1]=>string(10)"text/plain" [2]=>string(10)"text/plain" } ["tmp_name"]=>array(3) { [0]=>string(14)"/tmp/blablabla" [1]=>string(14)"/tmp/phpyzZxta" [2]=>string(14)"/tmp/phpn3nopO" } ["error"]=>array(3) { [0]=>int(0) [1]=>int(0) [2]=>int(0) } ["size"]=>array(3) { [0]=>int(0) [1]=>int(0) [2]=>int(0) } } } 1.2处理上传 move_uploaded_file();必须要在http.conf中设置documentRoot文件 ## 下载 header("Content-Type:application/octet-stream"); //打开始终下载的mimetype header("Content-Disposition: attachment; filename=文件名.后缀名"); // 文件名.后缀名 换成你的文件名这里的文件名是下载后的文件名,和你的源文件名没有关系。 header("Pragma: no-cache"); // 缓存 header("Expires: 0″); header("Content-Length:3390″); 记得加enctype="multipart/form-data"
alskjstl/hilojack.github.io
_posts/2013-2-3-php-file.md
Markdown
mit
8,412
require 'statsample' module Grid class Row attr_reader :top_y, :bottom_y def initialize(item) @data = [] self << item end def <<(item) @data << item @top_y = quartiles_meam(@data.map(&:y)) @bottom_y = quartiles_meam(@data.map{|item| item.y + item.height}) end def inbound_y?(y) @top_y <= y && y <= @bottom_y end def include?(item) @data.include?(item) end def height @bottom_y - @top_y end private def quartiles_meam(array) quartiles(array).to_scale.mean end def quartiles(array) return array if array.size < 7 lower = (array.size - 3)/4 upper = lower * 3 + 3 array[lower..upper] end end end
xli/ewall
lib/grid/row.rb
Ruby
mit
746
import unittest from src.data_structures.mockdata import MockData class TestMockData (unittest.TestCase): def setUp(self): self.data = MockData() def test_random_data(self): data = MockData() a_set = data.get_random_elements(10) self.assertTrue(len(a_set) == 10, "the data should have 10 elements!") if __name__ == '__main__': unittest.main()
alcemirsantos/algorithms-py
tests/data_stuctures/test_mockdata.py
Python
mit
400
// // Person.h // SJDBMapProject // // Created by BlueDancer on 2017/6/4. // Copyright © 2017年 SanJiang. All rights reserved. // #import <Foundation/Foundation.h> #import "SJDBMapUseProtocol.h" @class Book; @class PersonTag; @class Goods; @class TestTest; @interface Person : NSObject<SJDBMapUseProtocol> @property (nonatomic, strong) Book *aBook; @property (nonatomic, assign) NSInteger personID; @property (nonatomic, strong) NSString *name; @property (nonatomic, strong) NSArray<PersonTag *> *tags; @property (nonatomic, strong) NSString *test; @property (nonatomic, strong) NSString *teet; @property (nonatomic, strong) NSString *ttttt; @property (nonatomic, strong) NSArray<Goods *> *goods; @property (nonatomic, assign) NSInteger age; @property (nonatomic, assign) NSInteger group; @property (nonatomic, assign) NSInteger index; @property (nonatomic, assign) NSInteger ID; @property (nonatomic, assign) NSInteger unique; @property (nonatomic, strong) NSURL *tessss; @property (nonatomic, strong) NSString *teesssf; @property (nonatomic, strong) TestTest *testTest; @end
changsanjiang/SJDBMap
SJDBMapProject/Model/Person.h
C
mit
1,103
/* ======================================== * File Name : B.cpp * Creation Date : 16-11-2020 * Last Modified : Po 16. listopadu 2020, 01:03:10 * Created By : Karel Ha <[email protected]> * URL : https://codeforces.com/problemset/problem/1296/B * Points Gained (in case of online contest) : AC ==========================================*/ #include <bits/stdc++.h> using namespace std; #define REP(I,N) FOR(I,0,N) #define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define ALL(A) (A).begin(), (A).end() #define MSG(a) cout << #a << " == " << (a) << endl; const int CLEAN = -1; template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } #define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); } vector<string> split(const string& s, char c) { vector<string> v; stringstream ss(s); string x; while (getline(ss, x, c)) v.emplace_back(x); return move(v); } void err(vector<string>::iterator it) {} template<typename T, typename... Args> void err(vector<string>::iterator it, T a, Args... args) { cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl; err(++it, args...); } int solve(int s) { if (s < 10) { return s; } int x = s - s % 10; return x + solve(s - x + x / 10); } int main() { int t; cin >> t; while (t--) { int s; cin >> s; cout << solve(s) << endl; } return 0; }
mathemage/CompetitiveProgramming
codeforces/div3/1296/B/B.cpp
C++
mit
1,574
# frozen_string_literal: true module Wardrobe module Plugins module Validation module Refinements refine NilClass do def filled? 'must be filled' end def empty? # Nil is valid as empty end end end end end end
agensdev/wardrobe
lib/wardrobe/plugins/validation/refinements/nil_class.rb
Ruby
mit
315
# fish-p2p FISH: FIle SHaring, a Distributed File System - Decentralised P2P system
tobiajo/fish-p2p
README.md
Markdown
mit
84
<!DOCTYPE html> <html> <head> <title>Poet -- node.js blogging platform</title> <link rel="stylesheet" href="styles/prettify.css"> <link rel="stylesheet" href="styles/poet.css"> <link href="http://fonts.googleapis.com/cs?family=La+Belle+Aurore" rel="stylesheet" type="text/css"> <script src="js/ga.js"></script> </head> <body> <div class="header"> <div class="wrap"><a href="http://github.com/jsantell/poet"> <h1>Poet</h1> <h2>write your code love poem</h2></a></div> </div> <div class="wrap"> <div class="cartoon"></div> <h2 id="what-is-poet-">What is Poet?</h2> <p><a href="http://github.com/jsantell/poet" title="Poet"><strong>Poet</strong></a> is a blog generator in <a href="http://nodejs.org" title="node.js">node.js</a> to generate routing, render markdown/pug/whatever posts, and get a blog up and running <em>fast</em>. Poet may not make you blog-famous, and it may give you one less excuse for not having a blog, but just imagine the insane hipster cred you get for having node power your blog. <em>&quot;Cool blog, is this Wordpress or something?&quot;</em> your square friend asks. <em>&quot;Nah dude, this is in node,&quot;</em> you respond, while skateboarding off into the sunset, doing mad flips and stuff. Little do they know you just used Poet&#39;s autoroute generation to get your content in, like, seconds, up on that internet.</p> <h2 id="getting-started">Getting Started</h2> <p>First thing first, throw <strong>Poet</strong> into your express app&#39;s package.json, or just install it locally with:</p> <pre> npm install poet </pre> <p>Once you have the <strong>Poet</strong> module in your app, just instantiate an instance with your Express app and options, and call the <code>init</code> method:</p> <pre> var express = require('express'), app = express(), Poet = require('poet'); var poet = Poet(app, { posts: './_posts/', postsPerPage: 5, metaFormat: 'json' }); poet.init().then(function () { // ready to go! }); /* set up the rest of the express app */ </pre> <p>If using Express 3, be sure to use Poet version &lt;= <code>1.1.0</code>. For Express 4+, use Poet <code>2.0.0+</code>.</p> <h2 id="posts">Posts</h2> <p>Posts are constructed in <a href="http://daringfireball.net/projects/markdown/">markdown</a>/<a href="https://pugjs.org">pug</a>/<a href="#Templates">whatever-you-want</a>, prefixed by front matter via <a href="https://github.com/mojombo/jekyll/wiki/YAML-Front-Matter">YAML</a> or <a href="https://github.com/jsantell/node-json-front-matter">JSON</a>. All attributes are stored in the posts object. An example of a blog post formatted with JSON Front Matter is below:</p> <pre> {{{ "title": "Hello World!", "tags": ["blog", "fun"], "category": "javascript", "date": "7-29-2013" }}} Here goes the content that belongs to the post... </pre> <h3 id="post-previews">Post Previews</h3> <p>There are several ways of specifying the text of your post preview. <strong>Poet</strong> checks several properties and the first valid option is used. The order and ways to accomplish this are below.</p> <ul> <li>A <code>preview</code> property on a post. The text of this property runs through the appropriate template and be saved as the preview for a post</li> <li>A <code>previewLength</code> property on a post, which will take the first <code>n</code> characters of your post (before running through a templating engine), becoming your preview.</li> <li>The last, and most likely easiest, is specifying a <code>readMoreTag</code> option in your <strong>Poet</strong> configuration, which by default is <code>&lt;!--more--&gt;</code>. Whenever the <code>readMoreTag</code> is found int he post, anything proceeding it becomes the preview. You can set this globally in your <strong>Poet</strong> config, or specify a <code>readMoreTag</code> property for each post individually</li> </ul> <h2 id="options">Options</h2> <ul> <li><code>posts</code> path to directory of your files of posts (default: <code>./\_posts/</code>)</li> <li><code>metaFormat</code> format of your front matter on every blog post. Can be <code>yaml</code> or <code>json</code> (default: <code>json</code>)</li> <li><code>postsPerPage</code> How many posts are displayed per page in the page route (default: <code>5</code>)</li> <li><code>readMoreLink</code> A function taking the post object as the only parameter, returning a string that is appended to the post&#39;s preview value. By default will be a function returning <code>&lt;a href=&quot;{post.link}&quot;&gt;{post.title}&lt;/a&gt;</code></li> <li><code>readMoreTag</code> A string in a post that is rendered as a read more link when parsed. (default: <code>&lt;!--more--&gt;</code>)</li> <li><code>showDrafts</code> An option on whether or not to display posts that have <code>drafts</code> meta set to true (default: <code>process.env.NODE\_ENV !== &#39;production&#39;</code>)</li> <li><code>routes</code> A hash of route keys (ex: <code>&#39;/post/:post&#39;</code> and the related view file (ex: <code>&#39;post&#39;</code>). More information in the <a href="#Routes">routes</a> section below.</li> </ul> <h2 id="methods">Methods</h2> <h3 id="poet-init-callback-">Poet::init([callback])</h3> <p>The <code>init</code> method traverses the directory of posts and stores all the information in memory, sets up the internal structures for retrieval and returns a promise resolving to the instance upon completion. An optional callback may be provided for a node style callback with <code>err</code> and <code>poet</code> arguments passed in, called upon completion. This is used when initializing the application, or if reconstructing the internal storage is needed.</p> <h3 id="poet-watch-callback-">Poet::watch([callback])</h3> <p>Sets up the <strong>Poet</strong> instance to watch the posts directory for changes (a new post, updated post, etc.) and reinitializes the engine and storage. An optional <code>callback</code> may be provided to signify the completion of the reinitialization.</p> <p>For an example of using <code>watch</code>, check out <a href="https://github.com/jsantell/poet/blob/master/examples/watcher.js">the watcher example</a></p> <h3 id="poet-unwatch-">Poet::unwatch()</h3> <p>Removes all watchers currently bound to the <strong>Poet</strong> instance.</p> <h3 id="poet-clearcache-">Poet::clearCache()</h3> <p>Used internally, this clears the <strong>Poet</strong> instance&#39;s internal cache, allowing it to be rebuilt on it&#39;s next use. This should not be used in most cases. Returns the <strong>Poet</strong> instance.</p> <h3 id="Templates">Poet::addTemplate(data)</h3> <p><strong>Poet</strong> comes with two templating engines by default (pug and markdown). To specify your own templating language, the <code>addTemplate</code> method may be used, taking a <code>data</code> object with two keys: <code>ext</code> and <code>fn</code>. <code>ext</code> may be a string or an array of strings, specifiying which extensions should use this templating engine, and <code>fn</code> does the rendering, where it is a function that passes an object with several properties: <code>source</code>, <code>filename</code> and <code>locals</code> for rendering engine local variables, and returns the formatted string. Here&#39;s an example of using your own YAML formatter:</p> <pre> var express = require('express'), app = express(), yaml = require('yaml'), Poet = require('poet'); var poet = Poet(app); poet.addTemplate({ ext: 'yaml', fn : function (options) { return yaml.eval(options.source); } }).init(); </pre> <p>This runs any post with the file extension <code>yaml</code> (ex: <code>my_post.yaml</code>) through the <code>fn</code> specified (by calling the <code>yaml</code> module&#39;s <code>eval</code> method.</p> <h3 id="poet-addroute-route-handler-">Poet::addRoute(route, handler)</h3> <p><code>addRoute</code> allows you to specify the handler for a specific route type. Accepting a <code>route</code> string (ex: &#39;/myposts/:post&#39;) and a function <code>handler</code>, the route is parsed based off of parameter name (<code>:post</code> for example in the route <code>/myposts/:post</code>), and the previously stored route for that route type (post) is replaced.</p> <p>The below example uses all default routes except for the post route, and gives full control over how the request is handled. Obviously extra code is needed to specify this, but we can add arbitrary code here, for example, to do some sort of logging:</p> <pre> var express = require('express'), app = express(), Poet = require('poet'); var poet = Poet(app); poet.addRoute('/myposts/:post', function (req, res, next) { var post = poet.helpers.getPost(req.params.post); if (post) { // Do some fancy logging here res.render('post', { post: post }); } else { res.send(404); } }).init(); </pre> <p>For more examples on custom routing, check out the <a href="https://github.com/jsantell/poet/blob/master/examples/customRoutes.js">examples in the repository</a>.</p> <h2 id="routing">Routing</h2> <p>The default configuration uses the default routes with the view names below:</p> <ul> <li>&#39;/post/:post&#39;: &#39;post&#39;</li> <li>&#39;/page/:page&#39;: &#39;page&#39;</li> <li>&#39;/tag/:tag&#39;: &#39;tag&#39;</li> <li>&#39;/category/:category&#39;: &#39;category&#39;</li> </ul> <p>For example, if your site root is <code>http://mysite.com</code>, going to the page <code>http://mysite.com/post/hello-world</code> will call the &#39;post&#39; view in your view directory and render the appropriate post. The options passed into the instantiation of the <strong>Poet</strong> instance can have a <code>routes</code> key, with an object containing key/value pairs of strings mapping a route to a view. Based off of the paramter in the route (ex: <code>:post</code> in <code>/post/:post</code>), the previous route will be replaced.</p> <p>For an example of customizing your route names and views, view the <a href="https://github.com/jsantell/poet/blob/master/examples/configuredSetup.js">example in the repository</a>. To override the default handlers of, check out the <code>Poet::addRoute(route, handler)</code> method.</p> <h2 id="helpers">Helpers</h2> <p>Built in helper methods are stored on the <strong>Poet</strong> instance&#39;s <code>helper</code> property. Used internally, and in the view locals, they can be used outside of <strong>Poet</strong> as well.</p> <ul> <li><code>getPosts(from, to)</code> - an array of reverse chronologically ordered post objects. May specify <code>from</code> and <code>to</code> based on their index, to limit which posts should be returned.</li> <li><code>getTags()</code> - an array of tag names</li> <li><code>getCategories</code> - an array of category names</li> <li><code>tagURL(tag)</code> - a function that takes a name of a tag and returns the corresponding URL based off of the routing configuration</li> <li><code>pageURL(page)</code> - a function that takes the number of a page and returns the corresponding URL based off of the routing configuration</li> <li><code>categoryURL(category)</code> - a function that takes a name of a category and returns the corresponding URL based off of the routing configuration</li> <li><code>getPostCount()</code> - a function that returns the number of total posts registered</li> <li><code>getPost(title)</code> - a function that returns the corresponding post based off of <code>title</code></li> <li><code>getPageCount()</code> - a function that returns the total number of pages, based off of number of posts registered and the <code>postsPerPage</code> option.</li> <li><code>postsWithTag(tag)</code> - returns an array of posts that contain <code>tag</code></li> <li><code>postsWithCategory(cat)</code> - returns an array of posts are in category `cat</li> <li><code>options</code> - all of the option configurations</li> </ul> <h2 id="locals">Locals</h2> <p>In addition to all of the helpers being available to each view, there are additional variables accessible inside specific views.</p> <h3 id="post-locals">Post Locals</h3> <ul> <li><code>post.url</code> - the URL of the current post</li> <li><code>post.content</code> - the content of the current post</li> <li><code>post.preview</code> - the preview of the current post</li> </ul> <h3 id="page-locals">Page Locals</h3> <ul> <li><code>posts</code> - an array of post objects that are within the current post range</li> <li><code>page</code> - the number of the current page</li> </ul> <h3 id="tag-locals">Tag Locals</h3> <ul> <li><code>posts</code> - an array of all post objects that contain the current tag</li> <li><code>tag</code> - a string of the current tag&#39;s name</li> </ul> <h3 id="category-locals">Category Locals</h3> <ul> <li><code>posts</code> - an array of all post objects with the current category</li> <li><code>category</code> - a string of the current category&#39;s name</li> </ul> <h2 id="additional-examples">Additional Examples</h2> <p>Be sure to check out the examples in the repository</p> <ul> <li><a href="https://github.com/jsantell/poet/blob/master/examples/defaultSetup.js">Default configuration</a></li> <li><a href="https://github.com/jsantell/poet/blob/master/examples/configuredSetup.js">Specifying some options</a></li> <li><a href="https://github.com/jsantell/poet/blob/master/examples/customRoutes.js">Using your own custom routes</a></li> <li><a href="https://github.com/jsantell/poet/blob/master/examples/rss.js">Setting up an RSS feed</a></li> <li><a href="https://github.com/jsantell/poet/blob/master/examples/watcher.js">Using a watcher</a></li> </ul> <h2 id="get-bloggin-">Get Bloggin&#39;!</h2> <p>Time to start writing your sweet, beautiful words. For more development information, check out the <a href="https://github.com/jsantell/poet">repository</a>, or scope out the examples in there to get a better idea. If you have any comments, questions, or suggestions, hit me up <a href="http://twitter.com/jsantell">@jsantell</a>!</p> </div> </div> <script src="js/prettify.js"></script> <script> prettyPrint(); </script> <a href="https://github.com/jsantell/poet"><img style="position:absolute;top:0;right:0;border:0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a> </body> </html>
jsantell/poet
docs/public/index.html
HTML
mit
14,428
from rest_framework.filters import ( FilterSet ) from trialscompendium.trials.models import Treatment class TreatmentListFilter(FilterSet): """ Filter query list from treatment database table """ class Meta: model = Treatment fields = {'id': ['exact', 'in'], 'no_replicate': ['exact', 'in', 'gte', 'lte'], 'nitrogen_treatment': ['iexact', 'in', 'icontains'], 'phosphate_treatment': ['iexact', 'in', 'icontains'], 'tillage_practice': ['iexact', 'in', 'icontains'], 'cropping_system': ['iexact', 'in', 'icontains'], 'crops_grown': ['iexact', 'in', 'icontains'], 'farm_yard_manure': ['iexact', 'in', 'icontains'], 'farm_residue': ['iexact', 'in', 'icontains'], } order_by = ['tillage_practice', 'cropping_system', 'crops_grown']
nkoech/trialscompendium
trialscompendium/trials/api/treatment/filters.py
Python
mit
934
import React, { Component } from 'react'; class Main extends Component { render() { return ( <main className='Main'> <h1 className='Main-headline'>Web solutions focused on<br/>Simplicity & Reliability.</h1> <h2 className='Main-subhead'>Bleeding edge technology paired with amazing <em>talent</em> and <em>creativity</em>.</h2> <a href='#' className='Main-button'>Work With Us</a> </main> ); } } export default Main;
qubed-inc/qubed-io
src/Main/index.js
JavaScript
mit
466
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("SendGrid Webhook Example")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stack Solutions - www.stack-solutions.com")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("5e2f0c44-ee9f-43b9-815e-c862ed19a18b")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
paully21/SendGridWebHookExample
Website/Properties/AssemblyInfo.cs
C#
mit
1,401
<!DOCTYPE html> <!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" dir="ltr"> <!--<![endif]--> <!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) --> <!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca --> <head> <!-- Title begins / Début du titre --> <title> Canada Custom Shutters Ltd. - Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada </title> <!-- Title ends / Fin du titre --> <!-- Meta-data begins / Début des métadonnées --> <meta charset="utf-8" /> <meta name="dcterms.language" title="ISO639-2" content="eng" /> <meta name="dcterms.title" content="" /> <meta name="description" content="" /> <meta name="dcterms.description" content="" /> <meta name="dcterms.type" content="report, data set" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.subject" content="businesses, industry" /> <meta name="dcterms.issued" title="W3CDTF" content="" /> <meta name="dcterms.modified" title="W3CDTF" content="" /> <meta name="keywords" content="" /> <meta name="dcterms.creator" content="" /> <meta name="author" content="" /> <meta name="dcterms.created" title="W3CDTF" content="" /> <meta name="dcterms.publisher" content="" /> <meta name="dcterms.audience" title="icaudience" content="" /> <meta name="dcterms.spatial" title="ISO3166-1" content="" /> <meta name="dcterms.spatial" title="gcgeonames" content="" /> <meta name="dcterms.format" content="HTML" /> <meta name="dcterms.identifier" title="ICsiteProduct" content="536" /> <!-- EPI-11240 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- MCG-202 --> <meta content="width=device-width,initial-scale=1" name="viewport"> <!-- EPI-11567 --> <meta name = "format-detection" content = "telephone=no"> <!-- EPI-12603 --> <meta name="robots" content="noarchive"> <!-- EPI-11190 - Webtrends --> <script> var startTime = new Date(); startTime = startTime.getTime(); </script> <!--[if gte IE 9 | !IE ]><!--> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon"> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css"> <!--<![endif]--> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css"> <!--[if lt IE 9]> <link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" /> <link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script> <![endif]--> <!--[if lte IE 9]> <![endif]--> <noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <script>dataLayer1 = [];</script> <!-- End Google Tag Manager --> <!-- EPI-11235 --> <link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body class="home" vocab="http://schema.org/" typeof="WebPage"> <!-- EPIC HEADER BEGIN --> <!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER --> <noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script> <!-- End Google Tag Manager --> <!-- EPI-12801 --> <span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span> <ul id="wb-tphp"> <li class="wb-slc"> <a class="wb-sl" href="#wb-cont">Skip to main content</a> </li> <li class="wb-slc visible-sm visible-md visible-lg"> <a class="wb-sl" href="#wb-info">Skip to "About this site"</a> </li> </ul> <header role="banner"> <div id="wb-bnr" class="container"> <section id="wb-lng" class="visible-md visible-lg text-right"> <h2 class="wb-inv">Language selection</h2> <div class="row"> <div class="col-md-12"> <ul class="list-inline mrgn-bttm-0"> <li><a href="nvgt.do?V_TOKEN=1492272358519&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=7972&V_SEARCH.docsStart=7971&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/updt.sec?_flId?_flxKy=e1s1&amp;estblmntNo=234567041301&amp;profileId=61&amp;_evId=bck&amp;lang=eng&amp;V_SEARCH.showStricts=false&amp;prtl=1&amp;_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li> </ul> </div> </div> </section> <div class="row"> <div class="brand col-xs-8 col-sm-9 col-md-6"> <a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a> </div> <section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn"> <h2>Search and menus</h2> <ul class="list-inline text-right chvrn"> <li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li> </ul> <div id="mb-pnl"></div> </section> <!-- Site Search Removed --> </div> </div> <nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement"> <h2 class="wb-inv">Topics menu</h2> <div class="container nvbar"> <div class="row"> <ul class="list-inline menu"> <li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li> <li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li> <li><a href="https://travel.gc.ca/">Travel</a></li> <li><a href="https://www.canada.ca/en/services/business.html">Business</a></li> <li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li> <li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li> <li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li> <li><a href="https://www.canada.ca/en/services.html">More services</a></li> </ul> </div> </div> </nav> <!-- EPIC BODY BEGIN --> <nav role="navigation" id="wb-bc" class="" property="breadcrumb"> <h2 class="wb-inv">You are here:</h2> <div class="container"> <div class="row"> <ol class="breadcrumb"> <li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li> <li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li> <li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li> </ol> </div> </div> </nav> </header> <main id="wb-cont" role="main" property="mainContentOfPage" class="container"> <!-- End Header --> <!-- Begin Body --> <!-- Begin Body Title --> <!-- End Body Title --> <!-- Begin Body Head --> <!-- End Body Head --> <!-- Begin Body Content --> <br> <!-- Complete Profile --> <!-- Company Information above tabbed area--> <input id="showMore" type="hidden" value='more'/> <input id="showLess" type="hidden" value='less'/> <h1 id="wb-cont"> Company profile - Canadian Company Capabilities </h1> <div class="profileInfo hidden-print"> <ul class="list-inline"> <li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&amp;rstBtn.x=" class="btn btn-link">New Search</a>&nbsp;|</li> <li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do"> <input type="hidden" name="lang" value="eng" /> <input type="hidden" name="profileId" value="" /> <input type="hidden" name="prtl" value="1" /> <input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" /> <input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" /> <input type="hidden" name="V_SEARCH.depth" value="1" /> <input type="hidden" name="V_SEARCH.showStricts" value="false" /> <input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" /> </form></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=7970&amp;V_DOCUMENT.docRank=7971&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492272390390&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567090223&amp;profileId=&amp;key.newSearchLabel=">Previous Company</a></li> <li>|&nbsp;<a href="nvgt.do?V_SEARCH.docsStart=7972&amp;V_DOCUMENT.docRank=7973&amp;V_SEARCH.docsCount=3&amp;lang=eng&amp;prtl=1&amp;sbPrtl=&amp;profile=cmpltPrfl&amp;V_TOKEN=1492272390390&amp;V_SEARCH.command=navigate&amp;V_SEARCH.resultsJSP=%2fprfl.do&amp;estblmntNo=234567009478&amp;profileId=&amp;key.newSearchLabel=">Next Company</a></li> </ul> </div> <details> <summary>Third-Party Information Liability Disclaimer</summary> <p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p> </details> <h2> Canada Custom Shutters Ltd. </h2> <div class="row"> <div class="col-md-5"> <h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2> <p>Canada Custom Shutters Ltd.</p> <div class="mrgn-tp-md"></div> <p class="mrgn-bttm-0" ><a href="http://www.canadacustomshutters.com" target="_blank" title="Website URL">http://www.canadacustomshutters.com</a></p> <p><a href="mailto:[email protected]" title="[email protected]">[email protected]</a></p> </div> <div class="col-md-4 mrgn-sm-sm"> <h2 class="h5 mrgn-bttm-0">Mailing Address:</h2> <address class="mrgn-bttm-md"> 140 Toll Rd<br/> HOLLAND LANDING, Ontario<br/> L9N 1G8 <br/> </address> <h2 class="h5 mrgn-bttm-0">Location Address:</h2> <address class="mrgn-bttm-md"> 140 Toll Rd<br/> HOLLAND LANDING, Ontario<br/> L9N 1G8 <br/> </address> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (905) 953-0801 </p> <p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>: (866) 532-5893</p> <p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>: (905) 953-8247</p> </div> <div class="col-md-3 mrgn-tp-md"> </div> </div> <div class="row mrgn-tp-md mrgn-bttm-md"> <div class="col-md-12"> </div> </div> <!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> --> <div class="wb-tabs ignore-session"> <div class="tabpanels"> <details id="details-panel1"> <summary> Full profile </summary> <!-- Tab 1 --> <h2 class="wb-invisible"> Full profile </h2> <!-- Contact Information --> <h3 class="page-header"> Contact information </h3> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Milan Gigic </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Manager </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Area of Responsibility: </strong> </div> <div class="col-md-7"> Management Executive. </div> </div> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Goran Gigic </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Treasurer </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (905) 953-0801 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Facsimile: </strong> </div> <div class="col-md-7"> (905) 953-8247 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> [email protected] </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Company Description --> <h3 class="page-header"> Company description </h3> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Country of Ownership: </strong> </div> <div class="col-md-7"> Canada &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Year Established: </strong> </div> <div class="col-md-7"> 1987 </div> </div> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> Yes &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Industry (NAICS): </strong> </div> <div class="col-md-7"> 321919 - Other Millwork </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Manufacturer / Processor / Producer &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Total Sales ($CDN): </strong> </div> <div class="col-md-7"> $1,000,000 to $4,999,999&nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Export Sales ($CDN): </strong> </div> <div class="col-md-7"> $1 to $99,999&nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Number of Employees: </strong> </div> <div class="col-md-7"> 20&nbsp; </div> </div> </section> <!-- Products / Services / Licensing --> <h3 class="page-header"> Product / Service / Licensing </h3> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Product Name: </strong> </div> <div class="col-md-9"> SHUTTERS, WOODEN <br> </div> </div> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Technology Profile --> <!-- Market Profile --> <h3 class="page-header"> Market profile </h3> <section class="container-fluid"> <h4> Geographic markets: </h4> <h5> Export experience: </h5> <ul> <li>United States</li> </ul> </section> <p class="mrgn-tp-lg text-right small hidden-print"> <a href="#wb-cont">top of page</a> </p> <!-- Sector Information --> <details class="mrgn-tp-md mrgn-bttm-md"> <summary> Third-Party Information Liability Disclaimer </summary> <p> Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements. </p> </details> </details> <details id="details-panel2"> <summary> Contacts </summary> <h2 class="wb-invisible"> Contact information </h2> <!-- Contact Information --> <section class="container-fluid"> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Milan Gigic </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Manager </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Area of Responsibility: </strong> </div> <div class="col-md-7"> Management Executive. </div> </div> <div class="row mrgn-tp-lg"> <div class="col-md-3"> <strong> Goran Gigic </strong></div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Title: </strong> </div> <div class="col-md-7"> <!--if client gender is not null or empty we use gender based job title--> Treasurer </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Telephone: </strong> </div> <div class="col-md-7"> (905) 953-0801 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Facsimile: </strong> </div> <div class="col-md-7"> (905) 953-8247 </div> </div> <div class="row mrgn-lft-md"> <div class="col-md-5"> <strong> Email: </strong> </div> <div class="col-md-7"> [email protected] </div> </div> </section> </details> <details id="details-panel3"> <summary> Description </summary> <h2 class="wb-invisible"> Company description </h2> <section class="container-fluid"> <div class="row"> <div class="col-md-5"> <strong> Country of Ownership: </strong> </div> <div class="col-md-7"> Canada &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Year Established: </strong> </div> <div class="col-md-7"> 1987 </div> </div> <div class="row"> <div class="col-md-5"> <strong> Exporting: </strong> </div> <div class="col-md-7"> Yes &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Industry (NAICS): </strong> </div> <div class="col-md-7"> 321919 - Other Millwork </div> </div> <div class="row"> <div class="col-md-5"> <strong> Primary Business Activity: </strong> </div> <div class="col-md-7"> Manufacturer / Processor / Producer &nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Total Sales ($CDN): </strong> </div> <div class="col-md-7"> $1,000,000 to $4,999,999&nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Export Sales ($CDN): </strong> </div> <div class="col-md-7"> $1 to $99,999&nbsp; </div> </div> <div class="row"> <div class="col-md-5"> <strong> Number of Employees: </strong> </div> <div class="col-md-7"> 20&nbsp; </div> </div> </section> </details> <details id="details-panel4"> <summary> Products, services and licensing </summary> <h2 class="wb-invisible"> Product / Service / Licensing </h2> <section class="container-fluid"> <div class="row mrgn-bttm-md"> <div class="col-md-3"> <strong> Product Name: </strong> </div> <div class="col-md-9"> SHUTTERS, WOODEN <br> </div> </div> </section> </details> <details id="details-panel6"> <summary> Market </summary> <h2 class="wb-invisible"> Market profile </h2> <section class="container-fluid"> <h4> Geographic markets: </h4> <h5> Export experience: </h5> <ul> <li>United States</li> </ul> </section> </details> </div> </div> <div class="row"> <div class="col-md-12 text-right"> Last Update Date 2017-03-06 </div> </div> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z --> <!-- End Body Content --> <!-- Begin Body Foot --> <!-- End Body Foot --> <!-- END MAIN TABLE --> <!-- End body --> <!-- Begin footer --> <div class="row pagedetails"> <div class="col-sm-5 col-xs-12 datemod"> <dl id="wb-dtmd"> <dt class=" hidden-print">Date Modified:</dt> <dd class=" hidden-print"> <span><time>2017-03-02</time></span> </dd> </dl> </div> <div class="clear visible-xs"></div> <div class="col-sm-4 col-xs-6"> </div> <div class="col-sm-3 col-xs-6 text-right"> </div> <div class="clear visible-xs"></div> </div> </main> <footer role="contentinfo" id="wb-info"> <nav role="navigation" class="container wb-navcurr"> <h2 class="wb-inv">About government</h2> <!-- EPIC FOOTER BEGIN --> <!-- EPI-11638 Contact us --> <ul class="list-unstyled colcount-sm-2 colcount-md-3"> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&amp;from=Industries">Contact us</a></li> <li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li> <li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li> <li><a href="https://www.canada.ca/en/news.html">News</a></li> <li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li> <li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li> <li><a href="http://pm.gc.ca/eng">Prime Minister</a></li> <li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li> <li><a href="http://open.canada.ca/en/">Open government</a></li> </ul> </nav> <div class="brand"> <div class="container"> <div class="row"> <nav class="col-md-10 ftr-urlt-lnk"> <h2 class="wb-inv">About this site</h2> <ul> <li><a href="https://www.canada.ca/en/social.html">Social media</a></li> <li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li> <li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li> <li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li> </ul> </nav> <div class="col-xs-6 visible-sm visible-xs tofpg"> <a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a> </div> <div class="col-xs-6 col-md-2 text-right"> <object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object> </div> </div> </div> </div> </footer> <!--[if gte IE 9 | !IE ]><!--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script> <!--<![endif]--> <!--[if lt IE 9]> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script> <![endif]--> <script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script> <!-- EPI-10519 --> <span class="wb-sessto" data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span> <script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script> <!-- EPI-11190 - Webtrends --> <script src="/eic/home.nsf/js/webtrends.js"></script> <script>var endTime = new Date();</script> <noscript> <div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&amp;WT.js=No&amp;WT.tv=9.4.0&amp;dcssip=www.ic.gc.ca"/></div> </noscript> <!-- /Webtrends --> <!-- JS deps --> <script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script> <!-- EPI-11262 - Util JS --> <script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script> <!-- EPI-11383 --> <script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script> <span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span> </body></html> <!-- End Footer --> <!-- - Artifact ID: CBW - IMBS - CCC Search WAR - Group ID: ca.gc.ic.strategis.imbs.ccc.search - Version: 3.26 - Built-By: bamboo - Build Timestamp: 2017-03-02T21:29:28Z -->
GoC-Spending/data-corporations
html/123456204733.html
HTML
mit
39,817
// // SwiftMan.h // SwiftMan // // Created by yangjun on 16/4/29. // Copyright © 2016年 yangjun. All rights reserved. // #import "TargetConditionals.h" #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #elif TARGET_OS_MAC #import <Cocoa/Cocoa.h> #elif TARGET_OS_WATCH #import <WatchKit/WatchKit.h> #endif //! Project version number for SwiftMan. FOUNDATION_EXPORT double SwiftManVersionNumber; //! Project version string for SwiftMan. FOUNDATION_EXPORT const unsigned char SwiftManVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SwiftMan/PublicHeader.h>
easyui/SwiftMan
SwiftMan/SwiftMan.h
C
mit
641
/* * @brief This file contains USB HID Keyboard example using USB ROM Drivers. * * @note * Copyright(C) NXP Semiconductors, 2013 * All rights reserved. * * @par * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * LPC products. This software is supplied "AS IS" without any warranties of * any kind, and NXP Semiconductors and its licensor disclaim any and * all warranties, express or implied, including all implied warranties of * merchantability, fitness for a particular purpose and non-infringement of * intellectual property rights. NXP Semiconductors assumes no responsibility * or liability for the use of the software, conveys no license or rights under any * patent, copyright, mask work right, or any other intellectual property rights in * or to any products. NXP Semiconductors reserves the right to make changes * in the software without notification. NXP Semiconductors also makes no * representation or warranty that such application will be suitable for the * specified use without further testing or modification. * * @par * Permission to use, copy, modify, and distribute this software and its * documentation is hereby granted, under NXP Semiconductors' and its * licensor's relevant copyrights in the software, without fee, provided that it * is used in conjunction with NXP Semiconductors microcontrollers. This * copyright, permission, and disclaimer notice must appear in all copies of * this code. */ #include "board.h" #include <stdint.h> #include <string.h> #include "usbd_rom_api.h" #include "hid_keyboard.h" #include "ms_timer.h" /***************************************************************************** * Private types/enumerations/variables ****************************************************************************/ /** * @brief Structure to hold Keyboard data */ typedef struct { USBD_HANDLE_T hUsb; /*!< Handle to USB stack. */ uint8_t report[KEYBOARD_REPORT_SIZE]; /*!< Last report data */ uint8_t tx_busy; /*!< Flag indicating whether a report is pending in endpoint queue. */ ms_timer_t tmo; /*!< Timer to track when to send next report. */ } Keyboard_Ctrl_T; /** Singleton instance of Keyboard control */ static Keyboard_Ctrl_T g_keyBoard; /***************************************************************************** * Public types/enumerations/variables ****************************************************************************/ extern const uint8_t Keyboard_ReportDescriptor[]; extern const uint16_t Keyboard_ReportDescSize; /***************************************************************************** * Private functions ****************************************************************************/ /* Routine to update keyboard state */ static void Keyboard_UpdateReport(void) { uint8_t joystick_status = Joystick_GetStatus(); HID_KEYBOARD_CLEAR_REPORT(&g_keyBoard.report[0]); switch (joystick_status) { case JOY_PRESS: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x53); break; case JOY_LEFT: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x5C); break; case JOY_RIGHT: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x5E); break; case JOY_UP: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x60); break; case JOY_DOWN: HID_KEYBOARD_REPORT_SET_KEY_PRESS(g_keyBoard.report, 0x5A); break; } } /* HID Get Report Request Callback. Called automatically on HID Get Report Request */ static ErrorCode_t Keyboard_GetReport(USBD_HANDLE_T hHid, USB_SETUP_PACKET *pSetup, uint8_t * *pBuffer, uint16_t *plength) { /* ReportID = SetupPacket.wValue.WB.L; */ switch (pSetup->wValue.WB.H) { case HID_REPORT_INPUT: Keyboard_UpdateReport(); memcpy(*pBuffer, &g_keyBoard.report[0], KEYBOARD_REPORT_SIZE); *plength = KEYBOARD_REPORT_SIZE; break; case HID_REPORT_OUTPUT: /* Not Supported */ case HID_REPORT_FEATURE: /* Not Supported */ return ERR_USBD_STALL; } return LPC_OK; } /* HID Set Report Request Callback. Called automatically on HID Set Report Request */ static ErrorCode_t Keyboard_SetReport(USBD_HANDLE_T hHid, USB_SETUP_PACKET *pSetup, uint8_t * *pBuffer, uint16_t length) { /* we will reuse standard EP0Buf */ if (length == 0) { return LPC_OK; } /* ReportID = SetupPacket.wValue.WB.L; */ switch (pSetup->wValue.WB.H) { case HID_REPORT_OUTPUT: /* If the USB host tells us to turn on the NUM LOCK LED, * then turn on LED#2. */ if (**pBuffer & 0x01) { Board_LED_Set(0, 1); } else { Board_LED_Set(0, 0); } break; case HID_REPORT_INPUT: /* Not Supported */ case HID_REPORT_FEATURE: /* Not Supported */ return ERR_USBD_STALL; } return LPC_OK; } /* HID interrupt IN endpoint handler */ static ErrorCode_t Keyboard_EpIN_Hdlr(USBD_HANDLE_T hUsb, void *data, uint32_t event) { switch (event) { case USB_EVT_IN: g_keyBoard.tx_busy = 0; break; } return LPC_OK; } /***************************************************************************** * Public functions ****************************************************************************/ /* HID keyboard init routine */ ErrorCode_t Keyboard_init(USBD_HANDLE_T hUsb, USB_INTERFACE_DESCRIPTOR *pIntfDesc, uint32_t *mem_base, uint32_t *mem_size) { USBD_HID_INIT_PARAM_T hid_param; USB_HID_REPORT_T reports_data[1]; ErrorCode_t ret = LPC_OK; /* Do a quick check of if the interface descriptor passed is the right one. */ if ((pIntfDesc == 0) || (pIntfDesc->bInterfaceClass != USB_DEVICE_CLASS_HUMAN_INTERFACE)) { return ERR_FAILED; } /* init joystick control */ Board_Joystick_Init(); /* Init HID params */ memset((void *) &hid_param, 0, sizeof(USBD_HID_INIT_PARAM_T)); hid_param.max_reports = 1; hid_param.mem_base = *mem_base; hid_param.mem_size = *mem_size; hid_param.intf_desc = (uint8_t *) pIntfDesc; /* user defined functions */ hid_param.HID_GetReport = Keyboard_GetReport; hid_param.HID_SetReport = Keyboard_SetReport; hid_param.HID_EpIn_Hdlr = Keyboard_EpIN_Hdlr; /* Init reports_data */ reports_data[0].len = Keyboard_ReportDescSize; reports_data[0].idle_time = 0; reports_data[0].desc = (uint8_t *) &Keyboard_ReportDescriptor[0]; hid_param.report_data = reports_data; ret = USBD_API->hid->init(hUsb, &hid_param); /* update memory variables */ *mem_base = hid_param.mem_base; *mem_size = hid_param.mem_size; /* store stack handle for later use. */ g_keyBoard.hUsb = hUsb; /* start the mouse timer */ ms_timerInit(&g_keyBoard.tmo, HID_KEYBRD_REPORT_INTERVAL_MS); return ret; } /* Keyboard tasks */ void Keyboard_Tasks(void) { /* check if moue report timer expired */ if (ms_timerExpired(&g_keyBoard.tmo)) { /* reset timer */ ms_timerStart(&g_keyBoard.tmo); /* check device is configured before sending report. */ if ( USB_IsConfigured(g_keyBoard.hUsb)) { /* update report based on board state */ Keyboard_UpdateReport(); /* send report data */ if (g_keyBoard.tx_busy == 0) { g_keyBoard.tx_busy = 1; USBD_API->hw->WriteEP(g_keyBoard.hUsb, HID_EP_IN, &g_keyBoard.report[0], KEYBOARD_REPORT_SIZE); } } } }
miragecentury/M2_SE_RTOS_Project
Project/LPC1549_Keil/examples/usbd_rom/usbd_rom_hid_keyboard/hid_keyboard.c
C
mit
7,219
'use strict'; angular.module('main', ['ngRoute', 'ngResource', 'ui.route', 'main.system', 'main.index', 'main.events']); angular.module('main.system', []); angular.module('main.index', []); angular.module('main.events', []); 'use strict'; //Setting HTML5 Location Mode angular.module('main').config(['$locationProvider', function ($locationProvider) { $locationProvider.hashPrefix('!'); } ]); 'use strict'; angular.module('main.system') .factory('Global', [ function () { var obj = this; obj._data = { app: window.app || false }; return obj._data; } ]); 'use strict'; angular.element(document).ready(function() { //Fixing facebook bug with redirect if (window.location.hash === '#_=_') window.location.hash = '#!'; //Then init the app angular.bootstrap(document, ['main']); }); 'use strict'; angular.module('main').config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: '/views/index.html' }) .otherwise({ redirectTo: '/' }); } ]); 'use strict'; angular.module('main.index') .controller('IndexCtrl', ['$scope', '$routeParams', '$http', '$location', 'Global', 'Event', function ($scope, $routeParams, $http, $location, Global, Event) { $scope.global = Global; $scope.getEvents = function(){ Event.query(function(data){ $scope.events = data; }); }; $scope.init = function(){ $scope.getEvents(); }; } ]); 'use strict'; angular.module('main.events') .factory('Event', [ '$resource', function ($resource) { return $resource("/api/events/:id"); } ]);
NevadaCountyHackers/hackers-web-app
public/dist/app.js
JavaScript
mit
1,912
/** * StaticText.js * Text that cannot be changed after loaded by the game */ import GamePiece from './GamePiece.js'; import Info from './Info.js'; import Text from './Text.js'; export default class StaticText extends Text { constructor (config) { super(config); this.static = true; } }
javisaurusrex/zookillsoccer
modules/js/StaticText.js
JavaScript
mit
305
PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\ call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" msbuild steamworks4j.sln /p:Configuration=ReleaseDLL /p:Platform=Win32 /t:Rebuild move steamworks4j.dll ..\natives\libs\steamworks4j.dll copy ..\sdk\redistributable_bin\steam_api.dll ..\natives\libs\steam_api.dll msbuild steamworks4j.sln /p:Configuration=ReleaseDLL /p:Platform=x64 /t:Rebuild move steamworks4j.dll ..\natives\libs\steamworks4j64.dll copy ..\sdk\redistributable_bin\win64\steam_api64.dll ..\natives\libs\steam_api64.dll pause
franzbischoff/steamworks4j
build-natives/build-win.bat
Batchfile
mit
631
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_101) on Mon Sep 19 15:00:46 UTC 2016 --> <title>org.springframework.oxm.xmlbeans Class Hierarchy (Spring Framework 4.3.3.RELEASE API)</title><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "//hm.baidu.com/hm.js?dd1361ca20a10cc161e72d4bc4fef6df";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();</script> <meta name="date" content="2016-09-19"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.springframework.oxm.xmlbeans Class Hierarchy (Spring Framework 4.3.3.RELEASE API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/springframework/oxm/support/package-tree.html">Prev</a></li> <li><a href="../../../../org/springframework/oxm/xstream/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/springframework/oxm/xmlbeans/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.springframework.oxm.xmlbeans</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.springframework.oxm.support.<a href="../../../../org/springframework/oxm/support/AbstractMarshaller.html" title="class in org.springframework.oxm.support"><span class="typeNameLink">AbstractMarshaller</span></a> (implements org.springframework.oxm.<a href="../../../../org/springframework/oxm/Marshaller.html" title="interface in org.springframework.oxm">Marshaller</a>, org.springframework.oxm.<a href="../../../../org/springframework/oxm/Unmarshaller.html" title="interface in org.springframework.oxm">Unmarshaller</a>) <ul> <li type="circle">org.springframework.oxm.xmlbeans.<a href="../../../../org/springframework/oxm/xmlbeans/XmlBeansMarshaller.html" title="class in org.springframework.oxm.xmlbeans"><span class="typeNameLink">XmlBeansMarshaller</span></a></li> </ul> </li> <li type="circle">org.springframework.oxm.xmlbeans.<a href="../../../../org/springframework/oxm/xmlbeans/XmlOptionsFactoryBean.html" title="class in org.springframework.oxm.xmlbeans"><span class="typeNameLink">XmlOptionsFactoryBean</span></a> (implements org.springframework.beans.factory.<a href="../../../../org/springframework/beans/factory/FactoryBean.html" title="interface in org.springframework.beans.factory">FactoryBean</a>&lt;T&gt;)</li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Spring Framework</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/springframework/oxm/support/package-tree.html">Prev</a></li> <li><a href="../../../../org/springframework/oxm/xstream/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/springframework/oxm/xmlbeans/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
piterlin/piterlin.github.io
doc/spring4.3.3-docs/javadoc-api/org/springframework/oxm/xmlbeans/package-tree.html
HTML
mit
6,315
<?php /* * This file is part of the API Platform project. * * (c) Kévin Dunglas <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace ApiPlatform\Core\Tests\Metadata\Property\Factory; use ApiPlatform\Core\Metadata\Property\Factory\CachedPropertyNameCollectionFactory; use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Core\Metadata\Property\PropertyNameCollection; use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy; use ApiPlatform\Core\Tests\ProphecyTrait; use PHPUnit\Framework\TestCase; use Psr\Cache\CacheException; use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemPoolInterface; /** * @author Baptiste Meyer <[email protected]> */ class CachedPropertyNameCollectionFactoryTest extends TestCase { use ProphecyTrait; public function testCreateWithItemHit() { $cacheItem = $this->prophesize(CacheItemInterface::class); $cacheItem->isHit()->willReturn(true)->shouldBeCalled(); $cacheItem->get()->willReturn(new PropertyNameCollection(['id', 'name', 'description', 'dummy']))->shouldBeCalled(); $cacheItemPool = $this->prophesize(CacheItemPoolInterface::class); $cacheItemPool->getItem($this->generateCacheKey())->willReturn($cacheItem->reveal())->shouldBeCalled(); $decoratedPropertyNameCollectionFactory = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $cachedPropertyNameCollectionFactory = new CachedPropertyNameCollectionFactory($cacheItemPool->reveal(), $decoratedPropertyNameCollectionFactory->reveal()); $resultedPropertyNameCollection = $cachedPropertyNameCollectionFactory->create(Dummy::class); $expectedResult = new PropertyNameCollection(['id', 'name', 'description', 'dummy']); $this->assertEquals($expectedResult, $resultedPropertyNameCollection); $this->assertEquals($expectedResult, $cachedPropertyNameCollectionFactory->create(Dummy::class), 'Trigger the local cache'); } public function testCreateWithItemNotHit() { $resourceNameCollection = new PropertyNameCollection(['id', 'name', 'description', 'dummy']); $decoratedPropertyNameCollectionFactory = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $decoratedPropertyNameCollectionFactory->create(Dummy::class, [])->willReturn($resourceNameCollection)->shouldBeCalled(); $cacheItem = $this->prophesize(CacheItemInterface::class); $cacheItem->isHit()->willReturn(false)->shouldBeCalled(); $cacheItem->set($resourceNameCollection)->willReturn($cacheItem->reveal())->shouldBeCalled(); $cacheItemPool = $this->prophesize(CacheItemPoolInterface::class); $cacheItemPool->getItem($this->generateCacheKey())->willReturn($cacheItem->reveal())->shouldBeCalled(); $cacheItemPool->save($cacheItem->reveal())->willReturn(true)->shouldBeCalled(); $cachedPropertyNameCollectionFactory = new CachedPropertyNameCollectionFactory($cacheItemPool->reveal(), $decoratedPropertyNameCollectionFactory->reveal()); $resultedPropertyNameCollection = $cachedPropertyNameCollectionFactory->create(Dummy::class); $expectedResult = new PropertyNameCollection(['id', 'name', 'description', 'dummy']); $this->assertEquals($expectedResult, $resultedPropertyNameCollection); $this->assertEquals($expectedResult, $cachedPropertyNameCollectionFactory->create(Dummy::class), 'Trigger the local cache'); } public function testCreateWithGetCacheItemThrowsCacheException() { $decoratedPropertyNameCollectionFactory = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $decoratedPropertyNameCollectionFactory->create(Dummy::class, [])->willReturn(new PropertyNameCollection(['id', 'name', 'description', 'dummy']))->shouldBeCalled(); $cacheException = new class() extends \Exception implements CacheException {}; $cacheItemPool = $this->prophesize(CacheItemPoolInterface::class); $cacheItemPool->getItem($this->generateCacheKey())->willThrow($cacheException)->shouldBeCalled(); $cachedPropertyNameCollectionFactory = new CachedPropertyNameCollectionFactory($cacheItemPool->reveal(), $decoratedPropertyNameCollectionFactory->reveal()); $resultedPropertyNameCollection = $cachedPropertyNameCollectionFactory->create(Dummy::class); $expectedResult = new PropertyNameCollection(['id', 'name', 'description', 'dummy']); $this->assertEquals($expectedResult, $resultedPropertyNameCollection); $this->assertEquals($expectedResult, $cachedPropertyNameCollectionFactory->create(Dummy::class), 'Trigger the local cache'); } private function generateCacheKey(string $resourceClass = Dummy::class, array $options = []) { return CachedPropertyNameCollectionFactory::CACHE_KEY_PREFIX.md5(serialize([$resourceClass, $options])); } }
vincentchalamon/core
tests/Metadata/Property/Factory/CachedPropertyNameCollectionFactoryTest.php
PHP
mit
5,079
<?php namespace Tests\Behat\Mink; use Behat\Mink\Session; /** * @group unittest */ class SessionTest extends \PHPUnit_Framework_TestCase { private $driver; private $selectorsHandler; private $session; protected function setUp() { $this->driver = $this->getMockBuilder('Behat\Mink\Driver\DriverInterface')->getMock(); $this->selectorsHandler = $this->getMockBuilder('Behat\Mink\Selector\SelectorsHandler')->getMock(); $this->session = new Session($this->driver, $this->selectorsHandler); } public function testGetDriver() { $this->assertSame($this->driver, $this->session->getDriver()); } public function testGetPage() { $this->assertInstanceOf('Behat\Mink\Element\DocumentElement', $this->session->getPage()); } public function testGetSelectorsHandler() { $this->assertSame($this->selectorsHandler, $this->session->getSelectorsHandler()); } public function testVisit() { $this->driver ->expects($this->once()) ->method('visit') ->with($url = 'some_url'); $this->session->visit($url); } public function testReset() { $this->driver ->expects($this->once()) ->method('reset'); $this->session->reset(); } public function testGetResponseHeaders() { $this->driver ->expects($this->once()) ->method('getResponseHeaders') ->will($this->returnValue($ret = array(2, 3, 4))); $this->assertEquals($ret, $this->session->getResponseHeaders()); } public function testGetStatusCode() { $this->driver ->expects($this->once()) ->method('getStatusCode') ->will($this->returnValue($ret = 404)); $this->assertEquals($ret, $this->session->getStatusCode()); } public function testGetCurrentUrl() { $this->driver ->expects($this->once()) ->method('getCurrentUrl') ->will($this->returnValue($ret = 'http://some.url')); $this->assertEquals($ret, $this->session->getCurrentUrl()); } public function testExecuteScript() { $this->driver ->expects($this->once()) ->method('executeScript') ->with($arg = 'JS'); $this->session->executeScript($arg); } public function testEvaluateScript() { $this->driver ->expects($this->once()) ->method('evaluateScript') ->with($arg = 'JS func') ->will($this->returnValue($ret = '23')); $this->assertEquals($ret, $this->session->evaluateScript($arg)); } public function testWait() { $this->driver ->expects($this->once()) ->method('wait') ->with(1000, 'function() {}'); $this->session->wait(1000, 'function() {}'); } }
lrt/lrt
vendor/behat/mink/tests/Behat/Mink/SessionTest.php
PHP
mit
3,095
<?php namespace DuxCms\Model; use Think\Model; /** * 扩展字段数据操作 */ class FieldDataModel extends Model { //设置操作表 public function setTable($name) { $this->trueTableName = $this->tablePrefix.'ext_'.$name; } /** * 获取列表 * @return array 列表 */ public function loadList($where,$limit = 0,$order='data_id DESC'){ return $this->where($where)->limit($limit)->order($order)->select(); } /** * 获取数量 * @return array 数量 */ public function countList($where){ return $this->where($where)->count(); } /** * 获取信息 * @param int $dataId ID * @return array 信息 */ public function getInfo($dataId) { $map = array(); $map['data_id'] = $dataId; return $this->where($map)->find(); } /** * 更新信息 * @param string $type 更新类型 * @param array $fieldsetInfo 字段信息 * @param bool $prefix POST前缀 * @return bool 更新状态 */ public function saveData($type = 'add' , $fieldsetInfo){ //获取字段列表 $fieldList=D('DuxCms/Field')->loadList('fieldset_id='.$fieldsetInfo['fieldset_id']); if(empty($fieldList)||!is_array($fieldList)){ return; } //设置数据列表 $valiRules = array(); $autoRules = array(); $data = array(); foreach ($fieldList as $value) { $data[$value['field']] = I('Fieldset_'.$value['field']); $verify_data = base64_decode($value['verify_data']); if($verify_data){ $valiRules[] = array($value['field'], $verify_data ,$value['errormsg'],$value['verify_condition'],$value['verify_type'],3); } $autoRules[] = array($value['field'],'formatField',3,'callback',array($value['field'],$value['type'])); } $data = $this->auto($autoRules)->validate($valiRules)->create($data); if(!$data){ return false; } if($type == 'add'){ $this->tableName = $this->tableName; return $this->add($data); } if($type == 'edit'){ $data['data_id'] = I('post.data_id'); if(empty($data['data_id'])){ return false; } $status = $this->where('data_id='.$data['data_id'])->save(); if($status === false){ return false; } return true; } return false; } /** * 删除信息 * @param int $dataId ID * @return bool 删除状态 */ public function delData($dataId) { $map = array(); $map['data_id'] = $dataId; return $this->where($map)->delete(); } /** * 格式化字段信息 * @param string $field 字段名 * @param int $type 字段类型 * @return 格式化后数据 */ public function formatField($field,$type) { $data = $_POST['Fieldset_'.$field]; switch ($type) { case '2': case '3': return $data; break; case '6': $fileData=array(); if(is_array($data)){ foreach ($data['url'] as $key => $value) { $fileData[$key]['url'] = $value; $fileData[$key]['title'] = $data['title'][$key]; } return serialize($fileData); } break; case '7': case '8': return intval($data); break; case '10': if(!empty($data)){ return strtotime($data); }else{ return time(); } break; case '9': if(!empty($data)&&is_array($data)){ return implode(',',$data); } break; default: return I('post.Fieldset_'.$field); break; } } /** * 还原字段信息 * @param string $field 字段名 * @param int $type 字段类型 * @param int $type 字段配置信息 * @return 还原后数据 */ public function revertField($data,$type,$config) { switch ($type) { case '6': //文件列表 if(empty($data)){ return ; } $list=unserialize($data); return $list; break; case '7': case '8': if(empty($config)){ return $data; } $list = explode(",",trim($config)); $data = array(); $i = 0; foreach ($list as $value) { $i++; $data[$i] = $value; } return array( 'list' => $data, 'value' => intval($data), ); break; case '9': if(empty($config)){ return $data; } $list = explode(",",trim($config)); $data = array(); $i = 0; foreach ($list as $value) { $i++; $data[$i] = $value; } return array( 'list' => $data, 'value' => explode(",",trim($data)), ); break; case '11': return number_format($data,2); break; default: return html_out($data); break; } } /** * 字段列表显示 * @param int $type 字段类型 * @return array 字段类型列表 */ public function showListField($data,$type,$config) { switch ($type) { case '5': if($data){ return '<img name="" src="'.$data.'" alt="" style="max-width:170px; max-height:90px;" />'; }else{ return '无'; } break; case '6': //文件列表 if(empty($data)){ return '无'; } $list=unserialize($data); $html=''; if(!empty($list)){ foreach ($list as $key => $value) { $html.=$value['url'].'<br>'; } } return $html; break; case '7': case '8': if(empty($config)){ return $data; } $list=explode(",",trim($config)); foreach ($list as $key => $vo) { if($data==intval($key)+1){ return $vo; } } break; case '9': if(empty($config)){ return $data; } $list = explode(",",trim($config)); $newList = array(); $i = 0; foreach ($list as $value) { $i++; $newList[$i] = $value; } $data = explode(",",trim($data)); $html=''; foreach ($data as $key => $vo) { $html.=' '.$newList[$vo].' |'; } return substr($html,0,-1); break; case '10': return date('Y-m-d H:i:s',$data); break; case '11': return number_format($data,2); break; default: return $data; break; } } }
coneycode/cmsForMePad
Application/DuxCms/Model/FieldDataModel.class.php
PHP
mit
8,135
# Install on Laravel Forge 1. Disable nginx with `sudo update-rc.d -f nginx disable` 2. Create a new site for your blog, and install this Git Repository 3. Execute `npm install --production` in `/home/forge/{YOUR_GHOST_BLOG_SITE_NAME}`. 4. Reboot your server 5. Add a daenom for the root user that executes `npm start /home/forge/{YOUR_GHOST_BLOG_SITE_NAME} --production` 6. Update your deploy script to look like this: cd /home/forge/{YOUR_GHOST_BLOG_SITE_NAME} git pull origin master npm install --production forge daemon:restart {YOUR_DAEMON_ID} 7. Ta da!
adamgoose/ghost-blog
README.md
Markdown
mit
593
""" WSGI config for Carkinos project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Carkinos.settings") application = get_wsgi_application()
LeeYiFang/Carkinos
src/Carkinos/wsgi.py
Python
mit
393
# Smallest Integer # I worked on this challenge by myself. # smallest_integer is a method that takes an array of integers as its input # and returns the smallest integer in the array # # +list_of_nums+ is an array of integers # smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+ # # If +list_of_nums+ is empty the method should return nil # Your Solution Below def smallest_integer(list_of_nums) if list_of_nums == [] return nil else smallest = list_of_nums[0] list_of_nums.each do |num| if num < smallest smallest = num end end return smallest end end def smallest_integer(list_of_nums) if list_of_nums.empty? return nil else list_of_nums.sort[0] end end
jonwhuang/phase-0
week-4/smallest-integer/my_solution.rb
Ruby
mit
753
require_relative 'spec_helper' include LanguageSwitcher I18n.available_locales = [:pt, :en] describe "LanguageSwitcher" do it "should be able to switch to a language" do language(:pt){ I18n.locale.should == :pt } language(:en){ I18n.locale.should == :en } end it "should not be able to switch to a language unless it is included in I18n.default_locales" do lambda { language(:es) }.should raise_error end it "should pass thought each locale in I18n in order" do i = 0 each_language do |l| I18n.locale.should == I18n.available_locales[i] I18n.locale.should == l i+=1 end end # TODO: Add language_switcher view specs end
teonimesic/language_switcher
spec/language_switcher_spec.rb
Ruby
mit
682
import React from 'react'; import { string, node } from 'prop-types'; import classNames from 'classnames'; const TileAction = ({ children, className, ...rest }) => { return ( <div className={classNames('tile-action', className)} {...rest}> {children} </div> ); }; /** * TileAction property types. */ TileAction.propTypes = { className: string, children: node }; /** * TileAction default properties. */ TileAction.defaultProps = {}; export default TileAction;
Landish/react-spectre-css
src/components/TileAction/TileAction.js
JavaScript
mit
489
<?php /** * @link https://github.com/tigrov/yii2-country * @author Sergei Tigrov <[email protected]> */ namespace tigrov\country; /** * This is the model class for table "city_translation". * * @property integer $geoname_id * @property string $language_code * @property string $value */ class CityTranslation extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%city_translation}}'; } }
Tigrov/yii2-country
src/CityTranslation.php
PHP
mit
473
package com.mvas.webproxy.portals; import com.mvas.webproxy.DeviceConnectionInfo; import com.mvas.webproxy.RequestData; import com.mvas.webproxy.WebServer; import com.mvas.webproxy.config.PortalConfiguration; import org.apache.commons.io.IOUtils; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StalkerRequestHandler implements AbstractRequestHandler { private static final Logger logger = LoggerFactory.getLogger(StalkerRequestHandler.class); public static final String GET_PARAM_DEVICE_ID = "device_id"; public static final String GET_PARAM_DEVICE_ID2 = "device_id2"; public static final String GET_PARAM_SIGNATURE = "signature"; public static final String GET_PARAM_SESSION = "session"; public static final String CONFIG_PORTAL_URL = "portal"; public static final String GET_PARAM_MAC_ADDRESS = "mac"; public static final String ACTION_HANDSHAKE = "action=handshake"; Pattern cookiePattern = Pattern.compile(".*mac=(([0-9A-F]{2}[:-]){5}([0-9A-F]{2})).*"); Pattern handshakePattern = Pattern.compile(ACTION_HANDSHAKE); public static final String HEADER_AUTHORIZATION = "Authorization"; public static final class HeadersList { public HashMap<String, String> getList() { return list; } private HashMap<String, String> list = new HashMap<>(); } public static final class ParamsList { public HashMap<String, String> getList() { return list; } private HashMap<String, String> list = new HashMap<>(); } public HashMap<String, HeadersList> staticHeadersForMac = new HashMap<>(); public HashMap<String, ParamsList> staticParamsForMac = new HashMap<>(); DeviceConnectionInfo deviceConnectionInfo; static HashMap<String, Pattern> replacements = new HashMap<>(); static String[] configOptions; static String[] getParamNames; static { getParamNames = new String[] { GET_PARAM_DEVICE_ID, GET_PARAM_DEVICE_ID2, GET_PARAM_SIGNATURE, GET_PARAM_SESSION }; for (String name : getParamNames) { replacements.put(name, Pattern.compile("([\\?&])?(" + name + ")=([a-zA-Z0-9/+]*)")); } configOptions = new String[] { GET_PARAM_DEVICE_ID, GET_PARAM_DEVICE_ID2, GET_PARAM_SIGNATURE, GET_PARAM_SESSION, CONFIG_PORTAL_URL, GET_PARAM_MAC_ADDRESS }; } private HeadersList getHeadersForRequest(final RequestData requestData) { return staticHeadersForMac.get(requestData.getMacAddress()); } private ParamsList getParamsForRequest(final RequestData requestData) { return staticParamsForMac.get(requestData.getMacAddress()); } public StalkerRequestHandler(DeviceConnectionInfo deviceConnectionInfo) { this.deviceConnectionInfo = deviceConnectionInfo; } @Override public String getURL(final RequestData requestData) { logger.debug("StalkerRequestHandler::getURL()"); String result = requestData.getRealUrl().toString(); HashMap<String, String> staticParams = getParamsForRequest(requestData).getList(); for(Map.Entry<String, Pattern> entry: replacements.entrySet()) { Matcher matcher = entry.getValue().matcher(result); if(matcher.find()) { String name = matcher.group(2); if(staticParams.get(name) == null) { String value = matcher.group(3); staticParams.put(name, value); logger.debug("set static param [" + name + "] to [" + value + "]"); if(name.equals(GET_PARAM_DEVICE_ID)) WebServer.getPortalConfiguration().set(requestData.getConnectionName(), name, value); if(name.equals(GET_PARAM_DEVICE_ID2)) WebServer.getPortalConfiguration().set(requestData.getConnectionName(), name, value); } } } for(Map.Entry<String, Pattern> rep: replacements.entrySet()) { Pattern from = rep.getValue(); String to = rep.getKey(); result = result.replaceAll(from.pattern(), "$1$2=" + staticParams.get(to)); } logger.debug("New query string: " + result); return result; } @Override public void onRequest(final RequestData requestData, final URLConnection urlConnection) { logger.debug("StalkerRequestHandler::onRequest()"); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); for(Map.Entry<String, String> header: requestData.getHeaders().entrySet()) { String headerName = header.getKey(); String headerValue = header.getValue(); if(headerName.equals(HEADER_AUTHORIZATION)) { if(staticHeaders.get(HEADER_AUTHORIZATION) == null) staticHeaders.put(HEADER_AUTHORIZATION, headerValue); else { String authorizationHeader = staticHeaders.get(HEADER_AUTHORIZATION); if(headerValue.equals(authorizationHeader)) continue; logger.debug("Overwriting [" + HEADER_AUTHORIZATION + "] from {" + headerValue + " } to {" + authorizationHeader + "}"); urlConnection.setRequestProperty(HEADER_AUTHORIZATION, authorizationHeader); } } } } @Override public InputStream onResponse(final RequestData requestData, final InputStream iStream) { logger.debug("StalkerRequestHandler::onResponse()"); String target = requestData.getTarget(); if(!target.contains(".php")) return iStream; try { String data = IOUtils.toString(iStream); Matcher matcher = handshakePattern.matcher(requestData.getRealUrl().toString()); if(matcher.find()) { processHandshake(requestData, data); } return IOUtils.toInputStream(data); } catch (IOException e) { e.printStackTrace(); } return iStream; } @Override public void onBeforeRequest(final RequestData requestData, final PortalConfiguration portalConfiguration) { logger.debug("StalkerRequestHandler::onBeforeRequest()"); String macAddress = requestData.getMacAddress(); if(macAddress == null || macAddress.isEmpty()) { String cookie = requestData.getCookie().replace("%3A", ":"); Matcher matcher = cookiePattern.matcher(cookie); if(matcher.find()) { requestData.setMacAddress(matcher.group(1)); macAddress = matcher.group(1); logger.debug("MAC: " + matcher.group(1)); } else macAddress = "empty"; } if(!staticHeadersForMac.containsKey(macAddress)) staticHeadersForMac.put(macAddress, new HeadersList()); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); String token = portalConfiguration.get(requestData.getConnectionName(), "token"); if(token != null) staticHeaders.put(HEADER_AUTHORIZATION, "Bearer " + token); if(!staticParamsForMac.containsKey(macAddress)) { ParamsList params = new ParamsList(); HashMap<String, String> list = params.getList(); for(String name: configOptions) { String value = portalConfiguration.get(requestData.getConnectionName(), name); if(value == null) { logger.debug("Skipping NULL config value [" + name + "]"); continue; } logger.debug("Loading {" + name + "} -> {" + value + "}"); list.put(name, value); } staticParamsForMac.put(macAddress, params); } try { requestData.setRealUrl(new URL(getURL(requestData))); } catch (MalformedURLException e) { e.printStackTrace(); } } public void processHandshake(final RequestData requestData, final String data) { logger.debug("StalkerRequestHandler::processHandshake()"); HashMap<String, String> staticHeaders = getHeadersForRequest(requestData).getList(); JSONObject json; try { json = new JSONObject(data); JSONObject js = json.getJSONObject("js"); String token = js.getString("token"); staticHeaders.put(HEADER_AUTHORIZATION, "Bearer " + token); WebServer.getPortalConfiguration().set(requestData.getConnectionName(), "token", token); } catch (JSONException e) { e.printStackTrace(); } } }
mvasilchuk/webproxy
src/main/java/com/mvas/webproxy/portals/StalkerRequestHandler.java
Java
mit
9,322
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> :head :fbthumb </head> <body> <div id="wrapper"> <header> <div class="container"> <h1 class="col four"> <a href="@root_path/" class="logo">@name</a> </h1> <div class="col six nav"> <div class=navItems> :pages </div> </div> </div> </header> <div id="content" class="container" role="main"> <div class="description col four"> <h1>@title</h1> <p>@description</p> </div> <div class="col seven"> :media @content </div> <hr class="push"> </div> :footer </div> :analytics </body> </html>
senordavis/drawings
templates/contact.html
HTML
mit
741
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.actions; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import com.archimatetool.editor.ArchiPlugin; import com.archimatetool.editor.preferences.IPreferenceConstants; import com.archimatetool.editor.utils.StringUtils; /** * Check for New Action * * @author Phillip Beauvoir */ public class CheckForNewVersionAction extends Action { public CheckForNewVersionAction() { super(Messages.CheckForNewVersionAction_0); } String getOnlineVersion(URL url) throws IOException { URLConnection connection = url.openConnection(); connection.connect(); InputStream is = connection.getInputStream(); char[] buf = new char[32]; Reader r = new InputStreamReader(is, "UTF-8"); //$NON-NLS-1$ StringBuilder s = new StringBuilder(); while(true) { int n = r.read(buf); if(n < 0) { break; } s.append(buf, 0, n); } is.close(); r.close(); return s.toString(); } @Override public void run() { try { String versionFile = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.UPDATE_URL); if(!StringUtils.isSet(versionFile)) { return; } URL url = new URL(versionFile); String newVersion = getOnlineVersion(url); // Get this app's main version number String thisVersion = ArchiPlugin.INSTANCE.getVersion(); if(StringUtils.compareVersionNumbers(newVersion, thisVersion) > 0) { String downloadURL = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.DOWNLOAD_URL); // No download URL if(!StringUtils.isSet(downloadURL)) { MessageDialog.openInformation(null, Messages.CheckForNewVersionAction_1, Messages.CheckForNewVersionAction_2 + " (" + newVersion + "). "); //$NON-NLS-1$ //$NON-NLS-2$ return; } // Does have download URL boolean reply = MessageDialog.openQuestion(null, Messages.CheckForNewVersionAction_1, Messages.CheckForNewVersionAction_2 + " (" + newVersion + "). " + //$NON-NLS-1$ //$NON-NLS-2$ Messages.CheckForNewVersionAction_3); if(reply) { IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport(); IWebBrowser browser = support.getExternalBrowser(); if(browser != null) { URL url2 = new URL(downloadURL); browser.openURL(url2); } } } else { MessageDialog.openInformation(null, Messages.CheckForNewVersionAction_1, Messages.CheckForNewVersionAction_4); } } catch(MalformedURLException ex) { ex.printStackTrace(); } catch(IOException ex) { ex.printStackTrace(); showErrorMessage(Messages.CheckForNewVersionAction_5 + " " + ex.getMessage()); //$NON-NLS-1$ return; } catch(PartInitException ex) { ex.printStackTrace(); } }; @Override public boolean isEnabled() { String versionFile = ArchiPlugin.PREFERENCES.getString(IPreferenceConstants.UPDATE_URL); return StringUtils.isSet(versionFile); } private void showErrorMessage(String message) { MessageDialog.openError(null, Messages.CheckForNewVersionAction_6, message); } }
archimatetool/archi
com.archimatetool.editor/src/com/archimatetool/editor/actions/CheckForNewVersionAction.java
Java
mit
4,513
using System; using System.Collections.Generic; using EspaceClient.BackOffice.Domaine.Results; using EspaceClient.BackOffice.Silverlight.Business.Depots; using EspaceClient.BackOffice.Silverlight.Business.Interfaces; using EspaceClient.BackOffice.Silverlight.Infrastructure.Services; using EspaceClient.FrontOffice.Domaine; using nRoute.Components.Composition; using EspaceClient.BackOffice.Silverlight.Infrastructure.ServicePieceJointe; namespace EspaceClient.BackOffice.Silverlight.Data.Depots { /// <summary> /// Dépôt des pieces jointes /// </summary> [MapResource(typeof(IDepotPieceJointe), InstanceLifetime.Singleton)] public class DepotPieceJointe : IDepotPieceJointe { private readonly IServiceClientFactory _services; private readonly IApplicationContext _applicationContext; /// <summary> /// Initialise une nouvelle instance du dépôt. /// </summary> /// <param name="services">Fournisseur de services.</param> /// <param name="scheduler">Scheduler de tâches.</param> [ResolveConstructor] public DepotPieceJointe(IApplicationContext applicationContext, IServiceClientFactory services) { _applicationContext = applicationContext; _services = services; } public void UploadPieceJointeStarted(PieceJointeDto pieceJointe, Action<PieceJointeDto> callback, Action<Exception> error) { _services.ServicePieceJointe.Call<UploadPieceJointeStartedCompletedEventArgs>( s => s.UploadPieceJointeStartedAsync(_applicationContext.Context, pieceJointe), r => { if (r.Error != null) error(r.Error); else callback(r.Result); }); } public void UploadPieceJointeFinished(PieceJointeDto pieceJointe, Action<PieceJointeResult> callback, Action<Exception> error) { _services.ServicePieceJointe.Call<UploadPieceJointeFinishedCompletedEventArgs>( s => s.UploadPieceJointeFinishedAsync(_applicationContext.Context, pieceJointe), r => { if (r.Error != null) error(r.Error); else callback(r.Result); }); } public void AddLink(PieceJointeDto pieceJointe, Action<PieceJointeResult> callback, Action<Exception> error) { _services.ServicePieceJointe.Call<AddLinkCompletedEventArgs>( s => s.AddLinkAsync(_applicationContext.Context, pieceJointe), r => { if (r.Error != null) error(r.Error); else callback(r.Result); }); } public void UploadPieceJointe(PieceJointeDto pieceJointe, byte[] data, long part, Action<PieceJointeDto> callback, Action<Exception> error) { _services.ServicePieceJointe.Call<UploadPieceJointeCompletedEventArgs>( s => s.UploadPieceJointeAsync(_applicationContext.Context, pieceJointe, data, part), r => { if (r.Error != null) error(r.Error); else callback(r.Result); }); } public void GetPieceJointes(long vueId, long idFonctionnel, Action<IEnumerable<PieceJointeResult>> callback, Action<Exception> error) { _services.ServicePieceJointe.Call<GetPieceJointesCompletedEventArgs>( s => s.GetPieceJointesAsync(_applicationContext.Context, vueId, idFonctionnel), r => { if (r.Error != null) error(r.Error); else callback(r.Result); }); } public void GetPieceJointesByIdStarted(long pieceJointeId, Action<PieceJointeDto> callback, Action<Exception> error) { _services.ServicePieceJointe.Call<GetPieceJointeByIdStartedCompletedEventArgs>( s => s.GetPieceJointeByIdStartedAsync(_applicationContext.Context, pieceJointeId), r => { if (r.Error != null) error(r.Error); else callback(r.Result); }); } public void GetPieceJointesById(long pieceJointeId, long part, Action<byte[]> callback, Action<Exception> error) { _services.ServicePieceJointe.Call<GetPieceJointeByIdCompletedEventArgs>( s => s.GetPieceJointeByIdAsync(_applicationContext.Context, pieceJointeId, part), r => { if (r.Error != null) error(r.Error); else callback(r.Result); }); } public void DeletePieceJointe(long pieceJointeId, Action<bool> callback, Action<Exception> error) { _services.ServicePieceJointe.Call<DeletePieceJointeCompletedEventArgs>( s => s.DeletePieceJointeAsync(_applicationContext.Context, pieceJointeId), r => { if (r.Error != null) error(r.Error); else callback(r.Result); }); } } }
apo-j/Projects_Working
EC/espace-client-dot-net/EspaceClient.BackOffice.Silverlight.Data/Depots/DepotPieceJointe.cs
C#
mit
5,620
from io import BytesIO from django import forms from django.http import HttpResponse from django.template import Context, Template from braces.views import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, "The password you entered was incorrect, please try again.") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template(""" <font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font> <br/> {% if member.address or member.town %} {{ member.address }}<br/> {% if member.town %} {{ member.town }} NY <br/>{% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }} <br/> {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }} <br/> {% endif %} {% if member.email %} Email: {{ member.email }} <br/> {% endif %} {% if member.hobbies %} <strong>My Hobbies</strong>: {{ member.hobbies }} <br/> {% endif %} {% if member.canhelp %} <strong>I can help with</strong>: {{ member.canhelp }} <br/> {% endif %} {% if member.needhelp %} <strong>I could use help with</strong>: {{ member.needhelp }} <br/> {% endif %} """) content = [] for member in Member.objects.all(): context = Context({"member": member}) p = Paragraph(template.render(context), styles["Normal"]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
mooja/ssip3
app/members/views.py
Python
mit
4,530
import {Component} from "@angular/core"; @Component({ moduleId: module.id, selector: 'ptc-footer', templateUrl: 'footer.component.html' }) export class FooterComponent{ }
puncha/java-petclinic
src/main/webapp/resources/ng2/app/footer/footer.component.ts
TypeScript
mit
177
version https://git-lfs.github.com/spec/v1 oid sha256:8ecad6ce4ab24b16dd86e293b01f4b3d0ea62911d34288c6c78a9e6fe6b7da46 size 4972
yogeshsaroya/new-cdnjs
ajax/libs/semantic-ui/1.11.3/components/image.css
CSS
mit
129
<?php namespace Pinq\Iterators\Generators; use Pinq\Iterators\Standard\IIterator; /** * Implementation of the adapter iterator for Pinq\Iterators\IIterator using the generator * * @author Elliot Levin <[email protected]> */ class IIteratorAdapter extends Generator { /** * @var IIterator */ private $iterator; public function __construct(IIterator $iterator) { parent::__construct(); $this->iterator = $iterator; } public function &getIterator() { $this->iterator->rewind(); while ($element = $this->iterator->fetch()) { yield $element[0] => $element[1]; } } }
TimeToogo/Pinq
Source/Iterators/Generators/IIteratorAdapter.php
PHP
mit
671
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX ARM/ARM64 Code Generator Common Code XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator #ifdef _TARGET_ARMARCH_ // This file is ONLY used for ARM and ARM64 architectures #include "codegen.h" #include "lower.h" #include "gcinfo.h" #include "emit.h" //------------------------------------------------------------------------ // genCodeForTreeNode Generate code for a single node in the tree. // // Preconditions: // All operands have been evaluated. // void CodeGen::genCodeForTreeNode(GenTreePtr treeNode) { regNumber targetReg = treeNode->gtRegNum; var_types targetType = treeNode->TypeGet(); emitter* emit = getEmitter(); #ifdef DEBUG // Validate that all the operands for the current node are consumed in order. // This is important because LSRA ensures that any necessary copies will be // handled correctly. lastConsumedNode = nullptr; if (compiler->verbose) { unsigned seqNum = treeNode->gtSeqNum; // Useful for setting a conditional break in Visual Studio compiler->gtDispLIRNode(treeNode, "Generating: "); } #endif // DEBUG #ifdef _TARGET_ARM64_ // TODO-ARM: is this applicable to ARM32? // Is this a node whose value is already in a register? LSRA denotes this by // setting the GTF_REUSE_REG_VAL flag. if (treeNode->IsReuseRegVal()) { // For now, this is only used for constant nodes. assert((treeNode->OperGet() == GT_CNS_INT) || (treeNode->OperGet() == GT_CNS_DBL)); JITDUMP(" TreeNode is marked ReuseReg\n"); return; } #endif // _TARGET_ARM64_ // contained nodes are part of their parents for codegen purposes // ex : immediates, most LEAs if (treeNode->isContained()) { return; } switch (treeNode->gtOper) { case GT_START_NONGC: getEmitter()->emitDisableGC(); break; #ifdef _TARGET_ARM64_ case GT_PROF_HOOK: // We should be seeing this only if profiler hook is needed noway_assert(compiler->compIsProfilerHookNeeded()); #ifdef PROFILING_SUPPORTED // Right now this node is used only for tail calls. In future if // we intend to use it for Enter or Leave hooks, add a data member // to this node indicating the kind of profiler hook. For example, // helper number can be used. genProfilingLeaveCallback(CORINFO_HELP_PROF_FCN_TAILCALL); #endif // PROFILING_SUPPORTED break; #endif // _TARGET_ARM64_ case GT_LCLHEAP: genLclHeap(treeNode); break; case GT_CNS_INT: case GT_CNS_DBL: genSetRegToConst(targetReg, targetType, treeNode); genProduceReg(treeNode); break; case GT_NOT: case GT_NEG: genCodeForNegNot(treeNode); break; case GT_MOD: case GT_UMOD: case GT_DIV: case GT_UDIV: genCodeForDivMod(treeNode->AsOp()); break; case GT_OR: case GT_XOR: case GT_AND: assert(varTypeIsIntegralOrI(treeNode)); __fallthrough; #if !defined(_TARGET_64BIT_) case GT_ADD_LO: case GT_ADD_HI: case GT_SUB_LO: case GT_SUB_HI: #endif // !defined(_TARGET_64BIT_) case GT_ADD: case GT_SUB: case GT_MUL: genConsumeOperands(treeNode->AsOp()); genCodeForBinary(treeNode); break; case GT_LSH: case GT_RSH: case GT_RSZ: // case GT_ROL: // No ROL instruction on ARM; it has been lowered to ROR. case GT_ROR: genCodeForShift(treeNode); break; #if !defined(_TARGET_64BIT_) case GT_LSH_HI: case GT_RSH_LO: genCodeForShiftLong(treeNode); break; #endif // !defined(_TARGET_64BIT_) case GT_CAST: genCodeForCast(treeNode->AsOp()); break; case GT_BITCAST: { GenTree* op1 = treeNode->gtOp.gtOp1; if (varTypeIsFloating(treeNode) != varTypeIsFloating(op1)) { #ifdef _TARGET_ARM64_ inst_RV_RV(INS_fmov, targetReg, genConsumeReg(op1), targetType); #else // !_TARGET_ARM64_ if (varTypeIsFloating(treeNode)) { NYI_ARM("genRegCopy from 'int' to 'float'"); } else { assert(varTypeIsFloating(op1)); if (op1->TypeGet() == TYP_FLOAT) { inst_RV_RV(INS_vmov_f2i, targetReg, genConsumeReg(op1), targetType); } else { regNumber otherReg = (regNumber)treeNode->AsMultiRegOp()->gtOtherReg; assert(otherReg != REG_NA); inst_RV_RV_RV(INS_vmov_d2i, targetReg, otherReg, genConsumeReg(op1), EA_8BYTE); } } #endif // !_TARGET_ARM64_ } else { inst_RV_RV(ins_Copy(targetType), targetReg, genConsumeReg(op1), targetType); } } break; case GT_LCL_FLD_ADDR: case GT_LCL_VAR_ADDR: genCodeForLclAddr(treeNode); break; case GT_LCL_FLD: genCodeForLclFld(treeNode->AsLclFld()); break; case GT_LCL_VAR: genCodeForLclVar(treeNode->AsLclVar()); break; case GT_STORE_LCL_FLD: genCodeForStoreLclFld(treeNode->AsLclFld()); break; case GT_STORE_LCL_VAR: genCodeForStoreLclVar(treeNode->AsLclVar()); break; case GT_RETFILT: case GT_RETURN: genReturn(treeNode); break; case GT_LEA: // If we are here, it is the case where there is an LEA that cannot be folded into a parent instruction. genLeaInstruction(treeNode->AsAddrMode()); break; case GT_INDEX_ADDR: genCodeForIndexAddr(treeNode->AsIndexAddr()); break; case GT_IND: genCodeForIndir(treeNode->AsIndir()); break; #ifdef _TARGET_ARM_ case GT_MUL_LONG: genCodeForMulLong(treeNode->AsMultiRegOp()); break; #endif // _TARGET_ARM_ #ifdef _TARGET_ARM64_ case GT_MULHI: genCodeForMulHi(treeNode->AsOp()); break; case GT_SWAP: genCodeForSwap(treeNode->AsOp()); break; #endif // _TARGET_ARM64_ case GT_JMP: genJmpMethod(treeNode); break; case GT_CKFINITE: genCkfinite(treeNode); break; case GT_INTRINSIC: genIntrinsic(treeNode); break; #ifdef FEATURE_SIMD case GT_SIMD: genSIMDIntrinsic(treeNode->AsSIMD()); break; #endif // FEATURE_SIMD case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GE: case GT_GT: case GT_CMP: #ifdef _TARGET_ARM64_ case GT_TEST_EQ: case GT_TEST_NE: #endif // _TARGET_ARM64_ genCodeForCompare(treeNode->AsOp()); break; case GT_JTRUE: genCodeForJumpTrue(treeNode); break; #ifdef _TARGET_ARM64_ case GT_JCMP: genCodeForJumpCompare(treeNode->AsOp()); break; #endif // _TARGET_ARM64_ case GT_JCC: genCodeForJcc(treeNode->AsCC()); break; case GT_SETCC: genCodeForSetcc(treeNode->AsCC()); break; case GT_RETURNTRAP: genCodeForReturnTrap(treeNode->AsOp()); break; case GT_STOREIND: genCodeForStoreInd(treeNode->AsStoreInd()); break; case GT_COPY: // This is handled at the time we call genConsumeReg() on the GT_COPY break; case GT_LIST: case GT_FIELD_LIST: // Should always be marked contained. assert(!"LIST, FIELD_LIST nodes should always be marked contained."); break; case GT_PUTARG_STK: genPutArgStk(treeNode->AsPutArgStk()); break; case GT_PUTARG_REG: genPutArgReg(treeNode->AsOp()); break; #ifdef _TARGET_ARM_ case GT_PUTARG_SPLIT: genPutArgSplit(treeNode->AsPutArgSplit()); break; #endif case GT_CALL: genCallInstruction(treeNode->AsCall()); break; case GT_LOCKADD: case GT_XCHG: case GT_XADD: genLockedInstructions(treeNode->AsOp()); break; case GT_MEMORYBARRIER: instGen_MemoryBarrier(); break; case GT_CMPXCHG: NYI_ARM("GT_CMPXCHG"); #ifdef _TARGET_ARM64_ genCodeForCmpXchg(treeNode->AsCmpXchg()); #endif break; case GT_RELOAD: // do nothing - reload is just a marker. // The parent node will call genConsumeReg on this which will trigger the unspill of this node's child // into the register specified in this node. break; case GT_NOP: break; case GT_NO_OP: instGen(INS_nop); break; case GT_ARR_BOUNDS_CHECK: #ifdef FEATURE_SIMD case GT_SIMD_CHK: #endif // FEATURE_SIMD genRangeCheck(treeNode); break; case GT_PHYSREG: genCodeForPhysReg(treeNode->AsPhysReg()); break; case GT_NULLCHECK: genCodeForNullCheck(treeNode->AsOp()); break; case GT_CATCH_ARG: noway_assert(handlerGetsXcptnObj(compiler->compCurBB->bbCatchTyp)); /* Catch arguments get passed in a register. genCodeForBBlist() would have marked it as holding a GC object, but not used. */ noway_assert(gcInfo.gcRegGCrefSetCur & RBM_EXCEPTION_OBJECT); genConsumeReg(treeNode); break; case GT_PINVOKE_PROLOG: noway_assert(((gcInfo.gcRegGCrefSetCur | gcInfo.gcRegByrefSetCur) & ~fullIntArgRegMask()) == 0); // the runtime side requires the codegen here to be consistent emit->emitDisableRandomNops(); break; case GT_LABEL: genPendingCallLabel = genCreateTempLabel(); treeNode->gtLabel.gtLabBB = genPendingCallLabel; emit->emitIns_R_L(INS_adr, EA_PTRSIZE, genPendingCallLabel, targetReg); break; case GT_STORE_OBJ: case GT_STORE_DYN_BLK: case GT_STORE_BLK: genCodeForStoreBlk(treeNode->AsBlk()); break; case GT_JMPTABLE: genJumpTable(treeNode); break; case GT_SWITCH_TABLE: genTableBasedSwitch(treeNode); break; case GT_ARR_INDEX: genCodeForArrIndex(treeNode->AsArrIndex()); break; case GT_ARR_OFFSET: genCodeForArrOffset(treeNode->AsArrOffs()); break; #ifdef _TARGET_ARM_ case GT_CLS_VAR_ADDR: emit->emitIns_R_C(INS_lea, EA_PTRSIZE, targetReg, treeNode->gtClsVar.gtClsVarHnd, 0); genProduceReg(treeNode); break; case GT_LONG: assert(treeNode->isUsedFromReg()); genConsumeRegs(treeNode); break; #endif // _TARGET_ARM_ case GT_IL_OFFSET: // Do nothing; these nodes are simply markers for debug info. break; default: { #ifdef DEBUG char message[256]; _snprintf_s(message, _countof(message), _TRUNCATE, "NYI: Unimplemented node type %s", GenTree::OpName(treeNode->OperGet())); NYIRAW(message); #else NYI("unimplemented node"); #endif } break; } } //------------------------------------------------------------------------ // genSetRegToIcon: Generate code that will set the given register to the integer constant. // void CodeGen::genSetRegToIcon(regNumber reg, ssize_t val, var_types type, insFlags flags) { // Reg cannot be a FP reg assert(!genIsValidFloatReg(reg)); // The only TYP_REF constant that can come this path is a managed 'null' since it is not // relocatable. Other ref type constants (e.g. string objects) go through a different // code path. noway_assert(type != TYP_REF || val == 0); instGen_Set_Reg_To_Imm(emitActualTypeSize(type), reg, val, flags); } //--------------------------------------------------------------------- // genIntrinsic - generate code for a given intrinsic // // Arguments // treeNode - the GT_INTRINSIC node // // Return value: // None // void CodeGen::genIntrinsic(GenTreePtr treeNode) { assert(treeNode->OperIs(GT_INTRINSIC)); // Both operand and its result must be of the same floating point type. GenTreePtr srcNode = treeNode->gtOp.gtOp1; assert(varTypeIsFloating(srcNode)); assert(srcNode->TypeGet() == treeNode->TypeGet()); // Right now only Abs/Ceiling/Floor/Round/Sqrt are treated as math intrinsics. // switch (treeNode->gtIntrinsic.gtIntrinsicId) { case CORINFO_INTRINSIC_Abs: genConsumeOperands(treeNode->AsOp()); getEmitter()->emitInsBinary(INS_ABS, emitActualTypeSize(treeNode), treeNode, srcNode); break; #ifdef _TARGET_ARM64_ case CORINFO_INTRINSIC_Ceiling: genConsumeOperands(treeNode->AsOp()); getEmitter()->emitInsBinary(INS_frintp, emitActualTypeSize(treeNode), treeNode, srcNode); break; case CORINFO_INTRINSIC_Floor: genConsumeOperands(treeNode->AsOp()); getEmitter()->emitInsBinary(INS_frintm, emitActualTypeSize(treeNode), treeNode, srcNode); break; #endif case CORINFO_INTRINSIC_Round: NYI_ARM("genIntrinsic for round - not implemented yet"); genConsumeOperands(treeNode->AsOp()); getEmitter()->emitInsBinary(INS_ROUND, emitActualTypeSize(treeNode), treeNode, srcNode); break; case CORINFO_INTRINSIC_Sqrt: genConsumeOperands(treeNode->AsOp()); getEmitter()->emitInsBinary(INS_SQRT, emitActualTypeSize(treeNode), treeNode, srcNode); break; default: assert(!"genIntrinsic: Unsupported intrinsic"); unreached(); } genProduceReg(treeNode); } //--------------------------------------------------------------------- // genPutArgStk - generate code for a GT_PUTARG_STK node // // Arguments // treeNode - the GT_PUTARG_STK node // // Return value: // None // void CodeGen::genPutArgStk(GenTreePutArgStk* treeNode) { assert(treeNode->OperIs(GT_PUTARG_STK)); GenTreePtr source = treeNode->gtOp1; var_types targetType = source->TypeGet(); emitter* emit = getEmitter(); // This is the varNum for our store operations, // typically this is the varNum for the Outgoing arg space // When we are generating a tail call it will be the varNum for arg0 unsigned varNumOut = (unsigned)-1; unsigned argOffsetMax = (unsigned)-1; // Records the maximum size of this area for assert checks // Get argument offset to use with 'varNumOut' // Here we cross check that argument offset hasn't changed from lowering to codegen since // we are storing arg slot number in GT_PUTARG_STK node in lowering phase. unsigned argOffsetOut = treeNode->gtSlotNum * TARGET_POINTER_SIZE; #ifdef DEBUG fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(treeNode->gtCall, treeNode); assert(curArgTabEntry); assert(argOffsetOut == (curArgTabEntry->slotNum * TARGET_POINTER_SIZE)); #endif // DEBUG // Whether to setup stk arg in incoming or out-going arg area? // Fast tail calls implemented as epilog+jmp = stk arg is setup in incoming arg area. // All other calls - stk arg is setup in out-going arg area. if (treeNode->putInIncomingArgArea()) { varNumOut = getFirstArgWithStackSlot(); argOffsetMax = compiler->compArgSize; #if FEATURE_FASTTAILCALL // This must be a fast tail call. assert(treeNode->gtCall->IsFastTailCall()); // Since it is a fast tail call, the existence of first incoming arg is guaranteed // because fast tail call requires that in-coming arg area of caller is >= out-going // arg area required for tail call. LclVarDsc* varDsc = &(compiler->lvaTable[varNumOut]); assert(varDsc != nullptr); #endif // FEATURE_FASTTAILCALL } else { varNumOut = compiler->lvaOutgoingArgSpaceVar; argOffsetMax = compiler->lvaOutgoingArgSpaceSize; } bool isStruct = (targetType == TYP_STRUCT) || (source->OperGet() == GT_FIELD_LIST); if (!isStruct) // a normal non-Struct argument { instruction storeIns = ins_Store(targetType); emitAttr storeAttr = emitTypeSize(targetType); // If it is contained then source must be the integer constant zero if (source->isContained()) { #ifdef _TARGET_ARM64_ assert(source->OperGet() == GT_CNS_INT); assert(source->AsIntConCommon()->IconValue() == 0); emit->emitIns_S_R(storeIns, storeAttr, REG_ZR, varNumOut, argOffsetOut); #else // !_TARGET_ARM64_ // There is no zero register on ARM32 unreached(); #endif // !_TARGET_ARM64 } else { genConsumeReg(source); emit->emitIns_S_R(storeIns, storeAttr, source->gtRegNum, varNumOut, argOffsetOut); #ifdef _TARGET_ARM_ if (targetType == TYP_LONG) { // This case currently only occurs for double types that are passed as TYP_LONG; // actual long types would have been decomposed by now. assert(source->IsCopyOrReload()); regNumber otherReg = (regNumber)source->AsCopyOrReload()->GetRegNumByIdx(1); assert(otherReg != REG_NA); argOffsetOut += EA_4BYTE; emit->emitIns_S_R(storeIns, storeAttr, otherReg, varNumOut, argOffsetOut); } #endif // _TARGET_ARM_ } argOffsetOut += EA_SIZE_IN_BYTES(storeAttr); assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area } else // We have some kind of a struct argument { assert(source->isContained()); // We expect that this node was marked as contained in Lower if (source->OperGet() == GT_FIELD_LIST) { // Deal with the multi register passed struct args. GenTreeFieldList* fieldListPtr = source->AsFieldList(); // Evaluate each of the GT_FIELD_LIST items into their register // and store their register into the outgoing argument area for (; fieldListPtr != nullptr; fieldListPtr = fieldListPtr->Rest()) { GenTreePtr nextArgNode = fieldListPtr->gtOp.gtOp1; genConsumeReg(nextArgNode); regNumber reg = nextArgNode->gtRegNum; var_types type = nextArgNode->TypeGet(); emitAttr attr = emitTypeSize(type); // Emit store instructions to store the registers produced by the GT_FIELD_LIST into the outgoing // argument area emit->emitIns_S_R(ins_Store(type), attr, reg, varNumOut, argOffsetOut); argOffsetOut += EA_SIZE_IN_BYTES(attr); assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area } } else // We must have a GT_OBJ or a GT_LCL_VAR { noway_assert((source->OperGet() == GT_LCL_VAR) || (source->OperGet() == GT_OBJ)); var_types targetType = source->TypeGet(); noway_assert(varTypeIsStruct(targetType)); // We will copy this struct to the stack, possibly using a ldp/ldr instruction // in ARM64/ARM // Setup loReg (and hiReg) from the internal registers that we reserved in lower. // regNumber loReg = treeNode->ExtractTempReg(); #ifdef _TARGET_ARM64_ regNumber hiReg = treeNode->GetSingleTempReg(); #endif // _TARGET_ARM64_ regNumber addrReg = REG_NA; GenTreeLclVarCommon* varNode = nullptr; GenTreePtr addrNode = nullptr; if (source->OperGet() == GT_LCL_VAR) { varNode = source->AsLclVarCommon(); } else // we must have a GT_OBJ { assert(source->OperGet() == GT_OBJ); addrNode = source->gtOp.gtOp1; // addrNode can either be a GT_LCL_VAR_ADDR or an address expression // if (addrNode->OperGet() == GT_LCL_VAR_ADDR) { // We have a GT_OBJ(GT_LCL_VAR_ADDR) // // We will treat this case the same as above // (i.e if we just had this GT_LCL_VAR directly as the source) // so update 'source' to point this GT_LCL_VAR_ADDR node // and continue to the codegen for the LCL_VAR node below // varNode = addrNode->AsLclVarCommon(); addrNode = nullptr; } } // Either varNode or addrNOde must have been setup above, // the xor ensures that only one of the two is setup, not both assert((varNode != nullptr) ^ (addrNode != nullptr)); BYTE gcPtrArray[MAX_ARG_REG_COUNT] = {}; // TYPE_GC_NONE = 0 BYTE* gcPtrs = gcPtrArray; unsigned gcPtrCount; // The count of GC pointers in the struct int structSize; bool isHfa; // This is the varNum for our load operations, // only used when we have a multireg struct with a LclVar source unsigned varNumInp = BAD_VAR_NUM; #ifdef _TARGET_ARM_ // On ARM32, size of reference map can be larger than MAX_ARG_REG_COUNT gcPtrs = treeNode->gtGcPtrs; gcPtrCount = treeNode->gtNumberReferenceSlots; #endif // Setup the structSize, isHFa, and gcPtrCount if (varNode != nullptr) { varNumInp = varNode->gtLclNum; assert(varNumInp < compiler->lvaCount); LclVarDsc* varDsc = &compiler->lvaTable[varNumInp]; // This struct also must live in the stack frame // And it can't live in a register (SIMD) assert(varDsc->lvType == TYP_STRUCT); assert(varDsc->lvOnFrame && !varDsc->lvRegister); structSize = varDsc->lvSize(); // This yields the roundUp size, but that is fine // as that is how much stack is allocated for this LclVar isHfa = varDsc->lvIsHfa(); #ifdef _TARGET_ARM64_ gcPtrCount = varDsc->lvStructGcCount; for (unsigned i = 0; i < gcPtrCount; ++i) gcPtrs[i] = varDsc->lvGcLayout[i]; #endif // _TARGET_ARM_ } else // addrNode is used { assert(addrNode != nullptr); // Generate code to load the address that we need into a register genConsumeAddress(addrNode); addrReg = addrNode->gtRegNum; #ifdef _TARGET_ARM64_ // If addrReg equal to loReg, swap(loReg, hiReg) // This reduces code complexity by only supporting one addrReg overwrite case if (loReg == addrReg) { loReg = hiReg; hiReg = addrReg; } #endif // _TARGET_ARM64_ CORINFO_CLASS_HANDLE objClass = source->gtObj.gtClass; structSize = compiler->info.compCompHnd->getClassSize(objClass); isHfa = compiler->IsHfa(objClass); #ifdef _TARGET_ARM64_ gcPtrCount = compiler->info.compCompHnd->getClassGClayout(objClass, &gcPtrs[0]); #endif } // If we have an HFA we can't have any GC pointers, // if not then the max size for the the struct is 16 bytes if (isHfa) { noway_assert(gcPtrCount == 0); } #ifdef _TARGET_ARM64_ else { noway_assert(structSize <= 2 * TARGET_POINTER_SIZE); } noway_assert(structSize <= MAX_PASS_MULTIREG_BYTES); #endif // _TARGET_ARM64_ int remainingSize = structSize; unsigned structOffset = 0; unsigned nextIndex = 0; #ifdef _TARGET_ARM64_ // For a >= 16-byte structSize we will generate a ldp and stp instruction each loop // ldp x2, x3, [x0] // stp x2, x3, [sp, #16] while (remainingSize >= 2 * TARGET_POINTER_SIZE) { var_types type0 = compiler->getJitGCType(gcPtrs[nextIndex + 0]); var_types type1 = compiler->getJitGCType(gcPtrs[nextIndex + 1]); if (varNode != nullptr) { // Load from our varNumImp source emit->emitIns_R_R_S_S(INS_ldp, emitTypeSize(type0), emitTypeSize(type1), loReg, hiReg, varNumInp, 0); } else { // check for case of destroying the addrRegister while we still need it assert(loReg != addrReg); noway_assert((remainingSize == 2 * TARGET_POINTER_SIZE) || (hiReg != addrReg)); // Load from our address expression source emit->emitIns_R_R_R_I(INS_ldp, emitTypeSize(type0), loReg, hiReg, addrReg, structOffset, INS_OPTS_NONE, emitTypeSize(type0)); } // Emit stp instruction to store the two registers into the outgoing argument area emit->emitIns_S_S_R_R(INS_stp, emitTypeSize(type0), emitTypeSize(type1), loReg, hiReg, varNumOut, argOffsetOut); argOffsetOut += (2 * TARGET_POINTER_SIZE); // We stored 16-bytes of the struct assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area remainingSize -= (2 * TARGET_POINTER_SIZE); // We loaded 16-bytes of the struct structOffset += (2 * TARGET_POINTER_SIZE); nextIndex += 2; } #else // _TARGET_ARM_ // For a >= 4 byte structSize we will generate a ldr and str instruction each loop // ldr r2, [r0] // str r2, [sp, #16] while (remainingSize >= TARGET_POINTER_SIZE) { var_types type = compiler->getJitGCType(gcPtrs[nextIndex]); if (varNode != nullptr) { // Load from our varNumImp source emit->emitIns_R_S(INS_ldr, emitTypeSize(type), loReg, varNumInp, structOffset); } else { // check for case of destroying the addrRegister while we still need it assert(loReg != addrReg || remainingSize == TARGET_POINTER_SIZE); // Load from our address expression source emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), loReg, addrReg, structOffset); } // Emit str instruction to store the register into the outgoing argument area emit->emitIns_S_R(INS_str, emitTypeSize(type), loReg, varNumOut, argOffsetOut); argOffsetOut += TARGET_POINTER_SIZE; // We stored 4-bytes of the struct assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area remainingSize -= TARGET_POINTER_SIZE; // We loaded 4-bytes of the struct structOffset += TARGET_POINTER_SIZE; nextIndex += 1; } #endif // _TARGET_ARM_ // For a 12-byte structSize we will we will generate two load instructions // ldr x2, [x0] // ldr w3, [x0, #8] // str x2, [sp, #16] // str w3, [sp, #24] while (remainingSize > 0) { if (remainingSize >= TARGET_POINTER_SIZE) { var_types nextType = compiler->getJitGCType(gcPtrs[nextIndex]); emitAttr nextAttr = emitTypeSize(nextType); remainingSize -= TARGET_POINTER_SIZE; if (varNode != nullptr) { // Load from our varNumImp source emit->emitIns_R_S(ins_Load(nextType), nextAttr, loReg, varNumInp, structOffset); } else { assert(loReg != addrReg); // Load from our address expression source emit->emitIns_R_R_I(ins_Load(nextType), nextAttr, loReg, addrReg, structOffset); } // Emit a store instruction to store the register into the outgoing argument area emit->emitIns_S_R(ins_Store(nextType), nextAttr, loReg, varNumOut, argOffsetOut); argOffsetOut += EA_SIZE_IN_BYTES(nextAttr); assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area structOffset += TARGET_POINTER_SIZE; nextIndex++; } else // (remainingSize < TARGET_POINTER_SIZE) { int loadSize = remainingSize; remainingSize = 0; // We should never have to do a non-pointer sized load when we have a LclVar source assert(varNode == nullptr); // the left over size is smaller than a pointer and thus can never be a GC type assert(varTypeIsGC(compiler->getJitGCType(gcPtrs[nextIndex])) == false); var_types loadType = TYP_UINT; if (loadSize == 1) { loadType = TYP_UBYTE; } else if (loadSize == 2) { loadType = TYP_USHORT; } else { // Need to handle additional loadSize cases here noway_assert(loadSize == 4); } instruction loadIns = ins_Load(loadType); emitAttr loadAttr = emitAttr(loadSize); assert(loReg != addrReg); emit->emitIns_R_R_I(loadIns, loadAttr, loReg, addrReg, structOffset); // Emit a store instruction to store the register into the outgoing argument area emit->emitIns_S_R(ins_Store(loadType), loadAttr, loReg, varNumOut, argOffsetOut); argOffsetOut += EA_SIZE_IN_BYTES(loadAttr); assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area } } } } } //--------------------------------------------------------------------- // genPutArgReg - generate code for a GT_PUTARG_REG node // // Arguments // tree - the GT_PUTARG_REG node // // Return value: // None // void CodeGen::genPutArgReg(GenTreeOp* tree) { assert(tree->OperIs(GT_PUTARG_REG)); var_types targetType = tree->TypeGet(); regNumber targetReg = tree->gtRegNum; assert(targetType != TYP_STRUCT); GenTree* op1 = tree->gtOp1; genConsumeReg(op1); // If child node is not already in the register we need, move it if (targetReg != op1->gtRegNum) { inst_RV_RV(ins_Copy(targetType), targetReg, op1->gtRegNum, targetType); } genProduceReg(tree); } #ifdef _TARGET_ARM_ //--------------------------------------------------------------------- // genPutArgSplit - generate code for a GT_PUTARG_SPLIT node // // Arguments // tree - the GT_PUTARG_SPLIT node // // Return value: // None // void CodeGen::genPutArgSplit(GenTreePutArgSplit* treeNode) { assert(treeNode->OperIs(GT_PUTARG_SPLIT)); GenTreePtr source = treeNode->gtOp1; emitter* emit = getEmitter(); unsigned varNumOut = compiler->lvaOutgoingArgSpaceVar; unsigned argOffsetMax = compiler->lvaOutgoingArgSpaceSize; unsigned argOffsetOut = treeNode->gtSlotNum * TARGET_POINTER_SIZE; if (source->OperGet() == GT_FIELD_LIST) { GenTreeFieldList* fieldListPtr = source->AsFieldList(); // Evaluate each of the GT_FIELD_LIST items into their register // and store their register into the outgoing argument area for (unsigned idx = 0; fieldListPtr != nullptr; fieldListPtr = fieldListPtr->Rest(), idx++) { GenTreePtr nextArgNode = fieldListPtr->gtGetOp1(); regNumber fieldReg = nextArgNode->gtRegNum; genConsumeReg(nextArgNode); if (idx >= treeNode->gtNumRegs) { var_types type = nextArgNode->TypeGet(); emitAttr attr = emitTypeSize(type); // Emit store instructions to store the registers produced by the GT_FIELD_LIST into the outgoing // argument area emit->emitIns_S_R(ins_Store(type), attr, fieldReg, varNumOut, argOffsetOut); argOffsetOut += EA_SIZE_IN_BYTES(attr); assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area } else { var_types type = treeNode->GetRegType(idx); regNumber argReg = treeNode->GetRegNumByIdx(idx); // If child node is not already in the register we need, move it if (argReg != fieldReg) { inst_RV_RV(ins_Copy(type), argReg, fieldReg, type); } } } } else { var_types targetType = source->TypeGet(); assert(source->OperGet() == GT_OBJ); assert(varTypeIsStruct(targetType)); regNumber baseReg = treeNode->ExtractTempReg(); regNumber addrReg = REG_NA; GenTreeLclVarCommon* varNode = nullptr; GenTreePtr addrNode = nullptr; addrNode = source->gtOp.gtOp1; // addrNode can either be a GT_LCL_VAR_ADDR or an address expression // if (addrNode->OperGet() == GT_LCL_VAR_ADDR) { // We have a GT_OBJ(GT_LCL_VAR_ADDR) // // We will treat this case the same as above // (i.e if we just had this GT_LCL_VAR directly as the source) // so update 'source' to point this GT_LCL_VAR_ADDR node // and continue to the codegen for the LCL_VAR node below // varNode = addrNode->AsLclVarCommon(); addrNode = nullptr; } // Either varNode or addrNOde must have been setup above, // the xor ensures that only one of the two is setup, not both assert((varNode != nullptr) ^ (addrNode != nullptr)); // Setup the structSize, isHFa, and gcPtrCount BYTE* gcPtrs = treeNode->gtGcPtrs; unsigned gcPtrCount = treeNode->gtNumberReferenceSlots; // The count of GC pointers in the struct int structSize = treeNode->getArgSize(); // This is the varNum for our load operations, // only used when we have a struct with a LclVar source unsigned srcVarNum = BAD_VAR_NUM; if (varNode != nullptr) { srcVarNum = varNode->gtLclNum; assert(srcVarNum < compiler->lvaCount); // handle promote situation LclVarDsc* varDsc = compiler->lvaTable + srcVarNum; // This struct also must live in the stack frame // And it can't live in a register (SIMD) assert(varDsc->lvType == TYP_STRUCT); assert(varDsc->lvOnFrame && !varDsc->lvRegister); // We don't split HFA struct assert(!varDsc->lvIsHfa()); } else // addrNode is used { assert(addrNode != nullptr); // Generate code to load the address that we need into a register genConsumeAddress(addrNode); addrReg = addrNode->gtRegNum; // If addrReg equal to baseReg, we use the last target register as alternative baseReg. // Because the candidate mask for the internal baseReg does not include any of the target register, // we can ensure that baseReg, addrReg, and the last target register are not all same. assert(baseReg != addrReg); // We don't split HFA struct assert(!compiler->IsHfa(source->gtObj.gtClass)); } // Put on stack first unsigned nextIndex = treeNode->gtNumRegs; unsigned structOffset = nextIndex * TARGET_POINTER_SIZE; int remainingSize = structSize - structOffset; // remainingSize is always multiple of TARGET_POINTER_SIZE assert(remainingSize % TARGET_POINTER_SIZE == 0); while (remainingSize > 0) { var_types type = compiler->getJitGCType(gcPtrs[nextIndex]); if (varNode != nullptr) { // Load from our varNumImp source emit->emitIns_R_S(INS_ldr, emitTypeSize(type), baseReg, srcVarNum, structOffset); } else { // check for case of destroying the addrRegister while we still need it assert(baseReg != addrReg); // Load from our address expression source emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), baseReg, addrReg, structOffset); } // Emit str instruction to store the register into the outgoing argument area emit->emitIns_S_R(INS_str, emitTypeSize(type), baseReg, varNumOut, argOffsetOut); argOffsetOut += TARGET_POINTER_SIZE; // We stored 4-bytes of the struct assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area remainingSize -= TARGET_POINTER_SIZE; // We loaded 4-bytes of the struct structOffset += TARGET_POINTER_SIZE; nextIndex += 1; } // We set up the registers in order, so that we assign the last target register `baseReg` is no longer in use, // in case we had to reuse the last target register for it. structOffset = 0; for (unsigned idx = 0; idx < treeNode->gtNumRegs; idx++) { regNumber targetReg = treeNode->GetRegNumByIdx(idx); var_types type = treeNode->GetRegType(idx); if (varNode != nullptr) { // Load from our varNumImp source emit->emitIns_R_S(INS_ldr, emitTypeSize(type), targetReg, srcVarNum, structOffset); } else { // check for case of destroying the addrRegister while we still need it if (targetReg == addrReg && idx != treeNode->gtNumRegs - 1) { assert(targetReg != baseReg); emit->emitIns_R_R(INS_mov, emitActualTypeSize(type), baseReg, addrReg); addrReg = baseReg; } // Load from our address expression source emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), targetReg, addrReg, structOffset); } structOffset += TARGET_POINTER_SIZE; } } genProduceReg(treeNode); } #endif // _TARGET_ARM_ //---------------------------------------------------------------------------------- // genMultiRegCallStoreToLocal: store multi-reg return value of a call node to a local // // Arguments: // treeNode - Gentree of GT_STORE_LCL_VAR // // Return Value: // None // // Assumption: // The child of store is a multi-reg call node. // genProduceReg() on treeNode is made by caller of this routine. // void CodeGen::genMultiRegCallStoreToLocal(GenTreePtr treeNode) { assert(treeNode->OperGet() == GT_STORE_LCL_VAR); #if defined(_TARGET_ARM_) // Longs are returned in two return registers on Arm32. // Structs are returned in four registers on ARM32 and HFAs. assert(varTypeIsLong(treeNode) || varTypeIsStruct(treeNode)); #elif defined(_TARGET_ARM64_) // Structs of size >=9 and <=16 are returned in two return registers on ARM64 and HFAs. assert(varTypeIsStruct(treeNode)); #endif // _TARGET_* // Assumption: current implementation requires that a multi-reg // var in 'var = call' is flagged as lvIsMultiRegRet to prevent it from // being promoted. unsigned lclNum = treeNode->AsLclVarCommon()->gtLclNum; LclVarDsc* varDsc = &(compiler->lvaTable[lclNum]); noway_assert(varDsc->lvIsMultiRegRet); GenTree* op1 = treeNode->gtGetOp1(); GenTree* actualOp1 = op1->gtSkipReloadOrCopy(); GenTreeCall* call = actualOp1->AsCall(); assert(call->HasMultiRegRetVal()); genConsumeRegs(op1); ReturnTypeDesc* pRetTypeDesc = call->GetReturnTypeDesc(); unsigned regCount = pRetTypeDesc->GetReturnRegCount(); if (treeNode->gtRegNum != REG_NA) { // Right now the only enregistrable multi-reg return types supported are SIMD types. assert(varTypeIsSIMD(treeNode)); NYI("GT_STORE_LCL_VAR of a SIMD enregisterable struct"); } else { // Stack store int offset = 0; for (unsigned i = 0; i < regCount; ++i) { var_types type = pRetTypeDesc->GetReturnRegType(i); regNumber reg = call->GetRegNumByIdx(i); if (op1->IsCopyOrReload()) { // GT_COPY/GT_RELOAD will have valid reg for those positions // that need to be copied or reloaded. regNumber reloadReg = op1->AsCopyOrReload()->GetRegNumByIdx(i); if (reloadReg != REG_NA) { reg = reloadReg; } } assert(reg != REG_NA); getEmitter()->emitIns_S_R(ins_Store(type), emitTypeSize(type), reg, lclNum, offset); offset += genTypeSize(type); } varDsc->lvRegNum = REG_STK; } } //------------------------------------------------------------------------ // genRangeCheck: generate code for GT_ARR_BOUNDS_CHECK node. // void CodeGen::genRangeCheck(GenTreePtr oper) { #ifdef FEATURE_SIMD noway_assert(oper->OperGet() == GT_ARR_BOUNDS_CHECK || oper->OperGet() == GT_SIMD_CHK); #else // !FEATURE_SIMD noway_assert(oper->OperGet() == GT_ARR_BOUNDS_CHECK); #endif // !FEATURE_SIMD GenTreeBoundsChk* bndsChk = oper->AsBoundsChk(); GenTreePtr arrLen = bndsChk->gtArrLen; GenTreePtr arrIndex = bndsChk->gtIndex; GenTreePtr arrRef = NULL; int lenOffset = 0; GenTree* src1; GenTree* src2; emitJumpKind jmpKind; genConsumeRegs(arrIndex); genConsumeRegs(arrLen); if (arrIndex->isContainedIntOrIImmed()) { // To encode using a cmp immediate, we place the // constant operand in the second position src1 = arrLen; src2 = arrIndex; jmpKind = genJumpKindForOper(GT_LE, CK_UNSIGNED); } else { src1 = arrIndex; src2 = arrLen; jmpKind = genJumpKindForOper(GT_GE, CK_UNSIGNED); } var_types bndsChkType = genActualType(src2->TypeGet()); #if DEBUG // Bounds checks can only be 32 or 64 bit sized comparisons. assert(bndsChkType == TYP_INT || bndsChkType == TYP_LONG); // The type of the bounds check should always wide enough to compare against the index. assert(emitTypeSize(bndsChkType) >= emitActualTypeSize(src1->TypeGet())); #endif // DEBUG getEmitter()->emitInsBinary(INS_cmp, emitActualTypeSize(bndsChkType), src1, src2); genJumpToThrowHlpBlk(jmpKind, SCK_RNGCHK_FAIL, bndsChk->gtIndRngFailBB); } //--------------------------------------------------------------------- // genCodeForPhysReg - generate code for a GT_PHYSREG node // // Arguments // tree - the GT_PHYSREG node // // Return value: // None // void CodeGen::genCodeForPhysReg(GenTreePhysReg* tree) { assert(tree->OperIs(GT_PHYSREG)); var_types targetType = tree->TypeGet(); regNumber targetReg = tree->gtRegNum; if (targetReg != tree->gtSrcReg) { inst_RV_RV(ins_Copy(targetType), targetReg, tree->gtSrcReg, targetType); genTransferRegGCState(targetReg, tree->gtSrcReg); } genProduceReg(tree); } //--------------------------------------------------------------------- // genCodeForNullCheck - generate code for a GT_NULLCHECK node // // Arguments // tree - the GT_NULLCHECK node // // Return value: // None // void CodeGen::genCodeForNullCheck(GenTreeOp* tree) { assert(tree->OperIs(GT_NULLCHECK)); assert(!tree->gtOp1->isContained()); regNumber addrReg = genConsumeReg(tree->gtOp1); #ifdef _TARGET_ARM64_ regNumber targetReg = REG_ZR; #else regNumber targetReg = tree->GetSingleTempReg(); #endif getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, targetReg, addrReg, 0); } //------------------------------------------------------------------------ // genOffsetOfMDArrayLowerBound: Returns the offset from the Array object to the // lower bound for the given dimension. // // Arguments: // elemType - the element type of the array // rank - the rank of the array // dimension - the dimension for which the lower bound offset will be returned. // // Return Value: // The offset. // TODO-Cleanup: move to CodeGenCommon.cpp // static unsigned CodeGen::genOffsetOfMDArrayLowerBound(var_types elemType, unsigned rank, unsigned dimension) { // Note that the lower bound and length fields of the Array object are always TYP_INT return compiler->eeGetArrayDataOffset(elemType) + genTypeSize(TYP_INT) * (dimension + rank); } //------------------------------------------------------------------------ // genOffsetOfMDArrayLength: Returns the offset from the Array object to the // size for the given dimension. // // Arguments: // elemType - the element type of the array // rank - the rank of the array // dimension - the dimension for which the lower bound offset will be returned. // // Return Value: // The offset. // TODO-Cleanup: move to CodeGenCommon.cpp // static unsigned CodeGen::genOffsetOfMDArrayDimensionSize(var_types elemType, unsigned rank, unsigned dimension) { // Note that the lower bound and length fields of the Array object are always TYP_INT return compiler->eeGetArrayDataOffset(elemType) + genTypeSize(TYP_INT) * dimension; } //------------------------------------------------------------------------ // genCodeForArrIndex: Generates code to bounds check the index for one dimension of an array reference, // producing the effective index by subtracting the lower bound. // // Arguments: // arrIndex - the node for which we're generating code // // Return Value: // None. // void CodeGen::genCodeForArrIndex(GenTreeArrIndex* arrIndex) { emitter* emit = getEmitter(); GenTreePtr arrObj = arrIndex->ArrObj(); GenTreePtr indexNode = arrIndex->IndexExpr(); regNumber arrReg = genConsumeReg(arrObj); regNumber indexReg = genConsumeReg(indexNode); regNumber tgtReg = arrIndex->gtRegNum; noway_assert(tgtReg != REG_NA); // We will use a temp register to load the lower bound and dimension size values. regNumber tmpReg = arrIndex->GetSingleTempReg(); assert(tgtReg != tmpReg); unsigned dim = arrIndex->gtCurrDim; unsigned rank = arrIndex->gtArrRank; var_types elemType = arrIndex->gtArrElemType; unsigned offset; offset = genOffsetOfMDArrayLowerBound(elemType, rank, dim); emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset); // a 4 BYTE sign extending load emit->emitIns_R_R_R(INS_sub, EA_4BYTE, tgtReg, indexReg, tmpReg); offset = genOffsetOfMDArrayDimensionSize(elemType, rank, dim); emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset); // a 4 BYTE sign extending load emit->emitIns_R_R(INS_cmp, EA_4BYTE, tgtReg, tmpReg); emitJumpKind jmpGEU = genJumpKindForOper(GT_GE, CK_UNSIGNED); genJumpToThrowHlpBlk(jmpGEU, SCK_RNGCHK_FAIL); genProduceReg(arrIndex); } //------------------------------------------------------------------------ // genCodeForArrOffset: Generates code to compute the flattened array offset for // one dimension of an array reference: // result = (prevDimOffset * dimSize) + effectiveIndex // where dimSize is obtained from the arrObj operand // // Arguments: // arrOffset - the node for which we're generating code // // Return Value: // None. // // Notes: // dimSize and effectiveIndex are always non-negative, the former by design, // and the latter because it has been normalized to be zero-based. void CodeGen::genCodeForArrOffset(GenTreeArrOffs* arrOffset) { GenTreePtr offsetNode = arrOffset->gtOffset; GenTreePtr indexNode = arrOffset->gtIndex; regNumber tgtReg = arrOffset->gtRegNum; noway_assert(tgtReg != REG_NA); if (!offsetNode->IsIntegralConst(0)) { emitter* emit = getEmitter(); regNumber offsetReg = genConsumeReg(offsetNode); regNumber indexReg = genConsumeReg(indexNode); regNumber arrReg = genConsumeReg(arrOffset->gtArrObj); noway_assert(offsetReg != REG_NA); noway_assert(indexReg != REG_NA); noway_assert(arrReg != REG_NA); regNumber tmpReg = arrOffset->GetSingleTempReg(); unsigned dim = arrOffset->gtCurrDim; unsigned rank = arrOffset->gtArrRank; var_types elemType = arrOffset->gtArrElemType; unsigned offset = genOffsetOfMDArrayDimensionSize(elemType, rank, dim); // Load tmpReg with the dimension size and evaluate // tgtReg = offsetReg*tmpReg + indexReg. emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset); emit->emitIns_R_R_R_R(INS_MULADD, EA_PTRSIZE, tgtReg, tmpReg, offsetReg, indexReg); } else { regNumber indexReg = genConsumeReg(indexNode); if (indexReg != tgtReg) { inst_RV_RV(INS_mov, tgtReg, indexReg, TYP_INT); } } genProduceReg(arrOffset); } //------------------------------------------------------------------------ // indirForm: Make a temporary indir we can feed to pattern matching routines // in cases where we don't want to instantiate all the indirs that happen. // GenTreeIndir CodeGen::indirForm(var_types type, GenTree* base) { GenTreeIndir i(GT_IND, type, base, nullptr); i.gtRegNum = REG_NA; i.SetContained(); // has to be nonnull (because contained nodes can't be the last in block) // but don't want it to be a valid pointer i.gtNext = (GenTree*)(-1); return i; } //------------------------------------------------------------------------ // intForm: Make a temporary int we can feed to pattern matching routines // in cases where we don't want to instantiate. // GenTreeIntCon CodeGen::intForm(var_types type, ssize_t value) { GenTreeIntCon i(type, value); i.gtRegNum = REG_NA; // has to be nonnull (because contained nodes can't be the last in block) // but don't want it to be a valid pointer i.gtNext = (GenTree*)(-1); return i; } //------------------------------------------------------------------------ // genCodeForShift: Generates the code sequence for a GenTree node that // represents a bit shift or rotate operation (<<, >>, >>>, rol, ror). // // Arguments: // tree - the bit shift node (that specifies the type of bit shift to perform). // // Assumptions: // a) All GenTrees are register allocated. // void CodeGen::genCodeForShift(GenTreePtr tree) { var_types targetType = tree->TypeGet(); genTreeOps oper = tree->OperGet(); instruction ins = genGetInsForOper(oper, targetType); emitAttr size = emitActualTypeSize(tree); assert(tree->gtRegNum != REG_NA); genConsumeOperands(tree->AsOp()); GenTreePtr operand = tree->gtGetOp1(); GenTreePtr shiftBy = tree->gtGetOp2(); if (!shiftBy->IsCnsIntOrI()) { getEmitter()->emitIns_R_R_R(ins, size, tree->gtRegNum, operand->gtRegNum, shiftBy->gtRegNum); } else { unsigned immWidth = emitter::getBitWidth(size); // For ARM64, immWidth will be set to 32 or 64 ssize_t shiftByImm = shiftBy->gtIntCon.gtIconVal & (immWidth - 1); getEmitter()->emitIns_R_R_I(ins, size, tree->gtRegNum, operand->gtRegNum, shiftByImm); } genProduceReg(tree); } //------------------------------------------------------------------------ // genCodeForLclAddr: Generates the code for GT_LCL_FLD_ADDR/GT_LCL_VAR_ADDR. // // Arguments: // tree - the node. // void CodeGen::genCodeForLclAddr(GenTree* tree) { assert(tree->OperIs(GT_LCL_FLD_ADDR, GT_LCL_VAR_ADDR)); var_types targetType = tree->TypeGet(); regNumber targetReg = tree->gtRegNum; // Address of a local var. noway_assert(targetType == TYP_BYREF); inst_RV_TT(INS_lea, targetReg, tree, 0, EA_BYREF); genProduceReg(tree); } //------------------------------------------------------------------------ // genCodeForLclFld: Produce code for a GT_LCL_FLD node. // // Arguments: // tree - the GT_LCL_FLD node // void CodeGen::genCodeForLclFld(GenTreeLclFld* tree) { assert(tree->OperIs(GT_LCL_FLD)); var_types targetType = tree->TypeGet(); regNumber targetReg = tree->gtRegNum; emitter* emit = getEmitter(); NYI_IF(targetType == TYP_STRUCT, "GT_LCL_FLD: struct load local field not supported"); assert(targetReg != REG_NA); emitAttr size = emitTypeSize(targetType); unsigned offs = tree->gtLclOffs; unsigned varNum = tree->gtLclNum; assert(varNum < compiler->lvaCount); if (varTypeIsFloating(targetType)) { emit->emitIns_R_S(ins_Load(targetType), size, targetReg, varNum, offs); } else { #ifdef _TARGET_ARM64_ size = EA_SET_SIZE(size, EA_8BYTE); #endif // _TARGET_ARM64_ emit->emitIns_R_S(ins_Move_Extend(targetType, false), size, targetReg, varNum, offs); } genProduceReg(tree); } //------------------------------------------------------------------------ // genCodeForIndexAddr: Produce code for a GT_INDEX_ADDR node. // // Arguments: // tree - the GT_INDEX_ADDR node // void CodeGen::genCodeForIndexAddr(GenTreeIndexAddr* node) { GenTree* const base = node->Arr(); GenTree* const index = node->Index(); genConsumeReg(base); genConsumeReg(index); // NOTE: `genConsumeReg` marks the consumed register as not a GC pointer, as it assumes that the input registers // die at the first instruction generated by the node. This is not the case for `INDEX_ADDR`, however, as the // base register is multiply-used. As such, we need to mark the base register as containing a GC pointer until // we are finished generating the code for this node. gcInfo.gcMarkRegPtrVal(base->gtRegNum, base->TypeGet()); assert(!varTypeIsGC(index->TypeGet())); const regNumber tmpReg = node->GetSingleTempReg(); // Generate the bounds check if necessary. if ((node->gtFlags & GTF_INX_RNGCHK) != 0) { // Create a GT_IND(GT_LEA)) tree for the array length access and load the length into a register. GenTreeAddrMode arrLenAddr(base->TypeGet(), base, nullptr, 0, static_cast<unsigned>(node->gtLenOffset)); arrLenAddr.gtRegNum = REG_NA; arrLenAddr.SetContained(); arrLenAddr.gtNext = (GenTree*)(-1); GenTreeIndir arrLen = indirForm(TYP_INT, &arrLenAddr); arrLen.gtRegNum = tmpReg; arrLen.ClearContained(); getEmitter()->emitInsLoadStoreOp(ins_Load(TYP_INT), emitTypeSize(TYP_INT), arrLen.gtRegNum, &arrLen); #ifdef _TARGET_64BIT_ // The CLI Spec allows an array to be indexed by either an int32 or a native int. In the case that the index // is a native int on a 64-bit platform, we will need to widen the array length and the compare. if (index->TypeGet() == TYP_I_IMPL) { // Extend the array length as needed. getEmitter()->emitIns_R_R(ins_Move_Extend(TYP_INT, true), EA_8BYTE, arrLen.gtRegNum, arrLen.gtRegNum); } #endif // Generate the range check. getEmitter()->emitInsBinary(INS_cmp, emitActualTypeSize(TYP_I_IMPL), index, &arrLen); genJumpToThrowHlpBlk(genJumpKindForOper(GT_GE, CK_UNSIGNED), SCK_RNGCHK_FAIL, node->gtIndRngFailBB); } // Compute the address of the array element. switch (node->gtElemSize) { case 1: // dest = base + index getEmitter()->emitIns_R_R_R(INS_add, emitActualTypeSize(node), node->gtRegNum, base->gtRegNum, index->gtRegNum); break; case 2: case 4: case 8: case 16: { DWORD lsl; BitScanForward(&lsl, node->gtElemSize); // dest = base + index * scale genScaledAdd(emitActualTypeSize(node), node->gtRegNum, base->gtRegNum, index->gtRegNum, lsl); break; } default: { // tmp = scale CodeGen::genSetRegToIcon(tmpReg, (ssize_t)node->gtElemSize, TYP_INT); // dest = index * tmp + base getEmitter()->emitIns_R_R_R_R(INS_MULADD, emitActualTypeSize(node), node->gtRegNum, index->gtRegNum, tmpReg, base->gtRegNum); break; } } // dest = dest + elemOffs getEmitter()->emitIns_R_R_I(INS_add, emitActualTypeSize(node), node->gtRegNum, node->gtRegNum, node->gtElemOffset); gcInfo.gcMarkRegSetNpt(base->gtGetRegMask()); genProduceReg(node); } //------------------------------------------------------------------------ // genCodeForIndir: Produce code for a GT_IND node. // // Arguments: // tree - the GT_IND node // void CodeGen::genCodeForIndir(GenTreeIndir* tree) { assert(tree->OperIs(GT_IND)); var_types targetType = tree->TypeGet(); regNumber targetReg = tree->gtRegNum; emitter* emit = getEmitter(); emitAttr attr = emitTypeSize(tree); instruction ins = ins_Load(targetType); genConsumeAddress(tree->Addr()); if ((tree->gtFlags & GTF_IND_VOLATILE) != 0) { bool isAligned = ((tree->gtFlags & GTF_IND_UNALIGNED) == 0); assert((attr != EA_1BYTE) || isAligned); #ifdef _TARGET_ARM64_ GenTree* addr = tree->Addr(); bool useLoadAcquire = genIsValidIntReg(targetReg) && !addr->isContained() && (varTypeIsUnsigned(targetType) || varTypeIsI(targetType)) && !(tree->gtFlags & GTF_IND_UNALIGNED); if (useLoadAcquire) { switch (EA_SIZE(attr)) { case EA_1BYTE: assert(ins == INS_ldrb); ins = INS_ldarb; break; case EA_2BYTE: assert(ins == INS_ldrh); ins = INS_ldarh; break; case EA_4BYTE: case EA_8BYTE: assert(ins == INS_ldr); ins = INS_ldar; break; default: assert(false); // We should not get here } } emit->emitInsLoadStoreOp(ins, attr, targetReg, tree); if (!useLoadAcquire) // issue a INS_BARRIER_OSHLD after a volatile LdInd operation instGen_MemoryBarrier(INS_BARRIER_OSHLD); #else emit->emitInsLoadStoreOp(ins, attr, targetReg, tree); // issue a full memory barrier after a volatile LdInd operation instGen_MemoryBarrier(); #endif // _TARGET_ARM64_ } else { emit->emitInsLoadStoreOp(ins, attr, targetReg, tree); } genProduceReg(tree); } // Generate code for a CpBlk node by the means of the VM memcpy helper call // Preconditions: // a) The size argument of the CpBlk is not an integer constant // b) The size argument is a constant but is larger than CPBLK_MOVS_LIMIT bytes. void CodeGen::genCodeForCpBlk(GenTreeBlk* cpBlkNode) { // Make sure we got the arguments of the cpblk operation in the right registers unsigned blockSize = cpBlkNode->Size(); GenTreePtr dstAddr = cpBlkNode->Addr(); assert(!dstAddr->isContained()); genConsumeBlockOp(cpBlkNode, REG_ARG_0, REG_ARG_1, REG_ARG_2); #ifdef _TARGET_ARM64_ if (blockSize != 0) { assert(blockSize > CPBLK_UNROLL_LIMIT); } #endif // _TARGET_ARM64_ if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE) { // issue a full memory barrier before a volatile CpBlk operation instGen_MemoryBarrier(); } genEmitHelperCall(CORINFO_HELP_MEMCPY, 0, EA_UNKNOWN); if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE) { #ifdef _TARGET_ARM64_ // issue a INS_BARRIER_ISHLD after a volatile CpBlk operation instGen_MemoryBarrier(INS_BARRIER_ISHLD); #else // issue a full memory barrier after a volatile CpBlk operation instGen_MemoryBarrier(); #endif // _TARGET_ARM64_ } } //---------------------------------------------------------------------------------- // genCodeForCpBlkUnroll: Generates CpBlk code by performing a loop unroll // // Arguments: // cpBlkNode - Copy block node // // Return Value: // None // // Assumption: // The size argument of the CpBlk node is a constant and <= CPBLK_UNROLL_LIMIT bytes. // void CodeGen::genCodeForCpBlkUnroll(GenTreeBlk* cpBlkNode) { // Make sure we got the arguments of the cpblk operation in the right registers unsigned size = cpBlkNode->Size(); GenTreePtr dstAddr = cpBlkNode->Addr(); GenTreePtr source = cpBlkNode->Data(); GenTreePtr srcAddr = nullptr; assert((size != 0) && (size <= CPBLK_UNROLL_LIMIT)); emitter* emit = getEmitter(); if (dstAddr->isUsedFromReg()) { genConsumeReg(dstAddr); } if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE) { // issue a full memory barrier before a volatile CpBlkUnroll operation instGen_MemoryBarrier(); } if (source->gtOper == GT_IND) { srcAddr = source->gtGetOp1(); if (srcAddr->isUsedFromReg()) { genConsumeReg(srcAddr); } } else { noway_assert(source->IsLocal()); // TODO-Cleanup: Consider making the addrForm() method in Rationalize public, e.g. in GenTree. // OR: transform source to GT_IND(GT_LCL_VAR_ADDR) if (source->OperGet() == GT_LCL_VAR) { source->SetOper(GT_LCL_VAR_ADDR); } else { assert(source->OperGet() == GT_LCL_FLD); source->SetOper(GT_LCL_FLD_ADDR); } srcAddr = source; } unsigned offset = 0; // Grab the integer temp register to emit the loads and stores. regNumber tmpReg = cpBlkNode->ExtractTempReg(RBM_ALLINT); #ifdef _TARGET_ARM64_ if (size >= 2 * REGSIZE_BYTES) { regNumber tmp2Reg = cpBlkNode->ExtractTempReg(RBM_ALLINT); size_t slots = size / (2 * REGSIZE_BYTES); while (slots-- > 0) { // Load genCodeForLoadPairOffset(tmpReg, tmp2Reg, srcAddr, offset); // Store genCodeForStorePairOffset(tmpReg, tmp2Reg, dstAddr, offset); offset += 2 * REGSIZE_BYTES; } } // Fill the remainder (15 bytes or less) if there's one. if ((size & 0xf) != 0) { if ((size & 8) != 0) { genCodeForLoadOffset(INS_ldr, EA_8BYTE, tmpReg, srcAddr, offset); genCodeForStoreOffset(INS_str, EA_8BYTE, tmpReg, dstAddr, offset); offset += 8; } if ((size & 4) != 0) { genCodeForLoadOffset(INS_ldr, EA_4BYTE, tmpReg, srcAddr, offset); genCodeForStoreOffset(INS_str, EA_4BYTE, tmpReg, dstAddr, offset); offset += 4; } if ((size & 2) != 0) { genCodeForLoadOffset(INS_ldrh, EA_2BYTE, tmpReg, srcAddr, offset); genCodeForStoreOffset(INS_strh, EA_2BYTE, tmpReg, dstAddr, offset); offset += 2; } if ((size & 1) != 0) { genCodeForLoadOffset(INS_ldrb, EA_1BYTE, tmpReg, srcAddr, offset); genCodeForStoreOffset(INS_strb, EA_1BYTE, tmpReg, dstAddr, offset); } } #else // !_TARGET_ARM64_ size_t slots = size / REGSIZE_BYTES; while (slots-- > 0) { genCodeForLoadOffset(INS_ldr, EA_4BYTE, tmpReg, srcAddr, offset); genCodeForStoreOffset(INS_str, EA_4BYTE, tmpReg, dstAddr, offset); offset += REGSIZE_BYTES; } // Fill the remainder (3 bytes or less) if there's one. if ((size & 0x03) != 0) { if ((size & 2) != 0) { genCodeForLoadOffset(INS_ldrh, EA_2BYTE, tmpReg, srcAddr, offset); genCodeForStoreOffset(INS_strh, EA_2BYTE, tmpReg, dstAddr, offset); offset += 2; } if ((size & 1) != 0) { genCodeForLoadOffset(INS_ldrb, EA_1BYTE, tmpReg, srcAddr, offset); genCodeForStoreOffset(INS_strb, EA_1BYTE, tmpReg, dstAddr, offset); } } #endif // !_TARGET_ARM64_ if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE) { #ifdef _TARGET_ARM64_ // issue a INS_BARRIER_ISHLD after a volatile CpBlkUnroll operation instGen_MemoryBarrier(INS_BARRIER_ISHLD); #else // issue a full memory barrier after a volatile CpBlk operation instGen_MemoryBarrier(); #endif // !_TARGET_ARM64_ } } // Generates code for InitBlk by calling the VM memset helper function. // Preconditions: // a) The size argument of the InitBlk is not an integer constant. // b) The size argument of the InitBlk is >= INITBLK_STOS_LIMIT bytes. void CodeGen::genCodeForInitBlk(GenTreeBlk* initBlkNode) { unsigned size = initBlkNode->Size(); GenTreePtr dstAddr = initBlkNode->Addr(); GenTreePtr initVal = initBlkNode->Data(); if (initVal->OperIsInitVal()) { initVal = initVal->gtGetOp1(); } assert(!dstAddr->isContained()); assert(!initVal->isContained()); #ifdef _TARGET_ARM64_ if (size != 0) { assert(size > INITBLK_UNROLL_LIMIT); } #endif // _TARGET_ARM64_ genConsumeBlockOp(initBlkNode, REG_ARG_0, REG_ARG_1, REG_ARG_2); if (initBlkNode->gtFlags & GTF_BLK_VOLATILE) { // issue a full memory barrier before a volatile initBlock Operation instGen_MemoryBarrier(); } genEmitHelperCall(CORINFO_HELP_MEMSET, 0, EA_UNKNOWN); } // Generate code for a load from some address + offset // base: tree node which can be either a local address or arbitrary node // offset: distance from the base from which to load void CodeGen::genCodeForLoadOffset(instruction ins, emitAttr size, regNumber dst, GenTree* base, unsigned offset) { emitter* emit = getEmitter(); if (base->OperIsLocalAddr()) { if (base->gtOper == GT_LCL_FLD_ADDR) offset += base->gtLclFld.gtLclOffs; emit->emitIns_R_S(ins, size, dst, base->gtLclVarCommon.gtLclNum, offset); } else { emit->emitIns_R_R_I(ins, size, dst, base->gtRegNum, offset); } } // Generate code for a store to some address + offset // base: tree node which can be either a local address or arbitrary node // offset: distance from the base from which to load void CodeGen::genCodeForStoreOffset(instruction ins, emitAttr size, regNumber src, GenTree* base, unsigned offset) { emitter* emit = getEmitter(); if (base->OperIsLocalAddr()) { if (base->gtOper == GT_LCL_FLD_ADDR) offset += base->gtLclFld.gtLclOffs; emit->emitIns_S_R(ins, size, src, base->gtLclVarCommon.gtLclNum, offset); } else { emit->emitIns_R_R_I(ins, size, src, base->gtRegNum, offset); } } //------------------------------------------------------------------------ // genRegCopy: Generate a register copy. // void CodeGen::genRegCopy(GenTree* treeNode) { assert(treeNode->OperGet() == GT_COPY); var_types targetType = treeNode->TypeGet(); regNumber targetReg = treeNode->gtRegNum; assert(targetReg != REG_NA); GenTree* op1 = treeNode->gtOp.gtOp1; // Check whether this node and the node from which we're copying the value have the same // register type. // This can happen if (currently iff) we have a SIMD vector type that fits in an integer // register, in which case it is passed as an argument, or returned from a call, // in an integer register and must be copied if it's in an xmm register. if (varTypeIsFloating(treeNode) != varTypeIsFloating(op1)) { #ifdef _TARGET_ARM64_ inst_RV_RV(INS_fmov, targetReg, genConsumeReg(op1), targetType); #else // !_TARGET_ARM64_ if (varTypeIsFloating(treeNode)) { NYI_ARM("genRegCopy from 'int' to 'float'"); } else { assert(varTypeIsFloating(op1)); if (op1->TypeGet() == TYP_FLOAT) { inst_RV_RV(INS_vmov_f2i, targetReg, genConsumeReg(op1), targetType); } else { regNumber otherReg = (regNumber)treeNode->AsCopyOrReload()->gtOtherRegs[0]; assert(otherReg != REG_NA); inst_RV_RV_RV(INS_vmov_d2i, targetReg, otherReg, genConsumeReg(op1), EA_8BYTE); } } #endif // !_TARGET_ARM64_ } else { inst_RV_RV(ins_Copy(targetType), targetReg, genConsumeReg(op1), targetType); } if (op1->IsLocal()) { // The lclVar will never be a def. // If it is a last use, the lclVar will be killed by genConsumeReg(), as usual, and genProduceReg will // appropriately set the gcInfo for the copied value. // If not, there are two cases we need to handle: // - If this is a TEMPORARY copy (indicated by the GTF_VAR_DEATH flag) the variable // will remain live in its original register. // genProduceReg() will appropriately set the gcInfo for the copied value, // and genConsumeReg will reset it. // - Otherwise, we need to update register info for the lclVar. GenTreeLclVarCommon* lcl = op1->AsLclVarCommon(); assert((lcl->gtFlags & GTF_VAR_DEF) == 0); if ((lcl->gtFlags & GTF_VAR_DEATH) == 0 && (treeNode->gtFlags & GTF_VAR_DEATH) == 0) { LclVarDsc* varDsc = &compiler->lvaTable[lcl->gtLclNum]; // If we didn't just spill it (in genConsumeReg, above), then update the register info if (varDsc->lvRegNum != REG_STK) { // The old location is dying genUpdateRegLife(varDsc, /*isBorn*/ false, /*isDying*/ true DEBUGARG(op1)); gcInfo.gcMarkRegSetNpt(genRegMask(op1->gtRegNum)); genUpdateVarReg(varDsc, treeNode); // The new location is going live genUpdateRegLife(varDsc, /*isBorn*/ true, /*isDying*/ false DEBUGARG(treeNode)); } } } genProduceReg(treeNode); } //------------------------------------------------------------------------ // genCallInstruction: Produce code for a GT_CALL node // void CodeGen::genCallInstruction(GenTreeCall* call) { gtCallTypes callType = (gtCallTypes)call->gtCallType; IL_OFFSETX ilOffset = BAD_IL_OFFSET; // all virtuals should have been expanded into a control expression assert(!call->IsVirtual() || call->gtControlExpr || call->gtCallAddr); // Consume all the arg regs for (GenTreePtr list = call->gtCallLateArgs; list; list = list->MoveNext()) { assert(list->OperIsList()); GenTreePtr argNode = list->Current(); fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(call, argNode); assert(curArgTabEntry); // GT_RELOAD/GT_COPY use the child node argNode = argNode->gtSkipReloadOrCopy(); if (curArgTabEntry->regNum == REG_STK) continue; // Deal with multi register passed struct args. if (argNode->OperGet() == GT_FIELD_LIST) { GenTreeArgList* argListPtr = argNode->AsArgList(); unsigned iterationNum = 0; regNumber argReg = curArgTabEntry->regNum; for (; argListPtr != nullptr; argListPtr = argListPtr->Rest(), iterationNum++) { GenTreePtr putArgRegNode = argListPtr->gtOp.gtOp1; assert(putArgRegNode->gtOper == GT_PUTARG_REG); genConsumeReg(putArgRegNode); if (putArgRegNode->gtRegNum != argReg) { inst_RV_RV(ins_Move_Extend(putArgRegNode->TypeGet(), true), argReg, putArgRegNode->gtRegNum); } argReg = genRegArgNext(argReg); #if defined(_TARGET_ARM_) // A double register is modelled as an even-numbered single one if (putArgRegNode->TypeGet() == TYP_DOUBLE) { argReg = genRegArgNext(argReg); } #endif // _TARGET_ARM_ } } #ifdef _TARGET_ARM_ else if (curArgTabEntry->isSplit) { assert(curArgTabEntry->numRegs >= 1); genConsumeArgSplitStruct(argNode->AsPutArgSplit()); for (unsigned idx = 0; idx < curArgTabEntry->numRegs; idx++) { regNumber argReg = (regNumber)((unsigned)curArgTabEntry->regNum + idx); regNumber allocReg = argNode->AsPutArgSplit()->GetRegNumByIdx(idx); if (argReg != allocReg) { inst_RV_RV(ins_Move_Extend(argNode->TypeGet(), true), argReg, allocReg); } } } #endif else { regNumber argReg = curArgTabEntry->regNum; genConsumeReg(argNode); if (argNode->gtRegNum != argReg) { inst_RV_RV(ins_Move_Extend(argNode->TypeGet(), true), argReg, argNode->gtRegNum); } } } // Insert a null check on "this" pointer if asked. if (call->NeedsNullCheck()) { const regNumber regThis = genGetThisArgReg(call); #if defined(_TARGET_ARM_) const regNumber tmpReg = call->ExtractTempReg(); getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, tmpReg, regThis, 0); #elif defined(_TARGET_ARM64_) getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, REG_ZR, regThis, 0); #endif // _TARGET_* } // Either gtControlExpr != null or gtCallAddr != null or it is a direct non-virtual call to a user or helper method. CORINFO_METHOD_HANDLE methHnd; GenTree* target = call->gtControlExpr; if (callType == CT_INDIRECT) { assert(target == nullptr); target = call->gtCallAddr; methHnd = nullptr; } else { methHnd = call->gtCallMethHnd; } CORINFO_SIG_INFO* sigInfo = nullptr; #ifdef DEBUG // Pass the call signature information down into the emitter so the emitter can associate // native call sites with the signatures they were generated from. if (callType != CT_HELPER) { sigInfo = call->callSig; } #endif // DEBUG // If fast tail call, then we are done. In this case we setup the args (both reg args // and stack args in incoming arg area) and call target. Epilog sequence would // generate "br <reg>". if (call->IsFastTailCall()) { // Don't support fast tail calling JIT helpers assert(callType != CT_HELPER); // Fast tail calls materialize call target either in gtControlExpr or in gtCallAddr. assert(target != nullptr); genConsumeReg(target); // Use IP0 on ARM64 and R12 on ARM32 as the call target register. if (target->gtRegNum != REG_FASTTAILCALL_TARGET) { inst_RV_RV(INS_mov, REG_FASTTAILCALL_TARGET, target->gtRegNum); } return; } // For a pinvoke to unmanaged code we emit a label to clear // the GC pointer state before the callsite. // We can't utilize the typical lazy killing of GC pointers // at (or inside) the callsite. if (compiler->killGCRefs(call)) { genDefineTempLabel(genCreateTempLabel()); } // Determine return value size(s). ReturnTypeDesc* pRetTypeDesc = call->GetReturnTypeDesc(); emitAttr retSize = EA_PTRSIZE; emitAttr secondRetSize = EA_UNKNOWN; if (call->HasMultiRegRetVal()) { retSize = emitTypeSize(pRetTypeDesc->GetReturnRegType(0)); secondRetSize = emitTypeSize(pRetTypeDesc->GetReturnRegType(1)); } else { assert(!varTypeIsStruct(call)); if (call->gtType == TYP_REF || call->gtType == TYP_ARRAY) { retSize = EA_GCREF; } else if (call->gtType == TYP_BYREF) { retSize = EA_BYREF; } } // We need to propagate the IL offset information to the call instruction, so we can emit // an IL to native mapping record for the call, to support managed return value debugging. // We don't want tail call helper calls that were converted from normal calls to get a record, // so we skip this hash table lookup logic in that case. if (compiler->opts.compDbgInfo && compiler->genCallSite2ILOffsetMap != nullptr && !call->IsTailCall()) { (void)compiler->genCallSite2ILOffsetMap->Lookup(call, &ilOffset); } if (target != nullptr) { // A call target can not be a contained indirection assert(!target->isContainedIndir()); genConsumeReg(target); // We have already generated code for gtControlExpr evaluating it into a register. // We just need to emit "call reg" in this case. // assert(genIsValidIntReg(target->gtRegNum)); genEmitCall(emitter::EC_INDIR_R, methHnd, INDEBUG_LDISASM_COMMA(sigInfo) nullptr, // addr retSize MULTIREG_HAS_SECOND_GC_RET_ONLY_ARG(secondRetSize), ilOffset, target->gtRegNum); } else { // Generate a direct call to a non-virtual user defined or helper method assert(callType == CT_HELPER || callType == CT_USER_FUNC); void* addr = nullptr; #ifdef FEATURE_READYTORUN_COMPILER if (call->gtEntryPoint.addr != NULL) { assert(call->gtEntryPoint.accessType == IAT_VALUE); addr = call->gtEntryPoint.addr; } else #endif // FEATURE_READYTORUN_COMPILER if (callType == CT_HELPER) { CorInfoHelpFunc helperNum = compiler->eeGetHelperNum(methHnd); noway_assert(helperNum != CORINFO_HELP_UNDEF); void* pAddr = nullptr; addr = compiler->compGetHelperFtn(helperNum, (void**)&pAddr); assert(pAddr == nullptr); } else { // Direct call to a non-virtual user function. addr = call->gtDirectCallAddress; } assert(addr != nullptr); // Non-virtual direct call to known addresses #ifdef _TARGET_ARM_ if (!arm_Valid_Imm_For_BL((ssize_t)addr)) { regNumber tmpReg = call->GetSingleTempReg(); instGen_Set_Reg_To_Imm(EA_HANDLE_CNS_RELOC, tmpReg, (ssize_t)addr); genEmitCall(emitter::EC_INDIR_R, methHnd, INDEBUG_LDISASM_COMMA(sigInfo) NULL, retSize, ilOffset, tmpReg); } else #endif // _TARGET_ARM_ { genEmitCall(emitter::EC_FUNC_TOKEN, methHnd, INDEBUG_LDISASM_COMMA(sigInfo) addr, retSize MULTIREG_HAS_SECOND_GC_RET_ONLY_ARG(secondRetSize), ilOffset); } #if 0 && defined(_TARGET_ARM64_) // Use this path if you want to load an absolute call target using // a sequence of movs followed by an indirect call (blr instruction) // Load the call target address in x16 instGen_Set_Reg_To_Imm(EA_8BYTE, REG_IP0, (ssize_t) addr); // indirect call to constant address in IP0 genEmitCall(emitter::EC_INDIR_R, methHnd, INDEBUG_LDISASM_COMMA(sigInfo) nullptr, //addr retSize, secondRetSize, ilOffset, REG_IP0); #endif } // if it was a pinvoke we may have needed to get the address of a label if (genPendingCallLabel) { assert(call->IsUnmanaged()); genDefineTempLabel(genPendingCallLabel); genPendingCallLabel = nullptr; } // Update GC info: // All Callee arg registers are trashed and no longer contain any GC pointers. // TODO-Bug?: As a matter of fact shouldn't we be killing all of callee trashed regs here? // For now we will assert that other than arg regs gc ref/byref set doesn't contain any other // registers from RBM_CALLEE_TRASH assert((gcInfo.gcRegGCrefSetCur & (RBM_CALLEE_TRASH & ~RBM_ARG_REGS)) == 0); assert((gcInfo.gcRegByrefSetCur & (RBM_CALLEE_TRASH & ~RBM_ARG_REGS)) == 0); gcInfo.gcRegGCrefSetCur &= ~RBM_ARG_REGS; gcInfo.gcRegByrefSetCur &= ~RBM_ARG_REGS; var_types returnType = call->TypeGet(); if (returnType != TYP_VOID) { regNumber returnReg; if (call->HasMultiRegRetVal()) { assert(pRetTypeDesc != nullptr); unsigned regCount = pRetTypeDesc->GetReturnRegCount(); // If regs allocated to call node are different from ABI return // regs in which the call has returned its result, move the result // to regs allocated to call node. for (unsigned i = 0; i < regCount; ++i) { var_types regType = pRetTypeDesc->GetReturnRegType(i); returnReg = pRetTypeDesc->GetABIReturnReg(i); regNumber allocatedReg = call->GetRegNumByIdx(i); if (returnReg != allocatedReg) { inst_RV_RV(ins_Copy(regType), allocatedReg, returnReg, regType); } } } else { #ifdef _TARGET_ARM_ if (call->IsHelperCall(compiler, CORINFO_HELP_INIT_PINVOKE_FRAME)) { // The CORINFO_HELP_INIT_PINVOKE_FRAME helper uses a custom calling convention that returns with // TCB in REG_PINVOKE_TCB. fgMorphCall() sets the correct argument registers. returnReg = REG_PINVOKE_TCB; } else #endif // _TARGET_ARM_ if (varTypeIsFloating(returnType) && !compiler->opts.compUseSoftFP) { returnReg = REG_FLOATRET; } else { returnReg = REG_INTRET; } if (call->gtRegNum != returnReg) { #ifdef _TARGET_ARM_ if (compiler->opts.compUseSoftFP && returnType == TYP_DOUBLE) { inst_RV_RV_RV(INS_vmov_i2d, call->gtRegNum, returnReg, genRegArgNext(returnReg), EA_8BYTE); } else if (compiler->opts.compUseSoftFP && returnType == TYP_FLOAT) { inst_RV_RV(INS_vmov_i2f, call->gtRegNum, returnReg, returnType); } else #endif { inst_RV_RV(ins_Copy(returnType), call->gtRegNum, returnReg, returnType); } } } genProduceReg(call); } // If there is nothing next, that means the result is thrown away, so this value is not live. // However, for minopts or debuggable code, we keep it live to support managed return value debugging. if ((call->gtNext == nullptr) && !compiler->opts.MinOpts() && !compiler->opts.compDbgCode) { gcInfo.gcMarkRegSetNpt(RBM_INTRET); } } // Produce code for a GT_JMP node. // The arguments of the caller needs to be transferred to the callee before exiting caller. // The actual jump to callee is generated as part of caller epilog sequence. // Therefore the codegen of GT_JMP is to ensure that the callee arguments are correctly setup. void CodeGen::genJmpMethod(GenTreePtr jmp) { assert(jmp->OperGet() == GT_JMP); assert(compiler->compJmpOpUsed); // If no arguments, nothing to do if (compiler->info.compArgsCount == 0) { return; } // Make sure register arguments are in their initial registers // and stack arguments are put back as well. unsigned varNum; LclVarDsc* varDsc; // First move any en-registered stack arguments back to the stack. // At the same time any reg arg not in correct reg is moved back to its stack location. // // We are not strictly required to spill reg args that are not in the desired reg for a jmp call // But that would require us to deal with circularity while moving values around. Spilling // to stack makes the implementation simple, which is not a bad trade off given Jmp calls // are not frequent. for (varNum = 0; (varNum < compiler->info.compArgsCount); varNum++) { varDsc = compiler->lvaTable + varNum; if (varDsc->lvPromoted) { noway_assert(varDsc->lvFieldCnt == 1); // We only handle one field here unsigned fieldVarNum = varDsc->lvFieldLclStart; varDsc = compiler->lvaTable + fieldVarNum; } noway_assert(varDsc->lvIsParam); if (varDsc->lvIsRegArg && (varDsc->lvRegNum != REG_STK)) { // Skip reg args which are already in its right register for jmp call. // If not, we will spill such args to their stack locations. // // If we need to generate a tail call profiler hook, then spill all // arg regs to free them up for the callback. if (!compiler->compIsProfilerHookNeeded() && (varDsc->lvRegNum == varDsc->lvArgReg)) continue; } else if (varDsc->lvRegNum == REG_STK) { // Skip args which are currently living in stack. continue; } // If we came here it means either a reg argument not in the right register or // a stack argument currently living in a register. In either case the following // assert should hold. assert(varDsc->lvRegNum != REG_STK); assert(varDsc->TypeGet() != TYP_STRUCT); var_types storeType = genActualType(varDsc->TypeGet()); emitAttr storeSize = emitActualTypeSize(storeType); #ifdef _TARGET_ARM_ if (varDsc->TypeGet() == TYP_LONG) { // long - at least the low half must be enregistered getEmitter()->emitIns_S_R(ins_Store(TYP_INT), EA_4BYTE, varDsc->lvRegNum, varNum, 0); // Is the upper half also enregistered? if (varDsc->lvOtherReg != REG_STK) { getEmitter()->emitIns_S_R(ins_Store(TYP_INT), EA_4BYTE, varDsc->lvOtherReg, varNum, sizeof(int)); } } else #endif // _TARGET_ARM_ { getEmitter()->emitIns_S_R(ins_Store(storeType), storeSize, varDsc->lvRegNum, varNum, 0); } // Update lvRegNum life and GC info to indicate lvRegNum is dead and varDsc stack slot is going live. // Note that we cannot modify varDsc->lvRegNum here because another basic block may not be expecting it. // Therefore manually update life of varDsc->lvRegNum. regMaskTP tempMask = genRegMask(varDsc->lvRegNum); regSet.RemoveMaskVars(tempMask); gcInfo.gcMarkRegSetNpt(tempMask); if (compiler->lvaIsGCTracked(varDsc)) { VarSetOps::AddElemD(compiler, gcInfo.gcVarPtrSetCur, varNum); } } #ifdef PROFILING_SUPPORTED // At this point all arg regs are free. // Emit tail call profiler callback. genProfilingLeaveCallback(CORINFO_HELP_PROF_FCN_TAILCALL); #endif // Next move any un-enregistered register arguments back to their register. regMaskTP fixedIntArgMask = RBM_NONE; // tracks the int arg regs occupying fixed args in case of a vararg method. unsigned firstArgVarNum = BAD_VAR_NUM; // varNum of the first argument in case of a vararg method. for (varNum = 0; (varNum < compiler->info.compArgsCount); varNum++) { varDsc = compiler->lvaTable + varNum; if (varDsc->lvPromoted) { noway_assert(varDsc->lvFieldCnt == 1); // We only handle one field here unsigned fieldVarNum = varDsc->lvFieldLclStart; varDsc = compiler->lvaTable + fieldVarNum; } noway_assert(varDsc->lvIsParam); // Skip if arg not passed in a register. if (!varDsc->lvIsRegArg) continue; // Register argument noway_assert(isRegParamType(genActualType(varDsc->TypeGet()))); // Is register argument already in the right register? // If not load it from its stack location. regNumber argReg = varDsc->lvArgReg; // incoming arg register regNumber argRegNext = REG_NA; #ifdef _TARGET_ARM64_ if (varDsc->lvRegNum != argReg) { var_types loadType = TYP_UNDEF; if (varTypeIsStruct(varDsc)) { // Must be <= 16 bytes or else it wouldn't be passed in registers noway_assert(EA_SIZE_IN_BYTES(varDsc->lvSize()) <= MAX_PASS_MULTIREG_BYTES); loadType = compiler->getJitGCType(varDsc->lvGcLayout[0]); } else { loadType = compiler->mangleVarArgsType(genActualType(varDsc->TypeGet())); } emitAttr loadSize = emitActualTypeSize(loadType); getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, argReg, varNum, 0); // Update argReg life and GC Info to indicate varDsc stack slot is dead and argReg is going live. // Note that we cannot modify varDsc->lvRegNum here because another basic block may not be expecting it. // Therefore manually update life of argReg. Note that GT_JMP marks the end of the basic block // and after which reg life and gc info will be recomputed for the new block in genCodeForBBList(). regSet.AddMaskVars(genRegMask(argReg)); gcInfo.gcMarkRegPtrVal(argReg, loadType); if (compiler->lvaIsMultiregStruct(varDsc)) { if (varDsc->lvIsHfa()) { NYI_ARM64("CodeGen::genJmpMethod with multireg HFA arg"); } // Restore the second register. argRegNext = genRegArgNext(argReg); loadType = compiler->getJitGCType(varDsc->lvGcLayout[1]); loadSize = emitActualTypeSize(loadType); getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, argRegNext, varNum, TARGET_POINTER_SIZE); regSet.AddMaskVars(genRegMask(argRegNext)); gcInfo.gcMarkRegPtrVal(argRegNext, loadType); } if (compiler->lvaIsGCTracked(varDsc)) { VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varNum); } } // In case of a jmp call to a vararg method ensure only integer registers are passed. if (compiler->info.compIsVarArgs) { assert((genRegMask(argReg) & RBM_ARG_REGS) != RBM_NONE); fixedIntArgMask |= genRegMask(argReg); if (compiler->lvaIsMultiregStruct(varDsc)) { assert(argRegNext != REG_NA); fixedIntArgMask |= genRegMask(argRegNext); } if (argReg == REG_ARG_0) { assert(firstArgVarNum == BAD_VAR_NUM); firstArgVarNum = varNum; } } #else bool twoParts = false; var_types loadType = TYP_UNDEF; if (varDsc->TypeGet() == TYP_LONG) { twoParts = true; } else if (varDsc->TypeGet() == TYP_DOUBLE) { if (compiler->info.compIsVarArgs || compiler->opts.compUseSoftFP) { twoParts = true; } } if (twoParts) { argRegNext = genRegArgNext(argReg); if (varDsc->lvRegNum != argReg) { getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argReg, varNum, 0); getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argRegNext, varNum, REGSIZE_BYTES); } if (compiler->info.compIsVarArgs) { fixedIntArgMask |= genRegMask(argReg); fixedIntArgMask |= genRegMask(argRegNext); } } else if (varDsc->lvIsHfaRegArg()) { loadType = varDsc->GetHfaType(); regNumber fieldReg = argReg; emitAttr loadSize = emitActualTypeSize(loadType); unsigned maxSize = min(varDsc->lvSize(), (LAST_FP_ARGREG + 1 - argReg) * REGSIZE_BYTES); for (unsigned ofs = 0; ofs < maxSize; ofs += (unsigned)loadSize) { if (varDsc->lvRegNum != argReg) { getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, fieldReg, varNum, ofs); } assert(genIsValidFloatReg(fieldReg)); // we don't use register tracking for FP fieldReg = regNextOfType(fieldReg, loadType); } } else if (varTypeIsStruct(varDsc)) { regNumber slotReg = argReg; unsigned maxSize = min(varDsc->lvSize(), (REG_ARG_LAST + 1 - argReg) * REGSIZE_BYTES); for (unsigned ofs = 0; ofs < maxSize; ofs += REGSIZE_BYTES) { unsigned idx = ofs / REGSIZE_BYTES; loadType = compiler->getJitGCType(varDsc->lvGcLayout[idx]); if (varDsc->lvRegNum != argReg) { emitAttr loadSize = emitActualTypeSize(loadType); getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, slotReg, varNum, ofs); } regSet.AddMaskVars(genRegMask(slotReg)); gcInfo.gcMarkRegPtrVal(slotReg, loadType); if (genIsValidIntReg(slotReg) && compiler->info.compIsVarArgs) { fixedIntArgMask |= genRegMask(slotReg); } slotReg = genRegArgNext(slotReg); } } else { loadType = compiler->mangleVarArgsType(genActualType(varDsc->TypeGet())); if (varDsc->lvRegNum != argReg) { getEmitter()->emitIns_R_S(ins_Load(loadType), emitTypeSize(loadType), argReg, varNum, 0); } regSet.AddMaskVars(genRegMask(argReg)); gcInfo.gcMarkRegPtrVal(argReg, loadType); if (genIsValidIntReg(argReg) && compiler->info.compIsVarArgs) { fixedIntArgMask |= genRegMask(argReg); } } if (compiler->lvaIsGCTracked(varDsc)) { VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varNum); } #endif } // Jmp call to a vararg method - if the method has fewer than fixed arguments that can be max size of reg, // load the remaining integer arg registers from the corresponding // shadow stack slots. This is for the reason that we don't know the number and type // of non-fixed params passed by the caller, therefore we have to assume the worst case // of caller passing all integer arg regs that can be max size of reg. // // The caller could have passed gc-ref/byref type var args. Since these are var args // the callee no way of knowing their gc-ness. Therefore, mark the region that loads // remaining arg registers from shadow stack slots as non-gc interruptible. if (fixedIntArgMask != RBM_NONE) { assert(compiler->info.compIsVarArgs); assert(firstArgVarNum != BAD_VAR_NUM); regMaskTP remainingIntArgMask = RBM_ARG_REGS & ~fixedIntArgMask; if (remainingIntArgMask != RBM_NONE) { getEmitter()->emitDisableGC(); for (int argNum = 0, argOffset = 0; argNum < MAX_REG_ARG; ++argNum) { regNumber argReg = intArgRegs[argNum]; regMaskTP argRegMask = genRegMask(argReg); if ((remainingIntArgMask & argRegMask) != 0) { remainingIntArgMask &= ~argRegMask; getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argReg, firstArgVarNum, argOffset); } argOffset += REGSIZE_BYTES; } getEmitter()->emitEnableGC(); } } } //------------------------------------------------------------------------ // genIntToIntCast: Generate code for an integer cast // // Arguments: // treeNode - The GT_CAST node // // Return Value: // None. // // Assumptions: // The treeNode must have an assigned register. // For a signed convert from byte, the source must be in a byte-addressable register. // Neither the source nor target type can be a floating point type. // // TODO-ARM64-CQ: Allow castOp to be a contained node without an assigned register. // void CodeGen::genIntToIntCast(GenTreePtr treeNode) { assert(treeNode->OperGet() == GT_CAST); GenTreePtr castOp = treeNode->gtCast.CastOp(); emitter* emit = getEmitter(); var_types dstType = treeNode->CastToType(); var_types srcType = genActualType(castOp->TypeGet()); emitAttr movSize = emitActualTypeSize(dstType); bool movRequired = false; #ifdef _TARGET_ARM_ if (varTypeIsLong(srcType)) { genLongToIntCast(treeNode); return; } #endif // _TARGET_ARM_ regNumber targetReg = treeNode->gtRegNum; regNumber sourceReg = castOp->gtRegNum; // For Long to Int conversion we will have a reserved integer register to hold the immediate mask regNumber tmpReg = (treeNode->AvailableTempRegCount() == 0) ? REG_NA : treeNode->GetSingleTempReg(); assert(genIsValidIntReg(targetReg)); assert(genIsValidIntReg(sourceReg)); instruction ins = INS_invalid; genConsumeReg(castOp); Lowering::CastInfo castInfo; // Get information about the cast. Lowering::getCastDescription(treeNode, &castInfo); if (castInfo.requiresOverflowCheck) { emitAttr cmpSize = EA_ATTR(genTypeSize(srcType)); if (castInfo.signCheckOnly) { // We only need to check for a negative value in sourceReg emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, 0); emitJumpKind jmpLT = genJumpKindForOper(GT_LT, CK_SIGNED); genJumpToThrowHlpBlk(jmpLT, SCK_OVERFLOW); noway_assert(genTypeSize(srcType) == 4 || genTypeSize(srcType) == 8); // This is only interesting case to ensure zero-upper bits. if ((srcType == TYP_INT) && (dstType == TYP_ULONG)) { // cast to TYP_ULONG: // We use a mov with size=EA_4BYTE // which will zero out the upper bits movSize = EA_4BYTE; movRequired = true; } } else if (castInfo.unsignedSource || castInfo.unsignedDest) { // When we are converting from/to unsigned, // we only have to check for any bits set in 'typeMask' noway_assert(castInfo.typeMask != 0); #if defined(_TARGET_ARM_) if (arm_Valid_Imm_For_Instr(INS_tst, castInfo.typeMask, INS_FLAGS_DONT_CARE)) { emit->emitIns_R_I(INS_tst, cmpSize, sourceReg, castInfo.typeMask); } else { noway_assert(tmpReg != REG_NA); instGen_Set_Reg_To_Imm(cmpSize, tmpReg, castInfo.typeMask); emit->emitIns_R_R(INS_tst, cmpSize, sourceReg, tmpReg); } #elif defined(_TARGET_ARM64_) emit->emitIns_R_I(INS_tst, cmpSize, sourceReg, castInfo.typeMask); #endif // _TARGET_ARM* emitJumpKind jmpNotEqual = genJumpKindForOper(GT_NE, CK_SIGNED); genJumpToThrowHlpBlk(jmpNotEqual, SCK_OVERFLOW); } else { // For a narrowing signed cast // // We must check the value is in a signed range. // Compare with the MAX noway_assert((castInfo.typeMin != 0) && (castInfo.typeMax != 0)); #if defined(_TARGET_ARM_) if (emitter::emitIns_valid_imm_for_cmp(castInfo.typeMax, INS_FLAGS_DONT_CARE)) #elif defined(_TARGET_ARM64_) if (emitter::emitIns_valid_imm_for_cmp(castInfo.typeMax, cmpSize)) #endif // _TARGET_* { emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, castInfo.typeMax); } else { noway_assert(tmpReg != REG_NA); instGen_Set_Reg_To_Imm(cmpSize, tmpReg, castInfo.typeMax); emit->emitIns_R_R(INS_cmp, cmpSize, sourceReg, tmpReg); } emitJumpKind jmpGT = genJumpKindForOper(GT_GT, CK_SIGNED); genJumpToThrowHlpBlk(jmpGT, SCK_OVERFLOW); // Compare with the MIN #if defined(_TARGET_ARM_) if (emitter::emitIns_valid_imm_for_cmp(castInfo.typeMin, INS_FLAGS_DONT_CARE)) #elif defined(_TARGET_ARM64_) if (emitter::emitIns_valid_imm_for_cmp(castInfo.typeMin, cmpSize)) #endif // _TARGET_* { emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, castInfo.typeMin); } else { noway_assert(tmpReg != REG_NA); instGen_Set_Reg_To_Imm(cmpSize, tmpReg, castInfo.typeMin); emit->emitIns_R_R(INS_cmp, cmpSize, sourceReg, tmpReg); } emitJumpKind jmpLT = genJumpKindForOper(GT_LT, CK_SIGNED); genJumpToThrowHlpBlk(jmpLT, SCK_OVERFLOW); } ins = INS_mov; } else // Non-overflow checking cast. { if (genTypeSize(srcType) == genTypeSize(dstType)) { ins = INS_mov; } else { var_types extendType = TYP_UNKNOWN; if (genTypeSize(srcType) < genTypeSize(dstType)) { // If we need to treat a signed type as unsigned if ((treeNode->gtFlags & GTF_UNSIGNED) != 0) { extendType = genUnsignedType(srcType); } else extendType = srcType; #ifdef _TARGET_ARM_ movSize = emitTypeSize(extendType); #endif // _TARGET_ARM_ if (extendType == TYP_UINT) { #ifdef _TARGET_ARM64_ // If we are casting from a smaller type to // a larger type, then we need to make sure the // higher 4 bytes are zero to gaurentee the correct value. // Therefore using a mov with EA_4BYTE in place of EA_8BYTE // will zero the upper bits movSize = EA_4BYTE; #endif // _TARGET_ARM64_ movRequired = true; } } else // (genTypeSize(srcType) > genTypeSize(dstType)) { // If we need to treat a signed type as unsigned if ((treeNode->gtFlags & GTF_UNSIGNED) != 0) { extendType = genUnsignedType(dstType); } else extendType = dstType; #if defined(_TARGET_ARM_) movSize = emitTypeSize(extendType); #elif defined(_TARGET_ARM64_) if (extendType == TYP_INT) { movSize = EA_8BYTE; // a sxtw instruction requires EA_8BYTE } #endif // _TARGET_* } ins = ins_Move_Extend(extendType, true); } } // We should never be generating a load from memory instruction here! assert(!emit->emitInsIsLoad(ins)); if ((ins != INS_mov) || movRequired || (targetReg != sourceReg)) { emit->emitIns_R_R(ins, movSize, targetReg, sourceReg); } genProduceReg(treeNode); } //------------------------------------------------------------------------ // genFloatToFloatCast: Generate code for a cast between float and double // // Arguments: // treeNode - The GT_CAST node // // Return Value: // None. // // Assumptions: // Cast is a non-overflow conversion. // The treeNode must have an assigned register. // The cast is between float and double. // void CodeGen::genFloatToFloatCast(GenTreePtr treeNode) { // float <--> double conversions are always non-overflow ones assert(treeNode->OperGet() == GT_CAST); assert(!treeNode->gtOverflow()); regNumber targetReg = treeNode->gtRegNum; assert(genIsValidFloatReg(targetReg)); GenTreePtr op1 = treeNode->gtOp.gtOp1; assert(!op1->isContained()); // Cannot be contained assert(genIsValidFloatReg(op1->gtRegNum)); // Must be a valid float reg. var_types dstType = treeNode->CastToType(); var_types srcType = op1->TypeGet(); assert(varTypeIsFloating(srcType) && varTypeIsFloating(dstType)); genConsumeOperands(treeNode->AsOp()); // treeNode must be a reg assert(!treeNode->isContained()); #if defined(_TARGET_ARM_) if (srcType != dstType) { instruction insVcvt = (srcType == TYP_FLOAT) ? INS_vcvt_f2d // convert Float to Double : INS_vcvt_d2f; // convert Double to Float getEmitter()->emitIns_R_R(insVcvt, emitTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum); } else if (treeNode->gtRegNum != op1->gtRegNum) { getEmitter()->emitIns_R_R(INS_vmov, emitTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum); } #elif defined(_TARGET_ARM64_) if (srcType != dstType) { insOpts cvtOption = (srcType == TYP_FLOAT) ? INS_OPTS_S_TO_D // convert Single to Double : INS_OPTS_D_TO_S; // convert Double to Single getEmitter()->emitIns_R_R(INS_fcvt, emitActualTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum, cvtOption); } else if (treeNode->gtRegNum != op1->gtRegNum) { // If double to double cast or float to float cast. Emit a move instruction. getEmitter()->emitIns_R_R(INS_mov, emitActualTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum); } #endif // _TARGET_* genProduceReg(treeNode); } //------------------------------------------------------------------------ // genCreateAndStoreGCInfo: Create and record GC Info for the function. // void CodeGen::genCreateAndStoreGCInfo(unsigned codeSize, unsigned prologSize, unsigned epilogSize DEBUGARG(void* codePtr)) { IAllocator* allowZeroAlloc = new (compiler, CMK_GC) AllowZeroAllocator(compiler->getAllocatorGC()); GcInfoEncoder* gcInfoEncoder = new (compiler, CMK_GC) GcInfoEncoder(compiler->info.compCompHnd, compiler->info.compMethodInfo, allowZeroAlloc, NOMEM); assert(gcInfoEncoder != nullptr); // Follow the code pattern of the x86 gc info encoder (genCreateAndStoreGCInfoJIT32). gcInfo.gcInfoBlockHdrSave(gcInfoEncoder, codeSize, prologSize); // We keep the call count for the second call to gcMakeRegPtrTable() below. unsigned callCnt = 0; // First we figure out the encoder ID's for the stack slots and registers. gcInfo.gcMakeRegPtrTable(gcInfoEncoder, codeSize, prologSize, GCInfo::MAKE_REG_PTR_MODE_ASSIGN_SLOTS, &callCnt); // Now we've requested all the slots we'll need; "finalize" these (make more compact data structures for them). gcInfoEncoder->FinalizeSlotIds(); // Now we can actually use those slot ID's to declare live ranges. gcInfo.gcMakeRegPtrTable(gcInfoEncoder, codeSize, prologSize, GCInfo::MAKE_REG_PTR_MODE_DO_WORK, &callCnt); #ifdef _TARGET_ARM64_ if (compiler->opts.compDbgEnC) { // what we have to preserve is called the "frame header" (see comments in VM\eetwain.cpp) // which is: // -return address // -saved off RBP // -saved 'this' pointer and bool for synchronized methods // 4 slots for RBP + return address + RSI + RDI int preservedAreaSize = 4 * REGSIZE_BYTES; if (compiler->info.compFlags & CORINFO_FLG_SYNCH) { if (!(compiler->info.compFlags & CORINFO_FLG_STATIC)) preservedAreaSize += REGSIZE_BYTES; preservedAreaSize += 1; // bool for synchronized methods } // Used to signal both that the method is compiled for EnC, and also the size of the block at the top of the // frame gcInfoEncoder->SetSizeOfEditAndContinuePreservedArea(preservedAreaSize); } #endif // _TARGET_ARM64_ gcInfoEncoder->Build(); // GC Encoder automatically puts the GC info in the right spot using ICorJitInfo::allocGCInfo(size_t) // let's save the values anyway for debugging purposes compiler->compInfoBlkAddr = gcInfoEncoder->Emit(); compiler->compInfoBlkSize = 0; // not exposed by the GCEncoder interface } //------------------------------------------------------------------------------------------- // genJumpKindsForTree: Determine the number and kinds of conditional branches // necessary to implement the given GT_CMP node // // Arguments: // cmpTree - (input) The GenTree node that is used to set the Condition codes // - The GenTree Relop node that was used to set the Condition codes // jmpKind[2] - (output) One or two conditional branch instructions // jmpToTrueLabel[2] - (output) On Arm64 both branches will always branch to the true label // // Return Value: // Sets the proper values into the array elements of jmpKind[] and jmpToTrueLabel[] // // Assumptions: // At least one conditional branch instruction will be returned. // Typically only one conditional branch is needed // and the second jmpKind[] value is set to EJ_NONE // void CodeGen::genJumpKindsForTree(GenTreePtr cmpTree, emitJumpKind jmpKind[2], bool jmpToTrueLabel[2]) { // On ARM both branches will always branch to the true label jmpToTrueLabel[0] = true; jmpToTrueLabel[1] = true; // For integer comparisons just use genJumpKindForOper if (!varTypeIsFloating(cmpTree->gtOp.gtOp1)) { CompareKind compareKind = ((cmpTree->gtFlags & GTF_UNSIGNED) != 0) ? CK_UNSIGNED : CK_SIGNED; jmpKind[0] = genJumpKindForOper(cmpTree->gtOper, compareKind); jmpKind[1] = EJ_NONE; } else // We have a Floating Point Compare operation { assert(cmpTree->OperIsCompare()); // For details on this mapping, see the ARM Condition Code table // at section A8.3 in the ARMv7 architecture manual or // at section C1.2.3 in the ARMV8 architecture manual. // We must check the GTF_RELOP_NAN_UN to find out // if we need to branch when we have a NaN operand. // if ((cmpTree->gtFlags & GTF_RELOP_NAN_UN) != 0) { // Must branch if we have an NaN, unordered switch (cmpTree->gtOper) { case GT_EQ: jmpKind[0] = EJ_eq; // branch or set when equal (and no NaN's) jmpKind[1] = EJ_vs; // branch or set when we have a NaN break; case GT_NE: jmpKind[0] = EJ_ne; // branch or set when not equal (or have NaN's) jmpKind[1] = EJ_NONE; break; case GT_LT: jmpKind[0] = EJ_lt; // branch or set when less than (or have NaN's) jmpKind[1] = EJ_NONE; break; case GT_LE: jmpKind[0] = EJ_le; // branch or set when less than or equal (or have NaN's) jmpKind[1] = EJ_NONE; break; case GT_GT: jmpKind[0] = EJ_hi; // branch or set when greater than (or have NaN's) jmpKind[1] = EJ_NONE; break; case GT_GE: jmpKind[0] = EJ_hs; // branch or set when greater than or equal (or have NaN's) jmpKind[1] = EJ_NONE; break; default: unreached(); } } else // ((cmpTree->gtFlags & GTF_RELOP_NAN_UN) == 0) { // Do not branch if we have an NaN, unordered switch (cmpTree->gtOper) { case GT_EQ: jmpKind[0] = EJ_eq; // branch or set when equal (and no NaN's) jmpKind[1] = EJ_NONE; break; case GT_NE: jmpKind[0] = EJ_gt; // branch or set when greater than (and no NaN's) jmpKind[1] = EJ_lo; // branch or set when less than (and no NaN's) break; case GT_LT: jmpKind[0] = EJ_lo; // branch or set when less than (and no NaN's) jmpKind[1] = EJ_NONE; break; case GT_LE: jmpKind[0] = EJ_ls; // branch or set when less than or equal (and no NaN's) jmpKind[1] = EJ_NONE; break; case GT_GT: jmpKind[0] = EJ_gt; // branch or set when greater than (and no NaN's) jmpKind[1] = EJ_NONE; break; case GT_GE: jmpKind[0] = EJ_ge; // branch or set when greater than or equal (and no NaN's) jmpKind[1] = EJ_NONE; break; default: unreached(); } } } } //------------------------------------------------------------------------ // genCodeForJumpTrue: Generates code for jmpTrue statement. // // Arguments: // tree - The GT_JTRUE tree node. // // Return Value: // None // void CodeGen::genCodeForJumpTrue(GenTreePtr tree) { GenTree* cmp = tree->gtOp.gtOp1; assert(cmp->OperIsCompare()); assert(compiler->compCurBB->bbJumpKind == BBJ_COND); // Get the "kind" and type of the comparison. Note that whether it is an unsigned cmp // is governed by a flag NOT by the inherent type of the node emitJumpKind jumpKind[2]; bool branchToTrueLabel[2]; genJumpKindsForTree(cmp, jumpKind, branchToTrueLabel); assert(jumpKind[0] != EJ_NONE); // On ARM the branches will always branch to the true label assert(branchToTrueLabel[0]); inst_JMP(jumpKind[0], compiler->compCurBB->bbJumpDest); if (jumpKind[1] != EJ_NONE) { // the second conditional branch always has to be to the true label assert(branchToTrueLabel[1]); inst_JMP(jumpKind[1], compiler->compCurBB->bbJumpDest); } } //------------------------------------------------------------------------ // genCodeForJcc: Produce code for a GT_JCC node. // // Arguments: // tree - the node // void CodeGen::genCodeForJcc(GenTreeCC* tree) { assert(compiler->compCurBB->bbJumpKind == BBJ_COND); CompareKind compareKind = ((tree->gtFlags & GTF_UNSIGNED) != 0) ? CK_UNSIGNED : CK_SIGNED; emitJumpKind jumpKind = genJumpKindForOper(tree->gtCondition, compareKind); inst_JMP(jumpKind, compiler->compCurBB->bbJumpDest); } //------------------------------------------------------------------------ // genCodeForSetcc: Generates code for a GT_SETCC node. // // Arguments: // setcc - the GT_SETCC node // // Assumptions: // The condition represents an integer comparison. This code doesn't // have the necessary logic to deal with floating point comparisons, // in fact it doesn't even know if the comparison is integer or floating // point because SETCC nodes do not have any operands. // void CodeGen::genCodeForSetcc(GenTreeCC* setcc) { regNumber dstReg = setcc->gtRegNum; CompareKind compareKind = setcc->IsUnsigned() ? CK_UNSIGNED : CK_SIGNED; emitJumpKind jumpKind = genJumpKindForOper(setcc->gtCondition, compareKind); assert(genIsValidIntReg(dstReg)); // Make sure nobody is setting GTF_RELOP_NAN_UN on this node as it is ignored. assert((setcc->gtFlags & GTF_RELOP_NAN_UN) == 0); #ifdef _TARGET_ARM64_ inst_SET(jumpKind, dstReg); #else // Emit code like that: // ... // bgt True // movs rD, #0 // b Next // True: // movs rD, #1 // Next: // ... BasicBlock* labelTrue = genCreateTempLabel(); getEmitter()->emitIns_J(emitter::emitJumpKindToIns(jumpKind), labelTrue); getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(setcc->TypeGet()), dstReg, 0); BasicBlock* labelNext = genCreateTempLabel(); getEmitter()->emitIns_J(INS_b, labelNext); genDefineTempLabel(labelTrue); getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(setcc->TypeGet()), dstReg, 1); genDefineTempLabel(labelNext); #endif genProduceReg(setcc); } //------------------------------------------------------------------------ // genCodeForStoreBlk: Produce code for a GT_STORE_OBJ/GT_STORE_DYN_BLK/GT_STORE_BLK node. // // Arguments: // tree - the node // void CodeGen::genCodeForStoreBlk(GenTreeBlk* blkOp) { assert(blkOp->OperIs(GT_STORE_OBJ, GT_STORE_DYN_BLK, GT_STORE_BLK)); if (blkOp->OperIs(GT_STORE_OBJ) && blkOp->OperIsCopyBlkOp()) { assert(blkOp->AsObj()->gtGcPtrCount != 0); genCodeForCpObj(blkOp->AsObj()); return; } if (blkOp->gtBlkOpGcUnsafe) { getEmitter()->emitDisableGC(); } bool isCopyBlk = blkOp->OperIsCopyBlkOp(); switch (blkOp->gtBlkOpKind) { case GenTreeBlk::BlkOpKindHelper: if (isCopyBlk) { genCodeForCpBlk(blkOp); } else { genCodeForInitBlk(blkOp); } break; case GenTreeBlk::BlkOpKindUnroll: if (isCopyBlk) { genCodeForCpBlkUnroll(blkOp); } else { genCodeForInitBlkUnroll(blkOp); } break; default: unreached(); } if (blkOp->gtBlkOpGcUnsafe) { getEmitter()->emitEnableGC(); } } //------------------------------------------------------------------------ // genScaledAdd: A helper for genLeaInstruction. // void CodeGen::genScaledAdd(emitAttr attr, regNumber targetReg, regNumber baseReg, regNumber indexReg, int scale) { emitter* emit = getEmitter(); #if defined(_TARGET_ARM_) emit->emitIns_R_R_R_I(INS_add, attr, targetReg, baseReg, indexReg, scale, INS_FLAGS_DONT_CARE, INS_OPTS_LSL); #elif defined(_TARGET_ARM64_) emit->emitIns_R_R_R_I(INS_add, attr, targetReg, baseReg, indexReg, scale, INS_OPTS_LSL); #endif } //------------------------------------------------------------------------ // genLeaInstruction: Produce code for a GT_LEA node. // // Arguments: // lea - the node // void CodeGen::genLeaInstruction(GenTreeAddrMode* lea) { genConsumeOperands(lea); emitter* emit = getEmitter(); emitAttr size = emitTypeSize(lea); int offset = lea->Offset(); // In ARM we can only load addresses of the form: // // [Base + index*scale] // [Base + Offset] // [Literal] (PC-Relative) // // So for the case of a LEA node of the form [Base + Index*Scale + Offset] we will generate: // destReg = baseReg + indexReg * scale; // destReg = destReg + offset; // // TODO-ARM64-CQ: The purpose of the GT_LEA node is to directly reflect a single target architecture // addressing mode instruction. Currently we're 'cheating' by producing one or more // instructions to generate the addressing mode so we need to modify lowering to // produce LEAs that are a 1:1 relationship to the ARM64 architecture. if (lea->Base() && lea->Index()) { GenTree* memBase = lea->Base(); GenTree* index = lea->Index(); DWORD lsl; assert(isPow2(lea->gtScale)); BitScanForward(&lsl, lea->gtScale); assert(lsl <= 4); if (offset != 0) { regNumber tmpReg = lea->GetSingleTempReg(); if (emitter::emitIns_valid_imm_for_add(offset)) { if (lsl > 0) { // Generate code to set tmpReg = base + index*scale genScaledAdd(size, tmpReg, memBase->gtRegNum, index->gtRegNum, lsl); } else // no scale { // Generate code to set tmpReg = base + index emit->emitIns_R_R_R(INS_add, size, tmpReg, memBase->gtRegNum, index->gtRegNum); } // Then compute target reg from [tmpReg + offset] emit->emitIns_R_R_I(INS_add, size, lea->gtRegNum, tmpReg, offset); } else // large offset { // First load/store tmpReg with the large offset constant instGen_Set_Reg_To_Imm(EA_PTRSIZE, tmpReg, offset); // Then add the base register // rd = rd + base emit->emitIns_R_R_R(INS_add, size, tmpReg, tmpReg, memBase->gtRegNum); noway_assert(tmpReg != index->gtRegNum); // Then compute target reg from [tmpReg + index*scale] genScaledAdd(size, lea->gtRegNum, tmpReg, index->gtRegNum, lsl); } } else { if (lsl > 0) { // Then compute target reg from [base + index*scale] genScaledAdd(size, lea->gtRegNum, memBase->gtRegNum, index->gtRegNum, lsl); } else { // Then compute target reg from [base + index] emit->emitIns_R_R_R(INS_add, size, lea->gtRegNum, memBase->gtRegNum, index->gtRegNum); } } } else if (lea->Base()) { GenTree* memBase = lea->Base(); if (emitter::emitIns_valid_imm_for_add(offset)) { if (offset != 0) { // Then compute target reg from [memBase + offset] emit->emitIns_R_R_I(INS_add, size, lea->gtRegNum, memBase->gtRegNum, offset); } else // offset is zero { if (lea->gtRegNum != memBase->gtRegNum) { emit->emitIns_R_R(INS_mov, size, lea->gtRegNum, memBase->gtRegNum); } } } else { // We require a tmpReg to hold the offset regNumber tmpReg = lea->GetSingleTempReg(); // First load tmpReg with the large offset constant instGen_Set_Reg_To_Imm(EA_PTRSIZE, tmpReg, offset); // Then compute target reg from [memBase + tmpReg] emit->emitIns_R_R_R(INS_add, size, lea->gtRegNum, memBase->gtRegNum, tmpReg); } } else if (lea->Index()) { // If we encounter a GT_LEA node without a base it means it came out // when attempting to optimize an arbitrary arithmetic expression during lower. // This is currently disabled in ARM64 since we need to adjust lower to account // for the simpler instructions ARM64 supports. // TODO-ARM64-CQ: Fix this and let LEA optimize arithmetic trees too. assert(!"We shouldn't see a baseless address computation during CodeGen for ARM64"); } genProduceReg(lea); } //------------------------------------------------------------------------ // isStructReturn: Returns whether the 'treeNode' is returning a struct. // // Arguments: // treeNode - The tree node to evaluate whether is a struct return. // // Return Value: // Returns true if the 'treeNode" is a GT_RETURN node of type struct. // Otherwise returns false. // bool CodeGen::isStructReturn(GenTreePtr treeNode) { // This method could be called for 'treeNode' of GT_RET_FILT or GT_RETURN. // For the GT_RET_FILT, the return is always // a bool or a void, for the end of a finally block. noway_assert(treeNode->OperGet() == GT_RETURN || treeNode->OperGet() == GT_RETFILT); return varTypeIsStruct(treeNode); } //------------------------------------------------------------------------ // genStructReturn: Generates code for returning a struct. // // Arguments: // treeNode - The GT_RETURN tree node. // // Return Value: // None // // Assumption: // op1 of GT_RETURN node is either GT_LCL_VAR or multi-reg GT_CALL void CodeGen::genStructReturn(GenTreePtr treeNode) { assert(treeNode->OperGet() == GT_RETURN); assert(isStructReturn(treeNode)); GenTreePtr op1 = treeNode->gtGetOp1(); if (op1->OperGet() == GT_LCL_VAR) { GenTreeLclVarCommon* lclVar = op1->AsLclVarCommon(); LclVarDsc* varDsc = &(compiler->lvaTable[lclVar->gtLclNum]); var_types lclType = genActualType(varDsc->TypeGet()); // Currently only multireg TYP_STRUCT types such as HFA's(ARM32, ARM64) and 16-byte structs(ARM64) are supported // In the future we could have FEATURE_SIMD types like TYP_SIMD16 assert(lclType == TYP_STRUCT); assert(varDsc->lvIsMultiRegRet); ReturnTypeDesc retTypeDesc; unsigned regCount; retTypeDesc.InitializeStructReturnType(compiler, varDsc->lvVerTypeInfo.GetClassHandle()); regCount = retTypeDesc.GetReturnRegCount(); assert(regCount >= 2); assert(op1->isContained()); // Copy var on stack into ABI return registers // TODO: It could be optimized by reducing two float loading to one double int offset = 0; for (unsigned i = 0; i < regCount; ++i) { var_types type = retTypeDesc.GetReturnRegType(i); regNumber reg = retTypeDesc.GetABIReturnReg(i); getEmitter()->emitIns_R_S(ins_Load(type), emitTypeSize(type), reg, lclVar->gtLclNum, offset); offset += genTypeSize(type); } } else // op1 must be multi-reg GT_CALL { assert(op1->IsMultiRegCall() || op1->IsCopyOrReloadOfMultiRegCall()); genConsumeRegs(op1); GenTree* actualOp1 = op1->gtSkipReloadOrCopy(); GenTreeCall* call = actualOp1->AsCall(); ReturnTypeDesc* pRetTypeDesc; unsigned regCount; unsigned matchingCount = 0; pRetTypeDesc = call->GetReturnTypeDesc(); regCount = pRetTypeDesc->GetReturnRegCount(); var_types regType[MAX_RET_REG_COUNT]; regNumber returnReg[MAX_RET_REG_COUNT]; regNumber allocatedReg[MAX_RET_REG_COUNT]; regMaskTP srcRegsMask = 0; regMaskTP dstRegsMask = 0; bool needToShuffleRegs = false; // Set to true if we have to move any registers for (unsigned i = 0; i < regCount; ++i) { regType[i] = pRetTypeDesc->GetReturnRegType(i); returnReg[i] = pRetTypeDesc->GetABIReturnReg(i); regNumber reloadReg = REG_NA; if (op1->IsCopyOrReload()) { // GT_COPY/GT_RELOAD will have valid reg for those positions // that need to be copied or reloaded. reloadReg = op1->AsCopyOrReload()->GetRegNumByIdx(i); } if (reloadReg != REG_NA) { allocatedReg[i] = reloadReg; } else { allocatedReg[i] = call->GetRegNumByIdx(i); } if (returnReg[i] == allocatedReg[i]) { matchingCount++; } else // We need to move this value { // We want to move the value from allocatedReg[i] into returnReg[i] // so record these two registers in the src and dst masks // srcRegsMask |= genRegMask(allocatedReg[i]); dstRegsMask |= genRegMask(returnReg[i]); needToShuffleRegs = true; } } if (needToShuffleRegs) { assert(matchingCount < regCount); unsigned remainingRegCount = regCount - matchingCount; regMaskTP extraRegMask = treeNode->gtRsvdRegs; while (remainingRegCount > 0) { // set 'available' to the 'dst' registers that are not currently holding 'src' registers // regMaskTP availableMask = dstRegsMask & ~srcRegsMask; regMaskTP dstMask; regNumber srcReg; regNumber dstReg; var_types curType = TYP_UNKNOWN; regNumber freeUpReg = REG_NA; if (availableMask == 0) { // Circular register dependencies // So just free up the lowest register in dstRegsMask by moving it to the 'extra' register assert(dstRegsMask == srcRegsMask); // this has to be true for us to reach here assert(extraRegMask != 0); // we require an 'extra' register assert((extraRegMask & ~dstRegsMask) != 0); // it can't be part of dstRegsMask availableMask = extraRegMask & ~dstRegsMask; regMaskTP srcMask = genFindLowestBit(srcRegsMask); freeUpReg = genRegNumFromMask(srcMask); } dstMask = genFindLowestBit(availableMask); dstReg = genRegNumFromMask(dstMask); srcReg = REG_NA; if (freeUpReg != REG_NA) { // We will free up the srcReg by moving it to dstReg which is an extra register // srcReg = freeUpReg; // Find the 'srcReg' and set 'curType', change allocatedReg[] to dstReg // and add the new register mask bit to srcRegsMask // for (unsigned i = 0; i < regCount; ++i) { if (allocatedReg[i] == srcReg) { curType = regType[i]; allocatedReg[i] = dstReg; srcRegsMask |= genRegMask(dstReg); } } } else // The normal case { // Find the 'srcReg' and set 'curType' // for (unsigned i = 0; i < regCount; ++i) { if (returnReg[i] == dstReg) { srcReg = allocatedReg[i]; curType = regType[i]; } } // After we perform this move we will have one less registers to setup remainingRegCount--; } assert(curType != TYP_UNKNOWN); inst_RV_RV(ins_Copy(curType), dstReg, srcReg, curType); // Clear the appropriate bits in srcRegsMask and dstRegsMask srcRegsMask &= ~genRegMask(srcReg); dstRegsMask &= ~genRegMask(dstReg); } // while (remainingRegCount > 0) } // (needToShuffleRegs) } // op1 must be multi-reg GT_CALL } #endif // _TARGET_ARMARCH_ #endif // !LEGACY_BACKEND
wateret/coreclr
src/jit/codegenarmarch.cpp
C++
mit
135,282
<nav class="sr-only"> <div class="modal-header"> <div class="row"> <h1 class="h1 col-xs-10 col-sm-10 col-md-11 col-lg-11"><a href="/">WSJ Sections</a></h1> <a href="" class=" col-xs-1 col-sm-1 col-md-1 col-lg-1" ng-click="NC.cancel()">close </a> </div> <div class="row"> <ul class="nav nav-pills nav-sections" > <!-- <li ng-repeat="category in categories " ><a ng-click="NC.getNavSubCategories(category.slug)" href=""> {{NC.category.name}}</a></li>--> </ul> </div> <div class="row"> <hr style="border-top: 1px solid #444;" /> <!-- <h2 class="text-center modal-title col-md-11">{{ subCategories.section }}</h2>--> </div> </div> <div class="modal-body nav-section-stories"> <!-- <div ng-repeat="subCategory in subCategories" class="row sub-section" >--> <!-- <article class="col-xs-3 col-sm-2 col-md-2" >--> <!-- <a href="category/{{NC.subCategory.slug}}" class="story">--> <!-- <h3> {{subCategory.name}}</h3>--> <!-- </a>--> <!-- </article>--> <!-- <div class="col-xs-9 col-sm-10 col-md-10">--> <!-- <section class="row">--> <!-- <article ng-repeat="post in subCategory.posts" class="col-xs-12 col-sm-6 col-md-4" >--> <!----> <!-- <!-- <img ng-if="getSource(NC.post.galleries)" class="img-responsive" src="{{NC.getSource(post.galleries)}}" alt="Powell Street"/>-->--> <!----> <!-- <a href="/{{post.slug}}" class="story">--> <!-- <!-- <h2>{{post.name | limitTo:letterLimitHeadline }}</h2>-->--> <!-- <p>--> <!-- <!-- {{post.content | limitTo:letterLimit }}-->--> <!-- </p>--> <!-- </a>--> <!-- </article>--> <!-- </section>--> <!-- </div>--> <!----> <!-- </div> <!-- End/ .row -->--> </div> <div class="modal-footer"> <article style="background-color: #a6e1ec; height: 5rem;" class="col-md-4"> Advertisement </article> Copyright WSJ </div> </nav>
daniel-rodas/wsj
fuel/app/views/angular/navigation.php
PHP
mit
2,375
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AnalyzeThis { internal static class RegexExtensions { public static bool TryGetMatch(this Regex regex, string input, out Match match) { if (input == null) { match = null; return false; } match = regex.Match(input); return match.Success; } } }
tastott/AnalyzeThis
src/AnalyzeThis/RegexExtensions.cs
C#
mit
541
M.profile("generators"); function* forOfBlockScope() { let a = [1, 2, 3, 4, 5, 6, 7, 8]; let b = [10, 11, 12, 13, 14, 15, 16]; const funs = []; for (const i of a) { let j = 0; funs.push(function* iter() { yield `fo1: ${i} ${j++}`; }); } for (var i of a) { var j = 0; funs.push(function* iter() { yield `fo2: ${i} ${j++}`; }); } for (const i of a) { for (let j of b) { funs.push(function* iter() { yield `fo3: ${i} ${j++}`; }); } } for (const i of a) { for (let j of b) { yield `fo4: ${j}`; funs.push(function* iter() { yield `fo5: ${i} ${j++}`; }); } } for (const i of a) { yield `fo6: ${i}`; for (let j of b) { funs.push(function* iter() { yield `fo7: ${i} ${j++}`; }); } } for (const i of a) { yield `fo8 ${i}`; for (let j of b) { yield `fo9: ${i}`; funs.push(function* iter() { yield `fo10: ${i} ${j++}`; }); } } for (const i of funs) yield* i(); funs.length = 0; for (const i of a) { funs.push(function* iter() { yield `fo11: ${i}`; }); } for (const i of a) { yield `fo12 ${i}`; funs.push(function* iter() { yield `fo13 ${i}`; }); } let k = 0; for (const i of a) { yield `fo14 ${i} ${k} {m}`; let m = k; k++; if (k === 3) continue; if (k === 5) break; funs.push(function* iter() { yield `fo15 ${i} ${k} {m}`; }); } k = 0; up1: for (const i of a) { let m = k; k++; for (const j of b) { let n = m; m++; if (k === 3) continue up1; if (k === 5) break up1; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo18: ${i} ${j} ${k} ${m} ${n}`; }); } } k = 0; up2: for (const i of a) { let m = 0; k++; yield `fo16: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; if (k === 3) continue up2; if (k === 5) break up2; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo18: ${i} ${j} ${k} ${m} ${n}`; }); } } k = 0; up3: for (const i of a) { let m = 0; k++; for (const j of b) { let n = m; m++; yield `fo19 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) { continue up3; } if (k === 5) break up3; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo20: ${i} ${j} ${k} ${m} ${n}`; }); } } bl1: { let k = 0; yield `fo21: ${i} ${k}`; up4: for (const i of a) { let m = 0; k++; yield `fo22: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo23 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up4; if (k === 5) break bl1; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo24: ${i} ${j} ${k} ${m} ${n}`; }); } } } bl2: { let k = 0; yield `fo25`; up5: for (const i of a) { let m = 0; k++; yield `fo26: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo27 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up5; if (k === 5) break bl2; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo28: ${i} ${j} ${k} ${m} ${n}`; }); } } } bl3: { let k = 0; up6: for (const i of a) { let m = 0; k++; yield `fo29: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo30 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up6; if (k === 5) { for (const i of funs) yield* i(); return `r: ${i} ${j} ${k} ${m} ${n}`; } if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo31: ${i} ${j} ${k} ${m} ${n}`; }); } } } }
awto/effectfuljs
packages/core/test/samples/for-of-stmt/closures-in.js
JavaScript
mit
4,231
<?php /* * This file is a part of the NeimheadhBootstrapBundle project. * * (c) 2017 by Neimheadh * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Neimheadh\Bundle\CodeManipulationBundle\Model\File; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Exception\IOException; /** * The files models interface. * * @author Neimheadh <[email protected]> */ interface FileInterface { /** * Get path. * * @return string */ public function getPath(); /** * Set path. * * @param string $path * The file path. * @return \Neimheadh\Bundle\CodeManipulationBundle\Model\File\FileInterface */ public function setPath(string $path); /** * Get access mode. * * @return string */ public function getAccessMode(); /** * Set access mode. * * @param string $accessMode * The access mode. * @return \Neimheadh\Bundle\CodeManipulationBundle\Model\File\FileInterface */ public function setAccessMode(string $accessMode); /** * Check file access. * * @param bool $read * Force read checking. * @param bool $write * Force write checking. * @throws FileNotFoundException The file doesn't exist. * @throws IOException The file cannot be accessed in read mode (code = 1). * @throws IOException The file cannot be accessed in read mode (code = 2). * @throws IOException Unknown access mode (code = 3). */ public function check(bool $read = false, bool $write = false); /** * Is the file existing? * * @return bool */ public function isExisting(); /** * Is the file readable? * * @return bool */ public function isReadable(); /** * Is the file writable? * * @return bool */ public function isWritable(); /** * Process file line by line. * * @param callable $callback * The callback. * */ public function processLines($callback); /** * Append content in file. * * @param string $content * Amended content. * @param int|null $position * Amend position */ public function amend(string $content, int $position = null); }
neimheadh/code-manipulation-bundle
Model/File/FileInterface.php
PHP
mit
2,489
<!DOCTYPE html> <html> <head> <link href="css/awsdocs.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/awsdocs.min.js"></script> <meta charset="utf-8"> </head> <body> <div id="content" style="padding: 10px 30px;"> <h1 class="topictitle" id="aws-resource-route53-hostedzone">AWS::Route53::HostedZone</h1><p>The <code class="code">AWS::Route53::HostedZone</code> resource creates a hosted zone, which can contain a collection of record sets for a domain. You cannot create a hosted zone for a top-level domain (TLD). For more information, see <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateHostedZone.html">POST CreateHostedZone</a> or <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API-create-hosted-zone-private.html">POST CreateHostedZone (Private)</a> in the <em>Amazon Route&#xA0;53 API Reference</em>. </p><h2 id="aws-resource-route53-hostedzone-syntax">Syntax</h2><p>To declare this entity in your AWS CloudFormation template, use the following syntax:</p><div id="JSON" name="JSON" class="section langfilter"> <h3 id="aws-resource-route53-hostedzone-syntax.json">JSON</h3> <pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight">{ &quot;Type&quot; : &quot;AWS::Route53::HostedZone&quot;, &quot;Properties&quot; : { &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzoneconfig">HostedZoneConfig</a>&quot; : <a href="aws-properties-route53-hostedzone-hostedzoneconfig.html">HostedZoneConfig</a>, &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzonetags">HostedZoneTags</a>&quot; : [ <a href="aws-properties-route53-hostedzone-hostedzonetags.html">HostedZoneTags</a>, ... ], &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-name">Name</a>&quot; : <em class="replaceable"><code>String</code></em>, &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-queryloggingconfig">QueryLoggingConfig</a>&quot; : <a href="aws-properties-route53-hostedzone-queryloggingconfig.html">QueryLoggingConfig</a>, &quot;<a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-vpcs">VPCs</a>&quot; : [ <a href="aws-resource-route53-hostedzone-hostedzonevpcs.html">HostedZoneVPCs</a>, ... ] } }</code></pre> </div><div id="YAML" name="YAML" class="section langfilter"> <h3 id="aws-resource-route53-hostedzone-syntax.yaml">YAML</h3> <pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight">Type: &quot;AWS::Route53::HostedZone&quot; Properties: <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzoneconfig">HostedZoneConfig</a>: <a href="aws-properties-route53-hostedzone-hostedzoneconfig.html">HostedZoneConfig</a> <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzonetags">HostedZoneTags</a>: - <a href="aws-properties-route53-hostedzone-hostedzonetags.html">HostedZoneTags</a> <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-name">Name</a>: <em class="replaceable"><code>String</code></em> <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-queryloggingconfig">QueryLoggingConfig</a>: <a href="aws-properties-route53-hostedzone-queryloggingconfig.html">QueryLoggingConfig</a> <a href="aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-vpcs">VPCs</a>: - <a href="aws-resource-route53-hostedzone-hostedzonevpcs.html">HostedZoneVPCs</a> </code></pre> </div><h2 id="w2ab1c21c10d201c18b7">Properties</h2><div class="variablelist"> <dl> <dt><a id="cfn-route53-hostedzone-hostedzoneconfig"></a><span class="term"><code class="code">HostedZoneConfig</code></span></dt> <dd> <p>A complex type that contains an optional comment about your hosted zone.</p> <p><em>Required</em>: No </p> <p><em>Type</em>: <a href="aws-properties-route53-hostedzone-hostedzoneconfig.html">Route&#xA0;53 HostedZoneConfig Property</a></p> <p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt">No interruption</a></p> </dd> <dt><a id="cfn-route53-hostedzone-hostedzonetags"></a><span class="term"><code class="code">HostedZoneTags</code></span></dt> <dd> <p>An arbitrary set of tags (key&#x2013;value pairs) for this hosted zone.</p> <p><em>Required</em>: No </p> <p><em>Type</em>: List of <a href="aws-properties-route53-hostedzone-hostedzonetags.html">Amazon Route&#xA0;53 HostedZoneTags</a></p> <p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt">No interruption</a></p> </dd> <dt><a id="cfn-route53-hostedzone-name"></a><span class="term"><code class="code">Name</code></span></dt> <dd> <p>The name of the domain. For resource record types that include a domain name, specify a fully qualified domain name. </p> <p><em>Required</em>: Yes </p> <p><em>Type</em>: String </p> <p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement">Replacement</a></p> </dd> <dt><a id="cfn-route53-hostedzone-queryloggingconfig"></a><span class="term"><code class="code">QueryLoggingConfig</code></span></dt> <dd> <p>The configuration for DNS query logging.</p> <p><em>Required</em>: No </p> <p><em>Type</em>: <a href="aws-properties-route53-hostedzone-queryloggingconfig.html">Route&#xA0;53 QueryLoggingConfig</a></p> <p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt">No interruption</a></p> </dd> <dt><a id="cfn-route53-hostedzone-vpcs"></a><span class="term"><code class="code">VPCs</code></span></dt> <dd> <p>One or more VPCs that you want to associate with this hosted zone. When you specify this property, AWS CloudFormation creates a private hosted zone. </p> <p><em>Required</em>: No </p> <p><em>Type</em>: List of <a href="aws-resource-route53-hostedzone-hostedzonevpcs.html">Route&#xA0;53 HostedZoneVPCs</a></p> <p>If this property was specified previously and you&apos;re modifying values, updates require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt">no interruption</a>. If this property wasn&apos;t specified and you add values, updates require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement">replacement</a>. Also, if this property was specified and you remove all values, updates require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement">replacement</a>. </p> </dd> </dl> </div><h2 id="w2ab1c21c10d201c18b9">Return Values</h2><h3 id="w2ab1c21c10d201c18b9b2">Ref</h3><p>When the logical ID of this resource is provided to the <code class="code">Ref</code> intrinsic function, <code class="code">Ref</code> returns the hosted zone ID, such as <code class="code">Z23ABC4XYZL05B</code>. </p><p>For more information about using the <code class="code">Ref</code> function, see <a href="intrinsic-function-reference-ref.html">Ref</a>. </p><h3 id="w2ab1c21c10d201c18b9b4">Fn::GetAtt</h3><p><code class="code">Fn::GetAtt</code> returns a value for a specified attribute of this type. The following are the available attributes and sample return values. </p><div class="variablelist"> <dl> <dt><span class="term"><code class="literal">NameServers</code></span></dt> <dd> <p>Returns the set of name servers for the specific hosted zone. For example: <code class="code">ns1.example.com</code>. </p> <p>This attribute is not supported for private hosted zones.</p> </dd> </dl> </div><p>For more information about using <code class="code">Fn::GetAtt</code>, see <a href="intrinsic-function-reference-getatt.html">Fn::GetAtt</a>. </p><h2 id="w2ab1c21c10d201c18c11">Example</h2><p>The following template snippet creates a private hosted zone for the <code class="code">example.com</code> domain. </p><div id="JSON" name="JSON" class="section langfilter"> <h3 id="aws-resource-route53-hostedzone-example.json">JSON</h3> <pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight ">&quot;DNS&quot;: { &quot;Type&quot;: &quot;AWS::Route53::HostedZone&quot;, &quot;Properties&quot;: { &quot;HostedZoneConfig&quot;: { &quot;Comment&quot;: &quot;My hosted zone for example.com&quot; }, &quot;Name&quot;: &quot;example.com&quot;, &quot;VPCs&quot;: [{ &quot;VPCId&quot;: &quot;vpc-abcd1234&quot;, &quot;VPCRegion&quot;: &quot;ap-northeast-1&quot; }, { &quot;VPCId&quot;: &quot;vpc-efgh5678&quot;, &quot;VPCRegion&quot;: &quot;us-west-2&quot; }], &quot;HostedZoneTags&quot; : [{ &quot;Key&quot;: &quot;SampleKey1&quot;, &quot;Value&quot;: &quot;SampleValue1&quot; }, { &quot;Key&quot;: &quot;SampleKey2&quot;, &quot;Value&quot;: &quot;SampleValue2&quot; }] } }</code></pre> </div><div id="YAML" name="YAML" class="section langfilter"> <h3 id="aws-resource-route53-hostedzone-example.yaml">YAML</h3> <pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight ">DNS: Type: &quot;AWS::Route53::HostedZone&quot; Properties: HostedZoneConfig: Comment: &quot;My hosted zone for example.com&quot; Name: &quot;example.com&quot; VPCs: - VPCId: &quot;vpc-abcd1234&quot; VPCRegion: &quot;ap-northeast-1&quot; - VPCId: &quot;vpc-efgh5678&quot; VPCRegion: &quot;us-west-2&quot; HostedZoneTags: - Key: &quot;SampleKey1&quot; Value: &quot;SampleValue1&quot; - Key: &quot;SampleKey2&quot; Value: &quot;SampleValue2&quot;</code></pre> </div></div> </body> </html>
pdhodgkinson/AWSCloudFormationTemplateReference-dash-docset
AWS_CloudFormation_Template_Reference.docset/Contents/Resources/Documents/aws-resource-route53-hostedzone.html
HTML
mit
14,906
package fPPPrograms; import java.util.Scanner; public class LeapYear { public static void main(String[] args) { System.out.println("Enter a year to determine whether it is a leap year or not?"); Scanner yourInput = new Scanner(System.in); int year = yourInput.nextInt(); //String y = year%400 == 0? (year%4 == 0 ) && (year%100 !=0) ? "Yes" : "Not" : "Not" ; String y = ((year%4 == 0) && (year%100 != 0) || (year%400 == 0)) ? "Yes" : "Not"; System.out.println("The Year You Entered is " + y + " a Leap Year"); } }
haftommit/FPP.github.io
FPPSecondProject/src/week1lesson2/Q2.java
Java
mit
545
2020-02-24: Development Meeting =============================== Kacper, Craig, Mike H, Tim, Elias, Mike L, Tommy Agenda ------ * Updates * AHM - [name=Kacper] * 03/04/2020 10am - 5pm CDT * https://illinois.zoom.us/j/583802454 * for people @ NCSA: we gather in NCSA-2000 * optionally 04/04/2020 10am - 1pm (tbd) * THE NEWS * v0.10 / v1.0 planning? - [name=Craig] * v1.0: Tommy / v0.10: Kacper * Angular migration (waiting on the rest of us) * Versioning (backend close, needs testing; UI partially defined) * r2d composability (needs testing) * Sharing * Current activities: * Prov model * What we could get from just reprozip * Expansion out from that (~2 months) that could be part of a reproducible run * On deck * Git integration * Dataverse publishing * Image preservation * Reproducible run * MATLAB support (doable now) * Stata support * Ability to configure resources * Associate tale with manuscript * Link directly to tales from publication Updates ------- * Kacper * Related identifiers * Tale model update + import [girder_wholetale#391](https://github.com/whole-tale/girder_wholetale/pull/391) * Changes to Tale's metadata view [dashboard#595](https://github.com/whole-tale/dashboard/pull/595) * Use related identifiers to populate Zenodo's metadata [gwvolman#102](https://github.com/whole-tale/gwvolman/pull/102) * Refactored AinWT import jobs - [girder_wholetale#389](https://github.com/whole-tale/girder_wholetale/pull/389) * Imported (AinWT) Tales are singletons now [girder_wholetale#396](https://github.com/whole-tale/girder_wholetale/pull/396) * Minor fix to our bag export - [girder_wholetale#395](https://github.com/whole-tale/girder_wholetale/pull/395) * Hopefully tag and deploy rc2 today (demo tomorrow) * Craig * PresQT integration testing n * PR review and testing * Annual report * Mike H * Continue to work on versioning * Tim * Working on EarthCube proposal for next 2.5 weeks. * Implemented the example "script" (RMarkdown) for WT-C2Metadata project as a repo that can be run in place with Docker: https://github.com/tmcphillips/all-harvest-rippo * To run from outside a container: * git clone * git status * make clean * git status * make run * git status * To run with rstudio running in the container: * make rstudio * connect to http://localhost:8787 * Will be dropping in the ReproZip stuff to see what we can see. * Will we see downloading of input data sets? * Tommy * Few small fixes to file uploading UI * Few small fixes for error messages on various tale creation methods * Review * Prioritizing PR reviews for RC2 * Did a some work on a WT screencast/intro video * I estimate 2 hours fo work left before it's a complete rough draft * Elias * Began testing on staging * Web UI: Server notification counter shows up on top of logs * Mike L * Reviewed open dashboard PRs from Tommy and Kacper * Made a couple of other minor PRs * [Update label on Select Data submit button](https://github.com/whole-tale/dashboard/pull/598) * [Save filter state on Browse view across refresh / navigation](https://github.com/whole-tale/dashboard/pull/599) * [Tale title truncation on Run view](https://github.com/whole-tale/dashboard/pull/600)
whole-tale/wt-design-docs
development/meetings/2020-02-24.md
Markdown
mit
3,620
<?php namespace BigD\UbicacionBundle\Form\EventListener; use Doctrine\ORM\EntityRepository; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\PropertyAccess\PropertyAccess; class AddCityFieldSubscriber implements EventSubscriberInterface { private $factory; public function __construct(FormFactoryInterface $factory) { $this->factory = $factory; } public static function getSubscribedEvents() { return array( FormEvents::PRE_SET_DATA => 'preSetData', FormEvents::PRE_BIND => 'preBind' ); } private function addLocalidadForm($form, $city, $country) { $form->add($this->factory->createNamed('city', 'entity', $city, array( 'class' => 'LocationBundle:City', 'auto_initialize' => false, 'empty_value' => 'Select', 'attr' => array( 'class' => 'city_selector', ), 'query_builder' => function (EntityRepository $repository) use ($country) { $qb = $repository->createQueryBuilder('city') ->innerJoin('city.country', 'country'); if ($country instanceof Country) { $qb->where('city.country = :country') ->setParameter('country', $country->getId()); } elseif (is_numeric($country)) { $qb->where('country.id = :country') ->setParameter('country', $country); } else { $qb->where('country.name = :country') ->setParameter('country', null); } return $qb; } ))); } public function preSetData(FormEvent $event) { $data = $event->getData(); $form = $event->getForm(); if (null === $data) { $this->addCityForm($form, null, null); return; } $accessor = PropertyAccess::getPropertyAccessor(); $city = $accessor->getValue($data, 'city'); //$province = ($city) ? $city->getProvince() : null ; //$this->addCityForm($form, $city, $province); //$country = ($data->getCity()) ? $data->getCity()->getCountry() : null ; $country = ($city) ? $city->getCountry() : null; $this->addCityForm($form, $city, $country); } public function preBind(FormEvent $event) { $data = $event->getData(); $form = $event->getForm(); if (null === $data) { return; } // $city = array_key_exists('city', $data) ? $data['city'] : null; // $this->addCityForm($form, $city, $province); $country = array_key_exists('country', $data) ? $data['country'] : null; $city = array_key_exists('city', $data) ? $data['city'] : null; $this->addCityForm($form, $city, $country); } }
matudelatower/BigD
src/BigD/UbicacionBundle/Form/EventListener/AddCityFieldSubscriber.php
PHP
mit
3,120
/* * Webpack development server configuration * * This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if * the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload. */ 'use strict'; import webpack from 'webpack'; import path from 'path'; import autoprefixer from 'autoprefixer'; const API_URL = process.env['__API_URL__'] || 'http://localhost:3001/'; //eslint-disable-line export default { output: { path: path.join(__dirname, '.tmp'), filename: 'bundle.js', publicPath: '/static/' }, devtool: 'eval-source-map', entry: [ 'whatwg-fetch', 'webpack-dev-server/client?http://0.0.0.0:3000', 'webpack/hot/only-dev-server', 'react-hot-loader/patch', './src/index.js' ], module: { preLoaders: [{ test: /\.(js|jsx)$/, exclude: [/node_modules/, /vendor/], loader: 'eslint-loader' }], loaders: [{ test: /\.(js|jsx)$/, include: path.join(__dirname, 'src'), loader: 'babel-loader' }, { test: /\.scss/, loader: 'style-loader!css-loader!postcss-loader!sass-loader' }, { test: /\.json/, loader: 'json-loader' }, { test: /\.(png|jpg|ttf|svg|eot|woff|woff2)/, loader: 'url-loader?limit=8192' }] }, postcss: [ autoprefixer({ browsers: 'last 2 versions' }) ], plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin({ __DEV__: true, __DEVTOOLS__: false, __API_URL__: `\'${API_URL}\'` }) ] };
RiddleMan/giant-privacy-spy
client/webpack.config.js
JavaScript
mit
1,796
// This code will add an event listener to each anchor of the topbar after being dynamically replaced by "interchange" $("body").on("click", function(event){ // If the active element is one of the topbar's links continues if($(event.target).hasClass("topbarLink")) { // The parent li element of the current active link is stored var activeLink = $(event.target).parent(); // Takes each link and checks if its parent li element is active, removing "active" class if so. $("#topNavContent li:not(.divider)").each(function(){ // If the li element has nested li's with links they are checked also. if($(this).hasClass("has-dropdown")){ var dropdownList = $(this).children(".dropdown").children().not(".divider"); dropdownList.each(function(){ if($(this).hasClass("active")){ $(this).removeClass("active"); } }); } // The direct li element's "active" class is removed if($(this).hasClass("active")){ $(this).removeClass("active"); } }); // After having all topbar li elements deactivated, "active" class is added to the currently active link's li parent if(!$(activeLink).hasClass("active")){ $(activeLink).addClass("active"); } } }); // This variable is used to know if this script will be loaded at the time of checking it in the JS manager activeLinkActivatorLoaded = true;
joseAyudarte91/aterbe_web_project
js/commons/activateCurrentLink.js
JavaScript
mit
1,381
const elixir = require('laravel-elixir'); elixir((mix) => { // Mix all Sass files into one mix.sass('app.scss'); // Mix all vendor scripts together mix.scripts( [ 'jquery/dist/jquery.min.js', 'bootstrap-sass/assets/javascripts/bootstrap.min.js', 'bootstrap-sass/assets/javascripts/bootstrap/dropdown.js' ], 'resources/assets/js/vendor.js', 'node_modules' ); // Mix all script files into one mix.scripts( ['vendor.js', 'app.js'], 'public/js/app.js' ); // Copy vendor assets to public mix.copy('node_modules/bootstrap-sass/assets/fonts/bootstrap/','public/fonts/bootstrap') .copy('node_modules/font-awesome/fonts', 'public/fonts'); }); /* var elixir = require('laravel-elixir'); elixir(function(mix) { // Mix all scss files into one css file mix.sass([ 'charts.scss', 'app.scss' ], 'public/css/app.css'); // Mix all chart JS files into a master charts file mix.scriptsIn( 'resources/assets/js/charts', 'public/js/charts.js' ); // Mix common JS files into one file mix.scripts([ 'app.js' ], 'public/js/app.js'); }); */
jamesgifford/perfectlydopey
gulpfile.js
JavaScript
mit
1,236
require 'spec_helper' describe User do context 'fields' do it { should have_field(:email).of_type(String)} it { should have_field(:encrypted_password).of_type(String)} it { should have_field(:roles).of_type(Array)} end context 'Mass assignment' do it { should allow_mass_assignment_of(:email) } it { should allow_mass_assignment_of(:roles) } it { should allow_mass_assignment_of(:password) } it { should allow_mass_assignment_of(:password_confirmation) } end context 'Required fields' do it { should validate_presence_of(:roles)} end context 'Associations' do it { should embed_one :profile } end end
techvision/brails
spec/models/user_spec.rb
Ruby
mit
661
import {Map} from 'immutable'; export function getInteractiveLayerIds(mapStyle) { let interactiveLayerIds = []; if (Map.isMap(mapStyle) && mapStyle.has('layers')) { interactiveLayerIds = mapStyle.get('layers') .filter(l => l.get('interactive')) .map(l => l.get('id')) .toJS(); } else if (Array.isArray(mapStyle.layers)) { interactiveLayerIds = mapStyle.layers.filter(l => l.interactive) .map(l => l.id); } return interactiveLayerIds; }
RanaRunning/rana
web/src/components/MapGL/utils/style-utils.js
JavaScript
mit
480
<!doctype html> <html> <head> </head> <body> <h1>Milestones - Codenautas</h1> <div id=milestones></div> <script src=milestones.js></script> </body> </html>
codenautas/pruebas_de_concepto
milestones/milestones.html
HTML
mit
186
/* * Created on 24/02/2014 * */ package net.rlviana.pricegrabber.model.entity.common; import net.rlviana.pricegrabber.context.JPAPersistenceContext; import net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; /** * @author ramon */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {JPAPersistenceContext.class}) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false) @Transactional public class CurrencyTest extends AbstractReadOnlyEntityTest<Currency, String> { private static final Logger LOGGER = LoggerFactory.getLogger(CurrencyTest.class); @Test public void testFindAll() { } @Test public void testFindByCriteria() { } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getEntityPKFindOK() */ @Override protected String getEntityPKFindOK() { return "EU"; } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getEntityPKFindKO() */ @Override protected String getEntityPKFindKO() { return "NEU"; } /** * @return * @see net.rlviana.pricegrabber.model.entity.AbstractReadOnlyEntityTest#getTestClass() */ @Override protected Class<Currency> getTestClass() { return Currency.class; } }
rlviana/pricegrabber-app
pricegrabber-model/src/test/java/net/rlviana/pricegrabber/model/entity/common/CurrencyTest.java
Java
mit
1,712
package machinelearningservices // 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. // AllocationState enumerates the values for allocation state. type AllocationState string const ( // AllocationStateResizing ... AllocationStateResizing AllocationState = "Resizing" // AllocationStateSteady ... AllocationStateSteady AllocationState = "Steady" ) // PossibleAllocationStateValues returns an array of possible values for the AllocationState const type. func PossibleAllocationStateValues() []AllocationState { return []AllocationState{AllocationStateResizing, AllocationStateSteady} } // ApplicationSharingPolicy enumerates the values for application sharing policy. type ApplicationSharingPolicy string const ( // ApplicationSharingPolicyPersonal ... ApplicationSharingPolicyPersonal ApplicationSharingPolicy = "Personal" // ApplicationSharingPolicyShared ... ApplicationSharingPolicyShared ApplicationSharingPolicy = "Shared" ) // PossibleApplicationSharingPolicyValues returns an array of possible values for the ApplicationSharingPolicy const type. func PossibleApplicationSharingPolicyValues() []ApplicationSharingPolicy { return []ApplicationSharingPolicy{ApplicationSharingPolicyPersonal, ApplicationSharingPolicyShared} } // ClusterPurpose enumerates the values for cluster purpose. type ClusterPurpose string const ( // ClusterPurposeDenseProd ... ClusterPurposeDenseProd ClusterPurpose = "DenseProd" // ClusterPurposeDevTest ... ClusterPurposeDevTest ClusterPurpose = "DevTest" // ClusterPurposeFastProd ... ClusterPurposeFastProd ClusterPurpose = "FastProd" ) // PossibleClusterPurposeValues returns an array of possible values for the ClusterPurpose const type. func PossibleClusterPurposeValues() []ClusterPurpose { return []ClusterPurpose{ClusterPurposeDenseProd, ClusterPurposeDevTest, ClusterPurposeFastProd} } // ComputeInstanceAuthorizationType enumerates the values for compute instance authorization type. type ComputeInstanceAuthorizationType string const ( // ComputeInstanceAuthorizationTypePersonal ... ComputeInstanceAuthorizationTypePersonal ComputeInstanceAuthorizationType = "personal" ) // PossibleComputeInstanceAuthorizationTypeValues returns an array of possible values for the ComputeInstanceAuthorizationType const type. func PossibleComputeInstanceAuthorizationTypeValues() []ComputeInstanceAuthorizationType { return []ComputeInstanceAuthorizationType{ComputeInstanceAuthorizationTypePersonal} } // ComputeInstanceState enumerates the values for compute instance state. type ComputeInstanceState string const ( // ComputeInstanceStateCreateFailed ... ComputeInstanceStateCreateFailed ComputeInstanceState = "CreateFailed" // ComputeInstanceStateCreating ... ComputeInstanceStateCreating ComputeInstanceState = "Creating" // ComputeInstanceStateDeleting ... ComputeInstanceStateDeleting ComputeInstanceState = "Deleting" // ComputeInstanceStateJobRunning ... ComputeInstanceStateJobRunning ComputeInstanceState = "JobRunning" // ComputeInstanceStateRestarting ... ComputeInstanceStateRestarting ComputeInstanceState = "Restarting" // ComputeInstanceStateRunning ... ComputeInstanceStateRunning ComputeInstanceState = "Running" // ComputeInstanceStateSettingUp ... ComputeInstanceStateSettingUp ComputeInstanceState = "SettingUp" // ComputeInstanceStateSetupFailed ... ComputeInstanceStateSetupFailed ComputeInstanceState = "SetupFailed" // ComputeInstanceStateStarting ... ComputeInstanceStateStarting ComputeInstanceState = "Starting" // ComputeInstanceStateStopped ... ComputeInstanceStateStopped ComputeInstanceState = "Stopped" // ComputeInstanceStateStopping ... ComputeInstanceStateStopping ComputeInstanceState = "Stopping" // ComputeInstanceStateUnknown ... ComputeInstanceStateUnknown ComputeInstanceState = "Unknown" // ComputeInstanceStateUnusable ... ComputeInstanceStateUnusable ComputeInstanceState = "Unusable" // ComputeInstanceStateUserSettingUp ... ComputeInstanceStateUserSettingUp ComputeInstanceState = "UserSettingUp" // ComputeInstanceStateUserSetupFailed ... ComputeInstanceStateUserSetupFailed ComputeInstanceState = "UserSetupFailed" ) // PossibleComputeInstanceStateValues returns an array of possible values for the ComputeInstanceState const type. func PossibleComputeInstanceStateValues() []ComputeInstanceState { return []ComputeInstanceState{ComputeInstanceStateCreateFailed, ComputeInstanceStateCreating, ComputeInstanceStateDeleting, ComputeInstanceStateJobRunning, ComputeInstanceStateRestarting, ComputeInstanceStateRunning, ComputeInstanceStateSettingUp, ComputeInstanceStateSetupFailed, ComputeInstanceStateStarting, ComputeInstanceStateStopped, ComputeInstanceStateStopping, ComputeInstanceStateUnknown, ComputeInstanceStateUnusable, ComputeInstanceStateUserSettingUp, ComputeInstanceStateUserSetupFailed} } // ComputeType enumerates the values for compute type. type ComputeType string const ( // ComputeTypeAKS ... ComputeTypeAKS ComputeType = "AKS" // ComputeTypeAmlCompute ... ComputeTypeAmlCompute ComputeType = "AmlCompute" // ComputeTypeComputeInstance ... ComputeTypeComputeInstance ComputeType = "ComputeInstance" // ComputeTypeDatabricks ... ComputeTypeDatabricks ComputeType = "Databricks" // ComputeTypeDataFactory ... ComputeTypeDataFactory ComputeType = "DataFactory" // ComputeTypeDataLakeAnalytics ... ComputeTypeDataLakeAnalytics ComputeType = "DataLakeAnalytics" // ComputeTypeHDInsight ... ComputeTypeHDInsight ComputeType = "HDInsight" // ComputeTypeSynapseSpark ... ComputeTypeSynapseSpark ComputeType = "SynapseSpark" // ComputeTypeVirtualMachine ... ComputeTypeVirtualMachine ComputeType = "VirtualMachine" ) // PossibleComputeTypeValues returns an array of possible values for the ComputeType const type. func PossibleComputeTypeValues() []ComputeType { return []ComputeType{ComputeTypeAKS, ComputeTypeAmlCompute, ComputeTypeComputeInstance, ComputeTypeDatabricks, ComputeTypeDataFactory, ComputeTypeDataLakeAnalytics, ComputeTypeHDInsight, ComputeTypeSynapseSpark, ComputeTypeVirtualMachine} } // ComputeTypeBasicCompute enumerates the values for compute type basic compute. type ComputeTypeBasicCompute string const ( // ComputeTypeBasicComputeComputeTypeAKS ... ComputeTypeBasicComputeComputeTypeAKS ComputeTypeBasicCompute = "AKS" // ComputeTypeBasicComputeComputeTypeAmlCompute ... ComputeTypeBasicComputeComputeTypeAmlCompute ComputeTypeBasicCompute = "AmlCompute" // ComputeTypeBasicComputeComputeTypeCompute ... ComputeTypeBasicComputeComputeTypeCompute ComputeTypeBasicCompute = "Compute" // ComputeTypeBasicComputeComputeTypeComputeInstance ... ComputeTypeBasicComputeComputeTypeComputeInstance ComputeTypeBasicCompute = "ComputeInstance" // ComputeTypeBasicComputeComputeTypeDatabricks ... ComputeTypeBasicComputeComputeTypeDatabricks ComputeTypeBasicCompute = "Databricks" // ComputeTypeBasicComputeComputeTypeDataFactory ... ComputeTypeBasicComputeComputeTypeDataFactory ComputeTypeBasicCompute = "DataFactory" // ComputeTypeBasicComputeComputeTypeDataLakeAnalytics ... ComputeTypeBasicComputeComputeTypeDataLakeAnalytics ComputeTypeBasicCompute = "DataLakeAnalytics" // ComputeTypeBasicComputeComputeTypeHDInsight ... ComputeTypeBasicComputeComputeTypeHDInsight ComputeTypeBasicCompute = "HDInsight" // ComputeTypeBasicComputeComputeTypeVirtualMachine ... ComputeTypeBasicComputeComputeTypeVirtualMachine ComputeTypeBasicCompute = "VirtualMachine" ) // PossibleComputeTypeBasicComputeValues returns an array of possible values for the ComputeTypeBasicCompute const type. func PossibleComputeTypeBasicComputeValues() []ComputeTypeBasicCompute { return []ComputeTypeBasicCompute{ComputeTypeBasicComputeComputeTypeAKS, ComputeTypeBasicComputeComputeTypeAmlCompute, ComputeTypeBasicComputeComputeTypeCompute, ComputeTypeBasicComputeComputeTypeComputeInstance, ComputeTypeBasicComputeComputeTypeDatabricks, ComputeTypeBasicComputeComputeTypeDataFactory, ComputeTypeBasicComputeComputeTypeDataLakeAnalytics, ComputeTypeBasicComputeComputeTypeHDInsight, ComputeTypeBasicComputeComputeTypeVirtualMachine} } // ComputeTypeBasicComputeNodesInformation enumerates the values for compute type basic compute nodes // information. type ComputeTypeBasicComputeNodesInformation string const ( // ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute ... ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute ComputeTypeBasicComputeNodesInformation = "AmlCompute" // ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation ... ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation ComputeTypeBasicComputeNodesInformation = "ComputeNodesInformation" ) // PossibleComputeTypeBasicComputeNodesInformationValues returns an array of possible values for the ComputeTypeBasicComputeNodesInformation const type. func PossibleComputeTypeBasicComputeNodesInformationValues() []ComputeTypeBasicComputeNodesInformation { return []ComputeTypeBasicComputeNodesInformation{ComputeTypeBasicComputeNodesInformationComputeTypeAmlCompute, ComputeTypeBasicComputeNodesInformationComputeTypeComputeNodesInformation} } // ComputeTypeBasicComputeSecrets enumerates the values for compute type basic compute secrets. type ComputeTypeBasicComputeSecrets string const ( // ComputeTypeBasicComputeSecretsComputeTypeAKS ... ComputeTypeBasicComputeSecretsComputeTypeAKS ComputeTypeBasicComputeSecrets = "AKS" // ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets ... ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets ComputeTypeBasicComputeSecrets = "ComputeSecrets" // ComputeTypeBasicComputeSecretsComputeTypeDatabricks ... ComputeTypeBasicComputeSecretsComputeTypeDatabricks ComputeTypeBasicComputeSecrets = "Databricks" // ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine ... ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine ComputeTypeBasicComputeSecrets = "VirtualMachine" ) // PossibleComputeTypeBasicComputeSecretsValues returns an array of possible values for the ComputeTypeBasicComputeSecrets const type. func PossibleComputeTypeBasicComputeSecretsValues() []ComputeTypeBasicComputeSecrets { return []ComputeTypeBasicComputeSecrets{ComputeTypeBasicComputeSecretsComputeTypeAKS, ComputeTypeBasicComputeSecretsComputeTypeComputeSecrets, ComputeTypeBasicComputeSecretsComputeTypeDatabricks, ComputeTypeBasicComputeSecretsComputeTypeVirtualMachine} } // ComputeTypeBasicCreateServiceRequest enumerates the values for compute type basic create service request. type ComputeTypeBasicCreateServiceRequest string const ( // ComputeTypeBasicCreateServiceRequestComputeTypeACI ... ComputeTypeBasicCreateServiceRequestComputeTypeACI ComputeTypeBasicCreateServiceRequest = "ACI" // ComputeTypeBasicCreateServiceRequestComputeTypeAKS ... ComputeTypeBasicCreateServiceRequestComputeTypeAKS ComputeTypeBasicCreateServiceRequest = "AKS" // ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest ... ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest ComputeTypeBasicCreateServiceRequest = "CreateServiceRequest" // ComputeTypeBasicCreateServiceRequestComputeTypeCustom ... ComputeTypeBasicCreateServiceRequestComputeTypeCustom ComputeTypeBasicCreateServiceRequest = "Custom" ) // PossibleComputeTypeBasicCreateServiceRequestValues returns an array of possible values for the ComputeTypeBasicCreateServiceRequest const type. func PossibleComputeTypeBasicCreateServiceRequestValues() []ComputeTypeBasicCreateServiceRequest { return []ComputeTypeBasicCreateServiceRequest{ComputeTypeBasicCreateServiceRequestComputeTypeACI, ComputeTypeBasicCreateServiceRequestComputeTypeAKS, ComputeTypeBasicCreateServiceRequestComputeTypeCreateServiceRequest, ComputeTypeBasicCreateServiceRequestComputeTypeCustom} } // ComputeTypeBasicServiceResponseBase enumerates the values for compute type basic service response base. type ComputeTypeBasicServiceResponseBase string const ( // ComputeTypeBasicServiceResponseBaseComputeTypeACI ... ComputeTypeBasicServiceResponseBaseComputeTypeACI ComputeTypeBasicServiceResponseBase = "ACI" // ComputeTypeBasicServiceResponseBaseComputeTypeAKS ... ComputeTypeBasicServiceResponseBaseComputeTypeAKS ComputeTypeBasicServiceResponseBase = "AKS" // ComputeTypeBasicServiceResponseBaseComputeTypeCustom ... ComputeTypeBasicServiceResponseBaseComputeTypeCustom ComputeTypeBasicServiceResponseBase = "Custom" // ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase ... ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase ComputeTypeBasicServiceResponseBase = "ServiceResponseBase" ) // PossibleComputeTypeBasicServiceResponseBaseValues returns an array of possible values for the ComputeTypeBasicServiceResponseBase const type. func PossibleComputeTypeBasicServiceResponseBaseValues() []ComputeTypeBasicServiceResponseBase { return []ComputeTypeBasicServiceResponseBase{ComputeTypeBasicServiceResponseBaseComputeTypeACI, ComputeTypeBasicServiceResponseBaseComputeTypeAKS, ComputeTypeBasicServiceResponseBaseComputeTypeCustom, ComputeTypeBasicServiceResponseBaseComputeTypeServiceResponseBase} } // DeploymentType enumerates the values for deployment type. type DeploymentType string const ( // DeploymentTypeBatch ... DeploymentTypeBatch DeploymentType = "Batch" // DeploymentTypeGRPCRealtimeEndpoint ... DeploymentTypeGRPCRealtimeEndpoint DeploymentType = "GRPCRealtimeEndpoint" // DeploymentTypeHTTPRealtimeEndpoint ... DeploymentTypeHTTPRealtimeEndpoint DeploymentType = "HttpRealtimeEndpoint" ) // PossibleDeploymentTypeValues returns an array of possible values for the DeploymentType const type. func PossibleDeploymentTypeValues() []DeploymentType { return []DeploymentType{DeploymentTypeBatch, DeploymentTypeGRPCRealtimeEndpoint, DeploymentTypeHTTPRealtimeEndpoint} } // EncryptionStatus enumerates the values for encryption status. type EncryptionStatus string const ( // EncryptionStatusDisabled ... EncryptionStatusDisabled EncryptionStatus = "Disabled" // EncryptionStatusEnabled ... EncryptionStatusEnabled EncryptionStatus = "Enabled" ) // PossibleEncryptionStatusValues returns an array of possible values for the EncryptionStatus const type. func PossibleEncryptionStatusValues() []EncryptionStatus { return []EncryptionStatus{EncryptionStatusDisabled, EncryptionStatusEnabled} } // IdentityType enumerates the values for identity type. type IdentityType string const ( // IdentityTypeApplication ... IdentityTypeApplication IdentityType = "Application" // IdentityTypeKey ... IdentityTypeKey IdentityType = "Key" // IdentityTypeManagedIdentity ... IdentityTypeManagedIdentity IdentityType = "ManagedIdentity" // IdentityTypeUser ... IdentityTypeUser IdentityType = "User" ) // PossibleIdentityTypeValues returns an array of possible values for the IdentityType const type. func PossibleIdentityTypeValues() []IdentityType { return []IdentityType{IdentityTypeApplication, IdentityTypeKey, IdentityTypeManagedIdentity, IdentityTypeUser} } // LoadBalancerType enumerates the values for load balancer type. type LoadBalancerType string const ( // LoadBalancerTypeInternalLoadBalancer ... LoadBalancerTypeInternalLoadBalancer LoadBalancerType = "InternalLoadBalancer" // LoadBalancerTypePublicIP ... LoadBalancerTypePublicIP LoadBalancerType = "PublicIp" ) // PossibleLoadBalancerTypeValues returns an array of possible values for the LoadBalancerType const type. func PossibleLoadBalancerTypeValues() []LoadBalancerType { return []LoadBalancerType{LoadBalancerTypeInternalLoadBalancer, LoadBalancerTypePublicIP} } // NodeState enumerates the values for node state. type NodeState string const ( // NodeStateIdle ... NodeStateIdle NodeState = "idle" // NodeStateLeaving ... NodeStateLeaving NodeState = "leaving" // NodeStatePreempted ... NodeStatePreempted NodeState = "preempted" // NodeStatePreparing ... NodeStatePreparing NodeState = "preparing" // NodeStateRunning ... NodeStateRunning NodeState = "running" // NodeStateUnusable ... NodeStateUnusable NodeState = "unusable" ) // PossibleNodeStateValues returns an array of possible values for the NodeState const type. func PossibleNodeStateValues() []NodeState { return []NodeState{NodeStateIdle, NodeStateLeaving, NodeStatePreempted, NodeStatePreparing, NodeStateRunning, NodeStateUnusable} } // OperationName enumerates the values for operation name. type OperationName string const ( // OperationNameCreate ... OperationNameCreate OperationName = "Create" // OperationNameDelete ... OperationNameDelete OperationName = "Delete" // OperationNameReimage ... OperationNameReimage OperationName = "Reimage" // OperationNameRestart ... OperationNameRestart OperationName = "Restart" // OperationNameStart ... OperationNameStart OperationName = "Start" // OperationNameStop ... OperationNameStop OperationName = "Stop" ) // PossibleOperationNameValues returns an array of possible values for the OperationName const type. func PossibleOperationNameValues() []OperationName { return []OperationName{OperationNameCreate, OperationNameDelete, OperationNameReimage, OperationNameRestart, OperationNameStart, OperationNameStop} } // OperationStatus enumerates the values for operation status. type OperationStatus string const ( // OperationStatusCreateFailed ... OperationStatusCreateFailed OperationStatus = "CreateFailed" // OperationStatusDeleteFailed ... OperationStatusDeleteFailed OperationStatus = "DeleteFailed" // OperationStatusInProgress ... OperationStatusInProgress OperationStatus = "InProgress" // OperationStatusReimageFailed ... OperationStatusReimageFailed OperationStatus = "ReimageFailed" // OperationStatusRestartFailed ... OperationStatusRestartFailed OperationStatus = "RestartFailed" // OperationStatusStartFailed ... OperationStatusStartFailed OperationStatus = "StartFailed" // OperationStatusStopFailed ... OperationStatusStopFailed OperationStatus = "StopFailed" // OperationStatusSucceeded ... OperationStatusSucceeded OperationStatus = "Succeeded" ) // PossibleOperationStatusValues returns an array of possible values for the OperationStatus const type. func PossibleOperationStatusValues() []OperationStatus { return []OperationStatus{OperationStatusCreateFailed, OperationStatusDeleteFailed, OperationStatusInProgress, OperationStatusReimageFailed, OperationStatusRestartFailed, OperationStatusStartFailed, OperationStatusStopFailed, OperationStatusSucceeded} } // OrderString enumerates the values for order string. type OrderString string const ( // OrderStringCreatedAtAsc ... OrderStringCreatedAtAsc OrderString = "CreatedAtAsc" // OrderStringCreatedAtDesc ... OrderStringCreatedAtDesc OrderString = "CreatedAtDesc" // OrderStringUpdatedAtAsc ... OrderStringUpdatedAtAsc OrderString = "UpdatedAtAsc" // OrderStringUpdatedAtDesc ... OrderStringUpdatedAtDesc OrderString = "UpdatedAtDesc" ) // PossibleOrderStringValues returns an array of possible values for the OrderString const type. func PossibleOrderStringValues() []OrderString { return []OrderString{OrderStringCreatedAtAsc, OrderStringCreatedAtDesc, OrderStringUpdatedAtAsc, OrderStringUpdatedAtDesc} } // OsType enumerates the values for os type. type OsType string const ( // OsTypeLinux ... OsTypeLinux OsType = "Linux" // OsTypeWindows ... OsTypeWindows OsType = "Windows" ) // PossibleOsTypeValues returns an array of possible values for the OsType const type. func PossibleOsTypeValues() []OsType { return []OsType{OsTypeLinux, OsTypeWindows} } // PrivateEndpointConnectionProvisioningState enumerates the values for private endpoint connection // provisioning state. type PrivateEndpointConnectionProvisioningState string const ( // PrivateEndpointConnectionProvisioningStateCreating ... PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" // PrivateEndpointConnectionProvisioningStateDeleting ... PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" // PrivateEndpointConnectionProvisioningStateFailed ... PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" // PrivateEndpointConnectionProvisioningStateSucceeded ... PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" ) // PossiblePrivateEndpointConnectionProvisioningStateValues returns an array of possible values for the PrivateEndpointConnectionProvisioningState const type. func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { return []PrivateEndpointConnectionProvisioningState{PrivateEndpointConnectionProvisioningStateCreating, PrivateEndpointConnectionProvisioningStateDeleting, PrivateEndpointConnectionProvisioningStateFailed, PrivateEndpointConnectionProvisioningStateSucceeded} } // PrivateEndpointServiceConnectionStatus enumerates the values for private endpoint service connection status. type PrivateEndpointServiceConnectionStatus string const ( // PrivateEndpointServiceConnectionStatusApproved ... PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved" // PrivateEndpointServiceConnectionStatusDisconnected ... PrivateEndpointServiceConnectionStatusDisconnected PrivateEndpointServiceConnectionStatus = "Disconnected" // PrivateEndpointServiceConnectionStatusPending ... PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending" // PrivateEndpointServiceConnectionStatusRejected ... PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected" // PrivateEndpointServiceConnectionStatusTimeout ... PrivateEndpointServiceConnectionStatusTimeout PrivateEndpointServiceConnectionStatus = "Timeout" ) // PossiblePrivateEndpointServiceConnectionStatusValues returns an array of possible values for the PrivateEndpointServiceConnectionStatus const type. func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus { return []PrivateEndpointServiceConnectionStatus{PrivateEndpointServiceConnectionStatusApproved, PrivateEndpointServiceConnectionStatusDisconnected, PrivateEndpointServiceConnectionStatusPending, PrivateEndpointServiceConnectionStatusRejected, PrivateEndpointServiceConnectionStatusTimeout} } // ProvisioningState enumerates the values for provisioning state. type ProvisioningState string const ( // ProvisioningStateCanceled ... ProvisioningStateCanceled ProvisioningState = "Canceled" // ProvisioningStateCreating ... ProvisioningStateCreating ProvisioningState = "Creating" // ProvisioningStateDeleting ... ProvisioningStateDeleting ProvisioningState = "Deleting" // ProvisioningStateFailed ... ProvisioningStateFailed ProvisioningState = "Failed" // ProvisioningStateSucceeded ... ProvisioningStateSucceeded ProvisioningState = "Succeeded" // ProvisioningStateUnknown ... ProvisioningStateUnknown ProvisioningState = "Unknown" // ProvisioningStateUpdating ... ProvisioningStateUpdating ProvisioningState = "Updating" ) // PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. func PossibleProvisioningStateValues() []ProvisioningState { return []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateSucceeded, ProvisioningStateUnknown, ProvisioningStateUpdating} } // QuotaUnit enumerates the values for quota unit. type QuotaUnit string const ( // QuotaUnitCount ... QuotaUnitCount QuotaUnit = "Count" ) // PossibleQuotaUnitValues returns an array of possible values for the QuotaUnit const type. func PossibleQuotaUnitValues() []QuotaUnit { return []QuotaUnit{QuotaUnitCount} } // ReasonCode enumerates the values for reason code. type ReasonCode string const ( // ReasonCodeNotAvailableForRegion ... ReasonCodeNotAvailableForRegion ReasonCode = "NotAvailableForRegion" // ReasonCodeNotAvailableForSubscription ... ReasonCodeNotAvailableForSubscription ReasonCode = "NotAvailableForSubscription" // ReasonCodeNotSpecified ... ReasonCodeNotSpecified ReasonCode = "NotSpecified" ) // PossibleReasonCodeValues returns an array of possible values for the ReasonCode const type. func PossibleReasonCodeValues() []ReasonCode { return []ReasonCode{ReasonCodeNotAvailableForRegion, ReasonCodeNotAvailableForSubscription, ReasonCodeNotSpecified} } // RemoteLoginPortPublicAccess enumerates the values for remote login port public access. type RemoteLoginPortPublicAccess string const ( // RemoteLoginPortPublicAccessDisabled ... RemoteLoginPortPublicAccessDisabled RemoteLoginPortPublicAccess = "Disabled" // RemoteLoginPortPublicAccessEnabled ... RemoteLoginPortPublicAccessEnabled RemoteLoginPortPublicAccess = "Enabled" // RemoteLoginPortPublicAccessNotSpecified ... RemoteLoginPortPublicAccessNotSpecified RemoteLoginPortPublicAccess = "NotSpecified" ) // PossibleRemoteLoginPortPublicAccessValues returns an array of possible values for the RemoteLoginPortPublicAccess const type. func PossibleRemoteLoginPortPublicAccessValues() []RemoteLoginPortPublicAccess { return []RemoteLoginPortPublicAccess{RemoteLoginPortPublicAccessDisabled, RemoteLoginPortPublicAccessEnabled, RemoteLoginPortPublicAccessNotSpecified} } // ResourceIdentityType enumerates the values for resource identity type. type ResourceIdentityType string const ( // ResourceIdentityTypeNone ... ResourceIdentityTypeNone ResourceIdentityType = "None" // ResourceIdentityTypeSystemAssigned ... ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" // ResourceIdentityTypeSystemAssignedUserAssigned ... ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned,UserAssigned" // ResourceIdentityTypeUserAssigned ... ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" ) // PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type. func PossibleResourceIdentityTypeValues() []ResourceIdentityType { return []ResourceIdentityType{ResourceIdentityTypeNone, ResourceIdentityTypeSystemAssigned, ResourceIdentityTypeSystemAssignedUserAssigned, ResourceIdentityTypeUserAssigned} } // SSHPublicAccess enumerates the values for ssh public access. type SSHPublicAccess string const ( // SSHPublicAccessDisabled ... SSHPublicAccessDisabled SSHPublicAccess = "Disabled" // SSHPublicAccessEnabled ... SSHPublicAccessEnabled SSHPublicAccess = "Enabled" ) // PossibleSSHPublicAccessValues returns an array of possible values for the SSHPublicAccess const type. func PossibleSSHPublicAccessValues() []SSHPublicAccess { return []SSHPublicAccess{SSHPublicAccessDisabled, SSHPublicAccessEnabled} } // Status enumerates the values for status. type Status string const ( // StatusFailure ... StatusFailure Status = "Failure" // StatusInvalidQuotaBelowClusterMinimum ... StatusInvalidQuotaBelowClusterMinimum Status = "InvalidQuotaBelowClusterMinimum" // StatusInvalidQuotaExceedsSubscriptionLimit ... StatusInvalidQuotaExceedsSubscriptionLimit Status = "InvalidQuotaExceedsSubscriptionLimit" // StatusInvalidVMFamilyName ... StatusInvalidVMFamilyName Status = "InvalidVMFamilyName" // StatusOperationNotEnabledForRegion ... StatusOperationNotEnabledForRegion Status = "OperationNotEnabledForRegion" // StatusOperationNotSupportedForSku ... StatusOperationNotSupportedForSku Status = "OperationNotSupportedForSku" // StatusSuccess ... StatusSuccess Status = "Success" // StatusUndefined ... StatusUndefined Status = "Undefined" ) // PossibleStatusValues returns an array of possible values for the Status const type. func PossibleStatusValues() []Status { return []Status{StatusFailure, StatusInvalidQuotaBelowClusterMinimum, StatusInvalidQuotaExceedsSubscriptionLimit, StatusInvalidVMFamilyName, StatusOperationNotEnabledForRegion, StatusOperationNotSupportedForSku, StatusSuccess, StatusUndefined} } // Status1 enumerates the values for status 1. type Status1 string const ( // Status1Auto ... Status1Auto Status1 = "Auto" // Status1Disabled ... Status1Disabled Status1 = "Disabled" // Status1Enabled ... Status1Enabled Status1 = "Enabled" ) // PossibleStatus1Values returns an array of possible values for the Status1 const type. func PossibleStatus1Values() []Status1 { return []Status1{Status1Auto, Status1Disabled, Status1Enabled} } // UnderlyingResourceAction enumerates the values for underlying resource action. type UnderlyingResourceAction string const ( // UnderlyingResourceActionDelete ... UnderlyingResourceActionDelete UnderlyingResourceAction = "Delete" // UnderlyingResourceActionDetach ... UnderlyingResourceActionDetach UnderlyingResourceAction = "Detach" ) // PossibleUnderlyingResourceActionValues returns an array of possible values for the UnderlyingResourceAction const type. func PossibleUnderlyingResourceActionValues() []UnderlyingResourceAction { return []UnderlyingResourceAction{UnderlyingResourceActionDelete, UnderlyingResourceActionDetach} } // UsageUnit enumerates the values for usage unit. type UsageUnit string const ( // UsageUnitCount ... UsageUnitCount UsageUnit = "Count" ) // PossibleUsageUnitValues returns an array of possible values for the UsageUnit const type. func PossibleUsageUnitValues() []UsageUnit { return []UsageUnit{UsageUnitCount} } // ValueFormat enumerates the values for value format. type ValueFormat string const ( // ValueFormatJSON ... ValueFormatJSON ValueFormat = "JSON" ) // PossibleValueFormatValues returns an array of possible values for the ValueFormat const type. func PossibleValueFormatValues() []ValueFormat { return []ValueFormat{ValueFormatJSON} } // VariantType enumerates the values for variant type. type VariantType string const ( // VariantTypeControl ... VariantTypeControl VariantType = "Control" // VariantTypeTreatment ... VariantTypeTreatment VariantType = "Treatment" ) // PossibleVariantTypeValues returns an array of possible values for the VariantType const type. func PossibleVariantTypeValues() []VariantType { return []VariantType{VariantTypeControl, VariantTypeTreatment} } // VMPriceOSType enumerates the values for vm price os type. type VMPriceOSType string const ( // VMPriceOSTypeLinux ... VMPriceOSTypeLinux VMPriceOSType = "Linux" // VMPriceOSTypeWindows ... VMPriceOSTypeWindows VMPriceOSType = "Windows" ) // PossibleVMPriceOSTypeValues returns an array of possible values for the VMPriceOSType const type. func PossibleVMPriceOSTypeValues() []VMPriceOSType { return []VMPriceOSType{VMPriceOSTypeLinux, VMPriceOSTypeWindows} } // VMPriority enumerates the values for vm priority. type VMPriority string const ( // VMPriorityDedicated ... VMPriorityDedicated VMPriority = "Dedicated" // VMPriorityLowPriority ... VMPriorityLowPriority VMPriority = "LowPriority" ) // PossibleVMPriorityValues returns an array of possible values for the VMPriority const type. func PossibleVMPriorityValues() []VMPriority { return []VMPriority{VMPriorityDedicated, VMPriorityLowPriority} } // VMTier enumerates the values for vm tier. type VMTier string const ( // VMTierLowPriority ... VMTierLowPriority VMTier = "LowPriority" // VMTierSpot ... VMTierSpot VMTier = "Spot" // VMTierStandard ... VMTierStandard VMTier = "Standard" ) // PossibleVMTierValues returns an array of possible values for the VMTier const type. func PossibleVMTierValues() []VMTier { return []VMTier{VMTierLowPriority, VMTierSpot, VMTierStandard} } // WebServiceState enumerates the values for web service state. type WebServiceState string const ( // WebServiceStateFailed ... WebServiceStateFailed WebServiceState = "Failed" // WebServiceStateHealthy ... WebServiceStateHealthy WebServiceState = "Healthy" // WebServiceStateTransitioning ... WebServiceStateTransitioning WebServiceState = "Transitioning" // WebServiceStateUnhealthy ... WebServiceStateUnhealthy WebServiceState = "Unhealthy" // WebServiceStateUnschedulable ... WebServiceStateUnschedulable WebServiceState = "Unschedulable" ) // PossibleWebServiceStateValues returns an array of possible values for the WebServiceState const type. func PossibleWebServiceStateValues() []WebServiceState { return []WebServiceState{WebServiceStateFailed, WebServiceStateHealthy, WebServiceStateTransitioning, WebServiceStateUnhealthy, WebServiceStateUnschedulable} }
Azure/azure-sdk-for-go
services/machinelearningservices/mgmt/2021-04-01/machinelearningservices/enums.go
GO
mit
32,878
#include "utfgrid_encode.h" #include <unordered_map> #include <glog/logging.h> #include <jsoncpp/json/value.h> #include <mapnik/unicode.hpp> struct value_to_json_visitor { Json::Value operator() (const mapnik::value_null& val) {return Json::Value();} Json::Value operator() (const mapnik::value_bool& val) {return Json::Value(val);} Json::Value operator() (const mapnik::value_integer& val) {return Json::Value(static_cast<uint>(val));} Json::Value operator() (const mapnik::value_double& val) {return Json::Value(val);} Json::Value operator() (const mapnik::value_unicode_string& val) { std::string utf8_str; mapnik::to_utf8(val, utf8_str); return Json::Value(utf8_str); } }; std::string encode_utfgrid(const mapnik::grid_view& utfgrid, uint size) { Json::Value root(Json::objectValue); Json::Value& jgrid = root["grid"]; jgrid = Json::Value(Json::arrayValue); using lookup_type = mapnik::grid::lookup_type; using value_type = mapnik::grid::value_type; using feature_type = mapnik::grid::feature_type; using keys_type = std::unordered_map<lookup_type, value_type>; std::vector<lookup_type> key_order; keys_type keys; const mapnik::grid::feature_key_type& feature_keys = utfgrid.get_feature_keys(); std::uint16_t codepoint = 32; for (uint y = 0; y < utfgrid.height(); y += size) { std::string line; const value_type* row = utfgrid.get_row(y); for (uint x = 0; x < utfgrid.width(); x += size) { value_type feature_id = row[x]; auto feature_itr = feature_keys.find(feature_id); lookup_type val; if (feature_itr == feature_keys.end()) { feature_id = mapnik::grid::base_mask; } else { val = feature_itr->second; } auto key_iter = keys.find(val); if (key_iter == keys.end()) { // Create a new entry for this key. Skip the codepoints that // can't be encoded directly in JSON. if (codepoint == 34) ++codepoint; // Skip " else if (codepoint == 92) ++codepoint; // Skip backslash if (feature_id == mapnik::grid::base_mask) { keys[""] = codepoint; key_order.push_back(""); } else { keys[val] = codepoint; key_order.push_back(val); } line.append(reinterpret_cast<char*>(&codepoint), sizeof(codepoint)); ++codepoint; } else { line.append(reinterpret_cast<char*>(&key_iter->second), sizeof(key_iter->second)); } } jgrid.append(Json::Value(line)); } Json::Value& jkeys = root["keys"]; jkeys = Json::Value(Json::arrayValue); for (const auto& key_id : key_order) { jkeys.append(key_id); } Json::Value& jdata = root["data"]; const feature_type& g_features = utfgrid.get_grid_features(); const std::set<std::string>& attributes = utfgrid.get_fields(); feature_type::const_iterator feat_end = g_features.end(); for (const std::string& key_item : key_order) { if (key_item.empty()) { continue; } feature_type::const_iterator feat_itr = g_features.find(key_item); if (feat_itr == feat_end) { continue; } bool found = false; Json::Value jfeature(Json::objectValue); mapnik::feature_ptr feature = feat_itr->second; for (const std::string& attr : attributes) { value_to_json_visitor val_to_json; if (attr == "__id__") { jfeature[attr] = static_cast<uint>(feature->id()); } else if (feature->has_key(attr)) { found = true; jfeature[attr] = mapnik::util::apply_visitor(val_to_json, feature->get(attr)); } } if (found) { jdata[feat_itr->first] = jfeature; } } return root.toStyledString(); }
sputnik-maps/maps-express
src/utfgrid_encode.cpp
C++
mit
4,103
package me.moodcat.api; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import lombok.Getter; import me.moodcat.database.embeddables.VAVector; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; /** * A mood represents a vector in the valence-arousal plane which will be attached to song. */ @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum Mood { // CHECKSTYLE:OFF ANGRY(new VAVector(-0.6, 0.6), "Angry"), CALM(new VAVector(0.3, -0.9), "Calm"), EXCITING(new VAVector(0.4, 0.8), "Exciting"), HAPPY(new VAVector(0.7, 0.6), "Happy"), NERVOUS(new VAVector(-0.7, 0.4), "Nervous"), PLEASING(new VAVector(0.6, 0.3), "Pleasing"), PEACEFUL(new VAVector(0.5, -0.7), "Peaceful"), RELAXED(new VAVector(0.6, -0.3), "Relaxed"), SAD(new VAVector(-0.7, -0.2), "Sad"), SLEEPY(new VAVector(-0.2, -0.9), "Sleepy"); // CHECKSTYLE:ON /** * List of all names that represent moods. Used in {@link #nameRepresentsMood(String)}. * By storing this once, we save a lot of unnecessary list creations. */ private static final List<String> MOOD_NAMES = Arrays.asList(Mood.values()).stream() .map(moodValue -> moodValue.getName()) .collect(Collectors.toList()); /** * The vector that represents this mood. * * @return The vector of this mood. */ @Getter @JsonIgnore private final VAVector vector; /** * Readable name for the frontend. * * @return The readable name of this mood. */ @Getter private final String name; private Mood(final VAVector vector, final String name) { this.vector = vector; this.name = name; } /** * Get the mood that is closest to the given vector. * * @param vector * The vector to determine the mood for. * @return The Mood that is closest to the vector. */ public static Mood closestTo(final VAVector vector) { double distance = Double.MAX_VALUE; Mood mood = null; for (final Mood m : Mood.values()) { final double moodDistance = m.vector.distance(vector); if (moodDistance < distance) { distance = moodDistance; mood = m; } } return mood; } /** * Get the vector that represents the average of the provided list of moods. * * @param moods * The textual list of moods. * @return The average vector, or the zero-vector if no moods were found. */ public static VAVector createTargetVector(final List<String> moods) { final List<VAVector> actualMoods = moods.stream() .filter(Mood::nameRepresentsMood) .map(mood -> Mood.valueOf(mood.toUpperCase(Locale.ROOT))) .map(mood -> mood.getVector()) .collect(Collectors.toList()); return VAVector.average(actualMoods); } private static boolean nameRepresentsMood(final String mood) { return MOOD_NAMES.contains(mood); } }
MoodCat/MoodCat.me-Core
src/main/java/me/moodcat/api/Mood.java
Java
mit
3,192
<!-- CONTAINER BODY --> <div class="panel-group" > <div class="panel panel-default" > <div class="panel-body"> <h4>Filmovi</h4> <!-- Film List --> <hr/> <?php foreach($list as $row): ?> <div class="row text-left"> <div class="col-sm-4 col-fix-140"> <?PHP $id = $row['IDFilm']; $path = $row['Poster']; $link = site_url("index/film/$id"); echo "<a href="."$link"."><img src='"."$path"."' alt='Image' style='height:200px'></a>"; ?> </div> <div class="col-sm-8"> <?php $naslov = $row['Naziv']; echo "<b>$naslov</b>"; ?> <table class="opis"> <tr> <td><i>Ocena</i></td> <td> <?php $ocena = $row['Ocena']; echo "<div>"; for($k=0; $k<10; $k++){ if($k < $ocena) echo "<span class='glyphicon glyphicon-star positiv-rate'></span>"; else echo "<span class='glyphicon glyphicon-star negative-rate'></span>"; } echo "</div>"; ?> </td> </tr> <?php $original = $row['OriginalNaziv']; echo "<tr>"; echo "<td><i>Originalni naslov</i></td>"; echo "<td><b>$original</b></td>"; echo "</tr>"; $datum = $row['PocetakPrikazivanja']; echo "<tr>"; echo "<td><i>Pocetak prikazivanja</i></td>"; echo "<td><b>$datum</b></td>"; echo "</tr>"; $duzina = $row['Duzina']; echo "<tr>"; echo "<td><i>Duzina trajanja</i></td>"; echo "<td><b>$duzina min</b></td>"; echo "</tr>"; $zanr = $row['Zanr']; echo "<tr>"; echo "<td><i>Zanr</i></td>"; echo "<td><b>$zanr</b></td>"; echo "</tr>"; $reziser = $row['Reziser']; echo "<tr>"; echo "<td><i>Reziser</i></td>"; echo "<td><b>$reziser</b></td>"; echo "</tr>"; $poreklo = $row['Poreklo']; echo "<tr>"; echo "<td><i>Drzava</i></td>"; echo "<td><b>$poreklo</b></td>"; echo "</tr>"; ?> </table> </div> </div> <hr/> <?php endforeach; ?> </div> </div> </div> </div>
ti100521/bioskop
application/views/page/filmovi.php
PHP
mit
4,648
<?php $lang = array( 'addons' => 'Add-ons', 'accessories' => 'Accessories', 'modules' => 'Modules', 'extensions' => 'Extensions', 'plugins' => 'Plugins', 'accessory' => 'Accessory', 'module' => 'Module', 'extension' => 'Extension', 'rte_tool' => 'Rich Text Editor Tool', 'addons_accessories' => 'Accessories', 'addons_modules' => 'Modules', 'addons_plugins' => 'Plugins', 'addons_extensions' => 'Extensions', 'addons_fieldtypes' => 'Fieldtypes', 'accessory_name' => 'Accessory Name', 'fieldtype_name' => 'Fieldtype Name', 'install' => 'Install', 'uninstall' => 'Uninstall', 'installed' => 'Installed', 'not_installed' => 'Not Installed', 'uninstalled' => 'Uninstalled', 'remove' => 'Remove', 'preferences_updated' => 'Preferences Updated', 'extension_enabled' => 'Extension Enabled', 'extension_disabled' => 'Extension Disabled', 'extensions_enabled' => 'Extensions Enabled', 'extensions_disabled' => 'Extensions Disabled', 'delete_fieldtype_confirm' => 'Are you sure you want to remove this fieldtype?', 'delete_fieldtype' => 'Remove Fieldtype', 'data_will_be_lost' => 'All data associated with this fieldtype, including all associated channel data, will be permanently deleted!', 'global_settings_saved' => 'Settings Saved', 'package_settings' => 'Package Settings', 'component' => 'Component', 'current_status' => 'Current Status', 'required_by' => 'Required by:', 'available_to_member_groups' => 'Available to Member Groups', 'specific_page' => 'Specific Page?', 'description' => 'Description', 'version' => 'Version', 'status' => 'Status', 'fieldtype' => 'Fieldtype', 'edit_accessory_preferences' => 'Edit Accessory Preferences', 'member_group_assignment' => 'Assigned Member Groups', 'page_assignment' => 'Assigned Pages', 'none' => 'None', 'and_more' => 'and %x more...', 'plugins_not_available' => 'Plugin Feed Disabled in Beta Version.', 'no_extension_id' => 'No Extension Specified', // IGNORE ''=>''); /* End of file addons_lang.php */ /* Location: ./system/expressionengine/language/english/addons_lang.php */
cfox89/EE-Integration-to-API
system/expressionengine/language/english/addons_lang.php
PHP
mit
2,255
# ux - Micro Xylph ux は軽量でシンプルな動作を目標としたソフトウェアシンセサイザです。C# で作られており、Mono 上でも動作します。 ## 概要 ux は [Xylph](http://www.johokagekkan.go.jp/2011/u-20/xylph.html) (シルフ) の後継として開発されています。Xylph の開発で得られた最低限必要な機能を絞り、なおかつ Xylph よりも軽快に動作するよう設計されています。C# で記述しつつ、極力高速な動作が目標です。 ux は モノフォニック、複数パート、ポルタメント、ビブラートなどの機能を持ち、音源として矩形波、16 段三角波、ユーザ波形、線形帰還シフトレジスタによる擬似ノイズ、4 オペレータ FM 音源を搭載しています。 現在 Wiki を構築中です。ハンドルの詳細など仕様については Wiki を参照してください: https://github.com/nanase/ux/wiki ## バイナリ 過去のリリース(v0.1.5-dev以前)は [Releases](//github.com/nanase/ux/releases) よりダウンロード可能です。これらは uxPlayer を同梱しており実行可能となっています。 それ以降の最新リリースでは DLL のみの配布とします。uxPlayer のバイナリダウンロードは[こちらのリポジトリ](//github.com/nanase/uxPlayer)をご参照ください。 ## TODO in v0.3-dev * 音源 - [ ] エフェクト(リバーヴ)の追加 * セレクタ(Selector) - [ ] 新ポリフォニックアルゴリズムの追加 ## 姉妹リポジトリ * [ux++](//github.com/nanase/uxpp) - C++ 実装 * [rbux](//github.com/nanase/rbux) - Ruby 実装 ## 備考 * _ux_ と表記して _Micro Xylph (マイクロシルフ)_ と呼称し、プロジェクト内での表記も `ux` です(TeX のようなものです)。 * 性能を重視するためモノフォニック実装(1パート1音)です。ただし uxMidi でのドラムパートのみ 8 音のポリフォニックです。 * この仕様により大抵の MIDI ファイルは正常に再生できません。特に和音を持っている部分は音が抜けます。 * 音色がとにかく_貧弱_です。これは音源定義XMLファイルに充分な定義が無いためです。 - リポジトリ内の以下のファイルが音源定義XMLファイルです。 + [nanase/ux/uxConsole/ux_preset.xml](//github.com/nanase/ux/blob/v0.2-dev/uxConsole/ux_preset.xml) + [nanase/ux/uxPlayer/ux_preset.xml](//github.com/nanase/ux/blob/v0.2-dev/uxPlayer/ux_preset.xml) - 最新の定義ファイルを Gist に置いています: [gist.github.com/nanase/6068233](//gist.github.com/nanase/6068233) ## 動作確認 * Mono 2.10.8.1 (Linux Mint 14 64 bit) * .NET Framework 4.5 (Windows 7 64 bit) * (内部プロジェクトは互換性を理由に .NET Framework 4.0 をターゲットにしています) ## ライセンス **[MIT ライセンス](//github.com/nanase/ux/blob/v0.2-dev/LICENSE)** Copyright &copy; 2013-2014 Tomona Nanase
nanase/ux
README.md
Markdown
mit
3,064
--- title: L.esri.Layers.TiledMapLayer layout: documentation.hbs --- # {{page.data.title}} Inherits from [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer) Access tiles from ArcGIS Online and ArcGIS Server as well as visualize and identify features. Is you have Feature Services published in ArcGIS Online you can create a static set of tiles using your Feature Service. You can find details about that process in the [ArcGIS Online Help](http://doc.arcgis.com/en/arcgis-online/share-maps/publish-tiles.htm#ESRI_SECTION1_F68FCBD33BD54117B23232D41A762E89) **Your map service must be published using the Web Mercator Auxiliary Sphere tiling scheme (WKID 102100/3857) and the default scale options used by Google Maps, Bing Maps and [ArcGIS Online](http://resources.arcgis.com/en/help/arcgisonline-content/index.html#//011q00000002000000). Esri Leaflet will not support any other spatial reference for tile layers.** ### Constructor <table> <thead> <tr> <th>Constructor</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code class="nobr">L.esri.tiledMapLayer({{{param 'Object' 'options'}}})</code></td> <td>The <code>options</code> parameter can accept the same options as <a href="http://leafletjs.com/reference.html#tilelayer"><code>L.ImageOverlay</code></a>. You also must pass a <code>url</code> key in your <code>options</code>.</td> </tr> </tbody> </table> ### Options `L.esri.TiledMapLayer` also accepts all [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer-options) options. | Option | Type | Default | Description | | --- | --- | --- | --- | `url` | `String` | | *Required* URL of the [Map Service](http://resources.arcgis.com/en/help/arcgis-rest-api/#/Map_Service/02r3000000w2000000) with a tile cache. | `correctZoomLevels` | `Boolean` | `true` | If your tiles were generated in web mercator but at non-standard zoom levels this will remap then to the standard zoom levels. | `zoomOffsetAllowance` | `Number` | `0.1` | If `correctZoomLevels` is enabled this controls the amount of tolerance if the difference at each scale level for remapping tile levels. | `proxy` | `String` | `false` | URL of an [ArcGIS API for JavaScript proxy](https://developers.arcgis.com/javascript/jshelp/ags_proxy.html) or [ArcGIS Resource Proxy](https://github.com/Esri/resource-proxy) to use for proxying POST requests. | | `useCors` | `Boolean` | `true` | Dictates if the service should use CORS when making GET requests. | | `token` | `String` | `null` | Will use this token to authenticate all calls to the service. ### Methods `L.esri.BasemapLayer` inherits all methods from [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer). <table> <thead> <tr> <th>Method</th> <th>Returns</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>authenticate(&lt;String&gt; token)</code></td> <td><code>this</code></td> <td>Authenticates this service with a new token and runs any pending requests that required a token.</td> </tr> <tr> <td><code>metadata(&lt;Function&gt; callback, &lt;Object&gt; context)</code></td> <td><code>this</code></td> <td> Requests metadata about this Feature Layer. Callback will be called with `error` and `metadata`. <pre class="js"><code>featureLayer.metadata(function(error, metadata){ console.log(metadata); });</code></pre> </td> </tr> <tr> <td><code>identify()</code></td> <td><code>this</code></td> <td> Returns a new <a href="/api-reference/tasks/identify-features.html"><code>L.esri.services.IdentifyFeatures</code></a> object that can be used to identify features on this layer. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. <pre class="js"><code>featureLayer.identify() .at(latlng, latlngbounds, 5) .run(function(error, featureCollection){ console.log(featureCollection); });</code></pre> </td> </tr> </tbody> </table> ### Events `L.esri.TiledMapLayer` fires all [`L.TileLayer`](http://leafletjs.com/reference.html#tilelayer) events. ### Example ```js var map = L.map('map').setView([37.7614, -122.3911], 12); L.esri.tiledMapLayer("http://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer", { maxZoom: 15 }).addTo(map); ```
ZhangDubhe/Tropical-Cyclone-Information-System
components/esri-leaflet/site/source/pages/api-reference/layers/tiled-map-layer.md
Markdown
mit
4,575
import time import multiprocessing from flask import Flask app = Flask(__name__) backProc = None def testFun(): print('Starting') while True: time.sleep(3) print('looping') time.sleep(3) print('3 Seconds Later') @app.route('/') def root(): return 'Started a background process with PID ' + str(backProc.pid) + " is running: " + str(backProc.is_alive()) @app.route('/kill') def kill(): backProc.terminate() return 'killed: ' + str(backProc.pid) @app.route('/kill_all') def kill_all(): proc = multiprocessing.active_children() for p in proc: p.terminate() return 'killed all' @app.route('/active') def active(): proc = multiprocessing.active_children() arr = [] for p in proc: print(p.pid) arr.append(p.pid) return str(arr) @app.route('/start') def start(): global backProc backProc = multiprocessing.Process(target=testFun, args=(), daemon=True) backProc.start() return 'started: ' + str(backProc.pid) if __name__ == '__main__': app.run()
wikomega/wikodemo
test.py
Python
mit
1,073
package forscher.nocket.page.gen.ajax; import gengui.annotations.Eager; import java.io.Serializable; public class AjaxTargetUpdateTestInner implements Serializable { private String feld1; private String feld2; public String getEagerFeld1() { return feld1; } @Eager public void setEagerFeld1(String feld1) { this.feld1 = feld1; } public String getFeld2() { return feld2; } public void setFeld2(String feld2) { this.feld2 = feld2; } }
Nocket/nocket
examples/java/forscher/nocket/page/gen/ajax/AjaxTargetUpdateTestInner.java
Java
mit
518
--- layout: single title: Vue와 Firebase로 모던웹사이트 만들기 43 파이어베이스 함수에서 권한 확인하기 category: vf tag: [vue,node,express,vuetify,firebase,vscode] comments: true sidebar: nav: "vf" toc: true toc_label: "목차" toc_icon: "list" --- 파이어베이스 함수(functions)에서 토큰을 확인하고 풀어헤친 토큰정보(claims)로 권한에 따른 결과를 보냅니다. # 영상 {% include video id="x6_Q0GvDu74" provider="youtube" %}
fkkmemi/fkkmemi.github.io
_posts/2019-08-23-vf 043.md
Markdown
mit
489
''' Created by auto_sdk on 2014-12-17 17:22:51 ''' from top.api.base import RestApi class SubusersGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.user_nick = None def getapiname(self): return 'taobao.subusers.get'
CooperLuan/devops.notes
taobao/top/api/rest/SubusersGetRequest.py
Python
mit
303
var textDivTopIndex = -1; /** * Creates a div that contains a textfiled, a plus and a minus button * @param {String | undefined} textContent string to be added to the given new textField as value * @returns new div */ function createTextDiv( textContent ) { textDivTopIndex++; var newTextDiv = document.createElement("DIV"); newTextDiv.className = "inputTextDiv form-group row"; newTextDiv.id = "uriArray"+textDivTopIndex; newTextDiv.setAttribute("index", textDivTopIndex); //newTextDiv.innerHTML = "hasznaltauto.hu url:"; //textfield that asks for a car uri and its align-responsible container var textField = document.createElement("INPUT"); textField.id = uriInputFieldIdPrefix + textDivTopIndex; textField.type = "url"; textField.name = "carUri"+textDivTopIndex; textField.className = "form-control"; textField.placeholder = "hasznaltauto.hu url"; textField.value = (textContent === undefined) ? "" : textContent; //all textfield has it, but there is to be 10 at maximum so the logic overhead would be greater(always the last one should have it) than this efficiency decrease addEvent( textField, "focus", addOnFocus); var textFieldAlignerDiv = document.createElement("DIV"); textFieldAlignerDiv.className = "col-xs-10 col-sm-10 col-sm-10"; textFieldAlignerDiv.appendChild(textField); //add a new input field, or remove current var inputButtonMinus = document.createElement("BUTTON"); inputButtonMinus.className = "btn btn-default btn-sm col-xs-1 col-sm-1 col-md-1 form-control-static"; inputButtonMinus.type = "button"; //avoid submit, which is default for buttons on forms inputButtonMinus.innerHTML = "-"; inputButtonMinus.id = "inputButtonMinus" + textDivTopIndex; newTextDiv.appendChild(textFieldAlignerDiv); newTextDiv.appendChild(inputButtonMinus); currentInputUriCount++; return newTextDiv } function addOnFocus(event) { if ( isLastField(event.target) && currentInputUriCount < 10 ) { var addedTextDiv = createTextDiv(); formElement.insertBefore(addedTextDiv, sendButtonDiv); event.stopPropagation(); } } function isLastField(field) { textDivTopIndex = 0; $(".inputTextDiv").each(function(index) { textDivTopIndex = ( $(this).attr("index") > textDivTopIndex ) ? $(this).attr("index") : textDivTopIndex; }); return textDivTopIndex == field.parentElement.parentElement.getAttribute("index") || currentInputUriCount === 1; }
amdor/skyscraper_fes
DOMBuilder/InputElementBuilder.js
JavaScript
mit
2,501
#pragma once #include "ofMain.h" #include "ofxOsc.h" #include "VHPtriggerArea.h" #include "ofxXmlSettings.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); // variables // Cam ofVideoGrabber vidGrabber; ofTexture videoTexture; ofTexture contrastTexture; ofTexture backgroundTexture; unsigned char * background; unsigned char * pixels; unsigned char * buffer; unsigned char * timeBuffer; int camWidth; int camHeight; int totalPixels; float contrast_e[2]; float contrast_f[2]; float percent; float colorFactor[3]; // triggerArea VHPtriggerArea area; // OSC ofxOscReceiver receiver; // info ofTrueTypeFont font; // settings ofxXmlSettings XML; };
alg-a/herm3TICa
exploracion pruebas y juegos/backgroundSubtraction/src/ofApp.h
C
mit
1,372
using System.Collections.Generic; using System.Text.Json.Serialization; namespace MtgApiManager.Lib.Dto.Set { internal class RootSetListDto : IMtgResponse { [JsonPropertyName("sets")] public List<SetDto> Sets { get; set; } } }
MagicTheGathering/mtg-sdk-dotnet
src/MtgApiManager.Lib/Dto/Set/RootSetListDto.cs
C#
mit
258
--- tags: perl layout: post title: "Chris, meet testing" --- <p>I need to start writing software as if it will be released to lots of people tomorrow :) Interestingly, the potential (up to 90% I'd say) release of OpenInteract has coincided with my first reading of Kent Beck's book <a href="http://www1.fatbrain.com/asp/bookinfo/bookinfo.asp?theisbn=0201616416">Extreme Programming Explained</a>. I know, I'm probably a whole 18 months (meaning: eternity) behind the rest of the software development community, but it's new to me. <p>Anyway, XP places a lot of emphasis on testing, an area where my discipline is sorely lacking. The happy coincidence is that releasing for other people also forces me to write tests, just so they'll know everything at least nominally works. This way, I have an excuse to get in the habit of doing something I should be doing anyway. Happy day! <p>A nice side benefit of the SPOPS DBI tests is that it should be easy to find out whether particular DBD drivers support the necessary <tt>{NAME}</tt> and <tt>{TYPE}</tt> attributes or not. (I think drivers for most 'modern' databases do.) <p>Cleaning up the code (which isn't much of the work) and making it presentable (read: installable by someone other than me) also means that I get to hack around a bit in the <tt>Makefile.PL</tt> and <tt>ExtUtils::MakeMaker</tt> land. Eeek! But it's coming along -- it's done for SPOPS, I just need to figure out how to get a normal script (to install the packages, etc.) to run after 'make install'. This is a very powerful software package, and the perl way is to make easy things easy, so... where's the easy part? (Personally, I don't qualify editing a Makefile as easy, but I can be a little dense sometimes.) <p>The nutty thing is that you can (apparently) use E::MM to create PPM files (for ActivePerl users) and for this you can use the 'PPM_INSTALL_SCRIPT' key to specify a program to run after the package/module is installed. So someone recognized this as a good idea to do. Double eeek! <p><em>(Originally posted <a href="http://www.advogato.org/person/cwinters/diary.html?start=20">elsewhere</a>)</em></p>
cwinters/cwinters.github.io
_posts/2000-09-14-chris_meet_testing.md
Markdown
mit
2,190
# frozen_string_literal: true RSpec.describe Faraday::Response::RaiseError do let(:conn) do Faraday.new do |b| b.response :raise_error b.adapter :test do |stub| stub.get('ok') { [200, { 'Content-Type' => 'text/html' }, '<body></body>'] } stub.get('bad-request') { [400, { 'X-Reason' => 'because' }, 'keep looking'] } stub.get('unauthorized') { [401, { 'X-Reason' => 'because' }, 'keep looking'] } stub.get('forbidden') { [403, { 'X-Reason' => 'because' }, 'keep looking'] } stub.get('not-found') { [404, { 'X-Reason' => 'because' }, 'keep looking'] } stub.get('proxy-error') { [407, { 'X-Reason' => 'because' }, 'keep looking'] } stub.get('conflict') { [409, { 'X-Reason' => 'because' }, 'keep looking'] } stub.get('unprocessable-entity') { [422, { 'X-Reason' => 'because' }, 'keep looking'] } stub.get('4xx') { [499, { 'X-Reason' => 'because' }, 'keep looking'] } stub.get('nil-status') { [nil, { 'X-Reason' => 'nil' }, 'fail'] } stub.get('server-error') { [500, { 'X-Error' => 'bailout' }, 'fail'] } end end end it 'raises no exception for 200 responses' do expect { conn.get('ok') }.not_to raise_error end it 'raises Faraday::BadRequestError for 400 responses' do expect { conn.get('bad-request') }.to raise_error(Faraday::BadRequestError) do |ex| expect(ex.message).to eq('the server responded with status 400') expect(ex.response[:headers]['X-Reason']).to eq('because') expect(ex.response[:status]).to eq(400) expect(ex.response_status).to eq(400) expect(ex.response_body).to eq('keep looking') expect(ex.response_headers['X-Reason']).to eq('because') end end it 'raises Faraday::UnauthorizedError for 401 responses' do expect { conn.get('unauthorized') }.to raise_error(Faraday::UnauthorizedError) do |ex| expect(ex.message).to eq('the server responded with status 401') expect(ex.response[:headers]['X-Reason']).to eq('because') expect(ex.response[:status]).to eq(401) expect(ex.response_status).to eq(401) expect(ex.response_body).to eq('keep looking') expect(ex.response_headers['X-Reason']).to eq('because') end end it 'raises Faraday::ForbiddenError for 403 responses' do expect { conn.get('forbidden') }.to raise_error(Faraday::ForbiddenError) do |ex| expect(ex.message).to eq('the server responded with status 403') expect(ex.response[:headers]['X-Reason']).to eq('because') expect(ex.response[:status]).to eq(403) expect(ex.response_status).to eq(403) expect(ex.response_body).to eq('keep looking') expect(ex.response_headers['X-Reason']).to eq('because') end end it 'raises Faraday::ResourceNotFound for 404 responses' do expect { conn.get('not-found') }.to raise_error(Faraday::ResourceNotFound) do |ex| expect(ex.message).to eq('the server responded with status 404') expect(ex.response[:headers]['X-Reason']).to eq('because') expect(ex.response[:status]).to eq(404) expect(ex.response_status).to eq(404) expect(ex.response_body).to eq('keep looking') expect(ex.response_headers['X-Reason']).to eq('because') end end it 'raises Faraday::ProxyAuthError for 407 responses' do expect { conn.get('proxy-error') }.to raise_error(Faraday::ProxyAuthError) do |ex| expect(ex.message).to eq('407 "Proxy Authentication Required"') expect(ex.response[:headers]['X-Reason']).to eq('because') expect(ex.response[:status]).to eq(407) expect(ex.response_status).to eq(407) expect(ex.response_body).to eq('keep looking') expect(ex.response_headers['X-Reason']).to eq('because') end end it 'raises Faraday::ConflictError for 409 responses' do expect { conn.get('conflict') }.to raise_error(Faraday::ConflictError) do |ex| expect(ex.message).to eq('the server responded with status 409') expect(ex.response[:headers]['X-Reason']).to eq('because') expect(ex.response[:status]).to eq(409) expect(ex.response_status).to eq(409) expect(ex.response_body).to eq('keep looking') expect(ex.response_headers['X-Reason']).to eq('because') end end it 'raises Faraday::UnprocessableEntityError for 422 responses' do expect { conn.get('unprocessable-entity') }.to raise_error(Faraday::UnprocessableEntityError) do |ex| expect(ex.message).to eq('the server responded with status 422') expect(ex.response[:headers]['X-Reason']).to eq('because') expect(ex.response[:status]).to eq(422) expect(ex.response_status).to eq(422) expect(ex.response_body).to eq('keep looking') expect(ex.response_headers['X-Reason']).to eq('because') end end it 'raises Faraday::NilStatusError for nil status in response' do expect { conn.get('nil-status') }.to raise_error(Faraday::NilStatusError) do |ex| expect(ex.message).to eq('http status could not be derived from the server response') expect(ex.response[:headers]['X-Reason']).to eq('nil') expect(ex.response[:status]).to be_nil expect(ex.response_status).to be_nil expect(ex.response_body).to eq('fail') expect(ex.response_headers['X-Reason']).to eq('nil') end end it 'raises Faraday::ClientError for other 4xx responses' do expect { conn.get('4xx') }.to raise_error(Faraday::ClientError) do |ex| expect(ex.message).to eq('the server responded with status 499') expect(ex.response[:headers]['X-Reason']).to eq('because') expect(ex.response[:status]).to eq(499) expect(ex.response_status).to eq(499) expect(ex.response_body).to eq('keep looking') expect(ex.response_headers['X-Reason']).to eq('because') end end it 'raises Faraday::ServerError for 500 responses' do expect { conn.get('server-error') }.to raise_error(Faraday::ServerError) do |ex| expect(ex.message).to eq('the server responded with status 500') expect(ex.response[:headers]['X-Error']).to eq('bailout') expect(ex.response[:status]).to eq(500) expect(ex.response_status).to eq(500) expect(ex.response_body).to eq('fail') expect(ex.response_headers['X-Error']).to eq('bailout') end end describe 'request info' do let(:conn) do Faraday.new do |b| b.response :raise_error b.adapter :test do |stub| stub.post(url, request_body, request_headers) do [400, { 'X-Reason' => 'because' }, 'keep looking'] end end end end let(:request_body) { JSON.generate({ 'item' => 'sth' }) } let(:request_headers) { { 'Authorization' => 'Basic 123' } } let(:url_path) { 'request' } let(:query_params) { 'full=true' } let(:url) { "#{url_path}?#{query_params}" } subject(:perform_request) do conn.post url do |req| req.headers['Authorization'] = 'Basic 123' req.body = request_body end end it 'returns the request info in the exception' do expect { perform_request }.to raise_error(Faraday::BadRequestError) do |ex| expect(ex.response[:request][:method]).to eq(:post) expect(ex.response[:request][:url]).to eq(URI("http:/#{url}")) expect(ex.response[:request][:url_path]).to eq("/#{url_path}") expect(ex.response[:request][:params]).to eq({ 'full' => 'true' }) expect(ex.response[:request][:headers]).to match(a_hash_including(request_headers)) expect(ex.response[:request][:body]).to eq(request_body) end end end end
lostisland/faraday
spec/faraday/response/raise_error_spec.rb
Ruby
mit
7,602
class CreateBudgetsUsers < ActiveRecord::Migration def change create_table :budgets_users do |t| t.integer :user_id t.integer :budget_id t.timestamps end end end
FAMM/manatee
db/migrate/20140311222555_create_budgets_users.rb
Ruby
mit
193
package org.anodyneos.xp.tagext; import javax.servlet.jsp.el.ELException; import org.anodyneos.xp.XpContext; import org.anodyneos.xp.XpException; import org.anodyneos.xp.XpOutput; import org.xml.sax.SAXException; /** * @author jvas */ public interface XpTag { void doTag(XpOutput out) throws XpException, ELException, SAXException; XpTag getParent(); void setXpBody(XpFragment xpBody); void setXpContext(XpContext xpc); void setParent(XpTag parent); }
jvasileff/aos-xp
src.java/org/anodyneos/xp/tagext/XpTag.java
Java
mit
480
'use strict'; /** * Stripe library * * @module core/lib/c_l_stripe * @license MIT * @copyright 2016 Chris Turnbull <https://github.com/christurnbull> */ module.exports = function(app, db, lib) { return { /** * Donate */ donate: function(inObj, cb) { var number, expiry, cvc, currency; try { number = parseInt(inObj.body.number); var exp = inObj.body.expiry.split('/'); expiry = { month: parseInt(exp[0]), year: parseInt(exp[1]) }; cvc = parseInt(inObj.body.cvc); currency = inObj.body.currency.toLowerCase(); } catch (e) { return cb([{ msg: 'Invalid details.', desc: 'Payment has not been made' }], null); } // stripe supported zero-decimal currencies var zeroDecimal = { BIF: 'Burundian Franc', CLP: 'Chilean Peso', DJF: 'Djiboutian Franc', GNF: 'Guinean Franc', JPY: 'Japanese Yen', KMF: 'Comorian Franc', KRW: 'South Korean Won', MGA: 'Malagasy Ariary', PYG: 'Paraguayan Guaraní', RWF: 'Rwandan Franc', VND: 'Vietnamese Đồng', VUV: 'Vanuatu Vatu', XAF: 'Central African Cfa Franc', XOF: 'West African Cfa Franc', XPF: 'Cfp Franc' }; var amount = inObj.body.amount; if (!zeroDecimal.hasOwnProperty(currency.toUpperCase())) { // all other supoprted currencies are decimal amount = amount * 100; } var stripeData = { amount: amount, currency: currency.toLowerCase(), description: 'Donation from ' + inObj.body.name, source: { number: number, exp_month: expiry.month, exp_year: expiry.year, cvc: cvc, object: 'card', customer: inObj.body.customer, email: inObj.body.email } }; lib.core.stripe.charges.create(stripeData, function(err, charge) { if (err) { return cb(err, null); } // save to database etc... return cb(null, [charge]); }); } }; };
christurnbull/MEANr-api
src/core/lib/c_l_stripePay.js
JavaScript
mit
2,158
using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Xunit; namespace MR.AspNetCore.Jobs.Server { public class InfiniteRetryProcessorTest { [Fact] public async Task Process_ThrowingProcessingCanceledException_Returns() { // Arrange var services = new ServiceCollection(); services.AddLogging(); var loggerFactory = services.BuildServiceProvider().GetService<ILoggerFactory>(); var inner = new ThrowsProcessingCanceledExceptionProcessor(); var p = new InfiniteRetryProcessor(inner, loggerFactory); var context = new ProcessingContext(); // Act await p.ProcessAsync(context); } private class ThrowsProcessingCanceledExceptionProcessor : IProcessor { public Task ProcessAsync(ProcessingContext context) { throw new OperationCanceledException(); } } } }
mrahhal/MR.AspNetCore.Jobs
test/MR.AspNetCore.Jobs.Tests/Server/InfiniteRetryProcessorTest.cs
C#
mit
891
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct _notify_raceboss_cry_msg_request_zocl { char wszCryMsg[10][65]; }; END_ATF_NAMESPACE
goodwinxp/Yorozuya
library/ATF/_notify_raceboss_cry_msg_request_zocl.hpp
C++
mit
284
/* artifact generator: C:\My\wizzi\v5\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js primary source IttfDocument: c:\my\wizzi\v5\plugins\wizzi-core\src\ittf\root\legacy.js.ittf */ 'use strict'; module.exports = require('wizzi-legacy-v4');
wizzifactory/wizzi-core
legacy.js
JavaScript
mit
259
--- title: "Puppet" description: "Deregister Sensu clients from the client registry if they no longer have an associated Puppet node." version: 1.0 weight: 12 --- **ENTERPRISE: Built-in integrations are available for [Sensu Enterprise][1] users only.** # Puppet Integration - [Overview](#overview) - [Configuration](#configuration) - [Example(s)](#examples) - [Integration Specification](#integration-specification) - [`puppet` attributes](#puppet-attributes) - [`ssl` attributes](#ssl-attributes) ## Overview Deregister Sensu clients from the client registry if they no longer have an associated [Puppet][2] node. The `puppet` enterprise handler requires access to a SSL truststore and keystore, containing a valid (and whitelisted) Puppet certificate, private key, and CA. The local Puppet agent certificate, private key, and CA can be used. ## Configuration ### Example(s) The following is an example global configuration for the `puppet` enterprise handler (integration). ~~~ json { "puppet": { "endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/", "ssl": { "keystore_file": "/etc/sensu/ssl/puppet/keystore.jks", "keystore_password": "secret", "truststore_file": "/etc/sensu/ssl/puppet/truststore.jks", "truststore_password": "secret" }, "timeout": 10 } } ~~~ The Puppet enterprise handler is most commonly used as part of the `keepalive` set handler. For example: ~~~ json { "handlers": { "keepalive": { "type": "set", "handlers": [ "pagerduty", "puppet" ] } } } ~~~ When querying PuppetDB for a node, by default, Sensu will use the Sensu client's name for the Puppet node name. Individual Sensu clients can override the name of their corresponding Puppet node, using specific client definition attributes. The following is an example client definition, specifying its Puppet node name. ~~~ json { "client": { "name": "i-424242", "address": "8.8.8.8", "subscriptions": [ "production", "webserver" ], "puppet": { "node_name": "webserver01.example.com" } } } ~~~ ### Integration Specification _NOTE: the following integration definition attributes may be overwritten by the corresponding Sensu [client definition `puppet` attributes][3], which are included in [event data][4]._ #### `puppet` attributes The following attributes are configured within the `{"puppet": {} }` [configuration scope][5]. `endpoint` : description : The PuppetDB API endpoint (URL). If an API path is not specified, `/pdb/query/v4/nodes/` will be used. : required : true : type : String : example : ~~~ shell "endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/" ~~~ `ssl` : description : A set of attributes that configure SSL for PuppetDB API queries. : required : true : type : Hash : example : ~~~ shell "ssl": {} ~~~ #### `ssl` attributes The following attributes are configured within the `{"puppet": { "ssl": {} } }` [configuration scope][3]. ##### EXAMPLE {#ssl-attributes-example} ~~~ json { "puppet": { "endpoint": "https://10.0.1.12:8081/pdb/query/v4/nodes/", "...": "...", "ssl": { "keystore_file": "/etc/sensu/ssl/puppet/keystore.jks", "keystore_password": "secret", "truststore_file": "/etc/sensu/ssl/puppet/truststore.jks", "truststore_password": "secret" } } } ~~~ ##### ATTRIBUTES {#ssl-attributes-specification} `keystore_file` : description : The file path for the SSL certificate keystore. : required : true : type : String : example : ~~~ shell "keystore_file": "/etc/sensu/ssl/puppet/keystore.jks" ~~~ `keystore_password` : description : The SSL certificate keystore password. : required : true : type : String : example : ~~~ shell "keystore_password": "secret" ~~~ `truststore_file` : description : The file path for the SSL certificate truststore. : required : true : type : String : example : ~~~ shell "truststore_file": "/etc/sensu/ssl/puppet/truststore.jks" ~~~ `truststore_password` : description : The SSL certificate truststore password. : required : true : type : String : example : ~~~ shell "truststore_password": "secret" ~~~ [?]: # [1]: /enterprise [2]: https://puppet.com?ref=sensu-enterprise [3]: ../../reference/clients.html#puppet-attributes [4]: ../../reference/events.html#event-data [5]: ../../reference/configuration.html#configuration-scopes
palourde/sensu-docs
docs/1.0/enterprise/integrations/puppet.md
Markdown
mit
4,504
#!/bin/env node 'use strict'; var winston = require('winston'), path = require('path'), mcapi = require('mailchimp-api'), Parser = require('./lib/parser'), ApiWrapper = require('./lib/api-wrapper'); var date = new Date(); date = date.toJSON().replace(/(-|:)/g, '.'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level: 'silly'}); winston.add(winston.transports.File, { filename: path.join('./', 'logs', 'sxla' + date + '.log'), level: 'silly', timestamp: true }); winston.info('*********** APPLICATION STARTED ***********'); var apiKey = process.env.MAILCHIMP_SXLA_API_KEY; var listId = process.env.MAILCHIMP_SXLA_LIST_ID; winston.debug('apiKey: ', apiKey); winston.debug('listId: ', listId); var api = new ApiWrapper(mcapi, apiKey, listId, winston); var parser = new Parser(winston); parser.parseCsv(__dirname + '/data/soci14-15.csv', function (data) { api.batchSubscribe(data); });
napcoder/sxla-mailchimp-importer
app.js
JavaScript
mit
959
+++ hook = "A list of the best podcasts that I'm listening to this year." published_at = 2016-08-28T01:13:48Z title = "Podcasts 2016" +++ After moving to the big city, I've spent a lot more time on foot over the past few years. I eventually picked up another habit that pairs with walking perfectly: podcasts. As of 2016, here are my favorites: * [Common Sense][common-sense]: Dan Carlin on the American political system. Dan takes the side of neither party, but comments on them from the outside in a very informed way. He has the incredible gift to be able to speak for hours in a way that's hugely information-dense. No co-host required. * [Hardcore History][hardcore-history]: Dan Carlin's podcast on history, and maybe _the_ best podcast that's out there right now. Dan's impassioned approach to the subject makes every episode great. In particular, check on the series on the fall of the Roman republic and the exploits of Genghis Khan. * [Road Work][road-work]: John Roderick (a musician) and Dan Benjamin (a podcaster) talk about things. I know that doesn't sound very interesting, but Roderick has a way with words and is one of the world's great story tellers. * [Waking Up with Sam Harris][waking-up]: Sam Harris is best known for his atheism, but only because that's his most controversial pursuit. He's a great thinker in general, and the most articulate person that you'll ever hear. Topics range from current events, society, or interviews with various intellectuals, and as you'd expect, a healthy dose of criticism on religious radicalism. And some others that deserve mention: * [8-4 Play][8-4-play]: Focuses on recent developments in gaming, specifically in Japan. I don't play many video games anymore, but I still find it fascinating. * [99% Invisible][99-invisible]: A podcast on architecture and design that manages to drudge up original material that's as interesting as it is obscure. * [The Bike Shed][bike-shed]: Titled with a concept that every programmer will know well, this one is unsurprisingly about -- software. Episode quality is variable, but there's occasionally some great content on advanced topics like Rust and ORM internals. * [Planet Money][planet-money]: These guys really have a real knack for making economics interesting. Its major weakness is that it never trackles a subject in depth. * [Radiolab][radiolab]: Covers scientific subjects and comes with good interviews and some great sound editing. It's only downside is that the hosts have a bad habit of brushing up against the realm of pseudo-science. * [Roderick on the Line][roderick]: A slight variation of _Road Work_ above, this one is John Roderick and Merlin Mann talking about things. Recent episodes have been a little lackluster, but comb through the backlog for some incredible stories. * [Song Exploder][song-exploder]: The best edited podcast on the list; breaks down popular songs and has their composer talk through the thinking and process that went into their creation. For best results, check the back catalog for songs that you like. [8-4-play]: https://overcast.fm/itunes393557569/8-4-play [99-invisible]:https://overcast.fm/itunes394775318/99-invisible [bike-shed]: https://overcast.fm/itunes935763119/the-bike-shed [common-sense]: https://overcast.fm/itunes155974141/common-sense-with-dan-carlin [hardcore-history]: https://overcast.fm/itunes173001861/dan-carlins-hardcore-history [planet-money]: https://overcast.fm/itunes290783428/planet-money [radiolab]: https://overcast.fm/itunes152249110/radiolab [road-work]: https://overcast.fm/itunes1030602911/road-work [roderick]: https://overcast.fm/itunes471418144/roderick-on-the-line [song-exploder]: https://overcast.fm/itunes788236947/song-exploder [waking-up]: https://overcast.fm/itunes733163012/waking-up-with-sam-harris
brandur/sorg
content/fragments/podcasts-2016.md
Markdown
mit
3,865
module.exports = { normalizeEntityName: function() {}, afterInstall: function() { this.addBowerPackageToProject('jsoneditor'); } };
jayphelps/ember-jsoneditor
blueprints/ember-jsoneditor/index.js
JavaScript
mit
143
# Wiper Wiper allows you to recursively delete specified folders. Say that you want to delete all 'obj' folders in a certain root folder. Type in 'obj' as the folder name to delete and select the root folder. Perform a dry run to list all folders that will be affected. Hit the delete button and you're done!
icerocker/Wiper
README.md
Markdown
mit
310
import AMD from '../../amd/src/amd.e6'; import Core from '../../core/src/core.e6'; import Event from '../../event/src/event.e6'; import Detect from '../../detect/src/detect.e6'; import Module from '../../modules/src/base.es6'; import ModulesApi from '../../modules/src/api.e6'; window.Moff = new Core(); window.Moff.amd = new AMD(); window.Moff.event = new Event(); window.Moff.Module = new Module(); window.Moff.detect = new Detect(); window.Moff.modules = new ModulesApi();
kfuzaylov/moff
packages/loader/src/loader.e6.js
JavaScript
mit
477
<html><body> <h4>Windows 10 x64 (19042.610)</h4><br> <h2>_PNP_DEVICE_DELETE_TYPE</h2> <font face="arial"> QueryRemoveDevice = 0n0<br> CancelRemoveDevice = 0n1<br> RemoveDevice = 0n2<br> SurpriseRemoveDevice = 0n3<br> EjectDevice = 0n4<br> RemoveFailedDevice = 0n5<br> RemoveUnstartedFailedDevice = 0n6<br> MaxDeviceDeleteType = 0n7<br> </font></body></html>
epikcraw/ggool
public/Windows 10 x64 (19042.610)/_PNP_DEVICE_DELETE_TYPE.html
HTML
mit
391
--- archive: tag layout: archive permalink: /tag/Simpsons/ tag: Simpsons title: Archive for Simpsons ---
goodevilgenius/pile
archives/tag-Simpsons.html
HTML
mit
106
# == Schema Information # # Table name: templates # # id :integer not null, primary key # name :string # image :string # description :text # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe Template, type: :model do describe "relationships" do it { should have_many(:cards).dependent(:restrict_with_error) } end describe "validators" do it { should validate_presence_of(:name) } it { should validate_presence_of(:image) } end end
abarrak/card-mine-api
spec/models/template_spec.rb
Ruby
mit
561
namespace RapidFTP.Chilkat.Tests.Utilities { using System.Diagnostics; using RapidFTP.Models; using RapidFTP.Utilities; using Xunit; using Xunit.Extensions; public class UnixPathTest { [InlineData("/lv1", 1)] [InlineData("/lv1/lv2", 2)] [InlineData("/lv1/lv2/", 2)] [InlineData("/lv1/lv2/lv3", 3)] [InlineData("/lv1/lv2/lv3/lv4", 4)] [InlineData("/lv1/lv2/lv3/lv4/lv5", 5)] [Theory] public void GetRelatedDirectories_GivenPath_ShouldSuccess(string path, int length) { var relatedDirectories = UnixPath.GetRelatedDirectories(path); Assert.Equal(length, relatedDirectories.Length); foreach (var directory in relatedDirectories) { Trace.WriteLine(directory); } } [InlineData("/", true)] [InlineData("/lv1", true)] [InlineData("/lv1/lv2", true)] [InlineData("/lv1/lv2/", true)] [InlineData("/lv1/lv2/lv_3", true)] [InlineData("/lv1/lv2/lv-3", true)] [InlineData("lv1", false)] [InlineData("lv1/lv2", false)] [InlineData("", false)] [InlineData("/lv1/*", false)] [Theory] public void IsWellFormed(string path, bool expected) { var result = UnixPath.IsWellFormed(path, ItemType.Directory); Assert.Equal(expected, result); } } }
khoale/RapidFTP
src/RapidFTP.Chilkat.Tests/Utilities/UnixPathTest.cs
C#
mit
1,453
package org.real2space.neumann.evaris.core.structure; /** * Project Neumann * * @author RealTwo-Space * @version 0 * * created 2016/11/01 * added "extends Ring<F>" 2016/11/9 */ public interface Field<F> extends Ring<F> { /* * Multiply this member by an inverse of "other". */ public void divide (F other); /* * Returns an inverse of this member. */ public F inverse (); }
RealTwo-Space/Neumann
neumann/src/org/real2space/neumann/evaris/core/structure/Field.java
Java
mit
426
# coding: utf-8 import unittest from config_reader import ConfigReader class TestConfigReader(unittest.TestCase): def setUp(self): self.config = ConfigReader(""" <root> <person> <name>山田</name> <age>15</age> </person> <person> <name>佐藤</name> <age>43</age> </person> </root> """) def test_get_names(self): self.assertEqual(self.config.get_names(), ['山田', '佐藤']) def test_get_ages(self): self.assertEqual(self.config.get_ages(), ['15', '43'])
orangain/jenkins-docker-sample
tests.py
Python
mit
681
# project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertIn(b"Logout", response.data) self.assertIn(b"Members", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"You were logged out. Bye!", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get("/logout", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get("/members", follow_redirects=True) self.assertIn(b"Please log in to access this page", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email="[email protected]", password="admin_user") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email="unknown", password="example") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( "/login", data=dict(email="[email protected]", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="[email protected]").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email="[email protected]").first() self.assertTrue( bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( "/login", data=dict(email="[email protected]", password="foo_bar"), follow_redirects=True, ) self.assertIn(b"Invalid email and/or password.", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get("/register", follow_redirects=True) self.assertIn(b"<h1>Register</h1>\n", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( "/register", data=dict( email="[email protected]", password="testing", confirm="testing", ), follow_redirects=True, ) self.assertIn(b"Welcome", response.data) self.assertTrue(current_user.email == "[email protected]") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == "__main__": unittest.main()
realpython/flask-skeleton
{{cookiecutter.app_slug}}/project/tests/test_user.py
Python
mit
4,811
inside = lambda x, y: 4*x*x+y*y <= 100 def coll(sx, sy, dx, dy): m = 0 for p in range(32): m2 = m + 2**(-p) if inside(sx + dx * m2, sy + dy * m2): m = m2 return (sx + dx*m, sy + dy*m) def norm(x, y): l = (x*x + y*y)**0.5 return (x/l, y/l) sx, sy = 0, 10.1 dx, dy = 1.4, -19.7 for I in range(999): sx, sy = coll(sx, sy, dx, dy) if sy > 0 and abs(sx) <= 0.01: print(I) break mx, my = norm(1, -4*sx/sy) d = mx*dx + my*dy dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d
jokkebk/euler
p144.py
Python
mit
538
# Git Back Control of Your Code ## A Simple and Straightforward Workflow for Working with Git and Github Becoming a better developer is about finding the process and workflow that works best for you and the rest of the team. I believe that version control is something all developers should use. Specifically, I think that git is a great option. There can be a bit of a learning curve with version control, but once you start using it, it becomes essential. If you are looking for a more interactive approach to learning git, then [give Try Git a shot](http://try.github.com/). *This post is a follow-up to [a presentation I gave](http://www.gristmill.io/workshops/3-git-back-control-of-your-code-learning-how-to-manage-your-code-with-git-github) on using Git and Github. Going through [the slides](http://brettchalupa.github.com/git-presentation/) should give you a quick overview of what was covered. This post is meant to take it one step further for those who could not attend.* ## Why use version control? The first question you are probably asking yourself is, "Why even use version control? I've got Dropbox! That's my version control." Getouttahere. Dropbox isn't version control. It's hosting for backups with somewhat deep OS integration. It's a good tool, but it's not a tool that should be used for managing your project's code. Developers should be using version control because: * Keeps a track-record of all of the changes you have ever made, ever * Allows for collaboration with other developers without stepping on toes * Provides a form of back-up by hosting a repository on another server, whether it is on the web or locally It's essential to programming. Working in an environment without version control is terrifying. ## Why use git? The next logic question is why use git? What about subversion or mercurial? Use whatever fits your needs the best. Version control systems, IDEs, and code libraries are tools. They are supposed to make your life easier. Use what you are most comfortable with. Use the tool best for the job. Use whatever it is that will help you become a better developer. It's up to you. Here are the reasons why I prefer to use git: 1. Github. This may be a strange reason, but Github is a reason why I use git. 2. The strong community and vast amount of resources. 3. The fact that [it is a distributed version control system](http://www.joelonsoftware.com/items/2010/03/17.html). If git isn't for you or you prefer another type of version control, then that's totally fine. ## Why use Github? There are a few options for git hosting out on the web. The two most common are probably [GitHub](http://github.com) and [Bitbucket](http://bitbucket.org). The two are very similar in terms of their features (Bitbucket also supports Mercurial, another distributed version control system). The major difference between the two is that Bitbucket allows for free private and public repositories. GitHub only allows for free public repositories. What this means is that if you want to host private projects on GitHub, then you need to pay money. If that's not for you or you can't afford it, then use Bitbucket. Most of this guide applies for use with Bitbucket or GitHub. That being said, I prefer to use GitHub over Bitbucket because: * Pull Requests - GitHub simply handles pull requests in a much nicer fashion, allowing people to comment on specific files in a commit or just on the pull request in general. * The [help section](http://help.github.com) is super useful. It's well written, organized, and more than enough to get anyone going. * [Gists](http://gist.github.com) - paste snippets of code publically or privately with features like comments and forking. Moral of the story, try both out and see what works for you. ## Useful Terminal Commands This guide should really be called *Using git and Github (with the terminal)*. That's the core of this guide - using the terminal. Whether it is msysgit on Windows or Terminal for Unix users, we will be using commands the entire time. Beginning to use the terminal can be a daunting task. The nice thing is, there is only about a handful of commands you'll use daily. Once you get the hang of those, the workflow starts to make sense. Here are a few of the most common commands you'll use when working with the terminal. * `pwd` - print working directory a.k.a. where am I? * `ls` - list files and directories in current directory a.k.a. what do we have here? * `cd path/to/location` - change directory * `touch path/to/file.rb` - create a file * `mkdir path/to/directory` - create a directory * `rm path/to/file.rb` - remove a specific file ### Flags Flags are little extra magical parameters you can pass in with terminal commands. They're pretty useful, and as you explore and research, you will continue to discover more. * `-a` - show all * `ls -a` - show all files in the current directory, not hidden and hidden * `git branch -a` - show all of the local and remote branches for the current git repository * `-v` - show the current version of anything * `ruby -v` - display the current version of Ruby installed * `-h` or `--help` - list the flag options of the command you're running, when in doubt run -h ## Setting up git [Follow this guide.](http://help.github.com/) That's it. Really. Github's guide on getting started with git on Windows, Mac, or Linux is precise and the best resource out there. help.github.com will be your best friend while you learn to use git and Github (and even when you continue to use it). ## Adding to the Codebase To start off, if you haven't already, you need to clone the project: `git clone [email protected]:projectowner/project-name.git` After the project is done cloning, change your directory to the project: `cd project_name` Once you've changed directories, you're almost ready to code. Next up is to make sure you're on the proper branch. To see what branch you are on, use the following: `git branch` If you're on master branch, there's probably a problem. You need to change branches or create a new one. Let's assume you need to create a new one. Please do the following command (where bc is your initials, this makes identifying who is working on what branch much easier): `git branch bc/branch_name` If you were to do `git branch` again, you'd see your new branch! To switch to that branch, simply do the following: `git checkout bc/branch_name` If you're feeling really snazzy, you can create a branch and switch to it at the same time by running: `git checkout -b bc/branch_name` Now you're ready to code! Once you're all done (or you think you're done), go ahead and add those changes. First, to see what changes have been made, simply do: `git status` You'll see any of the files you've added, changed, or removed. The most basic and quick command to add your changes to a commit is: `git add .` This will add of your new files and changes to the commit. To delete files, all you need to do is the following command: `git rm file.rb` If you delete your files a different way, you still need to run the command above to make git aware of the changes. If you erase a lot of files at once, here is a helpful command to make git aware of the changes: `git add -u` Once you've staged all of your changes to your commit, go ahead and make that commit! `git commit -m "Your commit message!"` Wow, great job! You're almost there. Next, all you need to do is push those commits to the remote repository on Github, and you're a git wizard. `git push origin bc/branch_name` ## Merging Branches You've created a branch, made some changes, saved those changes, and pushed them to your branch on the repository on Github. Now you think you're done coding your feature and you're ready to merge your branch into the master branch (or development branch depending on your structure). Now just hold your goddamned horses for a minute. Before you merge to master, you need to open a pull request. To do such a thing, navigate to your branch on the project in Github. Above all of the code on the upper-right, you will see a little button that says "Pull Request". Click that bad boy to open a pull request. Once you've opened a pull request, everyone will be notified via email (if they have that setting on) and a Github notification. What happens next is out of your hands for a little while. At least one other programmer needs to go through your code and make sure it's up to snuff. Make sure it's properly commented, it makes sense, and there is no [code smell](http://en.wikipedia.org/wiki/Code_smell). If there are some problems, expect them to leave some comments where the problems lie. You need to go through the code, make your changes, commit those changes, and push them again. How you and your team handle pull requests is up to you. In my opinion, it's best practice to have *at least* one other person review your code. Once they give you an _LGPA_ or a _Looks Good, Pull Away!_, you're ready to close & merge the Pull Request. Click the little button at the bottom of the pull request, and you're almost ready to start working on your next feature. You've got to remember to clean up though. Switch to your development or master branch: `git checkout master` Now go ahead and delete your local branch: `git branch -d bc/branch_name` Next you've got to delete your branch on Github: `git push origin :bc/branch_name` A few last steps and you've merged your first feature into the codebase. You've got to pull from the master branch on Github to get the lastest changes from the Pull Request merge: `git pull origin master` Now you're done merging you're branch. You've cleaned up and got your latest changes from the merge. Start the whole process over from the beginning and code away. *It's worth noting that this is probably a lazy approach to handling merges. [There's a ton of discussion on this topic and the proper ways to do it.](http://longair.net/blog/2009/04/16/git-fetch-and-merge/)* ## Other Useful git Commands There is a lot more to git than what was covered in this document. As everyone uses tools more and more, there is a hope to continue to learn more about that tool. As I learn more, I will be updating this with other important git commands and concepts. ### Rebase If you're on the branch `bc/current_working_branch` and you want to make sure you're not going to have merge commits, you'll want to rebase often. First, run: `git fetch origin master` Then, run: `git rebase origin/master` This will put your commits on top of the latest `origin/master` commit. This will not update your local master branch, so be advised. If you want to do an interactive rebase, it's the same process except that you say `git rebase -i origin/master`. I usually do a regular rebase before I do an interactive rebase so I can go ahead and fix any conflicts without the added confusion of an interactive rebase. ### Reset If you mess up and want to go back a commit (or even more), simply do: `git reset --hard HEAD~1` The `HEAD~1` means ONE commit before head. If you wanted to do FOUR commits before the head, simply do `HEAD~4` Or, you could look at the output of git log, find the commit id of the commit you want to back up to, and then do this: `git reset --hard <sha1-commit-id>` If you already pushed it, you will need to do a force push to get rid of it: `git push origin HEAD --force` ### Stashing Changes If you're ever working on code and need to store or **stash** your changes for later, there is a command for that. Run the following command to safely stash your changes in current branch away. `git stash` When you're ready to have those changes back, you can run: `git stash pop` Stashing is useful if two people are working on the same branch at the same time. If person A has made some code changes and person B has as well there may be some conflicts. Person A most likely wants to get the changes person B made, so if person A stashes their current changes and pulls from the branch then pops the stash, person A's changes will be reflected with person B's changes. ## Additional Resources * [git Homepage](http://git-scm.com/) * [git cheat sheet by TOWER](http://www.git-tower.com/files/cheatsheet/Git_Cheat_Sheet_grey.pdf) * [Try Git](http://try.github.com/)
brettchalupa/git-presentation
README.md
Markdown
mit
12,333
// // main.c // demo14 // // Created by weichen on 15/1/9. // Copyright (c) 2015年 weichen. All rights reserved. // #include <stdio.h> int main() { // 求输入的数的平均数,并输出大于平均数的数字 int x = 0; //输入的数 double num = 0; //总和(这个定义为double, 因为计算结果可能出现浮点数) int count = 0; //个数 double per; //平均数(结果也定义double) printf("请输入一些数:"); scanf("%d", &x); //不等于0时执行累计;输入等于0的值,来终止循环,并执行后面的代码 while(x != 0) { num += x; count++; scanf("%d", &x); } if(count > 0) { per = num / count; printf("%f \n", per); } return 0; }
farwish/Clang-foundation
demo14/demo14/main.c
C
mit
841
--- layout: default description: "你来到了没有知识的荒原 🙊" header-img: "img/404-bg.jpg" permalink: /404.html --- <!-- Page Header --> <header class="intro-header" style="background-image: url('{{ site.baseurl }}/{% if page.header-img %}{{ page.header-img }}{% else %}{{ site.header-img }}{% endif %}')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="site-heading" id="tag-heading"> <h1>404</h1> <span class="subheading">{{ page.description }}</span> </div> </div> </div> </div> </header> <script> document.body.classList.add('page-fullscreen'); </script>
xuepro/xuepro.github.io
404.html
HTML
mit
702
<!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/html; charset=utf-8" /> <title>Plugwise implementation: energykit.plugwise &mdash; EnergyKit 0.1.0 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.1.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="top" title="EnergyKit 0.1.0 documentation" href="index.html" /> <link rel="prev" title="Fake data implementation: energykit.fake" href="energykit.fake.html" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="energykit.fake.html" title="Fake data implementation: energykit.fake" accesskey="P">previous</a> |</li> <li><a href="index.html">EnergyKit 0.1.0 documentation</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="module-energykit.plugwise"> <span id="plugwise-implementation-energykit-plugwise"></span><h1>Plugwise implementation: <a class="reference internal" href="#module-energykit.plugwise" title="energykit.plugwise"><tt class="xref py py-mod docutils literal"><span class="pre">energykit.plugwise</span></tt></a><a class="headerlink" href="#module-energykit.plugwise" title="Permalink to this headline">¶</a></h1> <span class="target" id="module-energykit.plugwise.datasource"></span><dl class="class"> <dt id="energykit.plugwise.datasource.DataSource"> <em class="property">class </em><tt class="descclassname">energykit.plugwise.datasource.</tt><tt class="descname">DataSource</tt><a class="reference internal" href="_modules/energykit/plugwise/datasource.html#DataSource"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#energykit.plugwise.datasource.DataSource" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="energykit.html#energykit.datasource.DataSource" title="energykit.datasource.DataSource"><tt class="xref py py-class docutils literal"><span class="pre">energykit.datasource.DataSource</span></tt></a>, <a class="reference internal" href="energykit.html#energykit.pubsub.PubSub" title="energykit.pubsub.PubSub"><tt class="xref py py-class docutils literal"><span class="pre">energykit.pubsub.PubSub</span></tt></a></p> </dd></dl> <span class="target" id="module-energykit.plugwise.datastream"></span><dl class="class"> <dt id="energykit.plugwise.datastream.DataStream"> <em class="property">class </em><tt class="descclassname">energykit.plugwise.datastream.</tt><tt class="descname">DataStream</tt><big>(</big><em>source</em>, <em>key</em>, <em>type=0</em><big>)</big><a class="reference internal" href="_modules/energykit/plugwise/datastream.html#DataStream"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#energykit.plugwise.datastream.DataStream" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="energykit.html#energykit.datastream.DataStream" title="energykit.datastream.DataStream"><tt class="xref py py-class docutils literal"><span class="pre">energykit.datastream.DataStream</span></tt></a></p> </dd></dl> <span class="target" id="module-energykit.plugwise.datainterval"></span><dl class="class"> <dt id="energykit.plugwise.datainterval.DataInterval"> <em class="property">class </em><tt class="descclassname">energykit.plugwise.datainterval.</tt><tt class="descname">DataInterval</tt><big>(</big><em>stream</em>, <em>start_time=None</em>, <em>end_time=None</em><big>)</big><a class="reference internal" href="_modules/energykit/plugwise/datainterval.html#DataInterval"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#energykit.plugwise.datainterval.DataInterval" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="energykit.html#energykit.datainterval.DataInterval" title="energykit.datainterval.DataInterval"><tt class="xref py py-class docutils literal"><span class="pre">energykit.datainterval.DataInterval</span></tt></a></p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="energykit.fake.html" title="previous chapter">Fake data implementation: <tt class="docutils literal"><span class="pre">energykit.fake</span></tt></a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/energykit.plugwise.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="energykit.fake.html" title="Fake data implementation: energykit.fake" >previous</a> |</li> <li><a href="index.html">EnergyKit 0.1.0 documentation</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2013, Sander Dijkhuis, Interactive Institute. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2b1. </div> </body> </html>
interactiveinstitute/watthappened
docs/_build/html/energykit.plugwise.html
HTML
mit
7,038
/** * Module dependencies */ const express = require('express'); const cluster = require('cluster'); const numCPUs = require('os').cpus().length; const compression = require('compression'); const helmet = require('helmet'); const hpp = require('hpp'); const config = require('./config'); const api = require('./api'); const pages = require('./app'); /** * Create app and router */ const app = express(); /** * Set express trust proxy */ app.set('trust proxy', true); /** * Set static directory */ app.use(express.static(__dirname + '/public')); /** * Add middlewares */ app.use(compression()); app.use(helmet()); app.use(hpp()); /** * Ping route */ app.get('/ping', (req, res) => res.send('Pong')); /** * Add router */ app.use('/api', api); /** * Mount template router */ app.use('/', pages); /** * Port */ const port = process.env.PORT || config.server.port; /** * Cluster */ if (cluster.isMaster) { for (let i = 0; i < numCPUs; i += 1) { cluster.fork(); } cluster.on('online', (worker) => { console.log(`Worker ${worker.process.pid} is online`); }); cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died`); console.log('Starting a new worker'); cluster.fork(); }); } else { app.listen(port, '0.0.0.0', () => { console.log(`App listening on port ${port}.`); }); } /** * Handle unhandled exceptions */ process.on('unhandledException', err => console.log(err.toString())); /** * Expose app */ module.exports = app;
pazguille/haysubte
index.js
JavaScript
mit
1,517
class UsersController < ApplicationController def new end def create user = User.new( email: params[:email], password: params[:password], password_confirmation: params[:password_confirmation]) if user.save session[:user_id] = user.id flash[:success] = "Successfully Created User Account" redirect_to '/' else flash[:warning] = "Invalid Email or Password" redirect_to '/signup' end end end
acolletti21/braintree-store
app/controllers/users_controller.rb
Ruby
mit
504
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "$BUILT_PRODUCTS_DIR/SWXMLHash-watchOS/SWXMLHash.framework" install_framework "$BUILT_PRODUCTS_DIR/SwiftBus-watchOS/SwiftBus.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "$BUILT_PRODUCTS_DIR/SWXMLHash-watchOS/SWXMLHash.framework" install_framework "$BUILT_PRODUCTS_DIR/SwiftBus-watchOS/SwiftBus.framework" fi
victorwon/SwiftBus
Example/Pods/Target Support Files/Pods-SwiftBus Watch Example Extension/Pods-SwiftBus Watch Example Extension-frameworks.sh
Shell
mit
3,785
<div id="top" class="container-fluid"> <div class="navbar navbar-default navbar-fixed-top" style="border-bottom: 1px solid #666 !important;"> <h1 class="homeTitle pull-left">Books Library</h1> <a href="#/#/top" title="Top" class="btn btn-primary page-scroll home glyphicon glyphicon-plane pull-right"></a> </div> <div class="filters"> <form class="form-inline"> <div class="form-group"> <label for="orderProp"> Find me the best </label> <select ng-model="orderProp" id="orderProp" class="form-control" ng-change="currentPage=0"> <option value="">All</option> <option value="Non-Fiction">Non-Fiction</option> <option value="Fiction">Fiction</option> </select> </div> <div class="form-group"> <label for="orderG"> books about </label> <select ng-model="orderG" id="orderG" class="form-control" ng-change="currentPage=0"> <option value="">All</option> <option value="{{book.genre.name}}" ng-repeat="book in books | unique:'genre'">{{book.genre.name}}</option> </select> </div> <div class="form-group col-lg-2 col-xs-12 col-sm-3"> <div class="input-group"> <input ng-model="query" id="query" class="form-control" placeholder="Search Books" ng-change="currentPage=0"> <span class="input-group-addon glyphicon glyphicon-search" id="basic-addon2"></span> </div> </div> </div> </div> </div> </div> <div class="row bookWrapper"> <div ng-repeat="book in books | filter:query | filter:(orderProp || undefined):true | filter:(orderG || undefined):true | orderBy:orderProp | startFrom:currentPage*pageSize | limitTo:pageSize" class="bookContent clearfix"> <div class="col-xs-8 col-sm-5 col-md-4 bookList clearfix"> <div> <a href="#/books/{{book.id}}" ng-click="currentObj(book)"><img class="coverImg" ng-src="{{book.cover}}"></a> </div> <div class="bookname"> <h4><a href="#/books/{{book.id}}" ng-click="currentObj(book)">{{book.name}}</a></h4> <p><b><u>{{'by ' + book.author.name}}</u></b></p> <p><i>{{book.genre.category}}{{', ' + book.genre.name}}</i></p> <p><span class="right">{{book.published | date}}{{', ' + convertPublishedDate(book.published)}}</span></p> <p><span class="glyphicon glyphicon-heart"></span>{{' ' + book.likes + ' '}} Likes</p> </div> </div> </div> </div> <div class="row navigation pagination-lg"> <ul class="pagination pagination-lg"> <li> <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1" class="btn"> <span aria-hidden="true">&laquo;</span> </button> </li> <li><a href="javascript:void(0)">{{numberOfPages()==0 ? currentPage : currentPage+1}}</a></li> <li><a href="javascript:void(0)">/</a></li> <li><a href="javascript:void(0)">{{numberOfPages()}}</a></li> <li> <button ng-disabled="(currentPage + 1) == numberOfPages() || numberOfPages()==0" ng-click="currentPage=currentPage+1" class="btn"> <span aria-hidden="true">&raquo;</span> </button> </li> </ul> </nav> </div>
nitinjhamtani/Reedsy-Angular-SPA
app/partials/book-list.html
HTML
mit
3,054
#include <vector> #include <iostream> struct point { double x; double y; }; int main() { // Generate a lot of uniformly distributed 2d points in the range -1,-1 to +1,+1. enum { numXSamples = 10000 }; enum { numYSamples = 10000 }; std::vector<point> points; points.reserve(numXSamples * numYSamples); for(int x = 0;x < numXSamples;++x) { for(int y = 0;y < numXSamples;++y) { point p = {-1.0 + 2.0 * x / (numXSamples-1),-1.0 + 2.0 * y / (numYSamples-1)}; points.push_back(p); } } // Count the ratio of points inside the unit circle. int numerator = 0; int denominator = 0; for(auto pointIt = points.begin();pointIt != points.end();++pointIt) { if(pointIt->x * pointIt->x + pointIt->y * pointIt->y < 1.0) { ++numerator; } ++denominator; } // Derive the area of the unit circle. auto circleArea = 4.0 * (double)numerator / denominator; std::cout << "result: " << circleArea << std::endl; return 0; }
EOSIO/eos
libraries/wasm-jit/Test/Benchmark/Benchmark.cpp
C++
mit
944
#!/usr/bin/env bash # Copyright (c) 2016 Ericsson AB # # 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. # $1 = a file or a directory NAME=$(basename $0) function _sed() { sed -i 's/#\s*include\s\(\"\|<\).*\/\(.*\)\(\"\|>\).*/#include \"\2\"/g' $@ } if [ -f $1 ]; then _sed $1 elif [ -d $1 ]; then # Enter directory cd $1 # Save all files in one array files=($(find -type f)) number_of_files=${#files[*]} [ $number_of_files -eq 0 ] && exit _sed ${files[*]} fi
PatrikAAberg/dmce
dmce-remove-relpaths.sh
Shell
mit
1,477
// // RBViewController.h // Pods // // Created by Param Aggarwal on 01/02/15. // // #import <UIKit/UIKit.h> #import "RBViewControllerModel.h" @interface RBViewController : UIViewController + (instancetype)create:(RBViewControllerModel *)model; - (void)update:(RBViewControllerModel *)model; - (void)updateChildren:(RBViewControllerModel *)model; @end
paramaggarwal/Rubber
Classes/Components/ViewController/RBViewController.h
C
mit
358