identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/Elwalle/openshift-ansible-release-3.11/blob/master/roles/openshift_logging/library/logging_patch.py
Github Open Source
Open Source
Apache-2.0
2,021
openshift-ansible-release-3.11
Elwalle
Python
Code
289
1,025
#!/usr/bin/python """ Ansible module to help with creating context patch file with whitelisting for logging """ import difflib import re from ansible.module_utils.basic import AnsibleModule DOCUMENTATION = ''' --- module: logging_patch short_description: This will create a context patch file while giving ability to whitelist some lines (excluding them from comparison) description: - "To create configmap patches for logging" author: - Eric Wolinetz ewolinet@redhat.com ''' EXAMPLES = ''' - logging_patch: original_file: "{{ tempdir }}/current.yml" new_file: "{{ configmap_new_file }}" whitelist: "{{ configmap_protected_lines | default([]) }}" ''' def account_for_whitelist(current_file_contents, new_file_contents, white_list=None): """ This method will remove lines that contain whitelist values from the content of the file so that we aren't build a patch based on that line Usage: for current_file_contents: index: number_of_shards: 1 number_of_replicas: 0 unassigned.node_left.delayed_timeout: 2m translog: flush_threshold_size: 256mb flush_threshold_period: 5m and new_file_contents: index: number_of_shards: 2 number_of_replicas: 1 unassigned.node_left.delayed_timeout: 2m translog: flush_threshold_size: 256mb flush_threshold_period: 5m and white_list: ['number_of_shards', 'number_of_replicas'] We would end up with: index: number_of_shards: 2 number_of_replicas: 1 unassigned.node_left.delayed_timeout: 2m translog: flush_threshold_size: 256mb flush_threshold_period: 5m """ for line in white_list: regex_line = r".*" + re.escape(line) + r":.*\n" new_file_line = re.search(regex_line, new_file_contents) if new_file_line: current_file_contents = re.sub(regex_line, new_file_line.group(0), current_file_contents) else: current_file_contents = re.sub(regex_line, "", current_file_contents) return current_file_contents def run_module(): """ The body of the module, we check if the variable name specified as the value for the key is defined. If it is then we use that value as for the original key """ module = AnsibleModule( argument_spec=dict( original_file=dict(type='str', required=True), new_file=dict(type='str', required=True), whitelist=dict(required=False, type='list', default=[]) ), supports_check_mode=True ) original_fh = open(module.params['original_file'], "r") original_contents = original_fh.read() original_fh.close() new_fh = open(module.params['new_file'], "r") new_contents = new_fh.read() new_fh.close() original_contents = account_for_whitelist(original_contents, new_contents, module.params['whitelist']) uni_diff = difflib.unified_diff(original_contents.splitlines(), new_contents.splitlines(), lineterm='') return module.exit_json(changed=False, # noqa: F405 raw_patch="\n".join(uni_diff)) def main(): """ main """ run_module() if __name__ == '__main__': main()
16,786
https://github.com/hanyuxing5588/tableGZL/blob/master/XGMvc/Views/ysfp/ysfpSearch.cshtml
Github Open Source
Open Source
MIT
2,017
tableGZL
hanyuxing5588
C#
Code
1,080
5,912
<script type="text/javascript"> $(document).ready(function () { $('#ysfp-hselect').bind('click', function () { GetData(); }) $('#ysfp-haffirm').bind('click', function () { SelectData(); }) $('#ysfp-Reset').bind('click', function () { Clear(); }) }); function GetSelectValue(name, field) { var grid = $(name).combogrid("grid"); var row = grid.datagrid("getSelected"); if (null == row) { return ""; } else { return row[field]; } } function Clear() { $.view.clearView("ysfp", "ysfpdatafilter"); } function SelectData() { var selRow = $('#ysfp-BG_Assign').datagrid('getSelected'); if (!selRow) { $.messager.alert('系统提示', '请选择一条数据'); return; } var index = $('#ysfp-BG_Assign').datagrid('getRowIndex', selRow); var guid_bgsetup = GetSelectValue('#ysfp-BG_Assign-GUID_BGSetUp', "GUID"); var guid_bgtype = GetSelectValue('#ysfp-BG_Assign-GUID_BGTYPE', "GUID"); var guid_bgstep = GetSelectValue('#ysfp-BG_Assign-GUID_BGStep', "GUID"); var pStep = GetSelectValue('#ysfp-BG_Assign-GUID_BGSetUp', "PBG_StepGUID"); var year = $('#ysfp-BG_Assign-Year').combobox('getText'); var Maker = $('#ysfp-BG_Assign-Maker').validatebox('getValue'); var strJson = "{\"Guid_BGSetup\":\"" + guid_bgsetup + "\",\"Year\"\:\"" + year + "\",\"BGType\":\"" + guid_bgtype + "\",\"BGStep\":\"" + guid_bgstep + "\",\"GUIDPStep\":\"" + pStep + "\",\"Maker\":\"" + Maker + "\",\"Index\":\"" + index + "\"}"; condition = JSON.parse(strJson); var winId = '#b-window'; $(winId).dialog({ resizable: false, title: '预算分配编制', width: 1000, height: 600, modal: true, minimizable: false, maximizable: false, collapsible: false, href: '/History/ysfpSearch', onLoad: function (c) { $.view.initByRow("history", 4, selRow, condition); } }); } function ysfpSearch() { $.ajax({ url: "/ysfp/SearchHistoryEx", data: { }, dataType: "json", type: "POST", error: function (xmlhttprequest, textStatus, errorThrown) { $.messager.alert("错误", $.view.warning, 'error'); }, success: function (data) { $('#ysfp-BG_Assign').datagrid('loadData', data); } }); } function GetData() { // 获得界面上的筛选条件 var data = $.view.retrieveData("ysfp", "ysfpdatafilter"); var tcondition; var result = {}; var treeCondition = []; if (data && data.m) { for (var i = 0, j = data.m.length; i < j; i++) { var temp = data.m[i]; if (!temp && !temp.v) continue; result[temp.n] = temp.v; } } var r = $('#ysfp-tree-ysfpproject').tree('getChecked'); if (r) { var iLen = r.length; var Ids = []; for (var i = 0; i < iLen; i++) { if (r[i].attributes.m == "SS_Project") { Ids.push(r[i].id); } } var pr = Ids.join(','); tcondition = { treeModel: "SS_Project", treeValue: pr }; treeCondition.push(tcondition); } result = $.extend(result, { TreeNodeList: treeCondition }); $.ajax({ url: "/ysfp/SearchHistory", data: { condition: JSON.stringify(result) }, dataType: "json", type: "POST", error: function (xmlhttprequest, textStatus, errorThrown) { $.messager.alert("错误", $.view.warning, 'error'); }, success: function (data) { $('#ysfp-BG_Assign').datagrid('loadData', data); } }); } $.extend($.view, { init: function (scope, status, dataguid) { ; if (scope && status) { status = status + ""; var id = "[id^='" + scope + "-'].easyui-linkbutton"; switch (status) { case "1": //新建 $(id).linkbutton('bind', true); $('#' + scope + '-add').click(); ysfpSearch(); break; case "2": //修改 case "3": //删除 case "4": //浏览 ; var data = $.view.retrieveDoc(dataguid, scope); if (data) { $.view.loadData(scope, data); } $.view.setViewEditStatus(scope, status); $.view.cancelObj = { data: data, status: status }; break; } $.view.initAfter(scope, status, dataguid); } }, reSetRow: function (index, guid) { var ysfpState = $('#ysfp-BG_Assign-ysfpState').combobox('getValue'); var allRows = $('#ysfp-BG_Assign').datagrid('getRows'); var currRow = allRows[index]; if ("0" == ysfpState) { if (currRow.GUID != "") { currRow.GUID = ""; currRow.ysfpState = "未分配"; currRow.FlowState = "未提交流程"; $('#ysfp-BG_Assign').datagrid('refreshRow', parseInt(index)); } else { currRow.GUID = guid; currRow.ysfpState = "已分配"; $('#ysfp-BG_Assign').datagrid('refreshRow', parseInt(index)); $('#ysfp-BG_Assign').datagrid('selectRow', parseInt(index)); } } else if ("1" == ysfpState) { if (guid != "") { $('#ysfp-BG_Assign').datagrid('deleteRow', parseInt(index)); $('#ysfp-BG_Assign').datagrid('selectRow', parseInt(index)); var selRow = $('#ysfp-BG_Assign').datagrid('getSelected'); var rowIndex = $('#ysfp-BG_Assign').datagrid('getRowIndex', selRow); $('#ysfp-BG_Assign').datagrid('unselectRow', parseInt(rowIndex)); } } else { if (guid == "") { $('#ysfp-BG_Assign').datagrid('deleteRow', parseInt(index)); $('#ysfp-BG_Assign').datagrid('selectRow', parseInt(index)); var selRow = $('#ysfp-BG_Assign').datagrid('getSelected'); var rowIndex = $('#ysfp-BG_Assign').datagrid('getRowIndex', selRow); $('#ysfp-BG_Assign').datagrid('unselectRow', parseInt(rowIndex)); } } } }) </script> <body> <div class="easyui-layout" b-type="1" data-options="fit:true" z="1"> <div b-type="1" data-options="region:'north',tools:'#tbar'" style="height:51px"> <div id='tbar' b-type="1" style="padding: 2px 0 2px 2px;background:#fafafa;border:1px solid #ccc;"> <a href="#" class="easyui-linkbutton" id="ysfp-add" style="display:none" data-options="plain:'true',iconCls:'icon-xinzeng',hidden:true, bindmethod:{ 'click':['newDoc'] },scope:'ysfp',status:'1', bindparms:{'newDoc':['/ysfp/New']}, forbidstatus:[1,2,3]">新增</a> <a href="#" class="easyui-linkbutton" b-type="1" id="ysfp-hselect" b-action="hselect" data-options=" scope:'ysfp', plain:'true',iconCls:'icon-chaxun'">查询</a> @* <a href="#" class="easyui-linkbutton" b-type="1" id="ysfp-Reset" b-action="hselect" data-options=" scope:'ysfp', plain:'true',iconCls:'icon-chaxun'">重置</a>*@ <a href="#" class="easyui-linkbutton" b-type="1" id="ysfp-haffirm" b-action="haffirm" data-options="plain:'true', window:'b-window', scope:'ysfp', iconCls:'icon-queren'">分配</a> <a href="#" class="easyui-linkbutton" id="ysfp-close" data-options="plain:'true',iconCls:'icon-tuichu', bindmethod:{ 'click': ['closeTab'] }, scope:'ysfp'">退出</a> </div> </div> <div data-options="region:'west',split:'true'" style="width:270px"> <div class="easyui-tabs" data-options="fit:true"> <div title="项目"> <ul class="easyui-tree" id="ysfp-tree-ysfpproject" data-options=" url:'/Tree/GetProjectTreeCheck?select=1', checkbox:true, method:'post'"> </ul> </div> <div title="单位"> <ul class="easyui-tree" id="ysfp-tree-dw" data-options="associate:{ 'ysfp-BG_Assign-GUID_DW':['GUID','DWName'] }, bindmethod:{'onDblClick': ['setAssociate'] }, url:'/Tree/GetDWTree', forbidstatus:[4,3,2], method:'post'"> </ul> </div> <div title="部门"> <ul class="easyui-tree" id="ysfp-tree-dep" data-options="associate:{ 'ysfp-BG_Assign-GUID_DW':['GUID_DW','DWName'], 'ysfp-BG_Assign-GUID_Department':['GUID','DepartmentName'] }, bindmethod:{'onDblClick': ['setAssociate'] }, url:'/Tree/GetDepartmentTree', forbidstatus:[4,3,2], method:'post'"> </ul> </div> </div> </div> <div b-type="1" data-options="region:'center'" > <div b-type="1" id="ysfp-ysfpdatafilter" data-options="region:'north'"> <table border="0" style="width:100%;"> <tr> <td style="width: 75px; height: 15px; padding-left: 3%;"> &nbsp;预算设置&nbsp; </td> <td style="width: 170px;"> <select class="easyui-combogrid" id="ysfp-BG_Assign-GUID_BGSetUp" data-options=" columns:[[ {field:'GUID',hidden:'true'}, {field:'BGSetupKey',title:'预算设置编码',width:'100'}, {field:'BGSetupName',title:'预算设置名称',width:'215'}, {field:'GUID_BGStep',hidden:'true'}, {field:'GUID_BGType',hidden:'true'}, {field:'PBG_StepGUID',hidden:'true'}, ]], associate:{ 'ysfp-BG_Assign-GUID_BGTYPE':['GUID_BGType'], 'ysfp-BG_Assign-GUID_BGStep':['GUID_BGStep'] }, bindmethod: { 'onCloseEx': ['setAssociate'] }, panelWidth:240, width:160, method:'post', idField:'GUID', textField:'BGSetupName', filterField:'BGSetupKey,BGSetupName', remoteUrl:'/Combogrid/BGStepUpView', forbidstatus:[4,3,2] "> </select> </td> <td style="width: 75px; height: 15px;"> &nbsp;预算类型&nbsp; </td> <td style="width: 170px;"> <select class="easyui-combogrid" id="ysfp-BG_Assign-GUID_BGTYPE" data-options="columns:[[ {field:'GUID',hidden:'true'}, {field:'BGTypeKey',title:'预算类型编码',width:'100'}, {field:'BGTypeName',title:'预算类型名称',width:'215'} ]], width:160, panelWidth:240, method:'post', bindmethod:{ 'onCloseEx':['setAssociate'] }, forbidstatus:[-1], remoteUrl:'/Combogrid/BGType', method:'post', idField:'GUID', textField:'BGTypeName', sortName:'BGTypeKey', filterField:'BGTypeKey,BGTypeName'"> </select> </td> <td style="width:10%;"> <label for="field1">年度</label> </td> <td style="width:20%;"> <select id="ysfp-BG_Assign-Year" class="easyui-combobox" data-options="width:150,editable:false,tempValue:new Date().getFullYear()"; style="width:50px;"> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> <option value="2021">2021</option> <option value="2022">2022</option> <option value="2023">2023</option> <option value="2024">2024</option> <option value="2025">2025</option> <option value="2026">2026</option> <option value="2027">2027</option> <option value="2028">2028</option> <option value="2029">2029</option> <option value="2030">2030</option> <option value="2031">2031</option> <option value="2032">2032</option> <option value="2033">2033</option> <option value="2034">2034</option> <option value="2035">2035</option> <option value="2036">2036</option> <option value="2037">2037</option> <option value="2038">2038</option> <option value="2039">2039</option> <option value="2040">2040</option> <option value="2041">2041</option> <option value="2042">2042</option> <option value="2043">2043</option> <option value="2044">2044</option> <option value="2045">2045</option> <option value="2046">2046</option> <option value="2047">2047</option> <option value="2048">2048</option> <option value="2049">2049</option> <option value="2050">2050</option> </select> </td> </tr> <tr> <td style="height: 15px; width: 75px; padding-left: 3%;"> &nbsp;预算步骤&nbsp; </td> <td style="width: 170px;"> <select class="easyui-combogrid" id="ysfp-BG_Assign-GUID_BGStep" data-options=" columns:[[ {field:'GUID',hidden:'true'}, {field:'BGStepKey',title:'预算步骤编码',width:'100'}, {field:'BGStepName',title:'预算步骤名称',width:'215'} ]], panelWidth:240, width:160, method:'post', idField:'GUID', textField:'BGStepName', filterField:'BGStepKey,BGStepName', remoteUrl:'/Combogrid/BGStepView', forbidstatus:[-1] "> </select> </td> <td style="height: 15px; width: 75px;"> &nbsp;分配状态&nbsp; </td> <td style="width:20%;"> <select id="ysfp-BG_Assign-ysfpState" class="easyui-combobox" data-options="editable:false,tempValue:'1'"; style="width:160px;"> <option value="0" >全部</option> <option value="1">未分配</option> <option value="2">已分配</option> </select> </td> </tr> <tr> <td style="width: 75px; height: 15px; padding-left: 3%;"> &nbsp;预算单位&nbsp; </td> <td style="width: 170px; text-align: left;"> <select class="easyui-combogrid" id="ysfp-BG_Assign-GUID_DW" data-options=" columns:[[ {field:'GUID',hidden:'true'}, {field:'GUID_Department',hidden:'true'}, {field:'DWKey',title:'预算单位编码',width:'100'}, {field:'DWName',title:'预算单位名称',width:'215'} ]], panelWidth:240, width:160, method:'post', idField:'GUID', textField:'DWName', filterField:'DWKey,DWName', remoteUrl:'/Combogrid/DW', forbidstatus:[4,3,2] "> </select> </td> <td style="width: 75px; height: 15px;"> &nbsp;预算部门 </td> <td style="width: 160px;"> <select class="easyui-combogrid" id="ysfp-BG_Assign-GUID_Department" data-options="columns:[[ {field:'GUID',hidden:'true'}, {field:'GUID_DW',hidden:'true'}, {field:'DepartmentKey',title:'预算部门编码',width:'100'}, {field:'DepartmentName',title:'预算部门名称',width:'200'}, {field:'DWName',title:'所属单位名称',width:'215'} ]], width:160, panelWidth:440, method:'post', bindmethod:{ 'onCloseEx':['setAssociate'] }, associate:{ 'ysfp-BG_Assign-GUID_DW':['GUID_DW'] }, forbidstatus:[3,4,2], remoteUrl:'/Combogrid/Department', method:'post', idField:'GUID', textField:'DepartmentName', sortName:'DepartmentKey', filterField:'DepartmentKey,DepartmentName'"> </select> </td> </tr> </table> </div> <input class="easyui-validatebox" id="ysfp-BG_Assign-Maker" type="hidden"></input> <div b-type="1" data-options="region:'center',fit:true" > <table style="height:475px;padding:5px" class="easyui-datagrid" id="ysfp-BG_Assign" b-type="1" data-options=" fitColumns:false, method:'get', singleSelect:true, checkOnSelect:true, pagination:true, striped: false, pageSize:20, pageList:[20,50,100], rownumbers:true "> <thead> <tr> <th field="b-sel" data-options="width:100,checkbox:'true'"></th> <th field="GUID" hidden="true" width="80"></th> <th field="FunctionClass" hidden="true" width="80"></th> <th field="GUID_Department" hidden="true" width="80"></th> <th field="GUID_Dw" hidden="true" width="80"></th> <th field="GUID_Project" hidden="true" width="80"></th> <th field="ProjectKey"align="left" width="80" >项目编码</th> <th field="ProjectName"align="left" width="250" >项目名称</th> <th field="DWName"align="left" width="150" >预算单位</th> <th field="DepartmentName"align="left" width="80" >预算部门</th> <th field="Principal"align="left" width="80" >项目负责人</th> <th field="ysfpState"align="left" width="80" >分配状态</th> <th field="FlowState"align="left" width="100" >流程状态</th> </tr> </thead> </table> <label id="ysfp-extendregion" style="display: none"> <input id="ysfp-status" type="text"></input> <input id="initscope" type="text" value=@ViewData["scope"]></input> <input id="initstatus" type="text" value=@ViewData["status"]></input> <input id="initguid" type="text" value=@ViewData["guid"]></input> <div id="b-window" line="true"> </div> </label> </div> </div> </body>
41,934
https://github.com/ArthurBottcher/teste_goclin/blob/master/src/services/api.js
Github Open Source
Open Source
MIT
null
teste_goclin
ArthurBottcher
JavaScript
Code
65
261
import axios from 'axios' const http = axios.create({ baseURL:'https:/stage-api.goclin.com/v1/', headers: { 'api-key': '9q3llb2umtpoyqdpmwvfx0daxnl0ctv4i7oldawk7693k84yapik0vatw6i2d81j', 'content-type': 'application/json' } }) http.interceptors.response.use((response) => { return response }, (error) => { if (error.response) { console.log(error.response.data.message) return { hasError: true, error: error.response.data.message } } }) export async function login(user) { const response = await http.post('/auth/token/',user) return response } export async function register(user) { const response= await http.post('/auth/account', user) return response }
35,043
https://github.com/AmurKhoyetsyan/TUTORIAL-HTML-CSS-JS-SASS/blob/master/Loaders/How to create a loader using pure HTML and CSS Heart Spinner CSS Effects Version seven/css/style.sass
Github Open Source
Open Source
MIT
2,022
TUTORIAL-HTML-CSS-JS-SASS
AmurKhoyetsyan
Sass
Code
131
452
* padding: 0 margin: 0 box-sizing: border-box .parent width: 100vw height: 100vh background-color: #B12C2C display: flex flex-wrap: nowrap flex-direction: row justify-content: center align-items: center .loader width: 100px .loader-title width: 100% text-align: center font-weight: 700 line-height: 1.7 font-size: 20px color: #FFFFFF .loader-items width: 100% height: 100px position: relative .heart width: 40px height: 40px border-radius: 50% position: absolute left: 50% top: 50% transform: translate(-85%, -75%) background-color: #FFFFFF animation: loader 1000ms linear infinite &::after content: "" width: 100% height: 100% border-radius: 50% position: absolute left: 30px top: 0 background-color: #FFFFFF &::before content: "" width: 100% height: 100% transform: rotate(45deg) position: absolute left: 15px top: 15px background-color: #FFFFFF @keyframes loader to transform: translate(-60%, -60%) scale(.5) 30% transform: translate(-80%, -70%) scale(.8) 60% transform: translate(-60%, -60%) scale(.5) 80% transform: translate(-80%, -70%) scale(.8) from transform: translate(-85%, -75%) scale(1)
49,474
https://github.com/awais000/eboves-api/blob/master/src/api/apiBanners.ts
Github Open Source
Open Source
MIT
2,021
eboves-api
awais000
TypeScript
Code
41
150
import express from "express"; import { getAll, toggleActiveStatus, bulkDelete, create, update, getBanners, } from "../controllers/controllerBanners"; const app = express(); app.get("/", getAll); app.delete("/", bulkDelete); app.post("/", create); app.put("/:Aid", update); app.put("/toggle-active/:Aid", toggleActiveStatus); //---------------------------Website Route--------------------// export const WebsiteApp = express(); WebsiteApp.get("/", getBanners); export default app;
105
https://github.com/jsdelivrbot/challenge_word_classifier/blob/master/submissions/5748487163905b3a11d97c60/src/make-dist.js
Github Open Source
Open Source
MIT
2,018
challenge_word_classifier
jsdelivrbot
JavaScript
Code
459
1,708
var fs = require('fs'); var zlib = require('zlib'); var filesize = require('filesize'); var ClosureCompiler = require('closurecompiler'); var BloomFilter = require('bloom-filter'); var es6Minify = require('./es6-minify'); var processors = require('./processors'); var words = fs.readFileSync('./words.txt', 'utf8').split('\n'); var collectStatistic = !!process.argv[2]; var falsePositiveRate = 0.37961; var alphabet = 'abcdefghijklmnopqrstuvwxyz\''; var wordsSet = new Set(); var processedSet = new Set(); words .filter(word => word.length > 1) .forEach(word => wordsSet.add(word.toLowerCase())); var doesExist = (word) => wordsSet.has(word); var addToSet = (word) => { if ( // Exclude <= 3 words, we will return false in such case word.length > 3 && word.match(/'s$/) == null ) { processedSet.add(word); } }; if (collectStatistic) { var stats = { consecutive: {}, startCharCount: {}, endCharCount: {}, charCount: {}, length: {} }; for (var i = 0; i < alphabet.length; i++) { stats.consecutive[alphabet[i]] = 0; stats.startCharCount[alphabet[i]] = 0; stats.endCharCount[alphabet[i]] = 0; stats.charCount[alphabet[i]] = 0; } } wordsSet.forEach(word => { if (collectStatistic) { var match; if (match = word.match(/([aeijouybcdfghklmnpqrstvwxz])\1\1/)) { stats.consecutive[match[1]] += 1; } } processors(word, doesExist, addToSet); }); if (collectStatistic) { processedSet.forEach(word => { stats.length[word.length] |= 0; stats.length[word.length] += 1; stats.startCharCount[word[0]] += 1; stats.endCharCount[word[word.length - 1]] += 1; for (var j = 0; j < word.length; j++) { stats.charCount[word[j]] += 1; } }); } var compressScript = (filename, resolve, reject) => { ClosureCompiler.compile([filename], {}, (error, result) => { error && reject(); result ? resolve(result) : reject(); }); }; var serializeScript = (scriptStr) => { return scriptStr.trim() .replace(/\n/g, '') .replace(/function\(([a-zA-Z])\)/g, '$1=>') .replace(/function\(([a-zA-Z,]{1,})\)/g, '($1)=>') .slice(scriptStr.indexOf('=') + 1); }; var getHashes = () => { var filter = BloomFilter.create(processedSet.size, falsePositiveRate); processedSet.forEach(word => filter.insert(new Buffer(word, 'utf8'))); return filter.toObject().vData; }; var toBinary = (hashes) => { var int8 = new Uint8Array(hashes.length); hashes.forEach((hash, index) => int8[index] = hash); return new Buffer(int8, 'binary'); }; Promise.all([ new Promise((resolve, reject) => compressScript('processors.js', resolve, reject)), new Promise((resolve, reject) => compressScript('bloom.js', resolve, reject)) ]).then((values) => { var minifiedSolution = es6Minify('./solution.js'); var minifiedProcessors = 'p=' + serializeScript(values[0]); var minifiedBloomFilter = 'b=' + serializeScript(values[1]); var scripts = minifiedProcessors + minifiedBloomFilter + minifiedSolution; var dataGzip = zlib.gzipSync(toBinary(getHashes()), { level: 9 }); fs.writeFile('./dist/data.gz', dataGzip); fs.writeFile('./dist/words.txt', Array.from(processedSet).join('\n')); fs.writeFile('./dist/solution.js', scripts); if (collectStatistic) { console.log('Words length:'); Object .keys(stats.length) .forEach(length => { console.log(` ${length}: ${stats.length[length]}`); }); console.log(''); console.log('Start in:'); Object .keys(stats.startCharCount) .sort((a, b) => stats.startCharCount[b] - stats.startCharCount[a]) .forEach(char => { console.log(` ${char}: ${stats.startCharCount[char]}`); }); console.log(''); console.log('End with:'); Object .keys(stats.endCharCount) .sort((a, b) => stats.endCharCount[b] - stats.endCharCount[a]) .forEach(char => { console.log(` ${char}: ${stats.endCharCount[char]}`); }); console.log(''); console.log('Has char:'); Object .keys(stats.charCount) .sort((a, b) => stats.charCount[b] - stats.charCount[a]) .forEach(char => { console.log(` ${char}: ${stats.charCount[char]}`); }); console.log(''); console.log('Consecutive (>= 3):'); Object .keys(stats.charCount) .filter(char => stats.consecutive[char] > 0) .sort((a, b) => stats.consecutive[b] - stats.consecutive[a]) .forEach(char => { console.log(` ${char}: ${stats.consecutive[char]}`); }); console.log(''); } var filesLength = scripts.length + dataGzip.length; console.log(`Total size: ${filesize(filesLength, {standard: "iec"})} (${filesLength}/${Math.pow(2, 16)})`); console.log(`Words: ${processedSet.size}/${wordsSet.size}`); console.log(`Rejected: ${(100 - processedSet.size / wordsSet.size * 100).toFixed(2)}%`); });
14,387
https://github.com/PaulTrampert/PTrampert.ApiProxy/blob/master/PTrampert.ApiProxy/ApiProxyConfig.cs
Github Open Source
Open Source
MIT
null
PTrampert.ApiProxy
PaulTrampert
C#
Code
51
143
using System; using System.Collections.Generic; namespace PTrampert.ApiProxy { /// <summary> /// Dictionary of configured API's that the proxy can handle. Keys are compared with <see cref="StringComparer.OrdinalIgnoreCase"/>. /// </summary> public class ApiProxyConfig : Dictionary<string, ApiConfig> { /// <summary> /// Constructor for <see cref="ApiProxyConfig"/> /// </summary> public ApiProxyConfig() : base(StringComparer.OrdinalIgnoreCase) { } } }
42,737
https://github.com/cato976/Ecobee/blob/master/src/I8Beef.Ecobee/Protocol/Objects/RuntimeSensorMetadata.cs
Github Open Source
Open Source
MIT
2,018
Ecobee
cato976
C#
Code
145
346
using Newtonsoft.Json; namespace I8Beef.Ecobee.Protocol.Objects { /// <summary> /// Ecobee API runtime sensor metadata. /// </summary> [JsonObject(MemberSerialization.OptIn)] public class RuntimeSensorMetadata { /// <summary> /// The unique sensor identifier. It is composed of deviceName + deviceId + sensorId /// (from thermostat.device[].sensor[]) separated by colons. This value corresponds to /// the column name for the sensor reading values. /// </summary> [JsonProperty(PropertyName = "sensorId")] public string SensorId { get; set; } /// <summary> /// The user assigned sensor name. /// </summary> [JsonProperty(PropertyName = "sensorName")] public string SensorName { get; set; } /// <summary> /// The type of sensor. See Sensor Types. Values: co2, ctclamp, dryContact, humidity, /// plug, temperature /// </summary> [JsonProperty(PropertyName = "sensorType")] public string SensorType { get; set; } /// <summary> /// The usage configured for the sensor. Values: dischargeAir, indoor, monitor, outdoor /// </summary> [JsonProperty(PropertyName = "sensorUsage")] public string SensorUsage { get; set; } } }
16,789
https://github.com/zzti/DotNetCore.SKIT.FlurlHttpClient.Wechat/blob/master/src/SKIT.FlurlHttpClient.Wechat.Work/Models/CgibinSchool/User/Parent/CgibinSchoolUserCreateParentRequest.cs
Github Open Source
Open Source
MIT
2,023
DotNetCore.SKIT.FlurlHttpClient.Wechat
zzti
C#
Code
134
612
using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Work.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/school/user/create_parent 接口的请求。</para> /// </summary> public class CgibinSchoolUserCreateParentRequest : WechatWorkRequest { public static class Types { public class Child { /// <summary> /// 获取或设置学生账号。 /// </summary> [Newtonsoft.Json.JsonProperty("student_userid")] [System.Text.Json.Serialization.JsonPropertyName("student_userid")] public string StudentUserId { get; set; } = string.Empty; /// <summary> /// 获取或设置家长与学生的关系。 /// </summary> [Newtonsoft.Json.JsonProperty("relation")] [System.Text.Json.Serialization.JsonPropertyName("relation")] public string Relation { get; set; } = string.Empty; } } /// <summary> /// 获取或设置家长账号。 /// </summary> [Newtonsoft.Json.JsonProperty("parent_userid")] [System.Text.Json.Serialization.JsonPropertyName("parent_userid")] public string ParentUserId { get; set; } = string.Empty; /// <summary> /// 获取或设置手机号码。 /// </summary> [Newtonsoft.Json.JsonProperty("mobile")] [System.Text.Json.Serialization.JsonPropertyName("mobile")] public string MobileNumber { get; set; } = string.Empty; /// <summary> /// 获取或设置是否发起邀请。 /// </summary> [Newtonsoft.Json.JsonProperty("to_invite")] [System.Text.Json.Serialization.JsonPropertyName("to_invite")] public bool? RequireInvite { get; set; } /// <summary> /// 获取或设置家长的孩子列表。 /// </summary> [Newtonsoft.Json.JsonProperty("children")] [System.Text.Json.Serialization.JsonPropertyName("children")] public IList<Types.Child> Children { get; set; } = new List<Types.Child>(); } }
23,468
https://github.com/ricardoferreirasilva/jsweaver/blob/master/jsweaver/src/pt/up/fe/specs/jackdaw/abstracts/joinpoints/ABlockStatement.java
Github Open Source
Open Source
Apache-2.0
2,019
jsweaver
ricardoferreirasilva
Java
Code
483
1,505
package pt.up.fe.specs.jackdaw.abstracts.joinpoints; import java.util.List; import org.lara.interpreter.weaver.interf.SelectOp; import org.lara.interpreter.weaver.interf.JoinPoint; import java.util.Optional; import java.util.stream.Collectors; import java.util.Arrays; /** * Auto-Generated class for join point ABlockStatement * This class is overwritten by the Weaver Generator. * * * @author Lara Weaver Generator */ public abstract class ABlockStatement extends AStatement { protected AStatement aStatement; /** * */ public ABlockStatement(AStatement aStatement){ this.aStatement = aStatement; } /** * Default implementation of the method used by the lara interpreter to select scopes * @return */ public List<? extends AScope> selectScope() { return select(pt.up.fe.specs.jackdaw.abstracts.joinpoints.AScope.class, SelectOp.DESCENDANTS); } /** * Method used by the lara interpreter to select blockStatements * @return */ @Override public List<? extends ABlockStatement> selectBlockStatement() { return this.aStatement.selectBlockStatement(); } /** * Method used by the lara interpreter to select classBodys * @return */ @Override public List<? extends AClassBody> selectClassBody() { return this.aStatement.selectClassBody(); } /** * * @param position * @param code */ @Override public AJoinPoint[] insertImpl(String position, String code) { return this.aStatement.insertImpl(position, code); } /** * * @param position * @param code */ @Override public AJoinPoint[] insertImpl(String position, JoinPoint code) { return this.aStatement.insertImpl(position, code); } /** * */ @Override public String toString() { return this.aStatement.toString(); } /** * */ @Override public Optional<? extends AStatement> getSuper() { return Optional.of(this.aStatement); } /** * */ @Override public final List<? extends JoinPoint> select(String selectName) { List<? extends JoinPoint> joinPointList; switch(selectName) { case "scope": joinPointList = selectScope(); break; case "blockStatement": joinPointList = selectBlockStatement(); break; case "classBody": joinPointList = selectClassBody(); break; default: joinPointList = this.aStatement.select(selectName); break; } return joinPointList; } /** * */ @Override public final void defImpl(String attribute, Object value) { switch(attribute){ default: throw new UnsupportedOperationException("Join point "+get_class()+": attribute '"+attribute+"' cannot be defined"); } } /** * */ @Override protected final void fillWithAttributes(List<String> attributes) { this.aStatement.fillWithAttributes(attributes); } /** * */ @Override protected final void fillWithSelects(List<String> selects) { this.aStatement.fillWithSelects(selects); selects.add("scope"); } /** * */ @Override protected final void fillWithActions(List<String> actions) { this.aStatement.fillWithActions(actions); } /** * Returns the join point type of this class * @return The join point type */ @Override public final String get_class() { return "blockStatement"; } /** * Defines if this joinpoint is an instanceof a given joinpoint class * @return True if this join point is an instanceof the given class */ @Override public final boolean instanceOf(String joinpointClass) { boolean isInstance = get_class().equals(joinpointClass); if(isInstance) { return true; } return this.aStatement.instanceOf(joinpointClass); } /** * */ protected enum BlockStatementAttributes { PARENT("parent"), JOINPOINTNAME("joinPointName"), AST("ast"), CODE("code"), LINE("line"), ANCESTOR("ancestor"), COLUMN("column"), TYPE("type"), DESCENDANTS("descendants"), UUID("uuid"), FILE("file"), FIELD("field"), CHILDREN("children"), ROOT("root"); private String name; /** * */ private BlockStatementAttributes(String name){ this.name = name; } /** * Return an attribute enumeration item from a given attribute name */ public static Optional<BlockStatementAttributes> fromString(String name) { return Arrays.asList(values()).stream().filter(attr -> attr.name.equals(name)).findAny(); } /** * Return a list of attributes in String format */ public static List<String> getNames() { return Arrays.asList(values()).stream().map(BlockStatementAttributes::name).collect(Collectors.toList()); } /** * True if the enum contains the given attribute name, false otherwise. */ public static boolean contains(String name) { return fromString(name).isPresent(); } } }
45,447
https://github.com/vivekkanoje1989/edynamics_Laravel/blob/master/app/Modules/Projects/Controllers/ProjectsController.php
Github Open Source
Open Source
MIT
null
edynamics_Laravel
vivekkanoje1989
PHP
Code
1,845
7,519
<?php namespace App\Modules\Projects\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Modules\Projects\Models\MlstBmsbProjectStatus; use App\Modules\Projects\Models\MlstBmsbProjectType; use App\Modules\Projects\Models\Project; use App\Modules\Projects\Models\ProjectWebPage; use App\Modules\Projects\Models\ProjectWing; use App\Modules\Projects\Models\ProjectBlocks; use App\Models\MlstBmsbAmenity; use App\Models\MlstBmsbBlockType; use App\Models\ProjectBlock; use App\Models\ProjectStatus; use Auth; use App\Classes\CommonFunctions; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Validator; use App\Classes\S3; class ProjectsController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function index() { return view("Projects::index"); } public function manageProjects() { $getProjects = Project::select('id','created_by','project_status','project_type_id','project_name','created_at','project_status')->with(['getEmployee','projectTypes','projectStatus'])->get(); $i = 0; foreach($getProjects as $getProject){ $getProjects[$i]['projectStatus'] = $getProject['projectStatus']['project_status']; $getProjects[$i]['fullName'] = $getProject['getEmployee']['first_name'].' '.$getProject['getEmployee']['last_name']; $getProjects[$i]['projectType'] = $getProject['projectTypes']['project_type']; $i++; } if (!empty($getProjects)) { $result = ['success' => true, 'records' => $getProjects]; return json_encode($result); } else { $result = ['success' => false, 'message' => 'Something went wrong']; return json_encode($result); } // $getProjects = Project::join('employees','projects.created_by','=','employees.id') // ->join('laravel_developement_master_edynamics.mlst_bmsb_project_types as mlst_bmsb_project_types','projects.project_type_id','=','mlst_bmsb_project_types.id') // ->join('laravel_developement_master_edynamics.mlst_bmsb_project_status as mlst_bmsb_project_status','projects.project_status','=','mlst_bmsb_project_status.id') // ->select(['projects.id','projects.created_at','projects.project_name','employees.first_name','employees.last_name','mlst_bmsb_project_types.project_type','mlst_bmsb_project_status.project_status as pro_status','projects.project_status as b ','mlst_bmsb_project_status.id as c'])->get(); if (!empty($getProjects)) { $result = ['success' => true, 'records' => $getProjects]; } else { $result = ['success' => false, 'message' => 'Something went wrong']; } return json_encode($result); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view("Projects::create"); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $postdata = file_get_contents("php://input"); $input = json_decode($postdata, true); $loggedInUserId = Auth::guard('admin')->user()->id; $create = CommonFunctions::insertMainTableRecords($loggedInUserId); $input = array_merge($input['data'], $create); $createProject = Project::create($input); if (!empty($createProject)) { $result = ['success' => true, 'message' => 'Employee registeration successfully']; echo json_encode($result); } else { $result = ['success' => false, 'message' => 'Something went wrong. Record not created.']; echo json_encode($result); } } public function getprojects() { $getProjects = Project::with(['getEmployee','projectTypes','projectStatus'])->get(); if (!empty($getProjects)) { $result = ['success' => true, 'records' => $getProjects]; return json_encode($result); } else { $result = ['success' => false, 'message' => 'Something went wrong']; return json_encode($result); } } public function getProjectWings() { $postdata = file_get_contents("php://input"); $input = json_decode($postdata, true); $result = ProjectWing::where('project_id', '=', $input['project_id'])->get(); if (!empty($result)) { return json_encode(['result' => $result, 'status' => true]); } else { return json_encode(['result' => "No wings found", 'status' => true]); } } public function getFloorDetails() { $postdata = file_get_contents("php://input"); $input = json_decode($postdata, true); $result = ProjectBlocks::where('project_id', '=', $input['project_id'])->get(); if (!empty($result)) { return json_encode(['result' => $result, 'status' => true]); } else { return json_encode(['result' => "No wings found", 'status' => true]); } } public function basicInfo() { try { $postdata = file_get_contents("php://input"); $input = json_decode($postdata, true); if (empty($input)) $input = Input::all(); $projectId = $input['project_id']; $loggedInUserId = Auth::guard('admin')->user()->id; $isProjectExist = ProjectWebPage::where('project_id', '=', $projectId)->first(); if (!empty($input['projectImages'])) { if (count($input['projectImages']) > 1) { unset($input['projectImages']['upload']); foreach ($input['projectImages'] as $key => $value) { $isMultipleArr = is_array($input['projectImages'][$key]); if ($isMultipleArr) { $originalName = $input['projectImages'][$key][0]->getClientOriginalName(); } else { $originalName = $input['projectImages'][$key]->getClientOriginalName(); } if ($originalName !== 'fileNotSelected') { $imgRules = array( 'project_logo' => 'mimes:jpeg,png,jpg,gif,svg', 'project_thumbnail' => 'mimes:jpeg,png,jpg,gif,svg', 'project_favicon' => 'mimes:jpeg,png,jpg,gif,svg', 'project_banner_images.*' => 'mimes:jpeg,png,jpg,gif,svg', 'project_background_images.*' => 'mimes:jpeg,png,jpg,gif,svg', 'project_broacher.*' => 'mimes:jpeg,png,jpg,gif,svg', 'location_map_images.*' => 'mimes:jpeg,png,jpg,gif,svg', ); $validator = Validator::make($input['projectImages'], $imgRules); if ($validator->fails()) { $result = ['success' => false, 'message' => $validator->messages()]; return json_encode($result); } else { $s3FolderName = '/project/' . $key; // $implodeName = array(); if ($isMultipleArr) { $prImageName = explode(",", $isProjectExist[$key]); for ($i = 0; $i < count($input['projectImages'][$key]); $i++) { $imageName = 'project_' . $projectId . '_' . rand(pow(10, config('global.randomNoDigits') - 1), pow(10, config('global.randomNoDigits')) - 1) . '.' . $input['projectImages'][$key][$i]->getClientOriginalExtension(); S3::s3FileUpload($input['projectImages'][$key][$i]->getPathName(), $imageName, $s3FolderName); $prImageName[] = $imageName; } } else { /****************delete single image from s3 bucket start**************** */ if (!empty($input['projectImages'][$key])) { if ($isProjectExist[$key] !== $input['projectImages'][$key]) { $path = $s3FolderName . $isProjectExist[$key]; S3::s3FileDelete($path); } } /****************delete single image from s3 bucket end**************** */ $imageName = 'project_' . $projectId . '_' . rand(pow(10, config('global.randomNoDigits') - 1), pow(10, config('global.randomNoDigits')) - 1) . '.' . $input['projectImages'][$key]->getClientOriginalExtension(); S3::s3FileUpload($input['projectImages'][$key]->getPathName(), $imageName, $s3FolderName); $prImageName[] = $imageName; } $prImageName = array_filter($prImageName); $implodeImgName = implode(",", $prImageName); if (isset($input['statusData'])) { $input['statusData'][$key] = $implodeImgName; } elseif (isset($input['specificationData']) || isset($input['floorData'])) { $objName = $input['objName']; $input[$objName][$key] = $implodeImgName; } elseif (isset($input['layoutData'])) { $input['layoutData'][$key] = $implodeImgName; } else { $input['projectData'][$key] = $implodeImgName; } } } } } } // echo "<pre>";print_r($input['projectData']);exit; if (isset($input['projectData'])) { if (!empty($input['projectData']['project_amenities_list'])) { // $input['projectData']['project_amenities_list'] = $input['projectData']['project_amenities_list']; // } else { $input['projectData']['project_amenities_list'] = implode(',', array_map(function($el) { return $el['id']; }, $input['projectData']['project_amenities_list'])); } $input['projectData']['project_id'] = $projectId; if (empty($isProjectExist)) { $create = CommonFunctions::insertMainTableRecords($loggedInUserId); $input['projectData'] = array_merge($input['projectData'], $create); $actionProject = ProjectWebPage::create($input['projectData']); $msg = "Record added successfully"; } else { $update = CommonFunctions::updateMainTableRecords($loggedInUserId); $input['projectData'] = array_merge($input['projectData'], $update); $actionProject = ProjectWebPage::where('project_id', $projectId)->update($input['projectData']); $msg = "Record updated successfully"; } } if (isset($input['inventoryData'])) { $input['inventoryData']['project_id'] = $projectId; $isBlockExist = ProjectBlock::where(['project_id' => $projectId, 'wing_id' => $input['inventoryData']['wing_id']])->first(); if (empty($isBlockExist)) { $create = CommonFunctions::insertMainTableRecords($loggedInUserId); $input['inventoryData'] = array_merge($input['inventoryData'], $create); $actionProject = ProjectBlock::create($input['inventoryData']); $msg = "Record added successfully"; } else { $update = CommonFunctions::updateMainTableRecords($loggedInUserId); $input['inventoryData'] = array_merge($input['inventoryData'], $update); $actionProject = ProjectBlock::where(['project_id' => $projectId, 'wing_id' => $input['inventoryData']['wing_id']])->update($input['inventoryData']); $msg = "Record updated successfully"; } } if (isset($input['statusData'])) { $input['statusData']['project_id'] = $projectId; $input['statusData']['short_description'] = !empty($input['statusData']['status_short_description']) ? $input['statusData']['status_short_description'] : ""; $create = CommonFunctions::insertMainTableRecords($loggedInUserId); $input['statusData'] = array_merge($input['statusData'], $create); $actionProjectStatus = ProjectStatus::create($input['statusData']); $msg = "Record added successfully"; $getProjectStatusRecords = ProjectStatus::select('id', 'images', 'status', 'short_description')->get(); $result = ['success' => true, 'message' => $msg, 'records' => $getProjectStatusRecords]; return json_encode($result); } if (isset($input['specificationData']) || isset($input['floorData'])) { $objName = $input['objName']; $result = []; if (!empty($input[$objName]['modalData']['floors'])) { $projectWingName = ProjectWing::select('wing_name')->where('id', $input[$objName]['modalData']['wing'])->get(); $floorArr = array(); foreach ($input[$objName]['modalData']['floors'] as $key => $floor) { unset($floor['$hashKey'], $floor['wingId']); $floorId[] = $floor['id']; $floorArr[] = $floor; } sort($floorId); $input[$objName]['modalData']['floors'] = $floorId; if (isset($input['specificationData'])) { $input[$objName]['modalData']['specification_images'] = $implodeImgName; if (!empty($isProjectExist->specification_images)) { $mergeOldValue = json_decode($isProjectExist->specification_images, true); } $mergeOldValue[] = $input[$objName]['modalData']; $input[$objName]['specification_images'] = json_encode($mergeOldValue); $specificationTitle = ["image" => $implodeImgName, "title" => $projectWingName[0]->wing_name . ", Floor:" . implode(",", $floorId)]; } else if (isset($input['floorData'])) { $input[$objName]['modalData']['floor_plan_images'] = $implodeImgName; if (!empty($isProjectExist->floor_plan_images)) { $mergeOldValue = json_decode($isProjectExist->floor_plan_images, true); } $mergeOldValue[] = $input[$objName]['modalData']; $input[$objName]['floor_plan_images'] = json_encode($mergeOldValue); $specificationTitle = ["image" => $implodeImgName, "title" => $projectWingName[0]->wing_name . ", Floor:" . implode(",", $floorId)]; } unset($input[$objName]['modalData']); if (empty($isProjectExist)) { $create = CommonFunctions::insertMainTableRecords($loggedInUserId); $input[$objName] = array_merge($input[$objName], $create); $actionProject = ProjectWebPage::create($input[$objName]); $msg = "Record added successfully"; $result = ['success' => true, 'message' => $msg, 'specificationTitle' => $specificationTitle]; return json_encode($result); } else { $update = CommonFunctions::updateMainTableRecords($loggedInUserId); $input[$objName] = array_merge($input[$objName], $update); $actionProject = ProjectWebPage::where('project_id', $projectId)->update($input[$objName]); $msg = "Record updated successfully"; $result = ['success' => true, 'message' => $msg, 'specificationTitle' => $specificationTitle]; return json_encode($result); } } } if (isset($input['layoutData'])) { $result = []; if (!empty($input['layoutData']['modalData'])) { $projectWingName = ProjectWing::select('wing_name')->where('id', $input['layoutData']['modalData']['wing'])->get(); if (isset($input['layoutData'])) { $input['layoutData']['modalData']['layout_plan_images'] = $implodeImgName; if (!empty($isProjectExist->layout_plan_images)) { $mergeOldValue = json_decode($isProjectExist->layout_plan_images, true); } $mergeOldValue[] = $input['layoutData']['modalData']; $input['layoutData']['layout_plan_images'] = json_encode($mergeOldValue); $layoutTitle = ["image" => $implodeImgName, "title" => $projectWingName[0]->wing_name]; } unset($input['layoutData']['modalData']); if (empty($isProjectExist)) { $create = CommonFunctions::insertMainTableRecords($loggedInUserId); $input['layoutData'] = array_merge($input['layoutData'], $create); $actionProject = ProjectWebPage::create($input['layoutData']); $msg = "Record added successfully"; $result = ['success' => true, 'message' => $msg, 'layoutTitle' => $layoutTitle]; return json_encode($result); } else { $update = CommonFunctions::updateMainTableRecords($loggedInUserId); $input['layoutData'] = array_merge($input['layoutData'], $update); $actionProject = ProjectWebPage::where('project_id', $projectId)->update($input['layoutData']); $msg = "Record updated successfully"; $result = ['success' => true, 'message' => $msg, 'layoutTitle' => $layoutTitle]; return json_encode($result); } } } if (!empty($actionProject)) { $result = ['success' => true, 'message' => $msg]; } else { $result = ['success' => false, 'message' => 'Something went wrong.']; } } catch (\Exception $ex) { $result = ["success" => false, "status" => 412, "message" => $ex->getMessage()]; } return json_encode($result); } public function getProjectDetails($id) { $getProjectDetails = $getProjectStatusRecords = $getProjectInventory = array(); $getProjectDetails = ProjectWebPage::where("project_id","=",$id)->get(); $getProjectStatusRecords = ProjectStatus::select('id','images', 'status', 'short_description')->where("project_id","=",$id)->get(); $getWing = ProjectWing::select('id', 'project_id', 'wing_name', 'number_of_floors')->where('project_id', $id)->orderBy('id', 'ASC')->first(); $getProjectInventory = ProjectBlock::where([['wing_id','=',$getWing->id],['project_id','=',$id]])->orderBy('wing_id', 'ASC')->get(); /**************getSpecifiction**************/ $specificationTitle = array(); // echo "<pre>";print_r($getProjectDetails[0]->specification_images);exit; if(!empty($getProjectDetails[0]->specification_images) && ($getProjectDetails[0]->specification_images !== 'null')){ $decodeSpecificationDetails = json_decode($getProjectDetails[0]->specification_images,true); foreach($decodeSpecificationDetails as $key => $val){ $projectWingName = ProjectWing::select('wing_name')->where('id', $val['wing'])->get(); $specificationTitle[$key] = ["image" => $val['specification_images'],"title" => $projectWingName[0]->wing_name .", Floor:". implode(",", $val['floors'])]; } } $floorTitle = array(); if(!empty($getProjectDetails[0]->floor_plan_images) && ($getProjectDetails[0]->specification_images !== 'null')){ $decodeFloorDetails = json_decode($getProjectDetails[0]->floor_plan_images,true); foreach($decodeFloorDetails as $key => $val){ $projectWingName = ProjectWing::select('wing_name')->where('id', $val['wing'])->get(); $floorTitle[$key] = ["image" => $val['floor_plan_images'],"title" => $projectWingName[0]->wing_name .", Floor:". implode(",", $val['floors'])]; } } $layoutTitle = array(); if(!empty($getProjectDetails[0]->layout_plan_images)){ $decodeLayoutDetails = json_decode($getProjectDetails[0]->layout_plan_images,true); foreach($decodeLayoutDetails as $key => $val){ $projectWingName = ProjectWing::select('wing_name')->where('id', $val['wing'])->get(); $layoutTitle[$key] = ["image" => $val['layout_plan_images'],"title" => $projectWingName[0]->wing_name]; } } /**************getSpecifiction**************/ if(!empty($getProjectDetails[0])){ $result = ['success' => true, 'details' => $getProjectDetails[0], 'projectStatusRecords' => $getProjectStatusRecords, 'specificationTitle' => $specificationTitle, 'floorTitle' => $floorTitle, 'layoutTitle' => $layoutTitle, 'getProjectInventory' => $getProjectInventory ]; }else{ $result = ['success' => false, 'details' => array(), 'projectStatusRecords' => array(), 'specificationTitle' => array(), 'floorTitle' => array(), 'layoutTitle' => array(), 'getProjectInventory' => array()]; } return json_encode($result); } public function getAmenitiesListOnEdit() { $postdata = file_get_contents("php://input"); $request = json_decode($postdata, true); $amenityId = $request['data']; $arr = explode(",", $amenityId); $getAmenityList = MlstBmsbAmenity::select('id', 'name_of_amenity')->whereIn('id', $arr)->get(); if (!empty($getAmenityList)) { $result = ['success' => true, 'records' => $getAmenityList]; } else { $result = ['success' => false, 'message' => 'Something Went Wrong']; } return json_encode($result); } public function getInventoryDetails() { $postdata = file_get_contents("php://input"); $request = json_decode($postdata, true); $projectId = $request['data']['projectId']; if ($request['data']['wingId'] == 0) { $projectWing = ProjectWing::select('id', 'project_id', 'wing_name', 'number_of_floors')->where('project_id', $projectId)->orderBy('id', 'ASC')->first(); $projectData = ProjectBlock::where([['wing_id','=',$projectWing->id],['project_id','=',$projectId]])->orderBy('wing_id', 'ASC')->get(); } else { $projectData = ProjectBlock::where([['wing_id','=',$request['data']['wingId']],['project_id','=',$projectId]])->get(); } if (!empty($projectData)) { $result = ['success' => true, 'records' => $projectData]; } else { $result = ['success' => false, 'message' => 'Something went wrong']; } return json_encode($result); } public function getBlocks() { $postdata = file_get_contents("php://input"); $request = json_decode($postdata, true); $projectId = $request['data']['projectId']; $getBlockList = ProjectBlock::with('getBlockType')->where("project_id",$projectId)->get(); if (!empty($getBlockList)) { $result = ['success' => true, 'records' => $getBlockList]; } else { $result = ['success' => false, 'message' => 'Something Went Wrong']; } return json_encode($result); } public function deleteStatus(){ $postdata = file_get_contents("php://input"); $request = json_decode($postdata, true); $statusId = $request['data']['statusId']; if(!empty($request['data']['selectedImages'])){ foreach($request['data']['selectedImages'] as $key => $value){ $path = "/project/images/".$value; S3::s3FileDelete($path); } } ProjectStatus::where('id', $statusId)->delete(); $msg = "Record has been deleted successfully"; $getProjectStatusRecords = ProjectStatus::select('id', 'images', 'status', 'short_description')->get(); $result = ['success' => true, 'message' => $msg, 'records' => $getProjectStatusRecords]; return json_encode($result); } public function deleteImage(){ $postdata = file_get_contents("php://input"); $request = json_decode($postdata, true); if($request['tblFieldName'] == "specification_images"){ $selectedImgs = json_encode($request['selectedImg']); $decodeValue = json_decode($request['delImgName']); $path = $request['folderName'].$decodeValue->image; $deleteImg = S3::s3FileDelete($path); }else{ $selectedImgs = implode(',', $request['selectedImg']); $path = $request['folderName'].$request['delImgName']; $deleteImg = S3::s3FileDelete($path); } if ($deleteImg) { ProjectWebPage::where('id', $request['tblRowId'])->update([$request['tblFieldName'] => $selectedImgs]); $result = ['success' => true, 'message' => "Image deleted successfully"]; } else { $result = ['success' => false, 'message' => "Something went wrong. Please check internet connection"]; } return json_encode($result); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { // } public function webPage() { return view("Projects::webpage"); } public function projectType() { $typeList = MlstBmsbProjectType::all(); if (!empty($typeList)) { $result = ['success' => true, 'records' => $typeList]; } else { $result = ['success' => false, 'message' => 'Something went wrong']; } return json_encode($result); } public function projectStatus() { $typeStatus = MlstBmsbProjectStatus::all(); if (!empty($typeStatus)) { $result = ['success' => true, 'records' => $typeStatus]; } else { $result = ['success' => false, 'message' => 'Something went wrong']; } return json_encode($result); } public function getWings() { $postdata = file_get_contents("php://input"); $request = json_decode($postdata, true); $projectId = $request['data']['projectId']; $projectWing = ProjectWing::select('id', 'project_id', 'wing_name', 'number_of_floors')->where('project_id', $projectId)->get(); if (!empty($projectWing)) { $result = ['success' => true, 'records' => $projectWing]; } else { $result = ['success' => false, 'message' => 'Something went wrong']; } return json_encode($result); } }
20,319
https://github.com/velteren/basic-js/blob/master/src/extended-repeater.js
Github Open Source
Open Source
MIT
null
basic-js
velteren
JavaScript
Code
109
338
const CustomError = require("../extensions/custom-error"); module.exports = function repeater(str, options) { str = str + ''; let result = []; result[0] = str; if (options.repeatTimes === undefined) options.repeatTimes = 1; if (options.separator === undefined) options.separator = '+'; if (options.addition === undefined) options.addition = ''; if (options.additionRepeatTimes === undefined) options.additionRepeatTimes = 1; if (options.additionSeparator === undefined) options.additionSeparator = '|'; let counter = options.repeatTimes - 1; let tmparr = []; tmparr[0] = String(options.addition); for (let i = 0; i < options.additionRepeatTimes; i++) { if (i !== options.additionRepeatTimes - 1) { tmparr.push(options.additionSeparator); tmparr.push(String(options.addition)); } } let addition_union = tmparr.join(''); while (counter) { result.push(addition_union); result.push(options.separator); result.push(str); counter -= 1; } result.push(addition_union); return result.join(''); };
24,191
https://github.com/cypherdotXd/o3de/blob/master/Gems/LyShine/Code/Source/UiTooltipDisplayComponent.cpp
Github Open Source
Open Source
Apache-2.0, MIT
2,021
o3de
cypherdotXd
C++
Code
2,218
8,996
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "UiTooltipDisplayComponent.h" #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/RTTI/BehaviorContext.h> #include <AzCore/std/sort.h> #include <LyShine/Bus/UiTransform2dBus.h> #include <LyShine/Bus/UiElementBus.h> #include <LyShine/Bus/UiTextBus.h> #include <LyShine/Bus/UiCanvasBus.h> #include <LyShine/Bus/UiTooltipDataPopulatorBus.h> #include <LyShine/UiSerializeHelpers.h> #include <ITimer.h> //////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// UiTooltipDisplayComponent::UiTooltipDisplayComponent() : m_triggerMode(TriggerMode::OnHover) , m_autoPosition(true) , m_autoPositionMode(AutoPositionMode::OffsetFromMouse) , m_offset(0.0f, -10.0f) , m_autoSize(true) , m_delayTime(0.5f) , m_displayTime(5.0f) , m_state(State::Hidden) , m_stateStartTime(-1.0f) , m_curDelayTime(-1.0f) , m_timeSinceLastShown(-1.0f) , m_maxWrapTextWidth(-1.0f) , m_showSequence(nullptr) , m_hideSequence(nullptr) { } //////////////////////////////////////////////////////////////////////////////////////////////////// UiTooltipDisplayComponent::~UiTooltipDisplayComponent() { } //////////////////////////////////////////////////////////////////////////////////////////////////// UiTooltipDisplayInterface::TriggerMode UiTooltipDisplayComponent::GetTriggerMode() { return m_triggerMode; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetTriggerMode(TriggerMode triggerMode) { m_triggerMode = triggerMode; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool UiTooltipDisplayComponent::GetAutoPosition() { return m_autoPosition; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetAutoPosition(bool autoPosition) { m_autoPosition = autoPosition; } //////////////////////////////////////////////////////////////////////////////////////////////////// UiTooltipDisplayInterface::AutoPositionMode UiTooltipDisplayComponent::GetAutoPositionMode() { return m_autoPositionMode; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetAutoPositionMode(AutoPositionMode autoPositionMode) { m_autoPositionMode = autoPositionMode; } //////////////////////////////////////////////////////////////////////////////////////////////////// const AZ::Vector2& UiTooltipDisplayComponent::GetOffset() { return m_offset; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetOffset(const AZ::Vector2& offset) { m_offset = offset; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool UiTooltipDisplayComponent::GetAutoSize() { return m_autoSize; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetAutoSize(bool autoSize) { m_autoSize = autoSize; } //////////////////////////////////////////////////////////////////////////////////////////////////// AZ::EntityId UiTooltipDisplayComponent::GetTextEntity() { return m_textEntity; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetTextEntity(AZ::EntityId textEntity) { m_textEntity = textEntity; } //////////////////////////////////////////////////////////////////////////////////////////////////// float UiTooltipDisplayComponent::GetDelayTime() { return m_delayTime; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetDelayTime(float delayTime) { m_delayTime = delayTime; } //////////////////////////////////////////////////////////////////////////////////////////////////// float UiTooltipDisplayComponent::GetDisplayTime() { return m_displayTime; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetDisplayTime(float displayTime) { m_displayTime = displayTime; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::PrepareToShow(AZ::EntityId tooltipElement) { m_tooltipElement = tooltipElement; // We should be in the hidden state AZ_Assert(((m_state == State::Hiding) || (m_state == State::Hidden)), "State is not hidden when attempting to show tooltip"); if (m_state != State::Hidden) { EndTransitionState(); SetState(State::Hidden); } m_curDelayTime = m_delayTime; SetState(State::DelayBeforeShow); } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::Hide() { switch (m_state) { case State::Showing: { // Since sequences can't have keys that represent current values, // only play the hide animation if the show animation has completed. m_timeSinceLastShown = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); EndTransitionState(); SetState(State::Hidden); } break; case State::Shown: { m_timeSinceLastShown = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); // Check if there is a hide animation to play IUiAnimationSystem* animSystem = nullptr; PrepareSequenceForPlay(m_hideSequenceName, m_hideSequence, animSystem); if (m_hideSequence) { SetState(State::Hiding); animSystem->PlaySequence(m_hideSequence, nullptr, false, false); } else { SetState(State::Hidden); } } break; case State::DelayBeforeShow: { SetState(State::Hidden); } break; default: break; } } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::Update() { if (m_state == State::DelayBeforeShow) { // Check if it's time to show the tooltip if ((gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI) - m_stateStartTime) >= m_curDelayTime) { // Make sure nothing has changed with the hover interactable if (m_tooltipElement.IsValid() && UiTooltipDataPopulatorBus::FindFirstHandler(m_tooltipElement)) { Show(); } else { Hide(); } } } else if (m_state == State::Shown) { // Check if it's time to hide the tooltip if (m_displayTime >= 0.0f) { if ((gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI) - m_stateStartTime) >= m_displayTime) { // Hide tooltip Hide(); } } } } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::InGamePostActivate() { SetState(State::Hidden); } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::OnUiAnimationEvent(EUiAnimationEvent uiAnimationEvent, IUiAnimSequence* animSequence) { if (m_state == State::Showing && animSequence == m_showSequence) { if ((uiAnimationEvent == eUiAnimationEvent_Stopped) || (uiAnimationEvent == eUiAnimationEvent_Aborted)) { SetState(State::Shown); } } else if (m_state == State::Hiding && animSequence == m_hideSequence) { if ((uiAnimationEvent == eUiAnimationEvent_Stopped) || (uiAnimationEvent == eUiAnimationEvent_Aborted)) { SetState(State::Hidden); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// UiTooltipDisplayComponent::State UiTooltipDisplayComponent::GetState() { return m_state; } //////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC STATIC MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context); if (serializeContext) { serializeContext->Class<UiTooltipDisplayComponent, AZ::Component>() ->Version(2, &VersionConverter) ->Field("TriggerMode", &UiTooltipDisplayComponent::m_triggerMode) ->Field("AutoPosition", &UiTooltipDisplayComponent::m_autoPosition) ->Field("AutoPositionMode", &UiTooltipDisplayComponent::m_autoPositionMode) ->Field("Offset", &UiTooltipDisplayComponent::m_offset) ->Field("AutoSize", &UiTooltipDisplayComponent::m_autoSize) ->Field("Text", &UiTooltipDisplayComponent::m_textEntity) ->Field("DelayTime", &UiTooltipDisplayComponent::m_delayTime) ->Field("DisplayTime", &UiTooltipDisplayComponent::m_displayTime) ->Field("ShowSequence", &UiTooltipDisplayComponent::m_showSequenceName) ->Field("HideSequence", &UiTooltipDisplayComponent::m_hideSequenceName); AZ::EditContext* ec = serializeContext->GetEditContext(); if (ec) { auto editInfo = ec->Class<UiTooltipDisplayComponent>("TooltipDisplay", "A component that handles how the tooltip element is to be displayed."); editInfo->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "UI") ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/UiTooltipDisplay.png") ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/UiTooltipDisplay.png") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("UI", 0x27ff46b0)) ->Attribute(AZ::Edit::Attributes::AutoExpand, true); editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTooltipDisplayComponent::m_triggerMode, "Trigger Mode", "Sets the way the tooltip is triggered to display.") ->EnumAttribute(UiTooltipDisplayInterface::TriggerMode::OnHover, "On Hover") ->EnumAttribute(UiTooltipDisplayInterface::TriggerMode::OnPress, "On Press") ->EnumAttribute(UiTooltipDisplayInterface::TriggerMode::OnClick, "On Click"); editInfo->DataElement(0, &UiTooltipDisplayComponent::m_autoPosition, "Auto position", "Whether the element will automatically be positioned.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ_CRC("RefreshEntireTree", 0xefbc823c)); editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTooltipDisplayComponent::m_autoPositionMode, "Positioning", "Sets the positioning behavior of the element.") ->EnumAttribute(UiTooltipDisplayInterface::AutoPositionMode::OffsetFromMouse, "Offset from mouse") ->EnumAttribute(UiTooltipDisplayInterface::AutoPositionMode::OffsetFromElement, "Offset from element") ->Attribute(AZ::Edit::Attributes::Visibility, &UiTooltipDisplayComponent::m_autoPosition); editInfo->DataElement(0, &UiTooltipDisplayComponent::m_offset, "Offset", "The offset to use when positioning the element.") ->Attribute(AZ::Edit::Attributes::Visibility, &UiTooltipDisplayComponent::m_autoPosition); editInfo->DataElement(0, &UiTooltipDisplayComponent::m_autoSize, "Auto size", "Whether the element will automatically be sized so that the text element's size is the same as the size of the tooltip string.\n" "If auto size is on, the text element's anchors should be apart."); editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTooltipDisplayComponent::m_textEntity, "Text", "The UI element to hold the main tooltip text. Also used for auto sizing.") ->Attribute(AZ::Edit::Attributes::EnumValues, &UiTooltipDisplayComponent::PopulateTextEntityList); editInfo->DataElement(0, &UiTooltipDisplayComponent::m_delayTime, "Delay Time", "The amount of time to wait before displaying the element."); editInfo->DataElement(0, &UiTooltipDisplayComponent::m_displayTime, "Display Time", "The amount of time the element is to be displayed."); editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTooltipDisplayComponent::m_showSequenceName, "Show Sequence", "The sequence to be played when the element is about to show.") ->Attribute(AZ::Edit::Attributes::StringList, &UiTooltipDisplayComponent::PopulateSequenceList); editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiTooltipDisplayComponent::m_hideSequenceName, "Hide Sequence", "The sequence to be played when the element is about to hide.") ->Attribute(AZ::Edit::Attributes::StringList, &UiTooltipDisplayComponent::PopulateSequenceList); } } AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context); if (behaviorContext) { behaviorContext->Enum<(int)UiTooltipDisplayInterface::AutoPositionMode::OffsetFromMouse>("eUiTooltipDisplayAutoPositionMode_OffsetFromMouse") ->Enum<(int)UiTooltipDisplayInterface::AutoPositionMode::OffsetFromElement>("eUiTooltipDisplayAutoPositionMode_OffsetFromElement"); behaviorContext->Enum<(int)UiTooltipDisplayInterface::TriggerMode::OnHover>("eUiTooltipDisplayTriggerMode_OnHover") ->Enum<(int)UiTooltipDisplayInterface::TriggerMode::OnPress>("eUiTooltipDisplayTriggerMode_OnPress") ->Enum<(int)UiTooltipDisplayInterface::TriggerMode::OnPress>("eUiTooltipDisplayTriggerMode_OnClick"); behaviorContext->EBus<UiTooltipDisplayBus>("UiTooltipDisplayBus") ->Event("GetTriggerMode", &UiTooltipDisplayBus::Events::GetTriggerMode) ->Event("SetTriggerMode", &UiTooltipDisplayBus::Events::SetTriggerMode) ->Event("GetAutoPosition", &UiTooltipDisplayBus::Events::GetAutoPosition) ->Event("SetAutoPosition", &UiTooltipDisplayBus::Events::SetAutoPosition) ->Event("GetAutoPositionMode", &UiTooltipDisplayBus::Events::GetAutoPositionMode) ->Event("SetAutoPositionMode", &UiTooltipDisplayBus::Events::SetAutoPositionMode) ->Event("GetOffset", &UiTooltipDisplayBus::Events::GetOffset) ->Event("SetOffset", &UiTooltipDisplayBus::Events::SetOffset) ->Event("GetAutoSize", &UiTooltipDisplayBus::Events::GetAutoSize) ->Event("SetAutoSize", &UiTooltipDisplayBus::Events::SetAutoSize) ->Event("GetTextEntity", &UiTooltipDisplayBus::Events::GetTextEntity) ->Event("SetTextEntity", &UiTooltipDisplayBus::Events::SetTextEntity) ->Event("GetDelayTime", &UiTooltipDisplayBus::Events::GetDelayTime) ->Event("SetDelayTime", &UiTooltipDisplayBus::Events::SetDelayTime) ->Event("GetDisplayTime", &UiTooltipDisplayBus::Events::GetDisplayTime) ->Event("SetDisplayTime", &UiTooltipDisplayBus::Events::SetDisplayTime) ->VirtualProperty("DelayTime", "GetDelayTime", "SetDelayTime") ->VirtualProperty("DisplayTime", "GetDisplayTime", "SetDisplayTime"); behaviorContext->Class<UiTooltipDisplayComponent>()->RequestBus("UiTooltipDisplayBus"); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // PROTECTED MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::Activate() { UiTooltipDisplayBus::Handler::BusConnect(GetEntityId()); UiInitializationBus::Handler::BusConnect(GetEntityId()); } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::Deactivate() { UiTooltipDisplayBus::Handler::BusDisconnect(GetEntityId()); UiInitializationBus::Handler::BusDisconnect(GetEntityId()); // Stop listening for animation actions. The sequences may have been deleted at this point, // so first check if they still exist. IUiAnimationSystem* animSystem = nullptr; IUiAnimSequence* sequence; if (m_listeningForAnimationEvents) { m_listeningForAnimationEvents = false; sequence = GetSequence(m_showSequenceName, animSystem); if (sequence) { animSystem->RemoveUiAnimationListener(sequence, this); } sequence = GetSequence(m_hideSequenceName, animSystem); if (sequence) { animSystem->RemoveUiAnimationListener(sequence, this); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::SetState(State state) { m_state = state; m_stateStartTime = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); switch (m_state) { case State::Hiding: UiTooltipDisplayNotificationBus::Event(m_tooltipElement, &UiTooltipDisplayNotificationBus::Events::OnHiding); break; case State::Hidden: UiTooltipDisplayNotificationBus::Event(m_tooltipElement, &UiTooltipDisplayNotificationBus::Events::OnHidden); UiElementBus::Event(GetEntityId(), &UiElementBus::Events::SetIsEnabled, false); break; case State::Showing: case State::Shown: UiElementBus::Event(GetEntityId(), &UiElementBus::Events::SetIsEnabled, true); if (m_state == State::Showing) { UiTooltipDisplayNotificationBus::Event(m_tooltipElement, &UiTooltipDisplayNotificationBus::Events::OnShowing); } else { UiTooltipDisplayNotificationBus::Event(m_tooltipElement, &UiTooltipDisplayNotificationBus::Events::OnShown); } break; default: break; } } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::EndTransitionState() { if (m_state == State::Showing) { if (m_showSequence) { IUiAnimationSystem* animSystem = GetAnimationSystem(); if (animSystem) { animSystem->StopSequence(m_showSequence); } } SetState(State::Shown); } else if (m_state == State::Hiding) { if (m_hideSequence) { IUiAnimationSystem* animSystem = GetAnimationSystem(); if (animSystem) { animSystem->StopSequence(m_hideSequence); } } SetState(State::Hidden); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::Show() { // It is assumed that current state is DelayBeforeShow if (m_autoSize && m_textEntity.IsValid()) { // Initialize max wrap text width if (m_maxWrapTextWidth < 0.0f) { UiTransformInterface::Rect textRect; EBUS_EVENT_ID(m_textEntity, UiTransformBus, GetCanvasSpaceRectNoScaleRotate, textRect); m_maxWrapTextWidth = textRect.GetWidth(); } // If wrapping is on, reset display element to its original width UiTextInterface::WrapTextSetting wrapSetting = UiTextInterface::WrapTextSetting::NoWrap; EBUS_EVENT_ID_RESULT(wrapSetting, m_textEntity, UiTextBus, GetWrapText); if (wrapSetting != UiTextInterface::WrapTextSetting::NoWrap) { UiTransformInterface::Rect textRect; EBUS_EVENT_ID(m_textEntity, UiTransformBus, GetCanvasSpaceRectNoScaleRotate, textRect); AZ::Vector2 delta(m_maxWrapTextWidth - textRect.GetWidth(), 0.0f); ResizeElementByDelta(GetEntityId(), delta); } } // Assign tooltip data to the tooltip display element EBUS_EVENT_ID(m_tooltipElement, UiTooltipDataPopulatorBus, PushDataToDisplayElement, GetEntityId()); // Auto-resize display element so that the text element is the same size as the size of its text string if (m_autoSize && m_textEntity.IsValid()) { AutoResize(); } // Auto-position display element if (m_autoPosition) { AutoPosition(); } // Check if there is a show animation to play IUiAnimationSystem* animSystem = nullptr; PrepareSequenceForPlay(m_showSequenceName, m_showSequence, animSystem); if (m_showSequence) { SetState(State::Showing); animSystem->PlaySequence(m_showSequence, nullptr, false, false); } else { SetState(State::Shown); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::AutoResize() { // Get the text string size AZ::Vector2 stringSize(-1.0f, -1.0f); EBUS_EVENT_ID_RESULT(stringSize, m_textEntity, UiTextBus, GetTextSize); if (stringSize.GetX() < 0.0f || stringSize.GetY() < 0.0f) { return; } // Get the text element's rect UiTransformInterface::Rect textRect; EBUS_EVENT_ID(m_textEntity, UiTransformBus, GetCanvasSpaceRectNoScaleRotate, textRect); // Get the difference between the text element's size and the string size AZ::Vector2 delta(stringSize.GetX() - textRect.GetWidth(), stringSize.GetY() - textRect.GetHeight()); UiTextInterface::WrapTextSetting wrapSetting; EBUS_EVENT_ID_RESULT(wrapSetting, m_textEntity, UiTextBus, GetWrapText); if (wrapSetting != UiTextInterface::WrapTextSetting::NoWrap) { // In order for the wrapping to remain the same after the resize, the // text element width would need to match the string width exactly. To accommodate // for slight variation in size, add a small value to ensure that the string will fit // inside the text element's bounds. The downside to this is there may be extra space // at the bottom, but this is unlikely. const float epsilon = 0.01f; delta.SetX(delta.GetX() + epsilon); } // Resize the display element by the difference ResizeElementByDelta(GetEntityId(), delta); } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::ResizeElementByDelta(AZ::EntityId entityId, const AZ::Vector2& delta) { if ((delta.GetX() != 0.0f) || (delta.GetY() != 0.0f)) { // Resize the element based on the difference UiTransform2dInterface::Offsets offsets; EBUS_EVENT_ID_RESULT(offsets, entityId, UiTransform2dBus, GetOffsets); AZ::Vector2 pivot; EBUS_EVENT_ID_RESULT(pivot, entityId, UiTransformBus, GetPivot); if (delta.GetX() != 0.0f) { float leftOffsetDelta = delta.GetX() * pivot.GetX(); offsets.m_left -= leftOffsetDelta; offsets.m_right += delta.GetX() - leftOffsetDelta; } if (delta.GetY() != 0.0f) { float topOffsetDelta = delta.GetY() * pivot.GetY(); offsets.m_top -= topOffsetDelta; offsets.m_bottom += delta.GetY() - topOffsetDelta; } EBUS_EVENT_ID(entityId, UiTransform2dBus, SetOffsets, offsets); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::AutoPosition() { bool havePosition = false; AZ::Vector2 position(-1.0f, -1.0f); if (m_autoPositionMode == UiTooltipDisplayInterface::AutoPositionMode::OffsetFromMouse) { // Get current mouse position AZ::EntityId canvasId; EBUS_EVENT_ID_RESULT(canvasId, GetEntityId(), UiElementBus, GetCanvasEntityId); EBUS_EVENT_ID_RESULT(position, canvasId, UiCanvasBus, GetMousePosition); if (position.GetX() >= 0.0f && position.GetY() >= 0.0f) { // Check if the mouse is hovering over the tooltip element EBUS_EVENT_ID_RESULT(havePosition, m_tooltipElement, UiTransformBus, IsPointInRect, position); } } if (!havePosition) { // Get the pivot position of the tooltip element EBUS_EVENT_ID_RESULT(position, m_tooltipElement, UiTransformBus, GetViewportSpacePivot); } MoveToPosition(position, m_offset); } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::MoveToPosition(const AZ::Vector2& point, const AZ::Vector2& offsetFromPoint) { // Move the display element so that its pivot is a certain distance from the point UiTransform2dInterface::Offsets offsets; EBUS_EVENT_ID_RESULT(offsets, GetEntityId(), UiTransform2dBus, GetOffsets); AZ::Vector2 pivot; EBUS_EVENT_ID_RESULT(pivot, GetEntityId(), UiTransformBus, GetViewportSpacePivot); AZ::Vector2 moveDist = (point + offsetFromPoint) - pivot; offsets += moveDist; EBUS_EVENT_ID(GetEntityId(), UiTransform2dBus, SetOffsets, offsets); // Make sure that the display element stays within the bounds of its parent // Get parent rect UiTransformInterface::Rect parentRect; AZ::Entity* parentEntity = nullptr; EBUS_EVENT_ID_RESULT(parentEntity, GetEntityId(), UiElementBus, GetParent); if (parentEntity) { EBUS_EVENT_ID(parentEntity->GetId(), UiTransformBus, GetCanvasSpaceRectNoScaleRotate, parentRect); } else { AZ::EntityId canvasEntityId; EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); AZ::Vector2 size; EBUS_EVENT_ID_RESULT(size, canvasEntityId, UiCanvasBus, GetCanvasSize); parentRect.Set(0.0f, size.GetX(), 0.0f, size.GetY()); } // If the display element exceeds the top/bottom bounds of its parent, the offset // is flipped and applied to the top/bottom of the display element. // If positioning is to be relative to the tooltip element though, this step is skipped // to preserve the original position as much as possible. if (m_autoPositionMode != UiTooltipDisplayInterface::AutoPositionMode::OffsetFromElement) { CheckBoundsAndChangeYPosition(parentRect, point.GetY(), fabs(m_offset.GetY())); } ConstrainToBounds(parentRect); } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::CheckBoundsAndChangeYPosition(const UiTransformInterface::Rect& boundsRect, float yPoint, float yOffsetFromPoint) { // Get display element rect UiTransformInterface::Rect rect = GetAxisAlignedRect(); float yMoveDist = 0.0f; // Check upper and lower bounds if (rect.top < boundsRect.top) { // Move top of display element to an offset below the point yMoveDist = (yPoint + yOffsetFromPoint) - rect.top; } else if (rect.bottom > boundsRect.bottom) { // Move bottom of display element to an offset above the point yMoveDist = (yPoint - yOffsetFromPoint) - rect.bottom; } if (yMoveDist != 0.0f) { UiTransform2dInterface::Offsets offsets; EBUS_EVENT_ID_RESULT(offsets, GetEntityId(), UiTransform2dBus, GetOffsets); offsets.m_top += yMoveDist; offsets.m_bottom += yMoveDist; EBUS_EVENT_ID(GetEntityId(), UiTransform2dBus, SetOffsets, offsets); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::ConstrainToBounds(const UiTransformInterface::Rect& boundsRect) { // Get display element rect UiTransformInterface::Rect rect = GetAxisAlignedRect(); AZ::Vector2 moveDist(0.0f, 0.0f); // Check left and right bounds if (rect.left < boundsRect.left) { moveDist.SetX(boundsRect.left - rect.left); } else if (rect.right > boundsRect.right) { moveDist.SetX(boundsRect.right - rect.right); } // Check upper and lower bounds if (rect.top < boundsRect.top) { moveDist.SetY(boundsRect.top - rect.top); } else if (rect.bottom > boundsRect.bottom) { moveDist.SetY(boundsRect.bottom - rect.bottom); } if (moveDist.GetX() != 0.0f || moveDist.GetY() != 0.0f) { UiTransform2dInterface::Offsets offsets; EBUS_EVENT_ID_RESULT(offsets, GetEntityId(), UiTransform2dBus, GetOffsets); offsets += moveDist; EBUS_EVENT_ID(GetEntityId(), UiTransform2dBus, SetOffsets, offsets); } } //////////////////////////////////////////////////////////////////////////////////////////////////// UiTransformInterface::Rect UiTooltipDisplayComponent::GetAxisAlignedRect() { UiTransformInterface::RectPoints points; EBUS_EVENT_ID(GetEntityId(), UiTransformBus, GetCanvasSpacePointsNoScaleRotate, points); AZ::Matrix4x4 transform; EBUS_EVENT_ID(GetEntityId(), UiTransformBus, GetLocalTransform, transform); points = points.Transform(transform); UiTransformInterface::Rect rect; rect.left = points.GetAxisAlignedTopLeft().GetX(); rect.right = points.GetAxisAlignedBottomRight().GetX(); rect.top = points.GetAxisAlignedTopLeft().GetY(); rect.bottom = points.GetAxisAlignedBottomRight().GetY(); return rect; } //////////////////////////////////////////////////////////////////////////////////////////////////// IUiAnimationSystem* UiTooltipDisplayComponent::GetAnimationSystem() { AZ::EntityId canvasId; EBUS_EVENT_ID_RESULT(canvasId, GetEntityId(), UiElementBus, GetCanvasEntityId); IUiAnimationSystem* animSystem = nullptr; EBUS_EVENT_ID_RESULT(animSystem, canvasId, UiCanvasBus, GetAnimationSystem); return animSystem; } //////////////////////////////////////////////////////////////////////////////////////////////////// IUiAnimSequence* UiTooltipDisplayComponent::GetSequence(const AZStd::string& sequenceName, IUiAnimationSystem*& animSystemOut) { IUiAnimSequence* sequence = nullptr; if (!sequenceName.empty() && (sequenceName != "<None>")) { IUiAnimationSystem* animSystem = GetAnimationSystem(); if (animSystem) { sequence = animSystem->FindSequence(sequenceName.c_str()); animSystemOut = animSystem; } } return sequence; } //////////////////////////////////////////////////////////////////////////////////////////////////// void UiTooltipDisplayComponent::PrepareSequenceForPlay(const AZStd::string& sequenceName, IUiAnimSequence*& sequence, IUiAnimationSystem*& animSystemOut) { IUiAnimationSystem* animSystem = nullptr; if (!sequence) { sequence = GetSequence(sequenceName, animSystem); if (sequence) { m_listeningForAnimationEvents = true; animSystem->AddUiAnimationListener(sequence, this); } } else { animSystem = GetAnimationSystem(); if (!animSystem) { sequence = nullptr; } } if (sequence) { animSystemOut = animSystem; } } //////////////////////////////////////////////////////////////////////////////////////////////////// UiTooltipDisplayComponent::EntityComboBoxVec UiTooltipDisplayComponent::PopulateTextEntityList() { EntityComboBoxVec result; // add a first entry for "None" result.push_back(AZStd::make_pair(AZ::EntityId(AZ::EntityId()), "<None>")); // allow the destination to be the same entity as the source by // adding this entity (if it has a text component) if (UiTextBus::FindFirstHandler(GetEntityId())) { result.push_back(AZStd::make_pair(AZ::EntityId(GetEntityId()), GetEntity()->GetName())); } // Get a list of all descendant elements that support the UiTextBus LyShine::EntityArray matchingElements; EBUS_EVENT_ID(GetEntityId(), UiElementBus, FindDescendantElements, [](const AZ::Entity* entity) { return UiTextBus::FindFirstHandler(entity->GetId()) != nullptr; }, matchingElements); // add their names to the StringList and their IDs to the id list for (auto childEntity : matchingElements) { result.push_back(AZStd::make_pair(AZ::EntityId(childEntity->GetId()), childEntity->GetName())); } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// UiTooltipDisplayComponent::SequenceComboBoxVec UiTooltipDisplayComponent::PopulateSequenceList() { SequenceComboBoxVec result; // add a first entry for "None" result.push_back("<None>"); IUiAnimationSystem* animSystem = GetAnimationSystem(); if (animSystem) { for (int i = 0; i < animSystem->GetNumSequences(); i++) { IUiAnimSequence* sequence = animSystem->GetSequence(i); if (sequence) { result.push_back(sequence->GetName()); } } } // Sort the sequence names SequenceComboBoxVec::iterator iterBegin = result.begin(); ++iterBegin; if (iterBegin < result.end()) { AZStd::sort(iterBegin, result.end(), [](const AZStd::string s1, const AZStd::string s2) { return s1 < s2; }); } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// // PRIVATE STATIC MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// bool UiTooltipDisplayComponent::VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) { // conversion from version 1: // - Need to convert Vec2 to AZ::Vector2 if (classElement.GetVersion() <= 1) { if (!LyShine::ConvertSubElementFromVec2ToVector2(context, classElement, "Offset")) { return false; } } return true; }
48,184
https://github.com/cnojima/vscode-extension-readable-indent/blob/master/src/test/1_alpha-sort.test.ts
Github Open Source
Open Source
MIT
2,020
vscode-extension-readable-indent
cnojima
TypeScript
Code
92
237
import * as assert from 'assert'; import customAlphaSort from '../util/alpha-sort'; suite("Custom Sort Tests", () => { test('normal alphabeticals', () => { const expected = ['a','b','c']; const foo = ['b','c','a']; assert.deepEqual(customAlphaSort(foo), expected); }); test('normal alphabeticals, preserve whitespace', () => { const expected = ['a ', ' b ', ' c']; const foo = [' b ', ' c', 'a ']; assert.deepEqual(customAlphaSort(foo), expected); }); test('alphabetize, handling newlines', () => { const expected = ['', '', 'a', '', 'b', 'c', '']; const foo = ['', '', 'c', '', 'a', 'b', '']; assert.deepEqual(customAlphaSort(foo), expected); }); });
36,960
https://github.com/aldianwillia/minishop/blob/master/application/views/layout/v_nav_frontend.php
Github Open Source
Open Source
MIT
2,021
minishop
aldianwillia
PHP
Code
569
2,343
<!-- Navbar --> <nav class="main-header navbar navbar-expand-md navbar-light navbar-white"> <div class="container"> <a href="<?= base_url() ?>" class="navbar-brand"> <i class="fas fa-store text-primary"></i> <span class="brand-text font-weight-light"><b>Minihop Online</b></span> </a> <button class="navbar-toggler order-1" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse order-3" id="navbarCollapse"> <!-- Left navbar links --> <ul class="navbar-nav"> <li class="nav-item"> <a href="<?= base_url() ?>" class="nav-link">Home</a> </li> <!-- menampung data kategori didalam variabel kategori --> <?php $kategori = $this->m_home->get_all_data_kategori() ?> <!-- END --> <!-- Menu Kategori Dropdown --> <li class="nav-item dropdown"> <a id="dropdownSubMenu1" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">Kategori</a> <ul aria-labelledby="dropdownSubMenu1" class="dropdown-menu border-0 shadow"> <!-- perulangan pemanggilan data kategori--> <?php foreach ($kategori as $key => $value) { ?> <li><a href="<?= base_url('home/kategori/' . $value->id_kategori) ?>" class="dropdown-item"><?= $value->nama_kategori ?></a></li> <?php } ?> <!-- End Looping --> </ul> </li> <!-- Menu Kategori End Dropdown --> <li class="nav-item"> <a href="#" class="nav-link">Contact</a> </li> <li class="nav-item dropdown"> <a id="dropdownSubMenu1" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">Dropdown</a> <ul aria-labelledby="dropdownSubMenu1" class="dropdown-menu border-0 shadow"> <li><a href="#" class="dropdown-item">Some action </a></li> <li><a href="#" class="dropdown-item">Some other action</a></li> </ul> </li> </ul> <!-- Left navbar links End --> </div> <!-- Right navbar links --> <ul class="order-1 order-md-3 navbar-nav navbar-no-expand ml-auto"> <!-- Messages Dropdown Menu --> <li class="nav-item"> <a class="nav-link" data-toggle="dropdown" href="#"> <span class="brand-text font-weight-light">Pelanggan</span> <img src="<?= base_url() ?>template/dist/img/user1-128x128.jpg" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8"> </a> <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right"> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <i class="fas fa-envelope mr-2"></i> 4 new messages <span class="float-right text-muted text-sm">3 mins</span> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <i class="fas fa-users mr-2"></i> 8 friend requests <span class="float-right text-muted text-sm">12 hours</span> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <i class="fas fa-file mr-2"></i> 3 new reports <span class="float-right text-muted text-sm">2 days</span> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item dropdown-footer">See All Notifications</a> </div> </li> <!-- Messages Dropdown Menu End --> <li class="nav-item dropdown"> <a class="nav-link" data-toggle="dropdown" href="#"> <i class="fas fa-shopping-cart"></i> <span class="badge badge-danger navbar-badge">3</span> </a> <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right"> <a href="#" class="dropdown-item"> <!-- Message Start --> <div class="media"> <img src="<?= base_url() ?>template/dist/img/user1-128x128.jpg" alt="User Avatar" class="img-size-50 mr-3 img-circle"> <div class="media-body"> <h3 class="dropdown-item-title"> Brad Diesel <span class="float-right text-sm text-danger"><i class="fas fa-star"></i></span> </h3> <p class="text-sm">Call me whenever you can...</p> <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p> </div> </div> <!-- Message End --> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <!-- Message Start --> <div class="media"> <img src="<?= base_url() ?>template/dist/img/user8-128x128.jpg" alt="User Avatar" class="img-size-50 img-circle mr-3"> <div class="media-body"> <h3 class="dropdown-item-title"> John Pierce <span class="float-right text-sm text-muted"><i class="fas fa-star"></i></span> </h3> <p class="text-sm">I got your message bro</p> <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p> </div> </div> <!-- Message End --> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item"> <!-- Message Start --> <div class="media"> <img src="<?= base_url() ?>template/dist/img/user3-128x128.jpg" alt="User Avatar" class="img-size-50 img-circle mr-3"> <div class="media-body"> <h3 class="dropdown-item-title"> Nora Silvester <span class="float-right text-sm text-warning"><i class="fas fa-star"></i></span> </h3> <p class="text-sm">The subject goes here</p> <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p> </div> </div> <!-- Message End --> </a> <div class="dropdown-divider"></div> <a href="#" class="dropdown-item dropdown-footer">See All Messages</a> </div> </li> </ul> <!-- Right navbar links End --> </div> </nav> <!-- /.navbar --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <div class="content-header"> <!-- /.container-fluid --> <div class="container"> <!-- /.row --> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0 text-dark"><?= $title ?></h1> </div> <!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item"><a href="#">MiniShop</a></li> <li class="breadcrumb-item"><a href="#"><?= $title ?></a></li> </ol> </div> <!-- /.col End--> </div> <!-- /.row End --> </div> <!-- /.container-fluid End --> </div> <!-- /.content-header End --> <!-- Main content --> <div class="content"> <div class="container">
46,082
https://github.com/Chokitus/mq-tests/blob/master/src/main/java/br/edu/ufabc/chokitus/mq/instances/rabbitmq/RabbitMQWrapperFactory.java
Github Open Source
Open Source
MIT
null
mq-tests
Chokitus
Java
Code
195
857
package br.edu.ufabc.chokitus.mq.instances.rabbitmq; import java.util.Map; import java.io.IOException; import com.rabbitmq.client.ConnectionFactory; import br.edu.ufabc.chokitus.mq.exception.MessagingException; import br.edu.ufabc.chokitus.mq.factory.AbstractWrapperFactory; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class RabbitMQWrapperFactory extends AbstractWrapperFactory<RabbitMQConsumer, RabbitMQProducer, RabbitMQMessage, RabbitMQClientFactory> { public RabbitMQWrapperFactory(final Map<String, Object> properties) throws MessagingException { super(properties); } @Override protected void closeImpl() throws Exception { // Unnecessary } @Override protected RabbitMQClientFactory createClientFactory(final Map<String, Object> clientFactoryProperties) throws Exception { final ConnectionFactory factory = new ConnectionFactory(); factory.setHost((String) properties.get(RabbitMQProperty.HOST.getValue())); factory.setPort((int) properties.get(RabbitMQProperty.PORT.getValue())); return new RabbitMQClientFactory(clientFactoryProperties, factory); } @Override protected void startConsumerImpl(final RabbitMQConsumer client, final Map<String, Object> clientStartProperties, final RabbitMQClientFactory clientFactory) throws Exception { initializeQueue(client, clientStartProperties); } @Override protected void startProducerImpl(final RabbitMQProducer client, final Map<String, Object> clientStartProperties, final RabbitMQClientFactory clientFactory) throws Exception { initializeQueue(client, clientStartProperties); } @Override protected RabbitMQMessage createMessageForProducerImpl(final byte[] body, final String destination, final RabbitMQProducer producer, final Map<String, Object> messageProperties, final RabbitMQClientFactory clientFactory) throws Exception { return getMessage(body, destination, messageProperties); } private RabbitMQMessage getMessage(final byte[] body, final String destination, final Map<String, Object> messageProperties) { return new RabbitMQMessage(body, destination, messageProperties); } @SuppressWarnings("unchecked") private void initializeQueue(final RabbitMQClient client, final Map<String, Object> clientStartProperties) throws IOException { client.getChannel().queueDeclare( (String) clientStartProperties.getOrDefault(RabbitMQProperty.QUEUE_PROPERTY.getValue(), ""), (Boolean) clientStartProperties.getOrDefault(RabbitMQProperty.DURABLE_PROPERTY.getValue(), true), (Boolean) clientStartProperties.getOrDefault(RabbitMQProperty.EXCLUSIVE_PROPERTY.getValue(), false), (Boolean) clientStartProperties.getOrDefault(RabbitMQProperty.AUTO_DELETE_PROPERTY.getValue(), false), (Map<String, Object>) clientStartProperties.getOrDefault(RabbitMQProperty.ARGUMENTS_PROPERTY.getValue(), null)); } }
7,876
https://github.com/CivicDataLab/twitter-scraper/blob/master/scraper/listener.py
Github Open Source
Open Source
MIT
null
twitter-scraper
CivicDataLab
Python
Code
436
1,618
import sys import time import csv as csv_lib import datetime import tweepy import simplejson as json import message_recognizers import utils from load_tweets import save_tweets MISSING_FIELD_VALUE = '' def dump_with_timestamp(text, category="Unknown"): print("(%s)--%s--%s" % (category, datetime.datetime.now(), text)) def dump_stream_data(stream_data): dump_with_timestamp(stream_data) class StreamListener(tweepy.StreamListener): """ Tweepy StreamListener that dumps tweets to stdout. """ def __init__(self, opts, logger, api=None): super(StreamListener, self).__init__(api=api) self.opts = opts self.csv_writer = csv_lib.writer(sys.stdout) self.running = True self.first_message_received = None self.status_count = 0 self.logger = logger # Create a list of recognizer instances, in decreasing priority order. self.recognizers = ( message_recognizers.DataContainsRecognizer( handler_method=self.parse_status_and_dispatch, match_string='"in_reply_to_user_id_str":'), message_recognizers.DataContainsRecognizer( handler_method=self.parse_limit_and_dispatch, match_string='"limit":{'), message_recognizers.DataContainsRecognizer( handler_method=self.parse_warning_and_dispatch, match_string='"warning":'), message_recognizers.DataContainsRecognizer( handler_method=self.on_disconnect, match_string='"disconnect":'), # Everything else is sent to logger message_recognizers.MatchAnyRecognizer( handler_method=self.on_unrecognized), ) def on_unrecognized(self, stream_data): self.logger.warn("Unrecognized: %s", stream_data.strip()) def on_disconnect(self, stream_data): msg = json.loads(stream_data) self.logger.warn("Disconnect: code: %d stream_name: %s reason: %s", utils.resolve_with_default(msg, 'disconnect.code', 0), utils.resolve_with_default(msg, 'disconnect.stream_name', 'n/a'), utils.resolve_with_default(msg, 'disconnect.reason', 'n/a')) def parse_warning_and_dispatch(self, stream_data): try: warning = json.loads(stream_data).get('warning') return self.on_warning(warning) except json.JSONDecodeError: self.logger.exception("Exception parsing: %s" % stream_data) return False def parse_status_and_dispatch(self, stream_data): """ Process an incoming status message. """ status = tweepy.models.Status.parse(self.api, json.loads(stream_data)) if self.tweet_matchp(status): self.status_count += 1 if self.should_stop(): self.running = False return False save_tweets([stream_data.strip()]) print(stream_data.strip()) def parse_limit_and_dispatch(self, stream_data): return self.on_limit(json.loads(stream_data)['limit']['track']) def is_retweet(self, tweet): return hasattr(tweet, 'retweeted_status') \ or tweet.text.startswith('RT ') \ or ' RT ' in tweet.text def tweet_matchp(self, tweet): """Return True if tweet matches selection criteria... Currently this filters on self.opts.lang if it is not nothing... """ if self.opts.no_retweets and self.is_retweet(tweet): return False else: return True def on_warning(self, warning): self.logger.warn("Warning: code=%s message=%s" % (warning['code'], warning['message'])) # If code='FALLING_BEHIND' buffer state is in warning['percent_full'] def on_error(self, status_code): self.logger.error("StreamListener.on_error: %r" % status_code) if status_code != 401: self.logger.error(" -- stopping.") # Stop on anything other than a 401 error (Unauthorized) # Stop main loop. self.running = False return False def on_timeout(self): """Called when there's a timeout in communications. Return False to stop processing. """ self.logger.warn('on_timeout') return ## Continue streaming. def on_data(self, data): if not self.first_message_received: self.first_message_received = int(time.time()) if self.should_stop(): self.running = False return False # Exit main loop. for r in self.recognizers: if r.match(data): if r.handle_message(data) is False: # Terminate main loop. self.running = False return False # Stop streaming # Don't execute any other recognizers, and don't call base # on_data() because we've already handled the message. return # Don't execute any of the base class on_data() handlers. return def should_stop(self): """ Return True if processing should stop. """ if self.opts.duration: if self.first_message_received: et = int(time.time()) - self.first_message_received flag = et >= self.opts.duration if flag: self.logger.debug("Stop requested due to duration limits (et=%d, target=%d seconds).", et, self.opts.duration) return flag if self.opts.max_tweets and self.status_count > self.opts.max_tweets: self.logger.debug("Stop requested due to count limits (%d)." % self.opts.max_tweets) return True return False
40,774
https://github.com/tqt97/Laravel8MultiAuth/blob/master/routes/web.php
Github Open Source
Open Source
MIT
2,021
Laravel8MultiAuth
tqt97
PHP
Code
200
920
<?php use App\Http\Controllers\Backend\AdminController; use App\Http\Controllers\Backend\DashboardController; use App\Http\Controllers\Backend\FileUploadController; use App\Http\Controllers\Backend\Products\ProductCategoryController; use App\Http\Controllers\Backend\Products\ProductController; use App\Http\Controllers\LogoutController; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); // Route::get('upload-ui', [FileUploadController::class, 'dropzoneUi']); // Route::post('file-upload', [FileUploadController::class, 'dropzoneFileUpload'])->name('dropzoneFileUpload'); Route::group(['prefix' => 'admin', 'as' => 'admin.', 'middleware' => ['admin:admin']], function () { Route::get('/', [AdminController::class, 'loginForm']); Route::post('/', [AdminController::class, 'store'])->name('login'); }); Route::post('/admin/logout', [AdminController::class, 'destroy'])->name('admin.logout')->middleware('auth:admin'); Route::post('/logout', LogoutController::class)->name('logout')->middleware('auth:web'); // Route::middleware(['auth.admin:admin', 'verified'])->get('/admin/dashboard', function () { // return view('ad'); // })->name('admin.dashboard'); Route::middleware(['auth:sanctum,web', 'verified'])->get('/dashboard', function () { return view('dashboard'); })->name('dashboard'); Route::group(['prefix' => 'admin', 'as' => 'admin.', 'middleware' => ['auth.admin:admin']], function () { Route::get('/dashboard', DashboardController::class)->name('dashboard'); Route::group(['prefix' => 'product', 'as' => 'product.'], function () { Route::group(['prefix' => 'category', 'as' => 'category.'], function () { Route::get('/', [ProductCategoryController::class, 'index'])->name('index'); Route::get('/create', [ProductCategoryController::class, 'create'])->name('create'); Route::post('/store', [ProductCategoryController::class, 'store'])->name('store'); Route::get('/edit/{id}', [ProductCategoryController::class, 'edit'])->name('edit'); Route::post('/update/{id}', [ProductCategoryController::class, 'update'])->name('update'); Route::get('/destroy/{id}', [ProductCategoryController::class, 'destroy'])->name('destroy'); Route::get('/updateStatus', [ProductCategoryController::class, 'updateStatus'])->name('updateStatus'); }); Route::group(['prefix' => 'product', 'as' => 'product.'], function () { Route::get('/', [ProductController::class, 'index'])->name('index'); Route::get('/create', [ProductController::class, 'create'])->name('create'); Route::post('/store', [ProductController::class, 'store'])->name('store'); Route::get('/edit', [ProductController::class, 'edit'])->name('edit'); Route::post('/update', [ProductController::class, 'update'])->name('update'); Route::get('/destroy', [ProductController::class, 'destroy'])->name('destroy'); }); }); });
8,798
https://github.com/darknech97/grupo_satelite/blob/master/app/Http/Controllers/AlumnoController.php
Github Open Source
Open Source
MIT
null
grupo_satelite
darknech97
PHP
Code
299
999
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Alumno; use App\Models\Grado; use DB; class AlumnoController extends Controller { public $timestamps = false; /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //Requests list of data from data base $alumnos = Alumno::with('grado','grado.materias', 'grado.materias.materia')->get(); $grados = Grado::all(); return view('alumnos', compact('alumnos','grados')); //Encodes in json format all the data found $json = json_decode($alumnos , true); //Returns json return $json; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { echo "Create Alumno"; } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { try { $request->validate([ 'alm_codigo' => 'required', 'alm_nombre' => 'required', 'alm_edad' => 'required', ]); Alumno::create($request->all()); return redirect()->route('alumnos.index') ->with('success','Product created successfully.'); } catch (Throwable $e) { report($e); return false; } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Request $request,$id) { // echo $request['alm_id']; try{ DB::update('update alm_alumno set alm_codigo = ?,alm_nombre=?,alm_edad=?,alm_sexo=?,alm_id_grd=?,alm_observacion=? where alm_id = ?', [$request['alm_codigo'],$request['alm_nombre'],$request['alm_edad'],$request['alm_sexo'],$request['alm_id_grd'],$request['alm_observacion'],$request['alm_id']]); return redirect()->route('alumnos.index') ->with('success','Product created successfully.'); } catch (Throwable $e) { report($e); return false; } } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ Public function edit($id) { echo "Edit Alumno"; } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { echo "Update Alumno"; } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { try{ DB::delete('delete from alm_alumno where alm_id = ?',[$id]); return redirect()->route('alumnos.index') ->with('success','Product created successfully.'); } catch (Throwable $e) { report($e); return false; } } }
1,702
https://github.com/davelooi/interapp/blob/master/app/services/interapp/receive_message_service.rb
Github Open Source
Open Source
MIT
2,021
interapp
davelooi
Ruby
Code
56
221
module Interapp class ReceiveMessageService attr :message, :peer, :data, :return_value def initialize(payload:, peer_identifier:, signature:) find_peer(peer_identifier) @message = Message.new(payload: payload, peer: @peer, signature: signature) @data = JSON.load(@message.payload) end def perform if @message.verify @return_value = Interapp.configuration.handler.call(data, message.peer.identifier) else raise Interapp::SignatureInvalidError end rescue OpenSSL::ASN1::ASN1Error raise Interapp::SignatureInvalidError end private def find_peer(peer_identifier) @peer = Interapp::Peer.find(peer_identifier) raise Interapp::UnknownPeerError if @peer.nil? end end end
4,188
https://github.com/VenomBigBozz/Esercizi/blob/master/Uni/c++/programamzione-1/Esempi/laboratorio/varie/distruttori.cpp
Github Open Source
Open Source
Unlicense
null
Esercizi
VenomBigBozz
C++
Code
63
180
#include<iostream> using namespace std; class Classe { int *x; int n; public: Classe(int _n) : n(_n) { x = new int[n]; for(int i=0; i<n; i++) x[i] = i+1; } int getNum(int i) {return x[i];} ~Classe() { delete[] x; cout << "Eseguito il distruttore"; } }; int main() { Classe *o = new Classe(3); delete o; o = nullptr; if(o) cout << o->getNum(2); }
10,098
https://github.com/James4Deutschland/lazer/blob/master/GeneralUsageLister/MainIndex/zero/ff
Github Open Source
Open Source
WTFPL, GPL-1.0-or-later
2,020
lazer
James4Deutschland
Shell
Code
4
20
#!/bin/bash ff &> ../zero-log/ff.log
27,911
https://github.com/Zonotora/adventofcode/blob/master/2021/python/17.py
Github Open Source
Open Source
MIT
null
adventofcode
Zonotora
Python
Code
133
361
# flake8: noqa from python import * aoc = AdventOfCode("2021", "17", "", new) def trajectory(items, p1): s = items[0].split("=") [xmin, xmax] = [int(v) for v in s[1].split(",")[0].split("..")] [ymin, ymax] = [int(v) for v in s[2].split("..")] d = 300 answer = 0 for i in range(0, d): for j in range(-d, d): cmax = 0 x, y = 0, 0 vx, vy = i, j while True: x += vx y += vy if vx != 0: vx += -sign(vx) vy -= 1 cmax = max(cmax, y) if xmin <= x <= xmax and ymin <= y <= ymax: if p1: answer = max(answer, cmax) else: answer += 1 break if y <= ymin: break return answer @aoc.part(1) def part1(items): return trajectory(items, True) @aoc.part(2) def part2(items): return trajectory(items, False) if __name__ == "__main__": aoc.solve()
10,424
https://github.com/sntsabode/tkngen-api/blob/master/lib/server.ts
Github Open Source
Open Source
MIT
null
tkngen-api
sntsabode
TypeScript
Code
27
65
import { app as server } from './app' const PORT = process.env.PORT || 9000 server.listen(<number>PORT, '0.0.0.0', async () => { console.log('Server listening on PORT: %s', PORT) })
24,865
https://github.com/npezza93/eighty/blob/master/test/controllers/images_controller_test.rb
Github Open Source
Open Source
MIT
null
eighty
npezza93
Ruby
Code
40
136
# frozen_string_literal: true require "test_helper" class ImagesControllerTest < ActionDispatch::IntegrationTest include ActionDispatch::TestProcess include Devise::Test::IntegrationHelpers test "should create image" do sign_in users(:one) file = fixture_file_upload("files/logo.png", "image/png") assert_difference("Image.count") do post images_url(format: :js), params: { image: { image: file } } end end end
29,796
https://github.com/jeffmckelvey/KittyHawkMQ/blob/master/KittyHawk.MqttLib/Messages/MqttSubscribeAckMessage.cs
Github Open Source
Open Source
MIT
null
KittyHawkMQ
jeffmckelvey
C#
Code
274
833
 using KittyHawk.MqttLib.Collections; using KittyHawk.MqttLib.Interfaces; using KittyHawk.MqttLib.Utilities; namespace KittyHawk.MqttLib.Messages { public sealed class MqttSubscribeAckMessage : IMqttIdMessage { private readonly MqttMessageBase _msg; internal static MqttSubscribeAckMessage InternalDeserialize(byte[] buffer) { var msg = new MqttSubscribeAckMessage(); msg._msg.MsgBuffer = buffer; msg.ReadPayload(); return msg; } internal MqttSubscribeAckMessage() { _msg = new MqttMessageBase(MessageType.SubAck); } #region IMqttMessage public byte[] MessageBuffer { get { return _msg.MsgBuffer; } } public MessageType MessageType { get { return _msg.MessageType; } } public bool Duplicate { get { return _msg.Duplicate; } set { _msg.Duplicate = value; } } public int Retries { get; set; } public QualityOfService QualityOfService { get { return _msg.QualityOfService; } } public bool Retain { get { return _msg.Retain; } } /// <summary> /// Does this message expect a response such as an ACK message? /// </summary> public MessageType ExpectedResponse { get { return MessageType.None; } } public byte[] Serialize() { return _msg.Serialize(); } #endregion private int _messageId; public int MessageId { get { if (!_msg.VariableHeaderRead) { ReadVariableHeader(); } return _messageId; } } private readonly QualityOfServiceCollection _qoSLevels = new QualityOfServiceCollection(); public QualityOfServiceCollection QoSLevels { get { if (!_msg.PayloadRead) { ReadPayload(); } return _qoSLevels; } } private int ReadVariableHeader() { // Variable header could potentially be read by more than one thread but we're OK with that. // Just trying to guard against multiple threads reading in the variables at the same time. lock (_msg.SyncLock) { int pos; int length = _msg.ReadRemainingLength(out pos); _messageId = Frame.DecodeInt16(_msg.MsgBuffer, ref pos); _msg.VariableHeaderRead = true; return pos; } } private void ReadPayload() { lock (_msg.SyncLock) { if (!_msg.PayloadRead) { int pos = ReadVariableHeader(); while (pos < _msg.MsgBuffer.Length) { _qoSLevels.Add((QualityOfService)_msg.MsgBuffer[pos++]); } _msg.PayloadRead = true; } } } } }
11,497
https://github.com/marcosocon/pokemon-ui/blob/master/src/config/index.js
Github Open Source
Open Source
MIT
null
pokemon-ui
marcosocon
JavaScript
Code
10
35
const CONFIG = { API_URL: 'https://pokeapi.co/api/v2' } export default CONFIG;
25,669
https://github.com/getpro/mygenius/blob/master/Yeung/Classes/game/CCRadioMenu.h
Github Open Source
Open Source
MIT
2,012
mygenius
getpro
Objective-C
Code
38
141
// // CCRadioMenu.h // DrawSomeThing // // Created by Peteo on 12-4-3. // Copyright 2012 The9. All rights reserved. // #import "cocos2d.h" @interface CCRadioMenu : CCMenu { CCMenuItem *_curHighlighted; } -(void)setSelectedRadioItem:(CCMenuItem*)item; + (id) radioMenuWithItems:(CCMenuItem*) item, ... NS_REQUIRES_NIL_TERMINATION; @end
3,061
https://github.com/syam-s/IBAMR/blob/master/ibtk/include/ibtk/NodeSynchCopyFillPattern.h
Github Open Source
Open Source
BSD-3-Clause
2,021
IBAMR
syam-s
C
Code
544
1,247
// --------------------------------------------------------------------- // // Copyright (c) 2011 - 2019 by the IBAMR developers // All rights reserved. // // This file is part of IBAMR. // // IBAMR is free software and is distributed under the 3-clause BSD // license. The full text of the license can be found in the file // COPYRIGHT at the top level directory of IBAMR. // // --------------------------------------------------------------------- #ifndef included_IBTK_NodeSynchCopyFillPattern #define included_IBTK_NodeSynchCopyFillPattern /////////////////////////////// INCLUDES ///////////////////////////////////// #include "Box.h" #include "IntVector.h" #include "VariableFillPattern.h" #include "tbox/Pointer.h" #include <string> namespace SAMRAI { namespace hier { template <int DIM> class BoxGeometry; template <int DIM> class BoxOverlap; } // namespace hier } // namespace SAMRAI /////////////////////////////// CLASS DEFINITION ///////////////////////////// namespace IBTK { /*! * \brief Class NodeCellSynchCopyFillPattern is a concrete implementation of the * abstract base class SAMRAI::xfer::VariableFillPattern. It is used to * calculate overlaps according to a pattern which limits overlaps to the * node-centered ghost region surrounding a patch appropriate for * "synchronizing" node-centered values in an axis-by-axis manner at patch * boundaries. * * \note We synchronize data one axis at a time because node-centered values can * be shared by more than two patches. For instance, to synchronize nodal * values in three spatial dimensions, we first synchronize values in the x * direction, then in the y direction, and finally in the z direction. */ class NodeSynchCopyFillPattern : public SAMRAI::xfer::VariableFillPattern<NDIM> { public: /*! * \brief Constructor */ NodeSynchCopyFillPattern(unsigned int axis); /*! * \brief Destructor */ ~NodeSynchCopyFillPattern() = default; /*! * Calculate overlaps between the destination and source geometries according * to the desired pattern. This will return the portion of the intersection * of the geometries that lies in the ghost region of the specified width * surrounding the patch, excluding all edges and corners. The patch is * identified by the argument dst_patch_box. * * \param dst_geometry geometry object for destination box * \param src_geometry geometry object for source box * \param dst_patch_box box for the destination patch * \param src_mask the source mask, the box resulting from shifting the source *box * \param overwrite_interior controls whether or not to include the destination box *interior in *the overlap * \param src_offset the offset between source and destination index space (src + *src_offset = dst) * * \return pointer to the calculated overlap object */ SAMRAI::tbox::Pointer<SAMRAI::hier::BoxOverlap<NDIM> > calculateOverlap(const SAMRAI::hier::BoxGeometry<NDIM>& dst_geometry, const SAMRAI::hier::BoxGeometry<NDIM>& src_geometry, const SAMRAI::hier::Box<NDIM>& dst_patch_box, const SAMRAI::hier::Box<NDIM>& src_mask, bool overwrite_interior, const SAMRAI::hier::IntVector<NDIM>& src_offset) const override; /*! * Returns the stencil width. */ SAMRAI::hier::IntVector<NDIM>& getStencilWidth() override; /*! * Returns a string name identifier "NODE_SYNCH_COPY_FILL_PATTERN". */ const std::string& getPatternName() const override; private: /*! * \brief Default constructor. * * \note This constructor is not implemented and should not be used. */ NodeSynchCopyFillPattern() = delete; /*! * \brief Copy constructor. * * \note This constructor is not implemented and should not be used. * * \param from The value to copy to this object. */ NodeSynchCopyFillPattern(const NodeSynchCopyFillPattern& from) = delete; /*! * \brief Assignment operator. * * \note This operator is not implemented and should not be used. * * \param that The value to assign to this object. * * \return A reference to this object. */ NodeSynchCopyFillPattern& operator=(const NodeSynchCopyFillPattern& that) = delete; SAMRAI::hier::IntVector<NDIM> d_stencil_width = 1; const unsigned int d_axis; }; } // namespace IBTK ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef included_IBTK_NodeSynchCopyFillPattern
36,991
https://github.com/gotogame/Game2D/blob/master/Game2D/Core/GameBase_EventPartial.cs
Github Open Source
Open Source
MIT
null
Game2D
gotogame
C#
Code
348
1,932
using System; using System.Collections.Generic; using System.Text; using SDL2; namespace Game2D { //游戏基类_SDL事件部分 public partial class GameBase { #region 平台相关事件 /// <summary> /// 关闭事件,游戏窗口的关闭按钮被点击时引发一次 /// (默认未包含代码) /// (Windows平台可用) /// </summary> protected virtual void Closing() { } //---------------------------------------------------------------------------------------------------- /// <summary> /// 暂停事件,安卓活动从前台转入后台时引发一次 /// (默认未包含代码) /// (Android平台可用) /// </summary> protected virtual void Pause() { } /// <summary> /// 恢复事件,安卓活动从后台转回前台时引发一次 /// (默认未包含代码) /// (Android平台可用) /// </summary> protected virtual void Resume() { } #endregion #region 文本输入事件 /// <summary> /// 文本输入事件 /// (默认未包含代码) /// </summary> protected virtual void TextInput(string text) { } /// <summary> /// 文本编辑中事件 /// (默认未包含代码) /// </summary> protected virtual void TextEditing(string text, int start, int length) { } /// <summary> /// 设置文本输入矩形 /// </summary> /// <param name="rectangle">矩形</param> public static void SetTextInputRect(Rectangle rectangle) { SDL.SDL_Rect sdlRect = rectangle.ToSDLRectangle(); SDL.SDL_SetTextInputRect(ref sdlRect); } /// <summary> /// 是否监听文本输入事件 /// (设置为true 时开始监听文本输入事件与文本编辑中事件) /// (设置为false 时停止监听文本输入事件与文本编辑中事件) /// </summary> public static bool IsTextInputActive { get { return SDL.SDL_IsTextInputActive() == SDL.SDL_bool.SDL_TRUE; } set { if (value) SDL.SDL_StartTextInput(); else SDL.SDL_StopTextInput(); } } #endregion #region SDL事件 /// <summary> /// 更新SDL事件 /// </summary> private void UpdateSDLEvent() { //复位 InputState.KeyboardDownKeys_Source.Clear(); InputState.KeyboardUpKeys_Source.Clear(); InputState.MouseDownButtons_Source.Clear(); InputState.MouseUpButtons_Source.Clear(); InputState.PreviousMousePosition = InputState.CurrentMousePosition; InputState.MouseScrollWheel = Point.Zero; // while (SDL.SDL_PollEvent(out SDL.SDL_Event sdlEvent) == 1) { switch (sdlEvent.type) { case SDL.SDL_EventType.SDL_QUIT: { Closing(); break; } case SDL.SDL_EventType.SDL_APP_WILLENTERBACKGROUND: { Pause(); break; } case SDL.SDL_EventType.SDL_APP_DIDENTERBACKGROUND: { //Pause(); break; } case SDL.SDL_EventType.SDL_APP_WILLENTERFOREGROUND: { Resume(); break; } case SDL.SDL_EventType.SDL_APP_DIDENTERFOREGROUND: { //Resume(); break; } case SDL.SDL_EventType.SDL_KEYDOWN: { Key key = KeyConverter.SDLKeycodeToKey(sdlEvent.key.keysym.sym); if (!InputState.KeyboardPressedKeys_Source.Contains(key)) { InputState.KeyboardDownKeys_Source.Add(key); InputState.KeyboardPressedKeys_Source.Add(key); } break; } case SDL.SDL_EventType.SDL_KEYUP: { Key key = KeyConverter.SDLKeycodeToKey(sdlEvent.key.keysym.sym); if (InputState.KeyboardPressedKeys_Source.Contains(key)) { InputState.KeyboardPressedKeys_Source.Remove(key); InputState.KeyboardUpKeys_Source.Add(key); } break; } case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN: { MouseButton mouseButton = MouseButtonConverter.SDLMouseButtonToMouseButton(sdlEvent.button.button); if (!InputState.MousePressedButtons_Source.Contains(mouseButton)) { InputState.MouseDownButtons_Source.Add(mouseButton); InputState.MousePressedButtons_Source.Add(mouseButton); } break; } case SDL.SDL_EventType.SDL_MOUSEBUTTONUP: { MouseButton mouseButton = MouseButtonConverter.SDLMouseButtonToMouseButton(sdlEvent.button.button); if (InputState.MousePressedButtons_Source.Contains(mouseButton)) { InputState.MousePressedButtons_Source.Remove(mouseButton); InputState.MouseUpButtons_Source.Add(mouseButton); } break; } case SDL.SDL_EventType.SDL_MOUSEMOTION: { //SDL事件中获取的鼠标坐标为相对于游戏窗口的坐标 InputState.CurrentMousePosition = new Point(sdlEvent.motion.x, sdlEvent.motion.y); break; } case SDL.SDL_EventType.SDL_MOUSEWHEEL: { InputState.MouseScrollWheel = new Point(sdlEvent.wheel.x, sdlEvent.wheel.y); break; } case SDL.SDL_EventType.SDL_TEXTINPUT: { string text = null; unsafe { text = SDL.UTF8_ToManaged(new IntPtr(sdlEvent.text.text)); } TextInput(text); break; } case SDL.SDL_EventType.SDL_TEXTEDITING: { string text = null; unsafe { text = SDL.UTF8_ToManaged(new IntPtr(sdlEvent.edit.text)); } TextEditing(text, sdlEvent.edit.start, sdlEvent.edit.length); break; } } } } #endregion } }
22,387
https://github.com/faddiv/Misc/blob/master/SlowlyChangingDimensions/SlowlyChangingDimensions/ScdExampleTable2.cs
Github Open Source
Open Source
MIT
2,023
Misc
faddiv
C#
Code
116
289
using System.ComponentModel.DataAnnotations; namespace SlowlyChangingDimensions { public class ScdExampleTable2 { public int Id { get; set; } public int CorrelationId { get; set; } public DateTime CreatedTimestamp { get; set; } public DateTime EndTimestamp { get; set; } = DateTime.MaxValue; public bool IsCurrentVersion { get; set; } = true; [MaxLength(100)] public string Data1 { get; set; } [MaxLength(200)] public string Data2 { get; set; } [MaxLength(200)] public string Data3 { get; set; } public ScdExampleTable2 NewVersion(DateTime now) { var nextVersion = new ScdExampleTable2 { CreatedTimestamp = now, EndTimestamp = DateTime.MaxValue, Data1 = Data1, Data2 = Data2, Data3 = Data3, CorrelationId = CorrelationId, IsCurrentVersion = true }; EndTimestamp = now; IsCurrentVersion = false; return nextVersion; } } }
21,718
https://github.com/TonyReet/lottie-flutter/blob/master/lib/src/model/animatable/animatable_double_value.dart
Github Open Source
Open Source
MIT
2,022
lottie-flutter
TonyReet
Dart
Code
27
140
import '../../animation/keyframe/double_keyframe_animation.dart'; import '../../value/keyframe.dart'; import 'base_animatable_value.dart'; class AnimatableDoubleValue extends BaseAnimatableValue<double, double> { AnimatableDoubleValue() : super.fromValue(0.0); AnimatableDoubleValue.fromKeyframes(List<Keyframe<double>> keyframes) : super.fromKeyframes(keyframes); @override DoubleKeyframeAnimation createAnimation() { return DoubleKeyframeAnimation(keyframes); } }
9,374
https://github.com/ijp/GyojiBot/blob/master/game/moves/tachiai.py
Github Open Source
Open Source
MIT
2,020
GyojiBot
ijp
Python
Code
110
391
from game.transitions import Transition from game.moves.move import Move from game.stats import Stat class Tachiai(Move): allowed_transitions = [] def __init__(self, technique_name: str, primary: Stat, secondary: Stat): super(self, technique_name, primary, secondary) class Powerful(Tachiai): def __init__(self, primary: Stat, secondary: Stat): super(self, "Powerful Charge", primary, secondary) self.allowed_transitions = [Transition.POWER, Transition.WEIGHT] class Reserved(Tachiai): def __init__(self, primary: Stat, secondary: Stat): super(self, "Reserved", primary, secondary) self.allowed_transitions = [Transition.FOOTWORK, Transition.SPIRIT] class Low(Tachiai): def __init__(self, primary: Stat, secondary: Stat): super(self, "Low", primary, secondary) self.allowed_transitions = [Transition.POWER, Transition.SKILL] class Surprise(Tachiai): def __init__(self, primary: Stat, secondary: Stat): super(self, "Surprise", primary, secondary) self.allowed_transitions = [Transition.WEIGHT, Transition.SPIRIT] class Lateral(Tachiai): def __init__(self, primary: Stat, secondary: Stat): super(self, "Lateral", primary, secondary) self.allowed_transitions = [Transition.FOOTWORK, Transition.SKILL]
32,822
https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-libzip/artifacts/.gitignore
Github Open Source
Open Source
BSD-2-Clause
2,023
berry
yarnpkg
Ignore List
Code
5
28
/* !/lib/ !/exported.json !/build.sh !/.gitignore
42,002
https://github.com/doc22940/Editor/blob/master/electron/routes/photoshop.ts
Github Open Source
Open Source
Apache-2.0
null
Editor
doc22940
TypeScript
Code
246
756
import * as KoaRouter from 'koa-router'; import * as path from 'path'; import Settings from '../settings/settings'; import WebServer from '../web-server'; import * as GeneratorCore from 'generator-core/lib/generator'; import * as GeneratorLogging from 'generator-core/lib/logging'; import * as GeneratorConfig from 'generator-core/lib/config'; export default class PhotoshopRouter { // Public members public router: KoaRouter; public webServer: WebServer; private _generatorProcess: any = null; /** * Constructor * @param application: the KOA application */ constructor (webServer: WebServer) { this.webServer = webServer; this.router = new KoaRouter(); // Create routes this.hasProcess(); this.closeProcess(); this.createProcess(); webServer.localApplication.use(this.router.routes()); } /** * Returns wether or not the photoshop process is done. */ protected hasProcess (): void { this.router.get('/photoshop/hasProcess', async (ctx, next) => { ctx.body = this._generatorProcess !== null; }); } /** * Closes the photoshop process. */ protected closeProcess (): void { this.router.get('/photoshop/closeProcess', async (ctx, next) => { if (!this._generatorProcess) return (ctx.body = false); // Close plugin const plugin = this._generatorProcess.getPlugin('babylonjs-editor-photoshop-extension'); await plugin.close(); // Close process this._generatorProcess.shutdown(); this._generatorProcess = null; ctx.body = true; }); } /** * Creates the photoshop process. */ protected createProcess (): void { this.router.get('/photoshop/createProcess', async (ctx, next) => { // Logger const loggerManager = new GeneratorLogging.LoggerManager(GeneratorLogging.LOG_LEVEL_INFO); // Generator this._generatorProcess = GeneratorCore.createGenerator(loggerManager); // Start const extensionPath = path.join(Settings.ProcessDirectory, 'photoshop-extension'); try { await new Promise<void>(async (resolve, reject) => { // Reject this._generatorProcess.on("close", () => reject()); // Resolve await this._generatorProcess.start({ password: ctx.query.password, config: GeneratorConfig.getConfig() }); resolve(); }); this._generatorProcess.loadPlugin(extensionPath); ctx.body = true; } catch (e) { // Close process this._generatorProcess.shutdown(); this._generatorProcess = null; ctx.body = false; } }); } }
46,561
https://github.com/eisgroup/kraken-rules/blob/master/kraken-expression-language/src/main/java/kraken/el/ast/visitor/AstVisitor.java
Github Open Source
Open Source
Apache-2.0
2,021
kraken-rules
eisgroup
Java
Code
296
736
/* * Copyright 2019 EIS Ltd and/or one of its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kraken.el.ast.visitor; import kraken.el.ast.*; /** * Visits over Kraken Expression Language Abstract Syntax Tree nodes. * * Based on External Visitor Pattern to traverse Abstract Syntax Tree of Kraken Expression Language. * Abstract Syntax Tree implementation is based on Irregular Heterogeneous AST pattern as described by Terence Parr. * * @author mulevicius */ public interface AstVisitor<T> { T visit(Cast cast); T visit(InstanceOf instanceOf); T visit(TypeOf typeOf); T visit(BooleanLiteral booleanLiteral); T visit(StringLiteral stringLiteral); T visit(NumberLiteral numberLiteral); T visit(DateLiteral dateLiteral); T visit(DateTimeLiteral dateTimeLiteral); T visit(If anIf); T visit(ForEach forEach); T visit(ForSome forSome); T visit(ForEvery forEvery); T visit(In in); T visit(MoreThanOrEquals moreThanOrEquals); T visit(MoreThan moreThan); T visit(LessThanOrEquals lessThanOrEquals); T visit(LessThan lessThan); T visit(And and); T visit(Or or); T visit(MatchesRegExp matchesRegExp); T visit(Equals equals); T visit(NotEquals notEquals); T visit(Modulus modulus); T visit(Subtraction subtraction); T visit(Multiplication multiplication); T visit(Exponent exponent); T visit(Division division); T visit(Addition addition); T visit(Negation negation); T visit(Negative negative); T visit(Function function); T visit(InlineArray inlineArray); T visit(InlineMap inlineMap); T visit(Path path); T visit(AccessByIndex accessByIndex); T visit(CollectionFilter collectionFilter); T visit(ReferenceValue reference); T visit(Identifier identifier); T visit(Null aNull); T visit(This aThis); default T visit(Template template) { throw new IllegalStateException("Expression node is not supported: " + template.getNodeType()); }; }
32,939
https://github.com/sj26/christen/blob/master/app/assets/stylesheets/application.css.sass
Github Open Source
Open Source
MIT
2,021
christen
sj26
Sass
Code
43
154
@import bootstrap @import bootstrap-responsive body padding-top: 60px .footer padding: 20px 0 margin-top: 20px border-top: 1px solid #e5e5e5 background-color: #f5f5f5 ul margin: 10px 0 color: #777 li display: inline &:before display: inline-block content: "\B7" width: 1em text-align: center &:first-of-type:before display: none // @import **/*
46,345
https://github.com/Invectys/Sites/blob/master/YourSpaceMDB_4.2_Optimization/YourSpace/Services/ISUsers.cs
Github Open Source
Open Source
MIT
null
Sites
Invectys
C#
Code
34
118
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using YourSpace.Areas.Identity; using YourSpace.Modules.Moderation.Models; namespace YourSpace.Services { public interface ISUsers { public Task<List<MIdentityUser>> GetUsers(int page, MUserFilter filter = null); public int GetTotalPagesUsers(); } }
2,993
https://github.com/akuleshov7/diKTat/blob/master/diktat-rules/src/main/kotlin/generated/WarningNames.kt
Github Open Source
Open Source
MIT
2,021
diKTat
akuleshov7
Kotlin
Code
807
3,593
// This document was auto generated, please don't modify it. // This document contains all enum properties from Warnings.kt as Strings. package generated import kotlin.String public object WarningNames { public const val PACKAGE_NAME_MISSING: String = "PACKAGE_NAME_MISSING" public const val PACKAGE_NAME_INCORRECT_CASE: String = "PACKAGE_NAME_INCORRECT_CASE" public const val PACKAGE_NAME_INCORRECT_PREFIX: String = "PACKAGE_NAME_INCORRECT_PREFIX" public const val PACKAGE_NAME_INCORRECT_SYMBOLS: String = "PACKAGE_NAME_INCORRECT_SYMBOLS" public const val PACKAGE_NAME_INCORRECT_PATH: String = "PACKAGE_NAME_INCORRECT_PATH" public const val INCORRECT_PACKAGE_SEPARATOR: String = "INCORRECT_PACKAGE_SEPARATOR" public const val CLASS_NAME_INCORRECT: String = "CLASS_NAME_INCORRECT" public const val OBJECT_NAME_INCORRECT: String = "OBJECT_NAME_INCORRECT" public const val VARIABLE_NAME_INCORRECT_FORMAT: String = "VARIABLE_NAME_INCORRECT_FORMAT" public const val VARIABLE_NAME_INCORRECT: String = "VARIABLE_NAME_INCORRECT" public const val CONSTANT_UPPERCASE: String = "CONSTANT_UPPERCASE" public const val VARIABLE_HAS_PREFIX: String = "VARIABLE_HAS_PREFIX" public const val IDENTIFIER_LENGTH: String = "IDENTIFIER_LENGTH" public const val ENUM_VALUE: String = "ENUM_VALUE" public const val GENERIC_NAME: String = "GENERIC_NAME" public const val BACKTICKS_PROHIBITED: String = "BACKTICKS_PROHIBITED" public const val FUNCTION_NAME_INCORRECT_CASE: String = "FUNCTION_NAME_INCORRECT_CASE" public const val FUNCTION_BOOLEAN_PREFIX: String = "FUNCTION_BOOLEAN_PREFIX" public const val FILE_NAME_INCORRECT: String = "FILE_NAME_INCORRECT" public const val EXCEPTION_SUFFIX: String = "EXCEPTION_SUFFIX" public const val CONFUSING_IDENTIFIER_NAMING: String = "CONFUSING_IDENTIFIER_NAMING" public const val MISSING_KDOC_TOP_LEVEL: String = "MISSING_KDOC_TOP_LEVEL" public const val MISSING_KDOC_CLASS_ELEMENTS: String = "MISSING_KDOC_CLASS_ELEMENTS" public const val MISSING_KDOC_ON_FUNCTION: String = "MISSING_KDOC_ON_FUNCTION" public const val KDOC_TRIVIAL_KDOC_ON_FUNCTION: String = "KDOC_TRIVIAL_KDOC_ON_FUNCTION" public const val KDOC_WITHOUT_PARAM_TAG: String = "KDOC_WITHOUT_PARAM_TAG" public const val KDOC_WITHOUT_RETURN_TAG: String = "KDOC_WITHOUT_RETURN_TAG" public const val KDOC_WITHOUT_THROWS_TAG: String = "KDOC_WITHOUT_THROWS_TAG" public const val KDOC_EMPTY_KDOC: String = "KDOC_EMPTY_KDOC" public const val KDOC_WRONG_SPACES_AFTER_TAG: String = "KDOC_WRONG_SPACES_AFTER_TAG" public const val KDOC_WRONG_TAGS_ORDER: String = "KDOC_WRONG_TAGS_ORDER" public const val KDOC_NEWLINES_BEFORE_BASIC_TAGS: String = "KDOC_NEWLINES_BEFORE_BASIC_TAGS" public const val KDOC_NO_NEWLINES_BETWEEN_BASIC_TAGS: String = "KDOC_NO_NEWLINES_BETWEEN_BASIC_TAGS" public const val KDOC_NO_NEWLINE_AFTER_SPECIAL_TAGS: String = "KDOC_NO_NEWLINE_AFTER_SPECIAL_TAGS" public const val KDOC_NO_EMPTY_TAGS: String = "KDOC_NO_EMPTY_TAGS" public const val KDOC_NO_DEPRECATED_TAG: String = "KDOC_NO_DEPRECATED_TAG" public const val KDOC_NO_CONSTRUCTOR_PROPERTY: String = "KDOC_NO_CONSTRUCTOR_PROPERTY" public const val KDOC_EXTRA_PROPERTY: String = "KDOC_EXTRA_PROPERTY" public const val KDOC_NO_CONSTRUCTOR_PROPERTY_WITH_COMMENT: String = "KDOC_NO_CONSTRUCTOR_PROPERTY_WITH_COMMENT" public const val KDOC_CONTAINS_DATE_OR_AUTHOR: String = "KDOC_CONTAINS_DATE_OR_AUTHOR" public const val HEADER_WRONG_FORMAT: String = "HEADER_WRONG_FORMAT" public const val HEADER_MISSING_OR_WRONG_COPYRIGHT: String = "HEADER_MISSING_OR_WRONG_COPYRIGHT" public const val WRONG_COPYRIGHT_YEAR: String = "WRONG_COPYRIGHT_YEAR" public const val HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE: String = "HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE" public const val HEADER_NOT_BEFORE_PACKAGE: String = "HEADER_NOT_BEFORE_PACKAGE" public const val COMMENTED_OUT_CODE: String = "COMMENTED_OUT_CODE" public const val WRONG_NEWLINES_AROUND_KDOC: String = "WRONG_NEWLINES_AROUND_KDOC" public const val FIRST_COMMENT_NO_SPACES: String = "FIRST_COMMENT_NO_SPACES" public const val COMMENT_WHITE_SPACE: String = "COMMENT_WHITE_SPACE" public const val IF_ELSE_COMMENTS: String = "IF_ELSE_COMMENTS" public const val FILE_IS_TOO_LONG: String = "FILE_IS_TOO_LONG" public const val FILE_CONTAINS_ONLY_COMMENTS: String = "FILE_CONTAINS_ONLY_COMMENTS" public const val FILE_INCORRECT_BLOCKS_ORDER: String = "FILE_INCORRECT_BLOCKS_ORDER" public const val FILE_NO_BLANK_LINE_BETWEEN_BLOCKS: String = "FILE_NO_BLANK_LINE_BETWEEN_BLOCKS" public const val FILE_UNORDERED_IMPORTS: String = "FILE_UNORDERED_IMPORTS" public const val FILE_WILDCARD_IMPORTS: String = "FILE_WILDCARD_IMPORTS" public const val NO_BRACES_IN_CONDITIONALS_AND_LOOPS: String = "NO_BRACES_IN_CONDITIONALS_AND_LOOPS" public const val WRONG_ORDER_IN_CLASS_LIKE_STRUCTURES: String = "WRONG_ORDER_IN_CLASS_LIKE_STRUCTURES" public const val BLANK_LINE_BETWEEN_PROPERTIES: String = "BLANK_LINE_BETWEEN_PROPERTIES" public const val BRACES_BLOCK_STRUCTURE_ERROR: String = "BRACES_BLOCK_STRUCTURE_ERROR" public const val WRONG_INDENTATION: String = "WRONG_INDENTATION" public const val EMPTY_BLOCK_STRUCTURE_ERROR: String = "EMPTY_BLOCK_STRUCTURE_ERROR" public const val MORE_THAN_ONE_STATEMENT_PER_LINE: String = "MORE_THAN_ONE_STATEMENT_PER_LINE" public const val LONG_LINE: String = "LONG_LINE" public const val REDUNDANT_SEMICOLON: String = "REDUNDANT_SEMICOLON" public const val WRONG_NEWLINES: String = "WRONG_NEWLINES" public const val COMPLEX_EXPRESSION: String = "COMPLEX_EXPRESSION" public const val STRING_CONCATENATION: String = "STRING_CONCATENATION" public const val TOO_MANY_BLANK_LINES: String = "TOO_MANY_BLANK_LINES" public const val WRONG_WHITESPACE: String = "WRONG_WHITESPACE" public const val TOO_MANY_CONSECUTIVE_SPACES: String = "TOO_MANY_CONSECUTIVE_SPACES" public const val ANNOTATION_NEW_LINE: String = "ANNOTATION_NEW_LINE" public const val ENUMS_SEPARATED: String = "ENUMS_SEPARATED" public const val WHEN_WITHOUT_ELSE: String = "WHEN_WITHOUT_ELSE" public const val LONG_NUMERICAL_VALUES_SEPARATED: String = "LONG_NUMERICAL_VALUES_SEPARATED" public const val WRONG_DECLARATIONS_ORDER: String = "WRONG_DECLARATIONS_ORDER" public const val WRONG_MULTIPLE_MODIFIERS_ORDER: String = "WRONG_MULTIPLE_MODIFIERS_ORDER" public const val LOCAL_VARIABLE_EARLY_DECLARATION: String = "LOCAL_VARIABLE_EARLY_DECLARATION" public const val STRING_TEMPLATE_CURLY_BRACES: String = "STRING_TEMPLATE_CURLY_BRACES" public const val STRING_TEMPLATE_QUOTES: String = "STRING_TEMPLATE_QUOTES" public const val FILE_NAME_MATCH_CLASS: String = "FILE_NAME_MATCH_CLASS" public const val NULLABLE_PROPERTY_TYPE: String = "NULLABLE_PROPERTY_TYPE" public const val TYPE_ALIAS: String = "TYPE_ALIAS" public const val SMART_CAST_NEEDED: String = "SMART_CAST_NEEDED" public const val SAY_NO_TO_VAR: String = "SAY_NO_TO_VAR" public const val GENERIC_VARIABLE_WRONG_DECLARATION: String = "GENERIC_VARIABLE_WRONG_DECLARATION" public const val FLOAT_IN_ACCURATE_CALCULATIONS: String = "FLOAT_IN_ACCURATE_CALCULATIONS" public const val AVOID_NULL_CHECKS: String = "AVOID_NULL_CHECKS" public const val TOO_LONG_FUNCTION: String = "TOO_LONG_FUNCTION" public const val AVOID_NESTED_FUNCTIONS: String = "AVOID_NESTED_FUNCTIONS" public const val LAMBDA_IS_NOT_LAST_PARAMETER: String = "LAMBDA_IS_NOT_LAST_PARAMETER" public const val TOO_MANY_PARAMETERS: String = "TOO_MANY_PARAMETERS" public const val NESTED_BLOCK: String = "NESTED_BLOCK" public const val WRONG_OVERLOADING_FUNCTION_ARGUMENTS: String = "WRONG_OVERLOADING_FUNCTION_ARGUMENTS" public const val RUN_BLOCKING_INSIDE_ASYNC: String = "RUN_BLOCKING_INSIDE_ASYNC" public const val SINGLE_CONSTRUCTOR_SHOULD_BE_PRIMARY: String = "SINGLE_CONSTRUCTOR_SHOULD_BE_PRIMARY" public const val USE_DATA_CLASS: String = "USE_DATA_CLASS" public const val WRONG_NAME_OF_VARIABLE_INSIDE_ACCESSOR: String = "WRONG_NAME_OF_VARIABLE_INSIDE_ACCESSOR" public const val MULTIPLE_INIT_BLOCKS: String = "MULTIPLE_INIT_BLOCKS" public const val CLASS_SHOULD_NOT_BE_ABSTRACT: String = "CLASS_SHOULD_NOT_BE_ABSTRACT" public const val CUSTOM_GETTERS_SETTERS: String = "CUSTOM_GETTERS_SETTERS" public const val COMPACT_OBJECT_INITIALIZATION: String = "COMPACT_OBJECT_INITIALIZATION" public const val USELESS_SUPERTYPE: String = "USELESS_SUPERTYPE" public const val TRIVIAL_ACCESSORS_ARE_NOT_RECOMMENDED: String = "TRIVIAL_ACCESSORS_ARE_NOT_RECOMMENDED" public const val EXTENSION_FUNCTION_SAME_SIGNATURE: String = "EXTENSION_FUNCTION_SAME_SIGNATURE" public const val EMPTY_PRIMARY_CONSTRUCTOR: String = "EMPTY_PRIMARY_CONSTRUCTOR" public const val NO_CORRESPONDING_PROPERTY: String = "NO_CORRESPONDING_PROPERTY" public const val AVOID_USING_UTILITY_CLASS: String = "AVOID_USING_UTILITY_CLASS" public const val OBJECT_IS_PREFERRED: String = "OBJECT_IS_PREFERRED" public const val INVERSE_FUNCTION_PREFERRED: String = "INVERSE_FUNCTION_PREFERRED" public const val TOO_MANY_LINES_IN_LAMBDA: String = "TOO_MANY_LINES_IN_LAMBDA" }
50,820
https://github.com/Scenx/scen-springcloud-store/blob/master/scen-web-parent/scen-admin-web/src/main/java/com/scen/admin/controller/ContentController.java
Github Open Source
Open Source
Apache-2.0
2,019
scen-springcloud-store
Scenx
Java
Code
163
613
package com.scen.admin.controller; import com.scen.content.service.ContentService; import com.scen.pojo.Content; import com.scen.vo.EUDdataGridResult; import com.scen.vo.ScenResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 内容管理表现层 * * @author Scen * @date 2018/4/3 9:04 */ @RestController @RequestMapping("/content") public class ContentController { @Autowired private ContentService contentService; /** * 查询指定分类的所有内容 * * @param page * @param rows * @param categoryId * @return */ @RequestMapping("/query/list") public EUDdataGridResult getContentList(Integer page, Integer rows, Long categoryId) { return contentService.getContentList(page, rows, categoryId); } /** * 保存内容 * * @param content * @return */ @RequestMapping("/save") public ScenResult saveContent(Content content) { try { return contentService.saveContent(content); } catch (Exception e) { e.printStackTrace(); return ScenResult.build(500, "保存失败"); } } /** * 根据id批量删除内容 * * @param ids * @return */ @RequestMapping("/delete") public ScenResult deleteContent(Long[] ids) { try { return contentService.deleteContent(ids); } catch (Exception e) { e.printStackTrace(); return ScenResult.build(500, "删除失败"); } } /** * 更新内容 * * @param content * @return */ @RequestMapping("/edit") public ScenResult editContent(Content content) { try { return contentService.editContent(content); } catch (Exception e) { e.printStackTrace(); return ScenResult.build(500, "编辑失败"); } } }
43,748
https://github.com/aillieo/lua-structs/blob/master/lua-structs/LuaHeap.lua
Github Open Source
Open Source
MIT
2,022
lua-structs
aillieo
Lua
Code
211
714
local LuaHeap = {} LuaHeap.__index = LuaHeap local defaultComparer = function(x,y) return x < y end function LuaHeap:Clear() self._data = {} end function LuaHeap:Pop() local node = self._data[1] if node then local count = #self._data self._data[1] = self._data[count] self._data[count] = nil if self:Count() > 0 then self:_siftDown(1) end return node end return nil end function LuaHeap:Top() return self._data[1] end function LuaHeap:Push(value) local count = #self._data self._data[count + 1] = value self:_siftUp(count + 1) end function LuaHeap:Count() return #self._data end function LuaHeap:_siftUp(index) local parent = math.floor(index / 2) if self._data[parent] and self._comparer(self._data[index], self._data[parent]) then self._data[parent], self._data[index] = self._data[index], self._data[parent] return self:_siftUp(parent) end end function LuaHeap:_siftDown(index) local current = index local left = 2 * index local right = 2 * index + 1 if self._data[left] and self._comparer(self._data[left], self._data[current]) then current = left end if self._data[right] and self._comparer(self._data[right], self._data[current]) then current = right end if current ~= index then self._data[index], self._data[current] = self._data[current], self._data[index] return self:_siftDown(current) end end -- 找到第一个匹配的值 并删除 然后保持heap function LuaHeap:FindAndRemove(value) for i,v in ipairs(self._data) do if v == value then table.remove(self._data,i) if self:Count() > 0 then self:_siftDown(i) end return true end end return false end function LuaHeap.New(comparer) comparer = comparer or defaultComparer return setmetatable({ _data = {}, _comparer = comparer },LuaHeap) end function LuaHeap.__call(comparer) return LuaHeap.New(comparer) end return LuaHeap
37,398
https://github.com/senagbe/stroke/blob/master/src/com/isode/stroke/base/SafeString.java
Github Open Source
Open Source
BSD-3-Clause
2,021
stroke
senagbe
Java
Code
77
199
/* * Copyright (c) 2011-2015 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* * Copyright (c) 2015 Tarun Gupta. * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ package com.isode.stroke.base; import com.isode.stroke.base.SafeByteArray; public class SafeString { private SafeByteArray data; public SafeString(SafeByteArray data) { this.data = data; } public SafeString(String s) { this.data = new SafeByteArray(s); } public SafeByteArray getData() { return data; } }
41,205
https://github.com/adellape/openshift-docs/blob/master/modules/templates-create-from-existing-object.adoc
Github Open Source
Open Source
Apache-2.0
2,020
openshift-docs
adellape
AsciiDoc
Code
127
232
// Module included in the following assemblies: // // * openshift_images/using-templates.adoc [id="templates-create-from-existing-object_{context}"] = Creating a template from existing objects Rather than writing an entire template from scratch, you can export existing objects from your project in YAML form, and then modify the YAML from there by adding parameters and other customizations as template form. .Procedure . Export objects in a project in YAML form: + [source,terminal] ---- $ oc get -o yaml --export all > <yaml_filename> ---- + You can also substitute a particular resource type or multiple resources instead of `all`. Run `oc get -h` for more examples. + The object types included in `oc get --export all` are: + * BuildConfig * Build * DeploymentConfig * ImageStream * Pod * ReplicationController * Route * Service
22,229
https://github.com/jorgenunezsiri/accusyn/blob/master/src/variables/blockViewStateDictionary.js
Github Open Source
Open Source
MIT
2,021
accusyn
jorgenunezsiri
JavaScript
Code
74
145
import merge from 'lodash/merge'; let _blockViewStateDictionary = {}; // To save the current state for each block /** * Getter function for block view state dictionary * * @return {Object} Block view state dictionary */ export function getBlockViewStateDictionary() { return _blockViewStateDictionary; }; /** * Setter function for block view state dictionary * * @param {Object} dictionary Block view state dictionary * @return {undefined} undefined */ export function setBlockViewStateDictionary(dictionary) { _blockViewStateDictionary = merge({}, dictionary); };
28,256
https://github.com/gestaltjs/ruby/blob/master/src/bin/daily.ts
Github Open Source
Open Source
MIT
null
ruby
gestaltjs
TypeScript
Code
176
560
import { message } from "../lib/slack"; import { Message, Blocks, Md } from "slack-block-builder"; import npm from "npm-stat-api"; const multilingualGoodMorning = [ "Bon matin", "Buenos días", "Bon dia", "Egun on", "Bos días", "Buongiorno", "Suprabhat", "Sabah al-khair", "Ohayō", "Sawubona", "Bonan matenon", ]; const goodMorning = multilingualGoodMorning[ Math.floor(Math.random() * multilingualGoodMorning.length) ]; const result = await new Promise((resolve, reject) => { npm.stat("@gestaltjs/core", "2022-01-01", "2022-03-07", (error, value) => { if (error) { reject(error); } else if (value) { resolve(value); } }); }); console.log(result); // https://www.edoardoscibona.com/exploring-the-npm-registry-api await message( Message() .channel("#test") .blocks( Blocks.Header({ text: "Daily digest" }), Blocks.Section().text( `${goodMorning} ☀️👋. I'm here once again to share with you how the project and the community is evolving. Remember that I'm not AI-powered so resist asking me questions that you'd ask to Siri 😬.` ), Blocks.Divider() ) // .blocks( // Blocks.Section().text( // "One does not simply walk into Slack and click a button." // ), // Blocks.Section().text( // "At least that's what my friend Slackomir said :crossed_swords:" // ), // Blocks.Divider(), // Blocks.Actions().elements( // Elements.Button().text("Sure One Does").actionId("gotClicked") // ) // ) .asUser() .buildToObject() );
28,624
https://github.com/dedihartono/projek1/blob/master/application/views/lokasi_unit/v_test.php
Github Open Source
Open Source
MIT
null
projek1
dedihartono
PHP
Code
168
855
<a class="btn btn-primary" href="<?php echo base_url();?>index.php/kelola_unit/tambah_lokasi_unit">Tambah</a> <table class="table datatable"> <tr> <th>No</th> <th>Kode Lokasi</th> <th>Lokasi</th> <th>Aksi</th> </tr> <?php $n = 1; foreach ($lokasi_unit as $row) { ?> <tr> <td><?php echo $n++;?></td> <td><?php echo $row->kode_lokasi;?></td> <td><?php echo $row->lokasi_unit;?></td> <td> <a href="<?php echo $row->kode_lokasi;?>">Edit</a> <a href="<?php echo base_url();?>index.php/kelola_unit/hapus/<?php echo $row->kode_lokasi;?>">Hapus</a> </td> </tr> <?php } ;?> </table> <form action="<?php echo base_url();?>index.php/kelola_unit/proses_tambah" method="post"> <div class="form-group"> <label>Kode Lokasi</label> <input class="form-control" type="text" name="kode_lokasi"> </div> <div class="form-group"> <label>Nama Lokasi</label> <input class="form-control" type="text" name="nama_lokasi"> </div> <div class="form-group"> <button type="submit">Simpan</button> </div> </form> <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Classname extends CI_Controller{ public function __construct() { parent::__construct(); //Codeigniter : Write Less Do More } function index() { } public function tambah_lokasi_unit() { $data['konten'] = 'kelola_unit/v_tambah'; $this->load->view('template_admin', $data); } public function proses_tambah() { $data = array( 'kode_lokasi' => $this->input->post('kode_lokasi'), 'lokasi_unit' => $this->input->post('nama_lokasi'), ); $this->m_kelola_unit->tambah_data($data); redirect('kelola_unit'); } //di buat di m_kelola_unit public function tambah_data($data) { $this->db->insert('tb_lokasi_unit', $data); } public function hapus($id) { $id = $this->uri->segment('3'); $this->m_kelola_unit->hapus_data($id); redirect('kelola_unit'); } //model public function hapus_data($id) { $this->db->where('kode_lokasi', $id); $this->db->delete('tb_lokasi_unit'); } }
27,168
https://github.com/rosenfeld/rails-web-console/blob/master/lib/rails_web_console/engine.rb
Github Open Source
Open Source
MIT
2,022
rails-web-console
rosenfeld
Ruby
Code
10
31
module RailsWebConsole class Engine < ::Rails::Engine isolate_namespace RailsWebConsole end end
15,582
https://github.com/La0917-team/nucbaComercio/blob/master/frontend/src/Components/FormLogin/FormLogin.js
Github Open Source
Open Source
MIT
null
nucbaComercio
La0917-team
JavaScript
Code
55
208
import React from 'react' import {ButtonLogIn, ContainerForm, FormSignIn, H1Form, InputLogin, LabelLogIn, Structure} from './FormLoginStyles' function FormLogin() { return ( <ContainerForm> <Structure> <H1Form> Sign In </H1Form> <br/> <FormSignIn action='submit'> <LabelLogIn> Email address </LabelLogIn> <InputLogin placeholder='Enter email' type='email' required/> <LabelLogIn> Password </LabelLogIn> <InputLogin placeholder='Enter password' type='password' required/> <ButtonLogIn>Sign In</ButtonLogIn> </FormSignIn> </Structure> </ContainerForm> ) } export default FormLogin
19,540
https://github.com/DataCanvasIO/HyperNLP/blob/master/hypernlp/optimize/trainer.py
Github Open Source
Open Source
Apache-2.0
2,022
HyperNLP
DataCanvasIO
Python
Code
444
1,842
import abc from hypernlp.framework_config import Config if Config.framework == 'tensorflow': import tensorflow as tf from utils.logger import logger from utils.string_utils import home_path class Trainer(object): def __init__(self, model, optimzier, train_processers, epochs, epoch_length, evaluator, save_model_path): self.model = model self.__optimizer = optimzier self.optimizer = self.__optimizer() self.epochs = epochs self.epoch_length = epoch_length self.evaluator = evaluator self.save_path = save_model_path self.train_processers = train_processers assert isinstance(self.train_processers, list) or isinstance(self.train_processers, tuple) @abc.abstractmethod def run_optimization(self): pass def model_save_epoch(self, epoch): if not self.save_path[-1] == '/': raise SystemError("Checkpoints saving path should be end with '/'!") if Config.framework == "tensorflow": return self.save_path + "{}".format(epoch) + '.h5' elif Config.framework == "pytorch": return self.save_path + "{}".format(epoch) + '.pth' else: raise TypeError("Unsupported framework: '{}'".format(Config.framework)) def checkpoint_save_epoch(self): if self.save_path is None: self.save_path = home_path() + 'hypernlp/optimize/checkpoints/' if not self.save_path[-1] == '/': raise SystemError("Checkpoints saving path should be end with '/'!") if Config.framework == "tensorflow": return self.save_path + 'checkpoint.h5', self.save_path + 'optimizer_cpt.h5' elif Config.framework == "pytorch": return self.save_path + 'checkpoint.pth', self.save_path + 'optimizer_cpt.pth' else: raise TypeError("Unsupported framework: '{}'".format(Config.framework)) ''' Custom definition? User data input setting! ''' def train(self): try: if Config.framework == "tensorflow": if Config.USE_XLA is True: tf.config.optimizer.set_jit(True) tf.config.optimizer.set_experimental_options({"auto_mixed_precision": True}) for epoch in range(self.epochs): for it in range(self.epoch_length): loss = self.run_optimization() logger.info("epoch[{}:{}/{}] loss: {}".format(epoch, it, self.epoch_length, loss)) if self.save_path is not None: self.model.model_save(self.model_save_epoch(epoch)) if self.evaluator is not None: logger.info("epoch[{}] evaluation: {}".format(epoch, self.evaluator.eval(self.model))) except KeyboardInterrupt: logger.info('manually interrupt, try saving model for now...') model_cpt, optim_cpt = self.checkpoint_save_epoch() self.model.model_save(model_cpt) self.__optimizer.save(optim_cpt) logger.info('model saved.') class TFTrainer(Trainer): def __init__(self, model, losses, optimzier, epochs, epoch_length, evaluator, save_model_path): super(TFTrainer, self).__init__(model, losses, optimzier, epochs, epoch_length, evaluator, save_model_path) # register distribute_functions self.distibute_functions = [] for i in range(len(self.train_processers)): @tf.function def distributed_train_step(tp_index, batch_data): per_replica_losses = Config.strategy.run(self.run_processer, args=(self.train_processers[tp_index], batch_data, tp_index,)) return Config.strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None) self.distibute_functions.append(distributed_train_step) def run_processer(self, tp, batch_data, index): # Wrap computation inside a GradientTape for automatic differentiation. with tf.GradientTape() as g: loss = tp.step(self.model, batch_data, index) # Variables to update, i.e. trainable variables. trainable_variables = self.model.trainable_variables # Compute gradients. gradients = g.gradient(loss, trainable_variables) # Update W and b following gradients. self.optimizer.apply_gradients(zip(gradients, trainable_variables)) return loss def run_optimization(self): total_loss = 0 for index in range(0, len(self.train_processers)): batch_data = next(iter(self.train_processers[index].dataset.get_batch_data())) total_loss += self.distibute_functions[index](index, batch_data) return total_loss class PTTrainer(Trainer): def __init__(self, model, optimzier, train_processers, epochs, epoch_length, evaluator, save_model_path): super(PTTrainer, self).__init__(model, optimzier, train_processers, epochs, epoch_length, evaluator, save_model_path) def run_optimization(self): self.model.train() self.optimizer.zero_grad() loss = self.train_processers[0].step( self.model, self.train_processers[0].dataset.get_batch_data(), 0) for index in range(1, len(self.train_processers)): loss += self.train_processers[index].step( self.model, self.train_processers[index].dataset.get_batch_data(), index) # Compute gradients. loss.backward() # Update W and b following gradients. self.optimizer.step() return loss.data.cpu().numpy() def trainer(model, optimzier, train_processers, epochs, epoch_length, evaluator=None, save_model_path=None): if Config.framework == "tensorflow": return TFTrainer(model, optimzier, train_processers, epochs, epoch_length, evaluator, save_model_path) elif Config.framework == "pytorch": return PTTrainer(model, optimzier, train_processers, epochs, epoch_length, evaluator, save_model_path) else: raise ValueError("Unsupported framework: {}".format(Config.framework)) if __name__ == '__main__': tf.config.optimizer.set_jit(True) tf.config.optimizer.set_experimental_options({"auto_mixed_precision": True})
12,859
https://github.com/RoperoIvan/NarrativaEnTempsReal/blob/master/RoperoIvan/Introduction to Scripting Part 2 Starter/Assets/RW/Scripts/SheepSpawner.cs
Github Open Source
Open Source
MIT
null
NarrativaEnTempsReal
RoperoIvan
C#
Code
144
440
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SheepSpawner : MonoBehaviour { public bool canSpawn = true; // 1 public GameObject sheepPrefab; // 2 public List<Transform> sheepSpawnPositions = new List<Transform>(); // 3 public float timeBetweenSpawns; // 4 private List<GameObject> sheepList = new List<GameObject>(); // 5 // Start is called before the first frame update void Start() { StartCoroutine(SpawnRoutine()); } // Update is called once per frame void Update() { } private void SpawnSheep() { Vector3 randomPosition = sheepSpawnPositions[Random.Range(0, sheepSpawnPositions.Count)].position; // 1 GameObject sheep = Instantiate(sheepPrefab, randomPosition, sheepPrefab.transform.rotation); // 2 sheepList.Add(sheep); // 3 sheep.GetComponent<Sheep>().SetSpawner(this); // 4 } private IEnumerator SpawnRoutine() // 1 { while (canSpawn) // 2 { SpawnSheep(); // 3 yield return new WaitForSeconds(timeBetweenSpawns); // 4 } } public void RemoveSheepFromList(GameObject sheep) { sheepList.Remove(sheep); } public void DestroyAllSheep() { foreach (GameObject sheep in sheepList) // 1 { Destroy(sheep); // 2 } sheepList.Clear(); } }
38,347
https://github.com/epapasidero/horizontal-resequencing-fmod/blob/master/Assets/Scenes/SampleScene.unity
Github Open Source
Open Source
Apache-2.0
2,020
horizontal-resequencing-fmod
epapasidero
Unity3D Asset
Code
4,090
17,116
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!29 &1 OcclusionCullingSettings: m_ObjectHideFlags: 0 serializedVersion: 2 m_OcclusionBakeSettings: smallestOccluder: 5 smallestHole: 0.25 backfaceThreshold: 100 m_SceneGUID: 00000000000000000000000000000000 m_OcclusionCullingData: {fileID: 0} --- !u!104 &2 RenderSettings: m_ObjectHideFlags: 0 serializedVersion: 9 m_Fog: 0 m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} m_FogMode: 3 m_FogDensity: 0.01 m_LinearFogStart: 0 m_LinearFogEnd: 300 m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} m_AmbientIntensity: 1 m_AmbientMode: 0 m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} m_HaloStrength: 0.5 m_FlareStrength: 1 m_FlareFadeSpeed: 3 m_HaloTexture: {fileID: 0} m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} m_DefaultReflectionMode: 0 m_DefaultReflectionResolution: 128 m_ReflectionBounces: 1 m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 170076734} m_IndirectSpecularColor: {r: 0.44657898, g: 0.4964133, b: 0.5748178, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: m_ObjectHideFlags: 0 serializedVersion: 11 m_GIWorkflowMode: 0 m_GISettings: serializedVersion: 2 m_BounceScale: 1 m_IndirectOutputScale: 1 m_AlbedoBoost: 1 m_EnvironmentLightingMode: 0 m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 0 m_LightmapEditorSettings: serializedVersion: 12 m_Resolution: 2 m_BakeResolution: 10 m_AtlasSize: 512 m_AO: 0 m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 m_ExtractAmbientOcclusion: 0 m_Padding: 2 m_LightmapParameters: {fileID: 0} m_LightmapsBakeMode: 1 m_TextureCompression: 1 m_FinalGather: 0 m_FinalGatherFiltering: 1 m_FinalGatherRayCount: 256 m_ReflectionCompression: 2 m_MixedBakeMode: 2 m_BakeBackend: 1 m_PVRSampling: 1 m_PVRDirectSampleCount: 32 m_PVRSampleCount: 256 m_PVRBounces: 2 m_PVREnvironmentSampleCount: 256 m_PVREnvironmentReferencePointCount: 2048 m_PVRFilteringMode: 2 m_PVRDenoiserTypeDirect: 0 m_PVRDenoiserTypeIndirect: 0 m_PVRDenoiserTypeAO: 0 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 m_PVREnvironmentMIS: 0 m_PVRCulling: 1 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 m_PVRFilteringGaussRadiusAO: 2 m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 m_ExportTrainingData: 0 m_TrainingDataDestination: TrainingData m_LightProbeSampleCountMultiplier: 4 m_LightingDataAsset: {fileID: 0} m_UseShadowmask: 1 --- !u!196 &4 NavMeshSettings: serializedVersion: 2 m_ObjectHideFlags: 0 m_BuildSettings: serializedVersion: 2 agentTypeID: 0 agentRadius: 0.5 agentHeight: 2 agentSlope: 45 agentClimb: 0.4 ledgeDropHeight: 0 maxJumpAcrossDistance: 0 minRegionArea: 2 manualCellSize: 0 cellSize: 0.16666667 manualTileSize: 0 tileSize: 256 accuratePlacement: 0 debug: m_Flags: 0 m_NavMeshData: {fileID: 0} --- !u!1 &63887631 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 63887635} - component: {fileID: 63887634} - component: {fileID: 63887633} - component: {fileID: 63887632} m_Layer: 0 m_Name: Plane (1) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!64 &63887632 MeshCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 63887631} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 3 m_Convex: 0 m_CookingOptions: 14 m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &63887633 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 63887631} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 2b83fd3d4a804da45b975b3d240d5dfd, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &63887634 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 63887631} m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!4 &63887635 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 63887631} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.23389006, y: 0.21379566, z: -0.4043665} m_LocalScale: {x: 2, y: 1, z: 2} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &82953784 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 82953786} - component: {fileID: 82953785} - component: {fileID: 82953787} m_Layer: 0 m_Name: Cube (2) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!65 &82953785 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 82953784} m_Material: {fileID: 0} m_IsTrigger: 1 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!4 &82953786 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 82953784} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 20.23389, y: 0.21379566, z: 19.595634} m_LocalScale: {x: 20, y: 10, z: 20} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 8 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &82953787 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 82953784} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 744a208c85da6d04c861d81b992e4ead, type: 3} m_Name: m_EditorClassIdentifier: Emitters: - Target: {fileID: 538517056} Params: - Name: To Detected Value: 1 - Name: Invincible State Value: 0 - Name: To Conflict Value: 0 - Name: To Restricted Value: 0 - Name: To Peace Value: 0 TriggerEvent: 3 CollisionTag: Player --- !u!1 &170076733 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 170076735} - component: {fileID: 170076734} m_Layer: 0 m_Name: Directional Light m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!108 &170076734 Light: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 170076733} m_Enabled: 1 serializedVersion: 10 m_Type: 1 m_Shape: 0 m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} m_Intensity: 1 m_Range: 10 m_SpotAngle: 30 m_InnerSpotAngle: 21.80208 m_CookieSize: 10 m_Shadows: m_Type: 2 m_Resolution: -1 m_CustomResolution: -1 m_Strength: 1 m_Bias: 0.05 m_NormalBias: 0.4 m_NearPlane: 0.2 m_CullingMatrixOverride: e00: 1 e01: 0 e02: 0 e03: 0 e10: 0 e11: 1 e12: 0 e13: 0 e20: 0 e21: 0 e22: 1 e23: 0 e30: 0 e31: 0 e32: 0 e33: 1 m_UseCullingMatrixOverride: 0 m_Cookie: {fileID: 0} m_DrawHalo: 0 m_Flare: {fileID: 0} m_RenderMode: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294967295 m_RenderingLayerMask: 1 m_Lightmapping: 1 m_LightShadowCasterMode: 0 m_AreaSize: {x: 1, y: 1} m_BounceIntensity: 1 m_ColorTemperature: 6570 m_UseColorTemperature: 0 m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0} m_UseBoundingSphereOverride: 0 m_ShadowRadius: 0 m_ShadowAngle: 0 --- !u!4 &170076735 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 170076733} m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261} m_LocalPosition: {x: 0, y: 3, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0} --- !u!1 &237597122 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 237597124} - component: {fileID: 237597123} - component: {fileID: 237597125} m_Layer: 0 m_Name: Cube (3) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!65 &237597123 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 237597122} m_Material: {fileID: 0} m_IsTrigger: 1 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!4 &237597124 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 237597122} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.23389006, y: 0.21379566, z: 19.595634} m_LocalScale: {x: 20, y: 10, z: 20} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 9 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &237597125 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 237597122} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 744a208c85da6d04c861d81b992e4ead, type: 3} m_Name: m_EditorClassIdentifier: Emitters: - Target: {fileID: 538517056} Params: - Name: To Detected Value: 0 - Name: Invincible State Value: 0 - Name: To Conflict Value: 0 - Name: To Peace Value: 0 - Name: To Restricted Value: 1 TriggerEvent: 3 CollisionTag: Player --- !u!1 &303654689 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 303654691} - component: {fileID: 303654690} - component: {fileID: 303654692} m_Layer: 0 m_Name: Cube m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!65 &303654690 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 303654689} m_Material: {fileID: 0} m_IsTrigger: 1 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!4 &303654691 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 303654689} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.23389006, y: 0.21379566, z: -0.4043665} m_LocalScale: {x: 20, y: 10, z: 20} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 6 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &303654692 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 303654689} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 744a208c85da6d04c861d81b992e4ead, type: 3} m_Name: m_EditorClassIdentifier: Emitters: - Target: {fileID: 538517056} Params: - Name: To Detected Value: 0 - Name: Invincible State Value: 0 - Name: To Conflict Value: 0 - Name: To Restricted Value: 0 - Name: To Peace Value: 1 TriggerEvent: 3 CollisionTag: Player --- !u!1 &388582344 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 388582348} - component: {fileID: 388582347} - component: {fileID: 388582346} - component: {fileID: 388582345} m_Layer: 0 m_Name: Plane (7) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!64 &388582345 MeshCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 388582344} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 3 m_Convex: 0 m_CookingOptions: 14 m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &388582346 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 388582344} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 5251f1efb71adef4f9bcae10b5afaf0d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &388582347 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 388582344} m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!4 &388582348 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 388582344} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 10.233891, y: 0.21379566, z: -20.404366} m_LocalScale: {x: 4, y: 1, z: 2} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 5 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &472133476 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 472133478} - component: {fileID: 472133477} - component: {fileID: 472133479} m_Layer: 0 m_Name: Cube (1) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!65 &472133477 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 472133476} m_Material: {fileID: 0} m_IsTrigger: 1 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!4 &472133478 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 472133476} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 20.23389, y: 0.21379566, z: -0.4043665} m_LocalScale: {x: 20, y: 10, z: 20} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 7 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &472133479 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 472133476} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 744a208c85da6d04c861d81b992e4ead, type: 3} m_Name: m_EditorClassIdentifier: Emitters: - Target: {fileID: 538517056} Params: - Name: To Peace Value: 0 - Name: To Restricted Value: 0 - Name: To Detected Value: 0 - Name: Invincible State Value: 0 - Name: To Conflict Value: 1 TriggerEvent: 3 CollisionTag: Player --- !u!1 &534669902 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 534669905} - component: {fileID: 534669904} - component: {fileID: 534669903} - component: {fileID: 534669906} m_Layer: 0 m_Name: Main Camera m_TagString: MainCamera m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!81 &534669903 AudioListener: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_Enabled: 1 --- !u!20 &534669904 Camera: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_projectionMatrixMode: 1 m_GateFitMode: 2 m_FOVAxisMode: 0 m_SensorSize: {x: 36, y: 24} m_LensShift: {x: 0, y: 0} m_FocalLength: 50 m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: -1 m_CullingMask: serializedVersion: 2 m_Bits: 4294967295 m_RenderingPath: -1 m_TargetTexture: {fileID: 0} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 1 m_AllowMSAA: 1 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 1 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!4 &534669905 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_LocalRotation: {x: 0.42261827, y: 0, z: 0, w: 0.9063079} m_LocalPosition: {x: 8.9, y: 19.8, z: 35.6} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 50, y: 0, z: 0} --- !u!114 &534669906 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 534669902} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c2e85332738ad7f4a9fe610daef86b79, type: 3} m_Name: m_EditorClassIdentifier: playerObject: {fileID: 538517062} distanceFromObject: 6 --- !u!1001 &538517054 PrefabInstance: m_ObjectHideFlags: 0 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 0} m_Modifications: - target: {fileID: 149790, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_Name value: ThirdPersonController objectReference: {fileID: 0} - target: {fileID: 149790, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_TagString value: Player objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalPosition.x value: 0 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalPosition.y value: 0 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalPosition.z value: 0 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalRotation.x value: 0 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalRotation.y value: 0 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalRotation.z value: 0 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalRotation.w value: 1 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_RootOrder value: 1 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - target: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} m_RemovedComponents: [] m_SourcePrefab: {fileID: 100100000, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} --- !u!1 &538517055 stripped GameObject: m_CorrespondingSourceObject: {fileID: 149790, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} m_PrefabInstance: {fileID: 538517054} m_PrefabAsset: {fileID: 0} --- !u!114 &538517056 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 538517055} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 9a6610d2e704f1648819acc8d7460285, type: 3} m_Name: m_EditorClassIdentifier: Event: event:/HRS PlayEvent: 1 StopEvent: 0 CollisionTag: AllowFadeout: 1 TriggerOnce: 0 Preload: 0 Params: - Name: To Peace Value: 1 - Name: To Restricted Value: 0 - Name: To Conflict Value: 0 - Name: Invincible State Value: 0 - Name: To Detected Value: 0 OverrideAttenuation: 0 OverrideMinDistance: 0 OverrideMaxDistance: 0 --- !u!4 &538517062 stripped Transform: m_CorrespondingSourceObject: {fileID: 408730, guid: 7737647c22c1fc64a88d5cd030c352ce, type: 3} m_PrefabInstance: {fileID: 538517054} m_PrefabAsset: {fileID: 0} --- !u!1 &647491568 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 647491572} - component: {fileID: 647491571} - component: {fileID: 647491570} - component: {fileID: 647491569} m_Layer: 0 m_Name: Plane (2) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!64 &647491569 MeshCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 647491568} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 3 m_Convex: 0 m_CookingOptions: 14 m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &647491570 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 647491568} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: a24037aa2dae5b145b048dcaf948032a, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &647491571 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 647491568} m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!4 &647491572 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 647491568} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 20.23389, y: 0.21379566, z: 19.595634} m_LocalScale: {x: 2, y: 1, z: 2} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &675541834 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 675541838} - component: {fileID: 675541837} - component: {fileID: 675541836} - component: {fileID: 675541835} m_Layer: 0 m_Name: Plane (4) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!64 &675541835 MeshCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 675541834} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 3 m_Convex: 0 m_CookingOptions: 14 m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &675541836 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 675541834} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 24ecaffb63652ca4fa8cd12f429c23fd, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &675541837 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 675541834} m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!4 &675541838 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 675541834} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0.23389006, y: 0.21379566, z: 19.595634} m_LocalScale: {x: 2, y: 1, z: 2} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &845769234 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 845769235} m_Layer: 0 m_Name: Escenario m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &845769235 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 845769234} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: -0.23389006, y: -0.21379566, z: 0.4043665} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 63887635} - {fileID: 647491572} - {fileID: 675541838} - {fileID: 1266729294} - {fileID: 1968899500} - {fileID: 388582348} - {fileID: 303654691} - {fileID: 472133478} - {fileID: 82953786} - {fileID: 237597124} - {fileID: 1059608438} - {fileID: 1235073489} m_Father: {fileID: 0} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &1059608436 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 1059608438} - component: {fileID: 1059608437} - component: {fileID: 1059608439} m_Layer: 0 m_Name: Cube (4) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!65 &1059608437 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1059608436} m_Material: {fileID: 0} m_IsTrigger: 1 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!4 &1059608438 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1059608436} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 10.233891, y: 0.21379566, z: 39.595634} m_LocalScale: {x: 40, y: 10, z: 20} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 10 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &1059608439 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1059608436} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 744a208c85da6d04c861d81b992e4ead, type: 3} m_Name: m_EditorClassIdentifier: Emitters: - Target: {fileID: 538517056} Params: - Name: To Detected Value: 0 - Name: To Peace Value: 0 - Name: To Restricted Value: 0 - Name: To Conflict Value: 0 - Name: Invincible State Value: 1 TriggerEvent: 3 CollisionTag: Player --- !u!1 &1235073487 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 1235073489} - component: {fileID: 1235073488} - component: {fileID: 1235073490} m_Layer: 0 m_Name: Cube (5) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!65 &1235073488 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1235073487} m_Material: {fileID: 0} m_IsTrigger: 1 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 1, y: 1, z: 1} m_Center: {x: 0, y: 0, z: 0} --- !u!4 &1235073489 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1235073487} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 10.233891, y: 0.21379566, z: -20.404366} m_LocalScale: {x: 40, y: 10, z: 20} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 11 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &1235073490 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1235073487} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 744a208c85da6d04c861d81b992e4ead, type: 3} m_Name: m_EditorClassIdentifier: Emitters: - Target: {fileID: 538517056} Params: - Name: To Detected Value: 0 - Name: Invincible State Value: 1 - Name: To Conflict Value: 0 - Name: To Restricted Value: 0 - Name: To Peace Value: 0 TriggerEvent: 3 CollisionTag: Player --- !u!1 &1266729290 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 1266729294} - component: {fileID: 1266729293} - component: {fileID: 1266729292} - component: {fileID: 1266729291} m_Layer: 0 m_Name: Plane (5) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!64 &1266729291 MeshCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1266729290} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 3 m_Convex: 0 m_CookingOptions: 14 m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &1266729292 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1266729290} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: 5251f1efb71adef4f9bcae10b5afaf0d, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &1266729293 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1266729290} m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!4 &1266729294 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1266729290} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 10.233891, y: 0.21379566, z: 39.595634} m_LocalScale: {x: 4, y: 1, z: 2} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 3 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!1 &1968899496 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 1968899500} - component: {fileID: 1968899499} - component: {fileID: 1968899498} - component: {fileID: 1968899497} m_Layer: 0 m_Name: Plane (6) m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!64 &1968899497 MeshCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1968899496} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 3 m_Convex: 0 m_CookingOptions: 14 m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!23 &1968899498 MeshRenderer: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1968899496} m_Enabled: 1 m_CastShadows: 1 m_ReceiveShadows: 1 m_DynamicOccludee: 1 m_MotionVectors: 1 m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: - {fileID: 2100000, guid: e487ea40f1f78114fbaf88ce1c406ccd, type: 2} m_StaticBatchInfo: firstSubMesh: 0 subMeshCount: 0 m_StaticBatchRoot: {fileID: 0} m_ProbeAnchor: {fileID: 0} m_LightProbeVolumeOverride: {fileID: 0} m_ScaleInLightmap: 1 m_ReceiveGI: 1 m_PreserveUVs: 0 m_IgnoreNormalsForChartDetection: 0 m_ImportantGI: 0 m_StitchLightmapSeams: 0 m_SelectedEditorRenderState: 3 m_MinimumChartSize: 4 m_AutoUVMaxDistance: 0.5 m_AutoUVMaxAngle: 89 m_LightmapParameters: {fileID: 0} m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 --- !u!33 &1968899499 MeshFilter: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1968899496} m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0} --- !u!4 &1968899500 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1968899496} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 20.23389, y: 0.21379566, z: -0.4043665} m_LocalScale: {x: 2, y: 1, z: 2} m_Children: [] m_Father: {fileID: 845769235} m_RootOrder: 4 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
28,775
https://github.com/gluesys/p5-Mouse/blob/master/Moose-t-failing/050_metaclasses/012_moose_exporter.t
Github Open Source
Open Source
Artistic-1.0
2,019
p5-Mouse
gluesys
Perl
Code
1,005
3,194
#!/usr/bin/perl # This is automatically generated by author/import-moose-test.pl. # DO NOT EDIT THIS FILE. ANY CHANGES WILL BE LOST!!! use t::lib::MooseCompat; use strict; use warnings; use Test::More; $TODO = q{Mouse is not yet completed}; use Test::Exception; use Test::Requires { 'Test::Output' => '0.01', # skip all if not installed }; { package HasOwnImmutable; use Mouse; no Mouse; ::stderr_is( sub { eval q[sub make_immutable { return 'foo' }] }, '', 'no warning when defining our own make_immutable sub' ); } { is( HasOwnImmutable->make_immutable(), 'foo', 'HasOwnImmutable->make_immutable does not get overwritten' ); } { package MouseX::Empty; use Mouse (); Mouse::Exporter->setup_import_methods( also => 'Mouse' ); } { package WantsMouse; MouseX::Empty->import(); sub foo { 1 } ::can_ok( 'WantsMouse', 'has' ); ::can_ok( 'WantsMouse', 'with' ); ::can_ok( 'WantsMouse', 'foo' ); MouseX::Empty->unimport(); } { # Note: it's important that these methods be out of scope _now_, # after unimport was called. We tried a # namespace::clean(0.08)-based solution, but had to abandon it # because it cleans the namespace _later_ (when the file scope # ends). ok( ! WantsMouse->can('has'), 'WantsMouse::has() has been cleaned' ); ok( ! WantsMouse->can('with'), 'WantsMouse::with() has been cleaned' ); can_ok( 'WantsMouse', 'foo' ); # This makes sure that Mouse->init_meta() happens properly isa_ok( WantsMouse->meta(), 'Mouse::Meta::Class' ); isa_ok( WantsMouse->new(), 'Mouse::Object' ); } { package MouseX::Sugar; use Mouse (); sub wrapped1 { my $meta = shift; return $meta->name . ' called wrapped1'; } Mouse::Exporter->setup_import_methods( with_meta => ['wrapped1'], also => 'Mouse', ); } { package WantsSugar; MouseX::Sugar->import(); sub foo { 1 } ::can_ok( 'WantsSugar', 'has' ); ::can_ok( 'WantsSugar', 'with' ); ::can_ok( 'WantsSugar', 'wrapped1' ); ::can_ok( 'WantsSugar', 'foo' ); ::is( wrapped1(), 'WantsSugar called wrapped1', 'wrapped1 identifies the caller correctly' ); MouseX::Sugar->unimport(); } { ok( ! WantsSugar->can('has'), 'WantsSugar::has() has been cleaned' ); ok( ! WantsSugar->can('with'), 'WantsSugar::with() has been cleaned' ); ok( ! WantsSugar->can('wrapped1'), 'WantsSugar::wrapped1() has been cleaned' ); can_ok( 'WantsSugar', 'foo' ); } { package MouseX::MoreSugar; use Mouse (); sub wrapped2 { my $caller = shift->name; return $caller . ' called wrapped2'; } sub as_is1 { return 'as_is1'; } Mouse::Exporter->setup_import_methods( with_meta => ['wrapped2'], as_is => ['as_is1'], also => 'MouseX::Sugar', ); } { package WantsMoreSugar; MouseX::MoreSugar->import(); sub foo { 1 } ::can_ok( 'WantsMoreSugar', 'has' ); ::can_ok( 'WantsMoreSugar', 'with' ); ::can_ok( 'WantsMoreSugar', 'wrapped1' ); ::can_ok( 'WantsMoreSugar', 'wrapped2' ); ::can_ok( 'WantsMoreSugar', 'as_is1' ); ::can_ok( 'WantsMoreSugar', 'foo' ); ::is( wrapped1(), 'WantsMoreSugar called wrapped1', 'wrapped1 identifies the caller correctly' ); ::is( wrapped2(), 'WantsMoreSugar called wrapped2', 'wrapped2 identifies the caller correctly' ); ::is( as_is1(), 'as_is1', 'as_is1 works as expected' ); MouseX::MoreSugar->unimport(); } { ok( ! WantsMoreSugar->can('has'), 'WantsMoreSugar::has() has been cleaned' ); ok( ! WantsMoreSugar->can('with'), 'WantsMoreSugar::with() has been cleaned' ); ok( ! WantsMoreSugar->can('wrapped1'), 'WantsMoreSugar::wrapped1() has been cleaned' ); ok( ! WantsMoreSugar->can('wrapped2'), 'WantsMoreSugar::wrapped2() has been cleaned' ); ok( ! WantsMoreSugar->can('as_is1'), 'WantsMoreSugar::as_is1() has been cleaned' ); can_ok( 'WantsMoreSugar', 'foo' ); } { package My::Metaclass; use Mouse; BEGIN { extends 'Mouse::Meta::Class' } package My::Object; use Mouse; BEGIN { extends 'Mouse::Object' } package HasInitMeta; use Mouse (); sub init_meta { shift; return Mouse->init_meta( @_, metaclass => 'My::Metaclass', base_class => 'My::Object', ); } Mouse::Exporter->setup_import_methods( also => 'Mouse' ); } { package NewMeta; HasInitMeta->import(); } { isa_ok( NewMeta->meta(), 'My::Metaclass' ); isa_ok( NewMeta->new(), 'My::Object' ); } { package MouseX::CircularAlso; use Mouse (); ::dies_ok( sub { Mouse::Exporter->setup_import_methods( also => [ 'Mouse', 'MouseX::CircularAlso' ], ); }, 'a circular reference in also dies with an error' ); ::like( $@, qr/\QCircular reference in 'also' parameter to Mouse::Exporter between MouseX::CircularAlso and MouseX::CircularAlso/, 'got the expected error from circular reference in also' ); } { package MouseX::NoAlso; use Mouse (); ::dies_ok( sub { Mouse::Exporter->setup_import_methods( also => [ 'NoSuchThing' ], ); }, 'a package which does not use Mouse::Exporter in also dies with an error' ); ::like( $@, qr/\QPackage in also (NoSuchThing) does not seem to use Mouse::Exporter (is it loaded?) at /, 'got the expected error from a reference in also to a package which is not loaded' ); } { package MouseX::NotExporter; use Mouse (); ::dies_ok( sub { Mouse::Exporter->setup_import_methods( also => [ 'Mouse::Meta::Method' ], ); }, 'a package which does not use Mouse::Exporter in also dies with an error' ); ::like( $@, qr/\QPackage in also (Mouse::Meta::Method) does not seem to use Mouse::Exporter at /, 'got the expected error from a reference in also to a package which does not use Mouse::Exporter' ); } { package MouseX::OverridingSugar; use Mouse (); sub has { my $caller = shift->name; return $caller . ' called has'; } Mouse::Exporter->setup_import_methods( with_meta => ['has'], also => 'Mouse', ); } { package WantsOverridingSugar; MouseX::OverridingSugar->import(); ::can_ok( 'WantsOverridingSugar', 'has' ); ::can_ok( 'WantsOverridingSugar', 'with' ); ::is( has('foo'), 'WantsOverridingSugar called has', 'has from MouseX::OverridingSugar is called, not has from Mouse' ); MouseX::OverridingSugar->unimport(); } { ok( ! WantsSugar->can('has'), 'WantsSugar::has() has been cleaned' ); ok( ! WantsSugar->can('with'), 'WantsSugar::with() has been cleaned' ); } { package NonExistentExport; use Mouse (); ::stderr_like { Mouse::Exporter->setup_import_methods( also => ['Mouse'], with_meta => ['does_not_exist'], ); } qr/^Trying to export undefined sub NonExistentExport::does_not_exist/, "warns when a non-existent method is requested to be exported"; } { package WantsNonExistentExport; NonExistentExport->import; ::ok(!__PACKAGE__->can('does_not_exist'), "undefined subs do not get exported"); } { package AllOptions; use Mouse (); use Mouse::Deprecated -api_version => '0.88'; use Mouse::Exporter; Mouse::Exporter->setup_import_methods( also => ['Mouse'], with_meta => [ 'with_meta1', 'with_meta2' ], with_caller => [ 'with_caller1', 'with_caller2' ], as_is => ['as_is1'], ); sub with_caller1 { return @_; } sub with_caller2 (&) { return @_; } sub as_is1 {2} sub with_meta1 { return @_; } sub with_meta2 (&) { return @_; } } { package UseAllOptions; AllOptions->import(); } { can_ok( 'UseAllOptions', $_ ) for qw( with_meta1 with_meta2 with_caller1 with_caller2 as_is1 ); { my ( $caller, $arg1 ) = UseAllOptions::with_caller1(42); is( $caller, 'UseAllOptions', 'with_caller wrapped sub gets the right caller' ); is( $arg1, 42, 'with_caller wrapped sub returns argument it was passed' ); } { my ( $meta, $arg1 ) = UseAllOptions::with_meta1(42); isa_ok( $meta, 'Mouse::Meta::Class', 'with_meta first argument' ); is( $arg1, 42, 'with_meta1 returns argument it was passed' ); } is( prototype( UseAllOptions->can('with_caller2') ), prototype( AllOptions->can('with_caller2') ), 'using correct prototype on with_meta function' ); is( prototype( UseAllOptions->can('with_meta2') ), prototype( AllOptions->can('with_meta2') ), 'using correct prototype on with_meta function' ); } { package UseAllOptions; AllOptions->unimport(); } { ok( ! UseAllOptions->can($_), "UseAllOptions::$_ has been unimported" ) for qw( with_meta1 with_meta2 with_caller1 with_caller2 as_is1 ); } done_testing;
39,995
https://github.com/tendrie/datalift/blob/master/s4ac/shi3ld-policy-manager/shi3ld-policy-manager/public/javascripts/views/wizard.js
Github Open Source
Open Source
CECILL-B
2,021
datalift
tendrie
JavaScript
Code
165
543
/** * Abstract view to collect method to be inherithed by all wizard views */ define([ 'jquery', 'underscore', 'backbone', 'bootstrap' ], function($, _, Backbone){ var WizardView = Backbone.View.extend({ closeOnEsc: function (e) { //esc pressed if (e.keyCode == 27) { this.model.trigger('saveAlert', { cancelWizard: true, type: 'confirmCancel', }); } //tab pressed /*if (e.keyCode == 9) { this.tabindex = (this.tabindex + 1) % 10; this.tabindex range [0-9], tabindex attr range [1-10] $('[tabindex=' + (this.tabindex + 1) + ']').trigger('focus'); alert($('[tabindex=' + (this.tabindex + 1) + ']').attr('id')); }*/ }, cancelPolicy: function() { this.$modal.modal('hide'); this.model.destroy(); }, prevView: function(e){ var move; if ((e.target.id == "timeModalPrev") || (e.target.id == "outdoorModalPrev")){ this.updateWizardModel(); move = true } else { move = this.updateWizardModel(); } if (move) { this.$modal.modal('hide'); this.parentView.showModal(); } }, showModal: function() { if (this.$modal) { this.$modal.modal(); return; } //owerwrite modal make it lose proper DOM element on this.$modal so find with jquery //because hidden and showed later (ie moved on DOM because is the way bootstrap managed modals) $('#newPolicy').modal(); }, }); return WizardView; });
32,553
https://github.com/Baoxiaohe/rabbit-tasker/blob/master/index.js
Github Open Source
Open Source
MIT
2,020
rabbit-tasker
Baoxiaohe
JavaScript
Code
7
19
const master = require('./lib/master') module.exports = master;
49,082
https://github.com/cha-yh/react-boilerplate-by-cha/blob/master/src/containers/ExampleContainer/ExampleContainer.js
Github Open Source
Open Source
MIT
2,019
react-boilerplate-by-cha
cha-yh
JavaScript
Code
223
806
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { setSomethingAsync, getExample } from 'store/modules/example'; import image from 'images/exampleImg/window.png'; import classnames from 'classnames/bind'; import styles from './ExampleContainer.module.scss'; import './ExampleContainer.scss'; import ExampleComponent from './ExampleComponent'; const cx = classnames.bind(styles); class TestContainer extends Component { constructor(props) { super(props); this.state = { index: 1, loading: false } this.changeInput = this.changeInput.bind(this); this.prev = this.prev.bind(this); this.next = this.next.bind(this); } componentDidMount() { this.props.getExample(this.state.index); } loadingWrapper = async (func) => { this.setState({ loading: true }); await func; this.setState({ loading: false }); } changeInput(e) { this.props.setSomethingAsync(e.target.value) } prev = async () => { let index = this.state.index; this.loadingWrapper(this.props.getExample(index-1)) this.setState({ index: index - 1 }); } next = async () => { let index = this.state.index; this.loadingWrapper(this.props.getExample(index + 1)); this.setState({ index: this.state.index + 1, }); } render() { console.log('this.props.pender :', this.props.pender); const { something, data } = this.props; const {loading} = this.state; return ( <div className={cx('container')}> <ExampleComponent /> <div className={cx('async_test')}> <h3>Async input</h3> <input type="text" onChange={this.changeInput} /> <p>Async text : {something}</p> </div> <div className={cx('dummy_text_loader', {loading})}> <h1>{data && data.title}</h1> <div className={cx('row')}> <button className={cx('next-btn')} onClick={this.prev}>prev</button> <p>{this.state.index}</p> <button className='next-btn' onClick={this.next}>next</button> </div> </div> <img src={image} alt="" /> <div className="test"> <p>test</p> </div> </div> ); } } const mapStateToProps = ({ example, pender }) => ({ something: example.something, data: example.data, pender }); const mapDispatchToProps = { setSomethingAsync, getExample }; export default connect( mapStateToProps, mapDispatchToProps )(TestContainer);
46,677
https://github.com/dbeerten/iesi-ui/blob/master/src/views/routes.ts
Github Open Source
Open Source
MIT
2,020
iesi-ui
dbeerten
TypeScript
Code
17
53
export enum ROUTES { CURRENT_INDEX_PAGE = './', DASHBOARD = 'dashboard', ABOUT = 'about', ABOUT_TEAM = 'team', }
2,907
https://github.com/darken1/dhis2darken/blob/master/dhis-2/dhis-web/dhis-web-tracker-capture/src/main/webapp/dhis-web-tracker-capture/components/notes/notes-controller.js
Github Open Source
Open Source
BSD-3-Clause
2,014
dhis2darken
darken1
JavaScript
Code
10
55
trackerCapture.controller('NotesController', function($scope, storage, TranslationService) { TranslationService.translate(); $scope.attributes = storage.get('ATTRIBUTES'); });
40,817
https://github.com/konchunas/bash-to-fish/blob/master/test/comment/test.sh
Github Open Source
Open Source
MIT
2,022
bash-to-fish
konchunas
Shell
Code
8
12
# this is a comment ; echo foo
43,809
https://github.com/meomancer/inasafe-fba/blob/master/fixtures/schema/02_fbf/04_routines/00_functions/17_calculate_impact.sql
Github Open Source
Open Source
MIT
2,020
inasafe-fba
meomancer
SQL
Code
125
402
create or replace function kartoza_calculate_impact() returns character varying language plpgsql as $$ BEGIN refresh materialized view mv_flood_event_buildings with data; refresh materialized view mv_flooded_building_summary with data; refresh materialized view mv_flood_event_village_summary with data; refresh materialized view mv_flood_event_sub_district_summary with data; refresh materialized view mv_flood_event_district_summary with data; refresh materialized view mv_flood_event_roads with data; refresh materialized view mv_flooded_roads_summary with data; refresh materialized view mv_flood_event_road_village_summary with data; refresh materialized view mv_flood_event_road_sub_district_summary with data; refresh materialized view mv_flood_event_road_district_summary with data; refresh materialized view mv_flood_event_population with data; refresh materialized view mv_flood_event_population_village_summary with data; refresh materialized view mv_flood_event_population_sub_district_summary with data; refresh materialized view mv_flood_event_population_district_summary with data; refresh materialized view mv_flood_event_world_pop with data; refresh materialized view mv_flood_event_world_pop_village_summary with data; refresh materialized view mv_flood_event_world_pop_sub_district_summary with data; refresh materialized view mv_flood_event_world_pop_district_summary with data; RETURN 'OK'; END $$;
46,550
https://github.com/duyleomessi/java_datastruct_advance/blob/master/run.sh
Github Open Source
Open Source
Apache-2.0
null
java_datastruct_advance
duyleomessi
Shell
Code
13
73
#!/bin/sh echo "Build" javac -cp src:libs/javax.json-1.0.4.jar src/application/MapApp.java echo "Run" java -cp src:libs/javax.json-1.0.4.jar application.MapApp
9,307
https://github.com/Proglab/csf/blob/master/templates/security/login.html.twig
Github Open Source
Open Source
MIT
2,020
csf
Proglab
Twig
Code
112
440
{% extends 'base.html.twig' %} {% block title %}Log in!{% endblock %} {% block body %} <form method="post"> <div class="row"> <div class="col-lg-8 mb-4"> <h3>Login</h3> <form name="sentMessage" id="contactForm" novalidate> <div class="control-group form-group"> <div class="controls"> <label>E-mail:</label> <input type="email" value="{{ last_username }}" name="email" id="email" class="form-control" required autofocus> <p class="help-block"></p> </div> </div> <div class="control-group form-group"> <div class="controls"> <label>Password:</label> <input type="password" name="password" id="password" class="form-control" required> </div> </div> <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}"> <button class="btn btn-lg btn-primary" type="submit"> Log in </button> </form> </div> </div> </form> <div class="row"> <div class="col-lg-8 mb-4"> You don't have an account ? Please <a href="{{ path('app_register') }}">register</a> </div> <div class="col-lg-8 mb-4"> <a href="{{ path('app_forgot_password_request') }}">You lost your password ?</a> </div> </div> {% endblock %}
49,703
https://github.com/icevelyov/roslyn/blob/master/src/EditorFeatures/VisualBasicTest/Completion/CompletionProviderOrderTests.vb
Github Open Source
Open Source
MIT
2,022
roslyn
icevelyov
Visual Basic
Code
326
1,565
' 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. Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion <UseExportProvider> Public Class CompletionProviderOrderTests ''' <summary> ''' Verifies the exact order of all built-in completion providers. ''' </summary> <Fact> Public Sub TestCompletionProviderOrder() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim actualOrder = orderedVisualBasicCompletionProviders.Select(Function(x) x.Value.GetType()).ToArray() Dim expectedOrder = { GetType(FirstBuiltInCompletionProvider), GetType(KeywordCompletionProvider), GetType(SymbolCompletionProvider), GetType(PreprocessorCompletionProvider), GetType(ObjectInitializerCompletionProvider), GetType(ObjectCreationCompletionProvider), GetType(EnumCompletionProvider), GetType(NamedParameterCompletionProvider), GetType(VisualBasicSuggestionModeCompletionProvider), GetType(ImplementsClauseCompletionProvider), GetType(HandlesClauseCompletionProvider), GetType(PartialTypeCompletionProvider), GetType(CrefCompletionProvider), GetType(CompletionListTagCompletionProvider), GetType(OverrideCompletionProvider), GetType(XmlDocCommentCompletionProvider), GetType(InternalsVisibleToCompletionProvider), GetType(EmbeddedLanguageCompletionProvider), GetType(TypeImportCompletionProvider), GetType(ExtensionMethodImportCompletionProvider), GetType(LastBuiltInCompletionProvider) } AssertEx.EqualOrDiff( String.Join(Environment.NewLine, expectedOrder.Select(Function(x) x.FullName)), String.Join(Environment.NewLine, actualOrder.Select(Function(x) x.FullName))) End Sub ''' <summary> ''' Verifies that the order of built-in completion providers is deterministic. ''' </summary> <Fact> Public Sub TestCompletionProviderOrderMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) For i = 0 To orderedVisualBasicCompletionProviders.Count - 1 If i = 0 Then Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped) Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped) Continue For ElseIf i = orderedVisualBasicCompletionProviders.Count - 1 Then Assert.Empty(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped) If Not orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped.Contains(orderedVisualBasicCompletionProviders(i - 1).Metadata.Name) Then ' Make sure the last built-in provider comes before the marker Assert.Contains(orderedVisualBasicCompletionProviders(i).Metadata.Name, orderedVisualBasicCompletionProviders(i - 1).Metadata.BeforeTyped) End If Continue For End If If orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped.Any() Then Assert.Equal(orderedVisualBasicCompletionProviders.Last().Metadata.Name, Assert.Single(orderedVisualBasicCompletionProviders(i).Metadata.BeforeTyped)) End If Dim after = Assert.Single(orderedVisualBasicCompletionProviders(i).Metadata.AfterTyped) Assert.Equal(orderedVisualBasicCompletionProviders(i - 1).Metadata.Name, after) Next End Sub <Fact> Public Sub TestCompletionProviderFirstNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim firstCompletionProvider = orderedVisualBasicCompletionProviders.First() Assert.Equal("FirstBuiltInCompletionProvider", firstCompletionProvider.Metadata.Name) End Sub <Fact> Public Sub TestCompletionProviderLastNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim orderedVisualBasicCompletionProviders = ExtensionOrderer.Order(completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic)) Dim lastCompletionProvider = orderedVisualBasicCompletionProviders.Last() Assert.Equal("LastBuiltInCompletionProvider", lastCompletionProvider.Metadata.Name) End Sub <Fact> Public Sub TestCompletionProviderNameMetadata() Dim exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider() Dim completionProviderExports = exportProvider.GetExports(Of CompletionProvider, CompletionProviderMetadata)() Dim visualBasicCompletionProviders = completionProviderExports.Where(Function(export) export.Metadata.Language = LanguageNames.VisualBasic) For Each export In visualBasicCompletionProviders Assert.Equal(export.Value.GetType().Name, export.Metadata.Name) Next End Sub End Class End Namespace
8,074
https://github.com/yashashrirane/interlok/blob/master/interlok-core/src/main/java/com/adaptris/jdbc/CallableStatementExecutorImpl.java
Github Open Source
Open Source
Apache-2.0
2,021
interlok
yashashrirane
Java
Code
171
409
/* * Copyright 2017 Adaptris Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adaptris.jdbc; import java.sql.Statement; import org.apache.commons.lang3.BooleanUtils; import com.adaptris.annotation.InputFieldDefault; public abstract class CallableStatementExecutorImpl implements CallableStatementExecutor { @InputFieldDefault(value = "false") private Boolean handleMultipleResultsetsQuietly; public CallableStatementExecutorImpl() { } public Boolean getHandleMultipleResultsetsQuietly() { return handleMultipleResultsetsQuietly; } /** * Ignore SQL Exceptions when calling {@link Statement#getMoreResults(int)}. * * @param b true to ignore exceptions from {@link Statement#getMoreResults(int)}; default null (false). */ public void setHandleMultipleResultsetsQuietly(Boolean b) { this.handleMultipleResultsetsQuietly = b; } protected boolean ignoreMoreResultsException() { return BooleanUtils.toBooleanDefaultIfNull(getHandleMultipleResultsetsQuietly(), false); } }
41,894
https://github.com/sivasundar-ks/omci-lib-go/blob/master/generated/pwatmconfigurationdata.go
Github Open Source
Open Source
Apache-2.0
null
omci-lib-go
sivasundar-ks
Go
Code
776
1,857
/* * Copyright (c) 2018 - present. Boling Consulting Solutions (bcsw.net) * Copyright 2020-present Open Networking Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * NOTE: This file was generated, manual edits will be overwritten! * * Generated by 'goCodeGenerator.py': * https://github.com/cboling/OMCI-parser/README.md */ package generated import "github.com/deckarep/golang-set" // PwAtmConfigurationDataClassID is the 16-bit ID for the OMCI // Managed entity PW ATM configuration data const PwAtmConfigurationDataClassID ClassID = ClassID(337) var pwatmconfigurationdataBME *ManagedEntityDefinition // PwAtmConfigurationData (class ID #337) // This ME contains generic configuration data for an ATM pseudowire. Definitions of attributes are // from PW-ATM-MIB [IETF RFC 5605]. Instances of this ME are created and deleted by the OLT. // // Relationships // An instance of this ME is associated with an instance of the MPLS pseudowire TP ME with a // pseudowire type attribute equal to one of the following.//// 2 ATM AAL5 SDU VCC transport//// 3 ATM transparent cell transport//// 9 ATM n-to-one VCC cell transport//// 10 ATM n-to-one VPC cell transport//// 12 ATM one-to-one VCC cell mode//// 13 ATM one-to-one VPC cell mode//// 14 ATM AAL5 PDU VCC transport//// Alternatively, an instance of this ME may be associated with an Ethernet flow TP or a TCP/UDP // config data ME, depending on the transport layer of the pseudowire. // // Attributes // Managed Entity Id // Managed entity ID: This attribute uniquely identifies each instance of this ME. (R, // setbycreate)-(mandatory) (2 bytes) // // Tp Type // 2 TCP/UDP config data // // Transport Tp Pointer // Transport TP pointer: This attribute points to an associated instance of the transport layer TP, // whose type is specified by the TP type attribute. (R, W, setbycreate) (mandatory) (2 bytes) // // Pptp Atm Uni Pointer // PPTP ATM UNI pointer: This attribute points to an associated instance of the ITU-T G.983.2 PPTP // ATM UNI. Refer to [ITUT G.983.2] for the definition of the target ME. (R, W, setbycreate) // (mandatory) (2 bytes) // // Max C Ell C Oncatenation // Max cell concatenation: This attribute specifies the maximum number of ATM cells that can be // concatenated into one PW packet in the upstream direction. (R, W, setbycreate) (mandatory) (2 // bytes) // // Far End M Ax C Ell C Oncatenation // Far-end max cell concatenation: This attribute specifies the maximum number of ATM cells that // can be concatenated into one PW packet as provisioned at the far end. This attribute may be used // for error checking of downstream traffic. The value 0 specifies that the ONU uses its internal // default. (R, W, set-by-create) (optional) (2 bytes) // // Atm Cell Loss Priority Clp Qos Mapping // The value 0 specifies that the ONU uses its internal default. (R, W, setbycreate) (optional) (1 // byte) // // Timeout Mode // The value 0 specifies that the ONU uses its internal default. (R, W, setbycreate) (optional) (1 // byte) // // Pw Atm Mapping Table // (R,-W) (mandatory) (21N bytes, where N is the number of entries in the list) // type PwAtmConfigurationData struct { ManagedEntityDefinition Attributes AttributeValueMap } func init() { pwatmconfigurationdataBME = &ManagedEntityDefinition{ Name: "PwAtmConfigurationData", ClassID: 337, MessageTypes: mapset.NewSetWith( Create, Delete, Get, GetNext, Set, SetTable, ), AllowedAttributeMask: 0xff00, AttributeDefinitions: AttributeDefinitionMap{ 0: Uint16Field("ManagedEntityId", PointerAttributeType, 0x0000, 0, mapset.NewSetWith(Read, SetByCreate), false, false, false, 0), 1: ByteField("TpType", UnsignedIntegerAttributeType, 0x8000, 0, mapset.NewSetWith(Read, SetByCreate, Write), false, false, false, 1), 2: Uint16Field("TransportTpPointer", UnsignedIntegerAttributeType, 0x4000, 0, mapset.NewSetWith(Read, SetByCreate, Write), false, false, false, 2), 3: Uint16Field("PptpAtmUniPointer", UnsignedIntegerAttributeType, 0x2000, 0, mapset.NewSetWith(Read, SetByCreate, Write), false, false, false, 3), 4: Uint16Field("MaxCEllCOncatenation", UnsignedIntegerAttributeType, 0x1000, 0, mapset.NewSetWith(Read, SetByCreate, Write), false, false, false, 4), 5: Uint16Field("FarEndMAxCEllCOncatenation", UnsignedIntegerAttributeType, 0x0800, 0, mapset.NewSetWith(Read, SetByCreate, Write), false, true, false, 5), 6: ByteField("AtmCellLossPriorityClpQosMapping", UnsignedIntegerAttributeType, 0x0400, 0, mapset.NewSetWith(Read, SetByCreate, Write), false, true, false, 6), 7: ByteField("TimeoutMode", UnsignedIntegerAttributeType, 0x0200, 0, mapset.NewSetWith(Read, SetByCreate, Write), false, true, false, 7), 8: TableField("PwAtmMappingTable", TableAttributeType, 0x0100, TableInfo{nil, 21}, mapset.NewSetWith(Read, Write), false, false, false, 8), }, Access: CreatedByOlt, Support: UnknownSupport, } } // NewPwAtmConfigurationData (class ID 337) creates the basic // Managed Entity definition that is used to validate an ME of this type that // is received from or transmitted to the OMCC. func NewPwAtmConfigurationData(params ...ParamData) (*ManagedEntity, OmciErrors) { return NewManagedEntity(*pwatmconfigurationdataBME, params...) }
39,362
https://github.com/rickqi/datart/blob/master/frontend/src/app/pages/DashBoardPage/pages/BoardEditor/components/ControllerWidgetPanel/ControllerConfig/OtherSet.tsx/RadioStyle/RadioStyleSet.tsx
Github Open Source
Open Source
Apache-2.0
null
datart
rickqi
TypeScript
Code
153
326
/** * Datart * * Copyright 2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { FormItemProps, Radio } from 'antd'; import React, { memo } from 'react'; export interface RadioStyleSetProps extends FormItemProps<any> { value?: any; onChange?: any; } export const RadioStyleSet: React.FC<RadioStyleSetProps> = memo( ({ value, onChange }) => { function _onChange(val) { onChange?.(val); } return ( <Radio.Group onChange={_onChange} defaultValue={value}> <Radio.Button value="default">常规</Radio.Button> <Radio.Button value="button">按钮</Radio.Button> </Radio.Group> ); }, );
22,168
https://github.com/ExLuzZziVo/AspNetCore.CustomValidation/blob/master/src/TanvirArjel.CustomValidation.AspNetCore/Adapters/RequiredIfAttributeAdapter.cs
Github Open Source
Open Source
MIT
null
AspNetCore.CustomValidation
ExLuzZziVo
C#
Code
193
830
// <copyright file="RequiredIfAttributeAdapter.cs" company="TanvirArjel"> // Copyright (c) TanvirArjel. All rights reserved. // </copyright> using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.DataAnnotations; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.Extensions.Localization; using TanvirArjel.CustomValidation.Attributes; using TanvirArjel.CustomValidation.Extensions; namespace TanvirArjel.CustomValidation.AspNetCore.Adapters { internal class RequiredIfAttributeAdapter : AttributeAdapterBase<RequiredIfAttribute> { public RequiredIfAttributeAdapter(RequiredIfAttribute attribute, IStringLocalizer stringLocalizer) : base(attribute, stringLocalizer) { } public override void AddValidation(ClientModelValidationContext context) { var modelType = context.ModelMetadata.ContainerType; var otherPropertyInfo = modelType.GetProperty(Attribute.OtherPropertyName); if (otherPropertyInfo == null) { throw new ApplicationException($"Model does not contain any property named {Attribute.OtherPropertyName}"); } var otherPropertyType = otherPropertyInfo.PropertyType; if (otherPropertyType.IsDateTimeType()) { AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "datetime"); } else if (otherPropertyType.IsNumericType()) { AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "number"); } else if (otherPropertyType == typeof(string)) { AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "string"); } else if (otherPropertyType.IsTimeSpanType()) { AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "timespan"); } else if (otherPropertyType == typeof(bool)) { AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "boolean"); } else { throw new ApplicationException($"This attribute does not support type {otherPropertyType}"); } AddAttribute(context.Attributes, "data-val", "true"); AddAttribute(context.Attributes, "data-val-requiredif-other-property", "*." + Attribute.OtherPropertyName); AddAttribute(context.Attributes, "data-val-requiredif-comparison-type", Attribute.ComparisonType.ToString()); AddAttribute(context.Attributes, "data-val-requiredif-other-property-value", Attribute.OtherPropertyValue?.ToString() ?? string.Empty); string errorMessage = GetErrorMessage(context); AddAttribute(context.Attributes, "data-val-requiredif", errorMessage); } public override string GetErrorMessage(ModelValidationContextBase validationContext) { string propertyDisplayName = validationContext.ModelMetadata.GetDisplayName(); return GetErrorMessage(validationContext.ModelMetadata, propertyDisplayName); } private static void AddAttribute(IDictionary<string, string> attributes, string key, string value) { if (!attributes.ContainsKey(key)) { attributes.Add(key, value); } } } }
43,672
https://github.com/AgriculturalModelExchangeInitiative/SQ_Wheat_Phenology/blob/master/src/stics/SQ_Wheat_Phenology/PhenologyComponent.f90
Github Open Source
Open Source
MIT
2,022
SQ_Wheat_Phenology
AgriculturalModelExchangeInitiative
Fortran Free Form
Code
6,352
14,840
MODULE Phenologymod USE list_sub USE Phyllochronmod USE Phylsowingdatecorrectionmod USE Shootnumbermod USE Updateleafflagmod USE Updatephasemod USE Leafnumbermod USE Vernalizationprogressmod USE Ismomentregistredzc_39mod USE Cumulttfrommod USE Updatecalendarmod USE Registerzadokmod USE Ptqmod USE Gaimeanmod IMPLICIT NONE CONTAINS SUBROUTINE model_phenology(phyllochron_t1, & minFinalNumber_t1, & aMXLFNO, & currentdate, & cumulTT, & pNini, & sDsa_sh, & latitude, & kl, & calendarDates_t1, & calendarMoments_t1, & lincr, & ldecr, & pincr, & ptq, & pTQhf, & B, & areaSL, & areaSS, & lARmin, & sowingDensity, & lARmax, & lNeff, & rp, & p, & pdecr, & leafNumber_t1, & maxTvern, & dayLength, & deltaTT, & pastMaxAI_t1, & tTWindowForPTQ, & listGAITTWindowForPTQ_t1, & gAI, & pAR, & listPARTTWindowForPTQ_t1, & listTTShootWindowForPTQ1_t1, & listTTShootWindowForPTQ_t1, & vBEE, & calendarCumuls_t1, & isVernalizable, & vernaprog_t1, & minTvern, & intTvern, & vAI, & maxDL, & choosePhyllUse, & minDL, & hasLastPrimordiumAppeared_t1, & phase_t1, & pFLLAnth, & dcd, & dgf, & degfm, & ignoreGrainMaturation, & pHEADANTH, & finalLeafNumber_t1, & sLDL, & grainCumulTT, & sowingDay, & hasZadokStageChanged_t1, & currentZadokStage, & sowingDate, & sDws, & sDsa_nh, & hasFlagLeafLiguleAppeared, & der, & hasFlagLeafLiguleAppeared_t1, & tilleringProfile_t1, & targetFertileShoot, & leafTillerNumberArray_t1, & dse, & slopeTSFLN, & intTSFLN, & canopyShootNumber_t1, & hasZadokStageChanged, & listPARTTWindowForPTQ, & hasLastPrimordiumAppeared, & listTTShootWindowForPTQ, & listTTShootWindowForPTQ1, & calendarMoments, & canopyShootNumber, & calendarDates, & leafTillerNumberArray, & vernaprog, & phyllochron, & leafNumber, & numberTillerCohort, & tilleringProfile, & averageShootNumberPerPlant, & minFinalNumber, & finalLeafNumber, & phase, & listGAITTWindowForPTQ, & calendarCumuls, & gAImean, & pastMaxAI) IMPLICIT NONE REAL, INTENT(IN) :: phyllochron_t1 REAL, INTENT(IN) :: minFinalNumber_t1 REAL, INTENT(IN) :: aMXLFNO CHARACTER(65), INTENT(IN) :: currentdate REAL, INTENT(IN) :: cumulTT REAL, INTENT(IN) :: pNini REAL, INTENT(IN) :: sDsa_sh REAL, INTENT(IN) :: latitude REAL, INTENT(IN) :: kl CHARACTER(65), ALLOCATABLE , DIMENSION(:), INTENT(IN) :: & calendarDates_t1 CHARACTER(65), ALLOCATABLE , DIMENSION(:), INTENT(IN) :: & calendarMoments_t1 REAL, INTENT(IN) :: lincr REAL, INTENT(IN) :: ldecr REAL, INTENT(IN) :: pincr REAL, INTENT(INOUT) :: ptq REAL, INTENT(IN) :: pTQhf REAL, INTENT(IN) :: B REAL, INTENT(IN) :: areaSL REAL, INTENT(IN) :: areaSS REAL, INTENT(IN) :: lARmin REAL, INTENT(IN) :: sowingDensity REAL, INTENT(IN) :: lARmax REAL, INTENT(IN) :: lNeff REAL, INTENT(IN) :: rp REAL, INTENT(IN) :: p REAL, INTENT(IN) :: pdecr REAL, INTENT(IN) :: leafNumber_t1 REAL, INTENT(IN) :: maxTvern REAL, INTENT(IN) :: dayLength REAL, INTENT(IN) :: deltaTT REAL, INTENT(IN) :: pastMaxAI_t1 REAL, INTENT(IN) :: tTWindowForPTQ REAL, ALLOCATABLE , DIMENSION(:), INTENT(IN) :: & listGAITTWindowForPTQ_t1 REAL, INTENT(IN) :: gAI REAL, INTENT(IN) :: pAR REAL, ALLOCATABLE , DIMENSION(:), INTENT(IN) :: & listPARTTWindowForPTQ_t1 REAL, ALLOCATABLE , DIMENSION(:), INTENT(IN) :: & listTTShootWindowForPTQ1_t1 REAL, ALLOCATABLE , DIMENSION(:), INTENT(IN) :: & listTTShootWindowForPTQ_t1 REAL, INTENT(IN) :: vBEE REAL, ALLOCATABLE , DIMENSION(:), INTENT(IN) :: calendarCumuls_t1 INTEGER, INTENT(IN) :: isVernalizable REAL, INTENT(IN) :: vernaprog_t1 REAL, INTENT(IN) :: minTvern REAL, INTENT(IN) :: intTvern REAL, INTENT(IN) :: vAI REAL, INTENT(IN) :: maxDL CHARACTER(65), INTENT(IN) :: choosePhyllUse REAL, INTENT(IN) :: minDL INTEGER, INTENT(IN) :: hasLastPrimordiumAppeared_t1 REAL, INTENT(IN) :: phase_t1 REAL, INTENT(IN) :: pFLLAnth REAL, INTENT(IN) :: dcd REAL, INTENT(IN) :: dgf REAL, INTENT(IN) :: degfm LOGICAL, INTENT(IN) :: ignoreGrainMaturation REAL, INTENT(IN) :: pHEADANTH REAL, INTENT(IN) :: finalLeafNumber_t1 REAL, INTENT(IN) :: sLDL REAL, INTENT(IN) :: grainCumulTT INTEGER, INTENT(IN) :: sowingDay INTEGER, INTENT(IN) :: hasZadokStageChanged_t1 CHARACTER(65), INTENT(INOUT) :: currentZadokStage CHARACTER(65), INTENT(IN) :: sowingDate INTEGER, INTENT(IN) :: sDws REAL, INTENT(IN) :: sDsa_nh INTEGER, INTENT(INOUT) :: hasFlagLeafLiguleAppeared REAL, INTENT(IN) :: der INTEGER, INTENT(IN) :: hasFlagLeafLiguleAppeared_t1 REAL, ALLOCATABLE , DIMENSION(:), INTENT(IN) :: tilleringProfile_t1 REAL, INTENT(IN) :: targetFertileShoot INTEGER, ALLOCATABLE , DIMENSION(:), INTENT(IN) :: & leafTillerNumberArray_t1 REAL, INTENT(IN) :: dse REAL, INTENT(IN) :: slopeTSFLN REAL, INTENT(IN) :: intTSFLN REAL, INTENT(IN) :: canopyShootNumber_t1 REAL:: fixPhyll REAL, INTENT(OUT) :: leafNumber REAL, INTENT(OUT) :: gAImean REAL, INTENT(OUT) :: phyllochron INTEGER:: numberTillerCohort_t1 REAL, INTENT(OUT) :: averageShootNumberPerPlant REAL, INTENT(OUT) :: canopyShootNumber INTEGER, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & leafTillerNumberArray REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: tilleringProfile INTEGER, INTENT(OUT) :: numberTillerCohort CHARACTER(65), ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & calendarMoments CHARACTER(65), ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & calendarDates REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: calendarCumuls REAL, INTENT(OUT) :: finalLeafNumber REAL, INTENT(OUT) :: phase REAL:: cumulTTFromZC_39 INTEGER:: isMomentRegistredZC_39 REAL, INTENT(OUT) :: vernaprog REAL, INTENT(OUT) :: minFinalNumber REAL:: cumulTTFromZC_91 INTEGER, INTENT(OUT) :: hasLastPrimordiumAppeared REAL:: cumulTTFromZC_65 INTEGER, INTENT(OUT) :: hasZadokStageChanged REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: listGAITTWindowForPTQ REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: listPARTTWindowForPTQ REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & listTTShootWindowForPTQ REAL, INTENT(OUT) :: pastMaxAI REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & listTTShootWindowForPTQ1 !- Name: Phenology -Version: 001, -Time step: 1 !- Description: ! * Title: Phenology ! * Author: Pierre MARTRE ! * Reference: Modeling development phase in the ! Wheat Simulation Model SiriusQuality. ! See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427 ! * Institution: INRA/LEPSE ! * Abstract: see documentation !- inputs: ! * name: phyllochron_t1 ! ** description : phyllochron ! ** variablecategory : state ! ** inputtype : variable ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1000 ! ** default : 0 ! ** unit : °C d leaf-1 ! * name: minFinalNumber_t1 ! ** description : minimum final leaf number ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 25 ! ** default : 5.5 ! ** unit : leaf ! ** inputtype : variable ! ** variablecategory : state ! * name: aMXLFNO ! ** description : Absolute maximum leaf number ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 25 ! ** default : 24.0 ! ** unit : leaf ! ** inputtype : parameter ! * name: currentdate ! ** description : current date ! ** variablecategory : auxiliary ! ** datatype : DATE ! ** default : 2007/3/27 ! ** inputtype : variable ! ** unit : ! * name: cumulTT ! ** description : cumul thermal times at currentdate ! ** variablecategory : auxiliary ! ** datatype : DOUBLE ! ** min : -200 ! ** max : 10000 ! ** default : 112.330110409888 ! ** unit : °C d ! ** inputtype : variable ! * name: pNini ! ** description : Number of primorida in the apex at emergence ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 24 ! ** default : 4.0 ! ** unit : primordia ! ** inputtype : parameter ! * name: sDsa_sh ! ** description : Sowing date at which Phyllochrone is maximum in southern hemispher ! ** parametercategory : species ! ** inputtype : parameter ! ** datatype : DOUBLE ! ** min : 1 ! ** max : 365 ! ** default : 1.0 ! ** unit : d ! ** uri : some url ! * name: latitude ! ** description : Latitude ! ** parametercategory : soil ! ** datatype : DOUBLE ! ** min : -90 ! ** max : 90 ! ** default : 0.0 ! ** unit : ° ! ** uri : some url ! ** inputtype : parameter ! * name: kl ! ** description : Exctinction Coefficient ! ** inputtype : parameter ! ** parametercategory : species ! ** datatype : DOUBLE ! ** default : 0.45 ! ** min : 0.0 ! ** max : 50.0 ! ** unit : - ! ** uri : some url ! * name: calendarDates_t1 ! ** description : List containing the dates of the wheat developmental phases ! ** variablecategory : state ! ** datatype : DATELIST ! ** default : ['2007/3/21'] ! ** unit : ! ** inputtype : variable ! * name: calendarMoments_t1 ! ** description : List containing appearance of each stage at previous day ! ** variablecategory : state ! ** datatype : STRINGLIST ! ** default : ['Sowing'] ! ** unit : ! ** inputtype : variable ! * name: lincr ! ** description : Leaf number above which the phyllochron is increased by Pincr ! ** inputtype : parameter ! ** parametercategory : species ! ** datatype : DOUBLE ! ** default : 8.0 ! ** min : 0.0 ! ** max : 30.0 ! ** unit : leaf ! ** uri : some url ! * name: ldecr ! ** description : Leaf number up to which the phyllochron is decreased by Pdecr ! ** inputtype : parameter ! ** parametercategory : species ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 100.0 ! ** unit : leaf ! ** uri : some url ! * name: pincr ! ** description : Factor increasing the phyllochron for leaf number higher than Lincr ! ** inputtype : parameter ! ** parametercategory : species ! ** datatype : DOUBLE ! ** default : 1.5 ! ** min : 0.0 ! ** max : 10.0 ! ** unit : - ! ** uri : some url ! * name: ptq ! ** description : Photothermal quotient ! ** inputtype : variable ! ** variablecategory : state ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 10000.0 ! ** unit : MJ °C-1 d-1 m-2) ! ** uri : some url ! * name: pTQhf ! ** description : Slope to intercept ratio for Phyllochron parametrization with PhotoThermal Quotient ! ** inputtype : parameter ! ** parametercategory : genotypic ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : °C d leaf-1 ! ** uri : some url ! * name: B ! ** description : Phyllochron at PTQ equal 1 ! ** inputtype : parameter ! ** parametercategory : species ! ** datatype : DOUBLE ! ** default : 20.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : °C d leaf-1 ! ** uri : some url ! * name: areaSL ! ** description : Area Leaf ! ** inputtype : parameter ! ** parametercategory : genotypic ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : cm2 ! ** uri : some url ! * name: areaSS ! ** description : Area Sheath ! ** inputtype : parameter ! ** parametercategory : genotypic ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : cm2 ! ** uri : some url ! * name: lARmin ! ** description : LAR minimum ! ** inputtype : parameter ! ** parametercategory : genotypic ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : leaf-1 °C ! ** uri : some url ! * name: sowingDensity ! ** description : Sowing Density ! ** inputtype : parameter ! ** parametercategory : genotypic ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : plant m-2 ! ** uri : some url ! * name: lARmax ! ** description : LAR maximum ! ** inputtype : parameter ! ** parametercategory : genotypic ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : leaf-1 °C ! ** uri : some url ! * name: lNeff ! ** description : Leaf Number efficace ! ** inputtype : parameter ! ** parametercategory : genotypic ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : leaf ! ** uri : some url ! * name: rp ! ** description : Rate of change of Phyllochrone with sowing date ! ** parametercategory : species ! ** inputtype : parameter ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 365 ! ** default : 0 ! ** unit : d-1 ! ** uri : some url ! * name: p ! ** description : Phyllochron (Varietal parameter) ! ** inputtype : parameter ! ** parametercategory : species ! ** datatype : DOUBLE ! ** default : 120.0 ! ** min : 0.0 ! ** max : 1000.0 ! ** unit : °C d leaf-1 ! ** uri : some url ! * name: pdecr ! ** description : Factor decreasing the phyllochron for leaf number less than Ldecr ! ** inputtype : parameter ! ** parametercategory : species ! ** datatype : DOUBLE ! ** default : 0.4 ! ** min : 0.0 ! ** max : 10.0 ! ** unit : - ! ** uri : some url ! * name: leafNumber_t1 ! ** description : Actual number of phytomers ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 25 ! ** default : 0 ! ** unit : leaf ! ** inputtype : variable ! * name: maxTvern ! ** description : Maximum temperature for vernalization to occur ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : -20 ! ** max : 60 ! ** default : 23.0 ! ** unit : °C ! ** inputtype : parameter ! * name: dayLength ! ** description : day length ! ** variablecategory : auxiliary ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** default : 12.3037621834005 ! ** unit : mm2 m-2 ! ** inputtype : variable ! * name: deltaTT ! ** description : Thermal time increase of the day ! ** inputtype : variable ! ** variablecategory : auxiliary ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 100.0 ! ** unit : °C d ! ** uri : ! * name: pastMaxAI_t1 ! ** description : Maximum Leaf Area Index reached the current day ! ** inputtype : variable ! ** variablecategory : state ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 5000.0 ! ** unit : m2 leaf m-2 ground ! ** uri : ! * name: tTWindowForPTQ ! ** description : Thermal Time window for average ! ** inputtype : parameter ! ** parametercategory : constant ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 5000.0 ! ** unit : °C d ! ** uri : ! * name: listGAITTWindowForPTQ_t1 ! ** description : List of daily Green Area Index in the window dedicated to average ! ** inputtype : variable ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** default : [0.0] ! ** min : ! ** max : ! ** unit : m2 leaf m-2 ground ! ** uri : ! * name: gAI ! ** description : Green Area Index of the day ! ** inputtype : variable ! ** variablecategory : auxiliary ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 500.0 ! ** unit : m2 leaf m-2 ground ! ** uri : ! * name: pAR ! ** description : Daily Photosyntetically Active Radiation ! ** variablecategory : auxiliary ! ** datatype : DOUBLE ! ** default : 0.0 ! ** min : 0.0 ! ** max : 10000.0 ! ** unit : MJ m² d ! ** uri : some url ! ** inputtype : variable ! * name: listPARTTWindowForPTQ_t1 ! ** description : List of Daily PAR during TTWindowForPTQ thermal time period ! ** variablecategory : state ! ** inputtype : variable ! ** datatype : DOUBLELIST ! ** min : ! ** max : ! ** default : [0.0] ! ** unit : MJ m2 d ! ** uri : some url ! * name: listTTShootWindowForPTQ1_t1 ! ** description : List of daily shoot thermal time in the window dedicated to average ! ** inputtype : variable ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** default : [0.0] ! ** min : ! ** max : ! ** unit : °C d ! ** uri : ! * name: listTTShootWindowForPTQ_t1 ! ** description : List of Daily Shoot thermal time during TTWindowForPTQ thermal time period ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** min : ! ** max : ! ** default : [0.0] ! ** unit : °C d ! ** uri : some url ! ** inputtype : variable ! * name: vBEE ! ** description : Vernalization rate at 0°C ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1 ! ** default : 0.01 ! ** unit : d-1 ! ** inputtype : parameter ! * name: calendarCumuls_t1 ! ** description : list containing for each stage occured its cumulated thermal times at previous day ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** default : [0.0] ! ** unit : °C d ! ** inputtype : variable ! * name: isVernalizable ! ** description : true if the plant is vernalizable ! ** parametercategory : species ! ** datatype : INT ! ** min : 0 ! ** max : 1 ! ** default : 1 ! ** unit : ! ** inputtype : parameter ! * name: vernaprog_t1 ! ** description : progression on a 0 to 1 scale of the vernalization ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1 ! ** default : 0.5517254187376879 ! ** unit : ! ** inputtype : variable ! * name: minTvern ! ** description : Minimum temperature for vernalization to occur ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : -20 ! ** max : 60 ! ** default : 0.0 ! ** unit : °C ! ** inputtype : parameter ! * name: intTvern ! ** description : Intermediate temperature for vernalization to occur ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : -20 ! ** max : 60 ! ** default : 11.0 ! ** unit : °C ! ** inputtype : parameter ! * name: vAI ! ** description : Response of vernalization rate to temperature ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1 ! ** default : 0.015 ! ** unit : d-1 °C-1 ! ** inputtype : parameter ! * name: maxDL ! ** description : Saturating photoperiod above which final leaf number is not influenced by daylength ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 24 ! ** default : 15.0 ! ** unit : h ! ** inputtype : parameter ! * name: choosePhyllUse ! ** description : Switch to choose the type of phyllochron calculation to be used ! ** inputtype : parameter ! ** parametercategory : species ! ** datatype : STRING ! ** default : Default ! ** min : ! ** max : ! ** unit : - ! ** uri : some url ! * name: minDL ! ** description : Threshold daylength below which it does influence vernalization rate ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 12 ! ** max : 24 ! ** default : 8.0 ! ** unit : h ! ** inputtype : parameter ! * name: hasLastPrimordiumAppeared_t1 ! ** description : if Last Primordium has Appeared ! ** variablecategory : state ! ** datatype : INT ! ** min : 0 ! ** max : 1 ! ** default : 0 ! ** unit : ! ** inputtype : variable ! * name: phase_t1 ! ** description : the name of the phase ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 7 ! ** default : 1 ! ** unit : ! ** inputtype : variable ! * name: pFLLAnth ! ** description : Phyllochronic duration of the period between flag leaf ligule appearance and anthesis ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1000 ! ** unit : ! ** default : 2.22 ! ** inputtype : parameter ! * name: dcd ! ** description : Duration of the endosperm cell division phase ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** default : 100 ! ** unit : °C d ! ** inputtype : parameter ! * name: dgf ! ** description : Grain filling duration (from anthesis to physiological maturity) ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** default : 450 ! ** unit : °C d ! ** inputtype : parameter ! * name: degfm ! ** description : Grain maturation duration (from physiological maturity to harvest ripeness) ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 50 ! ** default : 0 ! ** unit : °C d ! ** inputtype : parameter ! * name: ignoreGrainMaturation ! ** description : true to ignore grain maturation ! ** parametercategory : species ! ** datatype : BOOLEAN ! ** default : FALSE ! ** unit : ! ** inputtype : parameter ! * name: pHEADANTH ! ** description : Number of phyllochron between heading and anthesiss ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1000 ! ** default : 1 ! ** unit : ! ** inputtype : parameter ! * name: finalLeafNumber_t1 ! ** description : final leaf number ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 25 ! ** default : 0 ! ** unit : leaf ! ** inputtype : variable ! * name: sLDL ! ** description : Daylength response of leaf production ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1 ! ** default : 0.85 ! ** unit : leaf h-1 ! ** inputtype : parameter ! * name: grainCumulTT ! ** description : cumulTT used for the grain developpment ! ** variablecategory : auxiliary ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** default : 0 ! ** unit : °C d ! ** inputtype : variable ! * name: sowingDay ! ** description : Day of Year at sowing ! ** parametercategory : species ! ** datatype : INT ! ** min : 1 ! ** max : 365 ! ** default : 1 ! ** unit : d ! ** uri : some url ! ** inputtype : parameter ! * name: hasZadokStageChanged_t1 ! ** description : true if the zadok stage has changed this time step ! ** variablecategory : state ! ** datatype : INT ! ** min : 0 ! ** max : 1 ! ** default : 0 ! ** unit : ! ** uri : some url ! ** inputtype : variable ! * name: currentZadokStage ! ** description : current zadok stage ! ** variablecategory : state ! ** datatype : STRING ! ** min : ! ** max : ! ** default : MainShootPlus1Tiller ! ** unit : ! ** uri : some url ! ** inputtype : variable ! * name: sowingDate ! ** description : Date of Sowing ! ** parametercategory : constant ! ** datatype : DATE ! ** min : ! ** max : ! ** default : 2007/3/21 ! ** unit : ! ** inputtype : parameter ! * name: sDws ! ** description : Sowing date at which Phyllochrone is minimum ! ** parametercategory : species ! ** datatype : INT ! ** default : 1 ! ** min : 1 ! ** max : 365 ! ** unit : d ! ** uri : some url ! ** inputtype : parameter ! * name: sDsa_nh ! ** description : Sowing date at which Phyllochrone is maximum in northern hemispher ! ** parametercategory : species ! ** datatype : DOUBLE ! ** default : 1.0 ! ** min : 1 ! ** max : 365 ! ** unit : d ! ** uri : some url ! ** inputtype : parameter ! * name: hasFlagLeafLiguleAppeared ! ** description : true if flag leaf has appeared (leafnumber reached finalLeafNumber) ! ** variablecategory : state ! ** datatype : INT ! ** min : 0 ! ** max : 1 ! ** default : 0 ! ** unit : ! ** inputtype : variable ! * name: der ! ** description : Duration of the endosperm endoreduplication phase ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** default : 300.0 ! ** unit : °C d ! ** uri : some url ! ** inputtype : parameter ! * name: hasFlagLeafLiguleAppeared_t1 ! ** description : true if flag leaf has appeared (leafnumber reached finalLeafNumber) ! ** variablecategory : state ! ** datatype : INT ! ** min : 0 ! ** max : 1 ! ** default : 1 ! ** unit : ! ** uri : some url ! ** inputtype : variable ! * name: tilleringProfile_t1 ! ** description : store the amount of new tiller created at each time a new tiller appears ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** default : [288.0] ! ** unit : ! ** inputtype : variable ! * name: targetFertileShoot ! ** description : max value of shoot number for the canopy ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 280 ! ** max : 1000 ! ** default : 600.0 ! ** unit : shoot ! ** inputtype : variable ! * name: leafTillerNumberArray_t1 ! ** description : store the number of tiller for each leaf layer ! ** variablecategory : state ! ** datatype : INTLIST ! ** unit : leaf ! ** default : [1, 1, 1] ! ** inputtype : variable ! * name: dse ! ** description : Thermal time from sowing to emergence ! ** parametercategory : genotypic ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1000 ! ** default : 105 ! ** unit : °C d ! ** inputtype : parameter ! * name: slopeTSFLN ! ** description : used to calculate Terminal spikelet ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** default : 0.9 ! ** unit : ! ** uri : some url ! ** inputtype : parameter ! * name: intTSFLN ! ** description : used to calculate Terminal spikelet ! ** parametercategory : species ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** default : 0.9 ! ** unit : ! ** uri : some url ! ** inputtype : parameter ! * name: canopyShootNumber_t1 ! ** description : shoot number for the whole canopy ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** default : 288.0 ! ** unit : shoot m-2 ! ** inputtype : variable !- outputs: ! * name: currentZadokStage ! ** description : current zadok stage ! ** variablecategory : state ! ** datatype : STRING ! ** unit : ! ** uri : some url ! * name: hasZadokStageChanged ! ** description : true if the zadok stage has changed this time step ! ** variablecategory : state ! ** datatype : INT ! ** min : 0 ! ** max : 1 ! ** unit : ! ** uri : some url ! * name: hasFlagLeafLiguleAppeared ! ** description : true if flag leaf has appeared (leafnumber reached finalLeafNumber) ! ** variablecategory : state ! ** datatype : INT ! ** min : 0 ! ** max : 1 ! ** unit : ! ** uri : some url ! * name: listPARTTWindowForPTQ ! ** description : List of Daily PAR during TTWindowForPTQ thermal time period ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** min : ! ** max : ! ** unit : MJ m2 d ! * name: hasLastPrimordiumAppeared ! ** description : if Last Primordium has Appeared ! ** variablecategory : state ! ** datatype : INT ! ** min : 0 ! ** max : 1 ! ** unit : ! * name: listTTShootWindowForPTQ ! ** description : List of Daily Shoot thermal time during TTWindowForPTQ thermal time period ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** min : ! ** max : ! ** unit : °C d ! * name: listTTShootWindowForPTQ1 ! ** description : List of daily shoot thermal time in the window dedicated to average ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** min : ! ** max : ! ** unit : °C d ! ** uri : ! * name: ptq ! ** description : Photothermal Quotient ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** unit : MJ °C-1 d m-2) ! * name: calendarMoments ! ** description : List containing apparition of each stage ! ** variablecategory : state ! ** datatype : STRINGLIST ! ** unit : ! * name: canopyShootNumber ! ** description : shoot number for the whole canopy ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** unit : shoot m-2 ! * name: calendarDates ! ** description : List containing the dates of the wheat developmental phases ! ** variablecategory : state ! ** datatype : DATELIST ! ** unit : ! * name: leafTillerNumberArray ! ** description : store the number of tiller for each leaf layer ! ** variablecategory : state ! ** datatype : INTLIST ! ** unit : leaf ! * name: vernaprog ! ** description : progression on a 0 to 1 scale of the vernalization ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** unit : ! * name: phyllochron ! ** description : the rate of leaf appearance ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 1000 ! ** unit : °C d leaf-1 ! ** uri : some url ! * name: leafNumber ! ** description : Actual number of phytomers ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** unit : leaf ! ** uri : some url ! * name: numberTillerCohort ! ** description : Number of tiller which appears ! ** variablecategory : state ! ** datatype : INT ! ** min : 0 ! ** max : 10000 ! ** unit : dimensionless ! * name: tilleringProfile ! ** description : store the amount of new tiller created at each time a new tiller appears ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** unit : dimensionless ! * name: averageShootNumberPerPlant ! ** description : average shoot number per plant in the canopy ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** unit : shoot m-2 ! * name: minFinalNumber ! ** description : minimum final leaf number ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 10000 ! ** unit : leaf ! * name: finalLeafNumber ! ** description : final leaf number ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 25 ! ** unit : leaf ! * name: phase ! ** description : the name of the phase ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0 ! ** max : 7 ! ** unit : ! * name: listGAITTWindowForPTQ ! ** description : List of daily Green Area Index in the window dedicated to average ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** min : ! ** max : ! ** unit : m2 leaf m-2 ground ! ** uri : ! * name: calendarCumuls ! ** description : list containing for each stage occured its cumulated thermal times ! ** variablecategory : state ! ** datatype : DOUBLELIST ! ** unit : °C d ! * name: gAImean ! ** description : Mean Green Area Index ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0.0 ! ** max : 500.0 ! ** unit : m2 leaf m-2 ground ! ** uri : ! * name: pastMaxAI ! ** description : Maximum Leaf Area Index reached the current day ! ** variablecategory : state ! ** datatype : DOUBLE ! ** min : 0.0 ! ** max : 5000.0 ! ** unit : m2 leaf m-2 ground ! ** uri : call model_phylsowingdatecorrection(sowingDay, latitude, sDsa_sh, rp, & sDws, sDsa_nh, p,fixPhyll) call model_vernalizationprogress(dayLength, deltaTT, cumulTT, & leafNumber_t1, calendarMoments_t1, calendarDates_t1, & calendarCumuls_t1, minTvern, intTvern, vAI, vBEE, minDL, maxDL, & maxTvern, pNini, aMXLFNO, vernaprog_t1, currentdate, isVernalizable, & minFinalNumber_t1,vernaprog,minFinalNumber,calendarMoments,calendarDates,calendarCumuls) call & model_ismomentregistredzc_39(calendarMoments_t1,isMomentRegistredZC_39) call model_cumulttfrom(calendarMoments_t1, calendarCumuls_t1, & cumulTT,cumulTTFromZC_65,cumulTTFromZC_39,cumulTTFromZC_91) call model_gaimean(gAI, tTWindowForPTQ, deltaTT, pastMaxAI_t1, & listTTShootWindowForPTQ1_t1, & listGAITTWindowForPTQ_t1,gAImean,pastMaxAI,listTTShootWindowForPTQ1,listGAITTWindowForPTQ) call model_updatephase(cumulTT, leafNumber_t1, cumulTTFromZC_39, & isMomentRegistredZC_39, gAI, grainCumulTT, dayLength, vernaprog, & minFinalNumber, fixPhyll, isVernalizable, dse, pFLLAnth, dcd, dgf, & degfm, maxDL, sLDL, ignoreGrainMaturation, pHEADANTH, choosePhyllUse, & p, phase_t1, cumulTTFromZC_91, phyllochron, & hasLastPrimordiumAppeared_t1, & finalLeafNumber_t1,finalLeafNumber,phase,hasLastPrimordiumAppeared) call model_ptq(tTWindowForPTQ, kl, listTTShootWindowForPTQ_t1, & listPARTTWindowForPTQ_t1, listGAITTWindowForPTQ, pAR, & deltaTT,listPARTTWindowForPTQ,listTTShootWindowForPTQ,ptq) call model_leafnumber(deltaTT, phyllochron_t1, & hasFlagLeafLiguleAppeared, leafNumber_t1, phase,leafNumber) call model_phyllochron(fixPhyll, leafNumber, lincr, ldecr, pdecr, & pincr, ptq, gAImean, kl, pTQhf, B, p, choosePhyllUse, areaSL, areaSS, & lARmin, lARmax, sowingDensity, lNeff,phyllochron) call model_updateleafflag(cumulTT, leafNumber, calendarMoments, & calendarDates, calendarCumuls, currentdate, finalLeafNumber, & hasFlagLeafLiguleAppeared_t1, phase,hasFlagLeafLiguleAppeared) call model_shootnumber(canopyShootNumber_t1, leafNumber, & sowingDensity, targetFertileShoot, tilleringProfile_t1, & leafTillerNumberArray_t1, & numberTillerCohort_t1,averageShootNumberPerPlant,canopyShootNumber,leafTillerNumberArray,tilleringProfile,numberTillerCohort) call model_registerzadok(cumulTT, phase, leafNumber, calendarMoments, & calendarDates, calendarCumuls, cumulTTFromZC_65, currentdate, der, & slopeTSFLN, intTSFLN, finalLeafNumber, currentZadokStage, & hasZadokStageChanged_t1, sowingDate,hasZadokStageChanged) call model_updatecalendar(cumulTT, calendarMoments, calendarDates, & calendarCumuls, currentdate, phase) END SUBROUTINE model_phenology SUBROUTINE init_phenology(aMXLFNO, & currentdate, & cumulTT, & pNini, & sDsa_sh, & latitude, & kl, & lincr, & ldecr, & pincr, & pTQhf, & B, & areaSL, & areaSS, & lARmin, & sowingDensity, & lARmax, & lNeff, & rp, & p, & pdecr, & maxTvern, & dayLength, & deltaTT, & tTWindowForPTQ, & gAI, & pAR, & vBEE, & isVernalizable, & minTvern, & intTvern, & vAI, & maxDL, & choosePhyllUse, & minDL, & pFLLAnth, & dcd, & dgf, & degfm, & ignoreGrainMaturation, & pHEADANTH, & sLDL, & grainCumulTT, & sowingDay, & sowingDate, & sDws, & sDsa_nh, & der, & targetFertileShoot, & dse, & slopeTSFLN, & intTSFLN, & currentZadokStage, & hasZadokStageChanged, & hasFlagLeafLiguleAppeared, & listPARTTWindowForPTQ, & hasLastPrimordiumAppeared, & listTTShootWindowForPTQ, & listTTShootWindowForPTQ1, & ptq, & calendarMoments, & canopyShootNumber, & calendarDates, & leafTillerNumberArray, & vernaprog, & phyllochron, & leafNumber, & numberTillerCohort, & tilleringProfile, & averageShootNumberPerPlant, & minFinalNumber, & finalLeafNumber, & phase, & listGAITTWindowForPTQ, & calendarCumuls, & gAImean, & pastMaxAI) IMPLICIT NONE REAL, INTENT(IN) :: aMXLFNO CHARACTER(65), INTENT(IN) :: currentdate REAL, INTENT(IN) :: cumulTT REAL, INTENT(IN) :: pNini REAL, INTENT(IN) :: sDsa_sh REAL, INTENT(IN) :: latitude REAL, INTENT(IN) :: kl REAL, INTENT(IN) :: lincr REAL, INTENT(IN) :: ldecr REAL, INTENT(IN) :: pincr REAL, INTENT(IN) :: pTQhf REAL, INTENT(IN) :: B REAL, INTENT(IN) :: areaSL REAL, INTENT(IN) :: areaSS REAL, INTENT(IN) :: lARmin REAL, INTENT(IN) :: sowingDensity REAL, INTENT(IN) :: lARmax REAL, INTENT(IN) :: lNeff REAL, INTENT(IN) :: rp REAL, INTENT(IN) :: p REAL, INTENT(IN) :: pdecr REAL, INTENT(IN) :: maxTvern REAL, INTENT(IN) :: dayLength REAL, INTENT(IN) :: deltaTT REAL, INTENT(IN) :: tTWindowForPTQ REAL, INTENT(IN) :: gAI REAL, INTENT(IN) :: pAR REAL, INTENT(IN) :: vBEE INTEGER, INTENT(IN) :: isVernalizable REAL, INTENT(IN) :: minTvern REAL, INTENT(IN) :: intTvern REAL, INTENT(IN) :: vAI REAL, INTENT(IN) :: maxDL CHARACTER(65), INTENT(IN) :: choosePhyllUse REAL, INTENT(IN) :: minDL REAL, INTENT(IN) :: pFLLAnth REAL, INTENT(IN) :: dcd REAL, INTENT(IN) :: dgf REAL, INTENT(IN) :: degfm LOGICAL, INTENT(IN) :: ignoreGrainMaturation REAL, INTENT(IN) :: pHEADANTH REAL, INTENT(IN) :: sLDL REAL, INTENT(IN) :: grainCumulTT INTEGER, INTENT(IN) :: sowingDay CHARACTER(65), INTENT(IN) :: sowingDate INTEGER, INTENT(IN) :: sDws REAL, INTENT(IN) :: sDsa_nh REAL, INTENT(IN) :: der REAL, INTENT(IN) :: targetFertileShoot REAL, INTENT(IN) :: dse REAL, INTENT(IN) :: slopeTSFLN REAL, INTENT(IN) :: intTSFLN CHARACTER(65), INTENT(OUT) :: currentZadokStage INTEGER, INTENT(OUT) :: hasZadokStageChanged INTEGER, INTENT(OUT) :: hasFlagLeafLiguleAppeared REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: listPARTTWindowForPTQ INTEGER, INTENT(OUT) :: hasLastPrimordiumAppeared REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & listTTShootWindowForPTQ REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & listTTShootWindowForPTQ1 REAL, INTENT(OUT) :: ptq CHARACTER(65), ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & calendarMoments REAL, INTENT(OUT) :: canopyShootNumber CHARACTER(65), ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & calendarDates INTEGER, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: & leafTillerNumberArray REAL, INTENT(OUT) :: vernaprog REAL, INTENT(OUT) :: phyllochron REAL, INTENT(OUT) :: leafNumber INTEGER, INTENT(OUT) :: numberTillerCohort REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: tilleringProfile REAL, INTENT(OUT) :: averageShootNumberPerPlant REAL, INTENT(OUT) :: minFinalNumber REAL, INTENT(OUT) :: finalLeafNumber REAL, INTENT(OUT) :: phase REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: listGAITTWindowForPTQ REAL, ALLOCATABLE , DIMENSION(:), INTENT(OUT) :: calendarCumuls REAL, INTENT(OUT) :: gAImean REAL, INTENT(OUT) :: pastMaxAI currentZadokStage = "" hasZadokStageChanged = 0 hasFlagLeafLiguleAppeared = 0 hasLastPrimordiumAppeared = 0 ptq = 0.0 canopyShootNumber = 0.0 vernaprog = 0.0 phyllochron = 0.0 leafNumber = 0.0 numberTillerCohort = 0 averageShootNumberPerPlant = 0.0 minFinalNumber = 0.0 finalLeafNumber = 0.0 phase = 0.0 gAImean = 0.0 pastMaxAI = 0.0 call Add(calendarMoments, 'Sowing') call Add(calendarCumuls, 0.0) call Add(calendarDates, sowingDate) minFinalNumber = 5.5 END SUBROUTINE init_phenology END MODULE
16,495
https://github.com/ikrutik/finance_bot/blob/master/src/rest/applications/aiogram/endpoints/callbacks.py
Github Open Source
Open Source
MIT
null
finance_bot
ikrutik
Python
Code
125
639
""" Callback handlers """ from aiogram import types from src.domains.types import PurchaseStates from src.interfaces.finance_interface import FinanceBotInterface from src.libs import keyboard from src.rest.applications.aiogram.bootstrap import get_dispatcher dispatcher = get_dispatcher() @dispatcher.callback_query_handler(lambda c: c.data and c.data == 'add') async def process_callback_add(callback_query: types.CallbackQuery): await dispatcher.bot.answer_callback_query( callback_query_id=callback_query.id ) await PurchaseStates.category.set() await dispatcher.bot.send_message( chat_id=callback_query.message.chat.id, text="🎲Выберите категорию", reply_markup=keyboard.keyboard_categories ) @dispatcher.callback_query_handler(lambda c: c.data and c.data == 'balance') async def process_callback_today_balance(callback_query: types.CallbackQuery): await dispatcher.bot.answer_callback_query( callback_query_id=callback_query.id ) await FinanceBotInterface().get_today_balance( message=callback_query.message ) @dispatcher.callback_query_handler(lambda c: c.data and c.data == 'purchases') async def process_callback_today_purchases(callback_query: types.CallbackQuery): await dispatcher.bot.answer_callback_query( callback_query_id=callback_query.id ) await FinanceBotInterface().get_today_purchases( message=callback_query.message ) @dispatcher.message_handler(lambda c: c.data and c.data == 'reset') async def process_callback_reset_state(callback_query: types.CallbackQuery): await dispatcher.bot.answer_callback_query( callback_query_id=callback_query.id ) current_state = dispatcher.current_state( user=callback_query.message.from_user.id ) if current_state is not None: await current_state.reset_data() await current_state.finish() await dispatcher.bot.send_message( chat_id=callback_query.message.from_user.id, text='Успешный сброс', reply_markup=keyboard.keyboard_menu )
7,469
https://github.com/carlosdevletian/matex/blob/master/resources/assets/js/components/orders/Show.vue
Github Open Source
Open Source
MIT
2,019
matex
carlosdevletian
Vue
Code
144
668
<template> <order-template> <p slot="items-title">Ordered items</p> <div slot="table-header" class="borderless"> <table class="table borderless mg-0"> <tbody> <tr> <td class="col-xs-7"> <p class="text-center mg-0">Items</p> </td> <td class="col-xs-3"> <p class="text-center mg-0 visible-xs-block">Qty</p> <p class="text-center mg-0 hidden-xs">Quantity</p> </td> <td class="col-xs-2"> <p class="text-center mg-0">Price</p> </td> </tr> </tbody> </table> </div> <div slot="items"> <div v-for="item in items"> <item-show :item="item"></item-show> </div> </div> <div slot="subtotal">$ {{ order.subtotal | inDollars }}</div> <div slot="shipping">Free</div> <div slot="tax">$ {{ order.tax | inDollars }}</div> <div slot="total">$ {{ order.total | inDollars }}</div> <p slot="address-title">Shipping address</p> <div slot="address-picker"> <div class="col-xs-12"><p>Name: {{ address.name }}</p></div> <div class="col-xs-12"><p>Street: {{ address.street }}</p></div> <div class="col-xs-12"><p>City: {{ address.city }}</p></div> <div class="col-xs-12"><p>State: {{ address.state }}</p></div> <div class="col-xs-12"><p>Zip: {{ address.zip }}</p></div> <div class="col-xs-12"><p>Phone Number: {{ address.phone_number }}</p></div> <div v-show="address.comment" class="col-xs-12">User comment: {{ address.comment }}</div> </div> <div v-if="admin" slot="edit-address-mg" class="mg-btm-30"> <a slot="edit-address" class="Button--card stick-to-bottom" :href="'/addresses/' + address.id ">Edit</a> </div> </order-template> </template> <script> export default { props: ['order', 'items', 'address', 'admin'], } </script>
4,526
https://github.com/r5r3/fpluslib/blob/master/src/scidata/fplus_cdi_async_writer.cpp
Github Open Source
Open Source
BSD-3-Clause
2,019
fpluslib
r5r3
C++
Code
481
1,350
#include "fplus_cdi_async_writer.h" // all writer objects are stored in a map. The fortran routines get only the index returned map<int,cdi_async_writer*> writers; // in case of multiple writers, only one is allowed to execute CDI commands. Is CDI thread save? mutex cdimtx; // constructor for the writer cdi_async_writer::cdi_async_writer() { this->mtx = new mutex(); this->size = 0; this->write_all_and_exit = false; this->write_thread = new thread(&cdi_async_writer::write_loop, this); } // destructor for the writer cdi_async_writer::~cdi_async_writer() { // write out all data to disk this->write_all_and_exit = true; this->write_thread->join(); // clean up delete this->mtx; delete this->write_thread; } // place a new operation in the queue void cdi_async_writer::add_operation(async_operation *op) { // lock for other operations this->mtx->lock(); // check the operation type switch (op->oper_type) { // write data for one time step case OTYPE_streamWriteVar: this->size += op->nvalues*sizeof(double); break; // define a new time step case OTYPE_streamDefTimestep: break; // unsupported operation! default: cerr << "ERROR: unsupported operation in asynchronous writer: " << op->oper_type << endl; exit(-1); } // add to queue and unlock this->queue.push_back(op); this->mtx->unlock(); } // endless loop which is used to write data to disk void cdi_async_writer::write_loop() { int status; while (true) { // wait for new data if (!this->write_all_and_exit || this->size == 0) usleep(100000); // get a new operation from the writer, first step: lock it this->mtx->lock(); // no elements, cycle! if (this->queue.size() == 0) { this->mtx->unlock(); // leave the loop if this is the final write process if (this->write_all_and_exit) { break; } else { continue; } } async_operation* op = this->queue.front(); this->queue.pop_front(); this->mtx->unlock(); // perform the operation cdimtx.lock(); switch (op->oper_type) { // write data for one time step case OTYPE_streamWriteVar: streamWriteVar(op->streamID, op->varID, op->values, op->nmiss); //reduce size this->size -= op->nvalues*sizeof(double); //cout << this->size << endl; break; // define a new time step case OTYPE_streamDefTimestep: taxisDefVdate(op->taxisID, op->idate); taxisDefVtime(op->taxisID, op->itime); status = streamDefTimestep(op->streamID, op->ind); break; } // throw away the old operation delete op; cdimtx.unlock(); } } // cleanup all data of a operation async_operation::~async_operation() { if (this->values != nullptr) { delete[] values; } } // create the writer object int init_writer() { int index = writers.size()+1; cdi_async_writer* writer = new cdi_async_writer(); writers[index] = writer; return index; } // write all data to disk and free the memory void destroy_writer(int index) { cdi_async_writer* writer = writers[index]; delete writer; writers.erase(index); } void streamWriteVar_async(int writer, int streamID, int varID, double* values, int nmiss, int nvalues) { // copy all information about this operation async_operation* op = new async_operation(); op->oper_type = OTYPE_streamWriteVar; op->streamID = streamID; op->varID = varID; op->values = new double[nvalues]; memcpy(op->values, values, nvalues*sizeof(double)); op->nvalues = nvalues; op->nmiss = nmiss; // put this operation into the queue writers[writer]->add_operation(op); } void streamDefTimestep_async(int writer, int taxisID, int idate, int itime, int streamID, int ind) { // copy all information about this operation async_operation* op = new async_operation(); op->oper_type = OTYPE_streamDefTimestep; op->taxisID = taxisID; op->idate = idate; op->itime = itime; op->streamID = streamID; op->ind = ind; // put this operation into the queue writers[writer]->add_operation(op); }
10,981
https://github.com/abhinav-v058/BillingApp/blob/master/BillingApp/BillingApp/BillingApp.Program/CodingTestTax.cs
Github Open Source
Open Source
MIT
null
BillingApp
abhinav-v058
C#
Code
33
103
using System; using System.Collections.Generic; using System.Text; namespace BillingApp.BillingApp.Program { public class CodingTestTax:ITax { float ITax.Percentage { get; set; } string ITax.Name { get; set; } HashSet<ItemTypeEnum> ITax.ExemptedItemTypes { get; set; } } }
210
https://github.com/Artoria-Huang/home1Module/blob/master/Example/Pods/Target Support Files/home1Module/home1Module-dummy.m
Github Open Source
Open Source
MIT
2,018
home1Module
Artoria-Huang
Objective-C
Code
10
44
#import <Foundation/Foundation.h> @interface PodsDummy_home1Module : NSObject @end @implementation PodsDummy_home1Module @end
7,105
https://github.com/JamiuJimoh/react-portfolio/blob/master/src/components/screen/About/About.js
Github Open Source
Open Source
2,020
react-portfolio
JamiuJimoh
JavaScript
Code
182
558
import React from 'react'; import './About.css'; const About = (props) => { return ( <div id="about" data-aos={props.data} className="about__me"> <div className="about"> <h1>LET ME INTRODUCE MYSELF</h1> <p> They say do what you love and you will enjoy every second of work. Learning new things and solving arising problems with the computer made me fall in love with web development. </p> <br /> <p> I am a computer science student in my finals. I am a frontend/backend developer, a footballer and an artist. My ability to adapt to different situations and my tendency to work better with a team is a skill I'm proud of. My primary stack is the MERN stack but i could work with other tools if need be. </p> </div> <div className="technologies"> <p>I have recently been working with different technologies like :</p> <div className="tech__logos"> <img src="https://img.icons8.com/color/48/000000/html-5.png" alt="html5 logo" /> <img src="https://img.icons8.com/color/48/000000/css3.png" alt="css3 logo" /> <img src="https://img.icons8.com/color/48/000000/javascript-logo-1.png" alt="javascript logo" /> <img src="https://img.icons8.com/color/48/000000/mongodb.png" alt="mongo db logo" /> <img src="https://img.icons8.com/color/48/000000/react-native.png" alt="react js logo" /> <img src="https://img.icons8.com/color/48/000000/nodejs.png" alt="node js logo" /> <img src="https://www.vectorlogo.zone/logos/expressjs/expressjs-ar21.svg" alt="express js logo" /> </div> </div> </div> ); }; export default About;
20,418
https://github.com/mblarsen/laravel-dynamic-factories/blob/master/tests/ExampleTest.php
Github Open Source
Open Source
MIT
null
laravel-dynamic-factories
mblarsen
PHP
Code
29
128
<?php namespace Mblarsen\LaravelDynamicFactories\Tests; use Orchestra\Testbench\TestCase; use Mblarsen\LaravelDynamicFactories\LaravelDynamicFactoriesServiceProvider; class ExampleTest extends TestCase { protected function getPackageProviders($app) { return [LaravelDynamicFactoriesServiceProvider::class]; } /** @test */ public function true_is_true() { $this->assertTrue(true); } }
11,916
https://github.com/misaka9981/SimpleBlog/blob/master/src/main/java/com/cxy/blog/mapper/CommentMapper.java
Github Open Source
Open Source
MIT
null
SimpleBlog
misaka9981
Java
Code
13
66
package com.cxy.blog.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.cxy.blog.model.Comment; public interface CommentMapper extends BaseMapper<Comment> { }
37,078
https://github.com/hogsy/xtread/blob/master/src/Tread/TextureBar.cpp
Github Open Source
Open Source
MIT
2,019
xtread
hogsy
C++
Code
184
621
// TextureBar.cpp : implementation file // #include "stdafx.h" #include "tread3d.h" #include "TextureBar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTextureBar dialog CTextureBar::CTextureBar(CWnd* pParent /*=NULL*/) { //{{AFX_DATA_INIT(CTextureBar) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CTextureBar::DoDataExchange(CDataExchange* pDX) { CDialogBar::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTextureBar) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CTextureBar, CDialogBar) //{{AFX_MSG_MAP(CTextureBar) ON_WM_CTLCOLOR() ON_WM_DESTROY() ON_WM_SETCURSOR() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTextureBar message handlers HBRUSH CTextureBar::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialogBar::OnCtlColor(pDC, pWnd, nCtlColor); // TODO: Change any attributes of the DC here // TODO: Return a different brush if the default is not desired return hbr; } void CTextureBar::OnDestroy() { CDialogBar::OnDestroy(); // TODO: Add your message handler code here } BOOL CTextureBar::OnInitDialog() { //CCJDockBar::OnInitDialog(); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } BOOL CTextureBar::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // TODO: Add your message handler code here and/or call default return CDialogBar::OnSetCursor(pWnd, nHitTest, message); }
19,681
https://github.com/De7vID/flingon-assister/blob/master/lib/klingontext.dart
Github Open Source
Open Source
Apache-2.0
null
flingon-assister
De7vID
Dart
Code
397
1,022
import 'package:flutter/material.dart'; import 'package:flutter/gestures.dart'; class KlingonText extends RichText { final TextStyle style; // Constructs a new KlingonText widget // // fromString: The source string, possibly containing {tlhIngan Hol mu'mey} // onTap: A callback to be run when links are tapped // style: The default style to apply to non-braced text KlingonText({String fromString, Function(String) onTap, this.style}) : super( text: _ProcessKlingonText(fromString, onTap, style), ); static MaterialColor _colorForPOS(String type, String flags) { // Use the default color for sentences, URLs, sources, and mailto links if (type == 'sen' || type == 'url' ||type == 'src' || type == 'mailto') { return null; } List<String> splitFlags = flags == null ? [] : flags.split(','); if (splitFlags.contains('suff') || splitFlags.contains('pre')) { return Colors.red; } if (type == 'v') { return Colors.yellow; } if (type == 'n') { return Colors.green; } return Colors.blue; } // Build a TextSpan containing 'src', with text {in curly braces} formatted // appropriately. static TextSpan _ProcessKlingonText(String src, Function(String) onTap, TextStyle style) { List<TextSpan> ret = []; String remainder = src; while (remainder.contains('{')) { // TODO handle URLs and other special text spans if (remainder.startsWith('{') && remainder.contains('}')) { int endIndex = remainder.indexOf('}'); String klingon = remainder.substring(1, endIndex); List<String> klingonSplit = klingon.split(':'); String textOnly = klingonSplit[0]; String textType = klingonSplit.length > 1 ? klingonSplit[1] : null; String textFlags = klingonSplit.length > 2 ? klingonSplit[2] : null; // Klingon words (i.e., anything that's not a URL or source citation) // should be in a serif font, to distinguish 'I' and 'l'. bool serif = textType != null && textType != 'url' && textType != 'src'; // Anything that's not a source citation or explicitly not a link should // be treated as a link. bool link = (textType != null && textType != 'src') && (textFlags == null || !textFlags.split(',').contains('nolink')); // Source citations are italicized bool italic = textType != null && textType == 'src'; TapGestureRecognizer recognizer = new TapGestureRecognizer();; remainder = remainder.substring(endIndex + 1); if (link && onTap != null) { recognizer.onTap = () {onTap(klingon);}; } ret.add(new TextSpan( text: textOnly, style: new TextStyle( fontFamily: serif ? 'RobotoSlab' : style.fontFamily, decoration: link ? TextDecoration.underline : null, fontStyle: italic ? FontStyle.italic : null, color: _colorForPOS(textType, textFlags), // TODO part of speech tagging ), recognizer: recognizer, )); } else { int endIndex = remainder.indexOf('{'); ret.add(new TextSpan(text: remainder.substring(0, endIndex))); remainder = remainder.substring(endIndex); } } ret.add(new TextSpan(text: remainder)); return new TextSpan(children: ret, style: style); } }
15,241
https://github.com/ericmutta/samples/blob/master/snippets/visualbasic/VS_Snippets_Remoting/Dns_Begin_EndResolve/VB/dns_begin_endresolve.vb
Github Open Source
Open Source
CC-BY-4.0, MIT
2,019
samples
ericmutta
Visual Basic
Code
282
738
 ' ' This program demonstrates 'BeginResolve' and 'EndResolve' methods of Dns class. ' It obtains the 'IPHostEntry' object by calling 'BeginResolve' and 'EndResolve' method ' of 'Dns' class by passing a URL, a callback function and an instance of 'RequestState' ' class.Then prints host name, IP address list and aliases. ' Imports System Imports System.Net Imports Microsoft.VisualBasic ' <Snippet1> ' <Snippet2> Class DnsBeginGetHostByName Class RequestState Public host As IPHostEntry Public Sub New() host = Nothing End Sub 'New End Class 'RequestState Public Shared Sub Main() Try ' Create an instance of the RequestState class. Dim myRequestState As New RequestState() ' Begin an asynchronous request for information such as the host name, IP addresses, ' or aliases for the specified URI. Dim asyncResult As IAsyncResult = CType(Dns.BeginResolve("www.contoso.com", AddressOf RespCallback, myRequestState),IAsyncResult) ' Wait until asynchronous call completes. While asyncResult.IsCompleted <> True End While Console.WriteLine(("Host name : " + myRequestState.host.HostName)) Console.WriteLine(ControlChars.Cr + "IP address list : ") Dim index As Integer For index = 0 To myRequestState.host.AddressList.Length - 1 Console.WriteLine(myRequestState.host.AddressList(index)) Next index Console.WriteLine(ControlChars.Cr + "Aliases : ") For index = 0 To myRequestState.host.Aliases.Length - 1 Console.WriteLine(myRequestState.host.Aliases(index)) Next index catch e as Exception Console.WriteLine("Exception caught!!!") Console.WriteLine(("Source : " + e.Source)) Console.WriteLine(("Message : " + e.Message)) End Try End Sub 'Main Private Shared Sub RespCallback(ar As IAsyncResult) Try ' Convert the IAsyncResult object to a RequestState object. Dim tempRequestState As RequestState = CType(ar.AsyncState, RequestState) ' End the asynchronous request. tempRequestState.host = Dns.EndResolve(ar) Catch e As ArgumentNullException Console.WriteLine("ArgumentNullException caught!!!") Console.WriteLine(("Source : " + e.Source)) Console.WriteLine(("Message : " + e.Message)) Catch e As Exception Console.WriteLine("Exception caught!!!") Console.WriteLine(("Source : " + e.Source)) Console.WriteLine(("Message : " + e.Message)) End Try End Sub 'RespCallback ' </Snippet2> ' </Snippet1> End Class 'DnsBeginGetHostByName
45,421
https://github.com/gries/OktolabMediaBundle/blob/master/Command/DeleteEpisodeCommand.php
Github Open Source
Open Source
MIT
null
OktolabMediaBundle
gries
PHP
Code
97
414
<?php namespace Oktolab\MediaBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class DeleteEpisodeCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('oktolab:media:delete_episode') ->setDescription('Removes an episode, its media, posterframe and video') ->addArgument('uniqID', InputArgument::REQUIRED, 'the uniqID of your episode') ->addOption('force', false, InputOption::VALUE_NONE, 'execute this command'); } protected function execute(InputInterface $input, OutputInterface $output) { $episode = $this ->getContainer() ->get('oktolab_media') ->getEpisode($input->getArgument('uniqID')); if ($episode) { if ($input->getOption('force')) { $this ->getContainer() ->get('oktolab_media_helper') ->deleteEpisode($episode); } else { $output->writeln('To truly delete this episode, use --force!'); } } else { $output->writeln( sprintf( 'No Episode with uniqID [%s] found', $input->getArgument('uniqID') ) ); } } }
16,102
https://github.com/fanjieqi/LeetCodeRuby/blob/master/1201-1300/1275. Find Winner on a Tic Tac Toe Game.rb
Github Open Source
Open Source
MIT
2,020
LeetCodeRuby
fanjieqi
Ruby
Code
104
294
# @param {Integer[][]} moves # @return {String} def tictactoe(moves) row, col, diag1, diag2 = {}, {}, {}, {} moves.each_with_index do |(x, y), i| row[x] = row[x].to_i + (i.even? ? 1 : -1) col[y] = col[y].to_i + (i.even? ? 1 : -1) diag1[x+y] = diag1[x+y].to_i + (i.even? ? 1 : -1) diag2[x-y] = diag2[x-y].to_i + (i.even? ? 1 : -1) return 'A' if row[x] == 3 || col[y] == 3 || diag1[x+y] == 3 || diag2[x-y] == 3 return 'B' if row[x] == -3 || col[y] == -3 || diag1[x+y] == -3 || diag2[x-y] == -3 end moves.size == 9 ? 'Draw' : 'Pending' end
6,149
https://github.com/JMMackenzie/Variable-BMW/blob/master/bm25.hpp
Github Open Source
Open Source
Apache-2.0
2,021
Variable-BMW
JMMackenzie
C++
Code
99
273
#pragma once #include <cmath> namespace ds2i { struct bm25 { static constexpr float b = 0.4; static constexpr float k1 = 0.9; static float doc_term_weight(uint64_t freq, float norm_len) { float f = (float)freq; return f / (f + k1 * (1.0f - b + b * norm_len)); } //IDF (inverse document frequency) static float query_term_weight(uint64_t freq, uint64_t df, uint64_t num_docs) { float f = (float)freq; float fdf = (float)df; float idf = std::log((float(num_docs) - fdf + 0.5f) / (fdf + 0.5f)); static const float epsilon_score = 1.0E-6; return f * std::max(epsilon_score, idf) * (1.0f + k1); } }; }
35,706
https://github.com/Epi-Info/Entomology-App/blob/master/src/main/java/goldengine/java/SymbolTypeConstants.java
Github Open Source
Open Source
Apache-2.0
2,020
Entomology-App
Epi-Info
Java
Code
175
397
package goldengine.java; /* * Licensed Material - Property of Matthew Hawkins (hawkini@barclays.net) * * GOLDParser - code ported from VB - Author Devin Cook. All rights reserved. * * No modifications to this code are allowed without the permission of the author. */ /**-------------------------------------------------------------------------------------------<br> * * Source File: SymbolTypeConstants.java<br> * * Author: Matthew Hawkins<br> * * Description: A set of constants associated with what type a symbol is. * Do NOT change these numbers!<br> * * *-------------------------------------------------------------------------------------------<br> * * Revision List<br> *<pre> * Author Version Description * ------ ------- ----------- * MPH 1.0 First Issue</pre><br> * *-------------------------------------------------------------------------------------------<br> * * IMPORT: NONE<br> * *-------------------------------------------------------------------------------------------<br> */ public interface SymbolTypeConstants { /** Normal nonterminal */ int symbolTypeNonterminal = 0; /** Normal terminal */ int symbolTypeTerminal = 1; /** Type of terminal */ int symbolTypeWhitespace = 2; /** End character (EOF) */ int symbolTypeEnd = 3; /** Comment start */ int symbolTypeCommentStart = 4; /** Comment end */ int symbolTypeCommentEnd = 5; /** Comment line */ int symbolTypeCommentLine = 6; /** Error symbol */ int symbolTypeError = 7; }
19,124
https://github.com/tomsnail/snail-dev/blob/master/snail-third-extends/snail-e3-tx/snail-e3-tx-weixin/src/main/java/cn/tomsnail/snail/e3/tx/weixin/util/sucai/MediaOper.java
Github Open Source
Open Source
Apache-2.0
2,019
snail-dev
tomsnail
Java
Code
91
484
package cn.tomsnail.snail.e3.tx.weixin.util.sucai; import java.io.File; public interface MediaOper { // 上传多媒体 String upload_media = "/media/upload?access_token=%s&type=%s"; // 下载多媒体 String get_media = "/media/get?access_token=%s&media_id=%s"; /** * 上传多媒体文件 * * <pre/> * 上传的临时多媒体文件有格式和大小限制,如下: * <li/> * 图片(image): 1M,支持JPG格式 * <li/> * 语音(voice):2M,播放长度不超过60s,支持AMR\MP3格式 * <li/> * 视频(video):10MB,支持MP4格式 * <li/> * 缩略图(thumb):64KB,支持JPG格式 * * <pre/> * 媒体文件在后台保存时间为3天,即3天后media_id失效。 * * @param type * 多媒体类型 {@link io.github.elkan1788.mpsdk4j.common.MediaType} * @param media * 多媒体文件 * @return 实体{@link Media} */ Media upMedia(String type, File media); /** * 下载多媒体文件 * * @param mediaId * 媒体文件ID * @return {@link File} */ File dlMedia(String mediaId); }
23,117
https://github.com/samuelhehe/Property/blob/master/app/src/main/java/xj/property/beans/NeighborDetailsV3Bean.java
Github Open Source
Open Source
Apache-2.0
2,018
Property
samuelhehe
Java
Code
490
1,507
package xj.property.beans; import java.util.List; /** * 作者:che on 2016/3/9 11:39 * ******************************************** * 公司:北京小间科技发展有限公司 * ******************************************** * 界面功能: */ public class NeighborDetailsV3Bean { private int cooperationId; private String title; private String content; private String emobId; private Long createTime; private int communityId; private String nickname; private String avatar; private String grade; private String identity; private List<NeighborDetailsUserV3Bean> users; private List<NeighborDetailsCooperationV3Bean> cooperationDetails; public int getCooperationId() { return cooperationId; } public void setCooperationId(int cooperationId) { this.cooperationId = cooperationId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getEmobId() { return emobId; } public void setEmobId(String emobId) { this.emobId = emobId; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public int getCommunityId() { return communityId; } public void setCommunityId(int communityId) { this.communityId = communityId; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } public List<NeighborDetailsUserV3Bean> getUsers() { return users; } public void setUsers(List<NeighborDetailsUserV3Bean> users) { this.users = users; } public List<NeighborDetailsCooperationV3Bean> getCooperationDetails() { return cooperationDetails; } public void setCooperationDetails(List<NeighborDetailsCooperationV3Bean> cooperationDetails) { this.cooperationDetails = cooperationDetails; } public class NeighborDetailsUserV3Bean { private String emobId; private String nickname; private String avatar; private Long createTime; public String getEmobId() { return emobId; } public void setEmobId(String emobId) { this.emobId = emobId; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } } public class NeighborDetailsCooperationV3Bean { private String emobIdFrom; private String detailContent; private String nicknameFrom; private String avatarFrom; private String gradeFrom; private String identityFrom; private String emobIdTo; private String nicknameTo; public String getEmobIdFrom() { return emobIdFrom; } public void setEmobIdFrom(String emobIdFrom) { this.emobIdFrom = emobIdFrom; } public String getDetailContent() { return detailContent; } public void setDetailContent(String detailContent) { this.detailContent = detailContent; } public String getNicknameFrom() { return nicknameFrom; } public void setNicknameFrom(String nicknameFrom) { this.nicknameFrom = nicknameFrom; } public String getAvatarFrom() { return avatarFrom; } public void setAvatarFrom(String avatarFrom) { this.avatarFrom = avatarFrom; } public String getGradeFrom() { return gradeFrom; } public void setGradeFrom(String gradeFrom) { this.gradeFrom = gradeFrom; } public String getIdentityFrom() { return identityFrom; } public void setIdentityFrom(String identityFrom) { this.identityFrom = identityFrom; } public String getEmobIdTo() { return emobIdTo; } public void setEmobIdTo(String emobIdTo) { this.emobIdTo = emobIdTo; } public String getNicknameTo() { return nicknameTo; } public void setNicknameTo(String nicknameTo) { this.nicknameTo = nicknameTo; } } }
44,426
https://github.com/cecimol/Plantillas/blob/master/Routes/chat.js
Github Open Source
Open Source
MIT
null
Plantillas
cecimol
JavaScript
Code
59
177
const express = require("express"); const { Router } = express; const router = new Router(); const { readFileAsync, writeFileAsync } = require("../helpers"); router.post("/", async (req, res) => { const chat = await readFileAsync("chat"); const obj = { email: req.body.email, mensaje: req.body.mensaje, }; chat.push(obj); await writeFileAsync("chat", chat); if (__socket) { console.log("emitiendo actualizar-chat"); __socket.emit("actualizar-chat", chat); } res.redirect("/"); }); module.exports = router;
10,429
https://github.com/AzureMentor/yo/blob/master/lib/routes/help.js
Github Open Source
Open Source
BSD-2-Clause
2,019
yo
AzureMentor
JavaScript
Code
110
332
'use strict'; const inquirer = require('inquirer'); const opn = require('opn'); module.exports = app => { app.insight.track('yoyo', 'help'); return inquirer.prompt([{ name: 'whereTo', type: 'list', message: 'Here are a few helpful resources.\n\nI will open the link you select in your browser for you', choices: [{ name: 'Take me to the documentation', value: 'http://yeoman.io/learning/' }, { name: 'View Frequently Asked Questions', value: 'http://yeoman.io/learning/faq.html' }, { name: 'File an issue on GitHub', value: 'http://yeoman.io/contributing/opening-issues.html' }, { name: 'Take me back home, Yo!', value: 'home' }] }]).then(answer => { app.insight.track('yoyo', 'help', answer); if (answer.whereTo === 'home') { console.log('I get it, you like learning on your own. I respect that.'); app.navigate('home'); return; } opn(answer.whereTo); }); };
17,560
https://github.com/phoddie/kinomajs/blob/master/kinoma/kpr/extensions/coap/kprCoAPMessage.c
Github Open Source
Open Source
LicenseRef-scancode-pcre, NICTA-1.0, BSD-3-Clause, WTFPL, IJG, Zlib, dtoa, FTL, MIT, Apache-2.0, LicenseRef-scancode-public-domain, LicenseRef-scancode-unknown-license-reference
2,016
kinomajs
phoddie
C
Code
2,423
9,416
/* * Copyright (C) 2010-2015 Marvell International Ltd. * Copyright (C) 2002-2010 Kinoma, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kprCoAPMessage.h" #include "FskEndian.h" #include "kprURL.h" #if defined(RUN_UNITTEST) && RUN_UNITTEST #include "kunit.h" ku_test(CoAP_message) { } #endif static void KprCoAPMessageDisposeOption(KprCoAPMessageOptionRecord *optRec); FskErr KprCoAPMessageNew(KprCoAPMessage *it) { FskErr err = kFskErrNone; KprCoAPMessage self = NULL; bailIfError(KprMemPtrNewClear(sizeof(KprCoAPMessageRecord), &self)); bailIfError(KprRetainableNew(&self->retainable)); *it = self; bail: if (err) { KprCoAPMessageDispose(self); } return err; } FskErr KprCoAPMessageDispose(KprCoAPMessage self) { if (self && KprRetainableRelease(self->retainable)) { KprCoAPMessageOptionRecord *optRec; KprMemoryBlockDispose(self->token); KprMemoryBlockDispose(self->payload); optRec = self->options; while (optRec != NULL) { KprCoAPMessageOptionRecord *next = optRec->next; KprCoAPMessageDisposeOption(optRec); optRec = next; } KprMemPtrDispose((void *) self->uri); KprMemPtrDispose((void *) self->host); KprMemPtrDispose((void *) self->path); KprMemPtrDispose((void *) self->query); KprRetainableDispose(self->retainable); KprMemPtrDispose(self); } return kFskErrNone; } FskErr KprCoAPMessageDisposeAt(KprCoAPMessage *it) { FskErr err = kFskErrNone; if (it) { err = KprCoAPMessageDispose(*it); *it = NULL; } return err; } FskErr KprCoAPMessageCopy(KprCoAPMessage original, KprCoAPMessage *it) { FskErr err = kFskErrNone; KprCoAPMessage self = NULL; bailIfError(KprCoAPMessageNew(&self)); self->messageId = original->messageId; if (original->token) { int size; size = original->token->size; if (size > 0) { bailIfError(KprCoAPMessageSetToken(self, KprMemoryBlockStart(original->token), size)); } } *it = self; bail: if (err) { KprCoAPMessageDispose(self); } return err; } KprCoAPMessage KprCoAPMessageRetain(KprCoAPMessage self) { KprRetainableRetain(self->retainable); return self; } Boolean KprCoAPMessageIsConfirmable(KprCoAPMessage self) { return (self->type == kKprCoAPMessageTypeConfirmable); } static int KprCoAPMessageCompareOption(const void *a, const void *b) { int o1 = ((KprCoAPMessageOptionRecord *)a)->option; int o2 = ((KprCoAPMessageOptionRecord *)b)->option; return o1 - o2; } static FskErr KprCoAPMessageAppendOption(KprCoAPMessage self, KprCoAPMessageOption option, KprCoAPMessageOptionFormat format, KprCoAPMessageOptionRecord **it) { FskErr err = kFskErrNone; KprCoAPMessageOptionRecord *optRec; bailIfError(KprMemPtrNewClear(sizeof(KprCoAPMessageOptionRecord), &optRec)); optRec->option = option; optRec->format = format; FskListInsertSorted(&self->options, optRec, KprCoAPMessageCompareOption); *it = optRec; bail: return err; } static void KprCoAPMessageDisposeOption(KprCoAPMessageOptionRecord *optRec) { switch (optRec->format) { case kKprCoAPMessageOptionFormatOpaque: KprMemPtrDispose((void *) optRec->value.opaque.data); break; case kKprCoAPMessageOptionFormatString: KprMemPtrDispose((void *) optRec->value.string); break; default: break; } KprMemPtrDispose(optRec); } FskErr KprCoAPMessageAppendEmptyOption(KprCoAPMessage self, KprCoAPMessageOption option) { FskErr err = kFskErrNone; KprCoAPMessageOptionRecord *optRec; bailIfError(KprCoAPMessageAppendOption(self, option, kKprCoAPMessageOptionFormatEmpty, &optRec)); bail: return err; } FskErr KprCoAPMessageAppendOpaqueOption(KprCoAPMessage self, KprCoAPMessageOption option, const void *data, UInt32 length) { FskErr err = kFskErrNone; KprCoAPMessageOptionRecord *optRec; if (length > kKprCoAPMessageOptionLengthMax) { bailIfError(kFskErrBadData); } bailIfError(KprCoAPMessageAppendOption(self, option, kKprCoAPMessageOptionFormatOpaque, &optRec)); if (length > 0) { bailIfError(KprMemPtrNewFromData(length, data, &optRec->value.opaque.data)); } optRec->value.opaque.length = length; bail: return err; } FskErr KprCoAPMessageAppendUintOption(KprCoAPMessage self, KprCoAPMessageOption option, UInt32 uint) { FskErr err = kFskErrNone; KprCoAPMessageOptionRecord *optRec; bailIfError(KprCoAPMessageAppendOption(self, option, kKprCoAPMessageOptionFormatUint, &optRec)); optRec->value.uint = uint; bail: return err; } FskErr KprCoAPMessageAppendStringOption(KprCoAPMessage self, KprCoAPMessageOption option, const char *string) { FskErr err = kFskErrNone; KprCoAPMessageOptionRecord *optRec; if (FskStrLen(string) > kKprCoAPMessageOptionLengthMax) { bailIfError(kFskErrBadData); } bailIfError(KprCoAPMessageAppendOption(self, option, kKprCoAPMessageOptionFormatString, &optRec)); optRec->value.string = FskStrDoCopy(string); bailIfNULL(optRec->value.string); bail: return err; } KprCoAPMessageOptionRecord *KprCoAPMessageFindOption(KprCoAPMessage self, KprCoAPMessageOption option) { KprCoAPMessageOptionRecord *optRec = self->options; while (optRec) { if (optRec->option == option) return optRec; if (optRec->option > option) break; optRec = optRec->next; } return NULL; } FskErr KprCoAPMessageRemoveOptions(KprCoAPMessage self, KprCoAPMessageOption option) { FskErr err = kFskErrNone; KprCoAPMessageOptionRecord *optRec; while ((optRec = KprCoAPMessageFindOption(self, option)) != NULL) { FskListRemove(&self->options, optRec); KprCoAPMessageDisposeOption(optRec); } return err; } FskErr KprCoAPMessageSetToken(KprCoAPMessage self, const void *token, UInt32 length) { FskErr err = kFskErrNone; if (length > kKprCoAPMessageTokenLengthMax) { bailIfError(kFskErrBadData); } KprMemoryBlockDisposeAt(&self->token); bailIfError(KprMemoryBlockNew(length, token, &self->token)); bail: return err; } FskErr KprCoAPMessageSetPayload(KprCoAPMessage self, const void *payload, UInt32 length) { FskErr err = kFskErrNone; KprMemoryBlockDisposeAt(&self->payload); bailIfError(KprMemoryBlockNew(length, payload, &self->payload)); bail: return err; } KprCoAPContentFormat KprCoAPMessageGetContentFormat(KprCoAPMessage self) { KprCoAPMessageOptionRecord *optRec = KprCoAPMessageFindOption(self, kKprCoAPMessageOptionContentFormat); if (optRec == NULL) return kKprCoAPContentFormatNone; return optRec->value.uint; } FskErr KprCoAPMessageSetContentFormat(KprCoAPMessage self, KprCoAPContentFormat format) { FskErr err = kFskErrNone; bailIfError(KprCoAPMessageRemoveOptions(self, kKprCoAPMessageOptionContentFormat)); bailIfError(KprCoAPMessageAppendUintOption(self, kKprCoAPMessageOptionContentFormat, format)); bail: return err; } typedef struct { UInt8 value; UInt8 extraBytes; UInt8 extraValue[2]; } KprCoAPMessagePackedOptionValue; static KprCoAPMessagePackedOptionValue KprCoAPMessagePackOptValue(UInt32 value) { KprCoAPMessagePackedOptionValue packed; /* 0 - 12 13: 0 - 255 => 13 - 268 14: 0 - 65535 => 269 - 65804 */ if (value <= 12) { packed.value = value; packed.extraBytes = 0; } else if (value <= 268) { packed.value = 13; packed.extraBytes = 1; packed.extraValue[0] = value - 13; } else { packed.value = 14; packed.extraBytes = 2; value = value - 269; packed.extraValue[0] = (value >> 8) & 0xff; packed.extraValue[1] = (value >> 0) & 0xff; } return packed; } static UInt32 KprCoAPMessageOptionLength(KprCoAPMessageOptionRecord *optRec) { switch (optRec->format) { case kKprCoAPMessageOptionFormatEmpty: return 0; case kKprCoAPMessageOptionFormatOpaque: return optRec->value.opaque.length; case kKprCoAPMessageOptionFormatUint: if (optRec->value.uint == 0) return 0; if (optRec->value.uint <= 0xff) return 1; if (optRec->value.uint <= 0xffff) return 2; if (optRec->value.uint <= 0xffffff) return 3; return 4; case kKprCoAPMessageOptionFormatString: return FskStrLen(optRec->value.string); } return 0; } static UInt32 KprCoAPMessageCalculateSerializedSize(KprCoAPMessage self) { UInt32 size; KprCoAPMessageOptionRecord *optRec; KprCoAPMessageOption prev; size = sizeof(UInt32); if (self->token) { size += self->token->size; } if (self->payload) { size += self->payload->size + 1; } optRec = self->options; prev = 0; while (optRec) { UInt32 optLen, optDelta; KprCoAPMessagePackedOptionValue packed; size += 1; optLen = KprCoAPMessageOptionLength(optRec); packed = KprCoAPMessagePackOptValue(optLen); size += packed.extraBytes; optDelta = optRec->option - prev; prev = optRec->option; packed = KprCoAPMessagePackOptValue(optDelta); size += packed.extraBytes; size += optLen; optRec = optRec->next; } return size; } static void KprCoAPMessageSerializeTo(KprCoAPMessage self, FskMemPtr data) { UInt32 header, version, type, tokenLength, code, messageId; KprCoAPMessageOptionRecord *optRec; KprCoAPMessageOption prev; /* 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Ver| T | TKL | Code | Message ID | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Token (if any, TKL bytes) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options (if any) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1 1 1 1 1 1 1 1| Payload (if any) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ // fixed header version = 0x01 << 30; type = self->type << 28; tokenLength = self->token ? self->token->size << 24 : 0; code = self->code << 16; messageId = self->messageId; header = version | type | tokenLength | code | messageId; header = FskEndianU32_NtoB(header); FskMemCopy(data, &header, sizeof(UInt32)); data += sizeof(UInt32); // token if (self->token) { data = KprMemoryBlockCopyTo(self->token, data); } // options optRec = self->options; prev = 0; while (optRec) { UInt32 opt, len, val32; KprCoAPMessagePackedOptionValue optDelta, optLen; UInt8 byte, *p; /* 0 1 2 3 4 5 6 7 +---------------+---------------+ | Option Delta | Option Length | 1 byte +---------------+---------------+ / Option Delta / 0-2 bytes \ (extended) \ +-------------------------------+ / Option Length / 0-2 bytes \ (extended) \ +-------------------------------+ / Option Value / 0 or more bytes +-------------------------------+ */ opt = optRec->option - prev; prev = optRec->option; optDelta = KprCoAPMessagePackOptValue(opt); len = KprCoAPMessageOptionLength(optRec); optLen = KprCoAPMessagePackOptValue(len); byte = optDelta.value << 4 | optLen.value; *(UInt8 *)data++ = byte; if (optDelta.extraBytes > 0) { FskMemCopy(data, optDelta.extraValue, optDelta.extraBytes); data += optDelta.extraBytes; } if (optLen.extraBytes > 0) { FskMemCopy(data, optLen.extraValue, optLen.extraBytes); data += optLen.extraBytes; } if (len > 0) { switch (optRec->format) { case kKprCoAPMessageOptionFormatEmpty: break; case kKprCoAPMessageOptionFormatOpaque: FskMemCopy(data, optRec->value.opaque.data, len); break; case kKprCoAPMessageOptionFormatUint: val32 = optRec->value.uint; val32 = FskEndianU32_NtoB(val32); p = (UInt8 *)&val32; FskMemCopy(data, p + (sizeof(UInt32) - len), len); break; case kKprCoAPMessageOptionFormatString: FskMemCopy(data, optRec->value.string, len); } data += len; } optRec = optRec->next; } // payload if (self->payload) { *(UInt8 *)data++ = 0xff; KprMemoryBlockCopyTo(self->payload, data); } } FskErr KprCoAPMessageSerialize(KprCoAPMessage self, KprMemoryBlock *it) { FskErr err = kFskErrNone; KprMemoryBlock chunk = NULL; UInt32 size; size = KprCoAPMessageCalculateSerializedSize(self); bailIfError(KprMemoryBlockNew(size, NULL, &chunk)); KprCoAPMessageSerializeTo(self, KprMemoryBlockStart(chunk)); *it = chunk; bail: if (err) { KprMemoryBlockDispose(chunk); } return err; } #define PTR_ADD(p, v) (const void *)((FskMemPtr) p + v) typedef struct KprCoAPMessageDataReaderRecord { const void *start; const void *end; UInt32 index; } KprCoAPMessageDataReaderRecord, *KprCoAPMessageDataReader; static void KprCoAPMessageDataReaderInit(KprCoAPMessageDataReader reader, const void *buffer, UInt32 size) { reader->start = buffer; reader->end = PTR_ADD(buffer, size); reader->index = 0; } static Boolean KprCoAPMessageDataReaderIsEOF(KprCoAPMessageDataReader reader) { return PTR_ADD(reader->start, reader->index) >= reader->end; } static Boolean KprCoAPMessageDataReaderGetPtr(KprCoAPMessageDataReader reader, UInt32 size, const void **p) { *p = PTR_ADD(reader->start, reader->index); reader->index += size; if (PTR_ADD(*p, size) > reader->end) return false; return true; } static Boolean KprCoAPMessageDataReaderRead(KprCoAPMessageDataReader reader, void *buffer, UInt32 size) { const void *p; if (!KprCoAPMessageDataReaderGetPtr(reader, size, &p)) return false; FskMemCopy(buffer, p, size); return true; } #define CHECK(test) if (!(test)) { err = kFskErrBadData; goto bail; } #define READ(p, s) CHECK(KprCoAPMessageDataReaderRead(&reader, p, s)) #define READ_INTO(val) READ(&val, sizeof(val)) #define HAS_DATA() !KprCoAPMessageDataReaderIsEOF(&reader) static Boolean KprCoAPMessageValidateMessage(KprCoAPMessage self) { if (self->code == 0) { if (self->token && self->token->size > 0) return false; if (self->payload && self->payload->size > 0) return false; return true; } return true; } FskErr KprCoAPMessageDeserialize(const void *buffer, UInt32 size, KprCoAPMessage *it) { FskErr err = kFskErrNone; KprCoAPMessage self = NULL; KprCoAPMessageDataReaderRecord reader; UInt32 header, version, len; Boolean hasPayloadMarker; KprCoAPMessageOption option; const void *p; char *str = NULL; bailIfError(KprCoAPMessageNew(&self)); KprCoAPMessageDataReaderInit(&reader, buffer, size); /* 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Ver| T | TKL | Code | Message ID | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Token (if any, TKL bytes) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options (if any) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1 1 1 1 1 1 1 1| Payload (if any) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ // fixed header READ_INTO(header); header = FskEndianU32_BtoN(header); version = (header >> 30) & 0x03; CHECK(version == 1); self->type = (header >> 28) & 0x03; len = (header >> 24) & 0xf; self->code = (header >> 16) & 0xff; self->messageId = (header) & 0xffff; // token if (len > 0) { const void *p; CHECK(KprCoAPMessageDataReaderGetPtr(&reader, len, &p)); bailIfError(KprCoAPMessageSetToken(self, p, len)); } // options hasPayloadMarker = false; option = 0; while (HAS_DATA()) { UInt32 opt; UInt8 byte, *byteP; UInt16 val16; UInt32 val32; KprCoAPMessageOptionFormat format; /* 0 1 2 3 4 5 6 7 +---------------+---------------+ | Option Delta | Option Length | 1 byte +---------------+---------------+ / Option Delta / 0-2 bytes \ (extended) \ +-------------------------------+ / Option Length / 0-2 bytes \ (extended) \ +-------------------------------+ / Option Value / 0 or more bytes +-------------------------------+ */ READ_INTO(byte); if (byte == 0xff) { hasPayloadMarker = true; break; } opt = (byte >> 4) & 0xf; len = (byte) & 0xf; if (opt == 13) { READ_INTO(byte); opt = 13 + byte; } else if (opt == 14) { READ_INTO(val16); opt = 13 + 256 + val16; } else { CHECK(opt != 15); } if (len == 13) { READ_INTO(byte); len = 13 + byte; } else if (len == 14) { READ_INTO(val16); len = 13 + 256 + val16; } else { CHECK(opt != 15); } option += opt; CHECK(KprCoAPMessageDataReaderGetPtr(&reader, len, &p)); format = KprCoAPMessageOptionGetFormat(option); switch (format) { case kKprCoAPMessageOptionFormatEmpty: CHECK(len == 0); bailIfError(KprCoAPMessageAppendEmptyOption(self, option)); break; case kKprCoAPMessageOptionFormatOpaque: bailIfError(KprCoAPMessageAppendOpaqueOption(self, option, p, len)); break; case kKprCoAPMessageOptionFormatUint: byteP = (UInt8 *)p; val32 = 0; while (len-- > 0) { val32 = val32 * 256 + *byteP++; } bailIfError(KprCoAPMessageAppendUintOption(self, option, val32)); break; case kKprCoAPMessageOptionFormatString: bailIfError(KprMemPtrNew(len + 1, &str)); FskMemCopy(str, p, len); str[len] = 0; bailIfError(KprCoAPMessageAppendStringOption(self, option, str)); KprMemPtrDispose(str); str = NULL; break; } } // payload if (HAS_DATA()) { CHECK(hasPayloadMarker == true); CHECK(KprCoAPMessageDataReaderGetPtr(&reader, 0, &p)); len = size - reader.index; bailIfError(KprCoAPMessageSetPayload(self, p, len)); } else { CHECK(hasPayloadMarker == false); } CHECK(KprCoAPMessageValidateMessage(self)); *it = self; bail: KprMemPtrDispose(str); if (err) { KprCoAPMessageDispose(self); } return err; } KprCoAPMessageOptionFormat KprCoAPMessageOptionGetFormat(KprCoAPMessageOption option) { switch (option) { case kKprCoAPMessageOptionIfNoneMatch: return kKprCoAPMessageOptionFormatEmpty; case kKprCoAPMessageOptionIfMatch: case kKprCoAPMessageOptionETag: return kKprCoAPMessageOptionFormatOpaque; case kKprCoAPMessageOptionUriPort: case kKprCoAPMessageOptionContentFormat: case kKprCoAPMessageOptionMaxAge: case kKprCoAPMessageOptionAccept: case kKprCoAPMessageOptionSize1: case kKprCoAPMessageOptionBlock2: case kKprCoAPMessageOptionBlock1: case kKprCoAPMessageOptionSize2: case kKprCoAPMessageOptionObserve: return kKprCoAPMessageOptionFormatUint; case kKprCoAPMessageOptionUriHost: case kKprCoAPMessageOptionLocationPath: case kKprCoAPMessageOptionUriPath: case kKprCoAPMessageOptionUriQuery: case kKprCoAPMessageOptionLocationQuery: case kKprCoAPMessageOptionProxyUri: case kKprCoAPMessageOptionProxyScheme: return kKprCoAPMessageOptionFormatString; } return kKprCoAPMessageOptionFormatEmpty; } static Boolean KprCoAPMessageIsValidURL(KprURLParts parts); static FskErr KprCoAPMessageParseAndAddOptionComponets(KprCoAPMessage request, char *str, char delimiter, KprCoAPMessageOption option); FskErr KprCoAPMessageParseUri(KprCoAPMessage self, const char *uri) { FskErr err = kFskErrNone; KprURLPartsRecord parts; char *host = NULL; char *path = NULL; char *query = NULL; int ipaddr, len; KprURLSplit((char *) uri, &parts); if (!KprCoAPMessageIsValidURL(&parts)) bailIfError(kFskErrInvalidParameter); bailIfError(KprCoAPStrNewWithLength(parts.host, parts.hostLength, &host)); bailIfError(KprCoAPStrNewWithLength(parts.path, parts.pathLength, &path)); bailIfError(KprCoAPStrNewWithLength(parts.query, parts.queryLength, &query)); if (query) { bailIfError(KprCoAPMessageParseAndAddOptionComponets(self, query, '&', kKprCoAPMessageOptionUriQuery)); } if (path) { len = FskStrLen(path); if (!(len == 0 || (len == 1 && *path == '/'))) { bailIfError(KprCoAPMessageParseAndAddOptionComponets(self, path + 1, '/', kKprCoAPMessageOptionUriPath)); } } if (!FskStrIsDottedQuad(host, &ipaddr)) { bailIfError(KprCoAPMessageAppendStringOption(self, kKprCoAPMessageOptionUriHost, host)); } self->uri = FskStrDoCopy(uri); bailIfNULL(self->uri); self->host = host; self->path = path; self->query = query; self->port = parts.port; bail: if (err) { KprMemPtrDispose(host); KprMemPtrDispose(path); KprMemPtrDispose(query); } return err; } FskErr KprCoAPMessageBuildUri(KprCoAPMessage request) { FskErr err = kFskErrNone; KprCoAPMessageOptionRecord *optRec; int hostLen = 0, portLen = 0, pathLen = 0, queryLen = 0; char *uri = NULL, *host = NULL, portStr[10], *path = NULL, *query = NULL; UInt32 len = 0; // coap://[hostname](:[port])/acd/dfe/gih?a=b&b=c // 7 + host.len + // port.len + 1 // optRec = request->options; while (optRec) { switch (optRec->option) { case kKprCoAPMessageOptionUriHost: hostLen = FskStrLen(optRec->value.string); break; case kKprCoAPMessageOptionUriPort: FskStrNumToStr(optRec->value.uint, portStr + 1, sizeof(portStr) - 1); portStr[0] = ':'; portLen = FskStrLen(portStr); break; case kKprCoAPMessageOptionUriPath: pathLen += 1 + FskStrCountEscapedCharsToEncode(optRec->value.string); break; case kKprCoAPMessageOptionUriQuery: queryLen += 1 + FskStrCountEscapedCharsToEncode(optRec->value.string); break; default: break; } optRec = optRec->next; } len = 7 + hostLen + portLen + pathLen + queryLen; bailIfError(KprMemPtrNew(len + 1, &request->uri)); uri = (char *)request->uri; if (hostLen > 0) { bailIfError(KprMemPtrNew(hostLen + 1, &request->host)); host = (char *)request->host; *host = 0; } if (pathLen > 0) { bailIfError(KprMemPtrNew(pathLen + 1, &request->path)); path = (char *)request->path; *path = 0; } if (queryLen > 0) { bailIfError(KprMemPtrNew((queryLen - 1) + 1, &request->query)); query = (char *)request->query; *query = 0; } optRec = request->options; while (optRec) { switch (optRec->option) { case kKprCoAPMessageOptionUriHost: FskStrCopy(host, optRec->value.string); break; case kKprCoAPMessageOptionUriPort: request->port = optRec->value.uint; break; case kKprCoAPMessageOptionUriPath: FskStrCat(path, "/"); FskStrEncodeEscapedChars(optRec->value.string, path + FskStrLen(path)); break; case kKprCoAPMessageOptionUriQuery: if (*query) FskStrCat(query, "&"); FskStrEncodeEscapedChars(optRec->value.string, query + FskStrLen(query)); break; default: break; } optRec = optRec->next; } FskStrCopy(uri, "coap://"); if (host) { FskStrCat(uri, host); } if (portLen > 0) { FskStrCat(uri, portStr); } if (path) { FskStrCat(uri, path); } if (query) { FskStrCat(uri, "?"); FskStrCat(uri, query); } bail: return err; } static Boolean KprCoAPMessageIsValidURL(KprURLParts parts) { if (parts->schemeLength != 4) return false; if (FskStrCompareCaseInsensitiveWithLength(parts->scheme, "coap", 4) != 0) return false; if (parts->hostLength == 0) return false; if (parts->fragmentLength > 0) return false; if (parts->port == 0 || parts->port == 80) { parts->port = 5683; } return true; } static FskErr KprCoAPMessageParseAndAddOptionComponets(KprCoAPMessage request, char *str, char delimiter, KprCoAPMessageOption option) { FskErr err = kFskErrNone; int len = FskStrLen(str); char *p = str, *end = p + len; while (p < end) { if (*p == delimiter) *p = 0; p += 1; } p = str; while (p < end) { len = FskStrLen(p); FskStrDecodeEscapedChars(p, p); bailIfError(KprCoAPMessageAppendStringOption(request, option, p)); p += len + 1; } bail: return err; }
27,571
https://github.com/futurum-dev/dotnet.futurum.webapiendpoint/blob/master/test/Futurum.WebApiEndpoint.Tests/OpenApi/WebApiEndpointDotnetTypeToOpenApiMapperTests.IsRequired.cs
Github Open Source
Open Source
MIT
null
dotnet.futurum.webapiendpoint
futurum-dev
C#
Code
57
323
using FluentAssertions; using Futurum.Core.Option; using Futurum.WebApiEndpoint.OpenApi; using Microsoft.AspNetCore.Http; using Xunit; namespace Futurum.WebApiEndpoint.Tests.OpenApi; public class WebApiEndpointDotnetTypeToOpenApiIsRequiredMapperTests { [Theory] [InlineData(typeof(string), true)] [InlineData(typeof(int), true)] [InlineData(typeof(long), true)] [InlineData(typeof(float), true)] [InlineData(typeof(double), true)] [InlineData(typeof(byte), true)] [InlineData(typeof(DateTime), true)] [InlineData(typeof(bool), true)] [InlineData(typeof(Guid), true)] [InlineData(typeof(IFormFile), true)] [InlineData(typeof(WebApiEndpoint.Range), true)] [InlineData(typeof(Option<WebApiEndpoint.Range>), false)] [InlineData(typeof(IEnumerable<IFormFile>), true)] public void check(Type type, bool expectedIsRequired) { var isRequired = WebApiEndpointDotnetTypeToOpenApiIsRequiredMapper.Execute(type); isRequired.Should().Be(expectedIsRequired); } }
4,078
https://github.com/reevoo/reevoomark-java-api/blob/master/taglib/src/test/java/com.reevoo.taglib/ReevooConversationsTest.java
Github Open Source
Open Source
MIT
2,016
reevoomark-java-api
reevoo
Java
Code
132
764
package com.reevoo.taglib; import com.reevoo.client.ReevooMarkClient; import com.reevoo.utils.TaglibConfig; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.*; import com.mockrunner.tag.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.PageContext; import java.util.LinkedHashMap; import java.util.Map; public class ReevooConversationsTest extends BasicTagTestCaseAdapter{ private ReevooMarkClient markClient = mock(ReevooMarkClient.class); private ReevooConversations conversationsTag = new ReevooConversations(); @Before public void setUp() throws Exception { super.setUp(); conversationsTag.setDynamicAttribute("", "sku", "12345"); conversationsTag.setTrkref("FOO"); conversationsTag.setClient(markClient); setTag(conversationsTag); } @Test public void testTagCallsClientWithCorrectAttributesAndTheConversationEndpoint() { conversationsTag.setNumberOfConversations("3"); processTagLifecycle(); Map<String, String> queryStringParams = new LinkedHashMap<String,String>(); queryStringParams.put("trkref", "FOO"); queryStringParams.put("sku", "12345"); queryStringParams.put("reviews", null); queryStringParams.put("conversations", "3"); verify(markClient).obtainReevooMarkData( "http://mark.reevoo.com/reevoomark/embeddable_conversations", queryStringParams); } @Test public void testTagRespondsWithContentFromClient() { when(markClient.obtainReevooMarkData(anyString(),anyMap())).thenReturn("FOO"); processTagLifecycle(); verifyOutput("FOO"); } @Test public void testTagReturnsTagBodyWhenNoResponseFromClient() { when(markClient.obtainReevooMarkData(anyString(), anyMap())).thenReturn(null); setBody("There are no reviews"); processTagLifecycle(); verifyOutput("There are no reviews"); } @Test public void testTagUsesDefaultTrkrefIfNoExplicitOneSpecified() { conversationsTag = new ReevooConversations(); conversationsTag.setClient(markClient); setTag(conversationsTag); processTagLifecycle(); Map<String, String> queryStringParams = new LinkedHashMap<String,String>(); queryStringParams.put("trkref", "REV"); queryStringParams.put("reviews", null); queryStringParams.put("conversations",null); verify(markClient).obtainReevooMarkData("http://mark.reevoo.com/reevoomark/embeddable_conversations", queryStringParams); } }
31,496
https://github.com/AlexanderSemenyak/Fusee/blob/master/src/Engine/Core/SceneRayCaster.cs
Github Open Source
Open Source
Zlib
null
Fusee
AlexanderSemenyak
C#
Code
778
1,986
using Fusee.Engine.Common; using Fusee.Engine.Core.Scene; using Fusee.Math.Core; using Fusee.Xene; using System; using System.Collections.Generic; namespace Fusee.Engine.Core { /// <summary> /// This class contains information about the scene of the picked point. /// </summary> public class RayCastResult { /// <summary> /// The scene node containter of the result. /// </summary> public SceneNode Node; /// <summary> /// The picked mesh. /// </summary> public Mesh Mesh; /// <summary> /// The index of the triangle in which the intersection of ray and mesh happened. /// </summary> public int Triangle; /// <summary> /// The barycentric u, v coordinates within the picked triangle. /// </summary> public float U, V; /// <summary> /// The (texture-) UV coordinates of the picked point. /// </summary> public float2 UV { get { float2 uva = Mesh.UVs[Mesh.Triangles[Triangle]]; float2 uvb = Mesh.UVs[Mesh.Triangles[Triangle + 1]]; float2 uvc = Mesh.UVs[Mesh.Triangles[Triangle + 2]]; return float2.Barycentric(uva, uvb, uvc, U, V); } } /// <summary> /// The model matrix. /// </summary> public float4x4 Model; /// <summary> /// Gets the triangles of the picked mesh. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> public void GetTriangle(out float3 a, out float3 b, out float3 c) { a = Mesh.Vertices[Mesh.Triangles[Triangle + 0]]; b = Mesh.Vertices[Mesh.Triangles[Triangle + 1]]; c = Mesh.Vertices[Mesh.Triangles[Triangle + 2]]; } /// <summary> /// Returns the barycentric triangle coordinates. /// </summary> public float3 TriangleBarycentric { get { GetTriangle(out var a, out var b, out var c); return float3.Barycentric(a, b, c, U, V); } } /// <summary> /// Returns the model position. /// </summary> public float3 ModelPos => TriangleBarycentric; /// <summary> /// Returns the world position of the intersection. /// </summary> public float3 WorldPos => float4x4.TransformPerspective(Model, ModelPos); /// <summary> /// Returns the (absolute) distance between ray origin and the intersection. /// </summary> public float DistanceFromOrigin; } /// <summary> /// Implements the scene raycaster. /// </summary> public class SceneRayCaster : Viserator<RayCastResult, SceneRayCaster.RayCasterState, SceneNode, SceneComponent> { /// <summary> /// The origin of the ray (in world space). /// </summary> public float3 Origin { get; private set; } /// <summary> /// The direction of the ray (in world space). /// </summary> public float3 Direction { get; private set; } #region State /// <summary> /// The raycaster state upon scene traversal. /// </summary> public class RayCasterState : VisitorState { private readonly CollapsingStateStack<float4x4> _model = new CollapsingStateStack<float4x4>(); /// <summary> /// The registered model. /// </summary> public float4x4 Model { set => _model.Tos = value; get => _model.Tos; } /// <summary> /// The default constructor for the <see cref="RayCasterState"/> class, which registers state stacks for the model./> /// </summary> public RayCasterState() { RegisterState(_model); } } #endregion /// <summary> /// The constructor to initialize a new SceneRayCaster. /// </summary> /// <param name="scene">The <see cref="SceneContainer"/> to use.</param> public SceneRayCaster(SceneContainer scene) : base(scene.Children) { } /// <summary> /// This method is called when traversal starts to initialize the traversal state. /// </summary> protected override void InitState() { base.InitState(); State.Model = float4x4.Identity; } /// <summary> /// Returns a collection of objects that are hit by the ray and that can be iterated over. /// </summary> /// <param name="origin">The origin of the ray (in world space).</param> /// <param name="direction">The direction of the ray (in world space).</param> /// <returns>A collection of <see cref="RayCastResult"/> that can be iterated over.</returns> public IEnumerable<RayCastResult> RayCast(float3 origin, float3 direction) { Origin = origin; Direction = direction; return Viserate(); } #region Visitors /// <summary> /// If a TransformComponent is visited the model matrix of the <see cref="RenderContext"/> and <see cref="RayCasterState"/> is updated. /// </summary> /// <param name="transform">The TransformComponent.</param> [VisitMethod] public void RenderTransform(Transform transform) { State.Model *= transform.Matrix(); } /// <summary> /// Creates a raycast result from a given mesh if it is hit by the ray. /// </summary> /// <param name="mesh">The given mesh.</param> [VisitMethod] public void HitMesh(Mesh mesh) { if (!mesh.Active) return; for (int i = 0; i < mesh.Triangles.Length; i += 3) { // Vertices of the picked triangle in world space var a = new float3(mesh.Vertices[mesh.Triangles[i + 0]]); a = float4x4.Transform(State.Model, a); var b = new float3(mesh.Vertices[mesh.Triangles[i + 1]]); b = float4x4.Transform(State.Model, b); var c = new float3(mesh.Vertices[mesh.Triangles[i + 2]]); c = float4x4.Transform(State.Model, c); // Normal of the plane defined by a, b, and c. var n = float3.Normalize(float3.Cross(a - c, b - c)); // Distance between "Origin" and the plane abc when following the Direction. var distance = -float3.Dot(Origin - a, n) / float3.Dot(Direction, n); if (distance < 0) return; // Position of the intersection point between ray and plane. var point = Origin + Direction * distance; if (float3.PointInTriangle(a, b, c, point, out float u, out float v)) { YieldItem(new RayCastResult { Mesh = mesh, Node = CurrentNode, Triangle = i, Model = State.Model, U = u, V = v, DistanceFromOrigin = System.Math.Abs(distance) }); } } } #endregion } }
42,993
https://github.com/Saumitra07/Android-Applications/blob/master/ForumsApp/InClass08/app/src/main/java/com/example/inclass08/Utils.java
Github Open Source
Open Source
MIT
null
Android-Applications
Saumitra07
Java
Code
43
148
package com.example.inclass08; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.text.ParseException; import java.util.Calendar; public class Utils { public static class HelperFunctions { public static String getDate() { DateFormat dateFormat2 = new SimpleDateFormat("MM/dd/yyyy hh:mm aa"); String dateString2 = dateFormat2.format(new Date()).toString(); return dateString2; } } }
27,808
https://github.com/securenative/react-awesome-query-builder/blob/master/build/npm/lib/components/containers/RuleContainer.js
Github Open Source
Open Source
MIT
null
react-awesome-query-builder
securenative
JavaScript
Code
639
2,211
'use strict'; exports.__esModule = true; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactAddonsShallowCompare = require('react-addons-shallow-compare'); var _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare); var _size = require('lodash/size'); var _size2 = _interopRequireDefault(_size); var _configUtils = require('../../utils/configUtils'); var _immutable = require('immutable'); var _immutable2 = _interopRequireDefault(_immutable); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _reactRedux = require('react-redux'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } exports.default = function (Rule) { var _class, _temp; var RuleContainer = (_temp = _class = function (_Component) { _inherits(RuleContainer, _Component); function RuleContainer(props) { _classCallCheck(this, RuleContainer); var _this = _possibleConstructorReturn(this, (RuleContainer.__proto__ || Object.getPrototypeOf(RuleContainer)).call(this, props)); _this.dummyFn = function () {}; _this.removeSelf = function () { _this.props.actions.removeRule(_this.props.path); }; _this.setField = function (field) { _this.props.actions.setField(_this.props.path, field); }; _this.setOperator = function (operator) { _this.props.actions.setOperator(_this.props.path, operator); }; _this.setOperatorOption = function (name, value) { _this.props.actions.setOperatorOption(_this.props.path, name, value); }; _this.setValue = function (delta, value, type) { _this.props.actions.setValue(_this.props.path, delta, value, type); }; _this.setValueSrc = function (delta, srcKey) { _this.props.actions.setValueSrc(_this.props.path, delta, srcKey); }; _this.pureShouldComponentUpdate = _reactAddonsPureRenderMixin2.default.shouldComponentUpdate.bind(_this); _this.componentWillReceiveProps(props); return _this; } _createClass(RuleContainer, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) {} }, { key: 'shouldComponentUpdate', //shouldComponentUpdate = this.pureShouldComponentUpdate; value: function shouldComponentUpdate(nextProps, nextState) { var prevProps = this.props; var prevState = this.state; var should = this.pureShouldComponentUpdate(nextProps, nextState); if (should) { if (prevState == nextState && prevProps != nextProps) { var chs = []; for (var k in nextProps) { var changed = nextProps[k] != prevProps[k]; if (k == 'dragging' && (nextProps.dragging.id || prevProps.dragging.id) != nextProps.id) { changed = false; //dragging another item -> ignore } if (changed) { chs.push(k); } } if (!chs.length) should = false; } } return should; } }, { key: 'render', value: function render() { var fieldConfig = (0, _configUtils.getFieldConfig)(this.props.field, this.props.config); var isGroup = fieldConfig && fieldConfig.type == '!struct'; return _react2.default.createElement( 'div', { className: 'group-or-rule-container rule-container', 'data-id': this.props.id }, [_react2.default.createElement(Rule, { key: "dragging", isForDrag: true, id: this.props.id, setField: this.dummyFn, setOperator: this.dummyFn, setOperatorOption: this.dummyFn, removeSelf: this.dummyFn, selectedField: this.props.field || null, selectedOperator: this.props.operator || null, value: this.props.value || null, valueSrc: this.props.valueSrc || null, operatorOptions: this.props.operatorOptions, config: this.props.config, treeNodesCnt: this.props.treeNodesCnt, dragging: this.props.dragging }), _react2.default.createElement(Rule, { key: this.props.id, id: this.props.id, removeSelf: this.removeSelf, setField: this.setField, setOperator: this.setOperator, setOperatorOption: this.setOperatorOption, setValue: this.setValue, setValueSrc: this.setValueSrc, selectedField: this.props.field || null, selectedOperator: this.props.operator || null, value: this.props.value || null, valueSrc: this.props.valueSrc || null, operatorOptions: this.props.operatorOptions, config: this.props.config, treeNodesCnt: this.props.treeNodesCnt, onDragStart: this.props.onDragStart, dragging: this.props.dragging })] ); } }]); return RuleContainer; }(_react.Component), _class.propTypes = { id: _propTypes2.default.string.isRequired, config: _propTypes2.default.object.isRequired, path: _propTypes2.default.any.isRequired, //instanceOf(Immutable.List) operator: _propTypes2.default.string, field: _propTypes2.default.string, actions: _propTypes2.default.object.isRequired, //{removeRule: Funciton, setField, setOperator, setOperatorOption, setValue, setValueSrc, ...} onDragStart: _propTypes2.default.func, value: _propTypes2.default.any, //depends on widget valueSrc: _propTypes2.default.any, operatorOptions: _propTypes2.default.object, treeNodesCnt: _propTypes2.default.number //connected: //dragging: PropTypes.object, //{id, x, y, w, h} }, _temp); ; var ConnectedRuleContainer = (0, _reactRedux.connect)(function (state) { return { dragging: state.dragging }; })(RuleContainer); return ConnectedRuleContainer; };
5,242
https://github.com/lawyu89/movie-recommender/blob/master/README.rdoc
Github Open Source
Open Source
MIT
null
movie-recommender
lawyu89
RDoc
Code
8
15
Great Lyfe Coding Challenge for Flight Movie Recommendation
31,717
https://github.com/dirend/SoupBinTCP.NET/blob/master/SoupBinTCP.NET/Messages/SequencedData.cs
Github Open Source
Open Source
Apache-2.0
2,021
SoupBinTCP.NET
dirend
C#
Code
68
201
using System; using System.Linq; namespace SoupBinTCP.NET.Messages { public class SequencedData : Message { public byte[] Message => Bytes.Skip(1).Take(Length - 1).ToArray(); public SequencedData(byte[] message) { const char type = 'S'; var messageLength = message.Length; var payload = new byte[messageLength + 1]; payload[0] = Convert.ToByte(type); Array.Copy(message, 0, payload, 1, messageLength); Bytes = payload; } internal SequencedData(byte[] bytes, bool addToBytesDirectly) { if (addToBytesDirectly) { Bytes = bytes; } } } }
29,671
https://github.com/nassan/Newbidder/blob/master/src/portable/MyPortableFactory.java
Github Open Source
Open Source
Apache-2.0
2,022
Newbidder
nassan
Java
Code
74
191
package portable; import com.hazelcast.nio.serialization.Portable; import com.hazelcast.nio.serialization.PortableFactory; /** * Create instances of the Portable classes. * * @author ingemar.svensson * */ public class MyPortableFactory implements PortableFactory { /** * Create an instance of a Portable matching the provided classId. */ @Override public Portable create(int classId) { if(classId == 1) { return new PortableClass(); } else if(classId == 2) { return new NestedPortableClass(); } else { throw new IllegalArgumentException(classId + " unsupported classId"); } } }
34,340
https://github.com/ventanium/ventanium/blob/master/src/vtm/net/socket_stream_server.c
Github Open Source
Open Source
BSD-2-Clause
2,020
ventanium
ventanium
C
Code
2,488
13,813
/* * Copyright (C) 2018-2020 Matthias Benkendorf */ #include "socket_stream_server.h" #include <string.h> /* memset() */ #include <vtm/core/error.h> #include <vtm/core/lang.h> #include <vtm/core/list.h> #include <vtm/core/map.h> #include <vtm/core/squeue.h> #include <vtm/net/socket_intl.h> #include <vtm/net/socket_listener.h> #include <vtm/util/atomic.h> #include <vtm/util/latch.h> #include <vtm/util/mutex.h> #include <vtm/util/spinlock.h> #include <vtm/util/thread.h> #define VTM_STREAM_SRV_ACCEPT_MAX_ERRORS 100 #define VTM_STREAM_SRV_WORKER_GET_SOCKET() worker_current_socket #define VTM_STREAM_SRV_WORKER_SET_SOCKET(SOCK) worker_current_socket = (SOCK) #define VTM_STREAM_SRV_WORKER_CLEAR_SOCKET() worker_current_socket = NULL enum vtm_socket_stream_srv_entry_type { VTM_SOCK_SRV_ACCEPTED, VTM_SOCK_SRV_READ, VTM_SOCK_SRV_WRITE, VTM_SOCK_SRV_CLOSED, VTM_SOCK_SRV_ERROR }; struct vtm_socket_stream_srv_entry { vtm_socket *sock; enum vtm_socket_stream_srv_entry_type type; struct vtm_socket_stream_srv_entry *next; }; struct vtm_socket_stream_srv { vtm_socket *socket; vtm_socket_listener *listener; struct vtm_socket_stream_srv_cbs cbs; void *usr_data; vtm_atomic_flag running; struct vtm_spinlock stop_lock; vtm_thread **threads; unsigned int thread_count; struct vtm_latch drain_prepare_latch; struct vtm_latch drain_run_latch; VTM_SQUEUE_STRUCT(struct vtm_socket_stream_srv_entry) events; vtm_mutex *events_mtx; vtm_cond *events_cond; vtm_list *release_socks; vtm_list *relay_events; vtm_map *cons; vtm_mutex *cons_mtx; }; static VTM_THREAD_LOCAL vtm_socket *worker_current_socket; /* forward declaration */ static int vtm_socket_stream_srv_create_socket(vtm_socket_stream_srv *srv, struct vtm_socket_stream_srv_opts *opts); static int vtm_socket_stream_srv_prepare_socket(vtm_socket_stream_srv *srv, struct vtm_socket_stream_srv_opts *opts); static int vtm_socket_stream_srv_main_run(vtm_socket_stream_srv *srv); static int vtm_socket_stream_srv_handle_direct(vtm_socket_stream_srv *srv, struct vtm_socket_event *events, size_t num_events, vtm_dataset *wd); static int vtm_socket_stream_srv_handle_queued(vtm_socket_stream_srv *srv, struct vtm_socket_event *events, size_t num_events); static void vtm_socket_stream_srv_drain_direct(vtm_socket_stream_srv *srv, vtm_dataset *wd); static void vtm_socket_stream_srv_drain_queued(vtm_socket_stream_srv *srv, vtm_dataset *wd); static int vtm_socket_stream_srv_accept(vtm_socket_stream_srv *srv, vtm_dataset *wd, bool direct); static int vtm_socket_stream_srv_create_event(vtm_socket_stream_srv *srv, enum vtm_socket_stream_srv_entry_type type, vtm_socket *sock); static void vtm_socket_stream_srv_add_event(vtm_socket_stream_srv *srv, struct vtm_socket_stream_srv_entry *event); static int vtm_socket_stream_srv_create_relay_event(vtm_socket_stream_srv *srv, enum vtm_socket_stream_srv_entry_type type, vtm_socket *sock); static int vtm_socket_stream_srv_workers_span(vtm_socket_stream_srv *srv, unsigned int threads); static void vtm_socket_stream_srv_workers_interrupt(vtm_socket_stream_srv *srv); static void vtm_socket_stream_srv_workers_join(vtm_socket_stream_srv *srv); static void vtm_socket_stream_srv_workers_free(vtm_socket_stream_srv *srv); static int vtm_socket_stream_srv_worker_run(void *arg); static void vtm_socket_stream_srv_worker_event(vtm_socket_stream_srv *srv, vtm_dataset *wd, struct vtm_socket_stream_srv_entry *event); static void vtm_socket_stream_srv_lock_cons(vtm_socket_stream_srv *srv); static void vtm_socket_stream_srv_unlock_cons(vtm_socket_stream_srv *srv); static void vtm_socket_stream_srv_free_sockets(vtm_socket_stream_srv *srv); /* socket functions */ static bool vtm_socket_stream_srv_sock_event(vtm_socket_stream_srv *srv, vtm_dataset *wd, struct vtm_socket_stream_srv_entry *event); static int vtm_socket_stream_srv_sock_check(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock, bool rearm); static void vtm_socket_stream_srv_sock_accepted(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock); static void vtm_socket_stream_srv_sock_can_read(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock); static void vtm_socket_stream_srv_sock_can_write(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock); static void vtm_socket_stream_srv_sock_closed(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock); static void vtm_socket_stream_srv_sock_error(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock); static void vtm_socket_stream_srv_sock_free(vtm_socket_stream_srv *srv, vtm_socket *sock); static void vtm_socket_stream_srv_sock_init_cbs(vtm_socket_stream_srv *srv, vtm_socket *sock); static int vtm_socket_stream_srv_sock_cb_update(void *stream_srv, vtm_socket *sock); static int vtm_socket_stream_srv_sock_trylock(vtm_socket *sock, unsigned int flags); static void vtm_socket_stream_srv_sock_unlock(vtm_socket *sock, unsigned int flags); vtm_socket_stream_srv* vtm_socket_stream_srv_new(void) { vtm_socket_stream_srv *srv; srv = malloc(sizeof(vtm_socket_stream_srv)); if (!srv) { vtm_err_oom(); return NULL; } memset(srv, 0, sizeof(*srv)); vtm_spinlock_init(&srv->stop_lock); return srv; } void vtm_socket_stream_srv_free(vtm_socket_stream_srv *srv) { free(srv); } void* vtm_socket_stream_srv_get_usr_data(vtm_socket_stream_srv *srv) { return srv->usr_data; } void vtm_socket_stream_srv_set_usr_data(vtm_socket_stream_srv *srv, void *data) { srv->usr_data = data; } int vtm_socket_stream_srv_run(vtm_socket_stream_srv *srv, struct vtm_socket_stream_srv_opts *opts) { int rc; /* lock for init process */ vtm_spinlock_lock(&srv->stop_lock); /* set callbacks */ srv->cbs = opts->cbs; /* create socket */ rc = vtm_socket_stream_srv_create_socket(srv, opts); if (rc != VTM_OK) goto unlock; /* prepare socket */ rc = vtm_socket_stream_srv_prepare_socket(srv, opts); if (rc != VTM_OK) goto clean_socket; /* create socket listener */ srv->listener = vtm_socket_listener_new(opts->events); if (!srv->listener) { rc = vtm_err_get_code(); goto clean_socket; } /* add server socket to listener */ vtm_socket_set_state(srv->socket, VTM_SOCK_STAT_NBL_READ); rc = vtm_socket_listener_add(srv->listener, srv->socket); if (rc != VTM_OK) goto clean_listener; /* create map for connections */ srv->cons = vtm_map_new(VTM_ELEM_POINTER, VTM_ELEM_POINTER, 64); if (!srv->cons) { rc = vtm_err_get_code(); goto clean_listener; } /* relay event list */ srv->relay_events = vtm_list_new(VTM_ELEM_POINTER, 8); if (!srv->relay_events) { rc = vtm_err_get_code(); goto clean; } vtm_list_set_free_func(srv->relay_events, free); if (opts->threads > 0) { /* create synch helpers */ vtm_latch_init(&srv->drain_prepare_latch, opts->threads); vtm_latch_init(&srv->drain_run_latch, 1); srv->cons_mtx = vtm_mutex_new(); if (!srv->cons_mtx) goto clean; /* create worker queue */ VTM_SQUEUE_INIT(srv->events); srv->events_mtx = vtm_mutex_new(); if (!srv->events_mtx) { rc = vtm_err_get_code(); goto clean; } srv->events_cond = vtm_cond_new(); if (!srv->events_cond) { rc = vtm_err_get_code(); goto clean; } /* releaseable sockets */ srv->release_socks = vtm_list_new(VTM_ELEM_POINTER, 8); if (!srv->release_socks) { rc = vtm_err_get_code(); goto clean; } } /* spawn workers */ vtm_atomic_flag_set(srv->running); rc = vtm_socket_stream_srv_workers_span(srv, opts->threads); if (rc != VTM_OK) goto clean; /* notify server ready */ if (srv->cbs.server_ready) srv->cbs.server_ready(srv, opts); /* init process finished */ vtm_spinlock_unlock(&srv->stop_lock); /* run queue listener */ rc = vtm_socket_stream_srv_main_run(srv); /* end for workers */ vtm_socket_stream_srv_workers_interrupt(srv); vtm_socket_stream_srv_workers_join(srv); vtm_socket_stream_srv_workers_free(srv); /* cleanup */ vtm_spinlock_lock(&srv->stop_lock); clean: if (opts->threads > 0) { vtm_socket_stream_srv_free_sockets(srv); VTM_SQUEUE_CLEAR(srv->events, struct vtm_socket_stream_srv_entry, free); vtm_cond_free(srv->events_cond); vtm_mutex_free(srv->events_mtx); vtm_mutex_free(srv->cons_mtx); vtm_list_free(srv->release_socks); vtm_latch_release(&srv->drain_prepare_latch); vtm_latch_release(&srv->drain_run_latch); } vtm_list_free(srv->relay_events); vtm_map_free(srv->cons); clean_listener: vtm_socket_listener_remove(srv->listener, srv->socket); vtm_socket_listener_free(srv->listener); srv->listener = NULL; clean_socket: vtm_socket_close(srv->socket); vtm_socket_free(srv->socket); unlock: vtm_spinlock_unlock(&srv->stop_lock); return rc; } int vtm_socket_stream_srv_stop(vtm_socket_stream_srv *srv) { int rc; vtm_spinlock_lock(&srv->stop_lock); vtm_atomic_flag_unset(srv->running); if (srv->listener) rc = vtm_socket_listener_interrupt(srv->listener); else rc = VTM_E_INVALID_STATE; vtm_spinlock_unlock(&srv->stop_lock); return rc; } static int vtm_socket_stream_srv_create_socket(vtm_socket_stream_srv *srv, struct vtm_socket_stream_srv_opts *opts) { struct vtm_socket_tls_opts tls_opts; if (opts->tls.enabled) { tls_opts.is_server = true; tls_opts.cert_file = opts->tls.cert_file; tls_opts.key_file = opts->tls.key_file; tls_opts.ciphers = opts->tls.ciphers; srv->socket = vtm_socket_tls_new(opts->addr.family, &tls_opts); } else { srv->socket = vtm_socket_new(opts->addr.family, VTM_SOCK_TYPE_STREAM); } if (!srv->socket) return VTM_ERROR; return VTM_OK; } static int vtm_socket_stream_srv_prepare_socket(vtm_socket_stream_srv *srv, struct vtm_socket_stream_srv_opts *opts) { int rc; /* set non-blocking */ rc = vtm_socket_set_opt(srv->socket, VTM_SOCK_OPT_NONBLOCKING, (bool[]) {true}, sizeof(bool)); if (rc != VTM_OK) return rc; /* bind socket */ rc = vtm_socket_bind(srv->socket, opts->addr.host, opts->addr.port); if (rc != VTM_OK) return rc; /* listen socket*/ return vtm_socket_listen(srv->socket, opts->backlog); } static int vtm_socket_stream_srv_main_run(vtm_socket_stream_srv *srv) { int rc; struct vtm_socket_event *events; size_t num_events; vtm_dataset *wd; /* GCC warns about uninitialized usage if optimizations turned on */ wd = NULL; if (srv->thread_count == 0) { wd = vtm_dataset_new(); if (!wd) return vtm_err_get_code(); if (srv->cbs.worker_init) srv->cbs.worker_init(srv, wd); } while (vtm_atomic_flag_isset(srv->running)) { rc = vtm_socket_listener_run(srv->listener, &events, &num_events); if (rc != VTM_OK) goto finish; if (srv->thread_count == 0) rc = vtm_socket_stream_srv_handle_direct(srv, events, num_events, wd); else rc = vtm_socket_stream_srv_handle_queued(srv, events, num_events); if (rc != VTM_OK) goto finish; } finish: vtm_atomic_flag_unset(srv->running); if (srv->thread_count == 0) { vtm_socket_stream_srv_drain_direct(srv, wd); if (srv->cbs.worker_end) srv->cbs.worker_end(srv, wd); vtm_dataset_free(wd); } else { vtm_socket_stream_srv_drain_queued(srv, wd); } return rc; } static int vtm_socket_stream_srv_handle_direct(vtm_socket_stream_srv *srv, struct vtm_socket_event *events, size_t num_events, vtm_dataset *wd) { int rc; size_t i; vtm_socket *sock; struct vtm_socket_stream_srv_entry *event; /* handle relay events */ while (vtm_list_size(srv->relay_events) > 0) { event = vtm_list_get_pointer(srv->relay_events, 0); VTM_STREAM_SRV_WORKER_SET_SOCKET(event->sock); switch (event->type) { case VTM_SOCK_SRV_CLOSED: vtm_socket_stream_srv_sock_closed(srv, wd, event->sock); break; case VTM_SOCK_SRV_ERROR: vtm_socket_stream_srv_sock_error(srv, wd, event->sock); break; default: break; } VTM_STREAM_SRV_WORKER_CLEAR_SOCKET(); vtm_list_remove(srv->relay_events, 0); free(event); } /* handle events from listener */ for (i=0; i < num_events; i++) { sock = events[i].sock; VTM_STREAM_SRV_WORKER_SET_SOCKET(sock); if (events[i].events & VTM_SOCK_EVT_CLOSED) { vtm_socket_close(sock); vtm_socket_stream_srv_sock_closed(srv, wd, sock); } else if (events[i].events & VTM_SOCK_EVT_ERROR) { vtm_socket_stream_srv_sock_error(srv, wd, sock); } else { if (events[i].events & VTM_SOCK_EVT_READ) { if (sock == srv->socket) { rc = vtm_socket_stream_srv_accept(srv, wd, true); if (rc != VTM_OK) { VTM_STREAM_SRV_WORKER_CLEAR_SOCKET(); return rc; } continue; } if (vtm_socket_get_state(sock) & VTM_SOCK_STAT_WRITE_AGAIN_WHEN_READABLE) { vtm_socket_stream_srv_sock_can_write(srv, wd, sock); } else { vtm_socket_stream_srv_sock_can_read(srv, wd, sock); } } if (events[i].events & VTM_SOCK_EVT_WRITE) { if (vtm_socket_get_state(sock) & VTM_SOCK_STAT_READ_AGAIN_WHEN_WRITEABLE) { vtm_socket_stream_srv_sock_can_read(srv, wd, sock); } else { vtm_socket_stream_srv_sock_can_write(srv, wd, sock); } } } } VTM_STREAM_SRV_WORKER_CLEAR_SOCKET(); return VTM_OK; } static int vtm_socket_stream_srv_handle_queued(vtm_socket_stream_srv *srv, struct vtm_socket_event *events, size_t num_events) { int rc, errc; size_t i, count; vtm_socket *sock, *acc; struct vtm_socket_stream_srv_entry *event; enum vtm_socket_stream_srv_entry_type event_type; errc = 0; acc = NULL; vtm_mutex_lock(srv->events_mtx); /* check for releaseable sockets */ count = vtm_list_size(srv->release_socks); for (i=0; i < count; i++) { sock = vtm_list_get_pointer(srv->release_socks, i); vtm_socket_enable_free_on_unref(sock); vtm_socket_unref(sock); } vtm_list_clear(srv->release_socks); /* process relay events */ while (vtm_list_size(srv->relay_events) > 0) { event = vtm_list_get_pointer(srv->relay_events, 0); vtm_list_remove(srv->relay_events, 0); VTM_SQUEUE_ADD(srv->events, event); } /* process events from listener */ for (i=0; i < num_events; i++) { sock = events[i].sock; /* closed */ if (events[i].events & VTM_SOCK_EVT_CLOSED) { vtm_socket_close(sock); rc = vtm_socket_stream_srv_create_event(srv, VTM_SOCK_SRV_CLOSED, sock); if (rc != VTM_OK) { errc++; break; } continue; } /* error */ if (events[i].events & VTM_SOCK_EVT_ERROR) { rc = vtm_socket_stream_srv_create_event(srv, VTM_SOCK_SRV_ERROR, sock); if (rc != VTM_OK) { errc++; break; } continue; } /* read */ if (events[i].events & VTM_SOCK_EVT_READ) { if (sock == srv->socket) { acc = sock; continue; } event_type = (vtm_socket_get_state(sock) & VTM_SOCK_STAT_WRITE_AGAIN_WHEN_READABLE) ? VTM_SOCK_SRV_WRITE : VTM_SOCK_SRV_READ; rc = vtm_socket_stream_srv_create_event(srv, event_type, sock); if (rc != VTM_OK) { errc++; break; } } /* write */ if (events[i].events & VTM_SOCK_EVT_WRITE) { event_type = (vtm_socket_get_state(sock) & VTM_SOCK_STAT_READ_AGAIN_WHEN_WRITEABLE) ? VTM_SOCK_SRV_READ : VTM_SOCK_SRV_WRITE; rc = vtm_socket_stream_srv_create_event(srv, event_type, sock); if (rc != VTM_OK) { errc++; break; } } } vtm_cond_signal_all(srv->events_cond); vtm_mutex_unlock(srv->events_mtx); if (errc > 0) return VTM_ERROR; if (acc) { rc = vtm_socket_stream_srv_accept(srv, NULL, false); if (rc != VTM_OK) return rc; } return VTM_OK; } static void vtm_socket_stream_srv_drain_direct(vtm_socket_stream_srv *srv, vtm_dataset *wd) { vtm_list *entries; struct vtm_map_entry *entry; size_t i, count; vtm_socket *sock; entries = vtm_map_entryset(srv->cons); if (!entries) return; count = vtm_list_size(entries); for (i=0; i < count; i++) { entry = vtm_list_get_pointer(entries,i); sock = entry->key.elem_pointer; vtm_socket_close(sock); vtm_socket_stream_srv_sock_closed(srv, wd, sock); } vtm_list_free(entries); } static void vtm_socket_stream_srv_drain_queued(vtm_socket_stream_srv *srv, vtm_dataset *wd) { int rc; vtm_list *entries; struct vtm_socket_stream_srv_entry *event; struct vtm_map_entry *entry; size_t i, count; vtm_socket *sock; /* wait for all threads to end event processing */ vtm_cond_signal_all(srv->events_cond); vtm_latch_await(&srv->drain_prepare_latch); vtm_socket_stream_srv_lock_cons(srv); vtm_mutex_lock(srv->events_mtx); /* clear all pending events */ VTM_SQUEUE_FOR_EACH(srv->events, event) vtm_socket_unref(event->sock); VTM_SQUEUE_CLEAR(srv->events, struct vtm_socket_stream_srv_entry, free); entries = vtm_map_entryset(srv->cons); if (!entries) goto unlock; count = vtm_list_size(entries); for (i=0; i < count; i++) { entry = vtm_list_get_pointer(entries,i); sock = entry->key.elem_pointer; vtm_socket_close(sock); rc = vtm_socket_stream_srv_create_event(srv, VTM_SOCK_SRV_CLOSED, sock); if (rc != VTM_OK) goto unlock; } vtm_list_free(entries); unlock: vtm_mutex_unlock(srv->events_mtx); vtm_socket_stream_srv_unlock_cons(srv); /* let all waiting threads process close events */ vtm_latch_count(&srv->drain_run_latch); } static int vtm_socket_stream_srv_create_event(vtm_socket_stream_srv *srv, enum vtm_socket_stream_srv_entry_type type, vtm_socket *sock) { struct vtm_socket_stream_srv_entry *event; event = malloc(sizeof(*event)); if (!event) { vtm_err_oom(); return vtm_err_get_code(); } vtm_socket_ref(sock); event->sock = sock; event->type = type; VTM_SQUEUE_ADD(srv->events, event); return VTM_OK; } static void vtm_socket_stream_srv_add_event(vtm_socket_stream_srv *srv, struct vtm_socket_stream_srv_entry *event) { vtm_socket_ref(event->sock); vtm_mutex_lock(srv->events_mtx); VTM_SQUEUE_ADD(srv->events, event); vtm_cond_signal(srv->events_cond); vtm_mutex_unlock(srv->events_mtx); } static int vtm_socket_stream_srv_create_relay_event(vtm_socket_stream_srv *srv, enum vtm_socket_stream_srv_entry_type type, vtm_socket *sock) { struct vtm_socket_stream_srv_entry *event; event = malloc(sizeof(*event)); if (!event) { vtm_err_oom(); return vtm_err_get_code(); } event->type = type; event->sock = sock; if (srv->thread_count > 0) vtm_mutex_lock(srv->events_mtx); vtm_list_add_va(srv->relay_events, event); if (srv->thread_count > 0) vtm_mutex_unlock(srv->events_mtx); return VTM_OK; } static int vtm_socket_stream_srv_accept(vtm_socket_stream_srv *srv, vtm_dataset *wd, bool direct) { int rc, errc; vtm_socket *client; struct vtm_socket_stream_srv_entry *node; errc = 0; while (true) { rc = vtm_socket_accept(srv->socket, &client); switch (rc) { case VTM_OK: errc = 0; break; case VTM_E_IO_AGAIN: return vtm_socket_listener_rearm(srv->listener, srv->socket); default: if (++errc < VTM_STREAM_SRV_ACCEPT_MAX_ERRORS) continue; return vtm_socket_listener_rearm(srv->listener, srv->socket); } if (direct) { vtm_socket_stream_srv_sock_accepted(srv, wd, client); } else { node = malloc(sizeof(*node)); if (!node) { vtm_err_oom(); return vtm_err_get_code(); } node->sock = client; node->type = VTM_SOCK_SRV_ACCEPTED; vtm_socket_make_threadsafe(client); vtm_socket_stream_srv_add_event(srv, node); } } VTM_ABORT_NOT_REACHABLE; return VTM_ERROR; } static int vtm_socket_stream_srv_workers_span(vtm_socket_stream_srv *srv, unsigned int threads) { unsigned int i; srv->thread_count = threads; if (srv->thread_count == 0) return VTM_OK; srv->threads = calloc(srv->thread_count, sizeof(vtm_thread*)); if (!srv->threads) return VTM_ERROR; for (i=0; i < srv->thread_count; i++) { srv->threads[i] = vtm_thread_new(vtm_socket_stream_srv_worker_run, srv); if (!srv->threads[i]) return VTM_ERROR; } return VTM_OK; } static void vtm_socket_stream_srv_workers_interrupt(vtm_socket_stream_srv *srv) { if (!srv->events_cond) return; vtm_cond_signal_all(srv->events_cond); } static void vtm_socket_stream_srv_workers_join(vtm_socket_stream_srv *srv) { vtm_thread *th; unsigned int i; if (srv->thread_count == 0) return; for (i=0; i < srv->thread_count; i++) { th = srv->threads[i]; vtm_thread_join(th); } } static void vtm_socket_stream_srv_workers_free(vtm_socket_stream_srv *srv) { vtm_thread *th; unsigned int i; if (srv->thread_count == 0) return; for (i=0; i < srv->thread_count; i++) { th = srv->threads[i]; vtm_thread_free(th); } free(srv->threads); } static int vtm_socket_stream_srv_worker_run(void *arg) { vtm_dataset *wd; struct vtm_socket_stream_srv_entry *event; vtm_socket_stream_srv *srv; srv = arg; wd = vtm_dataset_new(); if (!wd) return vtm_err_get_code(); if (srv->cbs.worker_init) srv->cbs.worker_init(srv, wd); /* normal operation */ while (vtm_atomic_flag_isset(srv->running)) { vtm_mutex_lock(srv->events_mtx); while (VTM_SQUEUE_IS_EMPTY(srv->events)) { if (!vtm_atomic_flag_isset(srv->running)) { vtm_mutex_unlock(srv->events_mtx); goto finish; } vtm_cond_wait(srv->events_cond, srv->events_mtx); } VTM_SQUEUE_POLL(srv->events, event); vtm_mutex_unlock(srv->events_mtx); vtm_socket_stream_srv_worker_event(srv, wd, event); } finish: /* wait for draining */ vtm_latch_count(&srv->drain_prepare_latch); vtm_latch_await(&srv->drain_run_latch); /* draining */ while (true) { vtm_mutex_lock(srv->events_mtx); VTM_SQUEUE_POLL(srv->events, event); vtm_mutex_unlock(srv->events_mtx); if (!event) break; vtm_socket_stream_srv_worker_event(srv, wd, event); } if (srv->cbs.worker_end) srv->cbs.worker_end(srv, wd); vtm_dataset_free(wd); return VTM_OK; } static VTM_INLINE void vtm_socket_stream_srv_worker_event(vtm_socket_stream_srv *srv, vtm_dataset *wd, struct vtm_socket_stream_srv_entry *event) { bool processed; vtm_socket *sock; sock = event->sock; VTM_STREAM_SRV_WORKER_SET_SOCKET(sock); processed = vtm_socket_stream_srv_sock_event(srv, wd, event); VTM_STREAM_SRV_WORKER_CLEAR_SOCKET(); if (processed) free(event); else vtm_socket_stream_srv_add_event(srv, event); vtm_socket_unref(sock); } static VTM_INLINE bool vtm_socket_stream_srv_sock_event(vtm_socket_stream_srv *srv, vtm_dataset *wd, struct vtm_socket_stream_srv_entry *event) { int rc; switch (event->type) { case VTM_SOCK_SRV_ACCEPTED: rc = vtm_socket_stream_srv_sock_trylock(event->sock, VTM_SOCK_STAT_READ_LOCKED); VTM_ASSERT(rc == VTM_OK); vtm_socket_stream_srv_sock_accepted(srv, wd, event->sock); vtm_socket_stream_srv_sock_unlock(event->sock, VTM_SOCK_STAT_READ_LOCKED); break; case VTM_SOCK_SRV_CLOSED: rc = vtm_socket_stream_srv_sock_trylock(event->sock, VTM_SOCK_STAT_READ_LOCKED | VTM_SOCK_STAT_WRITE_LOCKED); if (rc != VTM_OK) return false; vtm_socket_stream_srv_sock_closed(srv, wd, event->sock); vtm_socket_stream_srv_sock_unlock(event->sock, VTM_SOCK_STAT_READ_LOCKED | VTM_SOCK_STAT_WRITE_LOCKED); break; case VTM_SOCK_SRV_ERROR: rc = vtm_socket_stream_srv_sock_trylock(event->sock, VTM_SOCK_STAT_READ_LOCKED | VTM_SOCK_STAT_WRITE_LOCKED); if (rc != VTM_OK) return false; vtm_socket_stream_srv_sock_error(srv, wd, event->sock); vtm_socket_stream_srv_sock_unlock(event->sock, VTM_SOCK_STAT_READ_LOCKED | VTM_SOCK_STAT_WRITE_LOCKED); break; case VTM_SOCK_SRV_READ: if (vtm_socket_get_state(event->sock) & VTM_SOCK_STAT_CLOSED) return true; rc = vtm_socket_stream_srv_sock_trylock(event->sock, VTM_SOCK_STAT_READ_LOCKED); if (rc != VTM_OK) return true; vtm_socket_stream_srv_sock_can_read(srv, wd, event->sock); vtm_socket_stream_srv_sock_unlock(event->sock, VTM_SOCK_STAT_READ_LOCKED); break; case VTM_SOCK_SRV_WRITE: if (vtm_socket_get_state(event->sock) & VTM_SOCK_STAT_CLOSED) return true; rc = vtm_socket_stream_srv_sock_trylock(event->sock, VTM_SOCK_STAT_WRITE_LOCKED); if (rc != VTM_OK) return true; vtm_socket_stream_srv_sock_can_write(srv, wd, event->sock); vtm_socket_stream_srv_sock_unlock(event->sock, VTM_SOCK_STAT_WRITE_LOCKED); break; } return true; } static VTM_INLINE int vtm_socket_stream_srv_sock_check(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock, bool rearm) { int rc; unsigned int state; eval: state = vtm_socket_get_state(sock); if (state & VTM_SOCK_STAT_ERR) { vtm_socket_stream_srv_sock_error(srv, wd, sock); return VTM_E_IO_UNKNOWN; } else if (state & VTM_SOCK_STAT_CLOSED) { vtm_socket_stream_srv_sock_closed(srv, wd, sock); return VTM_E_IO_CLOSED; } else if (state & VTM_SOCK_STAT_HUP) { vtm_socket_close(sock); vtm_socket_stream_srv_sock_closed(srv, wd, sock); return VTM_E_IO_CLOSED; } if (rearm) { rc = vtm_socket_listener_rearm(srv->listener, sock); if (rc != VTM_OK) { vtm_socket_close(sock); goto eval; } } return VTM_OK; } static VTM_INLINE void vtm_socket_stream_srv_sock_accepted(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock) { int rc; /* check if NONBLOCKING can be activated */ rc = vtm_socket_set_opt(sock, VTM_SOCK_OPT_NONBLOCKING, (bool[]) {true}, sizeof(bool)); if (rc != VTM_OK) { vtm_socket_close(sock); vtm_socket_stream_srv_sock_free(srv, sock); return; } /* set stream srv callbacks */ vtm_socket_stream_srv_sock_init_cbs(srv, sock); /* run CONNECTED callback */ if (srv->cbs.sock_connected) srv->cbs.sock_connected(srv, wd, sock); /* check if socket was closed or got error in callback */ rc = vtm_socket_stream_srv_sock_check(srv, wd, sock, false); if (rc != VTM_OK) return; /* register socket to listener and add to connections */ vtm_socket_set_state(sock, VTM_SOCK_STAT_NBL_READ); vtm_socket_stream_srv_lock_cons(srv); rc = vtm_socket_listener_add(srv->listener, sock); if (rc == VTM_OK) vtm_map_put_va(srv->cons, sock, sock); vtm_socket_stream_srv_unlock_cons(srv); /* check for error, socket listener max could be reached */ if (rc != VTM_OK) { /* run DISCONNECTED callback */ vtm_socket_close(sock); if (srv->cbs.sock_disconnected) srv->cbs.sock_disconnected(srv, wd, sock); vtm_socket_stream_srv_sock_free(srv, sock); } } static VTM_INLINE void vtm_socket_stream_srv_sock_can_read(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock) { if (srv->cbs.sock_can_read) srv->cbs.sock_can_read(srv, wd, sock); vtm_socket_stream_srv_sock_check(srv, wd, sock, true); } static VTM_INLINE void vtm_socket_stream_srv_sock_can_write(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock) { if (srv->cbs.sock_can_write) srv->cbs.sock_can_write(srv, wd, sock); vtm_socket_stream_srv_sock_check(srv, wd, sock, true); } static VTM_INLINE void vtm_socket_stream_srv_sock_closed(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock) { bool removed; vtm_socket_stream_srv_lock_cons(srv); removed = vtm_map_remove_va(srv->cons, sock); vtm_socket_stream_srv_unlock_cons(srv); if (!removed) return; vtm_socket_listener_remove(srv->listener, sock); if (srv->cbs.sock_disconnected) srv->cbs.sock_disconnected(srv, wd, sock); vtm_socket_stream_srv_sock_free(srv, sock); } static VTM_INLINE void vtm_socket_stream_srv_sock_error(vtm_socket_stream_srv *srv, vtm_dataset *wd, vtm_socket *sock) { if (srv->cbs.sock_error) srv->cbs.sock_error(srv, wd, sock); vtm_socket_close(sock); vtm_socket_stream_srv_sock_closed(srv, wd, sock); } static VTM_INLINE void vtm_socket_stream_srv_sock_free(vtm_socket_stream_srv *srv, vtm_socket *sock) { if (srv->thread_count == 0) { vtm_socket_free(sock); return; } vtm_socket_ref(sock); vtm_mutex_lock(srv->events_mtx); vtm_list_add_va(srv->release_socks, sock); vtm_mutex_unlock(srv->events_mtx); vtm_socket_listener_interrupt(srv->listener); } static void vtm_socket_stream_srv_sock_init_cbs(vtm_socket_stream_srv *srv, vtm_socket *sock) { sock->stream_srv = srv; sock->vtm_socket_update_stream_srv = vtm_socket_stream_srv_sock_cb_update; } static int vtm_socket_stream_srv_sock_cb_update(void *stream_srv, vtm_socket *sock) { vtm_socket_stream_srv *srv; if (VTM_STREAM_SRV_WORKER_GET_SOCKET() == sock) return VTM_OK; srv = stream_srv; vtm_socket_lock(sock); if (sock->state & VTM_SOCK_STAT_ERR) { vtm_socket_ref(sock); vtm_socket_stream_srv_create_relay_event(srv, VTM_SOCK_SRV_ERROR, sock); vtm_socket_listener_interrupt(srv->listener); } else if (sock->state & VTM_SOCK_STAT_CLOSED) { vtm_socket_ref(sock); vtm_socket_stream_srv_create_relay_event(srv, VTM_SOCK_SRV_CLOSED, sock); vtm_socket_listener_interrupt(srv->listener); } else if (sock->state & VTM_SOCK_STAT_HUP) { vtm_socket_ref(sock); vtm_socket_close(sock); vtm_socket_stream_srv_create_relay_event(srv, VTM_SOCK_SRV_CLOSED, sock); vtm_socket_listener_interrupt(srv->listener); } else if (sock->state & (VTM_SOCK_STAT_READ_AGAIN | VTM_SOCK_STAT_READ_AGAIN_WHEN_WRITEABLE | VTM_SOCK_STAT_WRITE_AGAIN | VTM_SOCK_STAT_WRITE_AGAIN_WHEN_READABLE)) { vtm_socket_listener_rearm(srv->listener, sock); } vtm_socket_unlock(sock); return VTM_OK; } static VTM_INLINE int vtm_socket_stream_srv_sock_trylock(vtm_socket *sock, unsigned int flags) { int rc; vtm_socket_lock(sock); if (sock->state & flags) { rc = VTM_ERROR; } else { sock->state |= flags; rc = VTM_OK; } vtm_socket_unlock(sock); return rc; } static VTM_INLINE void vtm_socket_stream_srv_sock_unlock(vtm_socket *sock, unsigned int flags) { vtm_socket_lock(sock); sock->state &= ~flags; vtm_socket_unlock(sock); } static VTM_INLINE void vtm_socket_stream_srv_lock_cons(vtm_socket_stream_srv *srv) { if (srv->cons_mtx) vtm_mutex_lock(srv->cons_mtx); } static VTM_INLINE void vtm_socket_stream_srv_unlock_cons(vtm_socket_stream_srv *srv) { if (srv->cons_mtx) vtm_mutex_unlock(srv->cons_mtx); } static void vtm_socket_stream_srv_free_sockets(vtm_socket_stream_srv *srv) { size_t i, count; count = vtm_list_size(srv->release_socks); for (i=0; i < count; i++) vtm_socket_free(vtm_list_get_pointer(srv->release_socks, i)); }
29,519
https://github.com/panoramicdata/Errigal.Api/blob/master/Errigal.Api/Data/Ticketer/Port.cs
Github Open Source
Open Source
MIT
null
Errigal.Api
panoramicdata
C#
Code
50
145
using System.Collections.Generic; using System.Runtime.Serialization; namespace Errigal.Api.Data.Ticketer { [DataContract] public class Port : NamedIdentifiedItem { [DataMember(Name = "index")] public int Index { get; set; } [DataMember(Name = "status")] public string Status { get; set; } = string.Empty; [DataMember(Name = "services")] public List<CustomerService> Services { get; set; } = new(); } }
7,819
https://github.com/PillWatcher/pillwatcher-dpb-patient-service/blob/master/src/main/java/br/com/pillwatcher/dpb/repositories/MedicineRepository.java
Github Open Source
Open Source
MIT
2,020
pillwatcher-dpb-patient-service
PillWatcher
Java
Code
28
137
package br.com.pillwatcher.dpb.repositories; import br.com.pillwatcher.dpb.entities.Medicine; import io.swagger.model.DosageTypeEnum; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface MedicineRepository extends JpaRepository<Medicine, Long> { Optional<Medicine> findByDosageAndAndDosageTypeAndName(final Integer dosage, final DosageTypeEnum dosageType, final String name); }
33,885
https://github.com/ERNICommunity/at11/blob/master/parsers/sevcenkova/klubovna.ts
Github Open Source
Open Source
Unlicense
2,020
at11
ERNICommunity
TypeScript
Code
92
255
import { IMenuItem } from "../IMenuItem"; import { IParser } from "../IParser"; import { Sme } from "../sme"; import { parsePrice } from "../parserUtil"; export class Klubovna extends Sme implements IParser { public parse(html: string, date: Date, doneCallback: (menu: IMenuItem[]) => void): void { const menuItems = super.parseBase(html, date); if (menuItems.length > 0) { // first item is just date menuItems.shift(); // first 2 items are soup menuItems[0].isSoup = true; menuItems.forEach(item=> { const result = parsePrice(item.text); item.price = result.price; item.text = result.text.replace(/^.*\|\s+/, "").replace(/\(obsahuje:/, ""); }); menuItems[1].isSoup = true; } doneCallback(menuItems); } }
2,667
https://github.com/mvysny/karibu-tools/blob/master/testsuite/src/main/kotlin/RouterUtilsTest.kt
Github Open Source
Open Source
Apache-2.0
2,021
karibu-tools
mvysny
Kotlin
Code
539
2,249
package com.github.mvysny.kaributools import com.github.mvysny.dynatest.DynaNodeGroup import com.github.mvysny.dynatest.DynaTest import com.github.mvysny.dynatest.expectList import com.github.mvysny.dynatest.expectThrows import com.github.mvysny.kaributesting.v10.* import com.vaadin.flow.component.UI import com.vaadin.flow.component.orderedlayout.VerticalLayout import com.vaadin.flow.router.* import kotlin.test.expect fun DynaNodeGroup.routerUtilsTests() { group("QueryParameters") { test("get") { expect(null) { QueryParameters.empty()["foo"] } expect("bar") { QueryParameters("foo=bar")["foo"] } } test("get fails with multiple parameters") { expectThrows(IllegalStateException::class, "Multiple values present for foo: [bar, baz]") { QueryParameters("foo=bar&foo=baz")["foo"] } } test("getValues") { expectList() { QueryParameters.empty().getValues("foo") } expectList("bar") { QueryParameters("foo=bar") .getValues("foo") } expectList("bar", "baz") { QueryParameters("foo=bar&foo=baz") .getValues("foo") } } test("isEmpty") { expect(true) { QueryParameters.empty().isEmpty } expect(false) { QueryParameters("foo=bar").isEmpty } } test("isNotEmpty") { expect(false) { QueryParameters.empty().isNotEmpty } expect(true) { QueryParameters("foo=bar").isNotEmpty } } } group("navigation tests") { beforeEach { MockVaadin.setup(Routes().apply { routes.addAll(listOf( TestingView::class.java, TestingParametrizedView::class.java, RootView::class.java, TestingParametrizedView2::class.java, TestingView2::class.java )) }) _expectNone<TestingView>() _expectNone<TestingParametrizedView>() } afterEach { MockVaadin.tearDown() } group("navigateToView") { test("reified") { navigateTo<TestingView>() _get<TestingView>() } test("reified doesn't work on parametrized views") { expectThrows(IllegalArgumentException::class, "requires a parameter") { // it fails somewhere deeply in Vaadin Flow navigateTo<TestingParametrizedView>() } _expectNone<TestingParametrizedView>() } test("class") { navigateTo(TestingView::class) _get<TestingView>() } test("parametrized") { navigateTo(TestingParametrizedView::class, 1L) _get<TestingParametrizedView>() } } group("routerLinks") { test("no target") { expect("") { RouterLink().href } } test("simple target") { expect("testing") { RouterLink( "foo", TestingView::class.java).href } } test("parametrized target with missing param") { expectThrows(IllegalArgumentException::class, "requires a parameter") { RouterLink("foo", TestingParametrizedView::class.java) } } test("parametrized target") { expect("testingp/1") { RouterLink("foo", TestingParametrizedView::class.java, 1L).href } } test("navigateTo") { RouterLink("foo", TestingView::class.java).navigateTo() _expectOne<TestingView>() } } group("getRouteUrl") { test("no target") { expect("") { getRouteUrl(RootView::class) } } test("no target + query parameters") { expect("?foo=bar") { getRouteUrl(RootView::class, "foo=bar") } } test("simple target") { expect("testing") { getRouteUrl(TestingView::class) } } test("simple target + query parameters") { expect("testing?foo=bar") { getRouteUrl(TestingView::class, "foo=bar") } } test("parametrized target with missing param") { expectThrows(IllegalArgumentException::class, "requires a parameter") { getRouteUrl(TestingParametrizedView::class) } } } group("routeClass") { test("navigating to root view") { UI.getCurrent().navigate(TestingView::class.java) var called = false UI.getCurrent().addAfterNavigationListener { called = true expect(RootView::class.java) { it.routeClass } } UI.getCurrent().navigate(RootView::class.java) expect(true) { called } } test("navigating to TestingView") { var called = false UI.getCurrent().addAfterNavigationListener { called = true expect(TestingView::class.java) { it.routeClass } } UI.getCurrent().navigate(TestingView::class.java) expect(true) { called } } test("navigating to TestingView2") { var called = false UI.getCurrent().addAfterNavigationListener { called = true expect(TestingView::class.java) { it.routeClass } } UI.getCurrent().navigate(TestingView::class.java) expect(true) { called } } test("navigating to TestingParametrizedView") { var called = false UI.getCurrent().addAfterNavigationListener { called = true expect(TestingParametrizedView::class.java) { it.routeClass } } UI.getCurrent().navigate(TestingParametrizedView::class.java, 25L) expect(true) { called } } test("navigating to TestingParametrizedView2") { var called = false UI.getCurrent().addAfterNavigationListener { called = true expect(TestingParametrizedView2::class.java) { it.routeClass } } UI.getCurrent().navigate(TestingParametrizedView2::class.java, 25L) expect(true) { called } } test("location") { expect(RootView::class.java) { Location("").getRouteClass() } expect(TestingView::class.java) { Location("testing").getRouteClass() } expect(TestingView2::class.java) { Location("testing/foo/bar").getRouteClass() } expect(TestingParametrizedView::class.java) { Location("testingp/20").getRouteClass() } expect(TestingParametrizedView2::class.java) { Location("testingp/with/subpath/20").getRouteClass() } expect(null) { Location("nonexisting").getRouteClass() } expect(TestingView::class.java) { Location("testing?foo=bar").getRouteClass() } } } test("UI.currentViewLocation") { var expectedLocation = if (VaadinVersion.get.major > 14) "" else "." var expectedLocationBefore = expectedLocation UI.getCurrent().addBeforeLeaveListener { expect(expectedLocationBefore) { UI.getCurrent().currentViewLocation.pathWithQueryParameters } } UI.getCurrent().addBeforeEnterListener { expect(expectedLocationBefore) { UI.getCurrent().currentViewLocation.pathWithQueryParameters } } UI.getCurrent().addAfterNavigationListener { expect(expectedLocation) { UI.getCurrent().currentViewLocation.pathWithQueryParameters } } expect(expectedLocation) { UI.getCurrent().currentViewLocation.pathWithQueryParameters } expectedLocation = "testing" navigateTo<TestingView>() expect("testing") { UI.getCurrent().currentViewLocation.pathWithQueryParameters } expectedLocationBefore = "testing" } } } class AppLayout : VerticalLayout(), RouterLayout @Route("") class RootView : VerticalLayout() @Route("testing", layout = AppLayout::class) class TestingView : VerticalLayout() @Route("testing/foo/bar") class TestingView2 : VerticalLayout() @Route("testingp") class TestingParametrizedView : VerticalLayout(), HasUrlParameter<Long> { override fun setParameter(event: BeforeEvent, parameter: Long?) { parameter!! } } @Route("testingp/with/subpath") class TestingParametrizedView2 : VerticalLayout(), HasUrlParameter<Long> { override fun setParameter(event: BeforeEvent, parameter: Long?) { parameter!! } }
9,975