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/AzonMedia/component-users/blob/master/app/public_src/src/UsersAdmin.vue
Github Open Source
Open Source
MIT
2,022
component-users
AzonMedia
Vue
Code
1,670
6,323
<template> <div class="crud"> <div class="content"> <div id="data" class="tab"> <h3>Users <b-button variant="success" @click="show_update_modal('post', newObject)" size="sm">Create New</b-button> </h3> <!-- ======================= USERS LISTING ================== --> <template> <b-form @submit="submitSearch"> <b-table striped show-empty :items="items" :fields="fields" empty-text="No records found!" @row-clicked="row_click_handler" no-local-sorting @sort-changed="sortingChanged" head-variant="dark" table-hover> <template slot="top-row" slot-scope="{ fields }"> <td v-for="field in fields"> <!-- <template v-if="field.key=='meta_object_uuid'"> --> <template v-if="field.key=='action'"> <b-button size="sm" variant="outline-primary" type="submit" @click="search()">Search</b-button> </template> <template v-else-if="field.key=='granted_roles_names'"> <!-- <b-button size="sm" variant="outline-primary" type="submit" @click="search()">Search</b-button> --> <!-- <v-select v-model="searchValues[field.key]" label="role_name" :options="roles"></v-select> --> <!-- while the column is named inherits_role_name actually object_meta_uuid is provided so the field name should be inherits_role_uuid --> <!-- :reduce makes return only the uuid not the whole object role_name:meta_object_uuid --> <v-select v-model="searchValues['inherits_roles_uuids']" label="role_name" :reduce="role_name => role_name.meta_object_uuid" :options="roles"></v-select> </template> <template v-else> <b-form-input v-model="searchValues[field.key]" type="search" :placeholder="field.label"></b-form-input> </template> </td> </template> <!-- <template v-slot:cell(meta_object_uuid)="row"> --> <template v-slot:cell(action)="row"> <b-button size="sm" variant="outline-danger" v-on:click.stop="" @click="show_update_modal('delete', row.item)">Delete</b-button> <b-button size="sm" variant="outline-success" v-on:click.stop="" @click="show_permissions_modal( row.item )">Permissions</b-button> </template> </b-table> </b-form> </template> <!-- <b-pagination v-if="totalItems > limit" size="md" :total-rows="totalItems" v-model="currentPage" :per-page="limit" align="center"></b-pagination> --> <b-pagination-nav :link-gen="linkGen" :number-of-pages="numberOfPages" use-router></b-pagination-nav> <!-- ======================= MODAL UPDATE & DELETE ================== --> <b-modal id="crud-modal-user" :title="modalTitle" :header-bg-variant="modalVariant" header-text-variant="light" body-bg-variant="light" body-text-variant="dark" :ok-title="ButtonTitle" :ok-variant="ButtonVariant" centered @ok="update_modal_ok_handler" :cancel-disabled="actionState" :ok-disabled="loadingState" :ok-only="actionState && !loadingState" size="lg" > <template v-if="!actionState"> <!-- <p>{{actionTitle}}</p> --> <!-- apply filter "humanize" on the label --> <b-form-group class="form-group" v-for="(value, index) in putValues" v-if="index!='meta_object_uuid'" v-bind:key="index" :label="index + ':' | humanize" label-align="right" label-cols="3"> <template v-if="index === 'granted_roles_uuids'"> <!-- show checkboxes with roles --> <!-- <template v-for="(Role, index) in roles"> </template> --> <!-- <b-form-group v-for="(Role, index) in roles" :label="Role.role_name" label-align="right"> </b-form-group> --> <b-form-checkbox-group id="granted_roles" v-model="granted_roles" name="granted_roles"> <!-- <b-form-checkbox v-for="(Role, index) in roles" :value="Role.meta_object_uuid">{{Role.role_name}}</b-form-checkbox> --> <!-- because the inherits_role_uuid is not included in the record_properties, only role name, the checkboxes will be driven by name (which is also unique) --> <!-- <b-form-checkbox v-for="(Role, index) in roles" :value="Role.role_name" v-bind:key="Role.role_name">{{Role.role_name}}</b-form-checkbox> --> <b-form-checkbox v-for="(Role, index) in roles" :value="Role.meta_object_uuid" v-bind:key="Role.role_name">{{Role.role_name}}</b-form-checkbox> <!-- {{ putValues }} --> <!-- {{granted_roles}} --> </b-form-checkbox-group> </template> <template v-else-if="index.indexOf('password') != -1"> <b-form-input v-model="putValues[index]" :disabled="!editable_record_properties.includes(index)" type="password"></b-form-input> </template> <template v-else-if="index === 'user_is_disabled'"> <b-form-checkbox name="user_is_disabled" :value="true" :unchecked-value="false" v-model="putValues.user_is_disabled"></b-form-checkbox> </template> <template v-else-if="action === 'delete'"> <b-form-input :value="value" disabled></b-form-input> </template> <template v-else> <b-form-input v-model="putValues[index]" :disabled="!editable_record_properties.includes(index)"></b-form-input> </template> </b-form-group> <!-- <b-form-group label="User Password:" label-align="right" label-cols="3"> <b-form-input v-model="putValues['user_password']"></b-form-input> </b-form-group> <b-form-group label="Password Confirmation:" label-align="right" label-cols="3"> <b-form-input v-model="putValues['user_password_confirmation']"></b-form-input> </b-form-group> --> </template> <template v-else> <p v-if="loadingState"> {{loadingMessage}} ... </p> <p v-else> <template v-if="requestError == ''"> {{successfulMessage}} </template> <template v-else> The operation can not be performed due to an error:<br /> {{requestError}} </template> </p> </template> </b-modal> </div> </div> <!-- display: none in order to suppress anything that may be shown out-of-the-box from this component --> <!-- this component is needed for the permission popups --> <CrudC ref="Crud" style="display: none"></CrudC> </div> </template> <script> import Hook from '@GuzabaPlatform.Platform/components/hooks/Hooks.vue' import ToastMixin from '@GuzabaPlatform.Platform/ToastMixin.js' //imported for the permissions modal import CrudC from '@GuzabaPlatform.Crud/CrudAdmin.vue' import vSelect from 'vue-select' import 'vue-select/dist/vue-select.css' export default { name: "UsersAdmin", mixins: [ ToastMixin, ], components: { Hook, vSelect, CrudC, }, data() { return { checkbox_test: '0', limit: 10, currentPage: 1, totalItems: 0, //selectedClassName: '', //selectedClassNameShort: '', numberOfPages: 1, sortBy: 'none', sortDesc: false, searchValues: {}, putValues: {}, requestError: '', action: '', actionTitle: '', modalTitle: '', modalVariant: '', ButtonTitle: '', ButtonVariant: '', crudObjectUuid: '', actionState: false, loadingState: false, loadingMessage: '', successfulMessage: '', items: [], fields: [],//these are the columns record_properties: [], editable_record_properties: [], items_permissions: [ //must have a default even empty value to avoid the error on template load { permissions: [], } ], fields_permissions: [], fields_permissions_base: [ { key: 'role_id', label: 'Role ID', sortable: true }, { key: 'role_name', label: 'Role Name', sortable: true }, ], title_permissions: "Permissions", isBusy_permissions: false, selectedObject: {}, newObject: {}, /** The non-user roles */ roles: [], /** Used by the modification modal */ granted_roles: [], } }, methods: { /** * @param {int} pageNum * @return {string} */ linkGen(pageNum) { return pageNum === 1 ? '?' : `?page=${pageNum}` }, // https://stackoverflow.com/questions/58140842/vue-and-bootstrap-vue-dynamically-use-slots setSlotCell(action_name) { return `cell(${action_name})`; }, submitSearch(evt){ evt.preventDefault() this.search() }, get_roles() { this.$http.get('/admin/users/roles') .then(resp => { this.roles = resp.data.roles; }) .catch(err => { this.$bvToast.toast('Roles could not be loaded due to server error.' + '\n' + err.response.data.message) }); }, get_users() { if (typeof this.$route.query.page !== 'undefined') { this.currentPage = this.$route.query.page; } else { this.currentPage = 1; } this.fields = []; this.newObject = {}; for (let key in this.searchValues) { if (this.searchValues[key] == '') { delete this.searchValues[key]; } } let objJsonStr = JSON.stringify(this.searchValues);//this is passed as GET so needs to be stringified let searchValuesToPass = encodeURIComponent(window.btoa(objJsonStr)); let self = this; this.$http.get('/admin/users/' + self.currentPage + '/' + self.limit + '/'+ searchValuesToPass + '/' + this.sortBy + '/' + this.sortDesc) .then(resp => { // self.fields.push({ // label: 'UUID', // key: key, // sortable: true // }); for (let i in resp.data.listing_columns) { let key = resp.data.listing_columns[i]; self.fields.push({ key: key, sortable: true }); self.newObject[key] = ''; } self.fields.push({ label: 'Action', key: 'action', sortable: true }); self.items = resp.data.data; for (let aa = 0; aa < this.items.length; aa++) { this.items[aa]['granted_roles_names'] = this.items[aa]['granted_roles_names'].join(','); //this.items[aa]['granted_roles_uuids'] = this.items[aa]['granted_roles_uuids'].join(','); } self.totalItems = resp.data.totalItems; self.numberOfPages = Math.ceil (self.totalItems / self.limit ); self.record_properties = resp.data.record_properties; self.editable_record_properties = resp.data.editable_record_properties; }) .catch(err => { //console.log(err); this.$bvToast.toast('Users data could not be loaded due to server error.' + '\n' + err.response.data.message) }); }, search() { this.reset_params(); this.get_users(); }, //reset_params(className){ reset_params() { this.currentPage = 1; this.totalItems = 0; this.sortBy = 'user_name'; }, row_click_handler(record, index) { this.show_update_modal('put', record); }, /** * Shows the modal dialog for updating/creating/deleting a user record * @param {string} action The actual HTTP method to be executed * @param {array} row */ show_update_modal(action, row) { this.action = action; this.crudObjectUuid = null; this.putValues = {}; for (let key in row) { if (key == "meta_object_uuid") { this.crudObjectUuid = row[key]; //} else if (!key.includes("meta_")){ } else if (!key.includes("meta_") && this.record_properties.includes(key)) { // show only the properties listed in record_properties this.putValues[key] = row[key]; } } this.putValues['user_password'] = ''; this.putValues['user_password_confirmation'] = ''; //console.log(this.putValues); //console.log(row); //console.log(this.putValues); //this.granted_roles = this.putValues.inherits_role_name.split(','); //this.granted_roles = this.putValues.granted_roles_names.split(','); //this.granted_roles = this.putValues.granted_roles_uuids.split(','); this.granted_roles = this.putValues.granted_roles_uuids; //console.log(this.granted_roles); switch (this.action) { case 'delete' : this.modalTitle = 'Deleting user'; this.modalVariant = 'danger'; this.ButtonVariant = 'danger'; //this.actionTitle = 'Are you sure, you want to delete object:'; this.ButtonTitle = 'Delete'; break; case 'put' : this.modalTitle = 'Edit user'; this.modalVariant = 'success'; this.ButtonVariant = 'success'; //this.actionTitle = this.selectedClassNameShort + ":"; //this.actionTitle = this.selectedClassName + ":"; //this.actionTitle = 'Editing user:'; this.ButtonTitle = 'Save'; break; case 'post' : this.modalTitle = 'Create new user'; this.modalVariant = 'success'; this.ButtonVariant = 'success'; //this.actionTitle = this.selectedClassNameShort + ":"; //this.actionTitle = this.selectedClassName + ":"; this.ButtonTitle = 'Save'; break; } if (!this.crudObjectUuid && this.action != "post") { this.requestError = "This user has no meta data!"; this.actionState = true; this.loadingState = false; this.ButtonTitle = 'Ok'; } else { this.actionState = false this.loadingState = false } this.$bvModal.show('crud-modal-user'); }, update_modal_ok_handler(bvEvt) { if(!this.actionState) { bvEvt.preventDefault() //if actionState is false, doesn't close the modal this.actionState = true this.loadingState = true let self = this; let sendValues = {}; //because of the custom login needed for handling the granted roles the ActiveRecordDefaultControllercan not be used //let url = '/admin/crud-operations'; let url = '/admin/users/user'; this.putValues.granted_roles_uuids = this.granted_roles; switch(this.action) { case 'delete' : self.loadingMessage = 'Deleting user with uuid: ' + this.crudObjectUuid; //url += this.selectedClassName.toLowerCase() + '/' + this.crudObjectUuid; //url += this.selectedClassName.split('\\').join('-') + '/' + this.crudObjectUuid; url += '/' + this.crudObjectUuid; break; case 'put' : self.loadingMessage = 'Saving user with uuid: ' + this.crudObjectUuid; //url += this.selectedClassName.toLowerCase() + '/' + this.crudObjectUuid; //url += this.selectedClassName.split('\\').join('-') + '/' + this.crudObjectUuid; url += '/' + this.crudObjectUuid; sendValues = this.putValues; delete sendValues['meta_object_uuid']; break; case 'post' : self.loadingMessage = 'Saving new user'; //url += this.selectedClassName.toLowerCase(); //url += this.selectedClassName.split('\\').join('-'); sendValues = this.putValues; delete sendValues['meta_object_uuid']; break; } //sendValues.crud_class_name = this.selectedClassName.split('\\').join('-'); //sendValues.crud_class_name = 'GuzabaPlatform\\Platform\\Authorization\\Models\\User'; //the above is not needed //due to the Roles management the basic CRUD operation can not be used and a custom controller is needed this.$http({ method: this.action, url: url, data: sendValues }) .then(resp => { self.requestError = ''; self.successfulMessage = resp.data.message; self.get_users() }) .catch(err => { if (err.response.data.message) { self.requestError = err.response.data.message; } else { self.requestError = err; } }) .finally(function(){ self.loadingState = false self.actionState = true self.ButtonTitle = 'OK'; self.ButtonVariant = 'success'; }); } }, /* show_permissions_modal(row) { this.title_permissions = "Permissions for object of class \"" + row.meta_class_name + "\" with id: " + row.meta_object_id + ", object_uuid: " + row.meta_object_uuid; this.selectedObject = row; let self = this; this.$http.get('/admin/permissions-objects/' + this.selectedClassName.split('\\').join('-') + '/' + row.meta_object_uuid) .then(resp => { self.items_permissions = Object.values(resp.data.items); //self.fields_permissions = self.fields_permissions_base;//reset the columns self.fields_permissions = JSON.parse(JSON.stringify(self.fields_permissions_base)) //deep clone and produce again Array for (let action_name in self.items_permissions[0].permissions) { self.fields_permissions.push({ key: action_name, label: action_name, sortable: true, }); } }) .catch(err => { self.requestError = err; self.items_permissions = []; }).finally(function(){ self.$bvModal.show('crud-permissions'); }); }, */ //permissions_page(page_uuid, page_name) { show_permissions_modal(row) { //let row = {}; //console.log(row); row = JSON.parse(JSON.stringify(row)); //row.meta_object_uuid = page_uuid; row.meta_class_name = 'GuzabaPlatform\\Platform\\Authentication\\Models\\User';//not really needed as the title is overriden this.$refs.Crud.selectedClassName = 'GuzabaPlatform\\Platform\\Authentication\\Models\\User'; this.$refs.Crud.selectedObject.meta_object_uuid = row.meta_object_uuid; this.$refs.Crud.showPermissions(row); this.$refs.Crud.title_permissions = 'Permissions for User "' + row.user_name + '"'; }, /* toggle_permission(row, action, checked){ this.isBusy_permission = true; let sendValues = {} if (checked) { //if (typeof row.permissions[action] != "undefined") { //var object_uuid = row[action + '_granted']; let object_uuid = row.permissions[action]; this.action = "delete"; let url = 'acl-permissions/' + object_uuid; } else { this.action = "post"; let url = 'acl-permissions'; sendValues.role_id = row.role_id; sendValues.object_id = this.selectedObject.meta_object_id; sendValues.action_name = action; sendValues.class_name = this.selectedClassName.split(".").join("\\"); } let self = this; this.$http({ method: this.action, url: url, data: sendValues }) .then(resp => { this.$bvToast.toast(resp.data.message) }) .catch(err => { console.log(err); this.$bvToast.toast(err.response.data.message) //self.requestError = err; }) .finally(function(){ self.show_permissions_modal(self.selectedObject) self.isBusy_permission = false; }); }, */ sortingChanged(ctx) { this.sortBy = ctx.sortBy; this.sortDesc = ctx.sortDesc ? 1 : 0; this.get_users(); } }, props: { contentArgs: {} }, watch: { $route (to, from) { // needed because by default no class is loaded and when it is loaded the component for the two routes is the same. this.get_users(); } }, mounted() { this.get_roles(); this.get_users(); }, }; </script> <style> .content { height: 100vh; top: 64px; } .tab { float: left; height: 100%; overflow: none; padding: 20px; } #sidebar{ font-size: 10pt; border-width: 0 5px 0 0; border-style: solid; width: 30%; text-align: left; } #data { width: 100%; font-size: 10pt; } li { cursor: pointer; } .btn { width: 100%; } tr:hover{ background-color: #ddd !important; } th:hover{ background-color: #000 !important; } tr { cursor: pointer; } </style>
49,928
https://github.com/GreggKr/gradespeed-hisd/blob/master/lib/parseRaw.js
Github Open Source
Open Source
MIT
2,021
gradespeed-hisd
GreggKr
JavaScript
Code
291
1,100
'use strict' const cheerio = require('cheerio') const parseGradeString = str => str.charCodeAt(0) === 160 ? null : parseInt(str) const processGradeExceptions = str => { if (str === 'Exc') return str if (!str) return 'Blank' return parseInt(str) } /** * Parses raw html returned from fetchRaw and parses it into an array of objects * @param {string} bodyRaw * @return {Array} */ const parseRaw = bodyArr => { const $ = cheerio.load(bodyArr[0][1]) const asnBodyArr = bodyArr.slice(1) const returnArr = [] const cycleLinks = [] const mainTable = $('table.DataTable').first().children().first().children().slice(1) mainTable.each(function() { const e = $(this).children() cycleLinks.push([ $(e[4]).children().first().attr('href') || null, $(e[5]).children().first().attr('href') || null, $(e[6]).children().first().attr('href') || null, $(e[9]).children().first().attr('href') || null, $(e[10]).children().first().attr('href') || null, $(e[11]).children().first().attr('href') || null ]) returnArr.push({ teacher: e.first().text(), subject: $(e[2]).text(), period: parseInt($(e[3]).text()), c1: null, c2: null, c3: null, c4: null, c5: null, c6: null, c1Avg: parseGradeString($(e[4]).text()), c2Avg: parseGradeString($(e[5]).text()), c3Avg: parseGradeString($(e[6]).text()), c4Avg: parseGradeString($(e[9]).text()), c5Avg: parseGradeString($(e[10]).text()), c6Avg: parseGradeString($(e[11]).text()), ex1: parseGradeString($(e[7]).text()), ex2: parseGradeString($(e[12]).text()), sem1: parseGradeString($(e[8]).text()), sem2: parseGradeString($(e[13]).text()) }) }) returnArr.forEach((clss, idx) => { for (let i = 0; i <= 6; i++) { const objKey = 'c' + i const avgKey = objKey + 'Avg' if (clss[avgKey]) { clss[objKey] = { sections: [] } const targetLink = cycleLinks[idx][i - 1] const onlyLinks = asnBodyArr.map(arrPair => arrPair[0]) const bodyLocation = onlyLinks.indexOf(targetLink) const $ = cheerio.load(asnBodyArr[bodyLocation][1]) // We've loaded the page's HTML for specific assignments. Can access them now. const sections = $('.CategoryName') const weightPat = /(.*) - (\d+)%$/ sections.each(function() { const sectionAssignments = [] const gradeTable = $(this).next().next().children().first().children().filter(() => ( ($(this).attr('class') !== 'TableHeader') && $(this).attr('class') )) gradeTable.each(function() { if ($(this).children('.DateDue').text() !== 'Due' && $(this).children('.AssignmentName').text() !== '') { sectionAssignments.push({ name: $(this).children('.AssignmentName').text(), dateAssigned: $(this).children('.DateAssigned').text(), dateDue: $(this).children('.DateDue').text(), grade: processGradeExceptions($(this).children('.AssignmentGrade').text()) }) } }) clss[objKey].sections.push({ name: $(this).text().match(weightPat)[1], weight: parseInt($(this).text().match(weightPat)[2]), assignments: sectionAssignments }) }) } } }) return returnArr } module.exports = parseRaw
20,475
https://github.com/jimohalloran/platform/blob/master/src/Oro/Bundle/UIBundle/Resources/public/css/scss/oro/label.scss
Github Open Source
Open Source
MIT
null
platform
jimohalloran
SCSS
Code
49
199
/* @theme: admin.oro; */ .label { display: inline-block; max-width: 100%; padding: 0 $badge-padding-x; font-size: $base-font-size--s; font-weight: normal; line-height: 1.2; border-radius: $border-radius; &-large { font-size: $base-font-size; } .page-title__path & { @extend .badge; @extend .badge-pill; border: none; } } @each $color, $values in $label-theme-keys { .label-#{$color} { @include label-custom-variant($values...); } }
36,503
https://github.com/21hook/crm/blob/master/src/api/cuserGroup.js
Github Open Source
Open Source
MIT
null
crm
21hook
JavaScript
Code
258
915
/* * @Author: liyanfang * @Date: 2017-09-25 13:50:08 * @Last Modified by: liyanfang * @Last Modified time: 2017-09-25 13:57:48 */ import HTTP from './HTTP'; /** * [获取所有的用户组] * @return {[object]} * { "id":null, "name":null, "platform":null, "pageNo":1, "pageSize":10 } */ const getUserGroup = (data) => { const promise = new Promise((resolve, reject) => { HTTP.post('/member/cuserGroup/query.do', data) .then((response) => { if (response.data && response.data.status) { resolve(response.data.entry); } else { reject(response.data.message); } }) .catch(() => { reject('网络不稳定请刷新重试!'); }); }); return promise; }; /** * [增加新的用户组] * @param {[object]} * { "name":"红牛浙43北", "platform":1, "roleIds":[1,2] } * @return {[object]} [description] */ const addUserGroup = (data) => { const promise = new Promise((resolve, reject) => { HTTP.post('/member/cuserGroup/add.do', data) .then((response) => { if (response.data && response.data.status) { resolve(response.data.entry); } else { reject(response.data.message); } }) .catch(() => { reject('网络不稳定请刷新重试!'); }); }); return promise; }; /** * 更新一个用户组 * @param {[object]} * { "id":"4", "name":"1", "platform":4, "roleIds":[1234] } * @return {[object]} [description] */ const updataUserGroup = (data) => { const promise = new Promise((resolve, reject) => { HTTP.post('/member/cuserGroup/update.do', data) .then((response) => { if (response.data && response.data.status) { resolve(response.data.entry); } else { reject(response.data.message); } }) .catch(() => { reject('网络不稳定请刷新重试!'); }); }); return promise; }; /** * 删除指定用户组 * @param {[object]} * cuserGroupId=3 * @return {[object]} [description] */ const deleteUserGroup = (data) => { const promise = new Promise((resolve, reject) => { HTTP.get('/member/cuserGroup/delete.do', { params: data, }) .then((response) => { if (response.data && response.data.status) { resolve(response.data.entry); } else { reject(response.data.message); } }) .catch(() => { reject('网络不稳定请刷新重试!'); }); }); return promise; }; export default { getUserGroup, addUserGroup, updataUserGroup, deleteUserGroup, };
3,203
https://github.com/markhker/CookBokkJq/blob/master/src/scss/_responsive.scss
Github Open Source
Open Source
MIT
null
CookBokkJq
markhker
SCSS
Code
940
4,659
// _responsive.scss /* * Responsive styles * ========================================================================== */ .col1, .col11, .col12, .col13, .col23, .col14, .col34, .col16, .col56, .col18, .col38, .col58, .col78, .col112, .col512, .col712, .col1112, .col124, .col224, .col324, .col424, .col524, .col624, .col724, .col824, .col924, .col1024, .col1124, .col1224, .col1324, .col1424, .col1524, .col1624, .col1724, .col1824, .col1924, .col2024, .col2124, .col2224, .col2324, .col2424{ display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; flex-wrap: wrap; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; text-rendering: auto; } .col124{ width: 4.1667%; *width: 4.1357%; } .col112, .col224{ width: 8.3333%; *width: 8.3023%; } .col18, .col324{ width: 12.5000%; *width: 12.4690%; } .col16, .col424{ width: 16.6667%; *width: 16.6357%; } .col524{ width: 20.8333%; *width: 20.8023%; } .col14, .col624{ width: 25%; *width: 24.9690%; } .col724{ width: 29.1667%; *width: 29.1357%; } .col13, .col824{ width: 33.3333%; *width: 33.3023%; } .col38, .col924{ width: 37.5000%; *width: 37.4690%; } .col512, .col1024{ width: 41.6667%; *width: 41.6357%; } .col1124{ width: 45.8333%; *width: 45.8023%; } .col12, .col1224{ width: 50%; *width: 49.9690%; } .col1324{ width: 54.1667%; *width: 54.1357%; } .col712, .col1424{ width: 58.3333%; *width: 58.3023%; } .col58, .col1524{ width: 62.5000%; *width: 62.4690%; } .col23, .col1624{ width: 66.6667%; *width: 66.6357%; } .col1724{ width: 70.8333%; *width: 70.8023%; } .col34, .col1824{ width: 75%; *width: 74.9690%; } .col1924{ width: 79.1667%; *width: 79.1357%; } .col56, .col2024{ width: 83.3333%; *width: 83.3023%; } .col78, .col2124{ width: 87.5000%; *width: 87.4690%; } .col1112, .col2224{ width: 91.6667%; *width: 91.6357%; } .col2324{ width: 95.8333%; *width: 95.8023%; } .col1, .col11, .col2424{ width: 100%; } @media screen and (min-width: 30em) { .cols1, .cols11, .cols12, .cols13, .cols23, .cols14, .cols34, .cols16, .cols56, .cols18, .cols38, .cols58, .cols78, .cols112, .cols512, .cols712, .cols1112, .cols124, .cols224, .cols324, .cols424, .cols524, .cols624, .cols724, .cols824, .cols924, .cols1024, .cols1124, .cols1224, .cols1324, .cols1424, .cols1524, .cols1624, .cols1724, .cols1824, .cols1924, .cols2024, .cols2124, .cols2224, .cols2324, .cols2424{ display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; flex-wrap: wrap; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; text-rendering: auto; } .cols124{ width: 4.1667%; *width: 4.1357%; } .cols112, .cols224{ width: 8.3333%; *width: 8.3023%; } .cols18, .cols324{ width: 12.5000%; *width: 12.4690%; } .cols16, .cols424{ width: 16.6667%; *width: 16.6357%; } .cols524{ width: 20.8333%; *width: 20.8023%; } .cols14, .cols624{ width: 25%; *width: 24.9690%; } .cols724{ width: 29.1667%; *width: 29.1357%; } .cols13, .cols824{ width: 33.3333%; *width: 33.3023%; } .cols38, .cols924{ width: 37.5000%; *width: 37.4690%; } .cols512, .cols1024{ width: 41.6667%; *width: 41.6357%; } .cols1124{ width: 45.8333%; *width: 45.8023%; } .cols12, .cols1224{ width: 50%; *width: 49.9690%; } .cols1324{ width: 54.1667%; *width: 54.1357%; } .cols712, .cols1424{ width: 58.3333%; *width: 58.3023%; } .cols58, .cols1524{ width: 62.5000%; *width: 62.4690%; } .cols23, .cols1624{ width: 66.6667%; *width: 66.6357%; } .cols1724{ width: 70.8333%; *width: 70.8023%; } .cols34, .cols1824{ width: 75%; *width: 74.9690%; } .cols1924{ width: 79.1667%; *width: 79.1357%; } .cols56, .cols2024{ width: 83.3333%; *width: 83.3023%; } .cols78, .cols2124{ width: 87.5000%; *width: 87.4690%; } .cols1112, .cols2224{ width: 91.6667%; *width: 91.6357%; } .cols2324{ width: 95.8333%; *width: 95.8023%; } .cols1, .cols11, .cols2424{ width: 100%; } } @media screen and (min-width: 48em) { .colm1, .colm11, .colm12, .colm13, .colm23, .colm14, .colm34, .colm16, .colm56, .colm18, .colm38, .colm58, .colm78, .colm112, .colm512, .colm712, .colm1112, .colm124, .colm224, .colm324, .colm424, .colm524, .colm624, .colm724, .colm824, .colm924, .colm1024, .colm1124, .colm1224, .colm1324, .colm1424, .colm1524, .colm1624, .colm1724, .colm1824, .colm1924, .colm2024, .colm2124, .colm2224, .colm2324, .colm2424{ display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; flex-wrap: wrap; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; text-rendering: auto; } .colm124{ width: 4.1667%; *width: 4.1357%; } .colm112, .colm224{ width: 8.3333%; *width: 8.3023%; } .colm18, .colm324{ width: 12.5000%; *width: 12.4690%; } .colm16, .colm424{ width: 16.6667%; *width: 16.6357%; } .colm524{ width: 20.8333%; *width: 20.8023%; } .colm14, .colm624{ width: 25%; *width: 24.9690%; } .colm724{ width: 29.1667%; *width: 29.1357%; } .colm13, .colm824{ width: 33.3333%; *width: 33.3023%; } .colm38, .colm924{ width: 37.5000%; *width: 37.4690%; } .colm512, .colm1024{ width: 41.6667%; *width: 41.6357%; } .colm1124{ width: 45.8333%; *width: 45.8023%; } .colm12, .colm1224{ width: 50%; *width: 49.9690%; } .colm1324{ width: 54.1667%; *width: 54.1357%; } .colm712, .colm1424{ width: 58.3333%; *width: 58.3023%; } .colm58, .colm1524{ width: 62.5000%; *width: 62.4690%; } .colm23, .colm1624{ width: 66.6667%; *width: 66.6357%; } .colm1724{ width: 70.8333%; *width: 70.8023%; } .colm34, .colm1824{ width: 75%; *width: 74.9690%; } .colm1924{ width: 79.1667%; *width: 79.1357%; } .colm56, .colm2024{ width: 83.3333%; *width: 83.3023%; } .colm78, .colm2124{ width: 87.5000%; *width: 87.4690%; } .colm1112, .colm2224{ width: 91.6667%; *width: 91.6357%; } .colm2324{ width: 95.8333%; *width: 95.8023%; } .colm1, .colm11, .colm2424{ width: 100%; } } @media screen and (min-width: 81em) { .coll1, .coll11, .coll12, .coll13, .coll23, .coll14, .coll34, .coll16, .coll56, .coll18, .coll38, .coll58, .coll78, .coll112, .coll512, .coll712, .coll1112, .coll124, .coll224, .coll324, .coll424, .coll524, .coll624, .coll724, .coll824, .coll924, .coll1024, .coll1124, .coll1224, .coll1324, .coll1424, .coll1524, .coll1624, .coll1724, .coll1824, .coll1924, .coll2024, .coll2124, .coll2224, .coll2324, .coll2424{ display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; flex-wrap: wrap; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; text-rendering: auto; } .coll124{ width: 4.1667%; *width: 4.1357%; } .coll112, .coll224{ width: 8.3333%; *width: 8.3023%; } .coll18, .coll324{ width: 12.5000%; *width: 12.4690%; } .coll16, .coll424{ width: 16.6667%; *width: 16.6357%; } .coll524{ width: 20.8333%; *width: 20.8023%; } .coll14, .coll624{ width: 25%; *width: 24.9690%; } .coll724{ width: 29.1667%; *width: 29.1357%; } .coll13, .coll824{ width: 33.3333%; *width: 33.3023%; } .coll38, .coll924{ width: 37.5000%; *width: 37.4690%; } .coll512, .coll1024{ width: 41.6667%; *width: 41.6357%; } .coll1124{ width: 45.8333%; *width: 45.8023%; } .coll12, .coll1224{ width: 50%; *width: 49.9690%; } .coll1324{ width: 54.1667%; *width: 54.1357%; } .coll712, .coll1424{ width: 58.3333%; *width: 58.3023%; } .coll58, .coll1524{ width: 62.5000%; *width: 62.4690%; } .coll23, .coll1624{ width: 66.6667%; *width: 66.6357%; } .coll1724{ width: 70.8333%; *width: 70.8023%; } .coll34, .coll1824{ width: 75%; *width: 74.9690%; } .coll1924{ width: 79.1667%; *width: 79.1357%; } .coll56, .coll2024{ width: 83.3333%; *width: 83.3023%; } .coll78, .coll2124{ width: 87.5000%; *width: 87.4690%; } .coll1112, .coll2224{ width: 91.6667%; *width: 91.6357%; } .coll2324{ width: 95.8333%; *width: 95.8023%; } .coll1, .coll11, .coll2424{ width: 100%; } } .row { margin: 0; padding: 0; width: 100%; } .imgResponsive { max-width: 100%; height: auto; display: block; }
9,654
https://github.com/swoopfx/cm/blob/master/public/client/js/app/messages.js
Github Open Source
Open Source
BSD-3-Clause
2,019
cm
swoopfx
JavaScript
Code
31
112
(function ($) { "use strict"; $(window).bind('enterBreakpoint320', function () { var img = $('.messages-list .panel ul img'); $('.messages-list .panel ul').width(img.first().width() * img.length); }); $(window).bind('exitBreakpoint320', function () { $('.messages-list .panel ul').width('auto'); }); })(jQuery);
42,916
https://github.com/pgadea/identity-server-template/blob/master/src/Frontend/Spa/src/app/core/services/config.service.ts
Github Open Source
Open Source
MIT
2,021
identity-server-template
pgadea
TypeScript
Code
70
244
import { Injectable } from '@angular/core'; @Injectable() export class ConfigService { static readonly RESOURCE_BASE_URI = "https://localhost:5025"; static readonly AUTH_BASE_URI = "https://localhost:8787"; constructor() {} getDefaultRoute(role: string): string { switch(role) { case 'employer': return '/employer/jobs'; case 'applicant': return '/jobs/list'; } } get authApiURI() { return ConfigService.AUTH_BASE_URI + '/api'; } get authAppURI() { return ConfigService.AUTH_BASE_URI; } get resourceApiURI() { return ConfigService.RESOURCE_BASE_URI + "/api"; } get graphqlURI() { return ConfigService.RESOURCE_BASE_URI + "/graphql"; } }
45,646
https://github.com/vz-chameleon/aYouTubeCopycat/blob/master/src/main/java/views/PlaylistRightSideBarView.java
Github Open Source
Open Source
Apache-2.0
null
aYouTubeCopycat
vz-chameleon
Java
Code
319
1,896
package views; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.net.MalformedURLException; import javax.swing.Box; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import app.AppController; import elements.OurVideo; import elements.Playlist; import elements.PlaylistVideoComponent; import elements.ClosePlaylistButton; import elements.ImportPlaylistButton; import elements.SavePlaylistButton; public class PlaylistRightSideBarView extends JPanel{ private Playlist playlist; private AppController app; private JPanel result; private JScrollPane jsc; ImportPlaylistButton importPlaylistButton; SavePlaylistButton savePlaylistButton; ClosePlaylistButton closePlaylistButton; //JLabel label; //private Box bigvbox=Box.createVerticalBox(); private Box bigvbox; Color backgroundColor; public PlaylistRightSideBarView(AppController app){ super(); this.setLayout(new BorderLayout()); playlist = new Playlist(); this.app=app; this.setOpaque(false); backgroundColor = new Color(255,255,255,100); //this.setBackground(backgroundColor); bigvbox = Box.createVerticalBox(); //bigvbox.setBackground(backgroundColor); bigvbox.setOpaque(false); Box topPanel = Box.createVerticalBox(); Box hboxtitle = Box.createHorizontalBox(); JLabel topPanelLabel = new JLabel("Your Playlist"); hboxtitle.add(Box.createHorizontalGlue()); hboxtitle.add(topPanelLabel); hboxtitle.add(Box.createHorizontalGlue()); topPanel.add(hboxtitle); topPanelLabel.setForeground(Color.WHITE); Box hbox = Box.createHorizontalBox(); importPlaylistButton = new ImportPlaylistButton(app); importPlaylistButton.setFont(new Font("Corbel",Font.BOLD,15)); importPlaylistButton.setFocusPainted(false); importPlaylistButton.setContentAreaFilled(true); importPlaylistButton.setBackground(Color.LIGHT_GRAY); savePlaylistButton = new SavePlaylistButton(app); savePlaylistButton.setFont(new Font("Corbel",Font.BOLD,15)); savePlaylistButton.setFocusPainted(false); savePlaylistButton.setContentAreaFilled(true); savePlaylistButton.setBackground(Color.LIGHT_GRAY); closePlaylistButton = new ClosePlaylistButton(app); closePlaylistButton.setFont(new Font("Corbel",Font.BOLD,15)); closePlaylistButton.setFocusPainted(false); closePlaylistButton.setContentAreaFilled(true); closePlaylistButton.setBackground(Color.LIGHT_GRAY); hbox.add(importPlaylistButton); hbox.add(savePlaylistButton); hbox.add(closePlaylistButton); int border = hbox.getWidth()+2; topPanel.add(hbox); topPanel.add(Box.createHorizontalStrut(border)); this.add(topPanel,BorderLayout.NORTH); this.result = new JPanel(new BorderLayout()); result.setBackground(backgroundColor); result.add(bigvbox); result.setSize(new Dimension(338,100)); jsc = new JScrollPane(result); this.add(jsc); jsc.setPreferredSize(new Dimension(355,100)); jsc.setPreferredSize(new Dimension(355,800)); jsc.setVisible(true); jsc.setOpaque(false); } public Playlist getPlaylist(){ return playlist; } public void updatePlaylist(OurVideo video) throws MalformedURLException, IOException{ //result.remove(label); if(!(playlist.existsIn(video))){ playlist.addVideo(video); final PlaylistVideoComponent playlistComp = new PlaylistVideoComponent(playlist, video, app); playlistComp.setBackground(backgroundColor); playlistComp.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent e){ app.activatePlaylistMode(playlistComp.getVideo()); app.readOurVideo(playlistComp.getVideo()); } }); this.remove(jsc); this.repaint(); bigvbox.add(playlistComp); this.add(jsc); bigvbox.repaint(); bigvbox.revalidate(); } } public void fastUpdatePlaylist(OurVideo video) throws MalformedURLException, IOException{ //if(!(playlist.existsIn(video))){ System.out.println("adding video"); final PlaylistVideoComponent playlistComp = new PlaylistVideoComponent(playlist, video, app); playlistComp.setBackground(backgroundColor); playlistComp.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent e){ app.activatePlaylistMode(playlistComp.getVideo()); app.readOurVideo(playlistComp.getVideo()); } }); bigvbox.add(playlistComp); //} } public void remove(PlaylistVideoComponent pvc){ this.remove(jsc); this.repaint(); playlist.removeVideo(pvc.getVideo()); bigvbox.remove(pvc); this.add(jsc); bigvbox.repaint(); bigvbox.revalidate(); } public void setPlaylist(Playlist playlistChoice) { this.remove(jsc); this.repaint(); playlist = playlistChoice; bigvbox.removeAll(); if (playlistChoice!=null) for (OurVideo ov : playlistChoice.getVideos()){ try { fastUpdatePlaylist(ov); } catch (IOException e) { e.printStackTrace(); } } this.add(jsc); this.repaint(); bigvbox.repaint(); System.out.println("repainting"); } public void toggleClose(){ closePlaylistButton.doClick(); } public void toggleSave(){ savePlaylistButton.doClick(); } public Playlist newPlaylist() { playlist=new Playlist(); return playlist; } }
48,456
https://github.com/bocke/ucc/blob/master/test/cases/initialisation/struct_reinit_false.c
Github Open Source
Open Source
MIT
2,022
ucc
bocke
C
Code
20
51
// RUN: %layout_check %s struct B { int x[2]; } ent1 = { .x[0] = 5, .x[1] = 2 };
48,653
https://github.com/Christopherjl/resxible/blob/master/src/Resxible/Properties/AssemblyInfo.cs
Github Open Source
Open Source
MIT
2,015
resxible
Christopherjl
C#
Code
27
110
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle ("Resxible")] [assembly: AssemblyDescription ("")] [assembly: AssemblyCompany ("Apcurium")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyVersion ("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisibleAttribute(false)]
11,848
https://github.com/WFZ1/basic-js/blob/master/src/recursive-depth.js
Github Open Source
Open Source
MIT
null
basic-js
WFZ1
JavaScript
Code
33
106
const CustomError = require("../extensions/custom-error"); module.exports = class DepthCalculator { calculateDepth(arr) { const new_arr = arr.map(el => { if(Array.isArray(el)) return this.calculateDepth(el) + 1 return 1; }); return new_arr.length ? Math.max(...new_arr) : 1; } };
16,676
https://github.com/PieterjanDeconinck/quarkus/blob/master/independent-projects/qute/core/src/main/java/io/quarkus/qute/NamespaceResolver.java
Github Open Source
Open Source
Apache-2.0
2,022
quarkus
PieterjanDeconinck
Java
Code
164
449
package io.quarkus.qute; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.Function; /** * Namespace resolvers are used to find the current context object for an expression that starts with a namespace declaration. * <p> * For example the expression {@code data:colors} declares a namespace {@code data}. * * @see EngineBuilder#addNamespaceResolver(NamespaceResolver) */ public interface NamespaceResolver extends Resolver { /** * * @param namespace * @return a new builder instance */ static Builder builder(String namespace) { return new Builder(namespace); } /** * * @return the namespace * @see ExpressionImpl#namespace */ String getNamespace(); final class Builder { private final String namespace; private Function<EvalContext, CompletionStage<Object>> resolve; Builder(String namespace) { this.namespace = namespace; } public Builder resolve(Function<EvalContext, Object> func) { this.resolve = ctx -> CompletableFuture.completedFuture(func.apply(ctx)); return this; } public Builder resolveAsync(Function<EvalContext, CompletionStage<Object>> func) { this.resolve = func; return this; } public NamespaceResolver build() { Objects.requireNonNull(resolve); return new NamespaceResolver() { @Override public CompletionStage<Object> resolve(EvalContext context) { return resolve.apply(context); } @Override public String getNamespace() { return namespace; } }; } } }
8,441
https://github.com/evandhq/react-jupiter/blob/master/src/components/icons/utils.test.js
Github Open Source
Open Source
MIT
2,021
react-jupiter
evandhq
JavaScript
Code
140
396
import { getSizeOfIcon, getMarginOfIcon } from './utils'; import theme from './theme'; describe('Tests of icons utils', () => { describe('Test of icon sizes', () => { it('Should return 20 as font size of medium icons', () => { const sizeOfMediumIcon = getSizeOfIcon('md'); expect(sizeOfMediumIcon).toBe(theme.sizes.medium); }); it('Should return 24 as font size of large icons', () => { const sizeOfLargeIcon = getSizeOfIcon('lg'); expect(sizeOfLargeIcon).toBe(theme.sizes.large); }); it('Should return 16 as font size of small icons', () => { const sizeOfSmallIcon = getSizeOfIcon('sm'); expect(sizeOfSmallIcon).toBe(theme.sizes.small); }); }); describe('Test of icons margin', () => { it('Should return 10 as margin of medium icons', () => { const marginOfMediumIcon = getMarginOfIcon('md'); expect(marginOfMediumIcon).toBe(theme.sizes.mediumMargin); }); it('Should return 12 as margin of large icons', () => { const marginOfLargeIcon = getMarginOfIcon('lg'); expect(marginOfLargeIcon).toBe(theme.sizes.largeMargin); }); it('Should return 8 as margin of small icons', () => { const marginOfSmallIcon = getMarginOfIcon('sm'); expect(marginOfSmallIcon).toBe(theme.sizes.smallMargin); }); }); });
49,792
https://github.com/adfsaffs/daozhe_B/blob/master/src/pages/detail/commentcontainer.vue
Github Open Source
Open Source
MIT
2,017
daozhe_B
adfsaffs
Vue
Code
315
1,632
<template> <div class="ticket-comment-container"> <h3 class="ticket-comment-title">用户评论</h3> <div class="ticket-comment-list"> <div class="ticket-comment-item border-top" v-for = "(info, index) in commentsInfo" :key="info.id"> <div class="ticket-comment-stardate"> <span class="ticket-startlevel iconfont">&#xe628;&#xe628;&#xe628;&#xe628;&#xe628;</span> <span class="ticket-comment-date">{{info.userId}}&nbsp;&nbsp;{{info.data}}</span> </div> <p class="ticket-comment-content commentcon"> {{info.commentContent}} </p> <div class="ticket-comment-foldbtn iconfont" @click="handleClickFold" :id = "index+'0'">&#xe64b;</div> <div class="ticket-comment-imgs" > <div class="ticket-comment-imgouter" v-for = "imgs in info.imgUrl"> <div class="ticket-comment-imginner"> <img class="ticket-comment-img" :src="imgs"> </div> </div> </div> </div> </div> <a href="#"> <div class="ticket-more-refresh border-top">查看全部评论<span class="iconfont">&#xe649;</span></div> </a> </div> </template> <script> export default { data () { return { flag: false } }, props: ["commentsInfo"], methods: { handleClickFold: function(e) { var index = e.currentTarget.id; var comment = document.getElementsByClassName("commentcon")[index/10]; if(this.flag == false){ e.currentTarget.innerHTML = "&#xe601;"; comment.style.height ="auto"; comment.style.overflow ="auto"; }else{ e.currentTarget.innerHTML = "&#xe64b;"; comment.style.height ="100px"; } this.flag = !this.flag; } } } </script> <style scoped> @import "../../assets/font/iconfont.css"; .iconfont{ speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; } .ticket-comment-container{ position: relative; margin-top: .2rem; } .ticket-comment-title{ padding: 0 .2rem; height: .88rem; background: #fff; color: #333; font-size: .3rem; line-height: .88rem; text-indent: .2rem; } .ticket-comment-title::after{ content: " "; position: absolute; top: .33rem; left: .2rem; width: .06rem; height: .25rem; background: #1ba9ba; border-radius: .04rem; } .ticket-comment-list{ background: #fff; } .ticket-comment-item{ padding: .1rem .2rem .3rem .2rem; } .ticket-comment-stardate{ margin-bottom: .1rem; line-height: .6rem; } .ticket-startlevel, .ticket-comment-date{ vertical-align: middle; } .ticket-startlevel{ display: inline-block; position: relative; width: 1.4rem; height: .28rem; color: #00bcd4; } .ticket-comment-date{ position: relative; float: right; top: .16rem; margin-left: .2rem; line-height: .28rem; font-size: .24rem; color: #212121; } .ticket-comment-content{ word-break: break-all; word-wrap: break-word; height: 100px; overflow: hidden; line-height: .42rem; font-size: .26rem; color: #616161; } .ticket-comment-foldbtn{ height: .48rem; line-height: .48rem; text-align: center; font-size: .4rem; color: #9e9e9e; } .ticket-comment-imgs{ margin: .2rem 0 .1rem 0; position: relative; zoom: 1; overflow: hidden; } .ticket-comment-imgouter{ float: left; width: 33.33%; margin-bottom: .1rem; } .ticket-comment-imginner{ margin: 0 .07rem; height: 0; padding-bottom: 73.87%; overflow: hidden; } .ticket-comment-img{ width: 100%; background: #ccc; } .ticket-more-refresh{ position: relative; margin-top: -.02rem; height: .8rem; background: #fff; color: #616161; line-height: .8rem; text-align: center; z-index: 2; vertical-align: middle; } </style>
8,211
https://github.com/IBobko/revolut/blob/master/src/test/java/revolut/JettyServerTest.java
Github Open Source
Open Source
2,020
revolut
IBobko
Java
Code
1,341
5,307
package revolut; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.math.BigDecimal; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; class JettyServerTest { public static final String API_URL = "http://localhost:8080/api/v1"; @BeforeAll public static void setUp() throws Exception { Application.serverInitialization(); ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { Application.server.join(); return null; }); } @AfterAll public static void tearDown() throws Exception { Application.server.stop(); } @Test public void getAllHoldersPageTest() throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpGet httpget = new HttpGet(String.format("%s/holders", API_URL)); try (CloseableHttpResponse response = httpClient.execute(httpget)) { assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode holders = mapper.readTree(json); for (final Iterator<JsonNode> it = holders.elements(); it.hasNext(); ) { final JsonNode holder = it.next(); checkHolder(holder); } } } } public void checkHolder(JsonNode holder) { assertTrue(holder.has("fullName")); assertTrue(holder.has("accounts")); assertTrue(holder.has("id")); final JsonNode accounts = holder.get("accounts"); for (final Iterator<JsonNode> accountIt = accounts.elements(); accountIt.hasNext(); ) { final JsonNode account = accountIt.next(); assertTrue(account.has("id")); assertTrue(account.has("entries")); final JsonNode entries = account.get("entries"); for (final Iterator<JsonNode> entryIt = entries.elements(); entryIt.hasNext(); ) { final JsonNode entry = entryIt.next(); assertTrue(entry.has("amount")); assertTrue(entry.has("date")); } } } @Test public void getFirstHolderPageTest() throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpGet httpget = new HttpGet(String.format("%s/holders/id/1", API_URL)); try (CloseableHttpResponse response = httpClient.execute(httpget)) { assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode holder = mapper.readTree(json); checkHolder(holder); } } } @Test public void transactionTest() throws IOException { // Здесь нужно проверить что значения правильные. try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("{\"sum\": 1,\"payerAccountId\": 1,\"payeeAccountId\": 2}"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertTrue(answer.has("payerStatus")); assertTrue(answer.has("payeeStatus")); assertTrue(answer.has("status")); assertTrue(answer.has("payerBalance")); assertTrue(answer.has("payeeBalance")); assertTrue(answer.has("initialPayerBalance")); assertTrue(answer.has("initialPayeeBalance")); assertTrue(answer.has("transferSum")); } } } @Test public void transactionInsufficientBalanceTest() throws IOException { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("{\"sum\": 1000,\"payerAccountId\": 1,\"payeeAccountId\": 2}"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertEquals("INSUFFICIENT_SUM", answer.get("payerStatus").asText()); assertEquals("GOOD", answer.get("payeeStatus").asText()); assertEquals("BAD", answer.get("status").asText()); assertEquals("$ 500.00", answer.get("payerBalance").asText()); assertEquals("$ 500.00", answer.get("payeeBalance").asText()); assertEquals("$ 500.00", answer.get("initialPayerBalance").asText()); assertEquals("$ 500.00", answer.get("initialPayeeBalance").asText()); assertEquals("$ 1,000.00", answer.get("transferSum").asText()); } } } @Test public void transactionBetweenTheSameAccountTest() throws IOException { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("{\"sum\": 1000,\"payerAccountId\": 1,\"payeeAccountId\": 1}"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertEquals("The Payer and the payee can't be the same.", answer.get("error").asText()); } } } @Test public void transactionWithWrongRequestAccountTest() throws IOException { // lack of sum parameter. try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("{\"payerAccountId\": 1,\"payeeAccountId\": 1}"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertEquals("Sum can't be null", answer.get("error").asText()); } } // lack of full request. try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertEquals("Request can't be null", answer.get("error").asText()); } } // lack of full request. try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("{\"payerAccountId\": \"hello world\",\"payeeAccountId\": 1}"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertTrue(answer.get("error").asText().startsWith("java.lang.NumberFormatException")); } } // Ignoring unrecognized field try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("{\"sum\":\"10\",\"test\": \"hello world\",\"payeeAccountId\": 1,\"payerAccountId\": 2}"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } } // Incorrect Json try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("Hello World"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertTrue(answer.get("error").asText().startsWith("java.lang.IllegalStateException")); } } } @Test public void transactionWithNonexistingAccountTest() throws IOException { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("{\"sum\": 100, \"payerAccountId\": -1,\"payeeAccountId\": 1}"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertEquals("Payer not found.", answer.get("error").asText()); } } } @Test public void transactionWithAccountWithIncorrectCurrencyTest() throws IOException { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity("{\"sum\": 100, \"payerAccountId\": 7,\"payeeAccountId\": 1}"); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertEquals("Currencies differ: GBP/USD", answer.get("error").asText()); } } } @Test public void checkTotalSystemBalanceTest() throws IOException { BigDecimal totalSystemBalance = getToTalSystemBalance(); assertEquals(new BigDecimal("3000"), totalSystemBalance); } @Test public void transactionCheckingSystemForRobustWhenALotOfRequestsChangeBalanceTest() throws IOException { final BigDecimal totalBalance = getToTalSystemBalance(); final ExecutorService service = Executors.newCachedThreadPool(); try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(10); HttpClients.custom().setConnectionManager(connManager); for (int i = 1; i < 7; i++) { final Integer payerAccountId = i; final Integer payeeAccountId = (i == 6) ? 1 : i + 1; service.submit((Callable<String>) () -> { final HttpPut httpPut = new HttpPut(String.format("%s/transactions", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); HttpEntity requestEntity = new StringEntity(String.format("{\"sum\": 100, \"payerAccountId\": %d,\"payeeAccountId\": %d}", payerAccountId, payeeAccountId)); httpPut.setEntity(requestEntity); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertEquals("OK", answer.get("status").asText()); } return null; }); } awaitTerminationAfterShutdown(service); } final BigDecimal afterTotalBalance = getToTalSystemBalance(); assertEquals(totalBalance, afterTotalBalance); } public void awaitTerminationAfterShutdown(ExecutorService threadPool) { threadPool.shutdown(); try { if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) { threadPool.shutdownNow(); } } catch (InterruptedException ex) { threadPool.shutdownNow(); Thread.currentThread().interrupt(); } } public BigDecimal getToTalSystemBalance() throws IOException { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpGet httpGet = new HttpGet(String.format("%s/transactions/total-system-balance/USD", API_URL)); try (final CloseableHttpResponse response = httpClient.execute(httpGet)) { assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); return new BigDecimal(answer.get("totalBalance").asLong()); } } } @Test public void getToTalSystemBalanceWithIncorrectCurrencyTest() throws IOException { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpGet httpGet = new HttpGet(String.format("%s/transactions/total-system-balance/USD1", API_URL)); try (final CloseableHttpResponse response = httpClient.execute(httpGet)) { assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); final HttpEntity entity = response.getEntity(); assertNotNull(entity); assertEquals(MediaType.APPLICATION_JSON, entity.getContentType().getValue()); final String json = EntityUtils.toString(entity); final ObjectMapper mapper = new ObjectMapper(); final JsonNode answer = mapper.readTree(json); assertTrue(answer.get("error").asText().startsWith("Unknown currency")); } } } @Test public void page302StatusTest() throws IOException { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(API_URL); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode()); } } } @Test public void pageNotFoundTest() throws IOException { try (final CloseableHttpClient httpClient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut(String.format("%s/hello", API_URL)); httpPut.setHeader("Content-Type", MediaType.APPLICATION_JSON); try (final CloseableHttpResponse response = httpClient.execute(httpPut)) { assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } } } }
37,847
https://github.com/gelisam/klister/blob/master/src/ModuleName.hs
Github Open Source
Open Source
BSD-3-Clause
2,023
klister
gelisam
Haskell
Code
198
504
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module ModuleName ( -- * Module names ModuleName(..) , KernelName , kernelName , moduleNameFromPath , moduleNameToPath , moduleNameText , relativizeModuleName ) where import Data.Data (Data) import Data.Text (Text) import qualified Data.Text as T import System.Directory import System.FilePath import Data.Hashable import GHC.Generics (Generic) import ShortShow newtype KernelName = Kernel () deriving (Data, Eq, Ord, Show, Generic) instance Hashable KernelName kernelName :: KernelName kernelName = Kernel () data ModuleName = ModuleName FilePath | KernelName KernelName deriving (Data, Eq, Ord, Show, Generic) instance Hashable ModuleName instance ShortShow ModuleName where shortShow (ModuleName x) = x shortShow (KernelName _k) = "kernel" moduleNameFromPath :: FilePath -> IO ModuleName moduleNameFromPath file = ModuleName <$> canonicalizePath file moduleNameToPath :: ModuleName -> Either FilePath KernelName moduleNameToPath (ModuleName file) = Left file moduleNameToPath (KernelName _) = Right (Kernel ()) moduleNameText :: ModuleName -> Text moduleNameText (ModuleName f) = T.pack (show f) moduleNameText (KernelName _) = T.pack "kernel" -- | Given a path, relativize the @ModuleName@ with respect to the path. -- -- > relativizeModuleName "a/b/c/klister" "a/b/c/klister/examples/do.kl" = "examples/do.kl" -- relativizeModuleName :: FilePath -> ModuleName -> ModuleName relativizeModuleName l (ModuleName r) = ModuleName (makeRelative l r) relativizeModuleName _ k@KernelName{} = k
24,633
https://github.com/Bibazavr/react-native-image-colors/blob/master/android/src/main/java/com/reactnativeimagecolors/ImageColorsModule.java
Github Open Source
Open Source
MIT
2,022
react-native-image-colors
Bibazavr
Java
Code
557
1,827
package com.reactnativeimagecolors; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.util.Base64; import androidx.annotation.NonNull; import androidx.palette.graphics.Palette; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import java.net.MalformedURLException; import java.net.URI; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ImageColorsModule extends ReactContextBaseJavaModule { private static final String base64Scheme = "data"; private final ExecutorService executorService; private Integer pixelSpacing; ImageColorsModule(ReactApplicationContext reactContext) { super(reactContext); executorService = new ThreadPoolExecutor( 0, Integer.MAX_VALUE, 30L, TimeUnit.SECONDS, new SynchronousQueue<>() ); } @NonNull @Override public String getName() { return "ImageColors"; } /** * https://gist.github.com/maxjvh/a6ab15cbba9c82a5065d * pixelSpacing tells how many pixels to skip each pixel. * If pixelSpacing > 1: the average color is an estimate, but higher values mean better performance. * If pixelSpacing == 1: the average color will be the real average. * If pixelSpacing < 1: the method will most likely crash (don't use values below 1). */ private int calculateAverageColor(@NonNull Bitmap bitmap) { int R = 0; int G = 0; int B = 0; int height = bitmap.getHeight(); int width = bitmap.getWidth(); int n = 0; int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); int spacing = 5; if(pixelSpacing != null){ spacing = pixelSpacing; } for (int i = 0; i < pixels.length; i += spacing) { int color = pixels[i]; R += Color.red(color); G += Color.green(color); B += Color.blue(color); n++; } return Color.rgb(R / n, G / n, B / n); } private String getHex(int rgb) { return String.format("#%06X", (0xFFFFFF & rgb)); } private int parseColorFromHex(String colorHex) { return Color.parseColor(colorHex); } @ReactMethod public void getColors(String source, ReadableMap config, Promise promise) { executorService.execute(() -> { try { String defColor = "#000000"; pixelSpacing = null; if (config != null){ if (config.hasKey("defaultColor")) { defColor = config.getString("defaultColor"); } if (config.hasKey("pixelSpacing")) { pixelSpacing = config.getInt("pixelSpacing"); } } int defColorInt = parseColorFromHex(defColor); WritableMap resultMap = Arguments.createMap(); resultMap.putString("platform", "android"); Context context = getReactApplicationContext(); int resourceId = context.getResources().getIdentifier(source, "drawable", context.getPackageName()); Bitmap image = null; if (resourceId == 0) { // resource is not a local file // could be a URL, base64. URI uri = new URI(source); String scheme = uri.getScheme(); if(scheme == null) throw new Exception("Invalid URI scheme"); if (scheme.equals(base64Scheme)) { String[] parts = source.split(","); String base64Uri = parts[1]; byte[] decodedString = Base64.decode(base64Uri, Base64.DEFAULT); image = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); } else { image = BitmapFactory.decodeStream(uri.toURL().openConnection().getInputStream()); } } else { image = BitmapFactory.decodeResource(context.getResources(), resourceId); } if (image == null) throw new Exception("Invalid image URI – failed to get image"); int rgbAvg = calculateAverageColor(image); String hexAvg = getHex(rgbAvg); resultMap.putString("average", hexAvg); Palette.Builder builder = new Palette.Builder(image); builder.generate(palette -> { try { if (palette != null) { int rgb = palette.getDominantColor(defColorInt); String hex = getHex(rgb); resultMap.putString("dominant", hex); int rgb1 = palette.getVibrantColor(defColorInt); String hex1 = getHex(rgb1); resultMap.putString("vibrant", hex1); int rgb2 = palette.getDarkVibrantColor(defColorInt); String hex2 = getHex(rgb2); resultMap.putString("darkVibrant", hex2); int rgb3 = palette.getLightVibrantColor(defColorInt); String hex3 = getHex(rgb3); resultMap.putString("lightVibrant", hex3); int rgb4 = palette.getDarkMutedColor(defColorInt); String hex4 = getHex(rgb4); resultMap.putString("darkMuted", hex4); int rgb5 = palette.getLightMutedColor(defColorInt); String hex5 = getHex(rgb5); resultMap.putString("lightMuted", hex5); int rgb6 = palette.getMutedColor(defColorInt); String hex6 = getHex(rgb6); resultMap.putString("muted", hex6); promise.resolve(resultMap); } else { throw new Exception("Palette was null"); } } catch (Exception e) { handleException(e, promise); } }); } catch (MalformedURLException e) { handleException(new Exception("Invalid URL"), promise); } catch (Exception e) { handleException(e, promise); } }); } private void handleException(Exception e, Promise promise) { e.printStackTrace(); promise.reject("Error", "ImageColors: " + e.getMessage()); } }
22,750
https://github.com/jggonzalezh/ETV2/blob/master/ETV/Assets/reutilizables/fountain/Materials/Fountain.mat.meta
Github Open Source
Open Source
CC-BY-4.0, CC-BY-3.0
2,016
ETV2
jggonzalezh
Unity3D Asset
Code
12
68
fileFormatVersion: 2 guid: a7e0fbda2b682c748b3af7b7cccecec1 timeCreated: 1462564453 licenseType: Free NativeFormatImporter: userData: assetBundleName: assetBundleVariant:
40,242
https://github.com/jblab/password-validator-bundle/blob/master/src/Exception/PasswordSpecialCharacterException.php
Github Open Source
Open Source
MIT
null
password-validator-bundle
jblab
PHP
Code
17
57
<?php namespace Jblab\PasswordValidatorBundle\Exception; /** * Class PasswordValidationException * @package Jblab\PasswordValidatorBundle\Exception */ class PasswordSpecialCharacterException extends PasswordValidationException { }
29,353
https://github.com/Muhibullah-09/aws-eventbridge-vartual-lolly-app/blob/master/src/components/Layout.tsx
Github Open Source
Open Source
RSA-MD
null
aws-eventbridge-vartual-lolly-app
Muhibullah-09
TypeScript
Code
40
92
import React, { FC, ReactNode } from "react"; import Header from "./Header"; type LayoutProps = { children: ReactNode; }; const Layout: FC<LayoutProps> = ({ children }) => { return ( <div> <Header /> {children} </div> ); }; export default Layout;
19,384
https://github.com/yam-finance/synths-www/blob/master/src/composables/global.ts
Github Open Source
Open Source
MIT
2,021
synths-www
yam-finance
TypeScript
Code
302
833
import { computed, reactive, toRefs } from "vue" import { web3 } from "@/plugins/web3" let newNotificationTimer const globalState = reactive({ //Screen width screenWidth: 0 as number, //Block NUmber blockNumber: 0 as number, //Notifications isNotificationOpen: false as boolean, notifications: [] as object[], newNotifications: [] as object[], }) export function globalStore() { /** * @notice Set Screen width */ const setScreenWidth = (payload: number) => { globalState.screenWidth = payload } /** * @notice Set ETH block number globally. */ const setBlockNumber = (payload: number) => { console.log("setBlockNumber", payload) globalState.blockNumber = payload } /** * @notice Loads ETH block number */ const loadBlockNumber = () => { web3.getBlockNumber().then((res: number) => { setBlockNumber(res) }) setInterval(() => { web3.getBlockNumber().then((res: number) => { setBlockNumber(res) }) }, 40000) } /** * @notice Toggles Notification Layout. */ const toggleNotificationOpen = () => { globalState.isNotificationOpen = !globalState.isNotificationOpen } /** * @notice Delete notification from Layout. */ const deleteNotification = (index: number) => { globalState.notifications.splice(index, 1) } /** * @notice Delete notification from global view and put it to Layout. */ const deleteNewNotification = (index: number) => { clearTimeout(newNotificationTimer) globalState.notifications.push(globalState.newNotifications[index]) globalState.newNotifications.splice(index, 1) } /** * @notice Add global notifications. * * @param payload: Object Notification Data * @param payload.style: Number 0 - information style, 1 - success style, 2 - error style * @param payload.link: String Third-party link * @param payload.title String Notification Title * @param payload.content String Notification text content * @param saveGlobally: Boolean Saved notification to side bar by default */ const addNewNotifications = (payload: object, saveGlobally = true) => { globalState.newNotifications.push(payload) newNotificationTimer = setTimeout(() => { if (saveGlobally) globalState.notifications.push(payload) globalState.newNotifications.shift() }, 3000) } return { state: toRefs(globalState), //Screen Width setScreenWidth, isXl: computed(() => globalState.screenWidth >= 1280), isLg: computed(() => globalState.screenWidth >= 1024), isMd: computed(() => globalState.screenWidth >= 768), //Block NUmber setBlockNumber, loadBlockNumber, //Notifications toggleNotificationOpen, deleteNotification, deleteNewNotification, addNewNotifications, } }
32,396
https://github.com/hmcts/unspec-service/blob/master/src/main/java/uk/gov/hmcts/reform/unspec/validation/OrgPolicyValidator.java
Github Open Source
Open Source
MIT
2,021
unspec-service
hmcts
Java
Code
54
214
package uk.gov.hmcts.reform.unspec.validation; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.ccd.model.OrganisationPolicy; import uk.gov.hmcts.reform.unspec.enums.YesOrNo; import java.util.ArrayList; import java.util.List; @Component public class OrgPolicyValidator { public List<String> validate(OrganisationPolicy organisationPolicy, YesOrNo solicitorFirmRegistered) { List<String> errors = new ArrayList<>(); if (solicitorFirmRegistered == YesOrNo.YES && (organisationPolicy == null || organisationPolicy.getOrganisation() == null || organisationPolicy.getOrganisation().getOrganisationID() == null)) { errors.add("No Organisation selected"); } return errors; } }
42,865
https://github.com/liuzw1024/tms-koa/blob/master/sample.js
Github Open Source
Open Source
MIT
2,020
tms-koa
liuzw1024
JavaScript
Code
47
147
const log4jsConfig = require('./config/log4js') const log4js = require('log4js') log4js.configure(log4jsConfig) const { TmsKoa } = require('./lib/app') const tmsKoa = new TmsKoa() const middleware = async (ctx, next) => { const start = Date.now() await next() const ms = Date.now() - start ctx.set('X-Response-Time', `${ms}ms`) } tmsKoa.startup({ beforeController: [middleware] })
50,763
https://github.com/vsariola/adam/blob/master/capture/debug.h
Github Open Source
Open Source
MIT
2,022
adam
vsariola
C
Code
170
524
// This header contains some useful functions for debugging OpenGL. // Remember to disable them when building your final releases. #ifdef OPENGL_DEBUG #include <windows.h> #include <GL/gl.h> #include "glext.h" #define STRINGIFY2(x) #x // Thanks sooda! #define STRINGIFY(x) STRINGIFY2(x) #define CHECK_ERRORS() assertGlError(STRINGIFY(__LINE__)) static GLchar* getErrorString(GLenum errorCode) { if (errorCode == GL_NO_ERROR) { return (GLchar*) "No error"; } else if (errorCode == GL_INVALID_VALUE) { return (GLchar*) "Invalid value"; } else if (errorCode == GL_INVALID_ENUM) { return (GLchar*) "Invalid enum"; } else if (errorCode == GL_INVALID_OPERATION) { return (GLchar*) "Invalid operation"; } else if (errorCode == GL_STACK_OVERFLOW) { return (GLchar*) "Stack overflow"; } else if (errorCode == GL_STACK_UNDERFLOW) { return (GLchar*) "Stack underflow"; } else if (errorCode == GL_OUT_OF_MEMORY) { return (GLchar*) "Out of memory"; } return (GLchar*) "Unknown"; } static void assertGlError(const char* error_message) { const GLenum ErrorValue = glGetError(); if (ErrorValue == GL_NO_ERROR) return; const char* APPEND_DETAIL_STRING = ": %s\n"; const size_t APPEND_LENGTH = strlen(APPEND_DETAIL_STRING) + 1; const size_t message_length = strlen(error_message); MessageBox(NULL, error_message, getErrorString(ErrorValue), 0x00000000L); ExitProcess(0); } #else #define CHECK_ERRORS() #endif
13,491
https://github.com/ltbrdg/LightBridgeAndChadBishop/blob/master/resources/views/pages/make-belief-branding.twig
Github Open Source
Open Source
MIT
null
LightBridgeAndChadBishop
ltbrdg
Twig
Code
48
112
{% extends template | default('page') %} {% set title = 'Make Belief Branding' %} {% set categories = 'brand photography print illustration' %} {% set thumbnail_size = 'small' %} {% set thumbnail_name = '1389081017.jpg' %} {% block page_content %} <img src="/image/original/1389081017.jpg" alt="Make Belief Branding" /> {% endblock %}
48,359
https://github.com/MarcTG/Seguro/blob/master/routes/web.php
Github Open Source
Open Source
MIT
null
Seguro
MarcTG
PHP
Code
167
2,358
<?php Route::get('/', 'Auth\LoginController@showLoginForm'); Route::post('/login', 'Auth\LoginController@login')->name('login'); Route::middleware(['auth'])->group(function(){ Route::post('/logout', 'Auth\LoginController@logout')->name('logout'); Route::get('dashboard', 'DashboardController@index')->name('dashboard'); //Bitacora Route::get('bitacora/', 'BitacoraController@index')->name('bitacora'); //roles Route::get('roles/', 'RoleController@index')->name('roles.view') ->middleware('permission:roles.view'); Route::post('roles/store', 'RoleController@store')->name('store.role') ->middleware('permission:store.role'); Route::get('roles/create', 'RoleController@create')->name('create.role') ->middleware('permission:create.role'); Route::put('roles/{role}', 'RoleController@update')->name('roles.update') ->middleware('permission:roles.edit'); Route::get('roles/{role}', 'RoleController@show')->name('show.roles') ->middleware('permission:show.roles'); Route::delete('roles/{role}', 'RoleController@destroy')->name('destroy.role') ->middleware('permission:destroy.role'); Route::get('roles/{role}/edit', 'RoleController@edit')->name('roles.edit') ->middleware('permission:roles.edit'); //usuarios Route::get('/usuario', 'UserController@viewUsers')->name('view.users') ->middleware('permission:view.users'); Route::get('/usuario/crear', 'UserController@create')->name('create.user') ->middleware('permission:create.user'); Route::post('/usuario/save', 'UserController@store')->name('store.user') ->middleware('permission:create.users'); Route::get('/usuario/eliminar/{user}', 'UserController@destroy')->name('delete.user') ->middleware('permission:delete.user'); Route::get('/usuario/editar/{user}', 'UserController@edit')->name('edit.user') ->middleware('permission:edit.user'); Route::post('/usuario/update/{user}','UserController@update')->name('update.user') ->middleware('permission:edit.user'); //Comprobante Route::get('comprobante', 'ComprobanteController@index')->name('index.comprobante') ->middleware('permission:index.comprobante'); Route::get('comprobante/delete/{id}', 'ComprobanteController@destroy')->name('delete.comprobante') ->middleware('permission:index.comprobante'); Route::get('comprobante/ver/{id}', 'ComprobanteController@view')->name('view.comprobante') ->middleware('permission:view.comprobante'); Route::get('comprobante/crear', 'ComprobanteController@create')->name('create.comprobante') ->middleware('permission:create.comprobante'); Route::post('comprobante/guardar', 'ComprobanteController@store')->name('store.comprobante') ->middleware('permission:store.comprobante'); //medidas Route::get('/medidas', 'MedidaController@index')->name('view.medidas'); Route::get('/medida/crear', 'MedidaController@create')->name('create.medida'); Route::post('/medida/guardar', 'MedidaController@store')->name('store.medida'); Route::get('/medida/eliminar/{medida}', 'MedidaController@destroy')->name('delete.medida'); Route::get('/medida/editar/{medida}', 'MedidaController@edit')->name('edit.medida'); Route::post('/medida/update/{medida}','MedidaController@update')->name('update.medida'); //materia Route::get('/materia_prima', 'MateriaPrimaController@index')->name('view.materia_primas'); Route::get('/materia_prima/crear', 'MateriaPrimaController@create')->name('create.materia_prima'); Route::post('/materia_prima/guardar', 'MateriaPrimaController@store')->name('store.materia_prima'); Route::get('/materia_prima/eliminar/{materia_prima}', 'MateriaPrimaController@destroy')->name('delete.materia_prima'); Route::get('/materia_prima/editar/{materia_prima}', 'MateriaPrimaController@edit')->name('edit.materia_prima'); Route::post('/materia_prima/update/{materia_prima}','MateriaPrimaController@update')->name('update.materia_prima'); //Proveedor Route::get('/proveedor', 'ProveedorController@index')->name('view.proveedors') ; Route::get('/proveedor/crear', 'ProveedorController@create')->name('create.proveedor') ; Route::post('/proveedor/guardar', 'ProveedorController@store')->name('store.proveedor') ; Route::get('/proveedor/eliminar/{proveedor}', 'ProveedorController@destroy')->name('delete.proveedor') ; Route::get('/proveedor/editar/{proveedor}', 'ProveedorController@edit')->name('edit.proveedor'); Route::post('/proveedor/update/{proveedor}','ProveedorController@update')->name('update.proveedor'); //Productos Route::get('/producto', 'ProductoController@index')->name('index.productos'); Route::get('/producto/crear', 'ProductoController@create')->name('create.producto'); Route::get('/producto/{producto}', 'ProductoController@show')->name('show.productos'); Route::post('/producto/guardar', 'ProductoController@store')->name('store.producto'); Route::get('/producto/eliminar/{producto}', 'ProductoController@destroy')->name('delete.producto'); Route::get('/producto/editar/{producto}', 'ProductoController@edit')->name('edit.producto'); Route::post('/producto/update/{producto}','ProductoController@update')->name('update.producto'); //Recetas Route::get('/recetas', 'RecetaController@index')->name('index.receta'); Route::get('/receta/crear', 'RecetaController@create')->name('create.receta'); Route::get('/receta/{receta}', 'RecetaController@show')->name('show.receta'); Route::post('/receta/guardar', 'RecetaController@store')->name('store.receta'); Route::get('/receta/eliminar/{receta}', 'RecetaController@destroy')->name('delete.receta'); Route::get('/receta/editar/{receta}', 'RecetaController@edit')->name('edit.receta'); Route::post('/receta/update/{receta}','RecetaController@update')->name('update.receta'); //inventario Route::get('/inventario', 'InventarioController@index')->name('index.inventario'); Route::get('/inventario/crear', 'InventarioController@create')->name('create.inventario'); Route::get('/inventario/{inventario}', 'InventarioController@show')->name('show.inventario'); Route::post('/inventario/guardar', 'InventarioController@store')->name('store.inventario'); Route::get('/inventario/eliminar/{inventario}', 'InventarioController@destroy')->name('delete.inventario'); Route::get('/inventario/editar/{inventario}', 'InventarioController@edit')->name('edit.inventario'); Route::post('/inventario/update/{inventario}','InventarioController@update')->name('update.inventario'); Route::post('/inventario/finish/{inventario}','InventarioController@finish')->name('finish.inventario'); //Cliente Route::get('/cliente', 'ClienteController@index')->name('index.cliente'); Route::get('/cliente/crear', 'ClienteController@create')->name('create.cliente'); Route::get('/cliente/{cliente}', 'ClienteController@show')->name('show.cliente'); Route::post('/cliente/guardar', 'ClienteController@store')->name('store.cliente'); Route::get('/cliente/eliminar/{cliente}', 'ClienteController@destroy')->name('delete.cliente'); Route::get('/cliente/editar/{cliente}', 'ClienteController@edit')->name('edit.cliente'); Route::post('/cliente/update/{cliente}','ClienteController@update')->name('update.cliente'); });
48,872
https://github.com/mod1fy/TheraLang/blob/master/TheraLang.DLL/Models/ProjectTypeModel.cs
Github Open Source
Open Source
MIT
null
TheraLang
mod1fy
C#
Code
16
41
namespace TheraLang.DLL.Models { public class ProjectTypeModel { public string TypeName { get; set; } } }
14,974
https://github.com/webwizard0822/LMS-Masterstudy/blob/master/stm-lms-templates/account/private/student.php
Github Open Source
Open Source
MIT
null
LMS-Masterstudy
webwizard0822
PHP
Code
58
347
<?php if ( ! defined( 'ABSPATH' ) ) exit; //Exit if accessed directly ?> <?php /** * @var $current_user */ ?> <div class="row"> <div class="col-md-4 col-sm-12"> <?php STM_LMS_Templates::show_lms_template('account/private/parts/info', compact('current_user')); ?> </div> <div class="col-md-8 col-sm-12"> <div class="stm_lms_private_information" data-container-open=".stm_lms_private_information"> <?php STM_LMS_Templates::show_lms_template('account/private/parts/name_and_socials', compact('current_user')); ?> <?php STM_LMS_Templates::show_lms_template('account/private/parts/bio', compact('current_user')); ?> <?php STM_LMS_Templates::show_lms_template('account/private/parts/tabs', compact('current_user')); ?> </div> <?php STM_LMS_Templates::show_lms_template('account/private/parts/edit_account', array('current_user' => $current_user)); ?> </div> </div>
49,290
https://github.com/isabella232/helix-harmonicabsorber-reports/blob/master/report_00033_2021-03-01T14-23-16.841Z/interactive/comparison/histogram/1_vs_2.gnuplot
Github Open Source
Open Source
W3C, Apache-2.0
2,021
helix-harmonicabsorber-reports
isabella232
Gnuplot
Code
72
234
reset $astroCached <<EOF 16502.38717422109 100 EOF $astroInner <<EOF 11001.591449480726 100 EOF set key outside below set boxwidth 5500.795724740363 set xrange [9481.04:14959.5125] set yrange [0:100] set trange [0:100] set style fill transparent solid 0.5 noborder set parametric set terminal svg size 640, 500 enhanced background rgb 'white' set output "reports/report_00033_2021-03-01T14-23-16.841Z/interactive/comparison/histogram/1_vs_2.svg" plot $astroCached title "astro-cached" with boxes, \ $astroInner title "astro-inner" with boxes, \ 3785,t title "score p10=3785", \ 7300,t title "score median=7300" reset
33,511
https://github.com/erickwang108/js-web-tools/blob/master/src/__tests__/domElementPosition.test.js
Github Open Source
Open Source
MIT
2,020
js-web-tools
erickwang108
JavaScript
Code
702
2,251
import { scrollLeft, getOffset, offsetParent, scrollPrarent, position, } from '../domElementPosition'; import css from '../domElementStyle'; function createMockElement(width, height, top = 0, left = 0) { const newEle = document.createElement("div"); newEle.style.cssText = `width:${width}px;height:${height}px;`; newEle.getBoundingClientRect = () => ({ width, height, top, left, right: width, bottom: height, }); return newEle; } describe('position', () => { describe('Scroll', () => { it('scrollLeft', () => { expect(scrollLeft(window)).toEqual(0); }); }); describe('Position offset', () => { let mockEle = null; beforeEach(() => { mockEle = createMockElement(300, 400); document.body.appendChild(mockEle); }); afterEach(() => { document.body.removeChild(mockEle); }); it('should get default offset', () => { Object.defineProperty(mockEle, 'ownerDocument', { value: 'abc', }); const offset = getOffset(mockEle); expect(offset).toMatchObject({ top: 0, left: 0, width: 0, height: 0, }); }); it('should get offset', () => { const offset = getOffset(mockEle); expect(offset).toMatchObject({ top: 0, left: 0, width: 300, height: 400, }); }); }); describe('Position scroll prarent', () => { it('should get document element', () => { const mockNode = createMockElement(160, 160); document.body.appendChild(mockNode); const doc = offsetParent(mockNode); expect(doc).toEqual(document.documentElement); mockNode.parentNode.removeChild(mockNode); }); it('should get parent node', () => { document.body.innerHTML = ` <ul class="level-1"> <li class="item-i">I</li> <li class="item-ii" style="position: relative;">II <ul class="level-2" style="position: static;"> <li class="item-a">A</li> <li class="item-b">B</li> <li class="item-c">C</li> </ul> </li> <li class="item-iii">III</li> </ul> `; Object.defineProperty(HTMLElement.prototype, 'offsetParent', { get() { return this.parentNode; }, }); const doc = offsetParent(document.querySelector('.item-a')); expect(doc).toEqual(document.querySelector('.item-ii')); Object.defineProperty(HTMLElement.prototype, 'offsetParent', { get() { return null; }, }); document.body.innerHTML = ''; }); it('should get document node', () => { document.body.innerHTML = ` <div class="content" style="position:fixed"> This is content. </div> `; const ele = document.querySelector('.content'); expect(scrollPrarent(ele)).toEqual(document); Object.defineProperty(ele, 'ownerDocument', { value: null }); expect(scrollPrarent(ele)).toEqual(document); document.body.innerHTML = ''; }); it('should get document when content position is not fixed', () => { document.body.innerHTML = ` <div class="content"> This is content. </div> `; const ele = document.querySelector('.content'); expect(scrollPrarent(ele)).toEqual(document); document.body.innerHTML = ''; }); it('should scroll prarent node', () => { document.body.innerHTML = ` <div class="outer" style="width:200px;height:200px;overflow-y:scroll;"> <div class="inner" style="position:static;width:200px;height:400px;"> <div class="content" style="position:absolute;width:300px;height:400px;scrollHeight:600px;"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div> </div> </div> `; const contentEle = document.querySelector('.content'); document.querySelectorAll('div').forEach((ele) => { if (ele.style.cssText !== '') { const width = parseInt(css(ele, 'width'), 10); const height = parseInt(css(ele, 'height'), 10); ele.getBoundingClientRect = () => ({ width, height, top: 0, left: 0, right: width, bottom: height, }); Object.defineProperty(ele, 'scrollHeight', { configurable: true, value: 500 }); } }); const doc = scrollPrarent(contentEle); expect(doc).toEqual(document.querySelector('.outer')); document.body.innerHTML = ''; }); }); describe('Position', () => { it('should get node client rect', () => { document.body.innerHTML = ` <div id="outer" style="margin-top:20px;"> <div id="inner" style="position:fixed;width:200px;height:200px;top:24px;left:32px;margin-left:25px;"> inner content </div> </div> `; document.querySelectorAll('div').forEach((ele) => { if (ele.style.cssText !== '') { const width = parseInt(css(ele, 'width'), 10) || 0; const height = parseInt(css(ele, 'height'), 10) || 0; const top = parseInt(css(ele, 'top'), 10) || 0; const left = parseInt(css(ele, 'left'), 10) || 0; ele.getBoundingClientRect = () => ({ width, height, top, left, right: width, bottom: height, }); } }); const eleInner = document.getElementById('inner'); const eleOuter = document.getElementById('outer'); const pos = position(eleInner, eleOuter); expect(pos).toMatchObject({ left: 7, top: 24 }); document.body.innerHTML = ''; }); it('should get parent position', () => { const eleInnter = createMockElement(50, 50, 35, 15); const outerInnter = createMockElement(150, 150, 15, 10); outerInnter.appendChild(eleInnter); document.body.appendChild(outerInnter); Object.defineProperty(HTMLElement.prototype, 'offsetParent', { get() { return this.parentNode; }, }); const pos = position(eleInnter); expect(pos).toMatchObject({ left: 5, top: 20 }); document.body.innerHTML = ''; }); it('should get parent position', () => { const eleInnter = createMockElement(50, 50, 35, 15); const outerInnter = createMockElement(150, 150, 15, 10); outerInnter.appendChild(eleInnter); document.body.appendChild(outerInnter); Object.defineProperty(HTMLElement.prototype, 'offsetParent', { get() { return this.parentNode; }, }); const pos = position(eleInnter); expect(pos).toMatchObject({ left: 5, top: 20 }); document.body.innerHTML = ''; }); }); });
43,430
https://github.com/RonnChyran/java-stuff/blob/master/com/ronnchyran/ics3u1/arrays/allarrays/AllArrays3.java
Github Open Source
Open Source
Unlicense
null
java-stuff
RonnChyran
Java
Code
118
289
/* File Name: AllArrays3.java Name: Ronny Chan Class: ICS3U1-31 (B) Date: April 5, 2016 Description: Fills array with values, and reverses them. Notes: The length of one tab (\t) will treated as 5 spaces (c) 2016 Ronny Chan Licensed under the MIT License */ import java.util.*; // public class AllArrays3 { public static void main(String[] args) { int[][] data = {{3, 2, 5}, {1, 4, 4, 8, 13}, {9, 1, 0, 2}, {0, 2, 6, 4, -1, -8}}; int sum = 0; for (int[] row : data) { for (int value : row) { sum += value; } } System.out.println("The sum of all values in the data is " + sum); } //static void main }// AllArrays3 class
2,756
https://github.com/Kri-Ol/Convolution-of-Distributions/blob/master/ConvolutionPERT/PERT.cs
Github Open Source
Open Source
MIT
null
Convolution-of-Distributions
Kri-Ol
C#
Code
105
303
using System; using System.Diagnostics; namespace Convolution { // implemented according to https://en.wikipedia.org/wiki/PERT_distribution class PERT { public static double PDF(double x, double min, double mod, double max) { Debug.Assert(min < max); Debug.Assert(mod <= max); Debug.Assert(mod >= min); if (x < min) return 0.0; if (x > max) return 0.0; var range = max - min; var alpha = (4.0*mod + max - 5.0*min)/range; var beta = (5.0*max - min - 4.0*mod)/range; var v = Math.Pow(x - min, alpha-1.0) * Math.Pow(max - x, beta-1.0)/(Utils.Beta(alpha, beta)*Math.Pow(range, alpha+beta-1.0)); return v; } public static double CDF(double x, double min, double mod, double max) { throw new System.NotImplementedException("CDF"); } } }
34,334
https://github.com/andreyk0/mks-tft32-l-v3.0/blob/master/src/consts.rs
Github Open Source
Open Source
MIT
2,021
mks-tft32-l-v3.0
andreyk0
Rust
Code
8
41
use stm32f1xx_hal::time::Hertz; pub const SYS_FREQ: Hertz = Hertz(72_000_000);
24,246
https://github.com/tody411/SimpleMeshViewer/blob/master/src/command/FindExtremePoiintsCommand.cpp
Github Open Source
Open Source
MIT
null
SimpleMeshViewer
tody411
C++
Code
340
1,112
/*! \file FindExtremePoiintsCommand.cpp \author Tody FindExtremePoiintsCommand definition. date 2015/12/22 */ #include "FindExtremePoiintsCommand.h" #include <iostream> #include "ColorMap.h" #include "EigenUtil.h" void FindExtremePoiintsCommand::setupImp() { Mesh* mesh = _scene->mesh(); Eigen::SparseMatrix<double> L; mesh->faceLaplacian ( L, 1.0, 0.2, 0.5 ); _M = L.transpose() * L; //_M = _M.transpose() * _M; } void FindExtremePoiintsCommand::doImp () { double lambda = 1000.0; double w_r = 0.000001; Eigen::SparseMatrix<double> I = Eigen::MatrixXd::Identity ( _M.rows(), _M.cols() ).sparseView(); Eigen::SparseMatrix<double> A_cons; Eigen::VectorXd b_cons; computeWeightConstraint ( A_cons, b_cons ); Eigen::SparseMatrix<double> A = A_cons + lambda * _M + w_r * I; Eigen::VectorXd b = b_cons; Eigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver; solver.compute ( A ); if ( solver.info() != Eigen::Success ) { std::cout << "Solver Fail" << std::endl; return; } Eigen::VectorXd W = solver.solve ( b ); std::vector<int> iso_faces; Mesh* mesh = _scene->mesh(); mesh->isolatedFaces ( iso_faces ); double w_min = W.minCoeff(); for ( int i = 0; i < iso_faces.size(); i++ ) { W ( iso_faces[i] ) = w_min; } std::cout << EigenUtil::info ( W, "W" ); Eigen::MatrixXd C; ColorMap::heatMap ( W, C ); mesh->setFaceColors ( C ); _scene->setMeshDisplayMode ( Mesh::DisplayMode::FACE_COLOR ); } void FindExtremePoiintsCommand::computeWeightConstraint ( Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b ) { std::vector<int> faceIDs; _scene->selectionInfo()->faceSelection ( faceIDs ); if ( faceIDs.empty() ) { faceIDs.push_back ( 0 ); } int numFaces = _scene->mesh()->numFaces(); b = Eigen::VectorXd::Zero ( faceIDs.size() ); MeshData* mesh = _scene->mesh()->openMeshData(); MeshData::FaceIter f_it; MeshData::FaceFaceIter ff_it; Eigen::SparseMatrix<double> L ( faceIDs.size(), numFaces ); double w_cons = 10.0; for ( int si = 0; si < faceIDs.size(); si++ ) { int seed_face = faceIDs[si]; int ff_faces = 0; for ( ff_it = mesh->ff_begin ( mesh->face_handle ( seed_face ) ); ff_it.is_valid(); ++ff_it ) { int ffi = ff_it->idx(); L.insert ( si, ffi ) = -1.0; ff_faces += 1; } L.insert ( si, seed_face ) = ff_faces; b ( si ) = -ff_faces; } L.makeCompressed(); b = L.transpose() * b; A = L.transpose() * L; Eigen::SparseMatrix<double> A_cons ( faceIDs.size(), numFaces ); for ( int si = 0; si < faceIDs.size(); si++ ) { int seed_face = faceIDs[si]; A_cons.insert ( si, seed_face ) = w_cons; } A = A + A_cons.transpose() * A_cons; }
18,592
https://github.com/codefollower/Open-Source-Research/blob/master/Javac2007/流程/code/021Symbol/TypeSymbol.java
Github Open Source
Open Source
Apache-2.0
2,022
Open-Source-Research
codefollower
Java
Code
461
1,082
/** A class for type symbols. Type variables are represented by instances * of this class, classes and packages by instances of subclasses. */ public static class TypeSymbol extends Symbol implements TypeParameterElement { // Implements TypeParameterElement because type parameters don't // have their own TypeSymbol subclass. // TODO: type parameters should have their own TypeSymbol subclass public TypeSymbol(long flags, Name name, Type type, Symbol owner) { super(TYP, flags, name, type, owner); } /** form a fully qualified name from a name and an owner */ static public Name formFullName(Name name, Symbol owner) { if (owner == null) return name; if (((owner.kind != ERR)) && ((owner.kind & (VAR | MTH)) != 0 || (owner.kind == TYP && owner.type.tag == TYPEVAR) )) return name; Name prefix = owner.getQualifiedName(); if (prefix == null || prefix == prefix.table.empty) return name; else return prefix.append('.', name); } /** form a fully qualified name from a name and an owner, after * converting to flat representation */ static public Name formFlatName(Name name, Symbol owner) { if (owner == null || (owner.kind & (VAR | MTH)) != 0 || (owner.kind == TYP && owner.type.tag == TYPEVAR) ) return name; char sep = owner.kind == TYP ? '$' : '.'; Name prefix = owner.flatName(); if (prefix == null || prefix == prefix.table.empty) return name; else return prefix.append(sep, name); } /** * A total ordering between type symbols that refines the * class inheritance graph. * * Typevariables always precede other kinds of symbols. */ public final boolean precedes(TypeSymbol that, Types types) { if (this == that) return false; if (this.type.tag == that.type.tag) { if (this.type.tag == CLASS) { return types.rank(that.type) < types.rank(this.type) || types.rank(that.type) == types.rank(this.type) && that.getQualifiedName().compareTo(this.getQualifiedName()) < 0; } else if (this.type.tag == TYPEVAR) { return types.isSubtype(this.type, that.type); } } return this.type.tag == TYPEVAR; } // For type params; overridden in subclasses. public ElementKind getKind() { return ElementKind.TYPE_PARAMETER; } public java.util.List<Symbol> getEnclosedElements() { List<Symbol> list = List.nil(); for (Scope.Entry e = members().elems; e != null; e = e.sibling) { if (e.sym != null && (e.sym.flags() & SYNTHETIC) == 0 && e.sym.owner == this) list = list.prepend(e.sym); } return list; } // For type params. // Perhaps not needed if getEnclosingElement can be spec'ed // to do the same thing. // TODO: getGenericElement() might not be needed public Symbol getGenericElement() { return owner; } public <R, P> R accept(ElementVisitor<R, P> v, P p) { assert type.tag == TYPEVAR; // else override will be invoked return v.visitTypeParameter(this, p); } public List<Type> getBounds() { TypeVar t = (TypeVar)type; Type bound = t.getUpperBound(); if (!bound.isCompound()) return List.of(bound); ClassType ct = (ClassType)bound; if (!ct.tsym.erasure_field.isInterface()) { return ct.interfaces_field.prepend(ct.supertype_field); } else { // No superclass was given in bounds. // In this case, supertype is Object, erasure is first interface. return ct.interfaces_field; } } }
35,538
https://github.com/teetrinkers/eisbaer/blob/master/app/src/main/java/de/theess/eisbaer/log/NoLogTree.kt
Github Open Source
Open Source
CC-BY-4.0, MIT
2,021
eisbaer
teetrinkers
Kotlin
Code
24
68
package greenberg.moviedbshell.logging import timber.log.Timber class NoLogTree : Timber.Tree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { // no-op } }
39,336
https://github.com/siliu-group/pic-challenge-baseline/blob/master/lib/stanford_pic.py
Github Open Source
Open Source
MIT
2,021
pic-challenge-baseline
siliu-group
Python
Code
762
3,144
""" Let's get the relationships yo """ import torch import torch.nn as nn import torch.nn.parallel from torch.autograd import Variable from torch.nn import functional as F from lib.surgery import filter_dets_mask from lib.fpn.proposal_assignments.rel_assignments import rel_assignments from lib.pytorch_misc import arange from lib.object_detector import filter_det from lib.motif_pic import RelModel from lib.object_detector import Result from lib.fpn.proposal_assignments.proposal_assignments_gtbox import proposal_assignments_gtbox MODES = ('sgdet', 'sgcls', 'predcls') SIZE = 512 class RelModelStanford(RelModel): """ RELATIONSHIPS """ def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, use_resnet=False, use_proposals=False, **kwargs): """ :param classes: Object classes :param rel_classes: Relationship classes. None if were not using rel mode :param num_gpus: how many GPUS 2 use """ super(RelModelStanford, self).__init__(classes, rel_classes, mode=mode, num_gpus=num_gpus, require_overlap_det=require_overlap_det, use_resnet=use_resnet, nl_obj=0, nl_edge=0, use_proposals=use_proposals, thresh=0.01, pooling_dim=4096, use_bias=False) del self.context del self.post_lstm del self.post_emb self.rel_fc = nn.Linear(SIZE, self.num_rels) self.obj_fc = nn.Linear(SIZE, self.num_classes) self.obj_unary = nn.Linear(1024, SIZE) self.edge_unary = nn.Linear(1024, SIZE) self.edge_gru = nn.GRUCell(input_size=SIZE, hidden_size=SIZE) self.node_gru = nn.GRUCell(input_size=SIZE, hidden_size=SIZE) self.n_iter = 3 self.sub_vert_w_fc = nn.Sequential(nn.Linear(SIZE * 2, 1), nn.Sigmoid()) self.obj_vert_w_fc = nn.Sequential(nn.Linear(SIZE * 2, 1), nn.Sigmoid()) self.out_edge_w_fc = nn.Sequential(nn.Linear(SIZE * 2, 1), nn.Sigmoid()) self.in_edge_w_fc = nn.Sequential(nn.Linear(SIZE * 2, 1), nn.Sigmoid()) def message_pass(self, rel_rep, obj_rep, rel_inds): """ :param rel_rep: [num_rel, fc] :param obj_rep: [num_obj, fc] :param rel_inds: [num_rel, 2] of the valid relationships :return: object prediction [num_obj, 151], bbox_prediction [num_obj, 151*4] and rel prediction [num_rel, 51] """ # [num_obj, num_rel] with binary! numer = torch.arange(0, rel_inds.size(0)).long().cuda(rel_inds.get_device()) objs_to_outrels = rel_rep.data.new(obj_rep.size(0), rel_rep.size(0)).zero_() objs_to_outrels.view(-1)[rel_inds[:, 0] * rel_rep.size(0) + numer] = 1 objs_to_outrels = Variable(objs_to_outrels) objs_to_inrels = rel_rep.data.new(obj_rep.size(0), rel_rep.size(0)).zero_() objs_to_inrels.view(-1)[rel_inds[:, 1] * rel_rep.size(0) + numer] = 1 objs_to_inrels = Variable(objs_to_inrels) hx_rel = Variable(rel_rep.data.new(rel_rep.size(0), SIZE).zero_(), requires_grad=False) hx_obj = Variable(obj_rep.data.new(obj_rep.size(0), SIZE).zero_(), requires_grad=False) vert_factor = [self.node_gru(obj_rep, hx_obj)] edge_factor = [self.edge_gru(rel_rep, hx_rel)] for i in range(3): # compute edge context sub_vert = vert_factor[i][rel_inds[:, 0]] obj_vert = vert_factor[i][rel_inds[:, 1]] weighted_sub = self.sub_vert_w_fc( torch.cat((sub_vert, edge_factor[i]), 1)) * sub_vert weighted_obj = self.obj_vert_w_fc( torch.cat((obj_vert, edge_factor[i]), 1)) * obj_vert edge_factor.append(self.edge_gru(weighted_sub + weighted_obj, edge_factor[i])) # Compute vertex context pre_out = self.out_edge_w_fc(torch.cat((sub_vert, edge_factor[i]), 1)) * \ edge_factor[i] pre_in = self.in_edge_w_fc(torch.cat((obj_vert, edge_factor[i]), 1)) * edge_factor[ i] vert_ctx = objs_to_outrels @ pre_out + objs_to_inrels @ pre_in vert_factor.append(self.node_gru(vert_ctx, vert_factor[i])) # woohoo! done return self.obj_fc(vert_factor[-1]), self.rel_fc(edge_factor[-1]) # self.box_fc(vert_factor[-1]).view(-1, self.num_classes, 4), \ # self.rel_fc(edge_factor[-1]) def forward(self, x, im_sizes, image_offset, gt_boxes=None, gt_masks=None, gt_classes=None, gt_rels=None, pred_boxes=None, pred_masks=None, pred_fmaps=None, pred_dists=None): """ Forward pass for detection :param x: Images@[batch_size, 3, IM_SIZE, IM_SIZE] :param im_sizes: A numpy array of (h, w, scale) for each image. :param image_offset: Offset onto what image we're on for MGPU training (if single GPU this is 0) :param gt_boxes: Training parameters: :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :param train_anchor_inds: a [num_train, 2] array of indices for the anchors that will be used to compute the training loss. Each (img_ind, fpn_idx) :return: If train: scores, boxdeltas, labels, boxes, boxtargets, rpnscores, rpnboxes, rellabels if test: prob dists, boxes, img inds, maxscores, classes """ result = Result() if self.training: im_inds = gt_classes[:, 0] rois = torch.cat((im_inds.float()[:, None], gt_boxes), 1) rois, labels, result.rel_labels = proposal_assignments_gtbox(rois.data, gt_boxes.data, gt_classes.data, gt_rels.data, image_offset) pred_boxes = gt_boxes pred_masks = gt_masks result.rm_obj_labels = gt_classes[:, 1] else: im_inds = pred_boxes[:, 0].long() pred_boxes = pred_boxes[:, 1:] result.rel_dists = None rel_inds = self.get_rel_inds(result.rel_labels, im_inds, pred_boxes) rois = torch.cat((im_inds[:, None].float(), pred_boxes), 1) visual_rep = self.visual_rep(pred_fmaps, rois, rel_inds[:, 1:]) result.obj_fmap = self.obj_feature_map(pred_fmaps, rois) # Now do the approximation WHEREVER THERES A VALID RELATIONSHIP. result.rm_obj_dists, result.rel_dists = self.message_pass( F.relu(self.edge_unary(visual_rep)), self.obj_unary(result.obj_fmap), rel_inds[:, 1:]) # result.box_deltas_update = box_deltas if self.training: return result scores_nz = F.softmax(result.rm_obj_dists).data scores_nz[:, 0] = 0.0 result.obj_scores, score_ord = scores_nz[:, 1:].sort(dim=1, descending=True) result.obj_preds = score_ord[:, 0] + 1 result.obj_scores = result.obj_scores[:, 0] # # Decode here ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # if self.mode == 'predcls': # # Hack to get the GT object labels # result.obj_scores = result.rm_obj_dists.data.new(gt_classes.size(0)).fill_(1) # result.obj_preds = gt_classes.data[:, 1] # elif self.mode == 'sgdet': # order, obj_scores, obj_preds = filter_det(F.softmax(result.rm_obj_dists), # pred_boxes, # start_ind=0, # max_per_img=100, # thresh=0.00, # pre_nms_topn=6000, # post_nms_topn=300, # nms_thresh=0.3, # nms_filter_duplicates=True) # idx, perm = torch.sort(order) # result.obj_preds = rel_inds.new(result.rm_obj_dists.size(0)).fill_(1) # result.obj_scores = result.rm_obj_dists.data.new(result.rm_obj_dists.size(0)).fill_(0) # result.obj_scores[idx] = obj_scores.data[perm] # result.obj_preds[idx] = obj_preds.data[perm] # else: # scores_nz = F.softmax(result.rm_obj_dists).data # scores_nz[:, 0] = 0.0 # result.obj_scores, score_ord = scores_nz[:, 1:].sort(dim=1, descending=True) # result.obj_preds = score_ord[:, 0] + 1 # result.obj_scores = result.obj_scores[:, 0] result.obj_preds = Variable(result.obj_preds) result.obj_scores = Variable(result.obj_scores) # Set result's bounding boxes to be size # [num_boxes, topk, 4] instead of considering every single object assignment. # twod_inds = arange(result.obj_preds.data) * self.num_classes + result.obj_preds.data # # if self.mode == 'sgdet': # bboxes = result.boxes_all.view(-1, 4)[twod_inds].view(result.boxes_all.size(0), 4) # else: # # Boxes will get fixed by filter_dets function. # bboxes = result.rm_box_priors rel_rep = F.softmax(result.rel_dists) return filter_dets_mask(pred_boxes, pred_masks, result.obj_scores, result.obj_preds, rel_inds[:, 1:], rel_rep)
46,737
https://github.com/mypebble/crm-browser-extension/blob/master/src/collections/entity.js
Github Open Source
Open Source
FSFAP
null
crm-browser-extension
mypebble
JavaScript
Code
45
167
import Bb from 'backbone'; export default Bb.Collection.extend({ url: function(){ return `{{ crm_location }}/entity/?search=${this.search}`; }, parse: function(r){ return r['results']; }, fetch: function(){ if(this.isFetching) return; else{ this.isFetching = true; return Bb.Collection.prototype.fetch.call(this, arguments).always(() => { this.isFetching = false; }); } }, initialize: function(){ this.isFetching = false; } });
21,172
https://github.com/VictorEDA/alpha/blob/master/src/main/java/org/alpha/entities/BaseEntity.java
Github Open Source
Open Source
Apache-2.0
null
alpha
VictorEDA
Java
Code
447
1,090
package org.alpha.entities; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.Min; import org.alpha.Helper; /** * The base entity for all JPA classes. */ @MappedSuperclass public abstract class BaseEntity implements Serializable { /** * Generated UID needed for Serializable implementation. */ private static final long serialVersionUID = -8854612366680978064L; /** * The maximum size, in bytes, of access token. */ public static final int ACCESS_TOKEN_MAX_SIZE = 255; /** * The unique item id. */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Min(value = 0) @Column(name = "id") private long id; /** * The date of entity creation. The timestamp should be automatically set by persistence to NOW when * entity is created. */ @Column(name = "created_at", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date createdAt; /** * The date when entity was updated. The timestamp should be automatically updated by persistence. */ @Column(name = "updated_at", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date updatedAt; /** * Default constructor. */ protected BaseEntity() { // empty } /** * Set the timestamps on create. */ @PrePersist protected void onCreate() { createdAt = new Date(); updatedAt = createdAt; } /** * Set the update timestamp on update. */ @PreUpdate protected void onUpdate() { updatedAt = new Date(); } /** * Retrieves the 'id' variable. * @return the 'id' variable value */ public long getId() { return id; } /** * Sets the 'id' variable. * @param id the new 'id' variable value to set */ public void setId(long id) { this.id = id; } /** * Retrieves the 'createdAt' variable. * @return the 'createdAt' variable value */ public Date getCreatedAt() { return createdAt; } /** * Sets the 'createdAt' variable. * @param createdAt the new 'createdAt' variable value to set */ public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } /** * Retrieves the 'updatedAt' variable. * @return the 'updatedAt' variable value */ public Date getUpdatedAt() { return updatedAt; } /** * Sets the 'updatedAt' variable. * @param updatedAt the new 'updatedAt' variable value to set */ public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } /** * Override the default toString method for logging purposes. * @return JSON string */ @Override public String toString() { return Helper.toJsonString(this); } /** * Create hash code. * @return the hash code */ @Override public int hashCode() { return (int) id; } /** * The equals method. * @param obj the object to compare to * @return true if the provided object is equal to this object */ @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass() || id == 0) { return false; } return id == ((BaseEntity) obj).id; } }
35,460
https://github.com/LaudateCorpus1/More/blob/master/ByteString/ByteString.cs
Github Open Source
Open Source
MIT
2,021
More
LaudateCorpus1
C#
Code
1,113
2,798
// © Copyright 2016 HP Development Company, L.P. // SPDX-License-Identifier: MIT using System; namespace More { public static class Ascii { public static Boolean StartsWithAscii(this String value, Byte[] text, UInt32 offset, UInt32 length) { return StartsWithAscii(value, 0, text, offset, length); } public static Boolean StartsWithAscii(this String value, UInt32 stringOffset, Byte[] text, UInt32 offset, UInt32 length) { if (length > value.Length) return false; for (UInt32 i = 0; i < length; i++) { if (text[offset + i] != value[(int)(stringOffset + i)]) return false; } return true; } public static Boolean EqualsAscii(this String value, Byte[] text, UInt32 offset, UInt32 length) { return EqualsAscii(value, 0, text, offset, length); } public static Boolean EqualsAscii(this String value, UInt32 stringOffset, Byte[] text, UInt32 offset, UInt32 length) { if (length != value.Length) return false; for (UInt32 i = 0; i < length; i++) { if (text[offset + i] != value[(int)(stringOffset + i)]) return false; } return true; } /// <summary>The maximum number of bytes it would take to encode a C# Char type</summary> public const UInt32 MaxCharEncodeLength = 3; public static Byte GetCharEncodeLength(Char c) { return 1; } public static UInt32 GetEncodeLength(String str) { return (uint)str.Length; } // Returns the offset after encoding the character public static UInt32 EncodeChar(Char c, Byte[] buffer, UInt32 offset) { buffer[offset] = (Byte)c; return offset + 1; } // Returns the offset after encoding the character // Note: it is assumed that the caller will have already calculated the encoded length, for // that reason, this method does not return the offset after the encoding public static UInt32 Encode(String str, Byte[] buffer, UInt32 offset) { for (int i = 0; i < str.Length; i++) { buffer[offset++] = (Byte)str[i]; } return offset; } // Returns the offset after encoding the character // Note: it is assumed that the caller will have already calculated the encoded length, for // that reason, this method does not return the offset after the encoding public static unsafe Byte* EncodeUnsafe(String str, Byte* buffer) { for (int i = 0; i < str.Length; i++) { *buffer = (Byte)str[i]; buffer++; } return buffer; } } public static class ByteString { // // Number Parsing // static UInt32 ConsumeNum(this Byte[] array, UInt32 offset, UInt32 limit) { if (offset >= limit) return offset; if (array[offset] == '-') offset++; while (true) { if (offset >= limit) return offset; var c = array[offset]; if (c < '0' || c > '9') return offset; offset++; } } // Returns the new offset of all the digits parsed. Returns 0 to indicate overflow or invalid number. public static UInt32 TryParseUInt32(this Byte[] array, UInt32 offset, UInt32 limit, out UInt32 value) { if (offset >= limit) // Invalid number { value = 0; return 0; } UInt32 result; { Byte c = array[offset]; if (c > '9' || c < '0') { value = 0; // Invalid number return 0; } result = (uint)(c - '0'); } while (true) { offset++; if (offset >= limit) break; var c = array[offset]; if (c > '9' || c < '0') break; UInt32 newResult = result * 10 + c - '0'; if (newResult < result) { value = 0; return 0; // Overflow } result = newResult; } value = result; return offset; } // Returns the new offset of all the digits parsed. Returns 0 to indicate overflow. public static UInt32 TryParseInt32(this Byte[] array, UInt32 offset, UInt32 limit, out Int32 value) { if (offset >= limit) { value = 0; return 0; } Boolean negative; { var c = array[offset]; if (c == '-') { negative = true; offset++; } else { negative = false; } } if (offset >= limit) // Invalid number { value = 0; return 0; } UInt32 result; { Byte c = array[offset]; if (c > '9' || c < '0') { value = 0; // Invalid number return 0; } result = (uint)(c - '0'); } while (true) { offset++; if (offset >= limit) break; var c = array[offset]; if (c > '9' || c < '0') break; UInt32 newResult = result * 10 + c - '0'; if (newResult < result) { value = 0; return 0; // Overflow } result = newResult; } if (negative) { if (result > ((UInt32)Int32.MaxValue) + 1) { value = 0; return 0; // Overflow } value = -(int)result; } else { if (result > (UInt32)Int32.MaxValue) { value = 0; return 0; // Overflow } value = (int)result; } value = negative ? -(Int32)result : (Int32)result; return offset; } public static UInt32 ParseByte(this Byte[] array, UInt32 offset, UInt32 limit, out Byte value) { UInt32 uint32; var newOffset = array.TryParseUInt32(offset, limit, out uint32); if (newOffset == 0 || uint32 > (UInt32)Byte.MaxValue) throw new OverflowException(String.Format("Overflow while parsing '{0}' as a Byte", System.Text.Encoding.ASCII.GetString(array, (int)offset, (newOffset == 0) ? (int)ConsumeNum(array, offset, limit) : (int)newOffset))); value = (Byte)uint32; return newOffset; } public static UInt32 ParseUInt16(this Byte[] array, UInt32 offset, UInt32 limit, out UInt16 value) { UInt32 uint32; var newOffset = array.TryParseUInt32(offset, limit, out uint32); if (newOffset == 0 || uint32 > (UInt32)UInt16.MaxValue) throw new OverflowException(String.Format("Overflow while parsing '{0}' as a UInt16", System.Text.Encoding.ASCII.GetString(array, (int)offset, (newOffset == 0) ? (int)ConsumeNum(array, offset, limit) : (int)newOffset))); value = (UInt16)uint32; return newOffset; } public static UInt32 ParseUInt32(this Byte[] array, UInt32 offset, UInt32 limit, out UInt32 value) { var newOffset = array.TryParseUInt32(offset, limit, out value); if (newOffset == 0) throw new OverflowException(String.Format("Overflow while parsing '{0}' as a UInt32", System.Text.Encoding.ASCII.GetString(array, (int)offset, (newOffset == 0) ? (int)array.ConsumeNum(offset, limit) : (int)newOffset))); return newOffset; } public static UInt32 ParseInt32(this Byte[] array, UInt32 offset, UInt32 limit, out Int32 value) { var newOffset = array.TryParseInt32(offset, limit, out value); if (newOffset == 0) throw new OverflowException(String.Format("Overflow while parsing '{0}' as a Int32", System.Text.Encoding.ASCII.GetString(array, (int)offset, (newOffset == 0) ? (int)array.ConsumeNum(offset, limit) : (int)newOffset))); return newOffset; } } public struct AsciiPartsBuilder { readonly String[] parts; readonly String[] inbetweens; public AsciiPartsBuilder(String[] parts, params String[] inbetweens) { if (inbetweens.Length + 1 != parts.Length) { throw new ArgumentException(String.Format( "parts.Length ({0}) must be equal to inbetweens.Length + 1 ({1})", parts.Length, inbetweens.Length + 1)); } this.parts = parts; this.inbetweens = inbetweens; } public UInt32 PrecalculateLength() { UInt32 totalSize = 0; for (Int32 i = 0; i < parts.Length; i++) { totalSize += (UInt32)parts[i].Length; } for (Int32 i = 0; i < inbetweens.Length; i++) { totalSize += (UInt32)inbetweens[i].Length; } return totalSize; } public unsafe void BuildInto(Byte[] dst) { UInt32 offset = 0; for (Int32 i = 0; i < parts.Length - 1; i++) { offset = Ascii.Encode(parts[i], dst, offset); offset = Ascii.Encode(inbetweens[i], dst, offset); } Ascii.Encode(parts[parts.Length - 1], dst, offset); } public unsafe void BuildInto(Byte* dst) { for (Int32 i = 0; i < parts.Length - 1; i++) { dst = Ascii.EncodeUnsafe(parts[i], dst); dst = Ascii.EncodeUnsafe(inbetweens[i], dst); } Ascii.EncodeUnsafe(parts[parts.Length - 1], dst); } } }
31,649
https://github.com/lrfbeyond/slim-admin-api/blob/master/app/Controllers/HomeController.php
Github Open Source
Open Source
MIT
2,020
slim-admin-api
lrfbeyond
PHP
Code
517
1,955
<?php namespace App\Controllers; use Psr\Log\LoggerInterface; use Slim\Http\Request; use Slim\Http\Response; use App\Models\Article; use App\Models\Member; use App\Models\Comment; use App\Models\Log; use App\Models\Catelog; class HomeController extends Controller { public function index($req, $res) { $this->logger->info("haha index"); $rs = Article::find(502); return $rs->title; } public function getTotals($request, Response $response) { $totalArticles = Article::where('is_delete', 0)->count(); $totalComments = Comment::where('is_delete', 0)->count(); $totalMembers = Member::where('is_delete', 0)->count(); $res = [ 'totalArticles' => $totalArticles, 'totalComments' => $totalComments, 'totalMembers' => $totalMembers ]; return $response->withJson($res); } // 获取最新操作日志 public function getOptLog($request, $response) { $res['result'] = 'failed'; $user_auth = $_SESSION['admin_auth']; //print_r($user_auth); if (!empty($user_auth)) { $list = Log::where('user_id', $user_auth['userid'])->orderBy('id', 'desc')->take(8)->get(['id','event','created_at']); $res['list'] = $list; $res['result'] = 'success'; } return $response->withJson($res); } // 饼状图-资讯各分类总数 public function getPieData($request, $response) { $res['result'] = 'failed'; try { $catelog = new Catelog; $cate = $catelog->getCate(); $data = []; foreach ($cate as $key => $val) { $data[] = [ 'name' => $val['title'], 'value' => Article::where('cid', $val['id'])->where('is_delete', 0)->count() ]; } $res['data'] = $data; $res['result'] = 'success'; } catch (\Exception $e) { $res['msg'] = '出错了'; } return $response->withJson($res); } // 整站折线图统计-最近30天 public function getLineData($request, $response) { $res['result'] = 'failed'; //try { $dataArticle = []; $dataMember = []; $dataComment = []; for ($i = 29; $i >= 0; $i--) { $date = date('Y-m-d', strtotime('-'.$i.' days')); $dataArticle[] = Article::where('is_delete', 0)->where('created_at', 'like', $date.'%')->count(); $dataMember[] = Member::where('is_delete', 0)->where('created_at', 'like', $date.'%')->count(); $dataComment[] = Comment::where('is_delete', 0)->where('created_at', 'like', $date.'%')->count(); } $dates = []; for ($i = 29; $i >= 0; $i--) { $dates[] = date('m月d日', strtotime('-'.$i.' days')); } $res = [ 'result' => 'success', 'date' => $dates, 'dataArticle' => $dataArticle, 'dataMember' => $dataMember, 'dataComment' => $dataComment ]; // } catch (\Exception $e) { // $res['msg'] = '出错了'; // } return $response->withJson($res); } public function test2($req, $res) { $where['is_delete'] = 0; $date = $req->getParam('date'); // if (!empty($date)) { // $where[] = ['created_at', 'like', $date.'%']; // } $keys = $req->getParam('keys'); // if (!empty($keys)) { // $where[] = ['title', 'like', '%'.$keys.'%']; // } $query = Article::query(); // if (!empty($keys)) { // $query->where('title', 'like', '%'.$keys.'%'); // } if (!empty($date)) { $query->where('created_at', 'like', $date.'%'); } $query->when(!empty($keys), function ($q) use ($keys) { return $q->where('title', 'like', '%'.$keys.'%'); }); $query->where('id', '>=', 100)->orWhere('id', '<=', 300); // $query->where(function ($q) { // return $q->where('id', '>=', 100); // })->orWhere(function ($q) { // return $q->where('id', '<=', 300); // }); $rs = $query->take(10)->orderBy('id', 'desc')->get(['id','title','created_at']); return $res->withJson($rs); exit; // $query->when(request('filter_by') == 'likes', function ($q) { // return $q->where('likes', '>', request('likes_amount', 0)); // }); // $query->when(request('filter_by') == 'date', function ($q) { // return $q->orderBy('created_at', request('ordering_rule', 'desc')); // }); // 查询所有 $rs = Article::where($where)->take(10)->orderBy('id', 'desc')->get(['id','title','created_at']); foreach ($rs as $k => $v) { //echo $v['title'] . "<br/>"; // echo $v->title.'<br/>'; } return $res->withJson($rs); //查询1个 $rs = Article::find(1); //echo $rs->title; //查询多个 $rs = Article::find([1,2,3], ['id', 'title', 'created_at']); foreach ($rs as $k => $v) { //echo $v->title.'<br/>'; } // return $res->withJson($rs); // exit; //获取第一个 //$rs = Article::where('id', '>', '2')->first(); $rs = Article::where('id', '>', '2')->first(['id', 'title']); return $res->withJson($rs); //echo $rs->title; //聚合 $count = Article::where('id', '>', 2)->count(); //echo $count; //新增 // $art = new Article; // $art->title = 'abcw我的歌'; // $rs = $art->save(); // echo $art->id; // print_r($rs); //update // $art = Article::find(1); // $art->title = '中国人民'; // $rs = $art->save(); // print_r($rs); } public function test($request, $response) { // } }
10,712
https://github.com/ling1726/Omex/blob/master/src/Extensions/Logging/EmptyExecutionContext.cs
Github Open Source
Open Source
MIT
null
Omex
ling1726
C#
Code
299
820
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Reflection; namespace Microsoft.Omex.Extensions.Logging { /// <summary> /// Base class for machine information /// </summary> public class EmptyExecutionContext : IExecutionContext { /// <summary> /// Create instance of empty execution context /// Inherit from this class to populate defined properties with proper values /// </summary> /// <remarks> /// Please keep this initialization as lightweight as possible /// </remarks> protected EmptyExecutionContext() { MachineName = DefaultEmptyValue; MachineId = DefaultEmptyValue; ApplicationName = DefaultEmptyValue; ClusterIpAddress = IPAddress.None; Cluster = MachineId; EnvironmentName = DefaultEmptyValue; DeploymentSlice = DefaultEmptyValue; RegionName = DefaultEmptyValue; ServiceName = DefaultEmptyValue; BuildVersion = DefaultEmptyValue; IsCanary = false; IsPrivateDeployment = false; } /// <inheritdoc/> public string MachineId { get; protected set; } /// <inheritdoc/> public string MachineName { get; protected set; } /// <inheritdoc/> public string ApplicationName { get; protected set; } /// <inheritdoc/> public IPAddress ClusterIpAddress { get; protected set; } /// <inheritdoc/> public string Cluster { get; protected set; } /// <inheritdoc/> public string EnvironmentName { get; protected set; } /// <inheritdoc/> public string DeploymentSlice { get; protected set; } /// <inheritdoc/> public string RegionName { get; protected set; } /// <inheritdoc/> public string ServiceName { get; protected set; } /// <inheritdoc/> public string BuildVersion { get; protected set; } /// <inheritdoc/> public bool IsCanary { get; protected set; } /// <inheritdoc/> public bool IsPrivateDeployment { get; protected set; } /// <summary>Get Machine Name from eviroment variable</summary> protected string GetMachineName() => Environment.MachineName ?? DefaultEmptyValue; /// <summary>Get ip address</summary> protected IPAddress GetIpAddress(string hostNameOrAddress) => Array.Find(Dns.GetHostAddresses(hostNameOrAddress), address => address.AddressFamily == AddressFamily.InterNetwork) ?? IPAddress.None; /// <summary>Get build version</summary> protected string GetBuildVersion() { FileVersionInfo buildVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location); return string.Concat(buildVersion.FileBuildPart, ".", buildVersion.FilePrivatePart); } /// <summary>default empty value</summary> protected readonly string DefaultEmptyValue = "None"; } }
5,234
https://github.com/ryancreatescopy/rimble-ui/blob/master/src/ToastMessage/IconNegative.js
Github Open Source
Open Source
MIT
null
rimble-ui
ryancreatescopy
JavaScript
Code
36
93
import React, { Component } from 'react' import styled from 'styled-components' import { ReactComponent as NegativeIcon } from './icon-negative.svg' const WrappedIconNegative = (props) => ( <NegativeIcon {...props} /> ) const IconNegative = styled(WrappedIconNegative)`` export default IconNegative
22,119
https://github.com/vimalcvs/Hindi-to-English-Translation/blob/master/app/src/main/java/com/vimalinc/hieg/menu/SpaceItem.java
Github Open Source
Open Source
Apache-2.0
2,021
Hindi-to-English-Translation
vimalcvs
Java
Code
92
309
package com.vimalinc.hieg.menu; import android.content.Context; import android.view.View; import android.view.ViewGroup; /** * Created by VIMALCVS on 29.04.2019. */ public class SpaceItem extends DrawerItem<SpaceItem.ViewHolder> { private int spaceDp; public SpaceItem(int spaceDp) { this.spaceDp = spaceDp; } @Override public ViewHolder createViewHolder(ViewGroup parent) { Context c = parent.getContext(); View view = new View(c); int height = (int) (c.getResources().getDisplayMetrics().density * spaceDp); view.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, height)); return new ViewHolder(view); } @Override public void bindViewHolder(ViewHolder holder) { } @Override public boolean isSelectable() { return false; } static class ViewHolder extends DrawerAdapter.ViewHolder { public ViewHolder(View itemView) { super(itemView); } } }
23,188
https://github.com/itublockchain/ava-hack-barca-frontend/blob/master/src/hooks/useStatus.js
Github Open Source
Open Source
MIT
null
ava-hack-barca-frontend
itublockchain
JavaScript
Code
178
437
import { useMemo } from "react"; import { useState } from "react"; const PENDING = "PENDING"; const SUCCESS = "SUCCESS"; const FAIL = "FAIL"; /** * @typedef {('PENDING'|'SUCCESS'|'FAIL')} statuses */ /** * Callback for updating status state * * @callback updateStatus * @param {any} [data] */ /** * Status object with useful methods and payload * * @typedef {Object} statusObject * @property {Boolean} isPending * @property {Boolean} isSuccess * @property {Boolean} isFail * @property {updateStatus} pending * @property {updateStatus} success * @property {updateStatus} fail * @property {*} payload */ /** * Get an object that will reflect the status * * @param {statuses} initialState * @returns {statusObject} */ export function useStatus(initialState = "") { const [payload, setPayload] = useState(""); const [status, setStatus] = useState(initialState); const statusObj = useMemo( () => ({ isPending: status === PENDING, isSuccess: status === SUCCESS, isFail: status === FAIL, pending: (data) => { setStatus(PENDING); if (data) setPayload(data); }, success: (data) => { setStatus(SUCCESS); if (data) setPayload(data); }, fail: (data) => { setStatus(FAIL); if (data) setPayload(data); }, payload, }), [payload, status] ); return statusObj; }
46,252
https://github.com/challe535/IntraJ/blob/master/testfiles/CFG/IfStmt/IfStmt02/IfStmt02.java
Github Open Source
Open Source
BSD-3-Clause
2,022
IntraJ
challe535
Java
Code
22
48
public class IfStmt02 { { boolean b = true; if (b) { int a; } else { int c; } } }
18,144
https://github.com/leafcxy/BrnMall/blob/master/Libraries/BrnMall.Core/Asyn/State/UpdatePVStatState.cs
Github Open Source
Open Source
MIT
2,022
BrnMall
leafcxy
C#
Code
201
535
using System; namespace BrnMall.Core { /// <summary> /// 更新PV统计要使用的信息类 /// </summary> [Serializable] public class UpdatePVStatState { private int _storeid;//店铺id private bool _ismember;//是否为会员 private int _regionid;//区域id private string _browser;//浏览器 private string _os;//操作系统 private DateTime _time;//时间 public UpdatePVStatState(int storeId, bool isMember, int regionId, string browser, string os, DateTime time) { _storeid = storeId; _ismember = isMember; _regionid = regionId; _browser = browser; _os = os; _time = time; } /// <summary> /// 店铺id /// </summary> public int StoreId { get { return _storeid; } set { _storeid = value; } } /// <summary> /// 是否为会员 /// </summary> public bool IsMember { get { return _ismember; } set { _ismember = value; } } /// <summary> /// 区域id /// </summary> public int RegionId { get { return _regionid; } set { _regionid = value; } } /// <summary> /// 浏览器 /// </summary> public string Browser { get { return _browser; } set { _browser = value; } } /// <summary> /// 操作系统 /// </summary> public string OS { get { return _os; } set { _os = value; } } /// <summary> /// 时间 /// </summary> public DateTime Time { get { return _time; } set { _time = value; } } } }
46,650
https://github.com/korgan00/NumericalMethods/blob/master/Hoja1MetodosNumericos/SerieSumPI.m
Github Open Source
Open Source
MIT
2,018
NumericalMethods
korgan00
MATLAB
Code
26
92
function p = SerieSumPI (N) M = [0:1:N]; pArr = arrayfun(@(m) ((16^-m) *( 4/(8*m+1) - (2/(8*m+4) + 1/(8*m+5) + 1/(8*m+6)) )), M); p = sum(pArr); endfunction
21,309
https://github.com/triesch/synaptic-competition/blob/master/changeInPoolSize.py
Github Open Source
Open Source
MIT
null
synaptic-competition
triesch
Python
Code
518
1,571
#!/usr/bin/env python # Simple model of receptors diffusing in and out of synapses. # Simulation of the Dynamcis with the Euler method. # This simulates the effect of a sudden change in the pool size # # Jochen Triesch, January-April 2017 import numpy as np from matplotlib import pyplot as plt # parameters N = 3 # number of synapses steps = 10000 # number of time steps to simulate duration = 10.0 # duration in minutes change_time = 2.0 # time at which number of pool size changes in minutes ts = duration/steps # time step of the simulation beta = 60.0/43.0 # transition rate out of slots in 1/min delta = 1.0/14.0 # removal rate in 1/min phi = 2.67 # relative pool size F = 0.9 # set desired filling fraction # initializations: the w_i and p are set to their steady state values s = np.zeros(N) for i in range(0,N): s[i] = 40.0 + i*20.0 S = sum(s) gamma = delta*F*S*phi # production rate set to achieve desired p* alpha = beta/(phi*S*(1-F)) # set alpha accordingly P = gamma/delta # total number of receptors in steady state # variables we want to keep track of to plot them at the end: # 'u' stands for up-regulation and 'd' stands for down-regulation. # Up- and down-regulation are simulated simultaneously. pu = np.zeros(steps) # pool size pd = np.zeros(steps) wu = np.zeros([N,steps]) # synaptic weights wd = np.zeros([N,steps]) ru = np.zeros(steps) # relative change of synaptic weights rd = np.zeros(steps) times = np.zeros(steps) pu[0] = P pd[0] = P ru[0] = 1.0 rd[0] = 1.0 for i in range(0,N): wu[i,0] = F*s[i] wd[i,0] = F*s[i] # simulation loop for t in range(0, steps-1): if t==round(change_time/ts): # change pool size after some time pu[t]=2.0*P # double number of receptors in the pool pd[t]=0.0*P # set number of receptors in the pool to zero Wu = sum(wu[:,t]) Wd = sum(wd[:,t]) wu[:,t+1] = wu[:,t] + ts * (alpha*pu[t] * (s-wu[:,t]) - beta*wu[:,t]) wd[:,t+1] = wd[:,t] + ts * (alpha*pd[t] * (s-wd[:,t]) - beta*wd[:,t]) pu[t+1] = pu[t] + ts * (beta*Wu - alpha*pu[t]*(S-Wu) - delta*pu[t] + gamma) pd[t+1] = pd[t] + ts * (beta*Wd - alpha*pd[t]*(S-Wd) - delta*pd[t] + gamma) ru[t+1] = wu[0,t+1]/wu[0,0]*100.0 rd[t+1] = wd[0,t+1]/wd[0,0]*100.0 times[t+1] = ts*(t+1) # show results f = plt.figure(figsize=(4,3)) font = {'family' : 'serif', 'weight' : 'normal', 'size' : 12} plt.rc('font', **font) plt.rc('font', serif='Times New Roman') plt.gca().set_prop_cycle(plt.cycler('color', ['blue', 'green', 'red'])) [line1, line2, line3] = plt.plot(times, np.transpose(wu)) plt.plot(times, np.transpose(wd), ls='dotted') plt.legend((line3, line2, line1), (r'$w_3$', r'$w_2$', r'$w_1$'), loc=1, fontsize=12) plt.xlabel(r'$t \; [{\rm min}]$', fontsize=12) plt.ylabel(r'$w_i$', fontsize=12) plt.title(r'$F=0.9$', fontsize=12) plt.show() f.savefig("Fig4A.pdf", bbox_inches='tight') f2 = plt.figure(figsize=(4,3)) font = {'family' : 'serif', 'weight' : 'normal', 'size' : 12} plt.rc('font', **font) plt.rc('font', serif='Times New Roman') plt.plot(times, pu, "k") plt.plot(times, pd, "k", ls='dotted') plt.xlabel(r'$t \; [{\rm min}]$', fontsize=12) plt.ylabel('pool size', fontsize=12) plt.title(r'$F=0.9$', fontsize=12) plt.show() f2.savefig("Fig4C.pdf", bbox_inches='tight') f3 = plt.figure(figsize=(4,3)) font = {'family' : 'serif', 'weight' : 'normal', 'size' : 12} plt.rc('font', **font) plt.rc('font', serif='Times New Roman') plt.plot(times, ru, "k") plt.plot(times, rd, "k", ls='dotted') plt.axis((0.0, 10.0, 40.0, 140.0)) plt.xlabel(r'$t \; [{\rm min}]$', fontsize=12) plt.ylabel(r'$w_i(t)/w_i(0) \quad [\%]$', fontsize=12) plt.title(r'$F=0.9$', fontsize=12) plt.show() f3.savefig("Fig4B.pdf", bbox_inches='tight')
1,942
https://github.com/v3p/Cactus-game/blob/master/data/class/console.lua
Github Open Source
Open Source
MIT
2,020
Cactus-game
v3p
Lua
Code
1,456
5,060
local console = {} --==[[ < INTERNAL METHODS > ]]==-- function console:updateTextboxIndicator() self.textBox.indicator.x = self.textBox.x + self.margin.x + self.font:getWidth(self.sub(self.textBox.text, 1, self.textBox.indicator.position)) - 2 if self.textBox.indicator.x > self.textBox.x + self.textBox.width - self.margin.x - 2 then self.textBox.indicator.x = self.textBox.x + self.textBox.width - self.margin.x - 2 end if self.textBox.indicator.position == 0 then self.textBox.indicator.x = self.textBox.x + self.margin.x elseif self.textBox.indicator.position == 1 then self.textBox.indicator.x = self.textBox.x + self.margin.x + self.font:getWidth(self.sub(self.textBox.text, 1, 1)) -2 end self.textBox.indicator.t = math.pi / 2 end function console:positionTextboxText() if self.font:getWidth(self.sub(self.textBox.text, 1, self.textBox.indicator.position)) >= self.textBox.width - (self.margin.x * 2) then self.textBox.textX = (self.textBox.x + self.textBox.width - self.margin.x) - self.font:getWidth(self.sub(self.textBox.text, 1, self.textBox.indicator.position)) else self.textBox.textX = self.textBox.x + self.margin.x end end function console:clearTextBox() self.textBox.history[#self.textBox.history + 1] = self.textBox.text self.textBox.historyPosition = #self.textBox.history self.textBox.text = "" self:updateTextboxIndicator() self:positionTextboxText() end function console:lua(text) local status, err = pcall(loadstring(text)) err = err or false if err then self:print("LUA: "..tostring(err)) end end function console:clearHistory() self.history.text = {} self.history.position = 1 end local function wrapString(text, maxWidth, font) maxWidth = maxWidth or love.graphics.getWidth() font = font or love.graphics.getFont() local words = {} local str = "" local lineWidth = 0 local lineCount = 1 text:gsub("([^ ]+)", function(c) words[#words+1] = c.." " end) for i,v in ipairs(words) do local n = lineWidth + font:getWidth(v) if n > maxWidth then str = str.."\n" lineCount = lineCount + 1 lineWidth = 0 end str = str..v lineWidth = lineWidth + font:getWidth(v) end return str, lineCount, (font:getAscent() - font:getDescent()) * lineCount end --STRING FUNCTIONS function console.getCharBytes(string, char) char = char or 1 local b = string.byte(string, char) local bytes = 1 if b > 0 and b <= 127 then bytes = 1 elseif b >= 194 and b <= 223 then bytes = 2 elseif b >= 224 and b <= 239 then bytes = 3 elseif b >= 240 and b <= 244 then bytes = 4 end return bytes end function console.len(str) local pos = 1 local len = 0 while pos <= #str do len = len + 1 pos = pos + console.getCharBytes(str, pos) end return len end function console.sub(str, s, e) s = s or 1 e = e or console.len(str) if s < 1 then s = 1 end if e < 1 then e = console.len(str) + e + 1 end if e > console.len(str) then e = console.len(str) end if s > e then return "" end local sByte = 0 local eByte = 1 local pos = 1 local i = 0 while pos <= #str do i = i + 1 if i == s then sByte = pos end pos = pos + console.getCharBytes(str, pos) if i == e then eByte = pos - 1 break end end return string.sub(str, sByte, eByte) end function console.setAlpha(a) local r, g, b, _a = love.graphics.getColor() setColor(r, g, b, a) end --==[[ < PUBLIC METHODS > ]]==-- --CALLBACKS function console:init(x, y, width, height, visible, font) --Outside variables self.userKeyRepeat = love.keyboard.hasKeyRepeat() --Defaults x = x or 0 y = y or 0 width = width or love.graphics.getWidth() height = height or love.graphics.getHeight() visible = visible or true font = font or love.graphics.newFont(16) love.keyboard.setKeyRepeat(visible) --Options self.x = x self.y = y self.margin = { x = 8, y = 4 } self.width = width self.height = height self.font = font self.visible = visible --Elements self.textBox = { x = self.x, y = self.y + self.height - (self.font:getAscent() - font:getDescent() + (self.margin.y * 2)), textX = self.margin.x, width = self.width, height = (self.font:getAscent() - font:getDescent()) + (self.margin.y * 2), text = "", indicator = { x = self.x + self.margin.x, position = 0, char = "|", t = 0, alpha = 1, flashRate = 6 }, color = { box = {0, 0, 0, 200}, text = {255, 255, 255, 255} }, history = {}, historyPosition = 1, mode = "input" } self.history = { x = self.x, y = self.y, yOffset = 0, width = self.width, height = self.height - self.textBox.height, totalTextHeight = 0, scrollSpeed = 32, color = { box = {0, 0, 0, 150}, text = {200, 200, 200, 255} }, text = {}, maxHistory = 64 } end function console:resize(width, height) self.width = width self.height = height self.textBox.width = width self.textBox.y = height - self.textBox.height self.history.width = width self.history.height = height - self.textBox.height for i,v in ipairs(self.history.text) do local text, lines, height = wrapString(v.textRaw, width, self.font) v.text = text v.lines = lines v.height = height end end function console:update(dt) if self.visible then --Textbox Indicator self.textBox.indicator.t = self.textBox.indicator.t + self.textBox.indicator.flashRate * dt if self.textBox.indicator.t > math.pi then self.textBox.indicator.t = 0 end end end function console:draw() if self.visible then --Textbox console.setAlpha(1) love.graphics.setScissor(self.textBox.x, self.textBox.y, self.textBox.width, self.textBox.height) love.graphics.setFont(self.font) setColor(self.textBox.color.box) love.graphics.rectangle("fill", self.textBox.x, self.textBox.y, self.textBox.width, self.textBox.height) setColor(self.textBox.color.text) love.graphics.print(self.textBox.text, self.textBox.textX, self.textBox.y + self.margin.y) --textBox indicator lg.setColor(1, 1, 1, 1) console.setAlpha(math.sin(self.textBox.indicator.t)) love.graphics.print(self.textBox.indicator.char, self.textBox.indicator.x, self.textBox.y + self.margin.y) love.graphics.setScissor() --History console.setAlpha(1) love.graphics.setScissor(self.history.x, self.history.y, self.history.width, self.history.height) setColor(self.history.color.box) love.graphics.rectangle("fill", self.history.x, self.history.y, self.history.width, self.history.height) local y = (self.history.y + self.history.height - self.margin.y) + self.history.yOffset for i=#self.history.text, 1, -1 do local v = self.history.text[i] y = y - v.height setColor(v.color) love.graphics.print(v.text, self.history.x + self.margin.x, y) end love.graphics.setScissor() end end function console:textinput(t) if self.visible then if self.textBox.indicator.position == self.len(self.textBox.text) then self.textBox.text = self.textBox.text..t else if self.textBox.indicator.position > 0 then local b = self.sub(self.textBox.text, 1, self.textBox.indicator.position) local e = self.sub(self.textBox.text, self.textBox.indicator.position + 1) self.textBox.text = b..t..e else self.textBox.text = t..self.textBox.text end end self.textBox.indicator.position = self.textBox.indicator.position + 1 if self.textBox.indicator.position >= self.len(self.textBox.text) then self.textBox.indicator.position = self.len(self.textBox.text) end self.textBox.mode = "input" self:updateTextboxIndicator() self:positionTextboxText() end end function console:keypressed(key) if self.visible then if key == "backspace" then if #self.textBox.text > 0 then if self.textBox.indicator.position == self.len(self.textBox.text) then self.textBox.text = console.sub(self.textBox.text, 1, -2) else if self.textBox.indicator.position > 0 then if self.textBox.indicator.position > 1 then local b = self.sub(self.textBox.text, 1, self.textBox.indicator.position - 1) local e = self.sub(self.textBox.text, self.textBox.indicator.position + 1) self.textBox.text = b..e else self.textBox.text = self.sub(self.textBox.text, 2) end end end self.textBox.indicator.position = self.textBox.indicator.position - 1 if self.textBox.indicator.position < 0 then self.textBox.indicator.position = 0 end self.textBox.mode = "input" self:updateTextboxIndicator() self:positionTextboxText() end elseif key == "up" then if #self.textBox.history > 0 then if self.textBox.mode == "history" then self.textBox.historyPosition = self.textBox.historyPosition - 1 if self.textBox.historyPosition < 1 then self.textBox.historyPosition = 1 end else if #self.textBox.text > 0 then self.textBox.history[#self.textBox.history + 1] = self.textBox.text end end self.textBox.text = self.textBox.history[self.textBox.historyPosition] self:updateTextboxIndicator() self:positionTextboxText() self.textBox.mode = "history" end elseif key == "down" then if self.textBox.mode == "history" then self.textBox.historyPosition = self.textBox.historyPosition + 1 if self.textBox.historyPosition > #self.textBox.history then self.textBox.historyPosition = #self.textBox.history end self.textBox.text = self.textBox.history[self.textBox.historyPosition] self:updateTextboxIndicator() self:positionTextboxText() self.textBox.mode = "history" end elseif key == "left" then self.textBox.indicator.position = self.textBox.indicator.position - 1 if self.textBox.indicator.position < 0 then self.textBox.indicator.position = 0 end self:updateTextboxIndicator() console:positionTextboxText() elseif key == "right" then self.textBox.indicator.position = self.textBox.indicator.position + 1 if self.textBox.indicator.position >= self.len(self.textBox.text) then self.textBox.indicator.position = self.len(self.textBox.text) end self:updateTextboxIndicator() console:positionTextboxText() elseif key == "return" then console:lua(self.textBox.text) self:clearTextBox() elseif key == "pageup" then self.history.yOffset = self.history.yOffset + self.history.scrollSpeed if self.history.yOffset > self.history.totalTextHeight then self.history.yOffset = self.history.totalTextHeight end elseif key == "pagedown" then self.history.yOffset = self.history.yOffset - self.history.scrollSpeed if self.history.yOffset < 0 then self.history.yOffset = 0 end elseif key == "v" then if love.keyboard.isDown("lctrl") or love.keyboard.isDown("rctrl") then local pastedText = love.system.getClipboardText() if #pastedText > 0 then if self.textBox.indicator.position == self.len(self.textBox.text) then self.textBox.text = self.textBox.text..pastedText else if self.textBox.indicator.position > 0 then local b = self.sub(self.textBox.text, 1, self.textBox.indicator.position) local e = self.sub(self.textBox.text, self.textBox.indicator.position + 1) self.textBox.text = b..pastedText..e else self.textBox.text = pastedText..self.textBox.text end end self.textBox.indicator.position = self.textBox.indicator.position + self.len(pastedText) self:updateTextboxIndicator() self:positionTextboxText() end end elseif key == "c" then if love.keyboard.isDown("lctrl") or love.keyboard.isDown("rctrl") then if #self.textBox.text > 0 then love.system.setClipboardText(self.textBox.text) end end end end end function console:wheelmoved(sx, sy) local x, y = love.mouse.getPosition() if sy > 0 then if x > self.history.x and x < self.history.x + self.history.width and y > self.history.y and y < self.history.y + self.history.height then self.history.yOffset = self.history.yOffset + self.history.scrollSpeed if self.history.yOffset > (self.history.totalTextHeight - self.history.height + (self.margin.y * 2)) then self.history.yOffset = self.history.totalTextHeight - self.history.height + (self.margin.y * 2) end end elseif sy < 0 then if x > self.history.x and x < self.history.x + self.history.width and y > self.history.y and y < self.history.y + self.history.height then self.history.yOffset = self.history.yOffset - self.history.scrollSpeed if self.history.yOffset < 0 then self.history.yOffset = 0 end end end end function console:print(text, color) if text then text = tostring(text) color = color or self.history.color.text local wrappedText, lines, height = wrapString(text, self.history.width, self.font) self.history.text[#self.history.text + 1] = { textRaw = text, text = wrappedText, lines = lines, height = height, color = color } self.history.totalTextHeight = self.history.totalTextHeight + height self.history.yOffset = 0 if #self.history.text > self.history.maxHistory then self.history.totalTextHeight = self.history.totalTextHeight - self.history.text[1].height table.remove(self.history.text, 1) end end end --Setters/Getters function console:setVisible(visible) self.visible = visible if visible then love.keyboard.setKeyRepeat(true) else love.keyboard.setKeyRepeat(self.userKeyRepeat) end end function console:getVisible() return self.visible end function console:setFont(font) if font then self.font = font self.textBox.height = (font:getAscent() - font:getDescent()) + (self.margin.y * 2) self.textBox.y = self.y + self.height - self.textBox.height end end return console
39,491
https://github.com/kubesphere/kubesphere/blob/master/vendor/sigs.k8s.io/controller-runtime/pkg/envtest/crd.go
Github Open Source
Open Source
Apache-2.0
2,023
kubesphere
kubesphere
Go
Code
1,730
4,704
/* Copyright 2018 The Kubernetes Authors. 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 envtest import ( "bufio" "bytes" "context" "errors" "fmt" "io" "os" "path/filepath" "time" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" k8syaml "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "k8s.io/client-go/util/retry" "k8s.io/utils/pointer" "sigs.k8s.io/yaml" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/conversion" ) // CRDInstallOptions are the options for installing CRDs. type CRDInstallOptions struct { // Scheme is used to determine if conversion webhooks should be enabled // for a particular CRD / object. // // Conversion webhooks are going to be enabled if an object in the scheme // implements Hub and Spoke conversions. // // If nil, scheme.Scheme is used. Scheme *runtime.Scheme // Paths is a list of paths to the directories or files containing CRDs Paths []string // CRDs is a list of CRDs to install CRDs []*apiextensionsv1.CustomResourceDefinition // ErrorIfPathMissing will cause an error if a Path does not exist ErrorIfPathMissing bool // MaxTime is the max time to wait MaxTime time.Duration // PollInterval is the interval to check PollInterval time.Duration // CleanUpAfterUse will cause the CRDs listed for installation to be // uninstalled when terminating the test environment. // Defaults to false. CleanUpAfterUse bool // WebhookOptions contains the conversion webhook information to install // on the CRDs. This field is usually inherited by the EnvTest options. // // If you're passing this field manually, you need to make sure that // the CA information and host port is filled in properly. WebhookOptions WebhookInstallOptions } const ( defaultPollInterval = 100 * time.Millisecond defaultMaxWait = 10 * time.Second ) // InstallCRDs installs a collection of CRDs into a cluster by reading the crd yaml files from a directory. func InstallCRDs(config *rest.Config, options CRDInstallOptions) ([]*apiextensionsv1.CustomResourceDefinition, error) { defaultCRDOptions(&options) // Read the CRD yamls into options.CRDs if err := readCRDFiles(&options); err != nil { return nil, fmt.Errorf("unable to read CRD files: %w", err) } if err := modifyConversionWebhooks(options.CRDs, options.Scheme, options.WebhookOptions); err != nil { return nil, err } // Create the CRDs in the apiserver if err := CreateCRDs(config, options.CRDs); err != nil { return options.CRDs, fmt.Errorf("unable to create CRD instances: %w", err) } // Wait for the CRDs to appear as Resources in the apiserver if err := WaitForCRDs(config, options.CRDs, options); err != nil { return options.CRDs, fmt.Errorf("something went wrong waiting for CRDs to appear as API resources: %w", err) } return options.CRDs, nil } // readCRDFiles reads the directories of CRDs in options.Paths and adds the CRD structs to options.CRDs. func readCRDFiles(options *CRDInstallOptions) error { if len(options.Paths) > 0 { crdList, err := renderCRDs(options) if err != nil { return err } options.CRDs = append(options.CRDs, crdList...) } return nil } // defaultCRDOptions sets the default values for CRDs. func defaultCRDOptions(o *CRDInstallOptions) { if o.Scheme == nil { o.Scheme = scheme.Scheme } if o.MaxTime == 0 { o.MaxTime = defaultMaxWait } if o.PollInterval == 0 { o.PollInterval = defaultPollInterval } } // WaitForCRDs waits for the CRDs to appear in discovery. func WaitForCRDs(config *rest.Config, crds []*apiextensionsv1.CustomResourceDefinition, options CRDInstallOptions) error { // Add each CRD to a map of GroupVersion to Resource waitingFor := map[schema.GroupVersion]*sets.Set[string]{} for _, crd := range crds { gvs := []schema.GroupVersion{} for _, version := range crd.Spec.Versions { if version.Served { gvs = append(gvs, schema.GroupVersion{Group: crd.Spec.Group, Version: version.Name}) } } for _, gv := range gvs { log.V(1).Info("adding API in waitlist", "GV", gv) if _, found := waitingFor[gv]; !found { // Initialize the set waitingFor[gv] = &sets.Set[string]{} } // Add the Resource waitingFor[gv].Insert(crd.Spec.Names.Plural) } } // Poll until all resources are found in discovery p := &poller{config: config, waitingFor: waitingFor} return wait.PollImmediate(options.PollInterval, options.MaxTime, p.poll) } // poller checks if all the resources have been found in discovery, and returns false if not. type poller struct { // config is used to get discovery config *rest.Config // waitingFor is the map of resources keyed by group version that have not yet been found in discovery waitingFor map[schema.GroupVersion]*sets.Set[string] } // poll checks if all the resources have been found in discovery, and returns false if not. func (p *poller) poll() (done bool, err error) { // Create a new clientset to avoid any client caching of discovery cs, err := clientset.NewForConfig(p.config) if err != nil { return false, err } allFound := true for gv, resources := range p.waitingFor { // All resources found, do nothing if resources.Len() == 0 { delete(p.waitingFor, gv) continue } // Get the Resources for this GroupVersion // TODO: Maybe the controller-runtime client should be able to do this... resourceList, err := cs.Discovery().ServerResourcesForGroupVersion(gv.Group + "/" + gv.Version) if err != nil { return false, nil //nolint:nilerr } // Remove each found resource from the resources set that we are waiting for for _, resource := range resourceList.APIResources { resources.Delete(resource.Name) } // Still waiting on some resources in this group version if resources.Len() != 0 { allFound = false } } return allFound, nil } // UninstallCRDs uninstalls a collection of CRDs by reading the crd yaml files from a directory. func UninstallCRDs(config *rest.Config, options CRDInstallOptions) error { // Read the CRD yamls into options.CRDs if err := readCRDFiles(&options); err != nil { return err } // Delete the CRDs from the apiserver cs, err := client.New(config, client.Options{}) if err != nil { return err } // Uninstall each CRD for _, crd := range options.CRDs { crd := crd log.V(1).Info("uninstalling CRD", "crd", crd.GetName()) if err := cs.Delete(context.TODO(), crd); err != nil { // If CRD is not found, we can consider success if !apierrors.IsNotFound(err) { return err } } } return nil } // CreateCRDs creates the CRDs. func CreateCRDs(config *rest.Config, crds []*apiextensionsv1.CustomResourceDefinition) error { cs, err := client.New(config, client.Options{}) if err != nil { return fmt.Errorf("unable to create client: %w", err) } // Create each CRD for _, crd := range crds { crd := crd log.V(1).Info("installing CRD", "crd", crd.GetName()) existingCrd := crd.DeepCopy() err := cs.Get(context.TODO(), client.ObjectKey{Name: crd.GetName()}, existingCrd) switch { case apierrors.IsNotFound(err): if err := cs.Create(context.TODO(), crd); err != nil { return fmt.Errorf("unable to create CRD %q: %w", crd.GetName(), err) } case err != nil: return fmt.Errorf("unable to get CRD %q to check if it exists: %w", crd.GetName(), err) default: log.V(1).Info("CRD already exists, updating", "crd", crd.GetName()) if err := retry.RetryOnConflict(retry.DefaultBackoff, func() error { if err := cs.Get(context.TODO(), client.ObjectKey{Name: crd.GetName()}, existingCrd); err != nil { return err } crd.SetResourceVersion(existingCrd.GetResourceVersion()) return cs.Update(context.TODO(), crd) }); err != nil { return err } } } return nil } // renderCRDs iterate through options.Paths and extract all CRD files. func renderCRDs(options *CRDInstallOptions) ([]*apiextensionsv1.CustomResourceDefinition, error) { type GVKN struct { GVK schema.GroupVersionKind Name string } crds := map[GVKN]*apiextensionsv1.CustomResourceDefinition{} for _, path := range options.Paths { var ( err error info os.FileInfo files []string filePath = path ) // Return the error if ErrorIfPathMissing exists if info, err = os.Stat(path); os.IsNotExist(err) { if options.ErrorIfPathMissing { return nil, err } continue } if !info.IsDir() { filePath, files = filepath.Dir(path), []string{info.Name()} } else { entries, err := os.ReadDir(path) if err != nil { return nil, err } for _, e := range entries { files = append(files, e.Name()) } } log.V(1).Info("reading CRDs from path", "path", path) crdList, err := readCRDs(filePath, files) if err != nil { return nil, err } for i, crd := range crdList { gvkn := GVKN{GVK: crd.GroupVersionKind(), Name: crd.GetName()} if _, found := crds[gvkn]; found { // Currently, we only print a log when there are duplicates. We may want to error out if that makes more sense. log.Info("there are more than one CRD definitions with the same <Group, Version, Kind, Name>", "GVKN", gvkn) } // We always use the CRD definition that we found last. crds[gvkn] = crdList[i] } } // Converting map to a list to return res := []*apiextensionsv1.CustomResourceDefinition{} for _, obj := range crds { res = append(res, obj) } return res, nil } // modifyConversionWebhooks takes all the registered CustomResourceDefinitions and applies modifications // to conditionally enable webhooks if the type is registered within the scheme. func modifyConversionWebhooks(crds []*apiextensionsv1.CustomResourceDefinition, scheme *runtime.Scheme, webhookOptions WebhookInstallOptions) error { if len(webhookOptions.LocalServingCAData) == 0 { return nil } // Determine all registered convertible types. convertibles := map[schema.GroupKind]struct{}{} for gvk := range scheme.AllKnownTypes() { obj, err := scheme.New(gvk) if err != nil { return err } if ok, err := conversion.IsConvertible(scheme, obj); ok && err == nil { convertibles[gvk.GroupKind()] = struct{}{} } } // generate host port. hostPort, err := webhookOptions.generateHostPort() if err != nil { return err } url := pointer.String(fmt.Sprintf("https://%s/convert", hostPort)) for i := range crds { // Continue if we're preserving unknown fields. if crds[i].Spec.PreserveUnknownFields { continue } // Continue if the GroupKind isn't registered as being convertible. if _, ok := convertibles[schema.GroupKind{ Group: crds[i].Spec.Group, Kind: crds[i].Spec.Names.Kind, }]; !ok { continue } if crds[i].Spec.Conversion == nil { crds[i].Spec.Conversion = &apiextensionsv1.CustomResourceConversion{ Webhook: &apiextensionsv1.WebhookConversion{}, } } crds[i].Spec.Conversion.Strategy = apiextensionsv1.WebhookConverter crds[i].Spec.Conversion.Webhook.ConversionReviewVersions = []string{"v1", "v1beta1"} crds[i].Spec.Conversion.Webhook.ClientConfig = &apiextensionsv1.WebhookClientConfig{ Service: nil, URL: url, CABundle: webhookOptions.LocalServingCAData, } } return nil } // readCRDs reads the CRDs from files and Unmarshals them into structs. func readCRDs(basePath string, files []string) ([]*apiextensionsv1.CustomResourceDefinition, error) { var crds []*apiextensionsv1.CustomResourceDefinition // White list the file extensions that may contain CRDs crdExts := sets.NewString(".json", ".yaml", ".yml") for _, file := range files { // Only parse allowlisted file types if !crdExts.Has(filepath.Ext(file)) { continue } // Unmarshal CRDs from file into structs docs, err := readDocuments(filepath.Join(basePath, file)) if err != nil { return nil, err } for _, doc := range docs { crd := &apiextensionsv1.CustomResourceDefinition{} if err = yaml.Unmarshal(doc, crd); err != nil { return nil, err } if crd.Kind != "CustomResourceDefinition" || crd.Spec.Names.Kind == "" || crd.Spec.Group == "" { continue } crds = append(crds, crd) } log.V(1).Info("read CRDs from file", "file", file) } return crds, nil } // readDocuments reads documents from file. func readDocuments(fp string) ([][]byte, error) { b, err := os.ReadFile(fp) if err != nil { return nil, err } docs := [][]byte{} reader := k8syaml.NewYAMLReader(bufio.NewReader(bytes.NewReader(b))) for { // Read document doc, err := reader.Read() if err != nil { if errors.Is(err, io.EOF) { break } return nil, err } docs = append(docs, doc) } return docs, nil }
25,338
https://github.com/JPedroSilveira/INF01124-Classificacao-e-Pesquisa-de-Dados-2019-2-UFRGS/blob/master/Hash/AnyTypeHashTable.py
Github Open Source
Open Source
MIT
null
INF01124-Classificacao-e-Pesquisa-de-Dados-2019-2-UFRGS
JPedroSilveira
Python
Code
323
823
# coding=utf-8 import State class AnyTypeHashTable: # Cria uma HashTable baseado no tamanho passado def __init__(self, size): self.size = size self.dictionary = [None] * size self.data = [None] * size self.used = [False] * size def position_calculator(self, key): str_key = str(key) size = len(str_key) position = 0 for i in (0, size - 1): position = i * (ord(str_key[i]) + position) return position % self.size def add(self, key, data): position = start_position = self.position_calculator(key) if self.dictionary[position] is None: # se estiver vazio self.dictionary[position] = key # coloca a chave self.data[position] = data # associa dado self.used[position] = True return position else: # se estiver ocupado, tenta achar lugar usando linear probing first_pass = True while position != start_position or first_pass: first_pass = False # incrementa posicão (mas fica dentro do intervalo do array de chaves) position = position + 1 if self.dictionary[position] is None: self.dictionary[position] = key self.data[position] = data self.used[position] = True return position if position == start_position: # se posicao igual à inicial é porque fez a volta e não achou return State.HashState.empty.value # informa que deu problema (está cheio) else: return position # retorna posição onde colocou o dado def get(self, key): position = start_position = self.position_calculator(key) first_pass = True # busca elemento usando linear probing: while self.dictionary[position] != key and self.used[position] and (start_position != position or first_pass): first_pass = False position = position + 1 if self.dictionary[position] == key: return self.data[position] else: return None # se chegou aqui é porque não existe a chave def remove(self, key): position = start_position = self.position_calculator(key) first_pass = True # busca elemento usando linear probing: while self.dictionary[position] != key and self.used and (start_position != position or first_pass): first_pass = False position = position + 1 if self.dictionary[position] == key: self.dictionary[position] = None self.data[position] = None return position else: return None # se chegou aqui é porque não existe a chave return None def print_table(self): for i in range(0, self.size): print(f"({i:03d})[{str(self.dictionary[i]):64s}] = {str(self.data[i]):20s} ({self.used[i]})")
50,036
https://github.com/ziyu123/kaldi_feature/blob/master/include/mkl_vsl.f90
Github Open Source
Open Source
Apache-2.0
2,021
kaldi_feature
ziyu123
Fortran Free Form
Code
10,285
45,290
! file: mkl_vsl.fi ! ! Copyright(C) 2006-2015 Intel Corporation. All Rights Reserved. ! ! The source code, information and material ("Material") contained herein is ! owned by Intel Corporation or its suppliers or licensors, and title to such ! Material remains with Intel Corporation or its suppliers or licensors. The ! Material contains proprietary information of Intel or its suppliers and ! licensors. The Material is protected by worldwide copyright laws and treaty ! provisions. No part of the Material may be used, copied, reproduced, ! modified, published, uploaded, posted, transmitted, distributed or disclosed ! in any way without Intel's prior express written permission. No license ! under any patent, copyright or other intellectual property rights in the ! Material is granted to or conferred upon you, either expressly, by ! implication, inducement, estoppel or otherwise. Any license under such ! intellectual property rights must be express and approved by Intel in ! writing. ! ! *Third Party trademarks are the property of their respective owners. ! ! Unless otherwise agreed by Intel in writing, you may not remove or alter ! this notice or any other notice embedded in Materials by Intel or Intel's ! suppliers or licensors in any way. !++ ! Fortran 90 VSL interface. !-- MODULE MKL_VSL_TYPE !++ ! Definitions for VSL functions return values (errors, warnings) !-- ! "No error" status INTEGER(KIND=4) VSL_STATUS_OK INTEGER(KIND=4) VSL_ERROR_OK PARAMETER (VSL_STATUS_OK = 0) PARAMETER (VSL_ERROR_OK = 0) ! Common errors (-1..-999) INTEGER(KIND=4) VSL_ERROR_FEATURE_NOT_IMPLEMENTED INTEGER(KIND=4) VSL_ERROR_UNKNOWN INTEGER(KIND=4) VSL_ERROR_BADARGS INTEGER(KIND=4) VSL_ERROR_MEM_FAILURE INTEGER(KIND=4) VSL_ERROR_NULL_PTR INTEGER(KIND=4) VSL_ERROR_CPU_NOT_SUPPORTED PARAMETER (VSL_ERROR_FEATURE_NOT_IMPLEMENTED = -1) PARAMETER (VSL_ERROR_UNKNOWN = -2) PARAMETER (VSL_ERROR_BADARGS = -3) PARAMETER (VSL_ERROR_MEM_FAILURE = -4) PARAMETER (VSL_ERROR_NULL_PTR = -5) PARAMETER (VSL_ERROR_CPU_NOT_SUPPORTED = -6) ! RNG errors (-1000..-1999) ! brng errors INTEGER(KIND=4) VSL_RNG_ERROR_INVALID_BRNG_INDEX INTEGER(KIND=4) VSL_RNG_ERROR_LEAPFROG_UNSUPPORTED INTEGER(KIND=4) VSL_RNG_ERROR_SKIPAHEAD_UNSUPPORTED INTEGER(KIND=4) VSL_RNG_ERROR_BRNGS_INCOMPATIBLE INTEGER(KIND=4) VSL_RNG_ERROR_BAD_STREAM INTEGER(KIND=4) VSL_RNG_ERROR_BRNG_TABLE_FULL INTEGER(KIND=4) VSL_RNG_ERROR_BAD_STREAM_STATE_SIZE INTEGER(KIND=4) VSL_RNG_ERROR_BAD_WORD_SIZE INTEGER(KIND=4) VSL_RNG_ERROR_BAD_NSEEDS INTEGER(KIND=4) VSL_RNG_ERROR_BAD_NBITS INTEGER(KIND=4) VSL_RNG_ERROR_QRNG_PERIOD_ELAPSED INTEGER(KIND=4) VSL_RNG_ERROR_LEAPFROG_NSTREAMS_TOO_BIG PARAMETER (VSL_RNG_ERROR_INVALID_BRNG_INDEX = -1000) PARAMETER (VSL_RNG_ERROR_LEAPFROG_UNSUPPORTED = -1002) PARAMETER (VSL_RNG_ERROR_SKIPAHEAD_UNSUPPORTED = -1003) PARAMETER (VSL_RNG_ERROR_BRNGS_INCOMPATIBLE = -1005) PARAMETER (VSL_RNG_ERROR_BAD_STREAM = -1006) PARAMETER (VSL_RNG_ERROR_BRNG_TABLE_FULL = -1007) PARAMETER (VSL_RNG_ERROR_BAD_STREAM_STATE_SIZE = -1008) PARAMETER (VSL_RNG_ERROR_BAD_WORD_SIZE = -1009) PARAMETER (VSL_RNG_ERROR_BAD_NSEEDS = -1010) PARAMETER (VSL_RNG_ERROR_BAD_NBITS = -1011) PARAMETER (VSL_RNG_ERROR_QRNG_PERIOD_ELAPSED = -1012) PARAMETER (VSL_RNG_ERROR_LEAPFROG_NSTREAMS_TOO_BIG = -1013) ! abstract stream related errors INTEGER(KIND=4) VSL_RNG_ERROR_BAD_UPDATE INTEGER(KIND=4) VSL_RNG_ERROR_NO_NUMBERS INTEGER(KIND=4) VSL_RNG_ERROR_INVALID_ABSTRACT_STREAM PARAMETER (VSL_RNG_ERROR_BAD_UPDATE = -1120) PARAMETER (VSL_RNG_ERROR_NO_NUMBERS = -1121) PARAMETER (VSL_RNG_ERROR_INVALID_ABSTRACT_STREAM = -1122) ! non determenistic stream related errors INTEGER(KIND=4) VSL_RNG_ERROR_NONDETERM_NOT_SUPPORTED INTEGER(KIND=4) VSL_RNG_ERROR_NONDETERM_NRETRIES_EXCEEDED PARAMETER (VSL_RNG_ERROR_NONDETERM_NOT_SUPPORTED = -1130) PARAMETER (VSL_RNG_ERROR_NONDETERM_NRETRIES_EXCEEDED = -1131) ! read/write stream to file errors INTEGER(KIND=4) VSL_RNG_ERROR_FILE_CLOSE INTEGER(KIND=4) VSL_RNG_ERROR_FILE_OPEN INTEGER(KIND=4) VSL_RNG_ERROR_FILE_WRITE INTEGER(KIND=4) VSL_RNG_ERROR_FILE_READ INTEGER(KIND=4) VSL_RNG_ERROR_BAD_FILE_FORMAT INTEGER(KIND=4) VSL_RNG_ERROR_UNSUPPORTED_FILE_VER INTEGER(KIND=4) VSL_RNG_ERROR_BAD_MEM_FORMAT PARAMETER (VSL_RNG_ERROR_FILE_CLOSE = -1100) PARAMETER (VSL_RNG_ERROR_FILE_OPEN = -1101) PARAMETER (VSL_RNG_ERROR_FILE_WRITE = -1102) PARAMETER (VSL_RNG_ERROR_FILE_READ = -1103) PARAMETER (VSL_RNG_ERROR_BAD_FILE_FORMAT = -1110) PARAMETER (VSL_RNG_ERROR_UNSUPPORTED_FILE_VER = -1111) PARAMETER (VSL_RNG_ERROR_BAD_MEM_FORMAT = -1200) ! Convolution/correlation errors INTEGER(KIND=4) VSL_CC_ERROR_NOT_IMPLEMENTED INTEGER(KIND=4) VSL_CC_ERROR_ALLOCATION_FAILURE INTEGER(KIND=4) VSL_CC_ERROR_BAD_DESCRIPTOR INTEGER(KIND=4) VSL_CC_ERROR_SERVICE_FAILURE INTEGER(KIND=4) VSL_CC_ERROR_EDIT_FAILURE INTEGER(KIND=4) VSL_CC_ERROR_EDIT_PROHIBITED INTEGER(KIND=4) VSL_CC_ERROR_COMMIT_FAILURE INTEGER(KIND=4) VSL_CC_ERROR_COPY_FAILURE INTEGER(KIND=4) VSL_CC_ERROR_DELETE_FAILURE INTEGER(KIND=4) VSL_CC_ERROR_BAD_ARGUMENT INTEGER(KIND=4) VSL_CC_ERROR_DIMS INTEGER(KIND=4) VSL_CC_ERROR_START INTEGER(KIND=4) VSL_CC_ERROR_DECIMATION INTEGER(KIND=4) VSL_CC_ERROR_XSHAPE INTEGER(KIND=4) VSL_CC_ERROR_YSHAPE INTEGER(KIND=4) VSL_CC_ERROR_ZSHAPE INTEGER(KIND=4) VSL_CC_ERROR_XSTRIDE INTEGER(KIND=4) VSL_CC_ERROR_YSTRIDE INTEGER(KIND=4) VSL_CC_ERROR_ZSTRIDE INTEGER(KIND=4) VSL_CC_ERROR_X INTEGER(KIND=4) VSL_CC_ERROR_Y INTEGER(KIND=4) VSL_CC_ERROR_Z INTEGER(KIND=4) VSL_CC_ERROR_JOB INTEGER(KIND=4) VSL_CC_ERROR_KIND INTEGER(KIND=4) VSL_CC_ERROR_MODE INTEGER(KIND=4) VSL_CC_ERROR_TYPE INTEGER(KIND=4) VSL_CC_ERROR_PRECISION INTEGER(KIND=4) VSL_CC_ERROR_EXTERNAL_PRECISION INTEGER(KIND=4) VSL_CC_ERROR_INTERNAL_PRECISION INTEGER(KIND=4) VSL_CC_ERROR_METHOD INTEGER(KIND=4) VSL_CC_ERROR_OTHER PARAMETER (VSL_CC_ERROR_NOT_IMPLEMENTED = -2000) PARAMETER (VSL_CC_ERROR_ALLOCATION_FAILURE = -2001) PARAMETER (VSL_CC_ERROR_BAD_DESCRIPTOR = -2200) PARAMETER (VSL_CC_ERROR_SERVICE_FAILURE = -2210) PARAMETER (VSL_CC_ERROR_EDIT_FAILURE = -2211) PARAMETER (VSL_CC_ERROR_EDIT_PROHIBITED = -2212) PARAMETER (VSL_CC_ERROR_COMMIT_FAILURE = -2220) PARAMETER (VSL_CC_ERROR_COPY_FAILURE = -2230) PARAMETER (VSL_CC_ERROR_DELETE_FAILURE = -2240) PARAMETER (VSL_CC_ERROR_BAD_ARGUMENT = -2300) PARAMETER (VSL_CC_ERROR_DIMS = -2301) PARAMETER (VSL_CC_ERROR_START = -2302) PARAMETER (VSL_CC_ERROR_DECIMATION = -2303) PARAMETER (VSL_CC_ERROR_XSHAPE = -2311) PARAMETER (VSL_CC_ERROR_YSHAPE = -2312) PARAMETER (VSL_CC_ERROR_ZSHAPE = -2313) PARAMETER (VSL_CC_ERROR_XSTRIDE = -2321) PARAMETER (VSL_CC_ERROR_YSTRIDE = -2322) PARAMETER (VSL_CC_ERROR_ZSTRIDE = -2323) PARAMETER (VSL_CC_ERROR_X = -2331) PARAMETER (VSL_CC_ERROR_Y = -2332) PARAMETER (VSL_CC_ERROR_Z = -2333) PARAMETER (VSL_CC_ERROR_JOB = -2100) PARAMETER (VSL_CC_ERROR_KIND = -2110) PARAMETER (VSL_CC_ERROR_MODE = -2120) PARAMETER (VSL_CC_ERROR_TYPE = -2130) PARAMETER (VSL_CC_ERROR_PRECISION = -2400) PARAMETER (VSL_CC_ERROR_EXTERNAL_PRECISION = -2141) PARAMETER (VSL_CC_ERROR_INTERNAL_PRECISION = -2142) PARAMETER (VSL_CC_ERROR_METHOD = -2400) PARAMETER (VSL_CC_ERROR_OTHER = -2800) !++ ! SUMMARY STATTISTICS ERROR/WARNING CODES !-- ! Warnings INTEGER(KIND=4) VSL_SS_NOT_FULL_RANK_MATRIX INTEGER(KIND=4) VSL_SS_SEMIDEFINITE_COR PARAMETER (VSL_SS_NOT_FULL_RANK_MATRIX = 4028) PARAMETER (VSL_SS_SEMIDEFINITE_COR = 4029) ! Errors and messages (-4000..-4999) INTEGER(KIND=4) VSL_SS_ERROR_ALLOCATION_FAILURE INTEGER(KIND=4) VSL_SS_ERROR_BAD_DIMEN INTEGER(KIND=4) VSL_SS_ERROR_BAD_OBSERV_N INTEGER(KIND=4) VSL_SS_ERROR_STORAGE_NOT_SUPPORTED INTEGER(KIND=4) VSL_SS_ERROR_BAD_INDC_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_WEIGHTS INTEGER(KIND=4) VSL_SS_ERROR_BAD_MEAN_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_2R_MOM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_3R_MOM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_4R_MOM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_2C_MOM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_3C_MOM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_4C_MOM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_KURTOSIS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_SKEWNESS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MIN_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MAX_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_VARIATION_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_COV_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_COR_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_ACCUM_WEIGHT_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_QUANT_ORDER_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_QUANT_ORDER INTEGER(KIND=4) VSL_SS_ERROR_BAD_QUANT_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_ORDER_STATS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_MOMORDER_NOT_SUPPORTED INTEGER(KIND=4) VSL_SS_ERROR_ALL_OBSERVS_OUTLIERS INTEGER(KIND=4) VSL_SS_ERROR_BAD_ROBUST_COV_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_ROBUST_MEAN_ADDR INTEGER(KIND=4) VSL_SS_ERROR_METHOD_NOT_SUPPORTED INTEGER(KIND=4) VSL_SS_ERROR_BAD_GROUP_INDC_ADDR INTEGER(KIND=4) VSL_SS_ERROR_NULL_TASK_DESCRIPTOR INTEGER(KIND=4) VSL_SS_ERROR_BAD_OBSERV_ADDR INTEGER(KIND=4) VSL_SS_ERROR_SINGULAR_COV INTEGER(KIND=4) VSL_SS_ERROR_BAD_POOLED_COV_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_POOLED_MEAN_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_GROUP_COV_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_GROUP_MEAN_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_GROUP_INDC INTEGER(KIND=4) VSL_SS_ERROR_BAD_OUTLIERS_PARAMS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_OUTLIERS_PARAMS_N_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_OUTLIERS_WEIGHTS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_ROBUST_COV_PARAMS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_ROBUST_COV_PARAMS_N_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_STORAGE_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_PARTIAL_COV_IDX_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_PARTIAL_COV_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_PARTIAL_COR_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_PARAMS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_PARAMS_N_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_BAD_PARAMS_N INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_PARAMS INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_INIT_ESTIMATES_N_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_INIT_ESTIMATES_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_SIMUL_VALS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_SIMUL_VALS_N_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_ESTIMATES_N_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_ESTIMATES_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_SIMUL_VALS_N INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_ESTIMATES_N INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_OUTPUT_PARAMS INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_PRIOR_N_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_PRIOR_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MI_MISSING_VALS_N INTEGER(KIND=4) VSL_SS_ERROR_BAD_STREAM_QUANT_PARAMS_N_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_STREAM_QUANT_PARAMS_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_STREAM_QUANT_PARAMS_N INTEGER(KIND=4) VSL_SS_ERROR_BAD_STREAM_QUANT_PARAMS INTEGER(KIND=4) VSL_SS_ERROR_BAD_STREAM_QUANT_ORDER_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_STREAM_QUANT_ORDER INTEGER(KIND=4) VSL_SS_ERROR_BAD_STREAM_QUANT_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_PARAMTR_COR_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_COR INTEGER(KIND=4) VSL_SS_ERROR_BAD_PARTIAL_COV_IDX INTEGER(KIND=4) VSL_SS_ERROR_BAD_SUM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_2R_SUM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_3R_SUM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_4R_SUM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_2C_SUM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_3C_SUM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_4C_SUM_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_CP_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MDAD_ADDR INTEGER(KIND=4) VSL_SS_ERROR_BAD_MNAD_ADDR PARAMETER (VSL_SS_ERROR_ALLOCATION_FAILURE =-4000) PARAMETER (VSL_SS_ERROR_BAD_DIMEN =-4001) PARAMETER (VSL_SS_ERROR_BAD_OBSERV_N =-4002) PARAMETER (VSL_SS_ERROR_STORAGE_NOT_SUPPORTED =-4003) PARAMETER (VSL_SS_ERROR_BAD_INDC_ADDR =-4004) PARAMETER (VSL_SS_ERROR_BAD_WEIGHTS =-4005) PARAMETER (VSL_SS_ERROR_BAD_MEAN_ADDR =-4006) PARAMETER (VSL_SS_ERROR_BAD_2R_MOM_ADDR =-4007) PARAMETER (VSL_SS_ERROR_BAD_3R_MOM_ADDR =-4008) PARAMETER (VSL_SS_ERROR_BAD_4R_MOM_ADDR =-4009) PARAMETER (VSL_SS_ERROR_BAD_2C_MOM_ADDR =-4010) PARAMETER (VSL_SS_ERROR_BAD_3C_MOM_ADDR =-4011) PARAMETER (VSL_SS_ERROR_BAD_4C_MOM_ADDR =-4012) PARAMETER (VSL_SS_ERROR_BAD_KURTOSIS_ADDR =-4013) PARAMETER (VSL_SS_ERROR_BAD_SKEWNESS_ADDR =-4014) PARAMETER (VSL_SS_ERROR_BAD_MIN_ADDR =-4015) PARAMETER (VSL_SS_ERROR_BAD_MAX_ADDR =-4016) PARAMETER (VSL_SS_ERROR_BAD_VARIATION_ADDR =-4017) PARAMETER (VSL_SS_ERROR_BAD_COV_ADDR =-4018) PARAMETER (VSL_SS_ERROR_BAD_COR_ADDR =-4019) PARAMETER (VSL_SS_ERROR_BAD_ACCUM_WEIGHT_ADDR =-4020) PARAMETER (VSL_SS_ERROR_BAD_QUANT_ORDER_ADDR =-4021) PARAMETER (VSL_SS_ERROR_BAD_QUANT_ORDER =-4022) PARAMETER (VSL_SS_ERROR_BAD_QUANT_ADDR =-4023) PARAMETER (VSL_SS_ERROR_BAD_ORDER_STATS_ADDR =-4024) PARAMETER (VSL_SS_ERROR_MOMORDER_NOT_SUPPORTED =-4025) PARAMETER (VSL_SS_ERROR_ALL_OBSERVS_OUTLIERS =-4026) PARAMETER (VSL_SS_ERROR_BAD_ROBUST_COV_ADDR =-4027) PARAMETER (VSL_SS_ERROR_BAD_ROBUST_MEAN_ADDR =-4028) PARAMETER (VSL_SS_ERROR_METHOD_NOT_SUPPORTED =-4029) PARAMETER (VSL_SS_ERROR_BAD_GROUP_INDC_ADDR =-4030) PARAMETER (VSL_SS_ERROR_NULL_TASK_DESCRIPTOR =-4031) PARAMETER (VSL_SS_ERROR_BAD_OBSERV_ADDR =-4032) PARAMETER (VSL_SS_ERROR_SINGULAR_COV =-4033) PARAMETER (VSL_SS_ERROR_BAD_POOLED_COV_ADDR =-4034) PARAMETER (VSL_SS_ERROR_BAD_POOLED_MEAN_ADDR =-4035) PARAMETER (VSL_SS_ERROR_BAD_GROUP_COV_ADDR =-4036) PARAMETER (VSL_SS_ERROR_BAD_GROUP_MEAN_ADDR =-4037) PARAMETER (VSL_SS_ERROR_BAD_GROUP_INDC =-4038) PARAMETER (VSL_SS_ERROR_BAD_OUTLIERS_PARAMS_ADDR =-4039) PARAMETER (VSL_SS_ERROR_BAD_OUTLIERS_PARAMS_N_ADDR =-4040) PARAMETER (VSL_SS_ERROR_BAD_OUTLIERS_WEIGHTS_ADDR =-4041) PARAMETER (VSL_SS_ERROR_BAD_ROBUST_COV_PARAMS_ADDR =-4042) PARAMETER (VSL_SS_ERROR_BAD_ROBUST_COV_PARAMS_N_ADDR =-4043) PARAMETER (VSL_SS_ERROR_BAD_STORAGE_ADDR =-4044) PARAMETER (VSL_SS_ERROR_BAD_PARTIAL_COV_IDX_ADDR =-4045) PARAMETER (VSL_SS_ERROR_BAD_PARTIAL_COV_ADDR =-4046) PARAMETER (VSL_SS_ERROR_BAD_PARTIAL_COR_ADDR =-4047) PARAMETER (VSL_SS_ERROR_BAD_MI_PARAMS_ADDR =-4048) PARAMETER (VSL_SS_ERROR_BAD_MI_PARAMS_N_ADDR =-4049) PARAMETER (VSL_SS_ERROR_BAD_MI_BAD_PARAMS_N =-4050) PARAMETER (VSL_SS_ERROR_BAD_MI_PARAMS =-4051) PARAMETER (VSL_SS_ERROR_BAD_MI_INIT_ESTIMATES_N_ADDR =-4052) PARAMETER (VSL_SS_ERROR_BAD_MI_INIT_ESTIMATES_ADDR =-4053) PARAMETER (VSL_SS_ERROR_BAD_MI_SIMUL_VALS_ADDR =-4054) PARAMETER (VSL_SS_ERROR_BAD_MI_SIMUL_VALS_N_ADDR =-4055) PARAMETER (VSL_SS_ERROR_BAD_MI_ESTIMATES_N_ADDR =-4056) PARAMETER (VSL_SS_ERROR_BAD_MI_ESTIMATES_ADDR =-4057) PARAMETER (VSL_SS_ERROR_BAD_MI_SIMUL_VALS_N =-4058) PARAMETER (VSL_SS_ERROR_BAD_MI_ESTIMATES_N =-4059) PARAMETER (VSL_SS_ERROR_BAD_MI_OUTPUT_PARAMS =-4060) PARAMETER (VSL_SS_ERROR_BAD_MI_PRIOR_N_ADDR =-4061) PARAMETER (VSL_SS_ERROR_BAD_MI_PRIOR_ADDR =-4062) PARAMETER (VSL_SS_ERROR_BAD_MI_MISSING_VALS_N =-4063) PARAMETER (VSL_SS_ERROR_BAD_STREAM_QUANT_PARAMS_N_ADDR =-4064) PARAMETER (VSL_SS_ERROR_BAD_STREAM_QUANT_PARAMS_ADDR =-4065) PARAMETER (VSL_SS_ERROR_BAD_STREAM_QUANT_PARAMS_N =-4066) PARAMETER (VSL_SS_ERROR_BAD_STREAM_QUANT_PARAMS =-4067) PARAMETER (VSL_SS_ERROR_BAD_STREAM_QUANT_ORDER_ADDR =-4068) PARAMETER (VSL_SS_ERROR_BAD_STREAM_QUANT_ORDER =-4069) PARAMETER (VSL_SS_ERROR_BAD_STREAM_QUANT_ADDR =-4070) PARAMETER (VSL_SS_ERROR_BAD_PARAMTR_COR_ADDR =-4071) PARAMETER (VSL_SS_ERROR_BAD_COR =-4072) PARAMETER (VSL_SS_ERROR_BAD_PARTIAL_COV_IDX =-4073) PARAMETER (VSL_SS_ERROR_BAD_SUM_ADDR =-4074) PARAMETER (VSL_SS_ERROR_BAD_2R_SUM_ADDR =-4075) PARAMETER (VSL_SS_ERROR_BAD_3R_SUM_ADDR =-4076) PARAMETER (VSL_SS_ERROR_BAD_4R_SUM_ADDR =-4077) PARAMETER (VSL_SS_ERROR_BAD_2C_SUM_ADDR =-4078) PARAMETER (VSL_SS_ERROR_BAD_3C_SUM_ADDR =-4079) PARAMETER (VSL_SS_ERROR_BAD_4C_SUM_ADDR =-4080) PARAMETER (VSL_SS_ERROR_BAD_CP_ADDR =-4081) PARAMETER (VSL_SS_ERROR_BAD_MDAD_ADDR =-4082) PARAMETER (VSL_SS_ERROR_BAD_MNAD_ADDR =-4083) ! Internal errors caused by internal routines of the functions INTEGER(KIND=4) VSL_SS_ERROR_ROBCOV_INTERN_C1 INTEGER(KIND=4) VSL_SS_ERROR_PARTIALCOV_INTERN_C1 INTEGER(KIND=4) VSL_SS_ERROR_PARTIALCOV_INTERN_C2 INTEGER(KIND=4) VSL_SS_ERROR_MISSINGVALS_INTERN_C1 INTEGER(KIND=4) VSL_SS_ERROR_MISSINGVALS_INTERN_C2 INTEGER(KIND=4) VSL_SS_ERROR_MISSINGVALS_INTERN_C3 INTEGER(KIND=4) VSL_SS_ERROR_MISSINGVALS_INTERN_C4 INTEGER(KIND=4) VSL_SS_ERROR_MISSINGVALS_INTERN_C5 INTEGER(KIND=4) VSL_SS_ERROR_PARAMTRCOR_INTERN_C1 INTEGER(KIND=4) VSL_SS_ERROR_COVRANK_INTERNAL_ERROR_C1 INTEGER(KIND=4) VSL_SS_ERROR_INVCOV_INTERNAL_ERROR_C1 INTEGER(KIND=4) VSL_SS_ERROR_INVCOV_INTERNAL_ERROR_C2 PARAMETER (VSL_SS_ERROR_ROBCOV_INTERN_C1 =-5000) PARAMETER (VSL_SS_ERROR_PARTIALCOV_INTERN_C1 =-5010) PARAMETER (VSL_SS_ERROR_PARTIALCOV_INTERN_C2 =-5011) PARAMETER (VSL_SS_ERROR_MISSINGVALS_INTERN_C1 =-5021) PARAMETER (VSL_SS_ERROR_MISSINGVALS_INTERN_C2 =-5022) PARAMETER (VSL_SS_ERROR_MISSINGVALS_INTERN_C3 =-5023) PARAMETER (VSL_SS_ERROR_MISSINGVALS_INTERN_C4 =-5024) PARAMETER (VSL_SS_ERROR_MISSINGVALS_INTERN_C5 =-5025) PARAMETER (VSL_SS_ERROR_PARAMTRCOR_INTERN_C1 =-5030) PARAMETER (VSL_SS_ERROR_COVRANK_INTERNAL_ERROR_C1 =-5040) PARAMETER (VSL_SS_ERROR_INVCOV_INTERNAL_ERROR_C1 =-5041) PARAMETER (VSL_SS_ERROR_INVCOV_INTERNAL_ERROR_C2 =-5042) !++ ! CONV/CORR RELATED MACRO DEFINITIONS !-- INTEGER(KIND=4) VSL_CONV_MODE_AUTO INTEGER(KIND=4) VSL_CORR_MODE_AUTO INTEGER(KIND=4) VSL_CONV_MODE_DIRECT INTEGER(KIND=4) VSL_CORR_MODE_DIRECT INTEGER(KIND=4) VSL_CONV_MODE_FFT INTEGER(KIND=4) VSL_CORR_MODE_FFT INTEGER(KIND=4) VSL_CONV_PRECISION_SINGLE INTEGER(KIND=4) VSL_CORR_PRECISION_SINGLE INTEGER(KIND=4) VSL_CONV_PRECISION_DOUBLE INTEGER(KIND=4) VSL_CORR_PRECISION_DOUBLE PARAMETER (VSL_CONV_MODE_AUTO = 0) PARAMETER (VSL_CORR_MODE_AUTO = 0) PARAMETER (VSL_CONV_MODE_DIRECT = 1) PARAMETER (VSL_CORR_MODE_DIRECT = 1) PARAMETER (VSL_CONV_MODE_FFT = 2) PARAMETER (VSL_CORR_MODE_FFT = 2) PARAMETER (VSL_CONV_PRECISION_SINGLE = 1) PARAMETER (VSL_CORR_PRECISION_SINGLE = 1) PARAMETER (VSL_CONV_PRECISION_DOUBLE = 2) PARAMETER (VSL_CORR_PRECISION_DOUBLE = 2) !++ ! BASIC RANDOM NUMBER GENERATOR (BRNG) RELATED MACRO DEFINITIONS !-- ! MAX NUMBER OF BRNGS CAN BE REGISTERED IN VSL ! No more than VSL_MAX_REG_BRNGS basic generators can be registered in VSL ! (including predefined basic generators). ! ! Change this number to increase/decrease number of BRNGs can be registered. INTEGER VSL_MAX_REG_BRNGS PARAMETER (VSL_MAX_REG_BRNGS = 512) ! PREDEFINED BRNG NAMES INTEGER VSL_BRNG_SHIFT INTEGER VSL_BRNG_INC INTEGER VSL_BRNG_MCG31 INTEGER VSL_BRNG_R250 INTEGER VSL_BRNG_MRG32K3A INTEGER VSL_BRNG_MCG59 INTEGER VSL_BRNG_WH INTEGER VSL_BRNG_SOBOL INTEGER VSL_BRNG_NIEDERR INTEGER VSL_BRNG_MT19937 INTEGER VSL_BRNG_MT2203 INTEGER VSL_BRNG_IABSTRACT INTEGER VSL_BRNG_DABSTRACT INTEGER VSL_BRNG_SABSTRACT INTEGER VSL_BRNG_SFMT19937 INTEGER VSL_BRNG_NONDETERM PARAMETER (VSL_BRNG_SHIFT=20) PARAMETER (VSL_BRNG_INC=ISHFT(1, VSL_BRNG_SHIFT)) PARAMETER (VSL_BRNG_MCG31 =VSL_BRNG_INC) PARAMETER (VSL_BRNG_R250 =VSL_BRNG_MCG31 +VSL_BRNG_INC) PARAMETER (VSL_BRNG_MRG32K3A =VSL_BRNG_R250 +VSL_BRNG_INC) PARAMETER (VSL_BRNG_MCG59 =VSL_BRNG_MRG32K3A +VSL_BRNG_INC) PARAMETER (VSL_BRNG_WH =VSL_BRNG_MCG59 +VSL_BRNG_INC) PARAMETER (VSL_BRNG_SOBOL =VSL_BRNG_WH +VSL_BRNG_INC) PARAMETER (VSL_BRNG_NIEDERR =VSL_BRNG_SOBOL +VSL_BRNG_INC) PARAMETER (VSL_BRNG_MT19937 =VSL_BRNG_NIEDERR +VSL_BRNG_INC) PARAMETER (VSL_BRNG_MT2203 =VSL_BRNG_MT19937 +VSL_BRNG_INC) PARAMETER (VSL_BRNG_IABSTRACT=VSL_BRNG_MT2203 +VSL_BRNG_INC) PARAMETER (VSL_BRNG_DABSTRACT=VSL_BRNG_IABSTRACT+VSL_BRNG_INC) PARAMETER (VSL_BRNG_SABSTRACT=VSL_BRNG_DABSTRACT+VSL_BRNG_INC) PARAMETER (VSL_BRNG_SFMT19937=VSL_BRNG_SABSTRACT+VSL_BRNG_INC) PARAMETER (VSL_BRNG_NONDETERM=VSL_BRNG_SFMT19937+VSL_BRNG_INC) ! PREDEFINED PARAMETERS FOR NON-DETERMNINISTIC RANDOM NUMBER ! GENERATOR ! The library provides an abstraction to the source of ! non-deterministic random numbers supported in HW. ! Current version of the library provides interface to ! RDRAND-based only, available in latest Intel CPU. INTEGER(KIND=4) VSL_BRNG_RDRAND INTEGER(KIND=4) VSL_BRNG_NONDETERM_NRETRIES PARAMETER (VSL_BRNG_RDRAND = 0) PARAMETER (VSL_BRNG_NONDETERM_NRETRIES = 10) ! LEAPFROG METHOD FOR GRAY-CODE BASED QUASI-RANDOM NUMBER BASIC GENERATORS ! VSL_BRNG_SOBOL and VSL_BRNG_NIEDERR are Gray-code based quasi-random number ! basic generators. In contrast to pseudorandom number basic generators, ! quasi-random ones take the dimension as initialization parameter. ! ! Suppose that quasi-random number generator (QRNG) dimension is S. QRNG ! sequence is a sequence of S-dimensional vectors: ! ! x0=(x0[0],x0[1],...,x0[S-1]),x1=(x1[0],x1[1],...,x1[S-1]),... ! ! VSL treats the output of any basic generator as 1-dimensional, however: ! ! x0[0],x0[1],...,x0[S-1],x1[0],x1[1],...,x1[S-1],... ! ! Because of nature of VSL_BRNG_SOBOL and VSL_BRNG_NIEDERR QRNGs, ! the only S-stride Leapfrog method is supported for them. In other words, ! user can generate subsequences, which consist of fixed elements of ! vectors x0,x1,... For example, if 0 element is fixed, the following ! subsequence is generated: ! ! x0[1],x1[1],x2[1],... ! ! To use the s-stride Leapfrog method with given QRNG, user should call ! vslLeapfrogStream function with parameter k equal to element to be fixed ! (0<=k<S) and parameter nstreams equal to VSL_QRNG_LEAPFROG_COMPONENTS. INTEGER(KIND=4) VSL_QRNG_LEAPFROG_COMPONENTS PARAMETER (VSL_QRNG_LEAPFROG_COMPONENTS = Z"7FFFFFFF") ! USER-DEFINED PARAMETERS FOR QUASI-RANDOM NUMBER BASIC GENERATORS ! VSL_BRNG_SOBOL and VSL_BRNG_NIEDERR are Gray-code based quasi-random ! number basic generators. Default parameters of the generators ! support generation of quasi-random number vectors of dimensions ! S<=40 for SOBOL and S<=318 for NIEDERRITER. The library provides ! opportunity to register user-defined initial values for the ! generators and generate quasi-random vectors of desirable dimension. ! There is also opportunity to register user-defined parameters for ! default dimensions and obtain another sequence of quasi-random vectors. ! Service function vslNewStreamEx is used to pass the parameters to ! the library. Data are packed into array params, parameter of the routine. ! First element of the array is used for dimension S, second element ! contains indicator, VSL_USER_QRNG_INITIAL_VALUES, of user-defined ! parameters for quasi-random number generators. ! Macros VSL_USER_PRIMITIVE_POLYMS and VSL_USER_INIT_DIRECTION_NUMBERS ! are used to describe which data are passed to SOBOL QRNG and ! VSL_USER_IRRED_POLYMS - which data are passed to NIEDERRITER QRNG. ! For example, to demonstrate that both primitive polynomials and initial ! direction numbers are passed in SOBOL one should set third element of the ! array params to VSL_USER_PRIMITIVE_POLYMS | VSL_USER_DIRECTION_NUMBERS. ! Macro VSL_QRNG_OVERRIDE_1ST_DIM_INIT is used to override default ! initialization for the first dimension. Macro VSL_USER_DIRECTION_NUMBERS ! is used when direction numbers calculated on the user side are passed ! into the generators. More detailed description of interface for ! registration of user-defined QRNG initial parameters can be found ! in VslNotes.pdf. INTEGER VSL_USER_QRNG_INITIAL_VALUES INTEGER VSL_USER_PRIMITIVE_POLYMS INTEGER VSL_USER_INIT_DIRECTION_NUMBERS INTEGER VSL_USER_IRRED_POLYMS INTEGER VSL_USER_DIRECTION_NUMBERS INTEGER VSL_QRNG_OVERRIDE_1ST_DIM_INIT PARAMETER (VSL_USER_QRNG_INITIAL_VALUES = 1) PARAMETER (VSL_USER_PRIMITIVE_POLYMS = 1) PARAMETER (VSL_USER_INIT_DIRECTION_NUMBERS = 2) PARAMETER (VSL_USER_IRRED_POLYMS = 1) PARAMETER (VSL_USER_DIRECTION_NUMBERS = 4) PARAMETER (VSL_QRNG_OVERRIDE_1ST_DIM_INIT = 8) ! INITIALIZATION METHODS FOR USER-DESIGNED BASIC RANDOM NUMBER GENERATORS. ! Each BRNG must support at least VSL_INIT_METHOD_STANDARD initialization ! method. In addition, VSL_INIT_METHOD_LEAPFROG and VSL_INIT_METHOD_SKIPAHEAD ! initialization methods can be supported. ! ! If VSL_INIT_METHOD_LEAPFROG is not supported then initialization routine ! must return VSL_RNG_ERROR_LEAPFROG_UNSUPPORTED error code. ! ! If VSL_INIT_METHOD_SKIPAHEAD is not supported then initialization routine ! must return VSL_RNG_ERROR_SKIPAHEAD_UNSUPPORTED error code. ! ! If there is no error during initialization, the initialization routine must ! return VSL_ERROR_OK code. INTEGER VSL_INIT_METHOD_STANDARD INTEGER VSL_INIT_METHOD_LEAPFROG INTEGER VSL_INIT_METHOD_SKIPAHEAD PARAMETER (VSL_INIT_METHOD_STANDARD = 0) PARAMETER (VSL_INIT_METHOD_LEAPFROG = 1) PARAMETER (VSL_INIT_METHOD_SKIPAHEAD = 2) !++ ! ACCURACY FLAG FOR DISTRIBUTION GENERATORS ! This flag defines mode of random number generation. ! If accuracy mode is set distribution generators will produce ! numbers lying exactly within definitional domain for all values ! of distribution parameters. In this case slight performance ! degradation is expected. By default accuracy mode is switched off ! admitting random numbers to be out of the definitional domain for ! specific values of distribution parameters. ! This macro is used to form names for accuracy versions of ! distribution number generators !-- INTEGER(KIND=4) VSL_RNG_METHOD_ACCURACY_FLAG PARAMETER (VSL_RNG_METHOD_ACCURACY_FLAG=ISHFT(1,30)) !++ ! TRANSFORMATION METHOD NAMES FOR DISTRIBUTION RANDOM NUMBER GENERATORS ! VSL interface allows more than one generation method in a distribution ! transformation subroutine. Following macro definitions are used to ! specify generation method for given distribution generator. ! ! Method name macro is constructed as ! ! VSL_RNG_METHOD_<Distribution>_<Method> ! ! where ! ! <Distribution> - probability distribution ! <Method> - method name ! ! VSL_RNG_METHOD_<Distribution>_<Method> should be used with ! vsl<precision>Rng<Distribution> function only, where ! ! <precision> - s (single) or d (double) ! <Distribution> - probability distribution !-- ! Uniform ! ! <Method> <Short Description> ! STD standard method. Currently there is only one method for this ! distribution generator INTEGER VSL_RNG_METHOD_UNIFORM_STD PARAMETER (VSL_RNG_METHOD_UNIFORM_STD = 0) INTEGER VSL_RNG_METHOD_UNIFORM_STD_ACCURATE PARAMETER (VSL_RNG_METHOD_UNIFORM_STD_ACCURATE= & & IOR(VSL_RNG_METHOD_UNIFORM_STD, VSL_RNG_METHOD_ACCURACY_FLAG)) ! Uniform Bits ! ! <Method> <Short Description> ! STD standard method. Currently there is only one method for this ! distribution generator INTEGER VSL_RNG_METHOD_UNIFORMBITS_STD PARAMETER (VSL_RNG_METHOD_UNIFORMBITS_STD = 0) ! Uniform Bits 32 ! ! <Method> <Short Description> ! STD standard method. Currently there is only one method for this ! distribution generator INTEGER VSL_RNG_METHOD_UNIFORMBITS32_STD PARAMETER (VSL_RNG_METHOD_UNIFORMBITS32_STD = 0) ! Uniform Bits 64 ! ! <Method> <Short Description> ! STD standard method. Currently there is only one method for this ! distribution generator INTEGER VSL_RNG_METHOD_UNIFORMBITS64_STD PARAMETER (VSL_RNG_METHOD_UNIFORMBITS64_STD = 0) ! Gaussian ! ! <Method> <Short Description> ! BOXMULLER generates normally distributed random number x thru the pair of ! uniformly distributed numbers u1 and u2 according to the formula: ! ! x=sqrt(-ln(u1))*sin(2*Pi*u2) ! ! BOXMULLER2 generates pair of normally distributed random numbers x1 and x2 ! thru the pair of uniformly dustributed numbers u1 and u2 ! according to the formula ! ! x1=sqrt(-ln(u1))*sin(2*Pi*u2) ! x2=sqrt(-ln(u1))*cos(2*Pi*u2) ! ! NOTE: implementation correctly works with odd vector lengths ! ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_GAUSSIAN_BOXMULLER INTEGER VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2 INTEGER VSL_RNG_METHOD_GAUSSIAN_ICDF PARAMETER (VSL_RNG_METHOD_GAUSSIAN_BOXMULLER = 0) PARAMETER (VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2 = 1) PARAMETER (VSL_RNG_METHOD_GAUSSIAN_ICDF = 2) ! GaussianMV - multivariate (correlated) normal ! Multivariate (correlated) normal random number generator is based on ! uncorrelated Gaussian random number generator (see vslsRngGaussian and ! vsldRngGaussian functions): ! ! <Method> <Short Description> ! BOXMULLER generates normally distributed random number x thru the pair of ! uniformly distributed numbers u1 and u2 according to the formula: ! ! x=sqrt(-ln(u1))*sin(2*Pi*u2) ! ! BOXMULLER2 generates pair of normally distributed random numbers x1 and x2 ! thru the pair of uniformly dustributed numbers u1 and u2 ! according to the formula ! ! x1=sqrt(-ln(u1))*sin(2*Pi*u2) ! x2=sqrt(-ln(u1))*cos(2*Pi*u2) ! ! NOTE: implementation correctly works with odd vector lengths ! ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_GAUSSIANMV_BOXMULLER INTEGER VSL_RNG_METHOD_GAUSSIANMV_BOXMULLER2 INTEGER VSL_RNG_METHOD_GAUSSIANMV_ICDF PARAMETER (VSL_RNG_METHOD_GAUSSIANMV_BOXMULLER = 0) PARAMETER (VSL_RNG_METHOD_GAUSSIANMV_BOXMULLER2 = 1) PARAMETER (VSL_RNG_METHOD_GAUSSIANMV_ICDF = 2) ! Exponential ! ! <Method> <Short Description> ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_EXPONENTIAL_ICDF PARAMETER (VSL_RNG_METHOD_EXPONENTIAL_ICDF = 0) INTEGER VSL_RNG_METHOD_EXPONENTIAL_ICDF_ACCURATE PARAMETER (VSL_RNG_METHOD_EXPONENTIAL_ICDF_ACCURATE= & &IOR(VSL_RNG_METHOD_EXPONENTIAL_ICDF,VSL_RNG_METHOD_ACCURACY_FLAG)) ! Laplace ! ! <Method> <Short Description> ! ICDF inverse cumulative distribution function method ! ! ICDF - inverse cumulative distribution function method: ! ! x=+/-ln(u) with probability 1/2, ! ! where ! ! x - random number with Laplace distribution, ! u - uniformly distributed random number INTEGER VSL_RNG_METHOD_LAPLACE_ICDF PARAMETER (VSL_RNG_METHOD_LAPLACE_ICDF = 0) ! Weibull ! ! <Method> <Short Description> ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_WEIBULL_ICDF PARAMETER (VSL_RNG_METHOD_WEIBULL_ICDF = 0) INTEGER VSL_RNG_METHOD_WEIBULL_ICDF_ACCURATE PARAMETER (VSL_RNG_METHOD_WEIBULL_ICDF_ACCURATE= & & IOR(VSL_RNG_METHOD_WEIBULL_ICDF, VSL_RNG_METHOD_ACCURACY_FLAG)) ! Cauchy ! ! <Method> <Short Description> ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_CAUCHY_ICDF PARAMETER (VSL_RNG_METHOD_CAUCHY_ICDF = 0) ! Rayleigh ! ! <Method> <Short Description> ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_RAYLEIGH_ICDF PARAMETER (VSL_RNG_METHOD_RAYLEIGH_ICDF = 0) INTEGER VSL_RNG_METHOD_RAYLEIGH_ICDF_ACCURATE PARAMETER (VSL_RNG_METHOD_RAYLEIGH_ICDF_ACCURATE= & & IOR(VSL_RNG_METHOD_RAYLEIGH_ICDF, VSL_RNG_METHOD_ACCURACY_FLAG)) ! Lognormal ! ! <Method> <Short Description> ! BOXMULLER2 Box-Muller 2 algorithm based method INTEGER VSL_RNG_METHOD_LOGNORMAL_BOXMULLER2 INTEGER VSL_RNG_METHOD_LOGNORMAL_ICDF PARAMETER (VSL_RNG_METHOD_LOGNORMAL_BOXMULLER2 = 0) PARAMETER (VSL_RNG_METHOD_LOGNORMAL_ICDF = 1) INTEGER VSL_RNG_METHOD_LOGNORMAL_BOXMULLER2_ACCURATE INTEGER VSL_RNG_METHOD_LOGNORMAL_ICDF_ACCURATE PARAMETER (VSL_RNG_METHOD_LOGNORMAL_BOXMULLER2_ACCURATE= & & IOR(VSL_RNG_METHOD_LOGNORMAL_BOXMULLER2, & & VSL_RNG_METHOD_ACCURACY_FLAG)) PARAMETER (VSL_RNG_METHOD_LOGNORMAL_ICDF_ACCURATE= & & IOR(VSL_RNG_METHOD_LOGNORMAL_ICDF, VSL_RNG_METHOD_ACCURACY_FLAG)) ! Gumbel ! ! <Method> <Short Description> ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_GUMBEL_ICDF PARAMETER (VSL_RNG_METHOD_GUMBEL_ICDF = 0) ! Gamma ! ! <Method> <Short Description> ! GNORM nonlinear transformation of gaussian numbers ! alpha>1, based on acceptance/rejection method with ! squeezes ! ! alpha>=0.6, rejection from the Weibull distribution ! alpha<1 ! ! alpha<0.6, transformation of exponential power distribution ! (EPD), EPD random numbers are generated using ! by means of acceptance/rejection technique INTEGER VSL_RNG_METHOD_GAMMA_GNORM PARAMETER (VSL_RNG_METHOD_GAMMA_GNORM = 0) INTEGER VSL_RNG_METHOD_GAMMA_GNORM_ACCURATE PARAMETER (VSL_RNG_METHOD_GAMMA_GNORM_ACCURATE= & & IOR(VSL_RNG_METHOD_GAMMA_GNORM, VSL_RNG_METHOD_ACCURACY_FLAG)) ! Beta ! ! <Method> <Short Description> ! CJA - stands for first letters of Cheng, Johnk, and Atkinson ! Cheng - generation of beta random numbers of the second kind ! min(p,q)>1 based on acceptance/rejection technique and its ! transformation to beta random numbers of the first kind; ! ! Johnk, - if q + K*p^2+C<=0, K=0.852..., C=-0.956... ! Atkinson, algorithm of Johnk: beta distributed random number ! max(p,q)<1 is generated as u1^(1/p) / (u1^(1/p)+u2^(1/q)), ! if u1^(1/p)+u2^(1/q)<=1; ! otherwise switching algorithm of Atkinson: ! interval (0,1) is divided into two domains (0,t) and (t,1), ! on each interval acceptance/rejection technique with ! convenient majorizing function is used; ! ! Atkinson - switching algorithm of Atkinson is used ! min(p,q)<1 (with another point t, see short description above); ! max(p,q)>1 ! ! ICDF - inverse cumulative distribution function method according ! to formulas x=1-u^(1/q) for p = 1, and x = u^(1/p) for q=1, ! where x is beta distributed random number, ! u - uniformly distributed random number. ! for p=q=1 beta distribution reduces to uniform distribution. INTEGER VSL_RNG_METHOD_BETA_CJA PARAMETER (VSL_RNG_METHOD_BETA_CJA = 0) INTEGER VSL_RNG_METHOD_BETA_CJA_ACCURATE PARAMETER (VSL_RNG_METHOD_BETA_CJA_ACCURATE= & & IOR(VSL_RNG_METHOD_BETA_CJA, VSL_RNG_METHOD_ACCURACY_FLAG)) ! Bernoulli ! ! <Method> <Short Description> ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_BERNOULLI_ICDF PARAMETER (VSL_RNG_METHOD_BERNOULLI_ICDF = 0) ! Geometric ! ! <Method> <Short Description> ! ICDF inverse cumulative distribution function method INTEGER VSL_RNG_METHOD_GEOMETRIC_ICDF PARAMETER (VSL_RNG_METHOD_GEOMETRIC_ICDF = 0) ! Binomial ! ! <Method> <Short Description> ! BTPE for ntrial*min(p,1-p)>30 acceptance/rejection method with ! decomposition onto 4 regions: ! ! * 2 parallelograms; ! * triangle; ! * left exponential tail; ! * right exponential tail. ! ! othewise table lookup method is used INTEGER VSL_RNG_METHOD_BINOMIAL_BTPE PARAMETER (VSL_RNG_METHOD_BINOMIAL_BTPE = 0) ! Hypergeometric ! ! <Method> <Short Description> ! H2PE if mode of distribution is large, acceptance/rejection method is ! used with decomposition onto 3 regions: ! ! * rectangular; ! * left exponential tail; ! * right exponential tail. ! ! othewise table lookup method is used INTEGER VSL_RNG_METHOD_HYPERGEOMETRIC_H2PE PARAMETER (VSL_RNG_METHOD_HYPERGEOMETRIC_H2PE = 0) ! Poisson ! ! <Method> <Short Description> ! PTPE if lambda>=27, acceptance/rejection method is used with ! decomposition onto 4 regions: ! ! * 2 parallelograms; ! * triangle; ! * left exponential tail; ! * right exponential tail. ! ! othewise table lookup method is used ! ! POISNORM for lambda>=1 method is based on Poisson inverse CDF ! approximation by Gaussian inverse CDF; for lambda<1 ! table lookup method is used. INTEGER VSL_RNG_METHOD_POISSON_PTPE INTEGER VSL_RNG_METHOD_POISSON_POISNORM PARAMETER (VSL_RNG_METHOD_POISSON_PTPE = 0) PARAMETER (VSL_RNG_METHOD_POISSON_POISNORM = 1) ! Poisson ! ! <Method> <Short Description> ! POISNORM for lambda>=1 method is based on Poisson inverse CDF ! approximation by Gaussian inverse CDF; for lambda<1 ! ICDF method is used. INTEGER VSL_RNG_METHOD_POISSONV_POISNORM PARAMETER (VSL_RNG_METHOD_POISSONV_POISNORM = 0) ! Negbinomial ! ! <Method> <Short Description> ! NBAR if (a-1)*(1-p)/p>=100, acceptance/rejection method is used with ! decomposition onto 5 regions: ! ! * rectangular; ! * 2 trapezoid; ! * left exponential tail; ! * right exponential tail. ! ! othewise table lookup method is used. INTEGER VSL_RNG_METHOD_NEGBINOMIAL_NBAR PARAMETER (VSL_RNG_METHOD_NEGBINOMIAL_NBAR = 0) !++ ! MATRIX STORAGE SCHEMES !-- ! Some multivariate random number generators, e.g. GaussianMV, operate ! with matrix parameters. To optimize matrix parameters usage VSL offers ! following matrix storage schemes. (See VSL documentation for more details). ! ! FULL - whole matrix is stored ! PACKED - lower/higher triangular matrix is packed in 1-dimensional array ! DIAGONAL - diagonal elements are packed in 1-dimensional array INTEGER VSL_MATRIX_STORAGE_FULL INTEGER VSL_MATRIX_STORAGE_PACKED INTEGER VSL_MATRIX_STORAGE_DIAGONAL PARAMETER (VSL_MATRIX_STORAGE_FULL = 0) PARAMETER (VSL_MATRIX_STORAGE_PACKED = 1) PARAMETER (VSL_MATRIX_STORAGE_DIAGONAL = 2) !++ ! SUMMARY STATISTICS (SS) RELATED MACRO DEFINITIONS !-- !++ ! MATRIX STORAGE SCHEMES !-- ! ! SS routines work with matrix parameters, e.g. matrix of observations, ! variance-covariance matrix. To optimize work with matrices the library ! provides the following storage matrix schemes. ! !++ ! Matrix of observations: ! ROWS - observations of the random vector are stored in raws, that ! is, i-th row of the matrix of observations contains values ! of i-th component of the random vector ! COLS - observations of the random vector are stored in columns that ! is, i-th column of the matrix of observations contains values ! of i-th component of the random vector !-- INTEGER VSL_SS_MATRIX_STORAGE_ROWS INTEGER VSL_SS_MATRIX_STORAGE_COLS PARAMETER (VSL_SS_MATRIX_STORAGE_ROWS = Z"00010000") PARAMETER (VSL_SS_MATRIX_STORAGE_COLS = Z"00020000") !++ ! Variance-covariance/correlation matrix: ! FULL - whole matrix is stored ! L_PACKED - lower triangular matrix is stored as 1-dimensional array ! U_PACKED - upper triangular matrix is stored as 1-dimensional array !-- INTEGER VSL_SS_MATRIX_STORAGE_FULL INTEGER VSL_SS_MATRIX_STORAGE_L_PACKED INTEGER VSL_SS_MATRIX_STORAGE_U_PACKED PARAMETER (VSL_SS_MATRIX_STORAGE_FULL = Z"00000000") PARAMETER (VSL_SS_MATRIX_STORAGE_L_PACKED = Z"00000001") PARAMETER (VSL_SS_MATRIX_STORAGE_U_PACKED = Z"00000002") !++ ! SUMMARY STATISTICS LIBRARY METHODS !-- ! SS routines provide computation of basic statistical estimates ! (central/raw moments up to 4th order, variance-covariance, ! minimum, maximum, skewness/kurtosis) using the following methods ! - FAST - estimates are computed for price of one or two passes over ! observations using highly optimized MKL routines ! - 1PASS - estimate is computed for price of one pass of the observations ! - FAST_USER_MEAN - estimates are computed for price of one or two passes ! over observations given user defined mean for central moments, ! covariance and correlation ! - CP_TO_COVCOR - convert cross-product matrix to variance-covariance/ ! correlation matrix ! - SUM_TO_MOM - convert raw/central sums to raw/central moments INTEGER VSL_SS_METHOD_FAST INTEGER VSL_SS_METHOD_1PASS INTEGER VSL_SS_METHOD_FAST_USER_MEAN INTEGER VSL_SS_METHOD_CP_TO_COVCOR INTEGER VSL_SS_METHOD_SUM_TO_MOM PARAMETER (VSL_SS_METHOD_FAST = Z"00000001") PARAMETER (VSL_SS_METHOD_1PASS = Z"00000002") PARAMETER (VSL_SS_METHOD_FAST_USER_MEAN = Z"00000100") PARAMETER (VSL_SS_METHOD_CP_TO_COVCOR = Z"00000200") PARAMETER (VSL_SS_METHOD_SUM_TO_MOM = Z"00000400") ! SS provides routine for parametrization of correlation matrix using ! SPECTRAL DECOMPOSITION (SD) method INTEGER VSL_SS_METHOD_SD PARAMETER (VSL_SS_METHOD_SD = Z"00000004") ! SS routine for robust estimation of variance-covariance matrix ! and mean supports Rocke algorithm, TBS-estimator INTEGER VSL_SS_METHOD_TBS PARAMETER (VSL_SS_METHOD_TBS = Z"00000008") ! SS routine for estimation of missing values ! supports Multiple Imputation (MI) method INTEGER VSL_SS_METHOD_MI PARAMETER (VSL_SS_METHOD_MI = Z"00000010") ! SS provides routine for detection of outliers, BACON method INTEGER VSL_SS_METHOD_BACON PARAMETER (VSL_SS_METHOD_BACON= Z"00000020") ! SS supports routine for estimation of quantiles for streaming data ! using the following methods: ! - ZW - intermediate estimates of quantiles during processing ! the next block are computed ! - ZW - intermediate estimates of quantiles during processing ! the next block are not computed INTEGER VSL_SS_METHOD_SQUANTS_ZW INTEGER VSL_SS_METHOD_SQUANTS_ZW_FAST PARAMETER (VSL_SS_METHOD_SQUANTS_ZW = Z"00000040") PARAMETER (VSL_SS_METHOD_SQUANTS_ZW_FAST = Z"00000080") ! Input of BACON algorithm is set of 3 parameters: ! - Initialization method of the algorithm ! - Parameter alfa such that 1-alfa is percentile of Chi2 distribution ! - Stopping criterion ! Number of BACON algorithm parameters INTEGER VSL_SS_BACON_PARAMS_N PARAMETER (VSL_SS_BACON_PARAMS_N = 3) ! SS implementation of BACON algorithm supports two initialization methods: ! - Mahalanobis distance based method ! - Median based method INTEGER(KIND=4) VSL_SS_METHOD_BACON_MAHALANOBIS_INIT INTEGER(KIND=4) VSL_SS_METHOD_BACON_MEDIAN_INIT PARAMETER (VSL_SS_METHOD_BACON_MAHALANOBIS_INIT = Z"00000001") PARAMETER (VSL_SS_METHOD_BACON_MEDIAN_INIT = Z"00000002") ! Input of TBS algorithm is set of 4 parameters: ! - Breakdown point ! - Asymptotic rejection probability ! - Stopping criterion ! - Maximum number of iterations ! Number of TBS algorithm parameters INTEGER VSL_SS_TBS_PARAMS_N PARAMETER (VSL_SS_TBS_PARAMS_N = 4) ! Input of MI algorithm is set of 5 parameters: ! - Maximal number of iterations for EM algorithm ! - Maximal number of iterations for DA algorithm ! - Stopping criterion ! - Number of sets to impute ! - Total number of missing values in dataset ! Number of MI algorithm parameters INTEGER VSL_SS_MI_PARAMS_SIZE PARAMETER (VSL_SS_MI_PARAMS_SIZE = 5) ! SS MI algorithm expects that missing values are ! marked with NANs REAL(KIND=8) VSL_SS_DNAN REAL(KIND=4) VSL_SS_SNAN PARAMETER (VSL_SS_DNAN = Z"FFF8000000000000") PARAMETER (VSL_SS_SNAN = Z"FFC00000") ! Input of ZW algorithm is 1 parameter: ! - accuracy of quantile estimation ! Number of ZW algorithm parameters INTEGER VSL_SS_SQUANTS_ZW_PARAMS_N PARAMETER (VSL_SS_SQUANTS_ZW_PARAMS_N = 1) !++ ! MACROS USED SS EDIT AND COMPUTE ROUTINES !-- ! SS EditTask routine is way to edit input and output parameters of the task, ! e.g., pointers to arrays which hold observations, weights of observations, ! arrays of mean estimates or covariance estimates. ! Macros below define parameters available for modification INTEGER VSL_SS_ED_DIMEN INTEGER VSL_SS_ED_OBSERV_N INTEGER VSL_SS_ED_OBSERV INTEGER VSL_SS_ED_OBSERV_STORAGE INTEGER VSL_SS_ED_INDC INTEGER VSL_SS_ED_WEIGHTS INTEGER VSL_SS_ED_MEAN INTEGER VSL_SS_ED_2R_MOM INTEGER VSL_SS_ED_3R_MOM INTEGER VSL_SS_ED_4R_MOM INTEGER VSL_SS_ED_2C_MOM INTEGER VSL_SS_ED_3C_MOM INTEGER VSL_SS_ED_4C_MOM INTEGER VSL_SS_ED_KURTOSIS INTEGER VSL_SS_ED_SKEWNESS INTEGER VSL_SS_ED_MIN INTEGER VSL_SS_ED_MAX INTEGER VSL_SS_ED_VARIATION INTEGER VSL_SS_ED_COV INTEGER VSL_SS_ED_COV_STORAGE INTEGER VSL_SS_ED_COR INTEGER VSL_SS_ED_COR_STORAGE INTEGER VSL_SS_ED_ACCUM_WEIGHT INTEGER VSL_SS_ED_QUANT_ORDER_N INTEGER VSL_SS_ED_QUANT_ORDER INTEGER VSL_SS_ED_QUANT_QUANTILES INTEGER VSL_SS_ED_ORDER_STATS INTEGER VSL_SS_ED_GROUP_INDC INTEGER VSL_SS_ED_POOLED_COV_STORAGE INTEGER VSL_SS_ED_POOLED_MEAN INTEGER VSL_SS_ED_POOLED_COV INTEGER VSL_SS_ED_GROUP_COV_INDC INTEGER VSL_SS_ED_REQ_GROUP_INDC INTEGER VSL_SS_ED_GROUP_MEAN INTEGER VSL_SS_ED_GROUP_COV_STORAGE INTEGER VSL_SS_ED_GROUP_COV INTEGER VSL_SS_ED_ROBUST_COV_STORAGE INTEGER VSL_SS_ED_ROBUST_COV_PARAMS_N INTEGER VSL_SS_ED_ROBUST_COV_PARAMS INTEGER VSL_SS_ED_ROBUST_MEAN INTEGER VSL_SS_ED_ROBUST_COV INTEGER VSL_SS_ED_OUTLIERS_PARAMS_N INTEGER VSL_SS_ED_OUTLIERS_PARAMS INTEGER VSL_SS_ED_OUTLIERS_WEIGHT INTEGER VSL_SS_ED_ORDER_STATS_STORAGE INTEGER VSL_SS_ED_PARTIAL_COV_IDX INTEGER VSL_SS_ED_PARTIAL_COV INTEGER VSL_SS_ED_PARTIAL_COV_STORAGE INTEGER VSL_SS_ED_PARTIAL_COR INTEGER VSL_SS_ED_PARTIAL_COR_STORAGE INTEGER VSL_SS_ED_MI_PARAMS_N INTEGER VSL_SS_ED_MI_PARAMS INTEGER VSL_SS_ED_MI_INIT_ESTIMATES_N INTEGER VSL_SS_ED_MI_INIT_ESTIMATES INTEGER VSL_SS_ED_MI_SIMUL_VALS_N INTEGER VSL_SS_ED_MI_SIMUL_VALS INTEGER VSL_SS_ED_MI_ESTIMATES_N INTEGER VSL_SS_ED_MI_ESTIMATES INTEGER VSL_SS_ED_MI_PRIOR_N INTEGER VSL_SS_ED_MI_PRIOR INTEGER VSL_SS_ED_PARAMTR_COR INTEGER VSL_SS_ED_PARAMTR_COR_STORAGE INTEGER VSL_SS_ED_STREAM_QUANT_PARAMS_N INTEGER VSL_SS_ED_STREAM_QUANT_PARAMS INTEGER VSL_SS_ED_STREAM_QUANT_ORDER_N INTEGER VSL_SS_ED_STREAM_QUANT_ORDER INTEGER VSL_SS_ED_STREAM_QUANT_QUANTILES INTEGER VSL_SS_ED_SUM INTEGER VSL_SS_ED_2R_SUM INTEGER VSL_SS_ED_3R_SUM INTEGER VSL_SS_ED_4R_SUM INTEGER VSL_SS_ED_2C_SUM INTEGER VSL_SS_ED_3C_SUM INTEGER VSL_SS_ED_4C_SUM INTEGER VSL_SS_ED_CP INTEGER VSL_SS_ED_CP_STORAGE INTEGER VSL_SS_ED_MDAD INTEGER VSL_SS_ED_MNAD PARAMETER (VSL_SS_ED_DIMEN = 1) PARAMETER (VSL_SS_ED_OBSERV_N = 2) PARAMETER (VSL_SS_ED_OBSERV = 3) PARAMETER (VSL_SS_ED_OBSERV_STORAGE = 4) PARAMETER (VSL_SS_ED_INDC = 5) PARAMETER (VSL_SS_ED_WEIGHTS = 6) PARAMETER (VSL_SS_ED_MEAN = 7) PARAMETER (VSL_SS_ED_2R_MOM = 8) PARAMETER (VSL_SS_ED_3R_MOM = 9) PARAMETER (VSL_SS_ED_4R_MOM = 10) PARAMETER (VSL_SS_ED_2C_MOM = 11) PARAMETER (VSL_SS_ED_3C_MOM = 12) PARAMETER (VSL_SS_ED_4C_MOM = 13) PARAMETER (VSL_SS_ED_KURTOSIS = 14) PARAMETER (VSL_SS_ED_SKEWNESS = 15) PARAMETER (VSL_SS_ED_MIN = 16) PARAMETER (VSL_SS_ED_MAX = 17) PARAMETER (VSL_SS_ED_VARIATION = 18) PARAMETER (VSL_SS_ED_COV = 19) PARAMETER (VSL_SS_ED_COV_STORAGE = 20) PARAMETER (VSL_SS_ED_COR = 21) PARAMETER (VSL_SS_ED_COR_STORAGE = 22) PARAMETER (VSL_SS_ED_ACCUM_WEIGHT = 23) PARAMETER (VSL_SS_ED_QUANT_ORDER_N = 24) PARAMETER (VSL_SS_ED_QUANT_ORDER = 25) PARAMETER (VSL_SS_ED_QUANT_QUANTILES = 26) PARAMETER (VSL_SS_ED_ORDER_STATS = 27) PARAMETER (VSL_SS_ED_GROUP_INDC = 28) PARAMETER (VSL_SS_ED_POOLED_COV_STORAGE = 29) PARAMETER (VSL_SS_ED_POOLED_MEAN = 30) PARAMETER (VSL_SS_ED_POOLED_COV = 31) PARAMETER (VSL_SS_ED_GROUP_COV_INDC = 32) PARAMETER (VSL_SS_ED_REQ_GROUP_INDC = 32) PARAMETER (VSL_SS_ED_GROUP_MEAN = 33) PARAMETER (VSL_SS_ED_GROUP_COV_STORAGE = 34) PARAMETER (VSL_SS_ED_GROUP_COV = 35) PARAMETER (VSL_SS_ED_ROBUST_COV_STORAGE = 36) PARAMETER (VSL_SS_ED_ROBUST_COV_PARAMS_N = 37) PARAMETER (VSL_SS_ED_ROBUST_COV_PARAMS = 38) PARAMETER (VSL_SS_ED_ROBUST_MEAN = 39) PARAMETER (VSL_SS_ED_ROBUST_COV = 40) PARAMETER (VSL_SS_ED_OUTLIERS_PARAMS_N = 41) PARAMETER (VSL_SS_ED_OUTLIERS_PARAMS = 42) PARAMETER (VSL_SS_ED_OUTLIERS_WEIGHT = 43) PARAMETER (VSL_SS_ED_ORDER_STATS_STORAGE = 44) PARAMETER (VSL_SS_ED_PARTIAL_COV_IDX = 45) PARAMETER (VSL_SS_ED_PARTIAL_COV = 46) PARAMETER (VSL_SS_ED_PARTIAL_COV_STORAGE = 47) PARAMETER (VSL_SS_ED_PARTIAL_COR = 48) PARAMETER (VSL_SS_ED_PARTIAL_COR_STORAGE = 49) PARAMETER (VSL_SS_ED_MI_PARAMS_N = 50) PARAMETER (VSL_SS_ED_MI_PARAMS = 51) PARAMETER (VSL_SS_ED_MI_INIT_ESTIMATES_N = 52) PARAMETER (VSL_SS_ED_MI_INIT_ESTIMATES = 53) PARAMETER (VSL_SS_ED_MI_SIMUL_VALS_N = 54) PARAMETER (VSL_SS_ED_MI_SIMUL_VALS = 55) PARAMETER (VSL_SS_ED_MI_ESTIMATES_N = 56) PARAMETER (VSL_SS_ED_MI_ESTIMATES = 57) PARAMETER (VSL_SS_ED_MI_PRIOR_N = 58) PARAMETER (VSL_SS_ED_MI_PRIOR = 59) PARAMETER (VSL_SS_ED_PARAMTR_COR = 60) PARAMETER (VSL_SS_ED_PARAMTR_COR_STORAGE = 61) PARAMETER (VSL_SS_ED_STREAM_QUANT_PARAMS_N = 62) PARAMETER (VSL_SS_ED_STREAM_QUANT_PARAMS = 63) PARAMETER (VSL_SS_ED_STREAM_QUANT_ORDER_N = 64) PARAMETER (VSL_SS_ED_STREAM_QUANT_ORDER = 65) PARAMETER (VSL_SS_ED_STREAM_QUANT_QUANTILES = 66) PARAMETER (VSL_SS_ED_SUM = 67) PARAMETER (VSL_SS_ED_2R_SUM = 68) PARAMETER (VSL_SS_ED_3R_SUM = 69) PARAMETER (VSL_SS_ED_4R_SUM = 70) PARAMETER (VSL_SS_ED_2C_SUM = 71) PARAMETER (VSL_SS_ED_3C_SUM = 72) PARAMETER (VSL_SS_ED_4C_SUM = 73) PARAMETER (VSL_SS_ED_CP = 74) PARAMETER (VSL_SS_ED_CP_STORAGE = 75) PARAMETER (VSL_SS_ED_MDAD = 76) PARAMETER (VSL_SS_ED_MNAD = 77) ! SS Compute routine calculates estimates supported by the library ! Macros below define estimates to compute INTEGER(KIND=8) VSL_SS_MEAN INTEGER(KIND=8) VSL_SS_2R_MOM INTEGER(KIND=8) VSL_SS_3R_MOM INTEGER(KIND=8) VSL_SS_4R_MOM INTEGER(KIND=8) VSL_SS_2C_MOM INTEGER(KIND=8) VSL_SS_3C_MOM INTEGER(KIND=8) VSL_SS_4C_MOM INTEGER(KIND=8) VSL_SS_SUM INTEGER(KIND=8) VSL_SS_2R_SUM INTEGER(KIND=8) VSL_SS_3R_SUM INTEGER(KIND=8) VSL_SS_4R_SUM INTEGER(KIND=8) VSL_SS_2C_SUM INTEGER(KIND=8) VSL_SS_3C_SUM INTEGER(KIND=8) VSL_SS_4C_SUM INTEGER(KIND=8) VSL_SS_KURTOSIS INTEGER(KIND=8) VSL_SS_SKEWNESS INTEGER(KIND=8) VSL_SS_VARIATION INTEGER(KIND=8) VSL_SS_MIN INTEGER(KIND=8) VSL_SS_MAX INTEGER(KIND=8) VSL_SS_COV INTEGER(KIND=8) VSL_SS_COR INTEGER(KIND=8) VSL_SS_CP INTEGER(KIND=8) VSL_SS_POOLED_COV INTEGER(KIND=8) VSL_SS_GROUP_COV INTEGER(KIND=8) VSL_SS_POOLED_MEAN INTEGER(KIND=8) VSL_SS_GROUP_MEAN INTEGER(KIND=8) VSL_SS_QUANTS INTEGER(KIND=8) VSL_SS_ORDER_STATS INTEGER(KIND=8) VSL_SS_ROBUST_COV INTEGER(KIND=8) VSL_SS_OUTLIERS INTEGER(KIND=8) VSL_SS_PARTIAL_COV INTEGER(KIND=8) VSL_SS_PARTIAL_COR INTEGER(KIND=8) VSL_SS_MISSING_VALS INTEGER(KIND=8) VSL_SS_PARAMTR_COR INTEGER(KIND=8) VSL_SS_STREAM_QUANTS INTEGER(KIND=8) VSL_SS_MDAD INTEGER(KIND=8) VSL_SS_MNAD PARAMETER ( VSL_SS_MEAN = Z"0000000000000001" ) PARAMETER ( VSL_SS_2R_MOM = Z"0000000000000002" ) PARAMETER ( VSL_SS_3R_MOM = Z"0000000000000004" ) PARAMETER ( VSL_SS_4R_MOM = Z"0000000000000008" ) PARAMETER ( VSL_SS_2C_MOM = Z"0000000000000010" ) PARAMETER ( VSL_SS_3C_MOM = Z"0000000000000020" ) PARAMETER ( VSL_SS_4C_MOM = Z"0000000000000040" ) PARAMETER ( VSL_SS_SUM = Z"0000000002000000" ) PARAMETER ( VSL_SS_2R_SUM = Z"0000000004000000" ) PARAMETER ( VSL_SS_3R_SUM = Z"0000000008000000" ) PARAMETER ( VSL_SS_4R_SUM = Z"0000000010000000" ) PARAMETER ( VSL_SS_2C_SUM = Z"0000000020000000" ) PARAMETER ( VSL_SS_3C_SUM = Z"0000000040000000" ) PARAMETER ( VSL_SS_4C_SUM = Z"0000000080000000" ) PARAMETER ( VSL_SS_KURTOSIS = Z"0000000000000080" ) PARAMETER ( VSL_SS_SKEWNESS = Z"0000000000000100" ) PARAMETER ( VSL_SS_VARIATION = Z"0000000000000200" ) PARAMETER ( VSL_SS_MIN = Z"0000000000000400" ) PARAMETER ( VSL_SS_MAX = Z"0000000000000800" ) PARAMETER ( VSL_SS_COV = Z"0000000000001000" ) PARAMETER ( VSL_SS_COR = Z"0000000000002000" ) PARAMETER ( VSL_SS_CP = Z"0000000100000000" ) PARAMETER ( VSL_SS_POOLED_COV = Z"0000000000004000" ) PARAMETER ( VSL_SS_GROUP_COV = Z"0000000000008000" ) PARAMETER ( VSL_SS_POOLED_MEAN = Z"0000000800000000" ) PARAMETER ( VSL_SS_GROUP_MEAN = Z"0000001000000000" ) PARAMETER ( VSL_SS_QUANTS = Z"0000000000010000" ) PARAMETER ( VSL_SS_ORDER_STATS = Z"0000000000020000" ) PARAMETER ( VSL_SS_ROBUST_COV = Z"0000000000040000" ) PARAMETER ( VSL_SS_OUTLIERS = Z"0000000000080000" ) PARAMETER ( VSL_SS_PARTIAL_COV = Z"0000000000100000" ) PARAMETER ( VSL_SS_PARTIAL_COR = Z"0000000000200000" ) PARAMETER ( VSL_SS_MISSING_VALS = Z"0000000000400000" ) PARAMETER ( VSL_SS_PARAMTR_COR = Z"0000000000800000" ) PARAMETER ( VSL_SS_STREAM_QUANTS = Z"0000000001000000" ) PARAMETER ( VSL_SS_MDAD = Z"0000000200000000" ) PARAMETER ( VSL_SS_MNAD = Z"0000000400000000" ) !++ ! TYPEDEFS !-- ! VSL STREAM STATE POINTER ! This structure is to store VSL stream state address allocated by ! VSLNEWSTREAM subroutine. TYPE VSL_STREAM_STATE INTEGER(KIND=4) descriptor1 INTEGER(KIND=4) descriptor2 END TYPE VSL_STREAM_STATE TYPE VSL_CONV_TASK INTEGER(KIND=4) descriptor1 INTEGER(KIND=4) descriptor2 END TYPE VSL_CONV_TASK TYPE VSL_CORR_TASK INTEGER(KIND=4) descriptor1 INTEGER(KIND=4) descriptor2 END TYPE VSL_CORR_TASK TYPE VSL_SS_TASK INTEGER(KIND=4) descriptor1 INTEGER(KIND=4) descriptor2 END TYPE VSL_SS_TASK ! BASIC RANDOM NUMBER GENERATOR PROPERTIES STRUCTURE ! The structure describes the properties of given basic generator, e.g. size ! of the stream state structure, pointers to function implementations, etc. ! ! BRNG properties structure fields: ! StreamStateSize - size of the stream state structure (in bytes) ! WordSize - size of base word (in bytes). Typically this is 4 bytes. ! NSeeds - number of words necessary to describe generator's state ! NBits - number of bits actually used in base word. For example, ! only 31 least significant bits are actually used in ! basic random number generator MCG31m1 with 4-byte base ! word. NBits field is useful while interpreting random ! words as a sequence of random bits. ! IncludesZero - FALSE if 0 cannot be generated in integer-valued ! implementation; TRUE if 0 can be potentially generated in ! integer-valued implementation. ! reserved - a reserved field for internal needs TYPE VSL_BRNG_PROPERTIES INTEGER(KIND=4) streamstatesize INTEGER(KIND=4) nseeds INTEGER(KIND=4) includeszero INTEGER(KIND=4) wordsize INTEGER(KIND=4) nbits INTEGER(KIND=4) reserved(8) END TYPE VSL_BRNG_PROPERTIES END MODULE MKL_VSL_TYPE MODULE MKL_VSL USE MKL_VSL_TYPE !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !============================================================================== !------------------------------------------------------------------------------ INTERFACE INTEGER FUNCTION vsldconvnewtask( task, mode, dims, xshape, & & yshape, zshape ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims),zshape(dims) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsconvnewtask( task, mode, dims, xshape, & & yshape, zshape ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims),zshape(dims) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzconvnewtask( task, mode, dims, xshape, & & yshape, zshape ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims),zshape(dims) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcconvnewtask( task, mode, dims, xshape, & & yshape, zshape ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims),zshape(dims) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldcorrnewtask( task, mode, dims, xshape, & & yshape, zshape ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims),zshape(dims) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslscorrnewtask( task, mode, dims, xshape, & & yshape, zshape ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims),zshape(dims) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzcorrnewtask( task, mode, dims, xshape, & & yshape, zshape ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims),zshape(dims) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslccorrnewtask( task, mode, dims, xshape, & & yshape, zshape ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims),zshape(dims) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldconvnewtask1d( task, mode, xshape, yshape, & & zshape ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsconvnewtask1d( task, mode, xshape, yshape, & & zshape ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzconvnewtask1d( task, mode, xshape, yshape, & & zshape ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcconvnewtask1d( task, mode, xshape, yshape, & & zshape ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldcorrnewtask1d( task, mode, xshape, yshape, & & zshape ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslscorrnewtask1d( task, mode, xshape, yshape, & & zshape ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzcorrnewtask1d( task, mode, xshape, yshape, & & zshape ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslccorrnewtask1d( task, mode, xshape, yshape, & & zshape ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldconvnewtaskx( task, mode, dims, xshape, & & yshape, zshape, x, xstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims) INTEGER :: zshape(dims),xstride(dims) REAL(8),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsconvnewtaskx( task, mode, dims, xshape, & & yshape, zshape, x, xstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims) INTEGER :: zshape(dims),xstride(dims) REAL(4),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzconvnewtaskx( task, mode, dims, xshape, & & yshape, zshape, x, xstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims) INTEGER :: zshape(dims),xstride(dims) COMPLEX(8),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcconvnewtaskx( task, mode, dims, xshape, & & yshape, zshape, x, xstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims) INTEGER :: zshape(dims),xstride(dims) COMPLEX(4),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldcorrnewtaskx( task, mode, dims, xshape, & & yshape, zshape, x, xstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims) INTEGER :: zshape(dims),xstride(dims) REAL(8),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslscorrnewtaskx( task, mode, dims, xshape, & & yshape, zshape, x, xstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims) INTEGER :: zshape(dims),xstride(dims) REAL(4),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzcorrnewtaskx( task, mode, dims, xshape, & & yshape, zshape, x, xstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims) INTEGER :: zshape(dims),xstride(dims) COMPLEX(8),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslccorrnewtaskx( task, mode, dims, xshape, & & yshape, zshape, x, xstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode,dims INTEGER :: xshape(dims),yshape(dims) INTEGER :: zshape(dims),xstride(dims) COMPLEX(4),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldconvnewtaskx1d( task, mode, xshape, & & yshape, zshape, x,xstride) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape,xstride REAL(8),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsconvnewtaskx1d( task, mode, xshape, & & yshape, zshape, x,xstride) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape,xstride REAL(4),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzconvnewtaskx1d( task, mode, xshape, & & yshape, zshape, x,xstride) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape,xstride COMPLEX(8),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcconvnewtaskx1d( task, mode, xshape, & & yshape, zshape, x,xstride) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape,xstride COMPLEX(4),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldcorrnewtaskx1d( task, mode, xshape, & & yshape, zshape, x,xstride) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape,xstride REAL(8),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslscorrnewtaskx1d( task, mode, xshape, & & yshape, zshape, x,xstride) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape,xstride REAL(4),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzcorrnewtaskx1d( task, mode, xshape, & & yshape, zshape, x,xstride) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape,xstride COMPLEX(8),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslccorrnewtaskx1d( task, mode, xshape, & & yshape, zshape, x,xstride) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: mode INTEGER :: xshape,yshape,zshape,xstride COMPLEX(4),DIMENSION(*):: x END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslconvdeletetask( task ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcorrdeletetask( task ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslconvcopytask( desttask, srctask ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: desttask TYPE(VSL_CONV_TASK) :: srctask END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcorrcopytask( desttask, srctask ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: desttask TYPE(VSL_CORR_TASK) :: srctask END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslConvSetMode( task, newmode ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: newmode END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslCorrSetMode( task, newmode ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: newmode END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslConvSetInternalPrecision( task, precision ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: precision END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslCorrSetInternalPrecision( task, precision ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: precision END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslConvSetStart( task, start ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*):: start END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslCorrSetStart( task, start ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*):: start END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslConvSetDecimation( task, decimation ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*):: decimation END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslCorrSetDecimation( task, decimation ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*):: decimation END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldconvexec( task, x, xstride, y, ystride, z, & & zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*) :: xstride,ystride,zstride REAL(KIND=8),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsconvexec( task, x, xstride, y, ystride, z, & & zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*) :: xstride,ystride,zstride REAL(KIND=4),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzconvexec( task, x, xstride, y, ystride, z, & & zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*) :: xstride,ystride,zstride COMPLEX(KIND=8),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcconvexec( task, x, xstride, y, ystride, z, & & zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*) :: xstride,ystride,zstride COMPLEX(KIND=4),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldcorrexec( task, x, xstride, y, ystride, z, & & zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*) :: xstride,ystride,zstride REAL(KIND=8),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslscorrexec( task, x, xstride, y, ystride, z, & & zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*) :: xstride,ystride,zstride REAL(KIND=4),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzcorrexec( task, x, xstride, y, ystride, z, & & zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*) :: xstride,ystride,zstride COMPLEX(KIND=8),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslccorrexec( task, x, xstride, y, ystride, z, & & zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*) :: xstride,ystride,zstride COMPLEX(KIND=4),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldconvexec1d( task, x, xstride, y, ystride, & & z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: xstride,ystride,zstride REAL(KIND=8),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsconvexec1d( task, x, xstride, y, ystride, & & z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: xstride,ystride,zstride REAL(KIND=4),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzconvexec1d( task, x, xstride, y, ystride, & & z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: xstride,ystride,zstride COMPLEX(KIND=8),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcconvexec1d( task, x, xstride, y, ystride, & & z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: xstride,ystride,zstride COMPLEX(KIND=4),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldcorrexec1d( task, x, xstride, y, ystride, & & z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: xstride,ystride,zstride REAL(KIND=8),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslscorrexec1d( task, x, xstride, y, ystride, & & z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: xstride,ystride,zstride REAL(KIND=4),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzcorrexec1d( task, x, xstride, y, ystride, & & z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: xstride,ystride,zstride COMPLEX(KIND=8),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslccorrexec1d( task, x, xstride, y, ystride, & & z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: xstride,ystride,zstride COMPLEX(KIND=4),DIMENSION(*):: x,y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldconvexecx( task, y, ystride, z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*) :: ystride,zstride REAL(KIND=8),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsconvexecx( task, y, ystride, z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*) :: ystride,zstride REAL(KIND=4),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzconvexecx( task, y, ystride, z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*) :: ystride,zstride COMPLEX(KIND=8),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcconvexecx( task, y, ystride, z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER,DIMENSION(*) :: ystride,zstride COMPLEX(KIND=4),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldcorrexecx( task, y, ystride, z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*) :: ystride,zstride REAL(KIND=8),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslscorrexecx( task, y, ystride, z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*) :: ystride,zstride REAL(KIND=4),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzcorrexecx( task, y, ystride, z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*) :: ystride,zstride COMPLEX(KIND=8),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslccorrexecx( task, y, ystride, z, zstride ) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER,DIMENSION(*) :: ystride,zstride COMPLEX(KIND=4),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldconvexecx1d( task, y, ystride, z, zstride) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: ystride,zstride REAL(KIND=8),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsconvexecx1d( task, y, ystride, z, zstride) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: ystride,zstride REAL(KIND=4),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzconvexecx1d( task, y, ystride, z, zstride) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: ystride,zstride COMPLEX(KIND=8),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslcconvexecx1d( task, y, ystride, z, zstride) USE MKL_VSL_TYPE TYPE(VSL_CONV_TASK) :: task INTEGER :: ystride,zstride COMPLEX(KIND=4),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vsldcorrexecx1d( task, y, ystride, z, zstride) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: ystride,zstride REAL(KIND=8),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslscorrexecx1d( task, y, ystride, z, zstride) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: ystride,zstride REAL(KIND=4),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslzcorrexecx1d( task, y, ystride, z, zstride) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: ystride,zstride COMPLEX(KIND=8),DIMENSION(*):: y,z END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslccorrexecx1d( task, y, ystride, z, zstride) USE MKL_VSL_TYPE TYPE(VSL_CORR_TASK) :: task INTEGER :: ystride,zstride COMPLEX(KIND=4),DIMENSION(*):: y,z END FUNCTION END INTERFACE !++ ! VSL CONTINUOUS DISTRIBUTION GENERATOR FUNCTION INTERFACES. !-- ! Uniform distribution INTERFACE INTEGER FUNCTION vsrnguniform( method, stream, n, r, a, b ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: b END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrnguniform( method, stream, n, r, a, b ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: b END FUNCTION END INTERFACE ! Gaussian distribution INTERFACE INTEGER FUNCTION vsrnggaussian( method, stream, n, r, a, sigma) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: sigma END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrnggaussian( method, stream, n, r, a, sigma) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: sigma END FUNCTION END INTERFACE ! GaussianMV distribution INTERFACE INTEGER FUNCTION vsrnggaussianmv( method, stream, n, r, dimen, & & mstorage, a, t ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER,INTENT(IN) :: dimen REAL(KIND=4),INTENT(OUT) :: r(dimen,n) INTEGER,INTENT(IN) :: mstorage REAL(KIND=4),INTENT(IN) :: a(dimen) REAL(KIND=4),INTENT(IN) :: t(dimen,dimen) END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrnggaussianmv( method, stream, n, r, dimen, & & mstorage, a, t ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) INTEGER,INTENT(IN) :: dimen INTEGER,INTENT(IN) :: mstorage REAL(KIND=8),INTENT(IN) :: a(dimen) REAL(KIND=8),INTENT(IN) :: t(dimen,dimen) END FUNCTION END INTERFACE ! Exponential distribution INTERFACE INTEGER FUNCTION vsrngexponential( method, stream, n, r, a, & & beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrngexponential( method, stream, n, r, a, & & beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE ! Laplace distribution INTERFACE INTEGER FUNCTION vsrnglaplace( method, stream, n, r, a, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrnglaplace( method, stream, n, r, a, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE ! Weibull distribution INTERFACE INTEGER FUNCTION vsrngweibull( method, stream, n, r, alpha, a, & & beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: alpha REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrngweibull( method, stream, n, r, alpha, a, & & beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: alpha REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE ! Cauchy distribution INTERFACE INTEGER FUNCTION vsrngcauchy( method, stream, n, r, a, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrngcauchy( method, stream, n, r, a, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE ! Rayleigh distribution INTERFACE INTEGER FUNCTION vsrngrayleigh( method, stream, n, r, a, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrngrayleigh( method, stream, n, r, a, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE ! Lognormal distribution INTERFACE INTEGER FUNCTION vsrnglognormal( method, stream, n, r, a,sigma, & & b, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: sigma REAL(KIND=4),INTENT(IN) :: b REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrnglognormal( method, stream, n, r, a,sigma, & & b, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: sigma REAL(KIND=8),INTENT(IN) :: b REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE ! Gumbel distribution INTERFACE INTEGER FUNCTION vsrnggumbel( method, stream, n, r, a, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrnggumbel( method, stream, n, r, a, beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE ! Gamma distribution INTERFACE INTEGER FUNCTION vsrnggamma( method, stream, n, r, alpha, a, & & beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: alpha REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrnggamma( method, stream, n, r, alpha, a, & & beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: alpha REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE ! Beta distribution INTERFACE INTEGER FUNCTION vsrngbeta( method, stream, n, r, p, q, a, & & beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=4),INTENT(IN) :: p REAL(KIND=4),INTENT(IN) :: q REAL(KIND=4),INTENT(IN) :: a REAL(KIND=4),INTENT(IN) :: beta END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vdrngbeta( method, stream, n, r, p, q, a, & & beta ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: p REAL(KIND=8),INTENT(IN) :: q REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: beta END FUNCTION END INTERFACE !++ ! VSL DISCRETE DISTRIBUTION GENERATOR FUNCTION INTERFACES. !-- ! Uniform distribution INTERFACE INTEGER FUNCTION virnguniform( method, stream, n, r, a, b ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) INTEGER(KIND=4),INTENT(IN) :: a INTEGER(KIND=4),INTENT(IN) :: b END FUNCTION END INTERFACE ! UniformBits distribution INTERFACE INTEGER FUNCTION virnguniformbits( method, stream, n, r ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) END FUNCTION END INTERFACE ! UniformBits32 distribution INTERFACE INTEGER FUNCTION virnguniformbits32( method, stream, n, r ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) END FUNCTION END INTERFACE ! UniformBits64 distribution INTERFACE INTEGER FUNCTION virnguniformbits64( method, stream, n, r ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=8),INTENT(OUT) :: r(n) END FUNCTION END INTERFACE ! Bernoulli distribution INTERFACE INTEGER FUNCTION virngbernoulli( method, stream, n, r, p ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: p END FUNCTION END INTERFACE ! Geometric distribution INTERFACE INTEGER FUNCTION virnggeometric( method, stream, n, r, p ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: p END FUNCTION END INTERFACE ! Binomial distribution INTERFACE INTEGER FUNCTION virngbinomial(method, stream, n, r, ntrial, p) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) INTEGER(KIND=4),INTENT(IN) :: ntrial REAL(KIND=8),INTENT(IN) :: p END FUNCTION END INTERFACE ! Hypergeometric distribution INTERFACE INTEGER FUNCTION virnghypergeometric( method, stream, n, r, l, & & s, m ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) INTEGER(KIND=4),INTENT(IN) :: l INTEGER(KIND=4),INTENT(IN) :: s INTEGER(KIND=4),INTENT(IN) :: m END FUNCTION END INTERFACE ! Poisson distribution INTERFACE INTEGER FUNCTION virngpoisson( method, stream, n, r, lambda ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: lambda END FUNCTION END INTERFACE ! PoissonV distribution INTERFACE INTEGER FUNCTION virngpoissonv( method, stream, n, r, lambda ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: lambda(n) END FUNCTION END INTERFACE ! Negbinomial distribution INTERFACE INTEGER FUNCTION virngnegbinomial( method, stream, n, r, a, p ) USE MKL_VSL_TYPE INTEGER,INTENT(IN) :: method TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(OUT) :: r(n) REAL(KIND=8),INTENT(IN) :: a REAL(KIND=8),INTENT(IN) :: p END FUNCTION END INTERFACE !++ ! VSL SERVICE FUNCTION INTERFACES. !-- ! NewStream - stream creation/initialization INTERFACE INTEGER FUNCTION vslnewstream( stream, brng, seed ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: brng INTEGER,INTENT(IN) :: seed END FUNCTION END INTERFACE ! NewStreamEx - advanced stream creation/initialization INTERFACE INTEGER FUNCTION vslnewstreamex( stream, brng, n, params ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: brng INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(IN) :: params(n) END FUNCTION END INTERFACE ! INEWABSTRACTSTREAM INTERFACE INTEGER FUNCTION vslinewabstractstream( stream, n, ibuf, ifunc) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE),INTENT(OUT) :: stream INTEGER,INTENT(IN) :: n INTEGER(KIND=4),INTENT(IN) :: ibuf(n) INTEGER(KIND=4),EXTERNAL :: ifunc END FUNCTION END INTERFACE ! DNEWABSTRACTSTREAM INTERFACE INTEGER FUNCTION vsldnewabstractstream( stream, n, dbuf, a, b, & & dfunc ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE),INTENT(OUT) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=8) ,INTENT(IN) :: dbuf(n) REAL(KIND=8) ,INTENT(IN) :: a REAL(KIND=8) ,INTENT(IN) :: b INTEGER(KIND=4),EXTERNAL :: dfunc END FUNCTION END INTERFACE ! SNEWABSTRACTSTREAM INTERFACE INTEGER FUNCTION vslsnewabstractstream( stream, n, sbuf, a, b, & & sfunc ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE),INTENT(OUT) :: stream INTEGER,INTENT(IN) :: n REAL(KIND=4) ,INTENT(IN) :: sbuf(n) REAL(KIND=4) ,INTENT(IN) :: a REAL(KIND=4) ,INTENT(IN) :: b INTEGER(KIND=4),EXTERNAL :: sfunc END FUNCTION END INTERFACE ! DeleteStream - delete stream INTERFACE INTEGER FUNCTION vsldeletestream( stream ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE) :: stream END FUNCTION END INTERFACE ! CopyStream - copy all stream information INTERFACE INTEGER FUNCTION vslcopystream( newstream, srcstream ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE) :: newstream TYPE(VSL_STREAM_STATE) :: srcstream END FUNCTION END INTERFACE ! CopyStreamState - copy stream state only INTERFACE INTEGER FUNCTION vslcopystreamstate( deststream, srcstream ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE) :: deststream TYPE(VSL_STREAM_STATE) :: srcstream END FUNCTION END INTERFACE ! LeapfrogStream - leapfrog method INTERFACE INTEGER FUNCTION vslleapfrogstream( stream, k, nstreams ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE) :: stream INTEGER,INTENT(IN) :: k INTEGER,INTENT(IN) :: nstreams END FUNCTION END INTERFACE ! SkipAheadStream - skip-ahead method INTERFACE INTEGER FUNCTION vslskipaheadstream( stream, nskip ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE) :: stream INTEGER(KIND=8),INTENT(IN) :: nskip END FUNCTION END INTERFACE ! GetBrngProperties - get BRNG properties INTERFACE INTEGER FUNCTION vslgetbrngproperties( brng, properties ) USE MKL_VSL_TYPE INTEGER(KIND=4),INTENT(IN) :: brng TYPE(VSL_BRNG_PROPERTIES),INTENT(OUT) :: properties END FUNCTION END INTERFACE ! GetNumRegBrngs - get number of registered BRNGs INTERFACE INTEGER FUNCTION vslgetnumregbrngs( ) END FUNCTION END INTERFACE ! GetStreamStateBrng - get BRNG associated with given stream INTERFACE INTEGER FUNCTION vslgetstreamstatebrng( stream ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE) :: stream END FUNCTION END INTERFACE ! RegisterBrng - register new BRNG INTERFACE INTEGER FUNCTION vslregisterbrng( properties ) USE MKL_VSL_TYPE TYPE(VSL_BRNG_PROPERTIES) :: properties END FUNCTION END INTERFACE ! SaveStreamF - save stream to file INTERFACE INTEGER FUNCTION vslsavestreamf( stream, fname ) USE MKL_VSL_TYPE CHARACTER(*) :: fname TYPE(VSL_STREAM_STATE) :: stream END FUNCTION END INTERFACE ! LoadStreamF - save stream to file INTERFACE INTEGER FUNCTION vslloadstreamf( stream, fname ) USE MKL_VSL_TYPE CHARACTER(*) :: fname TYPE(VSL_STREAM_STATE) :: stream END FUNCTION END INTERFACE ! SaveStreamM - save stream to memory INTERFACE INTEGER FUNCTION vslsavestreamm( stream, memptr ) USE MKL_VSL_TYPE INTEGER(KIND=1),DIMENSION(*),INTENT(OUT)::memptr TYPE(VSL_STREAM_STATE),INTENT(IN) :: stream END FUNCTION END INTERFACE ! LoadStreamM - load stream from memory INTERFACE INTEGER FUNCTION vslloadstreamm( stream, memptr ) USE MKL_VSL_TYPE INTEGER(KIND=1),DIMENSION(*),INTENT(IN)::memptr TYPE(VSL_STREAM_STATE),INTENT(OUT) ::stream END FUNCTION END INTERFACE ! GetStreamSize - get size of random stream INTERFACE INTEGER FUNCTION vslgetstreamsize( stream ) USE MKL_VSL_TYPE TYPE(VSL_STREAM_STATE),INTENT(IN) :: stream END FUNCTION END INTERFACE !++ ! SUMMARARY STATTISTICS LIBARY ROUTINES !-- ! Task constructors INTERFACE INTEGER FUNCTION vsldssnewtask(task,p,n,x_storage,x,w,indices) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: p INTEGER,INTENT(IN) :: n INTEGER,INTENT(IN) :: x_storage REAL(KIND=8),INTENT(IN) :: x(n,p) REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL:: w INTEGER,DIMENSION(*),INTENT(IN),OPTIONAL:: indices END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsssnewtask(task,p,n,x_storage,x,w,indices) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: p INTEGER,INTENT(IN) :: n INTEGER,INTENT(IN) :: x_storage REAL(KIND=4),INTENT(IN) :: x(n,p) REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL:: w INTEGER,DIMENSION(*),INTENT(IN),OPTIONAL:: indices END FUNCTION END INTERFACE ! Task editors ! Editor to modify a task parameter INTERFACE INTEGER FUNCTION vsldssedittask(task,parameter,par_addr) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: parameter REAL(KIND=8),DIMENSION(*),INTENT(IN) :: par_addr END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslsssedittask(task,parameter,par_addr) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: parameter REAL(KIND=4),DIMENSION(*),INTENT(IN) :: par_addr END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslissedittask(task,parameter,par_addr) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: parameter INTEGER,INTENT(IN) :: par_addr END FUNCTION END INTERFACE ! Task specific editors ! Editors to modify moments related parameters INTERFACE INTEGER FUNCTION vsldsseditmoments(task, mean, r2m, r3m, r4m, & & c2m, c3m, c4m) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=8),DIMENSION(*),INTENT(IN) :: mean REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: r2m REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: r3m REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: r4m REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: c2m REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: c3m REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: c4m END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditmoments(task, mean, r2m, r3m, r4m, & & c2m, c3m, c4m) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=4),DIMENSION(*),INTENT(IN) :: mean REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: r2m REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: r3m REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: r4m REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: c2m REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: c3m REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: c4m END FUNCTION END INTERFACE ! Editors to modify sums related parameters INTERFACE INTEGER FUNCTION vsldsseditsums(task, sum, r2s, r3s, r4s, & & c2s, c3s, c4s) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=8),DIMENSION(*),INTENT(IN) :: sum REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: r2s REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: r3s REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: r4s REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: c2s REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: c3s REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: c4s END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditsums(task, sum, r2s, r3s, r4s, & & c2s, c3s, c4s) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=4),DIMENSION(*),INTENT(IN) :: sum REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: r2s REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: r3s REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: r4s REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: c2s REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: c3s REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: c4s END FUNCTION END INTERFACE ! Editors to modify variance-covariance/correlation matrix ! related parameters INTERFACE INTEGER FUNCTION vsldsseditcovcor(task, mean,cov, cov_storage, & & cor, cor_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=8),DIMENSION(*),INTENT(IN) :: mean REAL(KIND=8),DIMENSION(*),INTENT(IN), OPTIONAL :: cov INTEGER,INTENT(IN), OPTIONAL :: cov_storage REAL(KIND=8),DIMENSION(*),INTENT(IN), OPTIONAL :: cor INTEGER,INTENT(IN), OPTIONAL :: cor_storage END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditcovcor(task, mean,cov, cov_storage, & & cor, cor_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=4),DIMENSION(*),INTENT(IN) :: mean REAL(KIND=4),DIMENSION(*),INTENT(IN), OPTIONAL :: cov INTEGER,INTENT(IN), OPTIONAL :: cov_storage REAL(KIND=4),DIMENSION(*),INTENT(IN), OPTIONAL :: cor INTEGER,INTENT(IN), OPTIONAL :: cor_storage END FUNCTION END INTERFACE ! Editors to modify cross-product matrix ! related parameters INTERFACE INTEGER FUNCTION vsldsseditcp(task, mean, sum, & & cp, cp_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=8),DIMENSION(*),INTENT(IN) :: mean REAL(KIND=8),DIMENSION(*),INTENT(IN), OPTIONAL :: sum REAL(KIND=8),DIMENSION(*),INTENT(IN) :: cp INTEGER,INTENT(IN) :: cp_storage END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditcp(task, mean, sum, & & cp, cp_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=4),DIMENSION(*),INTENT(IN) :: mean REAL(KIND=4),DIMENSION(*),INTENT(IN), OPTIONAL :: sum REAL(KIND=4),DIMENSION(*),INTENT(IN) :: cp INTEGER,INTENT(IN) :: cp_storage END FUNCTION END INTERFACE ! Editors to modify partial variance-covariance matrix ! related parameters INTERFACE INTEGER FUNCTION vsldsseditpartialcovcor(task, p_idx_array, & & cov, cov_storage, cor, cor_storage, & & p_cov, p_cov_storage, p_cor, p_cor_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,DIMENSION(*),INTENT(IN) :: p_idx_array REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: cov INTEGER,INTENT(IN),OPTIONAL :: cov_storage REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: cor INTEGER,INTENT(IN),OPTIONAL :: cor_storage REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: p_cov INTEGER,INTENT(IN),OPTIONAL :: p_cov_storage REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: p_cor INTEGER,INTENT(IN),OPTIONAL :: p_cor_storage END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditpartialcovcor(task, p_idx_array, & & cov, cov_storage, cor, cor_storage, & & p_cov, p_cov_storage, p_cor, p_cor_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,DIMENSION(*),INTENT(IN) :: p_idx_array REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: cov INTEGER,INTENT(IN),OPTIONAL :: cov_storage REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: cor INTEGER,INTENT(IN),OPTIONAL :: cor_storage REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: p_cov INTEGER,INTENT(IN),OPTIONAL :: p_cov_storage REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: p_cor INTEGER,INTENT(IN),OPTIONAL :: p_cor_storage END FUNCTION END INTERFACE ! Editors to modify quantiles related parameters INTERFACE INTEGER FUNCTION vsldsseditquantiles(task, quant_order_n, & & quant_order,quants, & & order_stats, order_stats_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN),OPTIONAL :: quant_order_n REAL(KIND=8),INTENT(IN),dimension(*),OPTIONAL::quant_order REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL::quants REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: & & order_stats INTEGER,INTENT(IN),OPTIONAL :: order_stats_storage END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditquantiles(task, quant_order_n, & & quant_order,quants, & & order_stats, order_stats_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN),OPTIONAL :: quant_order_n REAL(KIND=4),INTENT(IN),dimension(*),OPTIONAL::quant_order REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL::quants REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: & & order_stats INTEGER,INTENT(IN),OPTIONAL :: order_stats_storage END FUNCTION END INTERFACE ! Editors to modify stream data quantiles related parameters INTERFACE INTEGER FUNCTION vsldsseditstreamquantiles(task, & & quant_order_n, quant_order, quants, nparams, params) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: quant_order_n REAL(KIND=8),INTENT(IN),dimension(*) :: quant_order REAL(KIND=8),DIMENSION(*),INTENT(IN) :: quants INTEGER,INTENT(IN) :: nparams REAL(KIND=8),INTENT(IN), DIMENSION(*) :: params END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditstreamquantiles(task, & & quant_order_n, quant_order, quants, nparams, params) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: quant_order_n REAL(KIND=4),INTENT(IN),dimension(*) :: quant_order REAL(KIND=4),DIMENSION(*),INTENT(IN) :: quants INTEGER,INTENT(IN) :: nparams REAL(KIND=4),INTENT(IN), DIMENSION(*) :: params END FUNCTION END INTERFACE ! Editors to modify pooled/group variance-covariance matrix ! related parameters INTERFACE INTEGER FUNCTION vsldsseditpooledcovariance(task, grp_indices, & & pld_mean, pld_cov, grp_cov_indices, grp_means, grp_cov) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,DIMENSION(*),INTENT(IN) :: grp_indices REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: pld_mean REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: pld_cov INTEGER,DIMENSION(*),INTENT(IN),OPTIONAL ::grp_cov_indices REAL(KIND=8),DIMENSION(*),INTENT(IN),OPTIONAL :: grp_means REAL(KIND=8),DIMENSION(*),INTENT(IN), OPTIONAL :: grp_cov END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditpooledcovariance(task, grp_indices, & & pld_mean, pld_cov, grp_cov_indices, grp_means, grp_cov) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,DIMENSION(*),INTENT(IN) :: grp_indices REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: pld_mean REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: pld_cov INTEGER,DIMENSION(*),INTENT(IN),OPTIONAL ::grp_cov_indices REAL(KIND=4),DIMENSION(*),INTENT(IN),OPTIONAL :: grp_means REAL(KIND=4),DIMENSION(*),INTENT(IN), OPTIONAL :: grp_cov END FUNCTION END INTERFACE ! Editors to modify robust variance-covariance matrix ! related parameters INTERFACE INTEGER FUNCTION vsldsseditrobustcovariance(task,rcov_storage, & & nparams, params,rmean, rcov) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: rcov_storage INTEGER,INTENT(IN) :: nparams REAL(KIND=8),INTENT(IN) :: params(nparams) REAL(KIND=8),DIMENSION(*),INTENT(IN) :: rmean REAL(KIND=8),DIMENSION(*),INTENT(IN) :: rcov END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditrobustcovariance(task,rcov_storage, & & nparams, params,rmean, rcov) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: rcov_storage INTEGER,INTENT(IN) :: nparams REAL(KIND=4),INTENT(IN) :: params(nparams) REAL(KIND=4),DIMENSION(*),INTENT(IN) :: rmean REAL(KIND=4),DIMENSION(*),INTENT(IN) :: rcov END FUNCTION END INTERFACE ! Editors to modify outliers detection parameters INTERFACE INTEGER FUNCTION vsldsseditoutliersdetection(task, & & nparams, params, w) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: nparams REAL(KIND=8),DIMENSION(*),INTENT(IN) :: params(nparams) REAL(KIND=8),DIMENSION(*),INTENT(IN) :: w END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditoutliersdetection(task, & & nparams, params, w) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: nparams REAL(KIND=4),DIMENSION(*),INTENT(IN) :: params(nparams) REAL(KIND=4),DIMENSION(*),INTENT(IN) :: w END FUNCTION END INTERFACE ! Editors to modify missing values parameters INTERFACE INTEGER FUNCTION vsldsseditmissingvalues(task, nparams, params, & & init_estimates_n, init_estimates, prior_n, prior, & & simul_missing_vals_n,simul_missing_vals, & & estimates_n, estimates) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: nparams REAL(KIND=8),INTENT(IN) :: params(nparams) INTEGER,INTENT(IN),OPTIONAL :: init_estimates_n REAL(KIND=8),INTENT(IN), DIMENSION(*),OPTIONAL:: & & init_estimates INTEGER,INTENT(IN),OPTIONAL :: prior_n REAL(KIND=8),INTENT(IN),DIMENSION(*),OPTIONAL :: prior INTEGER,INTENT(IN),OPTIONAL :: simul_missing_vals_n REAL(KIND=8),INTENT(IN),DIMENSION(*),OPTIONAL :: & & simul_missing_vals INTEGER,INTENT(IN),OPTIONAL :: estimates_n REAL(KIND=8),INTENT(IN), DIMENSION(*), OPTIONAL :: & & estimates END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditmissingvalues(task, nparams, params, & & init_estimates_n, init_estimates, prior_n, prior, & & simul_missing_vals_n,simul_missing_vals, & & estimates_n, estimates) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER,INTENT(IN) :: nparams REAL(KIND=4),INTENT(IN) :: params(nparams) INTEGER,INTENT(IN),OPTIONAL :: init_estimates_n REAL(KIND=4),INTENT(IN), DIMENSION(*),OPTIONAL:: & & init_estimates INTEGER,INTENT(IN),OPTIONAL :: prior_n REAL(KIND=4),INTENT(IN),DIMENSION(*),OPTIONAL :: prior INTEGER,INTENT(IN),OPTIONAL :: simul_missing_vals_n REAL(KIND=4),INTENT(IN),DIMENSION(*),OPTIONAL :: & & simul_missing_vals INTEGER,INTENT(IN),OPTIONAL :: estimates_n REAL(KIND=4),INTENT(IN), DIMENSION(*), OPTIONAL :: & & estimates END FUNCTION END INTERFACE ! Editors to modify matrix parameterization ! related parameters INTERFACE INTEGER FUNCTION vsldsseditcorparameterization (task, & & cor, cor_storage, pcor, pcor_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=8),DIMENSION(*),INTENT(IN) :: cor INTEGER,INTENT(IN) :: cor_storage REAL(KIND=8),DIMENSION(*),INTENT(IN) :: pcor INTEGER,INTENT(IN) :: pcor_storage END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssseditcorparameterization (task, & & cor, cor_storage, pcor, pcor_storage) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task REAL(KIND=4),DIMENSION(*),INTENT(IN) :: cor INTEGER,INTENT(IN) :: cor_storage REAL(KIND=4),DIMENSION(*),INTENT(IN) :: pcor INTEGER,INTENT(IN) :: pcor_storage END FUNCTION END INTERFACE ! Compute routines INTERFACE INTEGER FUNCTION vsldsscompute(task, estimates, method) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER(KIND=8),INTENT(IN) :: estimates INTEGER,INTENT(IN) :: method END FUNCTION END INTERFACE INTERFACE INTEGER FUNCTION vslssscompute(task, estimates, method) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task INTEGER(KIND=8),INTENT(IN) :: estimates INTEGER,INTENT(IN) :: method END FUNCTION END INTERFACE ! Task destructor INTERFACE INTEGER FUNCTION vslssdeletetask(task) USE MKL_VSL_TYPE TYPE(VSL_SS_TASK) :: task END FUNCTION END INTERFACE END MODULE MKL_VSL
21,284
https://github.com/NghiaTranUIT/eSales/blob/master/eSales/FeTuoiNoView.m
Github Open Source
Open Source
MIT, Apache-2.0, PHP-3.01
2,013
eSales
NghiaTranUIT
Objective-C
Code
415
2,000
// // FeTuoiNoView.m // eSales // // Created by Nghia Tran on 9/10/13. // Copyright (c) 2013 Fe. All rights reserved. // #import "FeTuoiNoView.h" #import "FeTuoiNoCell.h" #import "FeDatabaseManager.h" @interface FeTuoiNoView() @property (strong, nonatomic) NSMutableArray *arrTuoiNo; -(void) setupDefaultView; @end @implementation FeTuoiNoView @synthesize txbNoHienTai = _txbNoHienTai, txbTongChuaToiHan = _txbTongChuaToiHan, txbTenKH = _txbTenKH, txbTongQH15Ngay = _txbTongQH15Ngay, txbTongQH7Ngay = _txbTongQH7Ngay, tableView = _tableView, arrTuoiNo = _arrTuoiNo, tbxTongQHTren15Ngay = _tbxTongQHTren15Ngay; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code } return self; } -(void) awakeFromNib { [self setupDefaultView]; UIImageView *bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background"]]; bg.frame = self.frame; bg.contentMode = UIViewContentModeScaleAspectFill; self.clipsToBounds = YES; [self insertSubview:bg atIndex:0]; } -(void) setupDefaultView { UINib *nib = [UINib nibWithNibName:@"FeTuoiNoCell" bundle:[NSBundle mainBundle]]; [_tableView registerNib:nib forCellReuseIdentifier:@"FeTuoiNoCell"]; NSUserDefaults *user = [NSUserDefaults standardUserDefaults]; NSDictionary *activeCust = [user objectForKey:@"ActiveCustomer"]; NSString *custID = [activeCust objectForKey:@"CustID"]; // Database FeDatabaseManager *db =[FeDatabaseManager sharedInstance]; _arrTuoiNo = [db arrTuoiNoFromDatabaseWithCustomerID:custID]; // Set some Txb CGFloat tongChuaToihan = 0; CGFloat tongQH7 = 0; CGFloat tongQH15 = 0; CGFloat tongQHTran15 = 0; for (NSDictionary *dict in _arrTuoiNo) { NSNumber *ChuaToiHan = [dict objectForKey:@"DueYet"]; NSNumber *QH7 = [dict objectForKey:@"Due7"]; NSNumber *QH15 = [dict objectForKey:@"Due15"]; NSNumber *QHTren15 = [dict objectForKey:@"DueOver15"]; tongChuaToihan += ChuaToiHan.floatValue; tongQH7 += QH7.floatValue; tongQH15 +=QH15.floatValue; tongQHTran15 +=QHTren15.floatValue; } NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle]; /* _txbTongChuaToiHan.text = [NSString stringWithFormat:@"%.2f",tongChuaToihan]; _txbTongQH7Ngay.text = [NSString stringWithFormat:@"%.2f",tongQH7]; _txbTongQH15Ngay.text = [NSString stringWithFormat:@"%.2f",tongQH15]; _tbxTongQHTren15Ngay.text = [NSString stringWithFormat:@"%.2f",tongQHTran15]; */ _txbTongChuaToiHan.text = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tongChuaToihan]]; _txbTongQH7Ngay.text = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tongQH7]]; _txbTongQH15Ngay.text = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tongQH15]]; _tbxTongQHTren15Ngay.text = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tongQHTran15]]; // Set title _txbTenKH.text = [activeCust objectForKey:@"CustName"]; _txbNoHienTai.text = @"0"; } -(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _arrTuoiNo.count; } -(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *IDCell = @"FeTuoiNoCell"; FeTuoiNoCell *cell = [_tableView dequeueReusableCellWithIdentifier:IDCell forIndexPath:indexPath]; NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle]; NSDictionary *dict = [_arrTuoiNo objectAtIndex:indexPath.row]; NSNumber *ChuaToiHan = [dict objectForKey:@"DueYet"]; NSNumber *HanMuc = [dict objectForKey:@"CreditLimit"]; NSNumber *QH7 = [dict objectForKey:@"Due7"]; NSNumber *QH15 = [dict objectForKey:@"Due15"]; NSNumber *QHTren15 = [dict objectForKey:@"DueOver15"]; /* cell.lblChuaToiHan.text = [NSString stringWithFormat:@"%.2f",ChuaToiHan.doubleValue]; cell.lblHanMuc.text = [NSString stringWithFormat:@"%.2f",HanMuc.doubleValue]; cell.lblHD.text = [dict objectForKey:@"OrderNumber"]; cell.lblQH15Ngay.text = [NSString stringWithFormat:@"%.2f",QH15.doubleValue]; cell.lblQH7Ngay.text = [NSString stringWithFormat:@"%2.f",QH7.doubleValue]; cell.lblQHTren15Ngay.text = [NSString stringWithFormat:@"%.2f",QHTren15.doubleValue]; */ cell.lblChuaToiHan.text = [numberFormatter stringFromNumber:ChuaToiHan]; cell.lblHanMuc.text = [numberFormatter stringFromNumber:HanMuc]; cell.lblHD.text = [dict objectForKey:@"OrderNumber"]; cell.lblQH15Ngay.text = [numberFormatter stringFromNumber:QH15]; cell.lblQH7Ngay.text = [numberFormatter stringFromNumber:QH7]; cell.lblQHTren15Ngay.text = [numberFormatter stringFromNumber:QHTren15]; // color Cell if (QHTren15.integerValue != 0) { cell.contentView.backgroundColor = [UIColor redColor]; } else { cell.contentView.backgroundColor = [UIColor whiteColor]; } return cell; } -(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 44; } @end
39,312
https://github.com/cirocosta/buildkit/blob/master/source/containerimage/pull.go
Github Open Source
Open Source
Apache-2.0
2,022
buildkit
cirocosta
Go
Code
719
2,373
package containerimage import ( "context" "encoding/json" "runtime" "github.com/containerd/containerd/content" "github.com/containerd/containerd/diff" "github.com/containerd/containerd/images" "github.com/containerd/containerd/leases" "github.com/containerd/containerd/platforms" "github.com/docker/distribution/reference" "github.com/moby/buildkit/cache" gw "github.com/moby/buildkit/frontend/gateway/client" "github.com/moby/buildkit/session" "github.com/moby/buildkit/snapshot" "github.com/moby/buildkit/source" "github.com/moby/buildkit/util/flightcontrol" "github.com/moby/buildkit/util/imageutil" "github.com/moby/buildkit/util/pull" "github.com/moby/buildkit/util/resolver" "github.com/moby/buildkit/util/winlayers" digest "github.com/opencontainers/go-digest" "github.com/opencontainers/image-spec/identity" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" ) // TODO: break apart containerd specifics like contentstore so the resolver // code can be used with any implementation type SourceOpt struct { Snapshotter snapshot.Snapshotter ContentStore content.Store Applier diff.Applier CacheAccessor cache.Accessor ImageStore images.Store // optional ResolverOpt resolver.ResolveOptionsFunc LeaseManager leases.Manager } type imageSource struct { SourceOpt g flightcontrol.Group } func NewSource(opt SourceOpt) (source.Source, error) { is := &imageSource{ SourceOpt: opt, } return is, nil } func (is *imageSource) ID() string { return source.DockerImageScheme } func (is *imageSource) ResolveImageConfig(ctx context.Context, ref string, opt gw.ResolveImageConfigOpt, sm *session.Manager) (digest.Digest, []byte, error) { type t struct { dgst digest.Digest dt []byte } key := ref if platform := opt.Platform; platform != nil { key += platforms.Format(*platform) } rm, err := source.ParseImageResolveMode(opt.ResolveMode) if err != nil { return "", nil, err } res, err := is.g.Do(ctx, key, func(ctx context.Context) (interface{}, error) { dgst, dt, err := imageutil.Config(ctx, ref, pull.NewResolver(ctx, is.ResolverOpt, sm, is.ImageStore, rm, ref), is.ContentStore, is.LeaseManager, opt.Platform) if err != nil { return nil, err } return &t{dgst: dgst, dt: dt}, nil }) if err != nil { return "", nil, err } typed := res.(*t) return typed.dgst, typed.dt, nil } func (is *imageSource) Resolve(ctx context.Context, id source.Identifier, sm *session.Manager) (source.SourceInstance, error) { imageIdentifier, ok := id.(*source.ImageIdentifier) if !ok { return nil, errors.Errorf("invalid image identifier %v", id) } platform := platforms.DefaultSpec() if imageIdentifier.Platform != nil { platform = *imageIdentifier.Platform } pullerUtil := &pull.Puller{ Snapshotter: is.Snapshotter, ContentStore: is.ContentStore, Applier: is.Applier, Src: imageIdentifier.Reference, Resolver: pull.NewResolver(ctx, is.ResolverOpt, sm, is.ImageStore, imageIdentifier.ResolveMode, imageIdentifier.Reference.String()), Platform: &platform, LeaseManager: is.LeaseManager, } p := &puller{ CacheAccessor: is.CacheAccessor, Puller: pullerUtil, Platform: platform, id: imageIdentifier, } return p, nil } type puller struct { CacheAccessor cache.Accessor Platform specs.Platform id *source.ImageIdentifier *pull.Puller } func mainManifestKey(ctx context.Context, desc specs.Descriptor, platform specs.Platform) (digest.Digest, error) { dt, err := json.Marshal(struct { Digest digest.Digest OS string Arch string Variant string `json:",omitempty"` }{ Digest: desc.Digest, OS: platform.OS, Arch: platform.Architecture, Variant: platform.Variant, }) if err != nil { return "", err } return digest.FromBytes(dt), nil } func (p *puller) CacheKey(ctx context.Context, index int) (string, bool, error) { _, desc, err := p.Puller.Resolve(ctx) if err != nil { return "", false, err } if index == 0 || desc.Digest == "" { k, err := mainManifestKey(ctx, desc, p.Platform) if err != nil { return "", false, err } return k.String(), false, nil } ref, err := reference.ParseNormalizedNamed(p.Src.String()) if err != nil { return "", false, err } ref, err = reference.WithDigest(ref, desc.Digest) if err != nil { return "", false, nil } _, dt, err := imageutil.Config(ctx, ref.String(), p.Resolver, p.ContentStore, p.LeaseManager, &p.Platform) if err != nil { return "", false, err } k := cacheKeyFromConfig(dt).String() if k == "" { k, err := mainManifestKey(ctx, desc, p.Platform) if err != nil { return "", false, err } return k.String(), true, nil } return k, true, nil } func (p *puller) Snapshot(ctx context.Context) (cache.ImmutableRef, error) { layerNeedsTypeWindows := false if platform := p.Puller.Platform; platform != nil { if platform.OS == "windows" && runtime.GOOS != "windows" { ctx = winlayers.UseWindowsLayerMode(ctx) layerNeedsTypeWindows = true } } // workaround for gcr, authentication not supported on blob endpoints pull.EnsureManifestRequested(ctx, p.Puller.Resolver, p.Puller.Src.String()) pulled, err := p.Puller.Pull(ctx) if err != nil { return nil, err } if pulled.ChainID == "" { return nil, nil } ref, err := p.CacheAccessor.GetFromSnapshotter(ctx, string(pulled.ChainID), cache.WithDescription("pulled from "+pulled.Ref)) if err != nil { return nil, err } if layerNeedsTypeWindows && ref != nil { if err := markRefLayerTypeWindows(ref); err != nil { ref.Release(context.TODO()) return nil, err } } if p.id.RecordType != "" && cache.GetRecordType(ref) == "" { if err := cache.SetRecordType(ref, p.id.RecordType); err != nil { ref.Release(context.TODO()) return nil, err } } return ref, nil } func markRefLayerTypeWindows(ref cache.ImmutableRef) error { if parent := ref.Parent(); parent != nil { defer parent.Release(context.TODO()) if err := markRefLayerTypeWindows(parent); err != nil { return err } } return cache.SetLayerType(ref, "windows") } // cacheKeyFromConfig returns a stable digest from image config. If image config // is a known oci image we will use chainID of layers. func cacheKeyFromConfig(dt []byte) digest.Digest { var img specs.Image err := json.Unmarshal(dt, &img) if err != nil { return digest.FromBytes(dt) } if img.RootFS.Type != "layers" || len(img.RootFS.DiffIDs) == 0 { return "" } return identity.ChainID(img.RootFS.DiffIDs) }
26,676
https://github.com/cool-dude/leetcode/blob/master/src/OO_Design/ProdCons.java
Github Open Source
Open Source
MIT
null
leetcode
cool-dude
Java
Code
81
386
import java.util.*; import java.io.*; public class ProdCons{ protected LinkedList lst=new LinekdList(); protected int MAX=10; protected boolean done=false; class Producer extends Thread{ public void run(){ while(true){ synchornized(lst){ while(lst.size()==MAX) //queue full try{ System.out.println("Producer WAITING"); lst.wait(); } catch(InterruptedException ex){ System.out.println("Producer INTERRUPTED"); } lst.addFirst(jstProduced); lst.notifyAll(); System.out.println("Produced 1;List size now" + lst.size()); } } } } class Consumer extends Thread{ public void run(){ while(true){ Object obj=null; synchronize(lst){ while(lst.size()==0){ try{ System.out.println("CONSUMER WAITING"); lst.wait(); } catch(InterruptedException ex){ System.out.println("CONSUMER INTERRUPTED"); } } obj=lst.removeLast(); lst.notifyAll(); } } } } }
50,856
https://github.com/scoriiu/0x-starter-project/blob/master/src/scenarios/match_orders.ts
Github Open Source
Open Source
Apache-2.0
2,019
0x-starter-project
scoriiu
TypeScript
Code
680
2,159
import { assetDataUtils, BigNumber, ContractWrappers, generatePseudoRandomSalt, Order, orderHashUtils, signatureUtils, } from '0x.js'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { NETWORK_CONFIGS, TX_DEFAULTS } from '../configs'; import { DECIMALS, NULL_ADDRESS, ZERO } from '../constants'; import { contractAddresses } from '../contracts'; import { PrintUtils } from '../print_utils'; import { providerEngine } from '../provider_engine'; import { getRandomFutureDateInSeconds } from '../utils'; /** * In this scenario, the leftMaker creates and signs an order (leftOrder) for selling ZRX for WETH. * The rightMaker has a matched (or mirrored) order (rightOrder) of WETH for ZRX. * The matcher submits both orders and the 0x Exchange contract calling matchOrders. * The matcher pays taker fees on both orders, the leftMaker pays the leftOrder maker fee * and the rightMaker pays the rightOrder maker fee. * Any spread in the two orders is sent to the sender. */ export async function scenarioAsync(): Promise<void> { PrintUtils.printScenario('Match Orders'); // Initialize the ContractWrappers, this provides helper functions around calling // 0x contracts as well as ERC20/ERC721 token contracts on the blockchain const contractWrappers = new ContractWrappers(providerEngine, { networkId: NETWORK_CONFIGS.networkId }); // Initialize the Web3Wrapper, this provides helper functions around fetching // account information, balances, general contract logs const web3Wrapper = new Web3Wrapper(providerEngine); const [leftMaker, rightMaker, matcherAccount] = await web3Wrapper.getAvailableAddressesAsync(); const zrxTokenAddress = contractAddresses.zrxToken; const etherTokenAddress = contractAddresses.etherToken; const printUtils = new PrintUtils( web3Wrapper, contractWrappers, { leftMaker, rightMaker, matcherAccount }, { WETH: etherTokenAddress, ZRX: zrxTokenAddress }, ); printUtils.printAccounts(); // the amount the maker is selling of maker asset const makerAssetAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(10), DECIMALS); // the amount the maker wants of taker asset const takerAssetAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(0.4), DECIMALS); // 0x v2 uses hex encoded asset data strings to encode all the information needed to identify an asset const makerAssetData = assetDataUtils.encodeERC20AssetData(zrxTokenAddress); const takerAssetData = assetDataUtils.encodeERC20AssetData(etherTokenAddress); let txHash; let txReceipt; // Allow the 0x ERC20 Proxy to move ZRX on behalf of makerAccount const leftMakerZRXApprovalTxHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( zrxTokenAddress, leftMaker, ); await printUtils.awaitTransactionMinedSpinnerAsync('Left Maker ZRX Approval', leftMakerZRXApprovalTxHash); // Approve the ERC20 Proxy to move ZRX for rightMaker const rightMakerZRXApprovalTxHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( zrxTokenAddress, rightMaker, ); await printUtils.awaitTransactionMinedSpinnerAsync('Right Maker ZRX Approval', rightMakerZRXApprovalTxHash); // Approve the ERC20 Proxy to move ZRX for matcherAccount const matcherZRXApprovalTxHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( zrxTokenAddress, matcherAccount, ); await printUtils.awaitTransactionMinedSpinnerAsync('Matcher ZRX Approval', matcherZRXApprovalTxHash); // Approve the ERC20 Proxy to move WETH for rightMaker const rightMakerWETHApprovalTxHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync( etherTokenAddress, rightMaker, ); await printUtils.awaitTransactionMinedSpinnerAsync('Right Maker WETH Approval', rightMakerZRXApprovalTxHash); // Convert ETH into WETH for taker by depositing ETH into the WETH contract const rightMakerWETHDepositTxHash = await contractWrappers.etherToken.depositAsync( etherTokenAddress, takerAssetAmount, rightMaker, ); await printUtils.awaitTransactionMinedSpinnerAsync('Right Maker WETH Deposit', rightMakerWETHDepositTxHash); PrintUtils.printData('Setup', [ ['Left Maker ZRX Approval', leftMakerZRXApprovalTxHash], ['Right Maker ZRX Approval', rightMakerZRXApprovalTxHash], ['Matcher Maker ZRX Approval', matcherZRXApprovalTxHash], ['Right Maker WETH Approval', rightMakerWETHApprovalTxHash], ['RIght Maker WETH Deposit', rightMakerWETHDepositTxHash], ]); // Set up the Order and fill it const randomExpiration = getRandomFutureDateInSeconds(); const exchangeAddress = contractAddresses.exchange; // Create the order const leftOrder: Order = { exchangeAddress, makerAddress: leftMaker, takerAddress: NULL_ADDRESS, senderAddress: NULL_ADDRESS, feeRecipientAddress: NULL_ADDRESS, expirationTimeSeconds: randomExpiration, salt: generatePseudoRandomSalt(), makerAssetAmount, takerAssetAmount, makerAssetData, takerAssetData, makerFee: ZERO, takerFee: ZERO, }; PrintUtils.printData('Left Order', Object.entries(leftOrder)); // Create the matched order const rightOrderTakerAssetAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(0.2), DECIMALS); const rightOrder: Order = { exchangeAddress, makerAddress: rightMaker, takerAddress: NULL_ADDRESS, senderAddress: NULL_ADDRESS, feeRecipientAddress: NULL_ADDRESS, expirationTimeSeconds: randomExpiration, salt: generatePseudoRandomSalt(), makerAssetAmount: leftOrder.takerAssetAmount, takerAssetAmount: rightOrderTakerAssetAmount, makerAssetData: leftOrder.takerAssetData, takerAssetData: leftOrder.makerAssetData, makerFee: ZERO, takerFee: ZERO, }; PrintUtils.printData('Right Order', Object.entries(rightOrder)); // Generate the order hash and sign it const leftOrderHashHex = orderHashUtils.getOrderHashHex(leftOrder); const leftOrderSignature = await signatureUtils.ecSignHashAsync(providerEngine, leftOrderHashHex, leftMaker); const leftSignedOrder = { ...leftOrder, signature: leftOrderSignature }; // Generate the order hash and sign it const rightOrderHashHex = orderHashUtils.getOrderHashHex(rightOrder); const rightOrderSignature = await signatureUtils.ecSignHashAsync(providerEngine, rightOrderHashHex, rightMaker); const rightSignedOrder = { ...rightOrder, signature: rightOrderSignature }; // Print out the Balances and Allowances await printUtils.fetchAndPrintContractAllowancesAsync(); await printUtils.fetchAndPrintContractBalancesAsync(); // Match the orders via 0x Exchange txHash = await contractWrappers.exchange.matchOrdersAsync(leftSignedOrder, rightSignedOrder, matcherAccount, { gasLimit: TX_DEFAULTS.gas, }); txReceipt = await printUtils.awaitTransactionMinedSpinnerAsync('matchOrders', txHash); printUtils.printTransaction('matchOrders', txReceipt, [ ['left orderHash', leftOrderHashHex], ['right orderHash', rightOrderHashHex], ]); // Print the Balances await printUtils.fetchAndPrintContractBalancesAsync(); // Stop the Provider Engine providerEngine.stop(); } void (async () => { try { if (!module.parent) { await scenarioAsync(); } } catch (e) { console.log(e); providerEngine.stop(); process.exit(1); } })();
11,419
https://github.com/BrPedro-dev/WebCrud/blob/master/src/main/resources/static/index.js
Github Open Source
Open Source
MIT
null
WebCrud
BrPedro-dev
JavaScript
Code
358
1,146
$(document).ready(function () { saveButton() reset() research() resetcampus() clickdelete() }) function saveButton() { $("#save").click(function () { var id = $("#userID").val() var name = $("#name").val() var age = $("#age").val() if (validAge(parseInt(age) && validName(name))) { $("#spanage").text("") ajaxSave(id, name, parseInt(age)) } else { $("#spanage").text("Invalid age") } }) } function validAge(Age) { if (Age >= 0 && Age <= 110) { return true } return false } function validName(Name) { if (Name != null) { return true } return false } function ajaxSave(id, name, age) { $.ajax({ url: "save", type: 'POST', async: true, contentType: 'application/json', data: JSON.stringify({ id: id, name: name, age: age }), success: function (response) { $("#userID").val(response.id) alert("Sucess") } }).fail(function (xhr, status, errorThrow) { alert("error saving user " + xhr.responseText); }) } function reset() { $("#reset").click(function () { resetcampus() }) } function research() { $("#research").click(function () { var name = $("#recipient-name").val() if (name != null && name.trim() != "") { $.ajax({ url: "searchbyname", type: 'GET', async: true, contentType: 'application/json', data: "name=" + name, success: table }).fail(function (xhr, status, errorThrow) { alert("error when searching user " + xhr.responseText); }) } }) } function table(response) { $("#tableresult > tbody > tr").remove(); for (var i = 0; i < response.length; i++) { $("#tableresult > tbody").append("<tr id= '" + response[i].id + "'><td>" + response[i].id + "</td><td>" + response[i].name + "</td><td>" + response[i].age + "</td><td> <button type='button' onclick=funcedit(" + response[i].id + ") class='buttons' id = 'edit'>edit</button>" + "</td><td> <button type='button' onclick=funcdelete(" + response[i].id + ") id='button' class='buttons' id ='delete'>Delete</button> </td></tr>"); } } function funcedit(id) { $.ajax({ url: "searchuser", type: 'GET', async: true, contentType: 'application/json', data: "iduser=" + id, success: function (response) { $("#userID").val(response.id) $("#name").val(response.name) $("#age").val(response.age) $('#Modal').modal('toggle'); } }).fail(function (xhr, status, errorThrow) { alert("error when searching user " + xhr.responseText); }) } function funcdelete(id) { if (confirm("Do you really want to delete? ")) { $.ajax({ url: "delete", type: 'DELETE', data: "iduser=" + id, success: function (response) { alert(response); resetcampus(); $("#" + id).remove(); } }).fail(function (xhr, status, errorThrow) { alert("error when delete user " + xhr.responseText); }) } } function resetcampus() { $("#userID").val("") $("#name").val("") $("#age").val("") } function clickdelete(){ var id = $("#userID").val() $("#delete").click(function(){ var id = $("#userID").val() if(id != null || id != ""){ funcdelete(id) } }) }
30,047
https://github.com/leehoang2000/tank-game-with-network/blob/master/client/message/HealthValueMessage.java
Github Open Source
Open Source
MIT
null
tank-game-with-network
leehoang2000
Java
Code
50
151
package client.message; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; public class HealthValueMessage extends Message { public HealthValueMessage(DatagramSocket senderSocket, InetSocketAddress destination, int playerID, int currentHealth, int roomID) throws SocketException, UnknownHostException { super(senderSocket, destination); this.data = HEALTH_VALUE + DELIMITER + roomID + DELIMITER + playerID + DELIMITER + currentHealth; } }
19,516
https://github.com/yanuarpmbd/arsip/blob/master/resources/views/yanjin/pinjam/edit-pinjam.blade.php
Github Open Source
Open Source
MIT
null
arsip
yanuarpmbd
PHP
Code
138
819
<div class="row"> <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Status Peminjaman</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> <div class="ibox-content"> <form method="post" class="form-horizontal" action="{{route('update.peminjam', $edit->id)}}"> @method('PATCH') @csrf <div class="form-group"><label class="col-sm-2 control-label">Nama</label> <div class="col-sm-10"><input type="text" name="nama" class="form-control" value="{{$edit->nama}}" readonly></div> </div> <div class="hr-line-dashed"></div> <div class="form-group"><label class="col-sm-2 control-label">Kode Arsip</label> <div class="col-sm-8"> <input type="text" name="kode_arsip" id="kode_arsip" class="form-control" value="{{$edit->kode_arsip}}" readonly> </div> <div class="col-sm-2"> <a onclick="myFunction()">Copy text</a> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"><label class="col-sm-2 control-label">Tanggal Pinjam</label> <div class="col-sm-10"><input type="text" name="tanggal" class="form-control" value="{{$edit->tanggal}}" readonly></div> </div> <div class="hr-line-dashed"></div> <div class="form-group" id="data_1"><label class="col-lg-2 control-label">Tanggal Kembali</label> <div class="col-lg-10"> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span> <input type="text" name="tanggal_kembali" id="tanggal_kembali" class="form-control" value="{{$today}}"> </div> </div> </div> <div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div> <div class="form-group"> <div class="col-sm-4 col-sm-offset-2"> <button class="btn btn-primary"><a href="{{route('arsip.form')}}" style="color: white">Cari</a></button> <button class="btn btn-white" type="submit">Cancel</button> <button class="btn btn-primary" type="submit">Save changes</button> </div> </div> </form> </div> </div> </div> </div>
26,000
https://github.com/Ermlab/python-ddd/blob/master/src/modules/catalog/module.py
Github Open Source
Open Source
MIT
2,022
python-ddd
Ermlab
Python
Code
114
480
from seedwork.application.modules import BusinessModule from .domain.repositories import ListingRepository from modules.catalog.application.query.get_all_listings import ( GetAllListings, get_all_listings, ) from modules.catalog.application.query.get_listings_of_seller import ( GetListingsOfSeller, get_listings_of_seller, ) from modules.catalog.application.query.get_listing_details import ( GetListingDetails, get_listing_details, ) from modules.catalog.application.command.create_listing_draft import ( CreateListingDraftCommand, create_listing_draft, ) class CatalogModule(BusinessModule): query_handlers = { GetAllListings: lambda self, q: get_all_listings(q, self.listing_repository), GetAllListings: lambda self, q: get_all_listings(q, self.listing_repository), GetListingDetails: lambda self, q: get_listing_details( q, self.listing_repository ), GetListingsOfSeller: lambda self, q: get_listings_of_seller( q, self.listing_repository ), } command_handlers = { CreateListingDraftCommand: lambda self, c: create_listing_draft( c, self.listing_repository ), } def __init__( self, listing_repository: ListingRepository, ) -> None: self.listing_repository = listing_repository @staticmethod def create(container): """Factory method for creating a module by using dependencies from a DI container""" return CatalogModule( logger=container.logger(), listing_repository=container.listing_repository(), )
38,020
https://github.com/candyninja001/pypad/blob/master/pypad/dungeon/floor_modifier/type_bonus_fm.py
Github Open Source
Open Source
MIT
null
pypad
candyninja001
Python
Code
89
335
from . import FloorModifier, FloorModifierLoader from ...monster_type import MonsterType from ...common import binary_to_list class TypeBonusFM(FloorModifier): @classmethod def handles(self, name): return name == 'btype' def parse_value(self): args = self.value.split(';') self.types = tuple(MonsterType(t) for t in binary_to_list(int(args[0]))) self.hp_multiplier = int(args[1]) / 10000 self.atk_multiplier = int(args[2]) / 10000 self.rcv_multiplier = int(args[3]) / 10000 def args_to_json(self) -> dict: return { 'types': [a.value for a in self.types], 'hp_multiplier': self.hp_multiplier, 'atk_multiplier': self.atk_multiplier, 'rcv_multiplier': self.rcv_multiplier, } def localize(self) -> str: return '' # TODO @property def floor_modifier_type(self): return 'type_bonus' # register the floor modifier class FloorModifierLoader._register_floor_modifier_class(TypeBonusFM)
49,834
https://github.com/EnEff-BIM/EnEffBIM-Framework/blob/master/MapAPI/mapapi/MapClasses.py
Github Open Source
Open Source
MIT
2,022
EnEffBIM-Framework
EnEff-BIM
Python
Code
3,783
13,151
import os import sys rootPath = os.path.dirname(__file__) try: default_path = rootPath[:rootPath.rfind("EnEffBIM-Framework")] modulePath = os.path.join(default_path, "EnEffBIM-Framework\\SimModel_Python_API\\" "\\simmodel_swig\\Release") os.environ['PATH'] = ';'.join([modulePath, os.environ['PATH']]) sys.path.append(modulePath) import SimModel except: default_path = rootPath[:rootPath.rfind("eneffbim-framework")] modulePath = os.path.join(default_path, "EnEffBIM-Framework\\SimModel_Python_API\\" "\\simmodel_swig\\Release") os.environ['PATH'] = ';'.join([modulePath, os.environ['PATH']]) sys.path.append(modulePath) import SimModel import numpy as np from numpy import linalg as LA import SimModel_Mapping import SimModel_Hierachy from SimProject_Project_DesignAlternative import SimProject_Project_DesignAlternative from SimSite_BuildingSite_Default import SimSite_BuildingSite_Default from SimBuilding_Building_Default import SimBuilding_Building_Default import SimBuildingStory_BuildingStory_Default import SimGroup_SpatialZoneGroup_ZoneGroup import SimGroup_SpatialZoneGroup_ZoneHvacGroup from SimSpatialZone_ThermalZone_Default import SimSpatialZone_ThermalZone_Default import SimSpace_Occupied_Default import SimList_EquipmentList_ZoneHvac import SimSpaceBoundary_SecondLevel_SubTypeA import SimSlab_Default_Default import SimSlab_RoofSlab_RoofUnderAir import SimSlab_Floor_FloorOverEarth import SimSlab_Floor_InterzoneFloor import SimWall_Wall_Default import SimWall_Wall_ExteriorAboveGrade import SimWall_Wall_Interior import SimWindow_Window_Exterior import SimMaterialLayerSet_Default_Default import SimMaterialLayerSet_OpaqueLayerSet_Roof import SimMaterialLayerSet_OpaqueLayerSet_Floor import SimMaterialLayerSet_OpaqueLayerSet_Wall import SimMaterialLayerSet_GlazingLayerSet_Window import SimFeatureElementSubtraction_Void_Opening import SimMaterialLayer_OpaqueMaterialLayer_Default import SimMaterialLayer_GlazingMaterialLayer_Default import SimMaterial_Default_Default import SimMaterial_OpaqueMaterial_Default import SimMaterial_OpaqueMaterial_AirGap import SimMaterial_GlazingMaterial_Gas import SimMaterial_GlazingMaterial_SimpleGlazingSystem import SimMaterial_GlazingMaterial_Glazing import SimModelRepresentationContext_GeometricRepresentationContext_Default import SimPlacement_Axis2Placement3D_Default import SimGeomVector_Vector_Direction from SimSystem_HvacHotWater_FullSystem import SimSystem_HvacHotWater_FullSystem import SimSystem_HvacHotWater_Control import SimController_SupplyWater_Temperature import SimSensor_TemperatureSensor_DryBulb from SimSystem_HvacHotWater_Demand import SimSystem_HvacHotWater_Demand import SimFlowController_Valve_Default import SimFlowController_Valve_TemperingValve import SimFlowEnergyTransfer_ConvectiveHeater_Water import SimFlowEnergyTransfer_ConvectiveHeater_Radiant_Water import SimFlowEnergyTransferStorage_HotWaterTank_Expansion import SimFlowEnergyTransferStorage_HotWaterTank_Mixed import SimFlowFitting_Default_Default import SimFlowFitting_Mixer_DemandProxyMixerWater import SimFlowFitting_Splitter_DemandProxySplitterWater import SimFlowSegment_Pipe_Indoor from SimSystem_HvacHotWater_Supply import SimSystem_HvacHotWater_Supply import SimFlowMover_Pump_VariableSpeedReturn import SimFlowPlant_Boiler_BoilerHotWater import SimConnection_HotWaterFlow_Default import SimNode_HotWaterFlowPort_Water_Out import SimNode_HotWaterFlowPort_Water_In import SimDistributionPort_HotWaterFlowPort_Water_Out import SimDistributionPort_HotWaterFlowPort_Water_In import SimDistributionPort_HotWaterFlowPort_Water_InOrOut import SimNode_DigitalControl_HWLoop_DigitalSignal_In import SimTimeSeriesSchedule_Year_Default import SimTimeSeriesSchedule_Week_Daily import SimTimeSeriesSchedule_Day_Interval import SimTemplateZoneLoads_ZoneLoads_Default import SimTemplateZoneConditions_ZoneConditions_Default import SimInternalLoad_Equipment_Electric import SimInternalLoad_People_Default import SimInternalLoad_Lights_Default import SimController_ZoneControlTemperature_Thermostat import SimControlScheme_SetpointScheme_SingleHeating import SimPerformanceCurve_Mathematical_Cubic from SimModel_Translator import SimTranslator class MoObject(object): """Base class for all mapped objects The MoObject class is the base class for all mapped objects in the StaticAPI. It contains some library specific data and ist always referenced directly or indirectly (MapGap) to a SimModel Object. Parameters ---------- project : instance of MapProject() MapProject as a "root" parent to have control over the connections in the overall model hierarchy_node : instance of libSimModelAPI.SimHierarchyNode() SimHierarchyNode() of the mapped or referenced MoObject Attributes ---------- target_location : str location within the library - part of Parameter/Object Mapping target_name : str name of the Modelica object (by default the SimModel Name, if it is only indrectly referenced to SimModel (MapGap) it is most likely the parent SimModel Name with some addition sim_ref_id : str for some application it might be useful to store the SimModel Reference ID of the mapped Object parameters : list of MapParameter or MapRecord This is an *iterable* list containing all records and parameters of the MoObject connectors : list of MapConnector This is an *iterable* list containing all Modelica connectors of the MoObject (e.g. Real, Heatport, Fluid) mapped_component : libSimModelAPI.MappedComponent Object if available mapped component. If there is an explicit SimModelObject for the hierarchy node, the first entry of MappedCompomponent is assinged, otherwise mapped_component is None and needs to be set for one to many mapping individually """ def __init__(self, project, hierarchy_node): self.parent = None self.project = project self.target_location = None self.hierarchy_node = hierarchy_node if self.hierarchy_node is not None: try: self.sim_instance = self.hierarchy_node.getSimModelObject() except: self.sim_instance = None else: self.sim_instance = None try: self.mapped_component = self.hierarchy_node.getMappedComponents()[0] except: self.mapped_component = None if self.sim_instance is not None: self.target_name = "Random" + self.sim_instance.RefId()[-5:] #self.target_name = self.sim_instance.SimModelName().getValue( # ).replace(" ", "").replace("(","").replace(")","").replace( # "-","_") else: self.target_name = None if self.sim_instance is not None: self.sim_ref_id = self.sim_instance.RefId() else: self.sim_ref_id = None self.parameters = [] self.records = [] self.connectors = [] def add_connector(self, name, type, hierarchy_node=None, dimension=1, design=None): """This adds a MapConnector to the MoObject For topology mapping it is necessary to add Modelica connectors to the MoObject. An instance of MapConnector is added to the MoObject.connectors list. The function sets the attributes of the MapConnector Parameters ---------- name : str name of the Connector in the Modelica model type : str type of the Connector (e.g. Real) dimension : int dimension of the connector if it is a vector Returns ---------- connector : MapConnector returns the instantiated MapConnector class """ connector = MapConnector(self, hierarchy_node) connector.name = name connector.type = type connector.dimension = dimension self.connectors.append(connector) return connector def add_parameter(self, name, value): """This adds a MapParameter to the MoObject For topology mapping it might be necessary to add additional parameters, besides the mapped once to some MoObjects. This creates an instance of MapParameter and adds it to MoObject parameter list. Parameters ---------- name : str name of the property in Modelica value : int/float/str/bool value of the property Returns ---------- mapped_prop : MapParameter returns the MapParameter instance """ existing_para = False for para in self.parameters: if para.name == name: existing_para = True break else: pass if existing_para is True: para.value = value return para elif existing_para is False: mapped_prop = MapParameter(self, name, value) self.parameters.append(mapped_prop) return mapped_prop def add_connection(self, connector_a, connector_b, index_a=None, index_b=None): """This connects the MoObject to another Object For topology mapping it might be necessary to connect two MoObjects. With the given Connectors of each Object a MapConnection is instantiated and the attributes are set. Parameters ---------- connector_a : MapConnector Own connector that should be connected (must be in connectors list!) connector_b : MapConnector Connector of the MoObject that is connected index_a : index of connector_a default is None, only appicable if MapConnector A has an index index_b : index of connector_b default is None, only appicable if MapConnector B has an index Returns ---------- mapped_con : MapConnector returns the MapConnector instance """ # if connector_a in self.connectors: # pass # else: # raise ValueError("input_connector is not assigned to MoObject") if connector_a.type == connector_b.type: mapped_con = MapConnection(connector_a, connector_b, index_a, index_b) mapped_con.type = connector_a.type self.project.connections.append(mapped_con) return mapped_con else: raise TypeError("Input/Ouput connector type or dimension" "do not match") class MapProject(object): """Root Class for each mapped data information The MapProject class is the root class for all mapped information and thus the head of the hierarchy tree. Further more it contains meta information about the used library. Parameters ---------- simxml_file : list of length 2 absolute path to the SimModel XML file, first entry geometry, second entry HVAC mapping_file : srt absolute path to the MappingRule XML file Attributes ---------- project_name : str name of the project used_library : str Name of used library library_version : str Version of used library buildings : list of MapBuilding() This is an *iterable* list containing all buildings of the project. The items of the list have to be an instance of the class "MapBuilding". connections : list of MapConnection() This is an *iterable* list containing all connections. hvac_components : list of MapComponents() This is an iterable list containing all MapComponents. mod_components : list of MapComponents() This is an iterable list containing all additionally added MapComponents (e.g. Non-Fluid) sim_hierarchy : instance of SimHierarchy SImHierarchy object, generic class """ def __init__(self, simxml_file, mapping_file): self.simxml_file = simxml_file self.project_name = "" self.used_library = "" self.library_version = "" self.buildings = [] self.connections = [] self.hvac_components = [] self.mod_components = [] self.dict_con = {} self.dict_con_inout = {} """Instantiate the SimModel Hierarchy and load the SimXML file through libSimModelAPI""" self.translator = SimTranslator() self.sim_hierarchy = self.translator.getSimHierarchy() if isinstance(simxml_file,list) or isinstance(simxml_file,tuple): load_sim = self.translator.loadSimModel(simxml_file[0], simxml_file[1]) else: load_sim = self.translator.loadSimModel(simxml_file) self.sim_mapping = self.translator.getSimMappedData(mapping_file) mapped_list = self.sim_mapping.getMappedComponentList() self.mapped_components = {} for a in range(mapped_list.size()): if mapped_list[a].getMappingRuleName() == "Component_Map_One2Many": if mapped_list[a].getUnmappedSimHierarchyNodes()[0].ClassType() in self.mapped_components: pass else: self.mapped_components[mapped_list[a].getUnmappedSimHierarchyNodes()[0].ClassType()] = str(mapped_list[a].getTargetLocation()) elif mapped_list[a].getMappingRuleName() == "Component_Map_Map_Gap": pass elif mapped_list[a].getMappingRuleName() == "Component_Map_One2One": self.mapped_components[mapped_list[a].getUnmappedSimHierarchyNodes()[0].ClassType()] = str(mapped_list[a].getTargetLocation()) self.library_objects = {} import importlib import sys this_module = sys.modules[__name__] for key, value in self.mapped_components.items(): m_class = value[(value.rfind(".")+1):len(value)] m_module = importlib.import_module("mapapi.molibs."+value) m_temp = getattr(m_module, m_class) self.library_objects[key] = m_temp setattr(this_module, m_class, m_temp) self.instantiate_buildings() def instantiate_buildings(self): '''Instantiates for each SimBuilding_Building_Default a MapBuilding. Search the libSimModel Hierarchy for the root and for Buildings, for each Building: instantiate a MapBuilding and appends it to the buildings list. ''' root_node = self.sim_hierarchy.getHierarchyRootNode() prj_child = root_node.getChildList() if isinstance(root_node.getSimModelObject(), SimProject_Project_DesignAlternative): for a in range(prj_child.size()): if isinstance(prj_child[a].getSimModelObject(), SimSite_BuildingSite_Default): site_child = prj_child[a].getChildList() for b in range(site_child.size()): if isinstance(site_child[b].getSimModelObject(), SimBuilding_Building_Default): MapBuilding(self, site_child[b]) class MapBuilding(MoObject): """Representation of a mapped building The MapBuilding class is a representation of a building mapped with Modelica information. It contains HVAC and geometric information. Note: As MapBuilding inherits from MoObject it is possible to implement connectors, parameters and whole models target names. Attributes ---------- thermal_zones : list of MapThermalZone() This is an *iterable* list containing all thermal zones of the building. The items of the list have to be an instance of the class MapThermalZone or inherit from MapThermalZone. hvac_components_sim : list This is a list with all (converted) hvac components from SimModel hvac_components_mod : list This is a list with all added hvac components because of MapGap, one to Many Mappings or Topology mapping """ def __init__(self, project, hierarchy_node): super(MapBuilding, self).__init__(project, hierarchy_node) #self.Longitude = self.hierarchy_node.getSimModelObject().Longitude() self.project.buildings.append(self) self.thermal_zones = [] self.hvac_components_node = [] self.hvac_components_sim = [] self.hvac_components_mod = [] self.internalGainsConv = self.add_connector(name="internalGainsConv", type="HeatPort") self.instantiate_components() self.instantiate_thermal_zones() self.convert_components() self.instantiate_connections() for tz in self.thermal_zones: tz.mapp_me() for a in self.hvac_components_sim: a.mapp_me() pass def instantiate_connections(self): '''instantiates the SimModel topology connections ''' for key, value in self.project.dict_con.items(): for comp in self.hvac_components_sim: if value['Source'].getSimModelObject().HostElement().getValue() == comp.sim_ref_id: comp.connected_in.append(self.project.sim_hierarchy.getHierarchyNode( value['Target'].getSimModelObject().HostElement().getValue())) if value['Target'].getSimModelObject().HostElement().getValue() == comp.sim_ref_id: comp.connected_out.append(self.project.sim_hierarchy.getHierarchyNode( value['Source'].getSimModelObject().HostElement().getValue())) for key, value in self.project.dict_con.items(): for comp in self.hvac_components_sim: if value['Source'].getSimModelObject().HostElement().getValue() == comp.sim_ref_id: value['Source_Mod'] = comp elif value['Target'].getSimModelObject().HostElement().getValue() == comp.sim_ref_id: value['Target_Mod'] = comp con = MapConnection(value['Source_Mod'].port_a, value['Target_Mod'].port_b) self.project.connections.append(con) in_out_keep = [] in_out_rem = [] for comp in self.project.hvac_components: if comp.comp_con_inout: if len(comp.comp_con_inout) == 1: in_out_keep.append(comp) else: in_out_rem.append(comp) for y in in_out_rem: self.project.hvac_components.remove(y) con = MapConnection(in_out_keep[0].port_a, in_out_keep[1].port_a) self.project.connections.append(con) def instantiate_thermal_zones(self): '''Instantiates for each SimSpatialZone_ThermalZone_Default a MapThermalZone. Search the libSimModel Hierarchy for thermalZones, for each thermal zone: instantiate a MapThermalZone and append it to the thermal zone list. ''' bldg_child = self.hierarchy_node.getChildList() for a in range(bldg_child.size()): if isinstance(bldg_child[a].getSimModelObject(), SimSpatialZone_ThermalZone_Default): self.thermal_zones.append(MapThermalZone(project=self.project, hierarchy_node=bldg_child[a], parent=self)) self.thermal_zones[-1].convert_me() def instantiate_components(self): '''Seach for Items attached to SimSystem_HvacHotWater_Supply and SimSystemHvacHotWater_Demand in SimModel, for each found: create MapComponent and add to hvac_component list ''' comp_help = {} bldg_child = self.hierarchy_node.getChildList() for a in range(bldg_child.size()): if isinstance(bldg_child[a].getSimModelObject(), SimSystem_HvacHotWater_FullSystem): full_system_child = bldg_child[a].getChildList() for b in range (full_system_child.size()): if isinstance(full_system_child[b].getSimModelObject(), SimSystem_HvacHotWater_Supply): supply_child = full_system_child[b].getChildList() for e in range(supply_child.size()): comp_help[supply_child[e].getSimModelObject().RefId()] = supply_child[e] for a in range(bldg_child.size()): if isinstance(bldg_child[a].getSimModelObject(), SimSystem_HvacHotWater_FullSystem): full_system_child = bldg_child[a].getChildList() for b in range(full_system_child.size()): if isinstance(full_system_child[b].getSimModelObject(), SimSystem_HvacHotWater_Demand): demand_child = full_system_child[b].getChildList() for f in range(demand_child.size()): comp_help[demand_child[f].getSimModelObject().RefId()] = demand_child[f] for key, value in comp_help.items(): component = MapComponent(self.project, value) component.find_loop_connection() self.hvac_components_sim.append(component) self.project.hvac_components = self.hvac_components_sim def convert_components(self): '''Once all hvac components in the SimXML are identified and instantiated as a MapComponent() on Python side (with help of instantiate_components() function ), we can convert these into the library specific classes, by calling the convert_me() function''' for a in self.hvac_components_sim: a.convert_me() class MapThermalZone(MoObject): """Representation of a mapped thermal zone The MapThermalZone class is a representation of a thermal zone mapped with Modelica information. It contains HVAC and geometric information. Note: As MapThermalZone inherits from MoObject it is possible to implement connectors, parameters and whole models target names. Parameters ---------- parent : instance of MapBuilding() parent of the MapThermalZone, instance of MapBuilding() Attributes ---------- space_boundaries : MapSpaceBoundaries() needs to be figured out """ def __init__(self, project, hierarchy_node, parent): super(MapThermalZone, self).__init__(project, hierarchy_node) self.parent = parent self.height = None self.area = None self.volume = None self.space_boundaries = [] from mapapi.molibs.AixLib.Building.LowOrder.ThermalZone import \ ThermalZone self.aix_lib = {"SimSpatialZone_ThermalZone_Default" : ThermalZone} self.instantiate_space_boundaries() spatial_child = self.hierarchy_node.getChildList() for a in range(spatial_child.size()): if spatial_child[a].ClassType() == "SimSpace_Occupied_Default": self.height = spatial_child[a].getSimModelObject().SpaceHeight().getValue() def convert_me(self): """Converts the MapComponent to a library specific component""" for key, value in self.aix_lib.items(): if self.hierarchy_node.ClassType() == key: self.__class__ = value self.init_me() return else: pass def instantiate_space_boundaries(self): tz_child = self.hierarchy_node.getChildList() for a in range(tz_child.size()): if tz_child[a].ClassType() == "SimSpace_Occupied_Default": occ_child = tz_child[a].getChildList() for b in range(occ_child.size()): if occ_child[b].ClassType() == \ "SimSpaceBoundary_SecondLevel_SubTypeA": if occ_child[b].getSimModelObject().PhysicalOrVirtualBoundary().getValue() == "PHYSICAL": space_bound = MapSpaceBoundary(self, occ_child[b]) space_bound.instantiate_element() self.space_boundaries.append(space_bound) class MapComponent(MoObject): """Representation of a mapped component The MapComponent class is a representation of any HVAC component mapped with Modelica information. It contains library specific information. Attributes ---------- map_control: MapControl() Pointer to an optional control element, instance of MapControl() hvac_loop : string if the MapComponent is referenced to a HVAC loop (e.g. MapThermalZone.hvac_component_group) the name of this loop can be stored here. This is a string because hvac_component_group is a dictionary with the name of the loops as the key connected_in : list of HierarchyNodes list of hierarchy nodes that are connected TO this MapComponent connected_out : list of HierarchyNodes list of hierarchy nodes that are connected FROM this MapComponent """ def __init__(self, project, hierarchy_node, parent=None): super(MapComponent, self).__init__(project, hierarchy_node) self.parent = parent self.map_control = None self.hvac_loop = None self.connected_in = [] self.connected_out = [] self.connected_in_or_out = [] self.connected_out_ref_id = [] self.comp_con = {} self.comp_con_inout = {} def find_loop_connection(self, hierarchy_node=None): ''' recursive function, to find all connected items in SimXML Parameters ---------- hierarchy_node : current hierarchy node Returns ------- ''' if hierarchy_node is not None: comp_child = hierarchy_node.getChildList() else: comp_child = self.hierarchy_node.getChildList() for i in range(comp_child.size()): outlet_child = comp_child[i].getChildList() if comp_child[i].ClassType() == \ "SimDistributionPort_HotWaterFlowPort_Water_Out" or comp_child[i].ClassType() == \ "SimDistributionPort_HotWaterFlowPort_Water_In": for j in range(outlet_child.size()): if outlet_child[j].ClassType() == "SimConnection_HotWaterFlow_Default": self.project.dict_con[outlet_child[j].getSimModelObject().RefId()] = {} self.project.dict_con[outlet_child[j].getSimModelObject().RefId()]['Source'] = \ self.project.sim_hierarchy.getHierarchyNode(outlet_child[j].getSimModelObject().SourcePort().getValue()) self.project.dict_con[outlet_child[j].getSimModelObject().RefId()]['Target'] = \ self.project.sim_hierarchy.getHierarchyNode(outlet_child[ j].getSimModelObject().TargetPort().getValue()) self.comp_con[ outlet_child[j].getSimModelObject().RefId()] = {} self.comp_con[outlet_child[j].getSimModelObject().RefId()]['Source'] = \ self.project.sim_hierarchy.getHierarchyNode(outlet_child[j].getSimModelObject().SourcePort().getValue()) self.comp_con[outlet_child[j].getSimModelObject().RefId()]['Target'] = \ self.project.sim_hierarchy.getHierarchyNode(outlet_child[ j].getSimModelObject().TargetPort().getValue()) elif comp_child[i].ClassType() == \ "SimDistributionPort_HotWaterFlowPort_Water_InOrOut": for j in range(outlet_child.size()): if outlet_child[j].ClassType() == "SimConnection_HotWaterFlow_Default": self.project.dict_con_inout[outlet_child[ j].getSimModelObject().RefId()] = [] self.project.dict_con_inout[outlet_child[ j].getSimModelObject().RefId()].append( self.project.sim_hierarchy.getHierarchyNode(outlet_child[j].getSimModelObject().SourcePort().getValue())) self.project.dict_con_inout[outlet_child[j].getSimModelObject().RefId()].append( self.project.sim_hierarchy.getHierarchyNode( outlet_child[ j].getSimModelObject().TargetPort().getValue())) self.comp_con_inout[ outlet_child[j].getSimModelObject().RefId()] = [] self.comp_con_inout[outlet_child[j].getSimModelObject().RefId()].append( self.project.sim_hierarchy.getHierarchyNode( outlet_child[j].getSimModelObject().SourcePort().getValue())) self.comp_con_inout[outlet_child[j].getSimModelObject().RefId()].append( self.project.sim_hierarchy.getHierarchyNode( outlet_child[ j].getSimModelObject().TargetPort().getValue())) def create_connection(self, test): self.project.connections.append(MapConnection(self,test)) def convert_me(self): """Converts the MapComponent to a library specific component""" for key, value in self.project.library_objects.items(): if self.hierarchy_node.ClassType() == key: self.__class__ = value self.init_me() return else: pass def fluid_two_port(self, medium="Water"): """Adds connection for Modelica Fluid Two port to component""" sim_port_out = None sim_port_in = None child = self.hierarchy_node.getChildList() for id in range(child.size()): if child[id].ClassType() == \ "SimDistributionPort_HotWaterFlowPort_Water_In": sim_port_in = child[id] if child[id].ClassType () == \ "SimDistributionPort_HotWaterFlowPort_Water_Out": sim_port_out = child[id] self.port_a = self.add_connector(name="port_a", type="FluidPort", dimension=1, hierarchy_node=sim_port_in) self.port_b = self.add_connector(name="port_b", type="FluidPort", dimension=1, hierarchy_node=sim_port_out) self.add_parameter(name="m_flow_small", value=0.01) if medium == "Water": self.add_parameter(name="replaceable package Medium", value="AixLib.Media.Water") else: pass def arrange_parameters(self, map_prop_list): """arranges parameters in such a way that it distinguishes between records and parameters""" for a in range(map_prop_list.size()): if map_prop_list[a].getRecordInstance() != "": if len(self.records) == 0: self.records.append(MapRecord(parent=self, record_location=map_prop_list[a].getRecordLocation(), name=map_prop_list[a].getRecordInstance())) else: for rec in self.records: if map_prop_list[a].getRecordInstance() == rec.name: pass else: self.records.append(MapRecord(parent=self, record_location=map_prop_list[a].getRecordLocation(), name=map_prop_list[a].getRecordInstance())) for b in range(map_prop_list.size()): if map_prop_list[b].getValueType() =="String" or map_prop_list[b].getValueType() =="Number": if map_prop_list[b].getRecordInstance() != "": for rec in self.records: if map_prop_list[b].getRecordInstance() == rec.name: rec.add_parameter(name=map_prop_list[b].getPropertyName(), value=map_prop_list[b].getPropertyValue()) else: print("warning: parameter seems to be aligned with " "empty record") else: self.add_parameter(name=map_prop_list[b].getPropertyName(), value=map_prop_list[b].getPropertyValue()) elif map_prop_list[b].getValueType() =="Matrix": matrix_data = map_prop_list[b].getPropertyValue() if map_prop_list[b].getRecordInstance() != "": for rec in self.records: if map_prop_list[b].getRecordInstance() == rec.name: rec.add_parameter(name=map_prop_list[b].getPropertyName(), value=[]) for row in range(matrix_data.size()): rec.parameters[-1].value.append(matrix_data[row]) else: self.add_parameter(name=map_prop_list[b].getPropertyName(), value=[]) for row in range(matrix_data.size()): self.parameters[-1].value.append(matrix_data[row]) class MapConnection(object): """Representation of a mapped connector The MapConnection class is a representation of a connection in Modelica. It contains two MapConnectors and the Modelica Type of the connection. Parameters ---------- connector_a : instance of a MapConnector() The input connector, with the parent/child relationshsip we can access the component connector_b : instance of a MapConnector() The output component, with the parent/child relationshsip we can access the component index_a : index of connector_a default is None, only appicable if MapConnector has an index index_b : index of connector_b default is None, only appicable if MapConnector has an index Attributes ---------- type : str Modelica Type of the connection. - Fluid - Real - Boolean - Heat - ... sim_ref_id : str refID of SimModel for the corresponding SimConnection """ def __init__(self, connector_a, connector_b, index_a = None, index_b = None): self.connector_a = connector_a self.connector_b = connector_b self.index_a = index_a self.index_b = index_b self.type = "" self.sim_ref_id = None class MapConnector(object): """Representation of a mapped connector The MapConnector class is a representation of any connector in Modelica. It contains connector information like name and type. Parameters ---------- parent : instance of a MapComponent() MapParameter receives an instance of MapComponent. Attributes ---------- name : str Name of the connector in the model. type : str - FluidPort - Real - Boolean - HeatPort - ... dimension : int dimension of the Modelica connector (default = 1) sim_ref_id : str refID of SimModel for the corresponding distributionPort """ def __init__(self, parent, hierarchy_node=None): self.parent = parent self.hierarchy_node = hierarchy_node self.name = "" self.type = "" self.dimension = 1 self.sim_ref_id = None class MapControl(object): """Representation of a mapped control strategy The MapControl class is a representation of a mapped control system. It is used to store control parameters and more important the control strategy/system itself Parameters ---------- parent : instance of a MapComponent() MapParameter receives an instance of MapComponent. Attributes ---------- control_strategy : str (library specific codelist) Probably a code list of possible control strategies control_objects : list of MoObject This is an *iterable* list containing all MoObjects of the control strategy control_connector : instance of a MapConnector() MapConnector of one of the control_objects that provides the output control variable """ def __init__(self, parent): self.parent = parent self.control_strategy = "" self.control_objects = [] self.control_connector = None class MapParameter(object): """Representation of a mapped property The MapParameter class is a representation of any Modelica parameter. Parameters ---------- parent : instance of a MapComponent() or MapRecord() MapParameter receives an instance of MapComponent or MapRecord() name : str Modelica name of the Parameter (e.g. Q_flow_max) value : float/int/bool/str/list/array Value of the Parameter, can be float, int, boolean, string, list or array with corresponding data type. """ def __init__(self, parent, name, value): self.parent = parent self.name = name self.value = value class MapRecord(object): """Representation of a mapped record The MapRecord class is a representation of any Modelica Record class. Parameters ---------- parent : instance of a MapComponent() MapRecords receives an instance of MapComponent. name : str Modelica name of the Record (e.g. boilerEfficiencyB) record_location : str location in the library of the base record Attributes ---------- parameters : list of MappedParameter or MapRecords This is an *iterable* list containing all records and parameters of the MapRecord """ def __init__(self, parent, record_location, name): self.parent = parent self.name = name self.record_location = record_location self.parameters = [] def add_parameter(self, name, value): """This adds a Parameter to the MapRecord For topology mapping it might be necessary to add additional propertys, besides the mapped once to some MoObjects. This creates an instance of MapParameter and adds it to MoObject property list. Parameters ---------- name : str name of the property in Modelica value : int/float/str/bool value of the property Returns ---------- mapped_prop : MapParameter returns the MapParameter instance """ mapped_prop = MapParameter(self, name, value) self.parameters.append(mapped_prop) return mapped_prop class MapSpaceBoundary(object): """Representation of a mapped space boundary The MapSpaceBoundary class is a representation of a space boundary filled with geometric information. Parameters ---------- parent : instance of MappedZone() MapSpaceBoundary receives an instance of MappedZone, in order to know to what zone it belongs to. Attributes ---------- sim_ref_id : str SimModel ref id type: str(?) OuterWall, InnerWall, Roof, Floor, Ceiling, Door, etc. internal_external: str(?) internal or external space boundary (is sun exposed?) area : float area of building element tilt : float tilt against horizontal orientation : float compass direction of building element (e.g. 0 : north, 90: east, 180: south, 270: west) inner_convection : float constant heat transfer coefficient of convection inner side inner_radiation : float constant heat transfer coefficient of radiation inner side outer_convection : float constant heat transfer coefficient of convection outer side for inner walls and ground floor zero outer_radiation : float constant heat transfer coefficient of radiation outer side for inner walls and ground floor zero simmodel_coordinates: array coordinates given in SimModel if needed for 3D-modelling simmodel_normal_vector: array normal vector from SimModel mapped_layer : list of MapMaterialLayer list of all layers of a building element """ def __init__(self, parent, hierarchy_node=None): self.parent = parent self.hierarchy_node = hierarchy_node self.type = None if self.hierarchy_node is not None: self.sim_instance = self.hierarchy_node.getSimModelObject() self.sim_ref_id = self.sim_instance.RefId() else: self.sim_instance = None self.possible_types = ['SimSlab_RoofSlab_RoofUnderAir', 'SimSlab_Floor_FloorOverEarth', 'SimWall_Wall_ExteriorAboveGrade', 'SimWindow_Window_Exterior', 'SimSlab_Default_Default', 'SimWall_Wall_Default', 'SimWall_Wall_Interior', 'SimSlab_Floor_InterzoneFloor'] self.possible_layers = ["SimMaterialLayerSet_OpaqueLayerSet_Wall", "SimMaterialLayerSet_OpaqueLayerSet_Roof", "SimMaterialLayerSet_OpaqueLayerSet_Floor", "SimMaterialLayerSet_GlazingLayerSet_Window"] self.internal_external = \ self.sim_instance.InternalOrExternalBoundary().getValue() self.area = self.sim_instance.GrossSurfaceArea().getValue()/1000000 self.tilt = None self.orientation = None self.inner_convection = None self.inner_radiation = None self.outer_convection = None self.outer_radiation = None self.simmodel_coordinates = None self.building_element = None self.layer_set = None self.mapped_layer = [] child = self.hierarchy_node.getChildList() for q in range(child.size()): if child[q].isClassType("SimGeomVector_Vector_Direction"): self.simmodel_normal_vector = child[q].getSimModelObject().DirectionRatios().getNumberList() self.set_orientation() self.set_tilt() else: self.simmodel_normal_vector = None def instantiate_element(self): bound_child = self.hierarchy_node.getChildList() for a in range(bound_child.size()): if bound_child[a].ClassType() in self.possible_types: self.type = bound_child[a].ClassType() self.building_element = bound_child[a].getSimModelObject() element_child = bound_child[a].getChildList() for b in range(element_child.size()): if element_child[b].ClassType() in self.possible_layers: self.layer_set = element_child[b].getSimModelObject() layer_child = element_child[b].getChildList() for c in range(layer_child.size()): self.mapped_layer.append(MapMaterialLayer(self,layer_child[c])) def set_orientation(self): normal_uni = np.asarray(self.simmodel_normal_vector) if normal_uni[0] > 0: phi = np.arctan(normal_uni[1]/normal_uni[0]) elif normal_uni[0] < 0 <= normal_uni[1]: phi = np.arctan(normal_uni[1]/normal_uni[0]) + np.pi elif normal_uni[0] < 0 > normal_uni[1]: phi = np.arctan(normal_uni[1]/normal_uni[0]) - np.pi elif normal_uni[0] == 0 < normal_uni[1]: phi = np.pi/2 elif normal_uni[0] == 0 > normal_uni[1]: phi = -np.pi/2 elif normal_uni[0] == 0 and normal_uni [1] == 0: phi = None if phi is None: if normal_uni[2] == -1: self.orientation = "Slab" elif normal_uni[2] == 1: self.orientation = "Roof" elif phi < 0: self.orientation = (phi+2*np.pi)*360/(2*np.pi) else: self.orientation = phi*360/(2*np.pi) if self.orientation in ["Slab","Roof"]: pass elif 0 <= self.orientation <= 90: self.orientation = 90 - self.orientation else: self.orientation = 450 - self.orientation def set_tilt(self): normal_uni = np.asarray(self.simmodel_normal_vector) z_axis = np.array([0, 0, 1]) self.tilt = np.arccos(np.dot(normal_uni, z_axis) / (LA.norm(z_axis) * LA.norm(normal_uni))) * 360 / (2 * np.pi) if self.tilt == 180: self.tilt = 0.0 elif str(self.tilt) == "nan": self.tilt = None class MapMaterialLayer(object): """Representation of a mapped building element layer The MapMaterialLayer class is the representation of a material layer Parameters ---------- parent : instance of MapBuildingElement() MapMaterialLayer receives an instance of MapBuildingElement, in order to know to what element it belongs to. Attributes ---------- material : MapMaterialLayer() material of the layer thickness : float thickness of the layer """ def __init__(self, parent, hierarchy_node=None): self.parent = parent self.material = None self.hierarchy_node = hierarchy_node if self.hierarchy_node is not None: self.sim_instance = self.hierarchy_node.getSimModelObject() self.thickness = self.sim_instance.SimMatLayer_LayerThickness().getValue() else: self.sim_instance = None self.sim_ref_id = self.sim_instance.RefId() self.instantiate_layer() def instantiate_layer(self): layer_child = self.hierarchy_node.getChildList() for a in range(layer_child.size()): self.material = MapMaterial(self, layer_child[a]) class MapMaterial(object): """Representation of a mapped material The MapMaterialLayer class is the representation of a material Parameters ---------- parent : instance of MapMaterialLayer() MapMaterialLayer receives an instance of MapMaterialLayer, in order to know to what layer it belongs to. Attributes ---------- name : str individual name density : float density of material in kg/m^3 thermal_conduc : float thermal conductivity of material in W/(m*K) heat_capac : float specific heat capacity of material in kJ/(kg*K) solar_absorp : float coefficient of absorption of solar short wave ir_emissivity : float coefficient of longwave emissivity of material transmittance : float coefficient of transmittanve of material """ def __init__(self, parent, hierarchy_node=None): self.parent = parent self.hierarchy_node = hierarchy_node self.sim_instance = self.hierarchy_node.getSimModelObject() self.name = None self.density = None self.thermal_conduc = None self.heat_capac = None self.solar_absorp = None self.ir_emissivity = None self.transmittance = None self.g_value = None self.tau = None self.u_value = None if self.hierarchy_node is not None: if self.hierarchy_node.ClassType() == \ "SimMaterial_OpaqueMaterial_Default": self.name = self.sim_instance.SimModelName().getValue() self.density = self.sim_instance.SimMaterial_Density().getValue() self.thermal_conduc = self.sim_instance.SimMaterial_Cond().getValue() self.heat_capac = self.sim_instance.SimMaterial_SpecificHeat().getValue() self.solar_absorp = self.sim_instance.SimMaterial_SolarAbsorptance().getValue() self.ir_emissivity = self.sim_instance.SimMaterial_ThermalAbsorptance().getValue() self.transmittance =(1- self.sim_instance.SimMaterial_VisAbsorptance().getValue()) elif self.hierarchy_node.ClassType() == \ "SimMaterial_GlazingMaterial_Glazing": self.name = self.sim_instance.SimModelName().getValue() self.thermal_conduc = self.sim_instance.SimMaterial_Cond().getValue() elif self.hierarchy_node.ClassType() == \ "SimMaterial_GlazingMaterial_Gas": self.name = self.sim_instance.SimModelName().getValue() self.heat_capac = \ self.sim_instance.SimMaterial_SpecificHeatCoefA().getValue() self.thermal_conduc = \ self.sim_instance.SimMaterial_CondCoefA().getValue() elif self.hierarchy_node.ClassType() == \ "SimMaterial_GlazingMaterial_SimpleGlazingSystem": self.name = self.sim_instance.SimModelName().getValue() self.g_value = self.sim_instance.SimMaterial_SolarHeatGainCoef().getValue() self.tau = self.sim_instance.SimMaterial_VisTrans().getValue() self.u_value = self.sim_instance.SimMaterial_UFactor().getValue() else: print(self.hierarchy_node.ClassType())
2,731
https://github.com/x4Cx58x54/network-planning/blob/master/interface/npGraphInterface/npGraphInterface/My Project/MainForm.Designer.vb
Github Open Source
Open Source
Apache-2.0
2,021
network-planning
x4Cx58x54
Visual Basic
Code
911
4,504
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class MainForm Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(MainForm)) Me.ButtonReadIn = New System.Windows.Forms.Button() Me.ButtonModifyDelete = New System.Windows.Forms.Button() Me.ButtonSearchView = New System.Windows.Forms.Button() Me.ButtonDrawGraph = New System.Windows.Forms.Button() Me.MenuStrip = New System.Windows.Forms.MenuStrip() Me.FileToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.NewProjectToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.OpenProjectToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripMenuItem1 = New System.Windows.Forms.ToolStripSeparator() Me.SaveToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.SaveAsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripMenuItem2 = New System.Windows.Forms.ToolStripSeparator() Me.CloseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripMenuItem5 = New System.Windows.Forms.ToolStripSeparator() Me.ExitToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.AboutToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ViewHelpToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripMenuItem3 = New System.Windows.Forms.ToolStripSeparator() Me.SendFeedbackToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.ToolStripMenuItem4 = New System.Windows.Forms.ToolStripSeparator() Me.CheckForUpdatesToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.AboutToolStripMenuItem1 = New System.Windows.Forms.ToolStripMenuItem() Me.MenuStrip.SuspendLayout() Me.SuspendLayout() ' 'ButtonReadIn ' Me.ButtonReadIn.BackColor = System.Drawing.SystemColors.ButtonHighlight Me.ButtonReadIn.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro Me.ButtonReadIn.FlatAppearance.MouseDownBackColor = System.Drawing.Color.White Me.ButtonReadIn.FlatAppearance.MouseOverBackColor = System.Drawing.Color.White Me.ButtonReadIn.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.ButtonReadIn.Font = New System.Drawing.Font("Segoe UI", 13.8!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ButtonReadIn.ForeColor = System.Drawing.SystemColors.ActiveCaptionText Me.ButtonReadIn.Location = New System.Drawing.Point(1, 28) Me.ButtonReadIn.Margin = New System.Windows.Forms.Padding(0) Me.ButtonReadIn.Name = "ButtonReadIn" Me.ButtonReadIn.Size = New System.Drawing.Size(255, 125) Me.ButtonReadIn.TabIndex = 0 Me.ButtonReadIn.Text = "Read-In" Me.ButtonReadIn.UseVisualStyleBackColor = False ' 'ButtonModifyDelete ' Me.ButtonModifyDelete.BackColor = System.Drawing.SystemColors.ButtonHighlight Me.ButtonModifyDelete.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro Me.ButtonModifyDelete.FlatAppearance.MouseDownBackColor = System.Drawing.Color.White Me.ButtonModifyDelete.FlatAppearance.MouseOverBackColor = System.Drawing.Color.White Me.ButtonModifyDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.ButtonModifyDelete.Font = New System.Drawing.Font("Segoe UI", 13.8!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ButtonModifyDelete.ForeColor = System.Drawing.SystemColors.ActiveCaptionText Me.ButtonModifyDelete.Location = New System.Drawing.Point(1, 154) Me.ButtonModifyDelete.Margin = New System.Windows.Forms.Padding(0) Me.ButtonModifyDelete.Name = "ButtonModifyDelete" Me.ButtonModifyDelete.Size = New System.Drawing.Size(255, 125) Me.ButtonModifyDelete.TabIndex = 2 Me.ButtonModifyDelete.Text = "Modify && Delete" Me.ButtonModifyDelete.UseVisualStyleBackColor = False ' 'ButtonSearchView ' Me.ButtonSearchView.BackColor = System.Drawing.SystemColors.ButtonHighlight Me.ButtonSearchView.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro Me.ButtonSearchView.FlatAppearance.MouseDownBackColor = System.Drawing.Color.White Me.ButtonSearchView.FlatAppearance.MouseOverBackColor = System.Drawing.Color.White Me.ButtonSearchView.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.ButtonSearchView.Font = New System.Drawing.Font("Segoe UI", 13.8!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ButtonSearchView.ForeColor = System.Drawing.SystemColors.ActiveCaptionText Me.ButtonSearchView.Location = New System.Drawing.Point(257, 28) Me.ButtonSearchView.Margin = New System.Windows.Forms.Padding(0) Me.ButtonSearchView.Name = "ButtonSearchView" Me.ButtonSearchView.Size = New System.Drawing.Size(255, 125) Me.ButtonSearchView.TabIndex = 3 Me.ButtonSearchView.Text = "Search && View" Me.ButtonSearchView.UseVisualStyleBackColor = False ' 'ButtonDrawGraph ' Me.ButtonDrawGraph.BackColor = System.Drawing.SystemColors.ButtonHighlight Me.ButtonDrawGraph.FlatAppearance.BorderColor = System.Drawing.Color.Gainsboro Me.ButtonDrawGraph.FlatAppearance.MouseDownBackColor = System.Drawing.Color.White Me.ButtonDrawGraph.FlatAppearance.MouseOverBackColor = System.Drawing.Color.White Me.ButtonDrawGraph.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.ButtonDrawGraph.Font = New System.Drawing.Font("Segoe UI", 13.8!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.ButtonDrawGraph.ForeColor = System.Drawing.SystemColors.ActiveCaptionText Me.ButtonDrawGraph.Location = New System.Drawing.Point(257, 154) Me.ButtonDrawGraph.Margin = New System.Windows.Forms.Padding(0) Me.ButtonDrawGraph.Name = "ButtonDrawGraph" Me.ButtonDrawGraph.Size = New System.Drawing.Size(255, 125) Me.ButtonDrawGraph.TabIndex = 4 Me.ButtonDrawGraph.Text = "Draw Graph" Me.ButtonDrawGraph.UseVisualStyleBackColor = False ' 'MenuStrip ' Me.MenuStrip.BackColor = System.Drawing.Color.FromArgb(CType(CType(250, Byte), Integer), CType(CType(250, Byte), Integer), CType(CType(250, Byte), Integer)) Me.MenuStrip.ImageScalingSize = New System.Drawing.Size(20, 20) Me.MenuStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FileToolStripMenuItem, Me.AboutToolStripMenuItem}) Me.MenuStrip.Location = New System.Drawing.Point(0, 0) Me.MenuStrip.Name = "MenuStrip" Me.MenuStrip.Size = New System.Drawing.Size(513, 28) Me.MenuStrip.TabIndex = 5 Me.MenuStrip.Text = "MenuStrip1" ' 'FileToolStripMenuItem ' Me.FileToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.NewProjectToolStripMenuItem, Me.OpenProjectToolStripMenuItem, Me.ToolStripMenuItem1, Me.SaveToolStripMenuItem, Me.SaveAsToolStripMenuItem, Me.ToolStripMenuItem2, Me.CloseToolStripMenuItem, Me.ToolStripMenuItem5, Me.ExitToolStripMenuItem}) Me.FileToolStripMenuItem.Name = "FileToolStripMenuItem" Me.FileToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Alt Or System.Windows.Forms.Keys.F), System.Windows.Forms.Keys) Me.FileToolStripMenuItem.Size = New System.Drawing.Size(44, 24) Me.FileToolStripMenuItem.Text = "File" ' 'NewProjectToolStripMenuItem ' Me.NewProjectToolStripMenuItem.Name = "NewProjectToolStripMenuItem" Me.NewProjectToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.N), System.Windows.Forms.Keys) Me.NewProjectToolStripMenuItem.Size = New System.Drawing.Size(232, 26) Me.NewProjectToolStripMenuItem.Text = "New..." ' 'OpenProjectToolStripMenuItem ' Me.OpenProjectToolStripMenuItem.Name = "OpenProjectToolStripMenuItem" Me.OpenProjectToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.O), System.Windows.Forms.Keys) Me.OpenProjectToolStripMenuItem.Size = New System.Drawing.Size(232, 26) Me.OpenProjectToolStripMenuItem.Text = "Open Project..." ' 'ToolStripMenuItem1 ' Me.ToolStripMenuItem1.Name = "ToolStripMenuItem1" Me.ToolStripMenuItem1.Size = New System.Drawing.Size(229, 6) ' 'SaveToolStripMenuItem ' Me.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem" Me.SaveToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.S), System.Windows.Forms.Keys) Me.SaveToolStripMenuItem.Size = New System.Drawing.Size(232, 26) Me.SaveToolStripMenuItem.Text = "Save" ' 'SaveAsToolStripMenuItem ' Me.SaveAsToolStripMenuItem.Name = "SaveAsToolStripMenuItem" Me.SaveAsToolStripMenuItem.Size = New System.Drawing.Size(232, 26) Me.SaveAsToolStripMenuItem.Text = "Save As..." ' 'ToolStripMenuItem2 ' Me.ToolStripMenuItem2.Name = "ToolStripMenuItem2" Me.ToolStripMenuItem2.Size = New System.Drawing.Size(229, 6) ' 'CloseToolStripMenuItem ' Me.CloseToolStripMenuItem.Name = "CloseToolStripMenuItem" Me.CloseToolStripMenuItem.Size = New System.Drawing.Size(232, 26) Me.CloseToolStripMenuItem.Text = "Close" ' 'ToolStripMenuItem5 ' Me.ToolStripMenuItem5.Name = "ToolStripMenuItem5" Me.ToolStripMenuItem5.Size = New System.Drawing.Size(229, 6) ' 'ExitToolStripMenuItem ' Me.ExitToolStripMenuItem.Name = "ExitToolStripMenuItem" Me.ExitToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Alt Or System.Windows.Forms.Keys.F4), System.Windows.Forms.Keys) Me.ExitToolStripMenuItem.Size = New System.Drawing.Size(232, 26) Me.ExitToolStripMenuItem.Text = "Exit" ' 'AboutToolStripMenuItem ' Me.AboutToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ViewHelpToolStripMenuItem, Me.ToolStripMenuItem3, Me.SendFeedbackToolStripMenuItem, Me.ToolStripMenuItem4, Me.CheckForUpdatesToolStripMenuItem, Me.AboutToolStripMenuItem1}) Me.AboutToolStripMenuItem.Name = "AboutToolStripMenuItem" Me.AboutToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Alt Or System.Windows.Forms.Keys.H), System.Windows.Forms.Keys) Me.AboutToolStripMenuItem.Size = New System.Drawing.Size(53, 24) Me.AboutToolStripMenuItem.Text = "Help" ' 'ViewHelpToolStripMenuItem ' Me.ViewHelpToolStripMenuItem.Name = "ViewHelpToolStripMenuItem" Me.ViewHelpToolStripMenuItem.Size = New System.Drawing.Size(216, 26) Me.ViewHelpToolStripMenuItem.Text = "View Help" ' 'ToolStripMenuItem3 ' Me.ToolStripMenuItem3.Name = "ToolStripMenuItem3" Me.ToolStripMenuItem3.Size = New System.Drawing.Size(213, 6) ' 'SendFeedbackToolStripMenuItem ' Me.SendFeedbackToolStripMenuItem.Name = "SendFeedbackToolStripMenuItem" Me.SendFeedbackToolStripMenuItem.Size = New System.Drawing.Size(216, 26) Me.SendFeedbackToolStripMenuItem.Text = "Send Feedback" ' 'ToolStripMenuItem4 ' Me.ToolStripMenuItem4.Name = "ToolStripMenuItem4" Me.ToolStripMenuItem4.Size = New System.Drawing.Size(213, 6) ' 'CheckForUpdatesToolStripMenuItem ' Me.CheckForUpdatesToolStripMenuItem.Name = "CheckForUpdatesToolStripMenuItem" Me.CheckForUpdatesToolStripMenuItem.Size = New System.Drawing.Size(216, 26) Me.CheckForUpdatesToolStripMenuItem.Text = "Check for Updates" ' 'AboutToolStripMenuItem1 ' Me.AboutToolStripMenuItem1.Name = "AboutToolStripMenuItem1" Me.AboutToolStripMenuItem1.Size = New System.Drawing.Size(216, 26) Me.AboutToolStripMenuItem1.Text = "About" ' 'MainForm ' Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 16.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.SystemColors.Window Me.ClientSize = New System.Drawing.Size(513, 280) Me.Controls.Add(Me.ButtonReadIn) Me.Controls.Add(Me.ButtonDrawGraph) Me.Controls.Add(Me.ButtonSearchView) Me.Controls.Add(Me.ButtonModifyDelete) Me.Controls.Add(Me.MenuStrip) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Location = New System.Drawing.Point(320, 200) Me.MainMenuStrip = Me.MenuStrip Me.MaximizeBox = False Me.Name = "MainForm" Me.ShowIcon = False Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual Me.Text = "Network Planning" Me.MenuStrip.ResumeLayout(False) Me.MenuStrip.PerformLayout() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents ButtonReadIn As Windows.Forms.Button Friend WithEvents ButtonModifyDelete As Windows.Forms.Button Friend WithEvents ButtonSearchView As Windows.Forms.Button Friend WithEvents ButtonDrawGraph As Windows.Forms.Button Friend WithEvents MenuStrip As Windows.Forms.MenuStrip Friend WithEvents FileToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents NewProjectToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents OpenProjectToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents SaveToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents SaveAsToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents ExitToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents AboutToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripMenuItem1 As Windows.Forms.ToolStripSeparator Friend WithEvents ToolStripMenuItem2 As Windows.Forms.ToolStripSeparator Friend WithEvents CloseToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripMenuItem5 As Windows.Forms.ToolStripSeparator Friend WithEvents ViewHelpToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripMenuItem3 As Windows.Forms.ToolStripSeparator Friend WithEvents SendFeedbackToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents ToolStripMenuItem4 As Windows.Forms.ToolStripSeparator Friend WithEvents CheckForUpdatesToolStripMenuItem As Windows.Forms.ToolStripMenuItem Friend WithEvents AboutToolStripMenuItem1 As Windows.Forms.ToolStripMenuItem End Class
13,739
https://github.com/xundeenergie/myshellconfig/blob/master/bash_completion.d/setproxy
Github Open Source
Open Source
MIT
2,021
myshellconfig
xundeenergie
Shell
Code
59
234
#!/bin/bash function _proxycreds() { KEYS="" for KEY_DIR in ${SETPROXY_CREDS_DIRS[*]};do KEYS="${KEYS} $(find ${KEY_DIR} -type f -name "*.conf" -exec basename {} \; 2>/dev/null |sed 's/\.conf$//')" done echo $KEYS } function _proxyfiles() { COMPREPLY=() local CUR KEYS CUR="${COMP_WORDS[COMP_CWORD]}" #KEYS="$(find ${KEY_DIR}/* -type f|awk -F ${KEY_DIR}/ '{print $2}'|sed 's/\.session$//')" KEYS=$(_proxycreds) COMPREPLY=( $(compgen -W "${KEYS}" -- ${CUR}) ) return 0 } complete -F _proxyfiles setproxy
7,057
https://github.com/sergiopvilar/limarka-projeto-integrador/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,020
limarka-projeto-integrador
sergiopvilar
Ignore List
Code
3
13
xxx-* Gemfile.lock *.pdf
35,656
https://github.com/gatsby-tv/icons/blob/master/src/components/Playlist.tsx
Github Open Source
Open Source
MIT
null
icons
gatsby-tv
TypeScript
Code
35
193
import * as React from "react"; function SvgPlaylist() { return ( <svg id="gz-svg-playlist" aria-hidden="true" viewBox="0 0 540 540" width="1em" height="1em" > <path id="playlist" fill="currentcolor" d="M235.406 71.731v49.618h255.735v135.767H540V71.731zM123.11 151.35v57.287h282.012v149.47h56.02V151.35zM0 238.636v229.633h375.121V238.636z" /> </svg> ); } export default SvgPlaylist;
28,882
https://github.com/jack1981/BABEL/blob/master/benchmark-data-generation/src/main/java/tn/lipsic/babel/package-info.java
Github Open Source
Open Source
Apache-2.0
2,020
BABEL
jack1981
Java
Code
2
13
package tn.lipsic.babel;
1,156
https://github.com/clun/spring-data-cassandra/blob/master/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/core/cql/ReactiveCqlTemplateUnitTests.java
Github Open Source
Open Source
Apache-2.0
2,020
spring-data-cassandra
clun
Java
Code
1,728
9,526
/* * Copyright 2016-2020 the original author or authors. * * 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 * * https://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 org.springframework.data.cassandra.core.cql; import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.data.cassandra.CassandraConnectionFailureException; import org.springframework.data.cassandra.CassandraInvalidQueryException; import org.springframework.data.cassandra.ReactiveResultSet; import org.springframework.data.cassandra.ReactiveSession; import org.springframework.data.cassandra.ReactiveSessionFactory; import org.springframework.data.cassandra.core.cql.session.DefaultReactiveSessionFactory; import org.springframework.lang.Nullable; import com.datastax.oss.driver.api.core.ConsistencyLevel; import com.datastax.oss.driver.api.core.DefaultConsistencyLevel; import com.datastax.oss.driver.api.core.NoNodeAvailableException; import com.datastax.oss.driver.api.core.cql.BoundStatement; import com.datastax.oss.driver.api.core.cql.ColumnDefinitions; import com.datastax.oss.driver.api.core.cql.PreparedStatement; import com.datastax.oss.driver.api.core.cql.Row; import com.datastax.oss.driver.api.core.cql.SimpleStatement; import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.driver.api.core.servererrors.InvalidQueryException; /** * Unit tests for {@link ReactiveCqlTemplate}. * * @author Mark Paluch */ @RunWith(MockitoJUnitRunner.class) public class ReactiveCqlTemplateUnitTests { @Mock ReactiveSession session; @Mock ReactiveResultSet reactiveResultSet; @Mock Row row; @Mock PreparedStatement preparedStatement; @Mock BoundStatement boundStatement; @Mock ColumnDefinitions columnDefinitions; ReactiveCqlTemplate template; ReactiveSessionFactory sessionFactory; @Before public void setup() throws Exception { this.sessionFactory = new DefaultReactiveSessionFactory(session); this.template = new ReactiveCqlTemplate(sessionFactory); } // ------------------------------------------------------------------------- // Tests dealing with a plain org.springframework.data.cassandra.core.cql.ReactiveSession // ------------------------------------------------------------------------- @Test // DATACASS-335 public void executeCallbackShouldExecuteDeferred() { Flux<String> flux = template.execute((ReactiveSessionCallback<String>) session -> { session.close(); return Mono.just("OK"); }); verify(session, never()).close(); flux.as(StepVerifier::create).expectNext("OK").verifyComplete(); verify(session).close(); } @Test // DATACASS-335 public void executeCallbackShouldTranslateExceptions() { Flux<String> flux = template.execute((ReactiveSessionCallback<String>) session -> { throw new InvalidQueryException(null, "wrong query"); }); flux.as(StepVerifier::create).expectError(CassandraInvalidQueryException.class).verify(); } @Test // DATACASS-335 public void executeCqlShouldExecuteDeferred() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); Mono<Boolean> mono = template.execute("UPDATE user SET a = 'b';"); verifyZeroInteractions(session); mono.as(StepVerifier::create).expectNext(false).verifyComplete(); verify(session).execute(any(Statement.class)); } @Test // DATACASS-335 public void executeCqlShouldTranslateExceptions() { when(session.execute(any(Statement.class))).thenThrow(new NoNodeAvailableException()); Mono<Boolean> mono = template.execute("UPDATE user SET a = 'b';"); mono.as(StepVerifier::create).expectError(CassandraConnectionFailureException.class).verify(); } // ------------------------------------------------------------------------- // Tests dealing with static CQL // ------------------------------------------------------------------------- @Test // DATACASS-335 public void executeCqlShouldCallExecution() { doTestStrings(reactiveCqlTemplate -> { reactiveCqlTemplate.execute("SELECT * from USERS").as(StepVerifier::create).expectNextCount(1).verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void executeCqlWithArgumentsShouldCallExecution() { doTestStrings(5, DefaultConsistencyLevel.ONE, null, "foo", reactiveCqlTemplate -> { reactiveCqlTemplate.execute("SELECT * from USERS").as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void queryForResultSetShouldCallExecution() { doTestStrings(reactiveCqlTemplate -> { Mono<ReactiveResultSet> mono = reactiveCqlTemplate.queryForResultSet("SELECT * from USERS"); mono.flatMapMany(ReactiveResultSet::rows).as(StepVerifier::create).expectNextCount(3).verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void queryWithResultSetExtractorShouldCallExecution() { doTestStrings(reactiveCqlTemplate -> { Flux<String> flux = reactiveCqlTemplate.query("SELECT * from USERS", (row, index) -> row.getString(0)); flux.as(StepVerifier::create).expectNext("Walter", "Hank", " Jesse").verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void queryWithResultSetExtractorWithArgumentsShouldCallExecution() { doTestStrings(5, ConsistencyLevel.ONE, null, "foo", reactiveCqlTemplate -> { Flux<String> flux = reactiveCqlTemplate.query("SELECT * from USERS", (row, index) -> row.getString(0)); flux.as(StepVerifier::create).expectNext("Walter", "Hank", " Jesse").verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void queryCqlShouldExecuteDeferred() { when(reactiveResultSet.wasApplied()).thenReturn(true); when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); Flux<Boolean> flux = template.query("UPDATE user SET a = 'b';", resultSet -> Mono.just(resultSet.wasApplied())); verifyZeroInteractions(session); flux.as(StepVerifier::create).expectNext(true).verifyComplete(); verify(session).execute(any(Statement.class)); } @Test // DATACASS-335 public void queryCqlShouldTranslateExceptions() { when(session.execute(any(Statement.class))).thenThrow(new NoNodeAvailableException()); Flux<Boolean> flux = template.query("UPDATE user SET a = 'b';", resultSet -> Mono.just(resultSet.wasApplied())); flux.as(StepVerifier::create).expectError(CassandraConnectionFailureException.class).verify(); } @Test // DATACASS-335 public void queryForObjectCqlShouldBeEmpty() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.empty()); Mono<String> mono = template.queryForObject("SELECT * FROM user", (row, rowNum) -> "OK"); mono.as(StepVerifier::create).verifyComplete(); } @Test // DATACASS-335 public void queryForObjectCqlShouldReturnRecord() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); Mono<String> mono = template.queryForObject("SELECT * FROM user", (row, rowNum) -> "OK"); mono.as(StepVerifier::create).expectNext("OK").verifyComplete(); } @Test // DATACASS-335 public void queryForObjectCqlShouldReturnNullValue() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); Mono<String> mono = template.queryForObject("SELECT * FROM user", (row, rowNum) -> null); mono.as(StepVerifier::create).verifyComplete(); } @Test // DATACASS-335 public void queryForObjectCqlShouldFailReturningManyRecords() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); Mono<String> mono = template.queryForObject("SELECT * FROM user", (row, rowNum) -> "OK"); mono.as(StepVerifier::create).expectError(IncorrectResultSizeDataAccessException.class).verify(); } @Test // DATACASS-335 public void queryForObjectCqlWithTypeShouldReturnRecord() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); when(row.getColumnDefinitions()).thenReturn(columnDefinitions); when(columnDefinitions.size()).thenReturn(1); when(row.getString(0)).thenReturn("OK"); Mono<String> mono = template.queryForObject("SELECT * FROM user", String.class); mono.as(StepVerifier::create).expectNext("OK").verifyComplete(); } @Test // DATACASS-335 public void queryForFluxCqlWithTypeShouldReturnRecord() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); when(row.getColumnDefinitions()).thenReturn(columnDefinitions); when(columnDefinitions.size()).thenReturn(1); when(row.getString(0)).thenReturn("OK", "NOT OK"); Flux<String> flux = template.queryForFlux("SELECT * FROM user", String.class); flux.as(StepVerifier::create).expectNext("OK", "NOT OK").verifyComplete(); } @Test // DATACASS-335 public void queryForRowsCqlReturnRows() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); Flux<Row> flux = template.queryForRows("SELECT * FROM user"); flux.as(StepVerifier::create).expectNext(row, row).verifyComplete(); } @Test // DATACASS-335 public void executeCqlShouldReturnWasApplied() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.wasApplied()).thenReturn(true); Mono<Boolean> mono = template.execute("UPDATE user SET a = 'b';"); mono.as(StepVerifier::create).expectNext(true).verifyComplete(); } @Test // DATACASS-335 public void executeCqlPublisherShouldReturnWasApplied() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.wasApplied()).thenReturn(true, false); Flux<Boolean> flux = template.execute(Flux.just("UPDATE user SET a = 'b';", "UPDATE user SET x = 'y';")); verifyZeroInteractions(session); flux.as(StepVerifier::create).expectNext(true).expectNext(false).verifyComplete(); verify(session, times(2)).execute(any(Statement.class)); } // ------------------------------------------------------------------------- // Tests dealing with com.datastax.oss.driver.api.core.cql.Statement // ------------------------------------------------------------------------- @Test // DATACASS-335 public void executeStatementShouldCallExecution() { doTestStrings(reactiveCqlTemplate -> { reactiveCqlTemplate.execute(SimpleStatement.newInstance("SELECT * from USERS")).as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void executeStatementWithArgumentsShouldCallExecution() { doTestStrings(5, ConsistencyLevel.ONE, DefaultConsistencyLevel.EACH_QUORUM, "foo", reactiveCqlTemplate -> { reactiveCqlTemplate.execute(SimpleStatement.newInstance("SELECT * from USERS")).as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void queryForResultStatementSetShouldCallExecution() { doTestStrings(reactiveCqlTemplate -> { reactiveCqlTemplate.queryForResultSet(SimpleStatement.newInstance("SELECT * from USERS")) .flatMapMany(ReactiveResultSet::rows).as(StepVerifier::create) // .expectNextCount(3) // .verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void queryWithResultSetStatementExtractorShouldCallExecution() { doTestStrings(reactiveCqlTemplate -> { Flux<String> flux = reactiveCqlTemplate.query(SimpleStatement.newInstance("SELECT * from USERS"), (row, index) -> row.getString(0)); flux.as(StepVerifier::create).expectNext("Walter", "Hank", " Jesse").verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void queryWithResultSetStatementExtractorWithArgumentsShouldCallExecution() { doTestStrings(5, ConsistencyLevel.ONE, null, "foo", reactiveCqlTemplate -> { Flux<String> flux = reactiveCqlTemplate.query(SimpleStatement.newInstance("SELECT * from USERS"), (row, index) -> row.getString(0)); flux.collectList().as(StepVerifier::create).consumeNextWith(rows -> { assertThat(rows).hasSize(3).contains("Walter", "Hank", " Jesse"); }).verifyComplete(); verify(session).execute(any(Statement.class)); }); } @Test // DATACASS-335 public void queryStatementShouldExecuteDeferred() { when(reactiveResultSet.wasApplied()).thenReturn(true); when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); Flux<Boolean> flux = template.query(SimpleStatement.newInstance("UPDATE user SET a = 'b';"), resultSet -> Mono.just(resultSet.wasApplied())); verifyZeroInteractions(session); flux.as(StepVerifier::create).expectNext(true).verifyComplete(); verify(session).execute(any(Statement.class)); } @Test // DATACASS-335 public void queryStatementShouldTranslateExceptions() { when(session.execute(any(Statement.class))).thenThrow(new NoNodeAvailableException()); Flux<Boolean> flux = template.query(SimpleStatement.newInstance("UPDATE user SET a = 'b';"), resultSet -> Mono.just(resultSet.wasApplied())); flux.as(StepVerifier::create).expectError(CassandraConnectionFailureException.class).verify(); } @Test // DATACASS-335 public void queryForObjectStatementShouldBeEmpty() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.empty()); Mono<String> mono = template.queryForObject(SimpleStatement.newInstance("SELECT * FROM user"), (row, rowNum) -> "OK"); mono.as(StepVerifier::create).verifyComplete(); } @Test // DATACASS-335 public void queryForObjectStatementShouldReturnRecord() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); Mono<String> mono = template.queryForObject(SimpleStatement.newInstance("SELECT * FROM user"), (row, rowNum) -> "OK"); mono.as(StepVerifier::create).expectNext("OK").verifyComplete(); } @Test // DATACASS-335 public void queryForObjectStatementShouldReturnNullValue() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); Mono<String> mono = template.queryForObject(SimpleStatement.newInstance("SELECT * FROM user"), (row, rowNum) -> null); mono.as(StepVerifier::create).verifyComplete(); } @Test // DATACASS-335 public void queryForObjectStatementShouldFailReturningManyRecords() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); Mono<String> mono = template.queryForObject(SimpleStatement.newInstance("SELECT * FROM user"), (row, rowNum) -> "OK"); mono.as(StepVerifier::create).expectError(IncorrectResultSizeDataAccessException.class).verify(); } @Test // DATACASS-335 public void queryForObjectStatementWithTypeShouldReturnRecord() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); when(row.getColumnDefinitions()).thenReturn(columnDefinitions); when(columnDefinitions.size()).thenReturn(1); when(row.getString(0)).thenReturn("OK"); Mono<String> mono = template.queryForObject(SimpleStatement.newInstance("SELECT * FROM user"), String.class); mono.as(StepVerifier::create).expectNext("OK").verifyComplete(); } @Test // DATACASS-335 public void queryForFluxStatementWithTypeShouldReturnRecord() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); when(row.getColumnDefinitions()).thenReturn(columnDefinitions); when(columnDefinitions.size()).thenReturn(1); when(row.getString(0)).thenReturn("OK", "NOT OK"); Flux<String> flux = template.queryForFlux(SimpleStatement.newInstance("SELECT * FROM user"), String.class); flux.as(StepVerifier::create).expectNext("OK", "NOT OK").verifyComplete(); } @Test // DATACASS-335 public void queryForRowsStatementReturnRows() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); Flux<Row> flux = template.queryForRows(SimpleStatement.newInstance("SELECT * FROM user")); flux.as(StepVerifier::create).expectNext(row, row).verifyComplete(); } @Test // DATACASS-335 public void executeStatementShouldReturnWasApplied() { when(session.execute(any(Statement.class))).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.wasApplied()).thenReturn(true); template.execute(SimpleStatement.newInstance("UPDATE user SET a = 'b';")).as(StepVerifier::create).expectNext(true) .verifyComplete(); } // ------------------------------------------------------------------------- // Methods dealing with prepared statements // ------------------------------------------------------------------------- @Test // DATACASS-335 public void queryPreparedStatementWithCallbackShouldCallExecution() { doTestStrings(reactiveCqlTemplate -> { Flux<Row> flux = reactiveCqlTemplate.execute("SELECT * from USERS", (session, ps) -> { return session.execute(ps.bind("A")).flatMapMany(ReactiveResultSet::rows); }); flux.as(StepVerifier::create).expectNextCount(3).verifyComplete(); }); } @Test // DATACASS-335 public void executePreparedStatementWithCallbackShouldCallExecution() { doTestStrings(reactiveCqlTemplate -> { Mono<Boolean> applied = reactiveCqlTemplate.execute("UPDATE users SET name = ?", "White"); when(this.preparedStatement.bind("White")).thenReturn(this.boundStatement); when(this.reactiveResultSet.wasApplied()).thenReturn(true); applied.as(StepVerifier::create).expectNext(true).verifyComplete(); }); } @Test // DATACASS-335 public void executePreparedStatementCallbackShouldExecuteDeferred() { when(session.prepare(anyString())).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind()).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); Flux<ReactiveResultSet> flux = template.execute("UPDATE user SET a = 'b';", (session, ps) -> session.execute(ps.bind())); verifyZeroInteractions(session); flux.as(StepVerifier::create).expectNext(reactiveResultSet).verifyComplete(); verify(session).prepare(anyString()); verify(session).execute(boundStatement); } @Test // DATACASS-335 public void executePreparedStatementCreatorShouldExecuteDeferred() { when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); Flux<ReactiveResultSet> flux = template.execute(session -> Mono.just(preparedStatement), (session, ps) -> session.execute(boundStatement)); verifyZeroInteractions(session); flux.as(StepVerifier::create).expectNext(reactiveResultSet).verifyComplete(); verify(session).execute(boundStatement); } @Test // DATACASS-335 public void executePreparedStatementCreatorShouldTranslateStatementCreationExceptions() { Flux<ReactiveResultSet> flux = template.execute(session -> { throw new NoNodeAvailableException(); }, (session, ps) -> session.execute(boundStatement)); flux.as(StepVerifier::create).expectError(CassandraConnectionFailureException.class).verify(); } @Test // DATACASS-335 public void executePreparedStatementCreatorShouldTranslateStatementCallbackExceptions() { Flux<ReactiveResultSet> flux = template.execute(session -> Mono.just(preparedStatement), (session, ps) -> { throw new NoNodeAvailableException(); }); flux.as(StepVerifier::create).expectError(CassandraConnectionFailureException.class).verify(); } @Test // DATACASS-335 public void queryPreparedStatementCreatorShouldReturnResult() { when(preparedStatement.bind()).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); Flux<Row> flux = template.query(session -> Mono.just(preparedStatement), ReactiveResultSet::rows); verifyZeroInteractions(session); flux.as(StepVerifier::create).expectNext(row).verifyComplete(); verify(preparedStatement).bind(); } @Test // DATACASS-335 public void queryPreparedStatementCreatorAndBinderShouldReturnResult() { when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); Flux<Row> flux = template.query(session -> Mono.just(preparedStatement), ps -> { ps.bind("a", "b"); return boundStatement; }, ReactiveResultSet::rows); verifyZeroInteractions(session); flux.as(StepVerifier::create).expectNext(row).verifyComplete(); verify(preparedStatement).bind("a", "b"); } @Test // DATACASS-335 public void queryPreparedStatementCreatorAndBinderAndMapperShouldReturnResult() { when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); Flux<Row> flux = template.query(session -> Mono.just(preparedStatement), ps -> { ps.bind("a", "b"); return boundStatement; }, (row, rowNum) -> row); verifyZeroInteractions(session); flux.as(StepVerifier::create).expectNext(row).verifyComplete(); verify(preparedStatement).bind("a", "b"); } @Test // DATACASS-335 public void queryForObjectPreparedStatementShouldBeEmpty() { when(session.prepare("SELECT * FROM user WHERE username = ?")).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind("Walter")).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.empty()); Mono<String> mono = template.queryForObject("SELECT * FROM user WHERE username = ?", (row, rowNum) -> "OK", "Walter"); mono.as(StepVerifier::create).verifyComplete(); } @Test // DATACASS-335 public void queryForObjectPreparedStatementShouldReturnRecord() { when(session.prepare("SELECT * FROM user WHERE username = ?")).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind("Walter")).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); Mono<String> mono = template.queryForObject("SELECT * FROM user WHERE username = ?", (row, rowNum) -> "OK", "Walter"); mono.as(StepVerifier::create).expectNext("OK").verifyComplete(); } @Test // DATACASS-335 public void queryForObjectPreparedStatementShouldFailReturningManyRecords() { when(session.prepare("SELECT * FROM user WHERE username = ?")).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind("Walter")).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); Mono<String> mono = template.queryForObject("SELECT * FROM user WHERE username = ?", (row, rowNum) -> "OK", "Walter"); mono.as(StepVerifier::create).expectError(IncorrectResultSizeDataAccessException.class).verify(); } @Test // DATACASS-335 public void queryForObjectPreparedStatementWithTypeShouldReturnRecord() { when(session.prepare("SELECT * FROM user WHERE username = ?")).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind("Walter")).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row)); when(row.getColumnDefinitions()).thenReturn(columnDefinitions); when(columnDefinitions.size()).thenReturn(1); when(row.getString(0)).thenReturn("OK"); Mono<String> mono = template.queryForObject("SELECT * FROM user WHERE username = ?", String.class, "Walter"); mono.as(StepVerifier::create).expectNext("OK").verifyComplete(); } @Test // DATACASS-335 public void queryForFluxPreparedStatementWithTypeShouldReturnRecord() { when(session.prepare("SELECT * FROM user WHERE username = ?")).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind("Walter")).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); when(row.getColumnDefinitions()).thenReturn(columnDefinitions); when(columnDefinitions.size()).thenReturn(1); when(row.getString(0)).thenReturn("OK", "NOT OK"); Flux<String> flux = template.queryForFlux("SELECT * FROM user WHERE username = ?", String.class, "Walter"); flux.as(StepVerifier::create).expectNext("OK", "NOT OK").verifyComplete(); } @Test // DATACASS-335 public void queryForRowsPreparedStatementReturnRows() { when(session.prepare("SELECT * FROM user WHERE username = ?")).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind("Walter")).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.rows()).thenReturn(Flux.just(row, row)); Flux<Row> flux = template.queryForRows("SELECT * FROM user WHERE username = ?", "Walter"); flux.as(StepVerifier::create).expectNextCount(2).verifyComplete(); } @Test // DATACASS-335 public void updatePreparedStatementShouldReturnApplied() { when(session.prepare("UPDATE user SET username = ?")).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind("Walter")).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.wasApplied()).thenReturn(true); Mono<Boolean> mono = template.execute("UPDATE user SET username = ?", "Walter"); mono.as(StepVerifier::create).expectNext(true).verifyComplete(); } @Test // DATACASS-335 public void updatePreparedStatementArgsPublisherShouldReturnApplied() { when(session.prepare("UPDATE user SET username = ?")).thenReturn(Mono.just(preparedStatement)); when(preparedStatement.bind("Walter")).thenReturn(boundStatement); when(preparedStatement.bind("Hank")).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(Mono.just(reactiveResultSet)); when(reactiveResultSet.wasApplied()).thenReturn(true); Flux<Boolean> flux = template.execute("UPDATE user SET username = ?", Flux.just(new Object[] { "Walter" }, new Object[] { "Hank" })); flux.as(StepVerifier::create).expectNext(true, true).verifyComplete(); verify(session, atMost(1)).prepare("UPDATE user SET username = ?"); verify(session, times(2)).execute(boundStatement); } private void doTestStrings(Consumer<ReactiveCqlTemplate> cqlTemplateConsumer) { doTestStrings(null, null, null, null, cqlTemplateConsumer); } private void doTestStrings(@Nullable Integer fetchSize, @Nullable ConsistencyLevel consistencyLevel, @Nullable ConsistencyLevel serialConsistencyLevel, @Nullable String executionProfile, Consumer<ReactiveCqlTemplate> cqlTemplateConsumer) { String[] results = { "Walter", "Hank", " Jesse" }; when(this.session.execute((Statement) any())).thenReturn(Mono.just(reactiveResultSet)); when(this.reactiveResultSet.rows()).thenReturn(Flux.just(row, row, row)); when(this.row.getString(0)).thenReturn(results[0], results[1], results[2]); when(this.session.prepare(anyString())).thenReturn(Mono.just(this.preparedStatement)); ReactiveCqlTemplate template = new ReactiveCqlTemplate(); template.setSessionFactory(this.sessionFactory); if (fetchSize != null) { template.setFetchSize(fetchSize); } if (consistencyLevel != null) { template.setConsistencyLevel(consistencyLevel); } if (serialConsistencyLevel != null) { template.setSerialConsistencyLevel(serialConsistencyLevel); } if (executionProfile != null) { template.setExecutionProfile(executionProfile); } cqlTemplateConsumer.accept(template); ArgumentCaptor<Statement> statementArgumentCaptor = ArgumentCaptor.forClass(Statement.class); verify(this.session).execute(statementArgumentCaptor.capture()); Statement statement = statementArgumentCaptor.getValue(); if (fetchSize != null) { assertThat(statement.getPageSize()).isEqualTo(fetchSize.intValue()); } if (consistencyLevel != null) { assertThat(statement.getConsistencyLevel()).isEqualTo(consistencyLevel); } if (serialConsistencyLevel != null) { assertThat(statement.getSerialConsistencyLevel()).isEqualTo(serialConsistencyLevel); } if (executionProfile != null) { assertThat(statement.getExecutionProfileName()).isEqualTo(executionProfile); } } }
3,898
https://github.com/sungdoolim/kotlin_practice/blob/master/prackot/src/prj2.java
Github Open Source
Open Source
Apache-2.0
null
kotlin_practice
sungdoolim
Java
Code
710
3,058
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Scanner; public class prj2 { static int COUNT=0; static int DENOVCOUNT=0; // 50만 //1000/5000-10 27% 잘 안되네 //1000/5000/ 7 //1000/7000/ 10 0.034% / 0.09 /0.09 //1500 5000 500000 10 0.4% / 7 / 잘 안도미 //250 20000 500000 10 0.3// 잘 안됨 //500000 2000 3000 10 0.49 0.41 0.3 0.449 0.47 //10만 //10만 100/2000/ 10 실패 // 10만/ 200/3000/ 10 실패 // 10만 / 500/1000/10 실패 //10만 500 2000 100000 10 0.3 /0.4/0.4/0.4 //100000 500 2000 10 //250 4000 100000 10 0.46 /6% 간혹 실패 //5만 //50000 300 2500 10 0.75% /0.67 /0.91/0.91 //250 2000 50000 10 0.28% 0.4% /0.44% 간혹 실패.... @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); System.out.print("mydna의 길이 입력 : "); int l=sc.nextInt();//50만 System.out.print("shortread 문자열 하나의 길이 입력 : "); int k=sc.nextInt();//50만 기준 2000 System.out.print("shortread 개수 입력: "); int n=sc.nextInt();//50만 기준 3000 makemydna.make(k,n,l); ArrayList<String> shortread=fileshort(); System.out.println("일치 최소 개수 입력 : "); int r=sc.nextInt(); // 몇개까지 일치하면 합칠 것 인지를 결정합니다. double beforeTime = System.currentTimeMillis(); //코드 실행 전에 시간 받아오기 brute(shortread,r,l,k); double afterTime = System.currentTimeMillis(); // 코드 실행 후에 시간 받아오기 double msecDiffTime = (afterTime - beforeTime); //두 시간에 차 계산 // System.out.println(COUNT); sc.close(); System.out.println("restricted denov"); compare_denov.compare(l); System.out.println("Excuting Time : "+msecDiffTime/1000+"seconds"); // beforeTime = System.currentTimeMillis(); //코드 실행 전에 시간 받아오기 System.out.println("trivial : "); trivial.triv(k, n, l); // // afterTime = System.currentTimeMillis(); // 코드 실행 후에 시간 받아오기 // msecDiffTime = (afterTime - beforeTime); //두 시간에 차 계산 // System.out.println("Excuting Time : "+msecDiffTime/1000+"seconds"); } @SuppressWarnings("unchecked") static void brute(ArrayList<String>shortread,int r,int l,int k) throws IOException { System.out.println("length = "+shortread.size()); denov(shortread,shortread.remove(0),r,l,k); // 첫 번째 shortread를 시작으로 하여 알고리즘을 진행합니다. // 제한 사항 - shortread의 0번 인덱스를 항상 시작 점으로 둔다(mydna의 시작점을 shortread의 0범 인덱스에 저장 시켜 놓음) // 바로 밑에 주석처리 코드는 원래 denove알고리즘의 목적과 맞지만, bruteforce로서 상당한 시간을 요구하기에 위 처럼 제한 사항을 둡니다. // ArrayList<String> shorttmp; // for(int i=0;i<shortread.size();i++){System.out.println(i); // shorttmp=(ArrayList<String>) shortread.clone(); // denov(shorttmp,shorttmp.remove(i),r,l,k); // } // } @SuppressWarnings("unchecked") static int denov(ArrayList<String> shorttmp,String res,int r,int l,int k) throws IOException { DENOVCOUNT++; String result=res; System.out.println("count: "+DENOVCOUNT+", "+result.length()); // if(DENOVCOUNT>=400){ // // 재귀적으로 호출하는 함수가 1000회 이상일 때 어느정도 길이가 만들어 졌다면 파일에 쓰고 메서드를 종료합니다 // if(result.length()>l*0.95) // { writefile(result); // return 1;} // return 1; //// else if(result.length()<l*0.75) { //// //길이가 75% 미만이 만들어 졌다면 계속 진행합니다. //// return 0; //// } // // } String compare,subtmp, subtmp2, subtmp3; int d,j,rl,rindex,ret,subrl; ArrayList<String>tmp; int len=shorttmp.size(); for(j=0;j<len;j++) { if(result.length()>=l*0.995) { // 반복을 하다 99.5%에 달하는 길이의 문자열이 완성되면 메서드를 끝냅니다. // 이는 무수히 많은 경우가 나올 수 있지만, 반복되는 경우가 많기에 메서드를 끝내도 된다 판단했습니다. writefile(result); return 1; } compare=shorttmp.get(j);//현재 완성시킬 result문자열과 비교를 할 shortread를 가져옵니다. subtmp=compare.substring(0,r);//shortread에서 r개만큼 앞 부분을 따로 저장을 합니다. subtmp2=compare.substring(r);// 위 코드의 나머지 부분을 따로 저장합니다. if(result.contains(subtmp)) {// result문자에 shortread의 앞 부분이 포함되는지를 확인합니다. rindex=result.lastIndexOf(subtmp); rl=result.length(); subrl=rl-rindex; if(subrl==r) {// result에 비교하는 shortread의 앞 부분이 포함되어 있고, 포함된 인덱스와 result의 길이의 차이가 0이라면 // 즉 result의 맨 끝 부분과 이어 붙일 shortread의 앞 부분이 일치한다면 일치하는 부분을 제외한 나머지 부분을 result에 더하여 저장합니다. result+=subtmp2; tmp=(ArrayList<String>) shorttmp.clone(); tmp.remove(j);//len--; //Collections.shuffle(tmp); ret= denov(tmp,result,r,l,k);// 성공적으로 이었다면 이은 shortread는 제거하고, 다시 denov 메서드를 재귀 호출 합니다. if(ret==1) {return 1;} }else if(subrl<k&&subrl>r) { //result에 비교하는 shortread의 앞 부분이 포함되어 있고, 포함된 인덱스와 result의 길이의 차이가 shortread의 길이보다 작다면, // 즉 일치하는 부분이 임의로 정한 숫자보다 많은 경우 d=subrl-r; subtmp3=subtmp2.substring(0,d);// 차이나는 만큼 다시 스트링을 따로 저장하며 이 부분도 result에 포함되는지를 비교합니다. if(result.substring(rl-d).equals(subtmp3)) {// result와 같다면 이어 붙입니다. result+=subtmp2.substring(d); tmp=(ArrayList<String>) shorttmp.clone(); tmp.remove(j);//len--; // Collections.shuffle(tmp); ret= denov(tmp,result,r,l,k); if (ret==1) { return 1;} } } } } if(result.length()>=l*0.995) { // 길이가 어느정도 (99.5%로 정함) 길게 나왔다면 파일에 쓰고 메서드를 종료합니다. // 길이가 길게 나오는 경우가 상당히 많지만 같은 문자열이 반복되는 경우가 대부분이라 하나의 문자열만을 비교합니다. writefile(result); return 1; } return 0; } static void writefile(String result) throws IOException{ try { System.out.println("write"); PrintWriter pw; pw = new PrintWriter("C:/Users/bohee/Desktop/denov.txt"); pw.print(result); pw.close(); // BufferedWriter bw=new BufferedWriter(new FileWriter("C:/Users/bohee/Desktop/denov.txt",true)); // PrintWriter pw; // pw = new PrintWriter(bw,true); // // pw.println(result); // pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } static ArrayList<String> fileshort() { ArrayList<String> strlist=new ArrayList<String>(); BufferedReader br; try { String str; br = new BufferedReader(new FileReader("C:/Users/bohee/Desktop/shortread.txt")); while(true) { str=br.readLine(); if(str==null) { break;} strlist.add(str); }br.close(); } catch ( IOException e) { e.printStackTrace(); } return strlist; } }
6,531
https://github.com/GBLodb/pyrotech-1.12/blob/master/src/main/java/com/codetaylor/mc/pyrotech/modules/core/event/StrawBedEventHandler.java
Github Open Source
Open Source
Apache-2.0
2,020
pyrotech-1.12
GBLodb
Java
Code
189
813
package com.codetaylor.mc.pyrotech.modules.core.event; import com.codetaylor.mc.pyrotech.modules.core.ModuleCore; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerSetSpawnEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.util.ArrayList; import java.util.List; public class StrawBedEventHandler { private final Int2ObjectMap<List<BlockPos>> usedBeds; public StrawBedEventHandler() { this.usedBeds = new Int2ObjectOpenHashMap<>(); this.usedBeds.defaultReturnValue(null); } @SubscribeEvent public void on(TickEvent.WorldTickEvent event) { if (event.phase != TickEvent.Phase.END) { return; } World world = event.world; if (world.isRemote) { return; } int dimensionId = world.provider.getDimension(); List<BlockPos> blockPosList = this.usedBeds.get(dimensionId); if (blockPosList == null || blockPosList.isEmpty()) { return; } for (BlockPos blockPos : blockPosList) { IBlockState blockState = world.getBlockState(blockPos); Block block = blockState.getBlock(); if (block == ModuleCore.Blocks.STRAW_BED && world.isDaytime()) { world.destroyBlock(blockPos, false); } } blockPosList.clear(); } @SubscribeEvent public void on(PlayerSetSpawnEvent event) { EntityPlayer player = event.getEntityPlayer(); World world = player.world; if (world.isRemote) { return; } BlockPos bedLocation = player.bedLocation; if (bedLocation == null) { return; } IBlockState blockState = world.getBlockState(bedLocation); Block block = blockState.getBlock(); if (block == ModuleCore.Blocks.STRAW_BED) { this.addUsedBed(world, bedLocation); event.setCanceled(true); } } private void addUsedBed(World world, BlockPos pos) { int dimensionId = world.provider.getDimension(); List<BlockPos> blockPosList = this.usedBeds.get(dimensionId); if (blockPosList == null) { blockPosList = new ArrayList<>(); this.usedBeds.put(dimensionId, blockPosList); } blockPosList.add(pos); } }
27,125
https://github.com/evvvrado/enafdigital/blob/master/public/site/css/scss/_hoteis.scss
Github Open Source
Open Source
MIT
null
enafdigital
evvvrado
SCSS
Code
303
1,154
.s_hoteis { padding-top: 8.95rem; padding-bottom: 6.35rem; .container-fav { .title { margin-bottom: 1.9rem; width: 100%; @include flex(row, center, space-between); h4 { color: $color-second; font-weight: 60x "" 0; font-size: 50px; line-height: 59px; letter-spacing: 0.02em; } } ._hoteisList { @include flex(row, center, space-between); ._hotel { border: 1px solid #ececec; width: 100%; max-width: 28rem; height: 44.8rem; // box-shadow: 10px 20px 40px rgba(19, 51, 113, 0.05); transition: 0.32s; border-radius: 0.8rem; ._pic { img { border-radius: 0.8rem 0.8rem 0 0; } } ._content { @include flex(column, center, space-between); ._top { margin-top: 2.8rem; position: relative; max-width: 21.7rem; margin-bottom: 5.3rem; height: 12.3rem; h4 { font-size: 2.4rem; font-weight: 500; margin-bottom: 1.4rem; } p { color: $color-alternative; font-size: 1.4rem; display: block; overflow: hidden; text-overflow: ellipsis; min-width: 21.7rem; } &::after { content: ""; position: absolute; bottom: -3.2rem; left: 0; height: 0.1rem; width: 100%; background-color: #f2f2f2; } } ._bottom { width: 100%; max-width: 21.7rem; span { font-size: 1.8rem; font-weight: bold; } a { display: block; margin-top: 1.3rem; font-size: 1.4rem; color: $color-second; } } } &:hover { cursor: pointer; transform: scale(1.1); transform-origin: center; } } @include fade(translateY(200px), 2s); } } @include responsive(992px) { .container-fav { overflow-x: hidden; ._hoteisList { overflow-x: scroll; scroll-snap-type: inline mandatory; display: inline-block; white-space: nowrap; ._hotel { white-space: normal; scroll-snap-align: start; margin-left: 1.5rem; display: inline-block; &:hover { transform: none; box-shadow: none; border: solid 2px $color-second; } } &:hover { animation-play-state: paused; } &::-webkit-scrollbar { display: none; } } } #nossoscursos & { ._hoteisList { width: 100%; animation: none; @include flex(row, center, space-between); flex-wrap: wrap; margin-top: 3rem; } } } @include responsive(720px) { padding-top: 1rem; .container-fav { .title { flex-direction: column; gap: 2rem; } } #nossoscursos & { ._hoteisList { width: 100%; justify-content: center; gap: 3rem; } } } #clinica & { padding-top: 9.3rem; padding-bottom: 0; .container-fav { ._title, .title { h4 { margin-bottom: 4.7rem; font-size: 3.8rem; color: $color-darkest; } } } } }
40,954
https://github.com/thefoo547/TheRentDesktop/blob/master/TheRent/src/therent/view/client/control_HboxBusqueda.java
Github Open Source
Open Source
BSD-3-Clause
null
TheRentDesktop
thefoo547
Java
Code
51
158
package therent.view.client; import com.jfoenix.controls.JFXTextField; import javafx.fxml.FXML; public class control_HboxBusqueda { @FXML private JFXTextField tfBuscar; //Evento para mandar el valor que se desea buscar al controlador de la ventana principal de cliente //Ya que ahi tenemos el menu desplegable(que es esta ventana) @FXML public void texto() { control_MenuCliente.text = tfBuscar.getText(); } }
40,090
https://github.com/naomi-sharif/personal/blob/master/src/scss/components/_nav-bar-wrapper.scss
Github Open Source
Open Source
MIT
null
personal
naomi-sharif
SCSS
Code
13
52
.nav-bar-wrapper { position: sticky; top: 0; background-color: #fff; width: 100%; z-index: $z-index-1; }
33,012
https://github.com/GerasimovDG/bd_lab/blob/master/src/items/item.interface.ts
Github Open Source
Open Source
MIT
null
bd_lab
GerasimovDG
TypeScript
Code
26
74
export interface Item { id: number; lastName: string; firstName: string; middleName: string; birthday: Date; averageMark: number; info?: { address: string, phone: string, login: string, }; }
35,839
https://github.com/ychxp/parking-control-admin/blob/master/src/pages/chargeStandard/index.tsx
Github Open Source
Open Source
Apache-2.0
2,020
parking-control-admin
ychxp
TSX
Code
347
1,242
import React, { useState, useCallback, useEffect } from 'react'; import { Tabs } from 'antd'; import { PageHeaderWrapper } from '@ant-design/pro-layout'; import { ChargingStandardTable, ChargingStandard } from './data'; import { setChargingStandard, requestChargingStandard } from './serves'; import RecordTable from './compontents/RecordList'; import CardCharge from './compontents/DataForm'; // import { BorderBottomOutlined } from '@ant-design/icons'; import styles from './index.less'; const { TabPane } = Tabs; const chargeType = [ { type: '小车', id: 0, dataType: 'smallCar', }, { type: '大车', id: 1, dataType: 'largeCar', }, { type: '三轮车', id: 2, dataType: 'tricycle', }, ]; export default () => { const [data, setData] = useState<ChargingStandard[]>(); //初始数据 const [loading, setLoading] = useState<boolean>(false); //表格的loading状态; const [carData, setCarData] = useState({ smallCar: [], largeCar: [], tricycle: [], }); const [type, setType] = useState('小车'); //车辆的类型; const [recordRow, setRecordRow] = useState<ChargingStandard>(); const [modalStatus, setModalStatus] = useState<boolean>(false); //打开Modal方法 const openModal = () => { setRecordRow(undefined); setModalStatus(true); }; //关闭弹出层的方法 const closeModal = () => { setModalStatus(false); }; //请求收费标准的数据方法 const requestData = useCallback(async () => { try { setLoading(true); let res = await requestChargingStandard(); let smallCar = res.filter((item: any, index: number) => item.type === '小车'); let largeCar = res.filter((item: any, index: number) => item.type === '大车'); let tricycle = res.filter((item: any, index: number) => item.type === '三轮车'); setData(res); setCarData({ smallCar: smallCar, largeCar: largeCar, tricycle: tricycle, }); setLoading(false); } catch (err) { setLoading(false); } }, [requestChargingStandard]); useEffect(() => { requestData(); }, [requestData]); //提交收费标准的数据方法 const CreateChargingStandards = useCallback( async (value: ChargingStandardTable[]) => { try { setLoading(true); await setChargingStandard({ key: '收费标准', value: value }); requestData(); setModalStatus(false); setLoading(false); return true; } catch (err) { setLoading(false); return false; } }, [requestData], ); //点击刷新按钮的操作 const refresh = useCallback(() => { requestData(); }, [requestData]); //设置收费标准的车辆类型 const setCarType = (number: number) => { setType(chargeType[number].type); }; //点击修改时候的功能 const changeRecord = (recordRow: ChargingStandard) => { setRecordRow(recordRow); setModalStatus(true); }; return ( <PageHeaderWrapper> <div className={styles.antTab}> <Tabs onChange={(value: any) => { setCarType(value); }} > {chargeType.map((item, index) => { return ( <TabPane tab={item.type} key={item.id}> <RecordTable onFinish={CreateChargingStandards} data={carData[item.dataType]} onrefresh={refresh} loading={loading} initialvalue={data} type={item.type} openModal={openModal} modify={changeRecord} ></RecordTable> </TabPane> ); })} </Tabs> </div> {modalStatus ? ( <CardCharge type={type} data={recordRow} initValue={data} status={modalStatus} cancel={closeModal} sureFunction={CreateChargingStandards} ></CardCharge> ) : null} </PageHeaderWrapper> ); };
35,129
https://github.com/huangboju/Pandora/blob/master/Demos/WebView/WKWebViewSimpleDemo-master/2015-01-31-WKWebViewDemo/2015-01-31-WKWebViewDemo/JSViewController.m
Github Open Source
Open Source
MIT
2,023
Pandora
huangboju
Objective-C
Code
221
966
// // JSViewController.m // 2015-01-31-WKWebViewDemo // // Created by TangJR on 15/1/31. // Copyright (c) 2015年 tangjr. All rights reserved. // #import "JSViewController.h" #import <WebKit/WebKit.h> #define HTML @"<head></head><img src='http://www.nsu.edu.cn/v/2014v3/img/background/3.jpg' />" @interface JSViewController () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler> @property (strong, nonatomic) WKWebView *webView; - (IBAction)refreshButtonPressed:(id)sender; @end @implementation JSViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. // 图片缩放的js代码 NSString *js = @"var count = document.images.length;for (var i = 0; i < count; i++) {var image = document.images[i];image.style.width=320;};window.alert('找到' + count + '张图');"; // 根据JS字符串初始化WKUserScript对象 WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; // 根据生成的WKUserScript对象,初始化WKWebViewConfiguration WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; [config.userContentController addUserScript:script]; _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; // _webView.UIDelegate = self; // _webView.navigationDelegate = self; [_webView loadHTMLString:@"<head></head><img src='http://www.nsu.edu.cn/v/2014v3/img/background/3.jpg' />" baseURL:nil]; [self.view addSubview:_webView]; } #pragma mark - WKUIDelegate /** * web界面中有弹出警告框时调用 * * @param webView 实现该代理的webview * @param message 警告框中的内容 * @param frame 主窗口 * @param completionHandler 警告框消失调用 */ - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler { [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil] show]; completionHandler(); } - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler { } - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler { } // 从web界面中接收到一个脚本时调用 - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { NSLog(@"%@", message); } #pragma mark - Button Pressed - (IBAction)refreshButtonPressed:(id)sender { [_webView reload]; } @end
19,830
https://github.com/takakv/vigenere-cryptanalysis/blob/master/Cryptanalysis/Analysis/Text.cs
Github Open Source
Open Source
MIT
null
vigenere-cryptanalysis
takakv
C#
Code
418
1,155
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace Analysis { public readonly struct Text { private readonly string _text; private readonly int _length; private readonly int[] _frequencies; public Text(string text) { _text = text.ToUpper().Trim(); _length = text.Length; _frequencies = new int[Alphabet.Length]; foreach (char c in _text) ++_frequencies[Array.IndexOf(Alphabet.Charset, c)]; } public void PrintFrequencies() { for (var i = 0; i < Alphabet.Length; ++i) Console.Write($"{Alphabet.Charset[i]}:{_frequencies[i]} "); Console.WriteLine(); } public string Content() { return _text; } public double GetIC() { double ic = 0; foreach (int i in _frequencies) ic += i * (i - 1); return ic / (_length * (_length - 1)); } public double[] GetMutualICList(Text altText) { var icList = new double[Alphabet.Length]; for (var i = 0; i < Alphabet.Length; ++i) { double ic = 0; for (var j = 0; j < Alphabet.Length; ++j) ic += _frequencies[j] * altText._frequencies[(j - i + Alphabet.Length) % Alphabet.Length] / (double) (_length * altText._length); icList[i] = ic; } return icList; } public Text[] GetSubstring(int strLength) { var texts = new List<char>[strLength]; for (var i = 0; i < strLength; ++i) { texts[i] = new List<char>(); } for (var i = 0; i < _length; ++i) { texts[i % strLength].Add(_text[i]); } var substring = new Text[strLength]; for (var i = 0; i < strLength; ++i) substring[i] = new Text(new string(texts[i].ToArray())); return substring; } public void GetRepetitions() { var substrLen = 2; int count; do { string substring = _text.Substring(0, substrLen++); count = Regex.Matches(_text, substring).Count; Console.WriteLine($"{substring} appears {count} times in text."); } while (count > 2); } public int Kasiski(string pattern) { int length = pattern.Length; var positions = new List<int>(); for (var i = 0; i < _length - length; ++i) { if (_text.Substring(i, length) == pattern.ToUpper()) positions.Add(i); } int gcd = positions[0]; for (var i = 1; i < positions.Count; ++i) gcd = GCD(gcd, positions[i]); return gcd; } public string Decipher(string key, Keys keys) { key = key.ToUpper(); if (key != "") return Decipher(key); var output = new StringBuilder(); foreach (string k in keys.Get()) { output.Append($"Key: {k}\n"); output.Append(Decipher(k)); output.Append("\n\n"); } return output.ToString(); } private string Decipher(string key) { var output = new StringBuilder(); int keyLength = key.Length, keyIndex = 0; foreach (char c in _text) { if (keyIndex == keyLength) keyIndex = 0; output.Append((char) ('A' + (c - key[keyIndex++] + Alphabet.Length) % Alphabet.Length)); } return output.ToString(); } private static int GCD(int a, int b) { while (true) { if (b == 0) return a; int a1 = a; a = b; b = a1 % b; } } } }
10,613
https://github.com/fossabot/ThScoreFileConverter/blob/master/ThScoreFileConverterTests/Models/Th10/Stubs/ScoreDataStub.cs
Github Open Source
Open Source
BSD-2-Clause
null
ThScoreFileConverter
fossabot
C#
Code
95
289
using System; using System.Collections.Generic; using System.Linq; using ThScoreFileConverter.Models.Th10; namespace ThScoreFileConverterTests.Models.Th10.Stubs { internal class ScoreDataStub<TStageProgress> : IScoreData<TStageProgress> where TStageProgress : struct, Enum { public ScoreDataStub() { } public ScoreDataStub(IScoreData<TStageProgress> scoreData) : this() { this.ContinueCount = scoreData.ContinueCount; this.DateTime = scoreData.DateTime; this.Name = scoreData.Name?.ToArray(); this.Score = scoreData.Score; this.SlowRate = scoreData.SlowRate; this.StageProgress = scoreData.StageProgress; } public byte ContinueCount { get; set; } public uint DateTime { get; set; } public IEnumerable<byte> Name { get; set; } public uint Score { get; set; } public float SlowRate { get; set; } public TStageProgress StageProgress { get; set; } } }
23,472
https://github.com/jfach/nautobot/blob/master/nautobot/ipam/tests/test_querysets.py
Github Open Source
Open Source
Apache-2.0
2,022
nautobot
jfach
Python
Code
431
5,299
import netaddr from nautobot.ipam.models import Prefix, Aggregate, IPAddress, RIR from nautobot.utilities.testing import TestCase class AggregateQuerysetTestCase(TestCase): queryset = Aggregate.objects.all() @classmethod def setUpTestData(cls): rir = RIR.objects.create(name="RIR 1", slug="rir-1") Aggregate.objects.create(prefix=netaddr.IPNetwork("192.168.0.0/16"), rir=rir) Aggregate.objects.create(prefix=netaddr.IPNetwork("192.168.1.0/24"), rir=rir) Aggregate.objects.create(prefix=netaddr.IPNetwork("192.168.2.0/24"), rir=rir) Aggregate.objects.create(prefix=netaddr.IPNetwork("192.168.3.0/24"), rir=rir) Aggregate.objects.create(prefix=netaddr.IPNetwork("192.168.3.192/28"), rir=rir) Aggregate.objects.create(prefix=netaddr.IPNetwork("192.168.3.208/28"), rir=rir) Aggregate.objects.create(prefix=netaddr.IPNetwork("192.168.3.224/28"), rir=rir) def test_net_equals(self): self.assertEqual(self.queryset.net_equals(netaddr.IPNetwork("192.168.0.0/16")).count(), 1) self.assertEqual(self.queryset.net_equals(netaddr.IPNetwork("192.1.0.0/16")).count(), 0) self.assertEqual(self.queryset.net_equals(netaddr.IPNetwork("192.1.1.1/32")).count(), 0) def test_net_contained(self): self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.0.0.0/8")).count(), 7) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.0.0/16")).count(), 6) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.3.0/24")).count(), 3) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.1.0/24")).count(), 0) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.3.192/28")).count(), 0) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.3.192/32")).count(), 0) def test_net_contained_or_equal(self): self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.0.0.0/8")).count(), 7) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.0.0/16")).count(), 7) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.3.0/24")).count(), 4) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.1.0/24")).count(), 1) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.3.192/28")).count(), 1) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.3.192/32")).count(), 0) def test_net_contains(self): self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.0.0/8")).count(), 0) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.0.0/16")).count(), 0) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.3.0/24")).count(), 1) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.3.192/28")).count(), 2) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.3.192/30")).count(), 3) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.3.192/32")).count(), 3) def test_net_contains_or_equals(self): self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.0.0/8")).count(), 0) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.0.0/16")).count(), 1) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.3.0/24")).count(), 2) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.3.192/28")).count(), 3) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.3.192/30")).count(), 3) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.3.192/32")).count(), 3) def test_get_by_prefix(self): prefix = self.queryset.net_equals(netaddr.IPNetwork("192.168.0.0/16"))[0] self.assertEqual(self.queryset.get(prefix="192.168.0.0/16"), prefix) def test_get_by_prefix_fails(self): _ = self.queryset.net_equals(netaddr.IPNetwork("192.168.0.0/16"))[0] with self.assertRaises(Aggregate.DoesNotExist): self.queryset.get(prefix="192.168.3.0/16") def test_filter_by_prefix(self): prefix = self.queryset.net_equals(netaddr.IPNetwork("192.168.0.0/16"))[0] self.assertEqual(self.queryset.filter(prefix="192.168.0.0/16")[0], prefix) class IPAddressQuerySet(TestCase): queryset = IPAddress.objects.all() @classmethod def setUpTestData(cls): IPAddress.objects.create(address="10.0.0.1/24", vrf=None, tenant=None) IPAddress.objects.create(address="10.0.0.2/24", vrf=None, tenant=None) IPAddress.objects.create(address="10.0.0.3/24", vrf=None, tenant=None) IPAddress.objects.create(address="10.0.0.4/24", vrf=None, tenant=None) IPAddress.objects.create(address="10.0.0.1/25", vrf=None, tenant=None) IPAddress.objects.create(address="2001:db8::1/64", vrf=None, tenant=None) IPAddress.objects.create(address="2001:db8::2/64", vrf=None, tenant=None) IPAddress.objects.create(address="2001:db8::3/64", vrf=None, tenant=None) def test_ip_family(self): self.assertEqual(self.queryset.ip_family(4).count(), 5) self.assertEqual(self.queryset.ip_family(6).count(), 3) def test_net_host_contained(self): self.assertEqual(self.queryset.net_host_contained(netaddr.IPNetwork("10.0.0.0/24")).count(), 5) self.assertEqual(self.queryset.net_host_contained(netaddr.IPNetwork("10.0.0.0/30")).count(), 4) self.assertEqual(self.queryset.net_host_contained(netaddr.IPNetwork("10.0.0.0/31")).count(), 2) self.assertEqual(self.queryset.net_host_contained(netaddr.IPNetwork("10.0.10.0/24")).count(), 0) def test_net_in(self): args = ["10.0.0.1/24"] self.assertEqual(self.queryset.net_in(args).count(), 1) args = ["10.0.0.1"] self.assertEqual(self.queryset.net_in(args).count(), 2) args = ["10.0.0.1/24", "10.0.0.1/25"] self.assertEqual(self.queryset.net_in(args).count(), 2) def test_get_by_address(self): address = self.queryset.net_in(["10.0.0.1/24"])[0] self.assertEqual(self.queryset.get(address="10.0.0.1/24"), address) def test_filter_by_address(self): address = self.queryset.net_in(["10.0.0.1/24"])[0] self.assertEqual(self.queryset.filter(address="10.0.0.1/24")[0], address) def test_string_search_parse_as_network_string(self): """ Tests that the parsing underlying `string_search` behaves as expected. """ tests = { "10": "10.0.0.0/8", "10.": "10.0.0.0/8", "10.0": "10.0.0.0/16", "10.0.0.4": "10.0.0.4/32", "10.0.0": "10.0.0.0/24", "10.0.0.4/24": "10.0.0.4/32", "10.0.0.4/24": "10.0.0.4/32", "2001": "2001::/16", "2001:": "2001::/16", "2001::": "2001::/16", "2001:db8:": "2001:db8::/32", "2001:0db8::": "2001:db8::/32", "2001:db8:abcd:0012::0/64": "2001:db8:abcd:12::/128", "2001:db8::1/65": "2001:db8::1/128", "fe80": "fe80::/16", "fe80::": "fe80::/16", "fe80::46b:a212:1132:3615": "fe80::46b:a212:1132:3615/128", "fe80::76:88e9:12aa:334d": "fe80::76:88e9:12aa:334d/128", } for test, expected in tests.items(): self.assertEqual(str(self.queryset._parse_as_network_string(test)), expected) def test_string_search(self): search_terms = { "10": 5, "10.0.0.1": 2, "10.0.0.1/24": 2, "10.0.0.1/25": 2, "10.0.0.2": 1, "11": 0, "2001": 3, "2001::": 3, "2001:db8::": 3, "2001:db8::1": 1, "fe80::": 0, } for term, cnt in search_terms.items(): self.assertEqual(self.queryset.string_search(term).count(), cnt) class PrefixQuerysetTestCase(TestCase): queryset = Prefix.objects.all() @classmethod def setUpTestData(cls): Prefix.objects.create(prefix=netaddr.IPNetwork("192.168.0.0/16")) Prefix.objects.create(prefix=netaddr.IPNetwork("192.168.1.0/24")) Prefix.objects.create(prefix=netaddr.IPNetwork("192.168.2.0/24")) Prefix.objects.create(prefix=netaddr.IPNetwork("192.168.3.0/24")) Prefix.objects.create(prefix=netaddr.IPNetwork("192.168.3.192/28")) Prefix.objects.create(prefix=netaddr.IPNetwork("192.168.3.208/28")) Prefix.objects.create(prefix=netaddr.IPNetwork("192.168.3.224/28")) Prefix.objects.create(prefix=netaddr.IPNetwork("fd78:da4f:e596:c217::/64")) Prefix.objects.create(prefix=netaddr.IPNetwork("fd78:da4f:e596:c217::/120")) Prefix.objects.create(prefix=netaddr.IPNetwork("fd78:da4f:e596:c217::/122")) def test_net_equals(self): self.assertEqual(self.queryset.net_equals(netaddr.IPNetwork("192.168.0.0/16")).count(), 1) self.assertEqual(self.queryset.net_equals(netaddr.IPNetwork("192.1.0.0/16")).count(), 0) self.assertEqual(self.queryset.net_equals(netaddr.IPNetwork("192.1.0.0/32")).count(), 0) def test_net_contained(self): self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.0.0.0/8")).count(), 7) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.0.0/16")).count(), 6) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.3.0/24")).count(), 3) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.1.0/24")).count(), 0) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.3.192/28")).count(), 0) self.assertEqual(self.queryset.net_contained(netaddr.IPNetwork("192.168.3.192/32")).count(), 0) def test_net_contained_or_equal(self): self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.0.0.0/8")).count(), 7) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.0.0/16")).count(), 7) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.3.0/24")).count(), 4) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.1.0/24")).count(), 1) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.3.192/28")).count(), 1) self.assertEqual(self.queryset.net_contained_or_equal(netaddr.IPNetwork("192.168.3.192/32")).count(), 0) def test_net_contains(self): self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.0.0/8")).count(), 0) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.0.0/16")).count(), 0) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.3.0/24")).count(), 1) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.3.192/28")).count(), 2) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.3.192/30")).count(), 3) self.assertEqual(self.queryset.net_contains(netaddr.IPNetwork("192.168.3.192/32")).count(), 3) def test_net_contains_or_equals(self): self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.0.0/8")).count(), 0) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.0.0/16")).count(), 1) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.3.0/24")).count(), 2) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.3.192/28")).count(), 3) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.3.192/30")).count(), 3) self.assertEqual(self.queryset.net_contains_or_equals(netaddr.IPNetwork("192.168.3.192/32")).count(), 3) def test_annotate_tree(self): self.assertEqual(self.queryset.annotate_tree().get(prefix="192.168.0.0/16").parents, 0) self.assertEqual(self.queryset.annotate_tree().get(prefix="192.168.0.0/16").children, 6) self.assertEqual(self.queryset.annotate_tree().get(prefix="192.168.3.0/24").parents, 1) self.assertEqual(self.queryset.annotate_tree().get(prefix="192.168.3.0/24").children, 3) self.assertEqual(self.queryset.annotate_tree().get(prefix="192.168.3.224/28").parents, 2) self.assertEqual(self.queryset.annotate_tree().get(prefix="192.168.3.224/28").children, 0) self.assertEqual(self.queryset.annotate_tree().get(prefix="fd78:da4f:e596:c217::/64").parents, 0) self.assertEqual(self.queryset.annotate_tree().get(prefix="fd78:da4f:e596:c217::/64").children, 2) self.assertEqual(self.queryset.annotate_tree().get(prefix="fd78:da4f:e596:c217::/120").parents, 1) self.assertEqual(self.queryset.annotate_tree().get(prefix="fd78:da4f:e596:c217::/120").children, 1) self.assertEqual(self.queryset.annotate_tree().get(prefix="fd78:da4f:e596:c217::/122").parents, 2) self.assertEqual(self.queryset.annotate_tree().get(prefix="fd78:da4f:e596:c217::/122").children, 0) def test_get_by_prefix(self): prefix = self.queryset.net_equals(netaddr.IPNetwork("192.168.0.0/16"))[0] self.assertEqual(self.queryset.get(prefix="192.168.0.0/16"), prefix) def test_get_by_prefix_fails(self): _ = self.queryset.net_equals(netaddr.IPNetwork("192.168.0.0/16"))[0] with self.assertRaises(Prefix.DoesNotExist): self.queryset.get(prefix="192.168.3.0/16") def test_filter_by_prefix(self): prefix = self.queryset.net_equals(netaddr.IPNetwork("192.168.0.0/16"))[0] self.assertEqual(self.queryset.filter(prefix="192.168.0.0/16")[0], prefix)
3,646
https://github.com/lambda-limbo/c-iterators/blob/master/CMakeLists.txt
Github Open Source
Open Source
MIT
2,018
c-iterators
lambda-limbo
CMake
Code
20
156
cmake_minimum_required(VERSION 2.8) project("Iterators") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") if(WIN32) set(EXEC_NAME "iterator") else() set(EXEC_NAME "iterator.out") endif() set(SRC src/main.c src/include/iterator.h src/include/iterator.c src/include/linked_list.h src/include/linked_list.c) add_executable(${EXEC_NAME} ${SRC})
27,348
https://github.com/dimpase/tt-fort/blob/master/print/putstrmodule.F90
Github Open Source
Open Source
MIT
2,021
tt-fort
dimpase
Fortran Free Form
Code
350
746
#ifndef MATLAB MODULE PUTSTRMODULE ! DUMMY VERSION ! An auxilliary module that accompanies DISPMODULE. This module contains dummy versions of the ! subroutines putstr and putnl that do nothing. It is needed to avoid an "undefined symbol" link ! error for these. In addition it defines the named constant (or parameter) DEFAULT_UNIT = -3, ! which makes the asterisk unit (usually the screen) the default to display on. ! ! The purpose of having this module is to make displaying possible in situations where ordinary ! print- and write-statements do not work. Then this module should be replaced by one defining ! functional versions of putstr and putnl. An example is given by the commented out PUTSTRMODULE ! for Matlab mex files below. ! integer, parameter :: DEFAULT_UNIT = -3 ! CONTAINS subroutine putstr(s) character(*), intent(in) :: s integer ldummy, ldummy1 ! these variables exist to avoid unused variable warnings ldummy = len(s) ldummy1 = ldummy ldummy = ldummy1 end subroutine putstr subroutine putnl() end subroutine putnl END MODULE PUTSTRMODULE #else MODULE PUTSTRMODULE ! for Matlab mex files. ! This module contains functional versions of subroutines putstr and putnl. It also sets ! DEFAULT_UNIT = -2, which makes putstr/putnl the default to display with. Using this module, ! instead of the dummy module above allows DISPMODULE to be used with Matlab mex files. ! used (commented in) instead of the one above (which should then be commented out), then ! DISPMODULE can be used with Matlab mex files. A shorter version (given in the user manual) ! may be used with g95, but the one below works for both g95 and gfortran. ! use, intrinsic :: ISO_C_BINDING integer, parameter :: default_unit = -2 interface subroutine mexprintf(s) bind(C, name = 'mexPrintf') import c_char character(c_char) s(*) end subroutine mexprintf end interface interface subroutine mexEvalString(s) bind(C, name = 'mexEvalString') import c_char character(c_char) s(*) end subroutine mexEvalString end interface CONTAINS subroutine putstr(s) character(*), intent(in) :: s call mexprintf(s//char(0)) call mexEvalString('drawnow;'); ! to dump string. end subroutine putstr subroutine putnl() call mexprintf(char(10)//char(0)) call mexEvalString('drawnow;'); ! to dump string. end subroutine putnl END MODULE PUTSTRMODULE #endif
30,830
https://github.com/Projeto-Game-Awake/Acao-e-Reacao/blob/master/js/init.js
Github Open Source
Open Source
MIT
null
Acao-e-Reacao
Projeto-Game-Awake
JavaScript
Code
25
79
var scene; var gameConfig = { type: Phaser.AUTO, scale: { parent: "FCG-board", width: 1200, height: 700, }, scene: [first,next,end], }; var game = new Phaser.Game(gameConfig);
25,369
https://github.com/waitingworld/ruoyi-server/blob/master/ruoyi-activiti/src/main/java/com/ruoyi/activiti/listener/ActivitiExecutionListener.java
Github Open Source
Open Source
MIT
null
ruoyi-server
waitingworld
Java
Code
58
302
package com.ruoyi.activiti.listener; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.ExecutionListener; import org.activiti.engine.delegate.Expression; import org.springframework.stereotype.Component; /** * 执行监听器 */ @Component public class ActivitiExecutionListener implements ExecutionListener { // 定义一个流程注入的表达式 private Expression expression; @Override public void notify(DelegateExecution delegateExecution) { System.out.println("xml任务:" + delegateExecution.getId() + " ActivitiListenner" + this.toString()); System.out.println("expression:" + expression.getExpressionText());//输出字符串表达式的内容 // eventName: // start:开始时触发 // end:结束时触发 // take:主要用于监控流程线,当流程流转该线时触发 String eventName = delegateExecution.getEventName(); System.out.println("===="+eventName+"====="); } }
48,685
https://github.com/hirakata-farm/GeoGlyphRail/blob/master/RSC/lines/10ES12ES/10ES_3EeastboundRF.geom
Github Open Source
Open Source
MIT
null
GeoGlyphRail
hirakata-farm
GLSL
Code
18
217
#T,datetime:Sat Aug 28 2021 23:33:55 GMT+0900 (日本標準時) 50.643941,3.071077,71.149738,x,F #P,N 50.639322,3.075508,66.154435,x,F #P,tn=y:hs=y:gu=1435:ms=200:ly=-1: 50.639226,3.075599,66.635179,Lille Europe Pass,V #P,tn=y:hs=y:gu=1435:ms=200:ly=-1: 50.637553,3.077184,74.025536,x,F #P,tn=y:hs=y:gu=1435:ms=200:ly=-1: 50.637183,3.077535,73.773870,x,F
47,329
https://github.com/skylark-integration/skylark-maqetta/blob/master/.original/maqetta-Release10.0.2/maqetta.core.client/WebContent/orion/editor/jsTemplateContentAssist.js
Github Open Source
Open Source
MIT, BSD-3-Clause, AFL-2.1
2,020
skylark-maqetta
skylark-integration
JavaScript
Code
1,082
2,832
/******************************************************************************* * @license * Copyright (c) 2011, 2012 IBM Corporation and others. * Copyright (c) 2012 VMware, Inc. * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution * License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). * * Contributors: * IBM Corporation - initial API and implementation * Andrew Eisenberg - rename to jsTemplateContentAssist.js *******************************************************************************/ /*global define */ define("orion/editor/jsTemplateContentAssist", [], function() { /** * Returns a string of all the whitespace at the start of the current line. * @param {String} buffer The document * @param {Integer} offset The current selection offset */ function leadingWhitespace(buffer, offset) { var whitespace = ""; offset = offset-1; while (offset > 0) { var c = buffer.charAt(offset--); if (c === '\n' || c === '\r') { //we hit the start of the line so we are done break; } if (/\s/.test(c)) { //we found whitespace to add it to our result whitespace = c.concat(whitespace); } else { //we found non-whitespace, so reset our result whitespace = ""; } } return whitespace; } function findPreviousChar(buffer, offset) { var c = ""; while (offset >= 0) { c = buffer[offset]; if (c === '\n' || c === '\r') { //we hit the start of the line so we are done break; } else if (/\s/.test(c)) { offset--; } else { // a non-whitespace character, we are done break; } } return c; } var uninterestingChars = { ':': ':', '!': '!', '@': '@', '#': '#', '$': '$', '^': '^', '&': '&', '*': '*', '.': '.', '?': '?', '<': '<', '>': '>' }; /** * Determines if the invocation location is a valid place to use * templates. We are not being too precise here. As an approximation, * just look at the previous character. * * @return {Boolean} true iff the current invocation location is * a valid place for template proposals to appear. * This means that the invocation location is at the start of anew statement. */ function isValid(prefix, buffer, offset) { var previousChar = findPreviousChar(buffer, offset-prefix.length-1); return !uninterestingChars[previousChar]; } /** * Removes prefix from string. * @param {String} prefix * @param {String} string */ function chop(prefix, string) { return string.substring(prefix.length); } /** * Returns proposals for javascript templates */ function getTemplateProposals(prefix, buffer, offset) { //any returned positions need to be offset based on current cursor position and length of prefix var startOffset = offset-prefix.length; var proposals = []; var whitespace = leadingWhitespace(buffer, offset); //common vars for each proposal var text, description, positions, endOffset; if ("if".indexOf(prefix) === 0) { //if statement text = "if (condition) {\n" + whitespace + "\t\n" + whitespace + '}'; description = "if - if statement"; positions = [{offset: startOffset+4, length: 9}]; endOffset = startOffset+whitespace.length+18;//after indentation inside if body proposals.push({proposal: chop(prefix, text), description: description, positions: positions, escapePosition: endOffset}); //if/else statement text = "if (condition) {\n" + whitespace + "\t\n" + whitespace + "} else {\n" + whitespace + "\t\n" + whitespace + "}"; description = "if - if else statement"; positions = [{offset: startOffset+4, length: 9}]; endOffset = startOffset+whitespace.length+18;//after indentation inside if body proposals.push({proposal: chop(prefix, text), description: description, positions: positions, escapePosition: endOffset}); } if ("for".indexOf(prefix) === 0) { //for loop text = "for (var i = 0; i < array.length; i++) {\n" + whitespace + "\t\n" + whitespace + '}'; description = "for - iterate over array"; positions = [{offset: startOffset+9, length: 1}, {offset: startOffset+20, length: 5}]; endOffset = startOffset+whitespace.length+42;//after indentation inside for loop body proposals.push({proposal: chop(prefix, text), description: description, positions: positions, escapePosition: endOffset}); //for ... in statement text = "for (var property in object) {\n" + whitespace + "\tif (object.hasOwnProperty(property)) {\n" + whitespace + "\t\t\n" + whitespace + "\t}\n" + whitespace + '}'; description = "for..in - iterate over properties of an object"; positions = [{offset: startOffset+9, length: 8}, {offset: startOffset+21, length: 6}]; endOffset = startOffset+(2*whitespace.length)+73;//after indentation inside if statement body proposals.push({proposal: chop(prefix, text), description: description, positions: positions, escapePosition: endOffset}); } //while loop if ("while".indexOf(prefix) === 0) { text = "while (condition) {\n" + whitespace + "\t\n" + whitespace + '}'; description = "while - while loop with condition"; positions = [{offset: startOffset+7, length: 9}]; endOffset = startOffset+whitespace.length+21;//after indentation inside while loop body proposals.push({proposal: chop(prefix, text), description: description, positions: positions, escapePosition: endOffset}); } //do/while loop if ("do".indexOf(prefix) === 0) { text = "do {\n" + whitespace + "\t\n" + whitespace + "} while (condition);"; description = "do - do while loop with condition"; positions = [{offset: startOffset+16, length: 9}]; endOffset = startOffset+whitespace.length+6;//after indentation inside do/while loop body proposals.push({proposal: chop(prefix, text), description: description, positions: positions, escapePosition: endOffset}); } //switch statement if ("switch".indexOf(prefix) === 0) { text = "switch (expression) {\n" + whitespace + "\tcase value1:\n" + whitespace + "\t\t\n" + whitespace + "\t\tbreak;\n" + whitespace + "\tdefault:\n" + whitespace + "}"; description = "switch - switch case statement"; positions = [{offset: startOffset+8, length: 10}, {offset: startOffset + 28, length: 6}]; endOffset = startOffset+(2*whitespace.length)+38;//after indentation inside first case statement proposals.push({proposal: chop(prefix, text), description: description, positions: positions, escapePosition: endOffset}); } if ("try".indexOf(prefix) === 0) { //try..catch statement text = "try {\n" + whitespace + "\t\n" + whitespace + "} catch (err) {\n" + whitespace + "}"; description = "try - try..catch statement"; endOffset = startOffset+whitespace.length+7;//after indentation inside try statement proposals.push({proposal: chop(prefix, text), description: description, escapePosition: endOffset}); //try..catch..finally statement text = "try {\n" + whitespace + "\t\n" + whitespace + "} catch (err) {\n" + whitespace + "} finally {\n" + whitespace + "}"; description = "try - try..catch statement with finally block"; endOffset = startOffset+whitespace.length+7;//after indentation inside try statement proposals.push({proposal: chop(prefix, text), description: description, escapePosition: endOffset}); } return proposals; } /** * Returns proposals for javascript keywords. */ function getKeyWordProposals(prefix, buffer, offset) { var keywords = ["break", "case", "catch", "continue", "debugger", "default", "delete", "do", "else", "finally", "for", "function", "if", "in", "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with"]; var proposals = []; for (var i = 0; i < keywords.length; i++) { if (keywords[i].indexOf(prefix) === 0) { proposals.push({proposal: chop(prefix, keywords[i]), description: keywords[i] }); } } return proposals; } /** * @name orion.editor.JSTemplateContentAssistProvider * @class Provides content assist for JavaScript keywords. */ function JSTemplateContentAssistProvider() {} JSTemplateContentAssistProvider.prototype = /** @lends orion.editor.JSTemplateContentAssistProvider.prototype */ { computeProposals: function(buffer, offset, context) { var prefix = context.prefix; var proposals = []; if (!isValid(prefix, buffer, offset)) { return proposals; } //we are not completing on an object member, so suggest templates and keywords proposals = proposals.concat(getTemplateProposals(prefix, buffer, offset)); proposals = proposals.concat(getKeyWordProposals(prefix, buffer, offset)); return proposals; } }; return { JSTemplateContentAssistProvider: JSTemplateContentAssistProvider }; });
15,542
https://github.com/nguyenngocduy1981/quiz-admin-frontend/blob/master/app/containers/SectionAddPage/saga.js
Github Open Source
Open Source
MIT
null
quiz-admin-frontend
nguyenngocduy1981
JavaScript
Code
366
1,143
import { call, put, takeLatest, } from 'redux-saga/effects'; import {push} from 'react-router-redux'; import request from 'utils/request'; import { CATEGORIES, CHILD_CATEGORY, SECTION_CHECK, SECTIONS } from '../../constants/service-model'; import { CHECK_EXISTED_SECTION, GO_HOME, LOAD_CATEGORIES, LOAD_CATEGORY, loadCategoriesSuccess, loadCategorySuccess, markExistedSection, requestError, SAVE_SECTION, saveSectionSuccess, SELECT_CATEGORY } from './actions'; import {SECTION_NEW_R, SECTION_R} from '../../constants/routers'; import {post} from '../../utils/request-method'; import notify from '../../utils/notify'; import {checkBeforeSave} from './utils'; import {ERROR_MSG, OPTION_FROM_GIVEN, PASSAGE_TYPES} from '../../constants/questions'; const _ = require('lodash'); export function* goHome(pl) { const {parentId, childId} = pl.payload; yield put(push(`${SECTION_R}/${parentId}/${childId}`)); } // export function* changeCategory(payload) { // yield put(push(SECTION_NEW_R + '/' + payload.id)); // } export function* checkExistedSection(req) { try { const {id, text, questionType} = req.payload; const res = yield call(request, SECTION_CHECK, post({text, questionType})); if (res.data) { notify(ERROR_MSG.ERR_EXISTED_S); yield put(markExistedSection(id)); } } catch (err) { yield put(requestError()); } } export function* fetchCategories() { try { const res = yield call(request, CATEGORIES); yield put(loadCategoriesSuccess(res.data)); } catch (err) { yield put(requestError()); } } export function* fetchCategory(payload) { try { const {id} = payload; const res = yield call(request, `${CHILD_CATEGORY}/${id}`); yield put(loadCategorySuccess(res.data)); } catch (err) { yield put(requestError()); } } function convertSection(sec, categoryId) { const { text, questionType, sectionOptions, passageText, passageOptions } = sec; const type = sec.questionType; if (type === OPTION_FROM_GIVEN) { return { text, questionType, categoryId, sectionOptions }; } if (PASSAGE_TYPES.includes(type)) { return { text, questionType, categoryId, passageText, passageOptions }; } return {text, questionType, categoryId}; } function convert2Save(sections, cat) { return sections.map((sec) => convertSection(sec, cat)); } export function* saveSections(req) { try { const {sections, catId} = req.payload; let hasError; if (hasError = !checkBeforeSave(sections)) { notify(ERROR_MSG.ERR_MANDATORY); } else { const res = yield call(request, SECTIONS, post(convert2Save(sections, catId))); if (res.error) { hasError = true; notify(res.error.message); } } yield put(saveSectionSuccess({sections, hasError})); } catch (err) { yield put(requestError()); } } /** * Root saga manages watcher lifecycle */ export default function* questionsData() { // Watches for LOAD_EXAM actions and calls getRepos when one comes in. // By using `takeLatest` only the result of the latest API call is applied. // It returns task descriptor (just like fork) so we can continue execution // It will be cancelled automatically on component unmount yield takeLatest(LOAD_CATEGORIES, fetchCategories); yield takeLatest(LOAD_CATEGORY, fetchCategory); yield takeLatest(SAVE_SECTION, saveSections); // yield takeLatest(SELECT_CATEGORY, changeCategory); yield takeLatest(CHECK_EXISTED_SECTION, checkExistedSection); yield takeLatest(GO_HOME, goHome); }
2,594
https://github.com/bitmark-inc/bitmark-mobile-android/blob/master/app/build.gradle
Github Open Source
Open Source
ISC
2,020
bitmark-mobile-android
bitmark-inc
Gradle
Code
794
4,173
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' apply from: 'versioning.gradle' apply from: '../autodimension.gradle' apply plugin: 'io.fabric' apply plugin: 'io.sentry.android.gradle' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "com.bitmark.registry" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode buildVersionCode() versionName buildVersionName() testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" externalNativeBuild { cmake { cppFlags "" } } javaCompileOptions { annotationProcessorOptions { arguments = ["room.schemaLocation": "$projectDir/schemas".toString()] } } } splits { abi { reset() enable project.hasProperty('splitApks') universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } bundle { density { // Different APKs are generated for devices with different screen densities; true by default. enableSplit false } abi { // Different APKs are generated for devices with different CPU architectures; true by default. enableSplit true } language { // This is disabled so that the App Bundle does NOT split the APK for each language. // We're gonna use the same APK for all languages. enableSplit false } } androidExtensions { experimental = true } signingConfigs { debug { def keystorePropertiesFile = rootProject.file( "keystores/debug.properties") def keystoreProperties = new Properties() keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) keyAlias keystoreProperties['key.alias'] keyPassword keystoreProperties['key.alias.password'] storeFile file('../keystores/debug.keystore') storePassword keystoreProperties['key.store.password'] } release { def keystorePropertiesFile = rootProject.file( "keystores/release.properties") def keystoreProperties = new Properties() keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) keyAlias keystoreProperties['key.alias'] keyPassword keystoreProperties['key.alias.password'] storeFile file('../keystores/release.keystore') storePassword keystoreProperties['key.store.password'] } } buildTypes { debug { debuggable true minifyEnabled false signingConfig signingConfigs.debug } release { minifyEnabled true shrinkResources true signingConfig signingConfigs.release proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] def abi = output.getFilter(com.android.build.OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } compileOptions { sourceCompatibility 1.8 targetCompatibility 1.8 } externalNativeBuild { cmake { path "CMakeLists.txt" } } flavorDimensions "version" productFlavors { inhouse { dimension "version" applicationIdSuffix ".inhouse" resValue "string", "app_name", "Bitmark" resValue "string", "chibi_scheme", "registry" manifestPlaceholders = [ appIcon: "@mipmap/ic_launcher_dev", appIconRound: "@mipmap/ic_launcher_dev_round" ] ext.betaDistributionReleaseNotesFilePath = "${project.rootDir}/distribution/release_note.txt" ext.betaDistributionEmailsFilePath = "${project.rootDir}/distribution/testers.txt" buildConfigField "String", "CORE_API_ENDPOINT", "\"https://api.test.bitmark.com\"" buildConfigField "String", "MOBILE_SERVER_ENDPOINT", "\"https://bm.test.bitmark.com\"" buildConfigField "String", "FILE_COURIER_SERVER_ENPOINT", "\"https://file-courier.test.bitmark.com\"" buildConfigField "String", "PROFILE_SERVER_ENDPOINT", "\"https://profiles.test.bitmark.com\"" buildConfigField "String", "REGISTRY_WEBSITE", "\"https://registry.test.bitmark.com\"" buildConfigField "String", "ZERO_ADDRESS", "\"dw9MQXcC5rJZb3QE1nz86PiQAheMP1dx9M3dr52tT8NNs14m33\"" buildConfigField "String", "KEY_ACCOUNT_SERVER_ENDPOINT", "\"https://key.test.bitmarkaccountassets.com\"" buildConfigField "String", "REGISTRY_WEB_ENDPOINT", "\"https://registry.test.bitmark.com\"" buildConfigField "String", "NOTIFICATION_CLIENT", "\"registryinhouse\"" buildConfigField "String", "TERMS_OF_SERVICE_URL", "\"https://bitmark.com/en/legal/terms?env=app\"" buildConfigField "String", "PRIVACY_POLICY_URL", "\"https://bitmark.com/en/legal/privacy?env=app\"" buildConfigField 'String', 'REGISTRY_API_ENDPOINT', "\"https://registry.test.bitmark.com/s/api/\"" buildConfigField 'String', 'PROFILE_SERVER_ENDPOINT', "\"https://profiles.test.bitmark.com/\"" } prd { dimension "version" resValue "string", "app_name", "Bitmark" resValue "string", "chibi_scheme", "registry" manifestPlaceholders = [ appIcon: "@mipmap/ic_launcher", appIconRound: "@mipmap/ic_launcher_round" ] ext.betaDistributionReleaseNotesFilePath = "${project.rootDir}/distribution/release_note.txt" ext.betaDistributionEmailsFilePath = "${project.rootDir}/distribution/testers.txt" buildConfigField "String", "CORE_API_ENDPOINT", "\"https://api.bitmark.com\"" buildConfigField "String", "MOBILE_SERVER_ENDPOINT", "\"https://bm.bitmark.com\"" buildConfigField "String", "FILE_COURIER_SERVER_ENPOINT", "\"https://file-courier.bitmark.com\"" buildConfigField "String", "PROFILE_SERVER_ENDPOINT", "\"https://profiles.bitmark.com\"" buildConfigField "String", "REGISTRY_WEBSITE", "\"https://registry.bitmark.com\"" buildConfigField "String", "ZERO_ADDRESS", "\"a3ezwdYVEVrHwszQrYzDTCAZwUD3yKtNsCq9YhEu97bPaGAKy1\"" buildConfigField "String", "KEY_ACCOUNT_SERVER_ENDPOINT", "\"https://key.bitmarkaccountassets.com\"" buildConfigField "String", "REGISTRY_WEB_ENDPOINT", "\"https://registry.bitmark.com\"" buildConfigField "String", "NOTIFICATION_CLIENT", "\"registry\"" buildConfigField "String", "TERMS_OF_SERVICE_URL", "\"https://bitmark.com/en/legal/terms?env=app\"" buildConfigField "String", "PRIVACY_POLICY_URL", "\"https://bitmark.com/en/legal/privacy?env=app\"" buildConfigField 'String', 'REGISTRY_API_ENDPOINT', "\"https://registry.bitmark.com/s/api/\"" buildConfigField 'String', 'PROFILE_SERVER_ENDPOINT', "\"https://profiles.bitmark.com/\"" } } packagingOptions { exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/license.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/notice.txt' exclude 'META-INF/ASL2.0' exclude 'lib/libsodiumjni.dylib' exclude 'lib/libsodiumjni.so' } sentry { // Disables or enables the automatic configuration of proguard // for Sentry. This injects a default config for proguard so // you don't need to do it manually. autoProguardConfig true // Enables or disables the automatic upload of mapping files // during a build. If you disable this you'll need to manually // upload the mapping files with sentry-cli when you do a release. autoUpload true } } dependencies { // Basic implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" // temporarily use this version of appcompat to avoid crashing in IntercomMessengerActivity // @see https://community.intercom.com/t/intercom-android-sdk-crashing-with-android-appcompat-1-1-0-alpha03/1095 implementation 'androidx.appcompat:appcompat:1.1.0-alpha02' implementation 'androidx.core:core-ktx:1.2.0-alpha02' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' // Dagger implementation 'com.google.dagger:dagger-android:2.23.2' implementation 'com.google.dagger:dagger-android-support:2.23.2' kapt 'com.google.dagger:dagger-android-processor:2.23.2' kapt 'com.google.dagger:dagger-compiler:2.23.2' // Rx2 implementation 'io.reactivex.rxjava2:rxjava:2.2.10' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' // Retrofit + Okhttp implementation "com.squareup.retrofit2:retrofit:2.6.0" implementation "com.squareup.retrofit2:adapter-rxjava2:2.6.0" implementation "com.squareup.retrofit2:converter-gson:2.6.0" implementation "com.squareup.okhttp3:okhttp:4.0.0" implementation "com.squareup.okhttp3:logging-interceptor:4.0.0" // Architecture component implementation "android.arch.lifecycle:livedata:2.0.0" implementation "android.arch.lifecycle:runtime:2.0.0" kapt "android.arch.lifecycle:compiler:2.0.0" // Room implementation 'androidx.room:room-runtime:2.1.0' kapt 'androidx.room:room-compiler:2.1.0' implementation 'androidx.room:room-rxjava2:2.1.0' // Glide implementation 'com.github.bumptech.glide:glide:4.9.0' kapt 'com.github.bumptech.glide:compiler:4.9.0' // Google Drive implementation 'com.google.android.gms:play-services-auth:17.0.0' implementation('com.google.api-client:google-api-client-android:1.26.0') { exclude group: 'org.apache.httpcomponents' } implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0') { exclude group: 'org.apache.httpcomponents' } implementation 'com.google.http-client:google-http-client-gson:1.26.0' // Bitmark SDK implementation 'com.bitmark.sdk:android-sdk:2.1.0' implementation 'com.bitmark.sdk:api-service:2.1.0' implementation 'com.bitmark.sdk:cryptography:1.6.0-SNAPSHOT' // Others implementation 'com.google.firebase:firebase-messaging:19.0.1' implementation 'com.aurelhubert:ahbottomnavigation:2.3.4' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.google.zxing:core:3.3.3' implementation('com.journeyapps:zxing-android-embedded:3.6.0') { transitive = false } implementation 'com.github.tbruyelle:rxpermissions:0.10.2' implementation 'io.intercom.android:intercom-sdk:5.4.0' implementation('com.crashlytics.sdk.android:crashlytics:2.9.8@aar') { transitive = true } implementation 'io.sentry:sentry-android:1.7.27' implementation 'org.slf4j:slf4j-nop:1.7.25' //debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-2' // Testing testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.3.0-alpha01' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0-alpha01' } task fillSecretKey << { def keyPropertiesFile = rootProject.file('key.properties') def keyProperties = new Properties() keyProperties.load(new FileInputStream(keyPropertiesFile)) def apiKeyFile = file('src/main/jni/api-key.cpp') def content = apiKeyFile.getText() content = content.replace('bitmark-api-key-to-be-filled', keyProperties['api.key.bitmark']) . replace('intercom-api-key-to-be-filled', keyProperties['api.key.intercom']) apiKeyFile.bytes = [] apiKeyFile.text = content } configurations.all { resolutionStrategy.eachDependency { details -> def requested = details.requested if (requested.group == 'androidx.appcompat') { details.useVersion '1.1.0-alpha02' } } } apply plugin: 'com.google.gms.google-services'
7,258
https://github.com/mohabtarig2/blog/blob/master/resources/js/tenders/offerTender.vue
Github Open Source
Open Source
MIT
null
blog
mohabtarig2
Vue
Code
97
487
<template> <div class="container"> <li class="list-group-item" > <span class="h5 text-primary font-weight-bold">{{com_id}}</span> <i class="fa fa-star "></i> <i class="fa fa-star "></i> <i class="fa fa-star "></i> <i class="fa fa-star text-op"></i> </li> <li class="list-group-item mb-2"> {{comment}} <div class="files"> <table class="table table-striped"> <thead> <tr> <th scope="col">Total Area Build</th> <th scope="col">{{TotalAreaBuild}} </th> </tr> <tr> <th scope="col">Budget</th> <th scope="col">{{budget}} AED</th> </tr> </thead> <tbody> <tr> <td>File</td> <td><i class="fa fa-pdf"><img :src="'offers/'+ name" width="300"></i> <a :href="'offers/'+ name" download><i class="fa fa-download text-dark font-wieght-font"><span class="font-weight-bold"> download</span> </i></a> </td> </tr> </tbody> </table> </div> <button class="btn btn-success" v-if="com_id">Accept</button> <button class="btn btn-secondary">report </button> </li> </div> </template> <script> export default { props:{comment:String,com_id:Number,count:Number,budget:Number,name:String,path:String,TotalAreaBuild:Number}, } </script>
41,075
https://github.com/qussarah/declare/blob/master/idea/testData/quickfix/leakingThis/accessOpenPropertyClass.kt
Github Open Source
Open Source
Apache-2.0
2,021
declare
qussarah
Kotlin
Code
17
37
// "Make 'My' final" "true" open class My(open val x: Int) { val y = <caret>x }
15,269
https://github.com/AdrianWR/libasm/blob/master/src/ft_strcpy.s
Github Open Source
Open Source
MIT
null
libasm
AdrianWR
GAS
Code
282
611
; **************************************************************************** # ; _ _ ___ _ _ _ _ # ; | || |__ \ | (_) | | | | # ; | || |_ ) | __| |_ ___ __ _ ___ ___ ___ _ __ ___ | |__ | |_ _ # ; |__ _/ / / _` | / __|/ _` / __/ __|/ _ \ '_ ` _ \| '_ \| | | | | # ; | |/ /_ | (_| | \__ \ (_| \__ \__ \ __/ | | | | | |_) | | |_| | # ; |_|____| \__,_|_|___/\__,_|___/___/\___|_| |_| |_|_.__/|_|\__, | # ; __/ | # ; ft_strcpy.s |___/ # ; By: iwillens <iwillens@student.42sp.org.br> # ; Created: 2020/04/02 22:33:26 by iwillens # ; Updated: 2020/04/02 22:34:32 by aroque # ; # ; _. ._ _ _. _ o o | | _ ._ _ ._ _| o ._ o _ # ; (_| | (_) (_| |_| (/_ | \/\/ | | | (/_ | | _> | (_| | |_| | | (_ # ; | _| # ; **************************************************************************** # ; first argument: rdi ; second argument: rsi ; third argument: rdx ; fourth argument: rcx ; fifth argument: r8 ; sixth argument: r9 global ft_strcpy section .text ft_strcpy: xor rcx, rcx ; clear counter mov rax, rdi ; set dest addres to rax (for return) looping: mov dl, byte[rsi + rcx] ; move rsi current char to rdi mov byte[rdi + rcx], dl ; moving before compare garantees \0 termination cmp byte[rsi + rcx], 0 ; check if \0 je end inc rcx ; incrementing counter will move to the next char jmp looping end: ret
5,902
https://github.com/amolloy/LinkAgainstTheWorldStudio/blob/master/Frameworks/TileMap/TileMap/TileMapLoader.swift
Github Open Source
Open Source
MIT
2,016
LinkAgainstTheWorldStudio
amolloy
Swift
Code
239
733
// // TileMapLoader.swift // TileMap // // Created by Andrew Molloy on 8/9/15. // Copyright © 2015 Andrew Molloy. All rights reserved. // import Foundation extension TileMap { enum Error : ErrorType { case InvalidHeaderError } public func open() throws -> Bool { inputStream.open() try loadFileHeader(inputStream) return true } public func loadChunks() throws { try loadChunks(inputStream) } private func loadFileHeader(inputStream : NSInputStream) throws { guard let formTag = inputStream.readChunkTag() else { throw Error.InvalidHeaderError } if (formTag != "FORM") { throw Error.InvalidHeaderError } // Skip past the data length guard let _ = inputStream.readBigInt() else { throw Error.InvalidHeaderError } guard let fmapTag = inputStream.readChunkTag() else { throw Error.InvalidHeaderError } if (fmapTag != "FMAP") { throw Error.InvalidHeaderError } } private func loadChunks(inputStream : NSInputStream) throws { while let chunk = try loadChunk(inputStream) { print("Loaded chunk type \(chunk)") } } private func loadChunk(inputStream: NSInputStream) throws -> Loadable? { guard let chunkTag = inputStream.readChunkTag() else { return nil } guard let chunkType = ChunkType(rawValue: chunkTag) else { return nil } guard let chunkLength = inputStream.readBigInt() else { return nil } let chunk : Loadable? if let loader = loaders[chunkType] { chunk = loader.init(inputStream: inputStream, dataLength: chunkLength, tileMap: self, chunkType: chunkType) } else { chunk = Unknown(inputStream: inputStream, dataLength: chunkLength, tileMap: self, chunkType: chunkType) } return chunk } func addLayer(layer: Layer, index: Int) { assert(index == layers.count, "Layers must appear in the file in order") layers.append(layer) } func addUnknownChunk(chunk: Unknown) { unknownChunks.append(chunk) } }
29,314
https://github.com/gatherdigital/endpoint/blob/master/spec/lib/endpoint/soap/client_spec.rb
Github Open Source
Open Source
MIT
null
endpoint
gatherdigital
Ruby
Code
616
2,357
require 'spec_helper' describe Endpoint::Soap::Client do subject { described_class.new version, endpoint, options } let(:version) { 2 } let(:endpoint) { 'http://endpoint.com' } let(:options) { {} } let(:soap_response) {{ status: 200, body: '<Envelope><Body></Body></Envelope>' }} let(:soap_fault_response) {{ status: 500, body: '<Envelope><Body><Fault><Code>Server</Code><Reason></Reason></Fault></Body></Envelope>' }} describe 'options' do let(:response) { double :response, code: 200, parsed_response: Nokogiri::XML(soap_response[:body]) } it 'has default options' do described_class.should_receive(:post) do |url, opts| opts.should include({ timeout: 500 }) response end subject.request end describe 'custom' do let(:options) {{ timeout: 501, proxy: { server: 'host.name', port: '3929' } }} it 'uses provided options' do described_class.should_receive(:post) do |url, opts| opts[:timeout].should == 501 response end subject.request end it 'extracts proxy options' do described_class.should_receive(:post) do |url, opts| opts[:http_proxyaddr].should == 'host.name' opts[:http_proxyport].should == '3929' response end subject.request end end end describe 'request' do it 'includes Content-Length header' do body = 'hello there you all' soap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<env:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <env:Body>hello there you all</env:Body>\n</env:Envelope>\n" stub_request(:post, endpoint) .with(headers: { 'Content-Length' => soap.size }, body: soap) .to_return(soap_response) subject.request body: body end it 'retries when Timeout::Error' do stub_request(:post, endpoint).to_timeout.then.to_return(soap_response) subject.request end it 'retries Timeout::Error only 5 times' do stub_request(:post, endpoint).to_timeout.times(5) lambda do subject.request end.should raise_error(/Too many failures.*execution expired/) end it 'retries when Errno::ECONNRESET' do stub_request(:post, endpoint).to_raise(Errno::ECONNRESET).then.to_return(soap_response) subject.request end it 'retries Errno::ECONNRESET only 5 times' do stub_request(:post, endpoint).to_raise(Errno::ECONNRESET).times(5) expect do subject.request end.to raise_error(/Too many failures.*Connection reset by peer/) end it 'retries 404 only 5 times' do stub_request(:post, endpoint) .to_return({ status: 404, body: '<html></html>' }) .times(5) expect do subject.request end.to raise_error(/Too many failures.*404/) end end describe 'SOAP 1.1' do let(:version) { 1 } let(:request_options) {{ action: 'http://host.com/action' }} let(:soap_fault_response) {{ status: 500, body: '<Envelope><Body><Fault><faultcode>Server</faultcode><faultstring></faultstring></Fault></Body></Envelope>' }} it 'includes Content-Type header for SOAP 1.1' do stub_request(:post, endpoint) .with(headers: { 'Content-Type' => 'text/xml;charset=UTF-8' }) .to_return(soap_response) subject.request request_options end it 'includes SOAPAction header' do stub_request(:post, endpoint) .with(headers: { 'SOAPAction' => 'http://host.com/action' }) .to_return(soap_response) subject.request request_options end it 'raises error when no SOAPAction header provided' do expect { subject.request }.to raise_error(/SOAPAction/) end it 'raises error when Fault' do stub_request(:post, endpoint).to_return(soap_fault_response) expect { subject.request request_options }.to raise_error(Endpoint::Soap::Fault, /Server/) end it 'answers the builder for version 1' do subject.fault_builder.should be_instance_of(Endpoint::Soap::Fault::Builder1) end end describe 'SOAP 1.2' do let(:version) { 2 } it 'includes Content-Type header for SOAP 1.2' do stub_request(:post, endpoint) .with(headers: { 'Content-Type' => 'application/soap+xml;charset=UTF-8' }) .to_return(soap_response) subject.request end it 'raises error when Fault' do stub_request(:post, endpoint).to_return(soap_fault_response) expect { subject.request }.to raise_error(Endpoint::Soap::Fault, /Server/) end it 'answers the builder for version 2' do subject.fault_builder.should be_instance_of(Endpoint::Soap::Fault::Builder2) end end describe 'observer' do let(:observer) do double('Observer').tap do |o| o.stub(:request) o.stub(:response) end end before do subject.observer = observer stub_request(:post, endpoint) .to_return(soap_response) end describe 'notification' do after { subject.request } it 'is made on request' do observer.should_receive(:request) do |method, url, options| method.should == :post url.should == endpoint options.should have_key(:body) options.should have_key(:headers) end end it 'is made on response' do observer.should_receive(:response) do |method, url, options| method.should == :post url.should == endpoint options.should have_key(:status) options.should have_key(:body) options.should have_key(:headers) end end end describe 'notification of errors' do it 'is made on soap fault' do stub_request(:post, endpoint).to_return(soap_fault_response) observer.should_receive(:request) observer.should_receive(:response) lambda do subject.request end.should raise_error(Endpoint::Soap::Fault) end it 'is made on HTTP errors' do stub_request(:post, endpoint).to_return(status: 500) observer.should_receive(:request) observer.should_receive(:response) lambda do subject.request end.should raise_error(Endpoint::HttpError) end end describe 'filters' do specify 'are applied to requests' do observer.should_receive(:request) do |method, url, options| options[:body].should =~ /stuff blah stuff/ end subject.request body: 'stuff password stuff', observer_body_filters:{'password' => 'blah'} end specify 'are applied to responses' do stub_request(:post, endpoint).to_return(body: '<Envelope><Body>stuff password stuff</Body></Envelope>') observer.should_receive(:response) do |method, url, options| options[:body].should =~ /stuff blah stuff/ end subject.request body: 'the request', observer_body_filters:{'password' => 'blah'} end end describe 'body parse errors' do before { Endpoint::ResponseParser.any_instance.should_receive(:perform_parsing).and_raise('error parsing') } after do lambda do subject.request end.should raise_error('error parsing') end it 'should notify request when request fails' do observer.should_receive(:request) end it 'should notify response when request fails' do observer.should_receive(:response) end end end end
25,109
https://github.com/fmarcos8/teste-beelabs-front/blob/master/src/http/index.js
Github Open Source
Open Source
MIT
null
teste-beelabs-front
fmarcos8
JavaScript
Code
38
141
import axios from "axios"; const http = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 60000, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } }); http.interceptors.response.use( response => response, error => { if (error.response) { return Promise.reject(error.response.data); } } ) export default http;
313
https://github.com/srdgame/frappe_make/blob/master/make/make/doctype/make_batch/make_batch.py
Github Open Source
Open Source
MIT
null
frappe_make
srdgame
Python
Code
96
306
# -*- coding: utf-8 -*- # Copyright (c) 2017, Dirk Chang and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import throw, _ from frappe.model.document import Document class MakeBatch(Document): def validate(self): if len(self.batch_no) != 6: throw(_("Batch NO length must be six!")) serial_code = frappe.get_value("Make Item", self.item, "serial_code") self.serial_code = "{0}-{1}".format(serial_code, self.batch_no) def batch_create(self, count): for i in range(count): doc = frappe.get_doc({ "doctype": "Make Serial NO", "item": self.item, "batch": self.name, }).insert() return "{0} Serial NO has been created!".format(count) def on_doctype_update(): """Add indexes in `Make Batch`""" frappe.db.add_index("Make Batch", ["item", "batch_no"])
16,778
https://github.com/repetere/ts-deeplearning/blob/master/test/unit/math_js_spec.js
Github Open Source
Open Source
MIT
2,021
ts-deeplearning
repetere
JavaScript
Code
782
2,046
import chai from 'chai'; import { TensorScriptModelInterface, size, flatten, } from '../../lib/model_interface.js'; import assert from 'assert'; const expect = chai.expect; const array = { reshape: TensorScriptModelInterface.reshape, flatten, }; const reshape = array.reshape; describe('util.array', function () { /** @test {../../lib/model_interface.mjs~size} */ describe('size', function () { it('should calculate the size of a scalar', function () { assert.deepEqual(size(2), []); assert.deepEqual(size('string'), []); }); it('should calculate the size of a 1-dimensional array', function () { assert.deepEqual(size([]), [0, ]); assert.deepEqual(size([1, ]), [1, ]); assert.deepEqual(size([1, 2, 3, ]), [3, ]); }); it('should calculate the size of a 2-dimensional array', function () { assert.deepEqual(size([[], ]), [1, 0, ]); assert.deepEqual(size([[], [], ]), [2, 0, ]); assert.deepEqual(size([[1, 2, ], [3, 4, ], ]), [2, 2, ]); assert.deepEqual(size([[1, 2, 3, ], [4, 5, 6, ], ]), [2, 3, ]); }); it('should calculate the size of a 3-dimensional array', function () { assert.deepEqual(size([[[], ], ]), [1, 1, 0, ]); assert.deepEqual(size([[[], [], ], ]), [1, 2, 0, ]); assert.deepEqual(size([[[], [], ], [[], [], ], ]), [2, 2, 0, ]); assert.deepEqual(size([[[1, ], [2, ], ], [[3, ], [4, ], ], ]), [2, 2, 1, ]); assert.deepEqual(size([[[1, 2, ], [3, 4, ], ], [[5, 6, ], [7, 8, ], ], ]), [2, 2, 2, ]); assert.deepEqual(size([ [[1, 2, 3, 4, ], [5, 6, 7, 8, ], ], [[1, 2, 3, 4, ], [5, 6, 7, 8, ], ], [[1, 2, 3, 4, ], [5, 6, 7, 8, ], ], ]), [3, 2, 4, ]); }); it('should not validate whether all dimensions match', function () { assert.deepEqual(size([[1, 2, ], [3, 4, 5, ], ]), [2, 2, ]); }); }); /** @test {../../lib/model_interface.mjs~reshape} */ describe('reshape', function () { it('should reshape a 1 dimensional array into a 2 dimensional array', function () { const a = [1, 2, 3, 4, 5, 6, 7, 8, ]; assert.deepEqual( reshape(a, [2, 4, ]), [[1, 2, 3, 4, ], [5, 6, 7, 8, ], ] ); assert.deepEqual( reshape(a, [4, 2, ]), [[1, 2, ], [3, 4, ], [5, 6, ], [7, 8, ], ] ); assert.deepEqual( reshape(a, [1, 8, ]), [[1, 2, 3, 4, 5, 6, 7, 8, ], ] ); assert.deepEqual( reshape(a, [1, 1, 8, ]), [[[1, 2, 3, 4, 5, 6, 7, 8, ], ], ] ); }); it('should reshape a 2 dimensional array into a 1 dimensional array', function () { const a = [ [0, 1, ], [2, 3, ], ]; assert.deepEqual( reshape(a, [4, ]), [0, 1, 2, 3, ] ); }); it('should reshape a 3 dimensional array', function () { const a = [[[1, 2, ], [3, 4, ], ], [[5, 6, ], [7, 8, ], ], ]; assert.deepEqual( reshape(a, [8, ]), [1, 2, 3, 4, 5, 6, 7, 8, ] ); assert.deepEqual( reshape(a, [2, 4, ]), [[1, 2, 3, 4, ], [5, 6, 7, 8, ], ] ); }); it('should throw an error when reshaping to a dimension with length 0', function () { assert.throws(function () { reshape([1, 2, ], [0, 2, ]); }, /DimensionError/); assert.throws(function () { reshape([1, 2, ], [2, 0, ]); }, /DimensionError/); }); it('should throw an error when reshaping a non-empty array to an empty array', function () { assert.throws(function () { reshape([1, ], []); }, /DimensionError/); assert.throws(function () { reshape([1, 2, ], []); }, /DimensionError/); }); it('should throw an error when reshaping to a size that differs from the original', function () { const a = [1, 2, 3, 4, 5, 6, 7, 8, 9, ]; assert.deepEqual( reshape(a, [3, 3, ]), [[1, 2, 3, ], [4, 5, 6, ], [7, 8, 9, ], ] ); assert.throws(function () { reshape(a, [3, 2, ]); }, /DimensionError/); assert.throws(function () { reshape(a, [2, 3, ]); }, /DimensionError/); assert.throws(function () { reshape(a, [3, 3, 3, ]); }, /DimensionError/); assert.throws(function () { reshape(a, [3, 4, ]); }, /DimensionError/); assert.throws(function () { reshape(a, [4, 3, ]); }, /DimensionError/); }); it('should throw an error in case of wrong type of arguments', function () { assert.throws(function () { reshape([], 2); }, /Array expected/); assert.throws(function () { reshape(2); }, /Array expected/); }); }); /** @test {../../lib/model_interface.mjs~flatten} */ describe('flatten', function () { it('should flatten a scalar', function () { assert.deepEqual(array.flatten(1), 1); }); it('should flatten a 1 dimensional array', function () { assert.deepEqual(array.flatten([1, 2, 3, ]), [1, 2, 3, ]); }); it('should flatten a 2 dimensional array', function () { assert.deepEqual(array.flatten([[1, 2, ], [3, 4, ], ]), [1, 2, 3, 4, ]); }); it('should flatten a 3 dimensional array', function () { assert.deepEqual(array.flatten([[[1, 2, ], [3, 4, ], ], [[5, 6, ], [7, 8, ], ], ]), [1, 2, 3, 4, 5, 6, 7, 8, ]); }); it('should return a new array', function () { const input = [3, 2, 1, ]; const flat = array.flatten(input); flat.sort(); assert.deepEqual(input, [3, 2, 1, ]); }); }); });
13,798
https://github.com/bgoonz/UsefulResourceRepo2.0/blob/master/_ORGS/NPM/node/test/sequential/test-debugger-exec-scope.js
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,022
UsefulResourceRepo2.0
bgoonz
JavaScript
Code
82
312
'use strict'; const common = require('../common'); common.skipIfInspectorDisabled(); const fixtures = require('../common/fixtures'); const startCLI = require('../common/debugger'); const assert = require('assert'); // exec .scope { const cli = startCLI([fixtures.path('debugger/backtrace.js')]); function onFatal(error) { cli.quit(); throw error; } cli.waitForInitialBreak() .then(() => cli.waitForPrompt()) .then(() => cli.stepCommand('c')) .then(() => cli.command('exec .scope')) .then(() => { assert.match( cli.output, /'moduleScoped'/, 'displays closure from module body'); assert.match(cli.output, /'a'/, 'displays local / function arg'); assert.match(cli.output, /'l1'/, 'displays local scope'); assert.doesNotMatch( cli.output, /'encodeURIComponent'/, 'omits global scope' ); }) .then(() => cli.quit()) .then(null, onFatal); }
50,459
https://github.com/chrisesler/opentsdb-horizon/blob/master/frontend/src/app/dashboard/components/dashboard-save-dialog/_dashboard-save-dialog.theme.scss
Github Open Source
Open Source
Apache-2.0
null
opentsdb-horizon
chrisesler
SCSS
Code
47
208
@mixin dashboard-save-dialog-component-theme() { $divider: mat-color($foreground, divider); .dashboard-save-dialog { .mat-dialog-title { background-color: mat-color($other, status-success); color: mat-color($other, status-success-contrast); } } // CDK Items // backdrop .dashboard-save-dialog-backdrop { background-color: mat-color($foreground, disabled); } // panel .dashboard-save-dialog-panel { .mat-dialog-title { border-bottom: 1px solid $divider; } .mat-dialog-actions { background-color: $divider; } } }
3,228
https://github.com/gregorschatz/DataTablesSrc/blob/master/test/api/core/state.save().js
Github Open Source
Open Source
MIT
2,022
DataTablesSrc
gregorschatz
JavaScript
Code
235
727
// todo tests // - Check it exists and is a function // - Check it returns an API instance // - Check it triggers a save // - Check that when reloaded the table will reflect this saved state describe('core - state.save()', function() { dt.libs({ js: ['jquery', 'datatables'], css: ['datatables'] }); describe('Check the defaults', function() { dt.html('basic'); it('Exists and is a function', function() { expect(typeof $('#example').DataTable().state.save).toBe('function'); }); it('Returns an object', function() { let table = $('#example').DataTable(); expect(table.state.save() instanceof $.fn.dataTable.Api).toBe(true); }); }); describe('Functional tests', function() { // Clear down save state before proceeding (otherwise old stuff may be lurking that will affect us) dt.html('basic'); it('Clear state save', function() { let table = $('#example').DataTable(); table.state.clear(); }); dt.html('basic'); it('State save does initiate a stateSaveCallback', function() { let inTest = false; let pageLength = 0; let table = $('#example').DataTable({ stateSave: true, stateSaveCallback: function(settings, data) { if (inTest) { // stops the update from an automatic stave save pageLength = data.length; } } }); table.page.len(15).draw(); expect(pageLength).toBe(0); inTest = true; table.state.save(); expect(pageLength).toBe(15); }); dt.html('basic'); it('Save state for reloading', function() { let table = $('#example').DataTable({ stateSave: true }); // note page() doesn't initiate a save - only the draw() does table.page(1); table.state.save(); expect(table.page()).toBe(1); }); dt.html('basic'); it('Save state loads', function() { let table = $('#example').DataTable({ stateSave: true }); expect(table.page()).toBe(1); }); dt.html('basic'); it('Ensure no errors if stateSave not enabled', function() { let table = $('#example').DataTable({ stateSave: false }); table.state.save(); expect(table.page.info().start).toBe(0); }); }); });
2,812
https://github.com/ewjoachim/procrastinate/blob/master/tests/unit/test_worker.py
Github Open Source
Open Source
MIT
2,020
procrastinate
ewjoachim
Python
Code
519
2,277
import pendulum import pytest from procrastinate import exceptions, jobs, tasks, worker pytestmark = pytest.mark.asyncio async def test_run(app, connector): class TestWorker(worker.Worker): i = 0 async def process_next_job(self): self.i += 1 if self.i == 2: raise exceptions.NoMoreJobs elif self.i == 3: raise exceptions.StopRequested test_worker = TestWorker(app=app, queues=["marsupilami"]) await test_worker.run() assert app.connector.queries == [ ("listen_for_jobs", "procrastinate_queue#marsupilami") ] @pytest.mark.parametrize( "side_effect, status", [ (None, "succeeded"), (exceptions.JobError(), "failed"), (exceptions.TaskNotFound(), "failed"), ], ) async def test_process_next_job( mocker, app, job_factory, connector, side_effect, status ): job = job_factory(id=1) await app.job_store.defer_job(job) test_worker = worker.Worker(app, queues=["queue"]) async def coro(*args, **kwargs): pass run_job = mocker.patch( "procrastinate.worker.Worker.run_job", side_effect=side_effect or coro ) await test_worker.process_next_job() run_job.assert_called_with(job=job) assert connector.jobs[1]["status"] == status async def test_process_next_job_raise_no_more_jobs(app): test_worker = worker.Worker(app) with pytest.raises(exceptions.NoMoreJobs): await test_worker.process_next_job() async def test_process_next_job_raise_stop_requested(app): test_worker = worker.Worker(app) @app.task def empty(): test_worker.stop_requested = True await empty.defer_async() with pytest.raises(exceptions.StopRequested): await test_worker.process_next_job() async def test_process_next_job_retry_failed_job(connector, mocker, app, job_factory): job = job_factory(id=1) await app.job_store.defer_job(job) mocker.patch( "procrastinate.worker.Worker.run_job", side_effect=exceptions.JobRetry( scheduled_at=pendulum.datetime(2000, 1, 1, tz="UTC") ), ) test_worker = worker.Worker(app, queues=["queue"]) await test_worker.process_next_job() assert len(connector.jobs) == 1 new_job = connector.jobs[1] assert new_job["status"] == "todo" assert new_job["id"] == 1 assert new_job["scheduled_at"] == pendulum.datetime(2000, 1, 1, tz="UTC") async def test_run_job(app): result = [] @app.task(queue="yay", name="task_func") def task_func(a, b): result.append(a + b) job = jobs.Job( id=16, task_kwargs={"a": 9, "b": 3}, lock="sherlock", task_name="task_func", queue="yay", ) test_worker = worker.Worker(app, queues=["yay"]) await test_worker.run_job(job) assert result == [12] async def test_run_job_async(app): result = [] @app.task(queue="yay", name="task_func") async def task_func(a, b): result.append(a + b) job = jobs.Job( id=16, task_kwargs={"a": 9, "b": 3}, lock="sherlock", task_name="task_func", queue="yay", ) test_worker = worker.Worker(app, queues=["yay"]) await test_worker.run_job(job) assert result == [12] async def test_run_job_log_result(caplog, app): caplog.set_level("INFO") result = [] def task_func(a, b): # pylint: disable=unused-argument s = a + b result.append(s) return s task = tasks.Task(task_func, app=app, queue="yay", name="job") app.tasks = {"task_func": task} job = jobs.Job( id=16, task_kwargs={"a": 9, "b": 3}, lock="sherlock", task_name="task_func", queue="yay", ) test_worker = worker.Worker(app, queues=["yay"]) await test_worker.run_job(job) assert result == [12] records = [record for record in caplog.records if record.action == "job_success"] assert len(records) == 1 record = records[0] assert record.result == 12 async def test_run_job_log_name(caplog, app): caplog.set_level("INFO") def task_func(): pass task = tasks.Task(task_func, app=app, queue="yay", name="job") app.tasks = {"task_func": task} job = jobs.Job( id=16, task_kwargs={}, lock="sherlock", task_name="task_func", queue="yay", ) test_worker = worker.Worker(app, queues=["yay"]) await test_worker.run_job(job) assert len(caplog.records) == 2 assert all(record.name.endswith("worker") for record in caplog.records) assert all(not hasattr(record, "worker_name") for record in caplog.records) caplog.clear() test_worker = worker.Worker(app, queues=["yay"], name="w1") await test_worker.run_job(job) assert len(caplog.records) == 2 assert all(record.name.endswith("worker.w1") for record in caplog.records) assert all(record.worker_name == "w1" for record in caplog.records) async def test_run_job_error(app): def job(a, b): # pylint: disable=unused-argument raise ValueError("nope") task = tasks.Task(job, app=app, queue="yay", name="job") task.func = job app.tasks = {"job": task} job = jobs.Job( id=16, task_kwargs={"a": 9, "b": 3}, lock="sherlock", task_name="job", queue="yay", ) test_worker = worker.Worker(app, queues=["yay"]) with pytest.raises(exceptions.JobError): await test_worker.run_job(job) async def test_run_job_retry(app): def job(a, b): # pylint: disable=unused-argument raise ValueError("nope") task = tasks.Task(job, app=app, queue="yay", name="job", retry=True) task.func = job app.tasks = {"job": task} job = jobs.Job( id=16, task_kwargs={"a": 9, "b": 3}, lock="sherlock", task_name="job", queue="yay", ) test_worker = worker.Worker(app, queues=["yay"]) with pytest.raises(exceptions.JobRetry): await test_worker.run_job(job) async def test_run_job_not_found(app): job = jobs.Job( id=16, task_kwargs={"a": 9, "b": 3}, lock="sherlock", task_name="job", queue="yay", ) test_worker = worker.Worker(app, queues=["yay"]) with pytest.raises(exceptions.TaskNotFound): await test_worker.run_job(job)
24,634