repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
vgrem/Office365-REST-Python-Client
office365/sharepoint/attachments/attachmentfile.py
2245
from office365.runtime.paths.resource_path import ResourcePath from office365.runtime.paths.service_operation import ServiceOperationPath from office365.sharepoint.internal.queries.download_file import create_download_file_query from office365.sharepoint.internal.queries.upload_file import create_upload_file_query from office365.sharepoint.files.file import AbstractFile class AttachmentFile(AbstractFile): """Represents an attachment file in a SharePoint List Item.""" def download(self, file_object): """Download attachment file content :type file_object: typing.IO """ def _download_file(): source_file = self.context.web.get_file_by_server_relative_path(self.server_relative_url) qry = create_download_file_query(source_file, file_object) self.context.add_query(qry) self.ensure_property("ServerRelativeUrl", _download_file) return self def upload(self, file_object): """ :type file_object: typing.IO """ def _upload_file(): target_file = self.context.web.get_file_by_server_relative_url(self.server_relative_url) qry = create_upload_file_query(target_file, file_object) self.context.add_query(qry) self.ensure_property("ServerRelativeUrl", _upload_file) return self @property def file_name(self): """ :rtype: str or None """ return self.properties.get("FileName", None) @property def server_relative_url(self): """ :rtype: str or None """ return self.properties.get("ServerRelativeUrl", None) @property def parent_collection(self): """ :rtype: office365.sharepoint.attachments.attachmentfile_collection.AttachmentFileCollection """ return self._parent_collection def set_property(self, name, value, persist_changes=True): super(AttachmentFile, self).set_property(name, value, persist_changes) # fallback: create a new resource path if name == "ServerRelativeUrl": self._resource_path = ServiceOperationPath( "getFileByServerRelativeUrl", [value], ResourcePath("Web"))
mit
ccummings/can-migrate-codemods
test/fixtures/version-3/can-map-backup/require-output.js
28
require('can-map-backup');
mit
brucevsked/vskeddemolist
vskeddemos/projects/jogampdemo/src/com/vsked/lesson1/HelloWorld.java
1583
package com.vsked.lesson1; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import javax.swing.JFrame; import com.jogamp.opengl.util.FPSAnimator; public class HelloWorld { public static void main(String[] args) { String windowTitle="this is window title"; int windowWidth=500; int windowHeight=500; GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); GLCanvas glCanvas = new GLCanvas(new GLCapabilities(GLProfile.get(GLProfile.GL2))); glCanvas.setSize( windowWidth, windowHeight ); glCanvas.setIgnoreRepaint( true ); JFrame frame = new JFrame( windowTitle ); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.getContentPane().setLayout( new BorderLayout() ); frame.getContentPane().add( glCanvas, BorderLayout.CENTER ); FPSAnimator animator = new FPSAnimator( glCanvas, 60 ); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setSize( frame.getContentPane().getPreferredSize() ); frame.setLocation(( screenSize.width - frame.getWidth() ) / 2 , ( screenSize.height - frame.getHeight() ) / 2 ); frame.setVisible( true ); glCanvas.requestFocus(); animator.start(); } }
mit
UKHomeOffice/passports-form-wizard
example/routes/branching/steps.js
652
module.exports = { '/': { entryPoint: true, resetJourney: true, next: 'choose-direction' }, '/choose-direction': { fields: ['direction'], next: [ { field: 'direction', value: 'right', next: 'right-branch' }, { field: 'direction', value: 'left', next: 'left-branch' }, 'neither-branch' ] }, '/right-branch': { fields: ['right-only'], next: 'done' }, '/left-branch': { fields: ['left-only'], next: 'done' }, '/neither-branch': { next: 'done' }, '/done': { noPost: true } };
mit
lust4life/WebApiProxy
WebApiProxy.Api.Sample/Areas/HelpPage/HelpPageAreaRegistration.cs
680
using System.Web.Http; using System.Web.Mvc; namespace WebApiProxy.Api.Sample.Areas.HelpPage { public class HelpPageAreaRegistration : AreaRegistration { public override string AreaName { get { return "HelpPage"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "HelpPage_Default", "Help/{action}/{apiId}", new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); HelpPageConfig.Register(GlobalConfiguration.Configuration); } } }
mit
SolidEdgeCommunity/Samples
Assembly/AddOccurrenceByFilename/cs/AddOccurrenceByFilename/Properties/AssemblyInfo.cs
1422
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AddOccurrenceByFilename")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AddOccurrenceByFilename")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0607c11b-53a1-4480-9d67-d208e252a7c7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
larister/SimBanker
app/scripts/helpers/SpawnHelper.js
988
define([ 'helpers/MortgageHelper', ], function( MortgageHelper ) { 'use strict'; return Backbone.Model.extend({ initialize: function(){ this.brokers = 1; this.houseCount = 1000; this.houseTypes = _(MortgageHelper.mortgageTypes).pluck('type'); window.setTimeout(_.bind(this.spawnMortgage, this), this.nextSpawnTime()); }, nextSpawnTime: function() { return (Math.random() * 6000) / this.brokers; }, spawnMortgage: function(){ this.houseCount--; var typeIndex = (Math.random() * 3); typeIndex = Math.floor(typeIndex); this.trigger('spawnMortgage', this.houseTypes[typeIndex]); if (this.houseCount > 0) { window.setTimeout(_.bind(this.spawnMortgage, this), this.nextSpawnTime()); } }, addBroker: function() { this.brokers++; } }); });
mit
mriveralee/tracheal-aire2
tests/dicom/dicomParser.test.js
1093
/** * Tests for the 'dicom/dicomParser.js' file. */ // Do not warn if these variables were not defined before. /* global module, asyncTest, equal, start */ module("dicomParser"); asyncTest("Test DICOM parsing.", 2, function() { // Local file: forbidden... // parse the DICOM file /*var reader = new FileReader(); reader.onload = function(event) { // parse DICOM file var data = dwv.image.getDataFromDicomBuffer(event.target.result); }; var file = new File("cta.dcm"); reader.readAsArrayBuffer(file);*/ var request = new XMLHttpRequest(); var url = "http://x.babymri.org/?53320924&.dcm"; request.open('GET', url, true); request.responseType = "arraybuffer"; request.onload = function(/*event*/) { // parse DICOM var data = dwv.image.getDataFromDicomBuffer(request.response); // check values equal(data.info.Rows.value, 256, "Number of rows"); equal(data.info.Columns.value, 256, "Number of columns"); // start async test start(); }; request.send(null); });
mit
pluskal/AppIdent
src/AppIdent.Tests/Features/Bases/SYNPacketsBaseTests.cs
2947
//Copyright (c) 2017 Jan Pluskal // //Permission is hereby granted, free of charge, to any person //obtaining a copy of this software and associated documentation //files (the "Software"), to deal in the Software without //restriction, including without limitation the rights to use, //copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the //Software is furnished to do so, subject to the following //conditions: // //The above copyright notice and this permission notice shall be //included in all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, //EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES //OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND //NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT //HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, //WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR //OTHER DEALINGS IN THE SOFTWARE. using System; using System.Net; using System.Threading.Tasks; using AppIdent.Features.Bases; using NetfoxFrameworkAPI.Tests.Properties; using Netfox.Core.Enums; using NUnit.Framework; namespace AppIdent.Tests.Features.Bases { [TestFixture] public class SYNPacketsBaseTests : FeatureBaseTests<SYNPacketsBase> { [Test] public override void ComputeDistanceToProtocolModelTest_TrainingToTesingDistance_ExpectedDistance() { this.ComputeDistanceToProtocolModelTest_TrainingToTesingDistance_NotZero(0.0d); } [Test] public override void ComputeFeature_FeatureValueDownFlow_ExpectedFeatureValue() { var feature = this.ComputeFeature_FeatureValue_ExpectedFeatureValue(DaRFlowDirection.down, 1.0d); } #region Overrides of FeatureBaseTests<SYNPacketsBase> public override void ComputeFeature_FeatureValueNonFlow_ExpectedFeatureValue() { } #endregion [Test] public override void ComputeFeature_FeatureValueUpFlow_ExpectedFeatureValue() { var feature = this.ComputeFeature_FeatureValue_ExpectedFeatureValue(DaRFlowDirection.up, 1.0d); } [OneTimeSetUp] public void OneTimeSetUp() { this.OneTimeSetUp(SnoopersPcaps.Default.features_three_conver_putty_ssh_cap); this.L7ConversationTesting = this.GetL7ConversationForIp(new IPEndPoint(IPAddress.Parse("192.168.1.102"), 21253)); this.L7ConversationTraining1 = this.GetL7ConversationForIp(new IPEndPoint(IPAddress.Parse("192.168.1.102"), 21263)); this.L7ConversationTraining2 = this.GetL7ConversationForIp(new IPEndPoint(IPAddress.Parse("192.168.1.102"), 21273)); } #region Overrides of FeatureBaseTests<SYNPacketsBase> #endregion } }
mit
sherxon/AlgoDS
src/problems/easy/SecondMinimumNodeInBinaryTree.java
827
package problems.easy; import problems.utils.TreeNode; import java.util.*; /** * Why Did you create this class? what does it do? */ public class SecondMinimumNodeInBinaryTree { public int findSecondMinimumValue(TreeNode root) { if(root==null || root.left==null)return -1; Queue<TreeNode> q= new LinkedList<>(); Set<Integer> set= new HashSet<>(); q.add(root); PriorityQueue<Integer> pq= new PriorityQueue<>(); while(!q.isEmpty()){ TreeNode x=q.remove(); if(set.add(x.val)){ pq.add(x.val); } if(x.left!=null) q.add(x.left); if(x.right!=null) q.add(x.right); } if(set.size()<2)return -1; pq.remove(); return pq.remove(); } }
mit
kunl/ng2-blog
server/app.ts
1451
import * as express from 'express'; import * as path from 'path'; import * as cookieParser from 'cookie-parser'; import { json, urlencoded } from 'body-parser'; import * as webpack from 'webpack'; // 路径为 dist/server/app import pool from './db'; import router from './routes'; let __root_path = 'server'; let app = <express.Application>express(); // view engine setup app.set('views', path.join(__root_path, 'views')); app.set('view engine', 'ejs'); app.use(json()); app.use(urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join('public'))); import {home} from './routes/home' app.use('/', home) app.use('/api', router); // catch 404 and forward to error handler app.use(function (req, res, next) { var err: Error = new Error('Not Found'); err['status'] = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(<express.ErrorRequestHandler>function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(<express.ErrorRequestHandler>function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); export { app };
mit
FenrirUnbound/apotheosis
test/functional/login.test.js
1800
var atob = require('atob'); var cookie = require('cookie'); var expect = require('chai').expect; var mockery = require('mockery'); var path = require('path'); var q = require('q'); describe('Login', function describeLogin() { var server; before(function onceBefore() { var env; mockery.enable({ useCleanCache: true, warnOnUnregistered: false }); env = require('node-env-file'); env(path.resolve(__dirname, '..', '..', '.env'), {raise: false}); }); beforeEach(function beforeAll(done) { var main = require('../../lib/server'); main().then(function (hapiServer) { server = hapiServer; done(); }) .done(); }); afterEach(function afterAll(done) { server.stop(function () { server = null; mockery.resetCache(); done(); }); }); after(function onceAfter() { mockery.disable(); }); function parseAndValidateCookie(response) { var headerInformation = response.headers['set-cookie'].pop(); var cookies = cookie.parse(headerInformation); var result = {}; expect(cookies).to.have.property('player'); expect(cookies).to.have.property('Path') .that.deep.equal('/'); result.player = parseInt(atob(cookies.player), 10); return result; } it('should validate a login', function testLogin(done) { var testId = 88888888; server.inject({ method: 'POST', url: '/api/login', payload: {playerId: testId} }, function verify(response) { var cookies; expect(response.statusCode).to.equal(204); expect(response.headers).to.have.property('set-cookie'); cookies = parseAndValidateCookie(response); expect(cookies).to.have.property('player') .that.equal(testId); done(); }); }); });
mit
juniorgasparotto/SpentBook
src_old/SpentBook.Web/Global.asax.cs
618
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace SpentBook.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); BinderConfig.RegisterBinders(); } } }
mit
orznet/sigamed1
src/Admin/UnadBundle/Form/DocenteType.php
1648
<?php namespace Admin\UnadBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class DocenteType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('modalidad', 'choice', array( 'choices' => array('TC' => 'Tiempo Completo', 'MT' => 'Medio Tiempo'), 'required' => true, )) ->add('vinculacion', 'choice', array( 'choices' => array('HC' => 'Hora Catedra', 'DO' => 'Ocasional','DC' => 'Carrera' ), 'required' => true, )) ->add('cargo') ->add('resolucion') ->add('perfil') ->add('escuela', 'entity', array( 'class' => 'AdminUnadBundle:Escuela', 'property' => 'sigla', )) ->add('centro', 'entity', array( 'class' => 'AdminUnadBundle:Centro', 'property' => 'nombre', )) ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Admin\UnadBundle\Entity\Docente' )); } /** * @return string */ public function getName() { return 'admin_unadbundle_docente'; } }
mit
riselabs-ufba/alumni-projects
Software-Reuse/2016.2/S.H.E-spl/USBListener/src/usbListener/USBListener.java
5079
package usbListener; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import gnu.io.*; import com.she.manager.DriverMqtt; /*** * * @author Ramon; Edilton; * @category Drive USB. */ public class USBListener { private static String hostMQTT = null; private String buildName = null; private static final String LOCALHOST = "localhost"; /*** * */ public USBListener(){ this(LOCALHOST); } /*** * * @param hostMQTT */ public USBListener(String hostMQTT){ USBListener.hostMQTT = hostMQTT; } /*** * Listener the USB port. * @param serialPort USB port to be listened to by the method. * @throws Exception */ public void listener(SerialPort serialPort) { InputStream in = null; OutputStream out = null; try { // Pega o InputStream da porta serial. in = serialPort.getInputStream(); // Pega o OutputStream da porta serial. out = serialPort.getOutputStream(); // Pega as propriedades do Sensor/atuador. this.getWhoAreYou(in); if(this.buildName != null){ if(!this.buildName.isEmpty()){ // Executa a thread de leitura de dados. (new Thread(new SerialReader(in,this.buildName))).start(); // Executa a thread de escrita de dados. (new Thread(new SerialWriter(out))).start(); } else{ // Pega as propriedades do Sensor/atuador. this.getWhoAreYou(in); } }else{ // Pega as propriedades do Sensor/atuador. this.getWhoAreYou(in); } } catch (IOException e) { try{ if (in != null){ in.close(); in = null; } if(out != null){ out.close(); out = null; } if(serialPort != null){ serialPort.close(); serialPort = null; } } catch (IOException e1){ e1.printStackTrace(); } // TODO Auto-generated catch block e.printStackTrace(); } } /*** * * @param in * @param out * @throws IOException */ private void getWhoAreYou(InputStream in) throws IOException{ String message = null; byte[] buffer = new byte[1024]; int i = 0; int len = -1; for (i = 0; (len = in.read()) != '\n'; i++) { buffer[i] = (byte)len; } buffer[i] = '\0'; message = new String(buffer); if (message.length() > 0){ if (TrataMensagem.tryReadingV(message)){ message = TrataMensagem.getMensagem(); System.out.println(message); JsonDecode jsonDecode = new JsonDecode(); jsonDecode.decodeMessagePropertyDevice(message); this.buildName = jsonDecode.getName(); }else{ this.getWhoAreYou(in); } } } /*** * This class is responsible for reading data from the USB port. * @author Ramon; Edilton; * */ public class SerialReader implements Runnable { private InputStream in = null; private String buildName = null; /*** * Constructor * @param in */ public SerialReader(InputStream in) { this(in,"sensor/actuator"); } /*** * * @param in * @param buildName */ public SerialReader(InputStream in, String buildName) { this.in = in; this.buildName = buildName; } /*** * Performs the process of reading data from the USB port. */ public void run() { byte[] buffer = new byte[1024]; int len = -1; DriverMqtt driver = new DriverMqtt.DriverMqttBuilder().host(USBListener.hostMQTT).build(this.buildName); String message = null; try { int i = 0; while(true) { for (i = 0; (len = this.in.read()) != '\n'; i++) { buffer[i] = (byte)len; } buffer[i] = '\0'; message = new String(buffer); if (message.length() > 0){ if (TrataMensagem.tryReadingV(message)){ // Pega a String no formato JSON. message = TrataMensagem.getMensagem(); // Only for test. System.out.println(message); // Publish on MQTT server. driver.publish(message); } } } } catch(IOException e) { try { if (in != null){ in.close(); in = null; } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } } } /*** * * @author Ramon; Edilton; * */ public class SerialWriter implements Runnable { private OutputStream out; public SerialWriter(OutputStream out) { this.out = out; } /*** * Read execute. */ public void run() { try { int c = 0; while((c = System.in.read()) > -1) { this.out.write(c); } } catch(IOException e) { e.printStackTrace(); try { if(out != null){ out.close(); out = null; } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } }
mit
hl198181/mars
util/lib/merge.js
1678
/*! * merge-descriptors * Copyright(c) 2014 Jonathan Ong * MIT Licensed */ /** * Module exports. * @public */ module.exports = merge /** * Module variables. * @private */ var hasOwnProperty = Object.prototype.hasOwnProperty /** * Merge the property descriptors of `src` into `dest` * * @param {object} dest Object to add descriptors to * @param {object} src Object to clone descriptors from * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties * @returns {object} Reference to dest * @public */ function merge(dest, src, redefine) { if (!dest) { throw new TypeError('argument dest is required') } if (!src) { throw new TypeError('argument src is required') } if (redefine === undefined) { // Default to true redefine = true } Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { if (!redefine && hasOwnProperty.call(dest, name)) { // Skip desriptor return } // Copy descriptor var descriptor = Object.getOwnPropertyDescriptor(src, name) Object.defineProperty(dest, name, descriptor) }) return dest } merge.reDefine = function(dest, src) { if (!dest) { throw new TypeError('argument dest is required') } if (!src) { throw new TypeError('argument src is required') } Object.getOwnPropertyNames(dest).forEach(function forEachOwnPropertyName(name) { // Copy descriptor var descriptor = Object.getOwnPropertyDescriptor(src, name) Object.defineProperty(dest, name, descriptor) }) return dest }
mit
robotex82/twitter-bootstrap-components-rails
app/helpers/twitter/bootstrap/components/rails/v4/components_helper.rb
5176
module Twitter module Bootstrap module Components module Rails module V4 module ComponentsHelper def bootstrap_alert(options, &block) Twitter::Bootstrap::Components::V4::Alert.new(self, options, &block).perform end def bootstrap_badge(options = {}, &block) Twitter::Bootstrap::Components::V4::Badge.new(self, options, &block).perform end def bootstrap_breadcrumb(options) Twitter::Bootstrap::Components::V4::Breadcrumb.new(options).perform end def bootstrap_button(options = {}, &block) Twitter::Bootstrap::Components::V4::Button.new(self, options, &block).perform end def bootstrap_button_group(options = {}, &block) Twitter::Bootstrap::Components::V4::ButtonGroup.new(self, options, &block).perform end def bootstrap_card(options = {}, &block) Twitter::Bootstrap::Components::V4::Card.new(self, options, &block).perform end def bootstrap_carousel(options = {}, &block) Twitter::Bootstrap::Components::V4::Carousel.new(self, options, &block).perform end def bootstrap_carousel_item(options = {}, &block) Twitter::Bootstrap::Components::V4::CarouselItem.new(self, options, &block).perform end def bootstrap_collapse(options) Twitter::Bootstrap::Components::V4::Collapse.new(options).perform end def bootstrap_dropdown(options) Twitter::Bootstrap::Components::V4::Dropdown.new(options).perform end # add-on def bootstrap_flash Twitter::Bootstrap::Components::V4::Flash.new(self).perform end def bootstrap_form(options) Twitter::Bootstrap::Components::V4::Form.new(options).perform end def bootstrap_portrait_card(options = {}, &block) Twitter::Bootstrap::Components::V4::PortraitCard.new(self, options, &block).perform end # add-on def bootstrap_form_for(object, *args, &block) options = args.extract_options! simple_form_for(object, *(args << options.merge(builder: Twitter::Bootstrap::Components::Rails::V4::DefaultFormBuilder, :defaults => { :input_html => { :class => "form-control" } })), &block) end def bootstrap_input_group(options) Twitter::Bootstrap::Components::V4::InputGroup.new(options).perform end def bootstrap_jumbotron(options) Twitter::Bootstrap::Components::V4::Jumbotron.new(options).perform end def bootstrap_list_group(options) Twitter::Bootstrap::Components::V4::ListGroup.new(options).perform end def bootstrap_modal(options) Twitter::Bootstrap::Components::V4::Modal.new(options).perform end def bootstrap_nav(options = {}, &block) Twitter::Bootstrap::Components::V4::Nav.new(self, options, &block).perform end def bootstrap_nav_item(options = {}, &block) Twitter::Bootstrap::Components::V4::NavItem.new(self, options, &block).perform end def bootstrap_navbar(options) Twitter::Bootstrap::Components::V4::Navbar.new(options).perform end def bootstrap_navbar_brand(options = {}, &block) Twitter::Bootstrap::Components::V4::NavbarBrand.new(self, options, &block).perform end def bootstrap_pagination(options) Twitter::Bootstrap::Components::V4::Pagination.new(options).perform end def bootstrap_popover(options) Twitter::Bootstrap::Components::V4::Popover.new(options).perform end def bootstrap_progress(options) Twitter::Bootstrap::Components::V4::Progress.new(options).perform end def bootstrap_scrollspy(options) Twitter::Bootstrap::Components::V4::Scrollspy.new(options).perform end def bootstrap_tooltip(options) Twitter::Bootstrap::Components::V4::Tooltip.new(options).perform end # subhelpers def card_block(options = {}, &block) Twitter::Bootstrap::Components::V4::Card::Block.new(self, options, &block).perform end def card_header(options = {}, &block) Twitter::Bootstrap::Components::V4::Card::Header.new(self, options, &block).perform end def card_blockquote(options = {}, &block) Twitter::Bootstrap::Components::V4::Card::Blockquote.new(self, options, &block).perform end def card_footer(options = {}, &block) Twitter::Bootstrap::Components::V4::Card::Footer.new(self, options, &block).perform end end end end end end end
mit
manuel84/ruby_cbr
lib/ruby_cbr/similarity/mapping_similarity.rb
566
module CBR class Similarity class MappingSimilarity < Similarity def initialize(opts={}) opts[:mapping] = {} opts[:mapping].default = BigDecimal.new(0) opts[:borderpoints].each do |k, v| if k.eql?('{{default}}') opts[:mapping].default = BigDecimal.new(v) else opts[:mapping][k] = BigDecimal(v, 4) end end # maybe normalize mapping super(opts) end def compare(real_value) @options[:mapping][real_value] end end end end
mit
kapmahc/axe
plugins/nut/p-admin-cards.go
2994
package nut import ( "time" "github.com/gin-gonic/gin" "github.com/go-pg/pg" "github.com/kapmahc/axe/web" ) func (p *AdminPlugin) checkCardToken(user *User, tid uint) bool { return p.Dao.Is(user.ID, RoleAdmin) } func (p *AdminPlugin) editCardH(tid uint, token string) (string, string, error) { var it Card if err := p.DB.Model(&it). Column("id", "title", "summary"). Where("id = ?", tid). Limit(1).Select(); err != nil { return "", "", err } return it.Title, it.Summary, nil } func (p *AdminPlugin) updateCardH(id uint, body string) error { return p.DB.RunInTransaction(func(tx *pg.Tx) error { _, err := tx.Model(&Card{ ID: id, Summary: body, Type: web.HTML, UpdatedAt: time.Now(), }).Column("summary", "type", "updated_at").Update() return err }) } func (p *AdminPlugin) indexCards(l string, c *gin.Context) (interface{}, error) { var items []Card err := p.DB.Model(&items). Where("lang = ?", l). Order("loc ASC").Order("sort_order ASC").Select() return items, err } func (p *AdminPlugin) showCard(l string, c *gin.Context) (interface{}, error) { var item Card err := p.DB.Model(&item). Where("id = ?", c.Param("id")). Limit(1).Select() return item, err } type fmCard struct { Href string `json:"href" binding:"required"` Title string `json:"title" binding:"required"` Summary string `json:"summary" binding:"required"` Type string `json:"type" binding:"required"` Action string `json:"action" binding:"required"` Logo string `json:"logo" binding:"required"` Loc string `json:"loc" binding:"required"` SortOrder int `json:"sortOrder"` } func (p *AdminPlugin) createCard(l string, c *gin.Context) (interface{}, error) { var fm fmCard if err := c.BindJSON(&fm); err != nil { return nil, err } err := p.DB.RunInTransaction(func(tx *pg.Tx) error { return tx.Insert(&Card{ Href: fm.Href, Title: fm.Title, Summary: fm.Summary, Type: fm.Type, Action: fm.Action, Loc: fm.Loc, Logo: fm.Logo, SortOrder: fm.SortOrder, Lang: l, UpdatedAt: time.Now(), }) }) return gin.H{}, err } func (p *AdminPlugin) updateCard(l string, c *gin.Context) (interface{}, error) { var fm fmCard if err := c.BindJSON(&fm); err != nil { return nil, err } err := p.DB.RunInTransaction(func(tx *pg.Tx) error { _, err := tx.Model(&Card{ Href: fm.Href, Title: fm.Title, Summary: fm.Summary, Type: fm.Type, Action: fm.Action, Loc: fm.Loc, Logo: fm.Logo, SortOrder: fm.SortOrder, UpdatedAt: time.Now(), }). Column("href", "title", "summary", "action", "type", "logo", "loc", "sort_order", "updated_at"). Where("id = ?", c.Param("id")). Update() return err }) return gin.H{}, err } func (p *AdminPlugin) destroyCard(l string, c *gin.Context) (interface{}, error) { _, err := p.DB.Model(&Card{}).Where("id = ?", c.Param("id")).Delete() return gin.H{}, err }
mit
jasonlam604/Stringizer
tests/ConcatTest.php
817
<?php use Stringizer\Stringizer; /** * ConcatTest Unit Tests */ class ConcatTest extends PHPUnit_Framework_TestCase { public function testConcat() { $s = new Stringizer("fizz"); $this->assertEquals("fizz buzz", $s->concat(" buzz")); } public function testPreConcat() { $s = new Stringizer("fizz"); $this->assertEquals("buzz fizz", $s->concat("buzz ", true)); } /** * @expectedException InvalidArgumentException */ public function testInvalidArgumentNull() { $s = new Stringizer("fizz"); $s->concat(null); } /** * @expectedException InvalidArgumentException */ public function testInvalidArgumentNullPreAppend() { $s = new Stringizer("fizz"); $s->concat(null, true); } }
mit
mocchit/sanou
src/primitive/lexical/LexicalUnit.java
227
package primitive.lexical; public class LexicalUnit { private LexicalType type; public LexicalUnit(LexicalType type){ this.type = type; } public LexicalType getType(){ return this.type; } }
mit
Gladg/Triburg
public/modules/accessories-purchase-orders/controllers/accessories-purchase-orders.client.controller.js
2529
'use strict'; // Accessories purchase orders controller angular.module('accessories-purchase-orders').controller('AccessoriesPurchaseOrdersController', ['$scope', '$stateParams', '$location', 'Authentication', 'AccessoriesPurchaseOrders', function($scope, $stateParams, $location, Authentication, AccessoriesPurchaseOrders) { $scope.authentication = Authentication; // Create new Accessories purchase order $scope.create = function() { // Create new Accessories purchase order object var accessoriesPurchaseOrder = new AccessoriesPurchaseOrders ({ orderNo: this.orderNo, styleNo: this.styleNo, poDate: this.poDate, poNo: this.poNo, orderQuantity: this.orderQuantity, supplier: this.supplier, specialNote: this.specialNote, slNo: this.slNo, itemName: this.itemName, uom: this.uom, units: this.units, requiredDate: this.requiredDate, remarks: this.remarks }); // Redirect after save accessoriesPurchaseOrder.$save(function(response) { $location.path('accessories-purchase-orders/' + response._id); // Clear form fields $scope.name = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Accessories purchase order $scope.remove = function(accessoriesPurchaseOrder) { if ( accessoriesPurchaseOrder ) { accessoriesPurchaseOrder.$remove(); for (var i in $scope.accessoriesPurchaseOrders) { if ($scope.accessoriesPurchaseOrders [i] === accessoriesPurchaseOrder) { $scope.accessoriesPurchaseOrders.splice(i, 1); } } } else { $scope.accessoriesPurchaseOrder.$remove(function() { $location.path('accessories-purchase-orders'); }); } }; // Update existing Accessories purchase order $scope.update = function() { var accessoriesPurchaseOrder = $scope.accessoriesPurchaseOrder; accessoriesPurchaseOrder.$update(function() { $location.path('accessories-purchase-orders/' + accessoriesPurchaseOrder._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Accessories purchase orders $scope.find = function() { $scope.accessoriesPurchaseOrders = AccessoriesPurchaseOrders.query(); }; // Find existing Accessories purchase order $scope.findOne = function() { $scope.accessoriesPurchaseOrder = AccessoriesPurchaseOrders.get({ accessoriesPurchaseOrderId: $stateParams.accessoriesPurchaseOrderId }); }; } ]);
mit
Daanvdk/is_valid
is_valid/is_dict.py
137
from .is_instance import is_instance #: A predicate that checks if the data is a dictionary. is_dict = is_instance(dict, rep='a dict')
mit
Lazose/104asisjava
javatest/src/Javatest33.java
717
import java.util.Scanner; import java.util.Random; public class Javatest33 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); Random rnd = new Random(); int[]data= new int[10]; int i = 0 ; boolean flag = false ; while(i<10){ data[i]=rnd.nextInt(100); flag= false; for (int j =0;j<i;j++){ if(data[i]==data[j]){ flag = true; } } if (flag==false){ i++; } } int j = 0; for(i=0;i<10;i++){ for(j=i+1;j<10;j++){ if(data[i]>data[j]){ int v1 = data[i]; data[i]=data[j]; data[j]=v1; } } } for(int o = 0; o<10 ; o++){ System.out.println(data[o]); } } }
mit
alexliyu/CDMSYSTEM
pyroute2/ipdb/__init__.py
32471
# -*- coding: utf-8 -*- ''' IPDB module =========== Basically, IPDB is a transactional database, containing records, representing network stack objects. Any change in the database is not reflected immediately in OS (unless you ask for that explicitly), but waits until `commit()` is called. One failed operation during `commit()` rolls back all the changes, has been made so far. Moreover, IPDB has commit hooks API, that allows you to roll back changes depending on your own function calls, e.g. when a host or a network becomes unreachable. IPDB vs. IPRoute ---------------- These two modules, IPRoute and IPDB, use completely different approaches. The first one, IPRoute, is synchronous by default, and can be used in the same way, as usual Linux utilities. It doesn't spawn any additional threads or processes, until you explicitly ask for that. The latter, IPDB, is an asynchronously updated database, that starts several additional threads by default. If your project's policy doesn't allow implicit threads, keep it in mind. The choice depends on your project's workflow. If you plan to retrieve the system info not too often (or even once), or you are sure there will be not too many network object, it is better to use IPRoute. If you plan to lookup the network info on a regular basis and there can be loads of network objects, it is better to use IPDB. Why? IPRoute just loads what you ask -- and loads all the information you ask to. While IPDB loads all the info upon startup, and later is just updated by asynchronous broadcast netlink messages. Assume you want to lookup ARP cache that contains hundreds or even thousands of objects. Using IPRoute, you have to load all the ARP cache every time you want to make a lookup. While IPDB will load all the cache once, and then maintain it up-to-date just inserting new records or removing them by one. So, IPRoute is much simpler when you need to make a call and then exit. While IPDB is cheaper in terms of CPU performance if you implement a long-running program like a daemon. Later it can change, if there will be (an optional) cache for IPRoute too. quickstart ---------- Simple tutorial:: from pyroute2 import IPDB # several IPDB instances are supported within on process ip = IPDB() # commit is called automatically upon the exit from `with` # statement with ip.interfaces.eth0 as i: i.address = '00:11:22:33:44:55' i.ifname = 'bala' i.txqlen = 2000 # basic routing support ip.routes.add({'dst': 'default', 'gateway': '10.0.0.1'}).commit() # do not forget to shutdown IPDB ip.release() Please, notice `ip.release()` call in the end. Though it is not forced in an interactive python session for the better user experience, it is required in the scripts to sync the IPDB state before exit. IPDB uses IPRoute as a transport, and monitors all broadcast netlink messages from the kernel, thus keeping the database up-to-date in an asynchronous manner. IPDB inherits `dict` class, and has two keys:: >>> from pyroute2 import IPDB >>> ip = IPDB() >>> ip.by_name.keys() ['bond0', 'lo', 'em1', 'wlan0', 'dummy0', 'virbr0-nic', 'virbr0'] >>> ip.by_index.keys() [32, 1, 2, 3, 4, 5, 8] >>> ip.interfaces.keys() [32, 1, 2, 3, 4, 5, 8, 'lo', 'em1', 'wlan0', 'bond0', 'dummy0', 'virbr0-nic', 'virbr0'] >>> ip.interfaces['em1']['address'] 'f0:de:f1:93:94:0d' >>> ip.interfaces['em1']['ipaddr'] [('10.34.131.210', 23), ('2620:52:0:2282:f2de:f1ff:fe93:940d', 64), ('fe80::f2de:f1ff:fe93:940d', 64)] >>> One can address objects in IPDB not only with dict notation, but with dot notation also:: >>> ip.interfaces.em1.address 'f0:de:f1:93:94:0d' >>> ip.interfaces.em1.ipaddr [('10.34.131.210', 23), ('2620:52:0:2282:f2de:f1ff:fe93:940d', 64), ('fe80::f2de:f1ff:fe93:940d', 64)] ``` It is up to you, which way to choose. The former, being more flexible, is better for developers, the latter, the shorter form -- for system administrators. The library has also IPDB module. It is a database synchronized with the kernel, containing some of the information. It can be used also to set up IP settings in a transactional manner: >>> from pyroute2 import IPDB >>> from pprint import pprint >>> ip = IPDB() >>> pprint(ip.by_name.keys()) ['bond0', 'lo', 'vnet0', 'em1', 'wlan0', 'macvtap0', 'dummy0', 'virbr0-nic', 'virbr0'] >>> ip.interfaces.lo {'promiscuity': 0, 'operstate': 'UNKNOWN', 'qdisc': 'noqueue', 'group': 0, 'family': 0, 'index': 1, 'linkmode': 0, 'ipaddr': [('127.0.0.1', 8), ('::1', 128)], 'mtu': 65536, 'broadcast': '00:00:00:00:00:00', 'num_rx_queues': 1, 'txqlen': 0, 'ifi_type': 772, 'address': '00:00:00:00:00:00', 'flags': 65609, 'ifname': 'lo', 'num_tx_queues': 1, 'ports': [], 'change': 0} >>> transaction modes ----------------- IPDB has several operating modes: * 'direct' -- any change goes immediately to the OS level * 'implicit' (default) -- the first change starts an implicit transaction, that have to be committed * 'explicit' -- you have to begin() a transaction prior to make any change * 'snapshot' -- no changes will go to the OS in any case The default is to use implicit transaction. This behaviour can be changed in the future, so use 'mode' argument when creating IPDB instances. The sample session with explicit transactions:: In [1]: from pyroute2 import IPDB In [2]: ip = IPDB(mode='explicit') In [3]: ifdb = ip.interfaces In [4]: ifdb.tap0.begin() Out[3]: UUID('7a637a44-8935-4395-b5e7-0ce40d31d937') In [5]: ifdb.tap0.up() In [6]: ifdb.tap0.address = '00:11:22:33:44:55' In [7]: ifdb.tap0.add_ip('10.0.0.1', 24) In [8]: ifdb.tap0.add_ip('10.0.0.2', 24) In [9]: ifdb.tap0.review() Out[8]: {'+ipaddr': set([('10.0.0.2', 24), ('10.0.0.1', 24)]), '-ipaddr': set([]), 'address': '00:11:22:33:44:55', 'flags': 4099} In [10]: ifdb.tap0.commit() Note, that you can `review()` the `last()` transaction, and `commit()` or `drop()` it. Also, multiple `self._transactions` are supported, use uuid returned by `begin()` to identify them. Actually, the form like 'ip.tap0.address' is an eye-candy. The IPDB objects are dictionaries, so you can write the code above as that:: ip.interfaces['tap0'].down() ip.interfaces['tap0']['address'] = '00:11:22:33:44:55' ... context managers ---------------- Also, interface objects in transactional mode can operate as context managers:: with ip.interfaces.tap0 as i: i.address = '00:11:22:33:44:55' i.ifname = 'vpn' i.add_ip('10.0.0.1', 24) i.add_ip('10.0.0.1', 24) On exit, the context manager will authomatically `commit()` the transaction. create interfaces ----------------- IPDB can also create interfaces:: with ip.create(kind='bridge', ifname='control') as i: i.add_port(ip.interfaces.eth1) i.add_port(ip.interfaces.eth2) i.add_ip('10.0.0.1/24') # the same as i.add_ip('10.0.0.1', 24) IPDB supports many interface types, see docs below for the `IPDB.create()` method. routing management ------------------ IPDB has a simple yet useful routing management interface. To add a route, one can use almost any syntax:: # spec as a dictionary spec = {'dst': '172.16.1.0/24', 'oif': 4, 'gateway': '192.168.122.60', 'metrics': {'mtu': 1400, 'advmss': 500}} # pass spec as is ip.routes.add(spec).commit() # pass spec as kwargs ip.routes.add(**spec).commit() # use keyword arguments explicitly ip.routes.add(dst='172.16.1.0/24', oif=4, ...).commit() To access and change the routes, one can use notations as follows:: # default table (254) # # change the route gateway and mtu # with ip.routes['172.16.1.0/24'] as route: route.gateway = '192.168.122.60' route.metrics.mtu = 1500 # access the default route print(ip.routes['default]) # change the default gateway with ip.routes['default'] as route: route.gateway = '10.0.0.1' # list automatic routes keys print(ip.routes.tables[255].keys()) performance issues ------------------ In the case of bursts of Netlink broadcast messages, all the activity of the pyroute2-based code in the async mode becomes suppressed to leave more CPU resources to the packet reader thread. So please be ready to cope with delays in the case of Netlink broadcast storms. It means also, that IPDB state will be synchronized with OS also after some delay. classes ------- ''' import sys import atexit import logging import traceback import threading from socket import AF_INET from socket import AF_INET6 from pyroute2.common import Dotkeys from pyroute2.iproute import IPRoute from pyroute2.netlink.rtnl import RTM_GETLINK from pyroute2.ipdb.common import CreateException from pyroute2.ipdb.interface import Interface from pyroute2.ipdb.linkedset import LinkedSet from pyroute2.ipdb.linkedset import IPaddrSet from pyroute2.ipdb.common import compat from pyroute2.ipdb.common import SYNC_TIMEOUT from pyroute2.ipdb.route import RoutingTables def get_addr_nla(msg): ''' Utility function to get NLA, containing the interface address. Incosistency in Linux IP addressing scheme is that IPv4 uses IFA_LOCAL to store interface's ip address, and IPv6 uses for the same IFA_ADDRESS. IPv4 sets IFA_ADDRESS to == IFA_LOCAL or to a tunneling endpoint. Args: * msg (nlmsg): RTM\_.*ADDR message Returns: * nla (nla): IFA_LOCAL for IPv4 and IFA_ADDRESS for IPv6 ''' nla = None if msg['family'] == AF_INET: nla = msg.get_attr('IFA_LOCAL') elif msg['family'] == AF_INET6: nla = msg.get_attr('IFA_ADDRESS') return nla class Watchdog(object): def __init__(self, ipdb, action, kwarg): self.event = threading.Event() self.ipdb = ipdb def cb(ipdb, msg, _action): if _action != action: return for key in kwarg: if (msg.get(key, None) != kwarg[key]) and \ (msg.get_attr(msg.name2nla(key)) != kwarg[key]): return self.event.set() self.cb = cb # register callback prior to other things self.ipdb.register_callback(self.cb) def wait(self, timeout=SYNC_TIMEOUT): self.event.wait(timeout=timeout) self.cancel() def cancel(self): self.ipdb.unregister_callback(self.cb) class IPDB(object): ''' The class that maintains information about network setup of the host. Monitoring netlink events allows it to react immediately. It uses no polling. ''' def __init__(self, nl=None, mode='implicit', restart_on_error=None): ''' Parameters: * nl -- IPRoute() reference * mode -- (implicit, explicit, direct) * iclass -- the interface class type If you do not provide iproute instance, ipdb will start it automatically. ''' self.mode = mode self.iclass = Interface self._stop = False # see also 'register_callback' self._post_callbacks = [] self._pre_callbacks = [] self._cb_threads = set() # locks and events self._links_event = threading.Event() self.exclusive = threading.RLock() self._shutdown_lock = threading.Lock() # load information self.restart_on_error = restart_on_error if \ restart_on_error is not None else nl is None self.initdb(nl) # start monitoring thread self._mthread = threading.Thread(target=self.serve_forever) if hasattr(sys, 'ps1'): self._mthread.setDaemon(True) self._mthread.start() # atexit.register(self.release) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.release() def initdb(self, nl=None): ''' Restart IPRoute channel, and create all the DB from scratch. Can be used when sync is lost. ''' self.nl = nl or IPRoute() self.nl.monitor = True self.nl.bind(async=True) # resolvers self.interfaces = Dotkeys() self.routes = RoutingTables(ipdb=self) self.by_name = Dotkeys() self.by_index = Dotkeys() # caches self.ipaddr = {} self.neighbors = {} # load information links = self.nl.get_links() for link in links: self.device_put(link, skip_slaves=True) for link in links: self.update_slaves(link) self.update_addr(self.nl.get_addr()) self.update_neighbors(self.nl.get_neighbors()) routes = self.nl.get_routes() self.update_routes(routes) def register_callback(self, callback, mode='post'): ''' IPDB callbacks are routines executed on a RT netlink message arrival. There are two types of callbacks: "post" and "pre" callbacks. ... "Post" callbacks are executed after the message is processed by IPDB and all corresponding objects are created or deleted. Using ipdb reference in "post" callbacks you will access the most up-to-date state of the IP database. "Post" callbacks are executed asynchronously in separate threads. These threads can work as long as you want them to. Callback threads are joined occasionally, so for a short time there can exist stopped threads. ... "Pre" callbacks are synchronous routines, executed before the message gets processed by IPDB. It gives you the way to patch arriving messages, but also places a restriction: until the callback exits, the main event IPDB loop is blocked. Normally, only "post" callbacks are required. But in some specific cases "pre" also can be useful. ... The routine, `register_callback()`, takes two arguments: 1. callback function 2. mode (optional, default="post") The callback should be a routine, that accepts three arguments:: cb(ipdb, msg, action) 1. ipdb is a reference to IPDB instance, that invokes the callback. 2. msg is a message arrived 3. action is just a msg['event'] field E.g., to work on a new interface, you should catch action == 'RTM_NEWLINK' and with the interface index (arrived in msg['index']) get it from IPDB:: index = msg['index'] interface = ipdb.interfaces[index] ''' lock = threading.Lock() def safe(*argv, **kwarg): with lock: callback(*argv, **kwarg) safe.hook = callback if mode == 'post': self._post_callbacks.append(safe) elif mode == 'pre': self._pre_callbacks.append(safe) def unregister_callback(self, callback, mode='post'): if mode == 'post': cbchain = self._post_callbacks elif mode == 'pre': cbchain = self._pre_callbacks else: raise KeyError('Unknown callback mode') for cb in tuple(cbchain): if callback == cb.hook: for t in tuple(self._cb_threads): t.join(3) return cbchain.pop(cbchain.index(cb)) def release(self): ''' Shutdown IPDB instance and sync the state. Since IPDB is asyncronous, some operations continue in the background, e.g. callbacks. So, prior to exit the script, it is required to properly shutdown IPDB. The shutdown sequence is not forced in an interactive python session, since it is easier for users and there is enough time to sync the state. But for the scripts the `release()` call is required. ''' with self._shutdown_lock: if self._stop: return self._stop = True try: self.nl.put({'index': 1}, RTM_GETLINK) self._mthread.join() except Exception: # Just give up. # We can not handle this case pass self.nl.close() def create(self, kind, ifname, reuse=False, **kwarg): ''' Create an interface. Arguments 'kind' and 'ifname' are required. * kind -- interface type, can be of: * bridge * bond * vlan * tun * dummy * veth * macvlan * macvtap * gre * team * ovs-bridge * ifname -- interface name * reuse -- if such interface exists, return it anyway Different interface kinds can require different arguments for creation. ► **veth** To properly create `veth` interface, one should specify `peer` also, since `veth` interfaces are created in pairs:: with ip.create(ifname='v1p0', kind='veth', peer='v1p1') as i: i.add_ip('10.0.0.1/24') i.add_ip('10.0.0.2/24') The code above creates two interfaces, `v1p0` and `v1p1`, and adds two addresses to `v1p0`. ► **macvlan** Macvlan interfaces act like VLANs within OS. The macvlan driver provides an ability to add several MAC addresses on one interface, where every MAC address is reflected with a virtual interface in the system. In some setups macvlan interfaces can replace bridge interfaces, providing more simple and at the same time high-performance solution:: ip.create(ifname='mvlan0', kind='macvlan', link=ip.interfaces.em1, macvlan_mode='private').commit() Several macvlan modes are available: 'private', 'vepa', 'bridge', 'passthru'. Ususally the default is 'vepa'. ► **macvtap** Almost the same as macvlan, but creates also a character tap device:: ip.create(ifname='mvtap0', kind='macvtap', link=ip.interfaces.em1, macvtap_mode='vepa').commit() Will create a device file `"/dev/tap%s" % ip.interfaces.mvtap0.index` ► **gre** Create GRE tunnel:: with ip.create(ifname='grex', kind='gre', gre_local='172.16.0.1', gre_remote='172.16.0.101', gre_ttl=16) as i: i.add_ip('192.168.0.1/24') i.up() ► **vlan** VLAN interfaces require additional parameters, `vlan_id` and `link`, where `link` is a master interface to create VLAN on:: ip.create(ifname='v100', kind='vlan', link=ip.interfaces.eth0, vlan_id=100) ip.create(ifname='v100', kind='vlan', link=1, vlan_id=100) The `link` parameter should be either integer, interface id, or an interface object. VLAN id must be integer. ► **vxlan** VXLAN interfaces are like VLAN ones, but require a bit more parameters:: ip.create(ifname='vx101', kind='vxlan', vxlan_link=ip.interfaces.eth0, vxlan_id=101, vxlan_group='239.1.1.1', vxlan_ttl=16) All possible vxlan parameters are listed in the module `pyroute2.netlink.rtnl.ifinfmsg:... vxlan_data`. ► **tuntap** Possible `tuntap` keywords: * `mode` — "tun" or "tap" * `uid` — integer * `gid` — integer * `ifr` — dict of tuntap flags (see tuntapmsg.py) ''' with self.exclusive: # check for existing interface if ifname in self.interfaces: if self.interfaces[ifname]._flicker or reuse: device = self.interfaces[ifname] device._flicker = False else: raise CreateException("interface %s exists" % ifname) else: device = \ self.by_name[ifname] = \ self.interfaces[ifname] = \ self.iclass(ipdb=self, mode='snapshot') device.update(kwarg) if isinstance(kwarg.get('link', None), Interface): device['link'] = kwarg['link']['index'] if isinstance(kwarg.get('vxlan_link', None), Interface): device['vxlan_link'] = kwarg['vxlan_link']['index'] device['kind'] = kind device['index'] = kwarg.get('index', 0) device['ifname'] = ifname device._mode = self.mode device.begin() return device def device_del(self, msg): # check for flicker devices if (msg.get('index', None) in self.interfaces) and \ self.interfaces[msg['index']]._flicker: self.interfaces[msg['index']].sync() return try: self.update_slaves(msg) if msg['change'] == 0xffffffff: # FIXME catch exception ifname = self.interfaces[msg['index']]['ifname'] self.interfaces[msg['index']].sync() del self.by_name[ifname] del self.by_index[msg['index']] del self.interfaces[ifname] del self.interfaces[msg['index']] del self.ipaddr[msg['index']] del self.neighbors[msg['index']] except KeyError: pass def device_put(self, msg, skip_slaves=False): # check, if a record exists index = msg.get('index', None) ifname = msg.get_attr('IFLA_IFNAME', None) # scenario #1: no matches for both: new interface # scenario #2: ifname exists, index doesn't: index changed # scenario #3: index exists, ifname doesn't: name changed # scenario #4: both exist: assume simple update and # an optional name change if ((index not in self.interfaces) and (ifname not in self.interfaces)): # scenario #1, new interface if compat.fix_check_link(self.nl, index): return device = \ self.by_index[index] = \ self.interfaces[index] = \ self.interfaces[ifname] = \ self.by_name[ifname] = self.iclass(ipdb=self) elif ((index not in self.interfaces) and (ifname in self.interfaces)): # scenario #2, index change old_index = self.interfaces[ifname]['index'] device = \ self.interfaces[index] = \ self.by_index[index] = self.interfaces[ifname] if old_index in self.interfaces: del self.interfaces[old_index] del self.by_index[old_index] if old_index in self.ipaddr: self.ipaddr[index] = self.ipaddr[old_index] del self.ipaddr[old_index] if old_index in self.neighbors: self.neighbors[index] = self.neighbors[old_index] del self.neighbors[old_index] else: # scenario #3, interface rename # scenario #4, assume rename old_name = self.interfaces[index]['ifname'] if old_name != ifname: # unlink old name del self.interfaces[old_name] del self.by_name[old_name] device = \ self.interfaces[ifname] = \ self.by_name[ifname] = self.interfaces[index] if index not in self.ipaddr: # for interfaces, created by IPDB self.ipaddr[index] = IPaddrSet() if index not in self.neighbors: self.neighbors[index] = LinkedSet() device.load_netlink(msg) if not skip_slaves: self.update_slaves(msg) def detach(self, item): with self.exclusive: if item in self.interfaces: del self.interfaces[item] if item in self.by_name: del self.by_name[item] if item in self.by_index: del self.by_index[item] def watchdog(self, action='RTM_NEWLINK', **kwarg): return Watchdog(self, action, kwarg) def update_routes(self, routes): for msg in routes: self.routes.load_netlink(msg) def _lookup_master(self, msg): master = None # lookup for IFLA_OVS_MASTER_IFNAME li = msg.get_attr('IFLA_LINKINFO') if li: data = li.get_attr('IFLA_INFO_DATA') if data: try: master = data.get_attr('IFLA_OVS_MASTER_IFNAME') except AttributeError: # IFLA_INFO_DATA can be undecoded, in that case # it will be just a string with a hex dump pass # lookup for IFLA_MASTER if master is None: master = msg.get_attr('IFLA_MASTER') # pls keep in mind, that in the case of IFLA_MASTER # lookup is done via interface index, while in the case # of IFLA_OVS_MASTER_IFNAME lookup is done via ifname return self.interfaces.get(master, None) def update_slaves(self, msg): # Update slaves list -- only after update IPDB! master = self._lookup_master(msg) index = msg['index'] # there IS a master for the interface if master is not None: if msg['event'] == 'RTM_NEWLINK': # TODO tags: ipdb # The code serves one particular case, when # an enslaved interface is set to belong to # another master. In this case there will be # no 'RTM_DELLINK', only 'RTM_NEWLINK', and # we can end up in a broken state, when two # masters refers to the same slave for device in self.by_index: if index in self.interfaces[device]['ports']: self.interfaces[device].del_port(index, direct=True) master.add_port(index, direct=True) elif msg['event'] == 'RTM_DELLINK': if index in master['ports']: master.del_port(index, direct=True) # there is NO masters for the interface, clean them if any else: device = self.interfaces[msg['index']] # clean device from ports for master in self.by_index: if index in self.interfaces[master]['ports']: self.interfaces[master].del_port(index, direct=True) master = device.if_master if master is not None: if 'master' in device: device.del_item('master') if (master in self.interfaces) and \ (msg['index'] in self.interfaces[master].ports): self.interfaces[master].del_port(msg['index'], direct=True) def update_addr(self, addrs, action='add'): # Update address list of an interface. for addr in addrs: nla = get_addr_nla(addr) if nla is not None: try: method = getattr(self.ipaddr[addr['index']], action) method(key=(nla, addr['prefixlen']), raw=addr) except: pass def update_neighbors(self, neighs, action='add'): for neigh in neighs: nla = neigh.get_attr('NDA_DST') if nla is not None: try: method = getattr(self.neighbors[neigh['ifindex']], action) method(key=nla, raw=neigh) except: pass def serve_forever(self): ''' Main monitoring cycle. It gets messages from the default iproute queue and updates objects in the database. .. note:: Should not be called manually. ''' while not self._stop: try: messages = self.nl.get() ## # Check it again # # NOTE: one should not run callbacks or # anything like that after setting the # _stop flag, since IPDB is not valid # anymore if self._stop: break except: logging.error('Restarting IPDB instance after ' 'error:\n%s', traceback.format_exc()) if self.restart_on_error: self.initdb() continue else: raise RuntimeError('Emergency shutdown') for msg in messages: # Run pre-callbacks # NOTE: pre-callbacks are synchronous for cb in self._pre_callbacks: try: cb(self, msg, msg['event']) except: pass with self.exclusive: if msg.get('event', None) == 'RTM_NEWLINK': self.device_put(msg) self._links_event.set() elif msg.get('event', None) == 'RTM_DELLINK': self.device_del(msg) elif msg.get('event', None) == 'RTM_NEWADDR': self.update_addr([msg], 'add') elif msg.get('event', None) == 'RTM_DELADDR': self.update_addr([msg], 'remove') elif msg.get('event', None) == 'RTM_NEWNEIGH': self.update_neighbors([msg], 'add') elif msg.get('event', None) == 'RTM_DELNEIGH': self.update_neighbors([msg], 'remove') elif msg.get('event', None) == 'RTM_NEWROUTE': self.update_routes([msg]) elif msg.get('event', None) == 'RTM_DELROUTE': table = msg.get('table', 254) dst = msg.get_attr('RTA_DST', False) if not dst: key = 'default' else: key = '%s/%s' % (dst, msg.get('dst_len', 0)) try: route = self.routes.tables[table][key] del self.routes.tables[table][key] route.sync() except KeyError: pass # run post-callbacks # NOTE: post-callbacks are asynchronous for cb in self._post_callbacks: t = threading.Thread(name="callback %s" % (id(cb)), target=cb, args=(self, msg, msg['event'])) t.start() self._cb_threads.add(t) # occasionally join cb threads for t in tuple(self._cb_threads): t.join(0) if not t.is_alive(): self._cb_threads.remove(t)
mit
natac13/CareerSmartDemo
app/store/configureStore.dev.js
1114
import { createStore, applyMiddleware } from 'redux'; /*** Middlewares ***/ import logger from 'redux-logger'; /*** Reducer ***/ import rootReducer from '../reducers/'; import { createHistory } from 'history'; import { syncHistory, routeReducer } from 'redux-simple-router'; export const history = createHistory(); // Sync dispatched route actions to the history const reduxRouterMiddleware = syncHistory(history); const loggerMiddleware = logger(); /*=========================================== = Immutable Dev tools = ===========================================*/ import Immutable from 'immutable'; import installDevTools from 'immutable-devtools'; installDevTools(Immutable); /*===== End of Immutable Dev tools ======*/ export default function configureStore(initialState) { // applyMiddleware supercharges createStore with middleware: // We can use it exactly like “vanilla” createStore. return createStore( rootReducer, initialState, applyMiddleware( reduxRouterMiddleware, loggerMiddleware ) ); }
mit
rtqichen/torchdiffeq
torchdiffeq/_impl/scipy_wrapper.py
1601
import abc import torch from scipy.integrate import solve_ivp from .misc import _handle_unused_kwargs class ScipyWrapperODESolver(metaclass=abc.ABCMeta): def __init__(self, func, y0, rtol, atol, solver="LSODA", **unused_kwargs): unused_kwargs.pop('norm', None) unused_kwargs.pop('grid_points', None) unused_kwargs.pop('eps', None) _handle_unused_kwargs(self, unused_kwargs) del unused_kwargs self.dtype = y0.dtype self.device = y0.device self.shape = y0.shape self.y0 = y0.detach().cpu().numpy().reshape(-1) self.rtol = rtol self.atol = atol self.solver = solver self.func = convert_func_to_numpy(func, self.shape, self.device, self.dtype) def integrate(self, t): if t.numel() == 1: return torch.tensor(self.y0)[None].to(self.device, self.dtype) t = t.detach().cpu().numpy() sol = solve_ivp( self.func, t_span=[t.min(), t.max()], y0=self.y0, t_eval=t, method=self.solver, rtol=self.rtol, atol=self.atol, ) sol = torch.tensor(sol.y).T.to(self.device, self.dtype) sol = sol.reshape(-1, *self.shape) return sol def convert_func_to_numpy(func, shape, device, dtype): def np_func(t, y): t = torch.tensor(t).to(device, dtype) y = torch.reshape(torch.tensor(y).to(device, dtype), shape) with torch.no_grad(): f = func(t, y) return f.detach().cpu().numpy().reshape(-1) return np_func
mit
ereddate/jquery-mobile
demos/table-column-toggle-example/index.php
6389
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Table Column toggle demo: Phone comparison - jQuery Mobile Demos</title> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700"> <link rel="stylesheet" href="../../css/themes/default/jquery.mobile.css"> <link rel="stylesheet" href="../_assets/css/jqm-demos.css"> <script src="../../js/jquery.js"></script> <script src="../_assets/js/"></script> <script src="../../js/"></script> <style> /*These apply across all breakpoints because they are outside of a media query */ table.phone-compare thead th { background-color: #fff; } table.phone-compare thead th h4 { text-transform: uppercase; font-size: 0.6em; margin: 0; } table.phone-compare thead th h3 { font-size: .9em; margin: -.4em 0 .8em 0; } table.phone-compare th.label { text-transform: uppercase; font-size: 0.6em; opacity: 0.5; padding: 1.2em .8em; background-color: #ddd; } table.phone-compare tbody tr.photos td { background-color: #fff; padding: 0; } table.phone-compare tbody tr.photos img { max-width: 100%; min-width: 60px; } /* Use the target selector to style the column chooser button */ a[href="#phone-table-popup"] { margin-bottom: 1.2em; } /* Show priority 1 at 320px (20em x 16px) */ @media screen and (min-width: 20em) { .phone-compare th.ui-table-priority-1, .phone-compare td.ui-table-priority-1 { display: table-cell; } } /* Show priority 2 at 560px (35em x 16px) */ @media screen and (min-width: 35em) { .phone-compare th.ui-table-priority-2, .phone-compare td.ui-table-priority-2 { display: table-cell; } } /* Show priority 3 at 720px (45em x 16px) */ @media screen and (min-width: 45em) { .phone-compare th.ui-table-priority-3, .phone-compare td.ui-table-priority-3 { display: table-cell; } } /* Manually hidden */ .phone-compare th.ui-table-cell-hidden, .phone-compare td.ui-table-cell-hidden { display: none; } /* Manually shown */ .phone-compare th.ui-table-cell-visible, .phone-compare td.ui-table-cell-visible { display: table-cell; } </style> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="../" title="jQuery Mobile Demos home"><img src="../_assets/img/jquery-logo.png" alt="jQuery Mobile"></a></h2> <p><span class="jqm-version"></span> Demos</p> <a href="#" class="jqm-navmenu-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-bars ui-nodisc-icon ui-alt-icon ui-btn-left">Menu</a> <a href="#" class="jqm-search-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-search ui-nodisc-icon ui-alt-icon ui-btn-right">Search</a> </div><!-- /header --> <div role="main" class="ui-content jqm-content"> <h1>Popular Phones</h1> <p>This is an example of how to use the column toggle table to create a comparison view where products can be shown or hidden.</p> <div data-demo-html="true" data-demo-css="true"> <table data-role="table" id="phone-table" data-mode="columntoggle" data-column-btn-text="Compare..." data-column-btn-theme="a" class="phone-compare ui-shadow table-stroke"> <thead> <tr> <th class="label">Model</th> <th> <h4>Apple</h4> <h3>iPhone 5</h3> </th> <th data-priority="1"> <h4>Samsung</h4> <h3>Galaxy S III</h3> </th> <th data-priority="2"> <h4>Nokia</h4> <h3>Lumia 920</h3> </th> <th data-priority="3"> <h4>HTC</h4> <h3>One X</h3> </th> </tr> </thead> <tbody> <tr class="photos"> <th class="label">Photo</th> <td><a href="#img-iphone5" data-rel="popup" data-position-to="window"><img src="../_assets/img/phone_iphone5.png"></a></td> <td><a href="#img-galaxy" data-rel="popup" data-position-to="window"><img src="../_assets/img/phone_galaxy3.png"></a></td> <td><a href="#img-lumia" data-rel="popup" data-position-to="window"><img src="../_assets/img/phone_lumia920.png"></a></td> <td><a href="#img-onex" data-rel="popup" data-position-to="window"><img src="../_assets/img/phone_onex.png"></a></td> </tr> <tr> <th class="label">Height</th> <td>4.87"</td> <td>5.38"</td> <td>5.11"</td> <td>5.3"</td> </tr> <tr> <th class="label">Width</th> <td>2.31"</td> <td>2.78"</td> <td>2.79"</td> <td>2.75"</td> </tr> <tr> <th class="label">Depth</th> <td>0.3"</td> <td>0.34"</td> <td>0.42"</td> <td>0.37"</td> </tr> <tr> <th class="label">Weight (lbs.)</th> <td>0.25</td> <td>0.29</td> <td>0.41</td> <td>0.29</td> </tr> </tbody> </table> <!-- Popups for lightbox images --> <div id="img-iphone5" data-role="popup" data-overlay-theme="a"> <img src="../_assets/img/phone_iphone5.png"> </div> <div id="img-galaxy" data-role="popup" data-overlay-theme="a"> <img src="../_assets/img/phone_galaxy3.png"> </div> <div id="img-lumia" data-role="popup" data-overlay-theme="a"> <img src="../_assets/img/phone_lumia920.png"> </div> <div id="img-onex" data-role="popup" data-overlay-theme="a"> <img src="../_assets/img/phone_onex.png"> </div> </div><!-- /data-demo --> </div><!-- /content --> <?php include( '../jqm-navmenu.php' ); ?> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>jQuery Mobile Demos version <span class="jqm-version"></span></p> <p>Copyright 2013 The jQuery Foundation</p> </div><!-- /footer --> <?php include( '../jqm-search.php' ); ?> </div><!-- /page --> </body> </html>
mit
half-evil/ripper
Ripper.Services/ImageHosts/PussyUpload.cs
5443
////////////////////////////////////////////////////////////////////////// // Code Named: VG-Ripper // Function : Extracts Images posted on RiP forums and attempts to fetch // them to disk. // // This software is licensed under the MIT license. See license.txt for // details. // // Copyright (c) The Watcher // Partial Rights Reserved. // ////////////////////////////////////////////////////////////////////////// // This file is part of the RiP Ripper project base. using System; using System.Collections; using System.IO; using System.Net; using System.Threading; namespace Ripper { using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// Worker class to get images hosted on PussyUpload.com /// </summary> public class PussyUpload : ServiceTemplate { public PussyUpload(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable) : base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable) { // // Add constructor logic here // } protected override bool DoDownload() { string strImgURL = ImageLinkURL; if (EventTable.ContainsKey(strImgURL)) { return true; } try { if (!Directory.Exists(SavePath)) Directory.CreateDirectory(SavePath); } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; return false; } string strFilePath = string.Empty; CacheObject CCObj = new CacheObject(); CCObj.IsDownloaded = false; CCObj.FilePath = strFilePath; CCObj.Url = strImgURL; try { EventTable.Add(strImgURL, CCObj); } catch (ThreadAbortException) { return true; } catch (Exception) { if (EventTable.ContainsKey(strImgURL)) { return false; } else { EventTable.Add(strImgURL, CCObj); } } string strIVPage = GetImageHostPage(ref strImgURL); if (strIVPage.Length < 10) { return false; } string strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1); int iStartSRC = 0; int iEndSRC = 0; iStartSRC = strIVPage.IndexOf("<img id=pic src=\""); if (iStartSRC < 0) { return false; } iStartSRC += 17; iEndSRC = strIVPage.IndexOf("\" onclick=\"scaleImg('pic');\"", iStartSRC); if (iEndSRC < 0) { return false; } strNewURL = "http://www.pussyupload.com/" + strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC); strFilePath = strNewURL.Substring(strNewURL.LastIndexOf("gallery/") + 19); strFilePath = Path.Combine(SavePath, Utility.RemoveIllegalCharecters(strFilePath)); ////////////////////////////////////////////////////////////////////////// string NewAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != NewAlteredPath) { strFilePath = NewAlteredPath; ((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; } try { WebClient client = new WebClient(); client.Headers.Add("Referer: " + strImgURL); client.DownloadFile(strNewURL, strFilePath); client.Dispose(); } catch (ThreadAbortException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (IOException ex) { //MainForm.DeleteMessage = ex.Message; //MainForm.Delete = true; ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return true; } catch (WebException) { ((CacheObject)EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(ImageLinkURL); return false; } ((CacheObject)EventTable[ImageLinkURL]).IsDownloaded = true; //CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath; CacheController.Instance().LastPic =((CacheObject)EventTable[ImageLinkURL]).FilePath = strFilePath; return true; } ////////////////////////////////////////////////////////////////////////// } }
mit
lavaleak/diplomata-unity
Runtime/Persistence/Models/ItemPersistent.cs
206
using System; namespace LavaLeak.Diplomata.Persistence.Models { [Serializable] public class ItemPersistent : Persistent { public string id; public bool have; public bool discarded; } }
mit
gabrielbull/php-waredesk-api
test/tests/Products/ProductUpdateTest.php
2576
<?php namespace Waredesk\Tests\Products; use GuzzleHttp\Psr7\Response; use Waredesk\Image; use Waredesk\Models\Code; use Waredesk\Models\Product; use Waredesk\Tests\BaseTest; class ProductUpdateTest extends BaseTest { public function testFake() { $this->assertTrue(true); } /*private function createProduct(): Product { $product = new Product(); $product->setName('Amazing T-Shirt'); $product->setDescription('This T-Shirt will cover your belly'); $variant = new Product\Variant(); $variant->setName('X-Large'); $product->getVariants()->add($variant); return $product; } public function testCreateProduct() { $product = $this->createProduct(); $this->mock->append(new Response(200, [], file_get_contents(__DIR__ . '/responses/createTestSuccess.json'))); $product = $this->waredesk->products->create($product); $this->assertNotEmpty($product->getId()); } public function testCreateProductWithImage() { $image = new Image(__DIR__.'/../../files/tshirt.jpg'); $product = $this->createProduct(); $product->setImage($image); $product->getVariants()->first()->setImage($image); $this->mock->append(new Response(200, [], file_get_contents(__DIR__ . '/responses/createWithImageTestSuccess.json'))); $product = $this->waredesk->products->create($product); $this->assertNotEmpty($product->getImages()['small']); $this->assertNotEmpty($product->getVariants()->first()->getImages()['small']); } public function testCreateByCloningCodes() { $code = new Code(); $code->reset([ 'id' => 'code_0F8f8936aeb96c8b6gZQ', 'name' => 'SKU', 'creation' => new \DateTime('2017-05-15T20:39:13+00:00'), 'modification' => new \DateTime('2017-05-15T20:39:13+00:00'), ]); $element = new Code\Element(); $element->reset([ 'id' => 'cele_0De08e7034ea879aL4gv', 'type' => 'text' ]); $code->getElements()->add($element); $product = $this->createProduct(); $codes = $product->getVariants()->first()->getCodes(); $codes->reset(); $codes->add($code); $array = $product->jsonSerialize(); $this->assertEquals($array['variants'][0]['codes'][0]['code'], 'code_0F8f8936aeb96c8b6gZQ'); $this->assertEquals($array['variants'][0]['codes'][0]['elements'][0]['element'], 'cele_0De08e7034ea879aL4gv'); }*/ }
mit
leowang721/edpx-timeline
lib/output/dep/echarts/2.0.3/src/chart/k.js
19965
/** * echarts图表类:K线图 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * */ define(function (require) { var ComponentBase = require('../component/base'); var ChartBase = require('./base'); // 图形依赖 var CandleShape = require('../util/shape/Candle'); // 组件依赖 require('../component/axis'); require('../component/grid'); require('../component/dataZoom'); var ecConfig = require('../config'); var ecData = require('../util/ecData'); var zrUtil = require('zrender/tool/util'); /** * 构造函数 * @param {Object} messageCenter echart消息中心 * @param {ZRender} zr zrender实例 * @param {Object} series 数据 * @param {Object} component 组件 */ function K(ecTheme, messageCenter, zr, option, myChart){ // 基类 ComponentBase.call(this, ecTheme, messageCenter, zr, option, myChart); // 图表基类 ChartBase.call(this); this.refresh(option); } K.prototype = { type : ecConfig.CHART_TYPE_K, /** * 绘制图形 */ _buildShape : function () { var series = this.series; this.selectedMap = {}; // 水平垂直双向series索引 ,position索引到seriesIndex var _position2sIndexMap = { top : [], bottom : [] }; var xAxis; for (var i = 0, l = series.length; i < l; i++) { if (series[i].type == ecConfig.CHART_TYPE_K) { series[i] = this.reformOption(series[i]); xAxis = this.component.xAxis.getAxis(series[i].xAxisIndex); if (xAxis.type == ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { _position2sIndexMap[xAxis.getPosition()].push(i); } } } //console.log(_position2sIndexMap) for (var position in _position2sIndexMap) { if (_position2sIndexMap[position].length > 0) { this._buildSinglePosition( position, _position2sIndexMap[position] ); } } this.addShapeList(); }, /** * 构建单个方向上的K线图 * * @param {number} seriesIndex 系列索引 */ _buildSinglePosition : function (position, seriesArray) { var mapData = this._mapData(seriesArray); var locationMap = mapData.locationMap; var maxDataLength = mapData.maxDataLength; if (maxDataLength === 0 || locationMap.length === 0) { return; } this._buildHorizontal(seriesArray, maxDataLength, locationMap); for (var i = 0, l = seriesArray.length; i < l; i++) { this.buildMark(seriesArray[i]); } }, /** * 数据整形 * 数组位置映射到系列索引 */ _mapData : function (seriesArray) { var series = this.series; var serie; // 临时映射变量 var serieName; // 临时映射变量 var legend = this.component.legend; var locationMap = []; // 需要返回的东西:数组位置映射到系列索引 var maxDataLength = 0; // 需要返回的东西:最大数据长度 // 计算需要显示的个数和分配位置并记在下面这个结构里 for (var i = 0, l = seriesArray.length; i < l; i++) { serie = series[seriesArray[i]]; serieName = serie.name; if (legend){ this.selectedMap[serieName] = legend.isSelected(serieName); } else { this.selectedMap[serieName] = true; } if (this.selectedMap[serieName]) { locationMap.push(seriesArray[i]); } // 兼职帮算一下最大长度 maxDataLength = Math.max(maxDataLength, serie.data.length); } return { locationMap : locationMap, maxDataLength : maxDataLength }; }, /** * 构建类目轴为水平方向的K线图系列 */ _buildHorizontal : function (seriesArray, maxDataLength, locationMap) { var series = this.series; // 确定类目轴和数值轴,同一方向随便找一个即可 var seriesIndex; var serie; var xAxisIndex; var categoryAxis; var yAxisIndex; // 数值轴各异 var valueAxis; // 数值轴各异 var pointList = {}; var candleWidth; var data; var value; var barMaxWidth; for (var j = 0, k = locationMap.length; j < k; j++) { seriesIndex = locationMap[j]; serie = series[seriesIndex]; xAxisIndex = serie.xAxisIndex || 0; categoryAxis = this.component.xAxis.getAxis(xAxisIndex); candleWidth = serie.barWidth || Math.floor(categoryAxis.getGap() / 2); barMaxWidth = serie.barMaxWidth; if (barMaxWidth && barMaxWidth < candleWidth) { candleWidth = barMaxWidth; } yAxisIndex = serie.yAxisIndex || 0; valueAxis = this.component.yAxis.getAxis(yAxisIndex); pointList[seriesIndex] = []; for (var i = 0, l = maxDataLength; i < l; i++) { if (typeof categoryAxis.getNameByIndex(i) == 'undefined') { // 系列数据超出类目轴长度 break; } data = serie.data[i]; value = typeof data != 'undefined' ? (typeof data.value != 'undefined' ? data.value : data) : '-'; if (value == '-' || value.length != 4) { // 数据格式不符 continue; } pointList[seriesIndex].push([ categoryAxis.getCoordByIndex(i), // 横坐标 candleWidth, valueAxis.getCoord(value[0]), // 纵坐标:开盘 valueAxis.getCoord(value[1]), // 纵坐标:收盘 valueAxis.getCoord(value[2]), // 纵坐标:最低 valueAxis.getCoord(value[3]), // 纵坐标:最高 i, // 数据index categoryAxis.getNameByIndex(i) // 类目名称 ]); } } // console.log(pointList) this._buildKLine(seriesArray, pointList); }, /** * 生成K线 */ _buildKLine : function (seriesArray, pointList) { var series = this.series; // normal: var nLineWidth; var nLineColor; var nLineColor0; // 阴线 var nColor; var nColor0; // 阴线 // emphasis: var eLineWidth; var eLineColor; var eLineColor0; var eColor; var eColor0; var serie; var queryTarget; var data; var seriesPL; var singlePoint; var candleType; var seriesIndex; for (var sIdx = 0, len = seriesArray.length; sIdx < len; sIdx++) { seriesIndex = seriesArray[sIdx]; serie = series[seriesIndex]; seriesPL = pointList[seriesIndex]; if (this._isLarge(seriesPL)) { seriesPL = this._getLargePointList(seriesPL); } if (serie.type == ecConfig.CHART_TYPE_K && typeof seriesPL != 'undefined' ) { // 多级控制 queryTarget = serie; nLineWidth = this.query( queryTarget, 'itemStyle.normal.lineStyle.width' ); nLineColor = this.query( queryTarget, 'itemStyle.normal.lineStyle.color' ); nLineColor0 = this.query( queryTarget, 'itemStyle.normal.lineStyle.color0' ); nColor = this.query( queryTarget, 'itemStyle.normal.color' ); nColor0 = this.query( queryTarget, 'itemStyle.normal.color0' ); eLineWidth = this.query( queryTarget, 'itemStyle.emphasis.lineStyle.width' ); eLineColor = this.query( queryTarget, 'itemStyle.emphasis.lineStyle.color' ); eLineColor0 = this.query( queryTarget, 'itemStyle.emphasis.lineStyle.color0' ); eColor = this.query( queryTarget, 'itemStyle.emphasis.color' ); eColor0 = this.query( queryTarget, 'itemStyle.emphasis.color0' ); /* * pointlist=[ * 0 x, * 1 width, * 2 y0, * 3 y1, * 4 y2, * 5 y3, * 6 dataIndex, * 7 categoryName * ] */ for (var i = 0, l = seriesPL.length; i < l; i++) { singlePoint = seriesPL[i]; data = serie.data[singlePoint[6]]; queryTarget = data; candleType = singlePoint[3] < singlePoint[2]; this.shapeList.push(this._getCandle( seriesIndex, // seriesIndex singlePoint[6], // dataIndex singlePoint[7], // name singlePoint[0], // x singlePoint[1], // width singlePoint[2], // y开盘 singlePoint[3], // y收盘 singlePoint[4], // y最低 singlePoint[5], // y最高 // 填充颜色 candleType ? (this.query( // 阳 queryTarget, 'itemStyle.normal.color' ) || nColor) : (this.query( // 阴 queryTarget, 'itemStyle.normal.color0' ) || nColor0), // 线宽 this.query( queryTarget, 'itemStyle.normal.lineStyle.width' ) || nLineWidth, // 线色 candleType ? (this.query( // 阳 queryTarget, 'itemStyle.normal.lineStyle.color' ) || nLineColor) : (this.query( // 阴 queryTarget, 'itemStyle.normal.lineStyle.color0' ) || nLineColor0), //------------高亮 // 填充颜色 candleType ? (this.query( // 阳 queryTarget, 'itemStyle.emphasis.color' ) || eColor || nColor) : (this.query( // 阴 queryTarget, 'itemStyle.emphasis.color0' ) || eColor0 || nColor0), // 线宽 this.query( queryTarget, 'itemStyle.emphasis.lineStyle.width' ) || eLineWidth || nLineWidth, // 线色 candleType ? (this.query( // 阳 queryTarget, 'itemStyle.emphasis.lineStyle.color' ) || eLineColor || nLineColor) : (this.query( // 阴 queryTarget, 'itemStyle.emphasis.lineStyle.color0' ) || eLineColor0 || nLineColor0) )); } } } // console.log(this.shapeList) }, _isLarge : function(singlePL) { return singlePL[0][1] < 0.5; }, /** * 大规模pointList优化 */ _getLargePointList : function(singlePL) { var total = this.component.grid.getWidth(); var len = singlePL.length; var newList = []; for (var i = 0; i < total; i++) { newList[i] = singlePL[Math.floor(len / total * i)]; } return newList; }, /** * 生成K线图上的图形 */ _getCandle : function ( seriesIndex, dataIndex, name, x, width, y0, y1, y2, y3, nColor, nLinewidth, nLineColor, eColor, eLinewidth, eLineColor ) { var series = this.series; var itemShape = { zlevel : this._zlevelBase, clickable: this.deepQuery( [series[seriesIndex].data[dataIndex], series[seriesIndex]], 'clickable' ), style : { x : x, y : [y0, y1, y2, y3], width : width, color : nColor, strokeColor : nLineColor, lineWidth : nLinewidth, brushType : 'both' }, highlightStyle : { color : eColor, strokeColor : eLineColor, lineWidth : eLinewidth }, _seriesIndex: seriesIndex }; ecData.pack( itemShape, series[seriesIndex], seriesIndex, series[seriesIndex].data[dataIndex], dataIndex, name ); itemShape = new CandleShape(itemShape); return itemShape; }, // 位置转换 getMarkCoord : function (seriesIndex, mpData) { var serie = this.series[seriesIndex]; var xAxis = this.component.xAxis.getAxis(serie.xAxisIndex); var yAxis = this.component.yAxis.getAxis(serie.yAxisIndex); return [ typeof mpData.xAxis != 'string' && xAxis.getCoordByIndex ? xAxis.getCoordByIndex(mpData.xAxis || 0) : xAxis.getCoord(mpData.xAxis || 0), typeof mpData.yAxis != 'string' && yAxis.getCoordByIndex ? yAxis.getCoordByIndex(mpData.yAxis || 0) : yAxis.getCoord(mpData.yAxis || 0) ]; }, /** * 刷新 */ refresh : function (newOption) { if (newOption) { this.option = newOption; this.series = newOption.series; } this.backupShapeList(); this._buildShape(); }, /** * 动画设定 */ addDataAnimation : function (params) { var series = this.series; var aniMap = {}; // seriesIndex索引参数 for (var i = 0, l = params.length; i < l; i++) { aniMap[params[i][0]] = params[i]; } var x; var dx; var y; var serie; var seriesIndex; var dataIndex; for (var i = 0, l = this.shapeList.length; i < l; i++) { seriesIndex = this.shapeList[i]._seriesIndex; if (aniMap[seriesIndex] && !aniMap[seriesIndex][3]) { // 有数据删除才有移动的动画 if (this.shapeList[i].type == 'candle') { dataIndex = ecData.get(this.shapeList[i], 'dataIndex'); serie = series[seriesIndex]; if (aniMap[seriesIndex][2] && dataIndex == serie.data.length - 1 ) { // 队头加入删除末尾 this.zr.delShape(this.shapeList[i].id); continue; } else if (!aniMap[seriesIndex][2] && dataIndex === 0) { // 队尾加入删除头部 this.zr.delShape(this.shapeList[i].id); continue; } dx = this.component.xAxis.getAxis( serie.xAxisIndex || 0 ).getGap(); x = aniMap[seriesIndex][2] ? dx : -dx; y = 0; this.zr.animate(this.shapeList[i].id, '') .when( 500, {position : [x, y]} ) .start(); } } } } }; zrUtil.inherits(K, ChartBase); zrUtil.inherits(K, ComponentBase); // 图表注册 require('../chart').define('k', K); return K; });
mit
yangra/SoftUni
DataStructures/Exams/EXAM02072017/src/main/java/enterprise/Position.java
93
package enterprise; public enum Position { DEVELOPER, MANAGER, HR, TEAM_LEAD, OWNER; }
mit
wix/wix-style-react
packages/wix-style-react/src/PageFooter/Center/index.js
36
export { default } from './Center';
mit
kimgea/twitter_scraper_selenium
sbot/twitter/scraper/scrape/base.py
2015
''' Created on 23. nov. 2015 @author: kga ''' import logging from selenium import webdriver class ScrapeBaseSelenium(object): """ Base class for scraping """ def __init__(self): self.browser = None self.base_url="http://mobile.twitter.com/" self.data = None self.user=None def get_storage_data(self): """ get scraped data with user/owner of that data """ return dict(user=self.user, data=self.data) def scrape_data(self): """ Add code to scrape wanted data """ raise NotImplementedError("Please Implement scrape_data method") def store_data(self): """ Add code on how o store scraped data """ raise NotImplementedError("Please Implement store_data method") def make_url(self): """ Add code tomake/prep the urs that is to be scraped """ raise NotImplementedError("Please Implement make_url method") def run(self, user): """ Run the scraper args: user (str): Twitter user screen_name of user to be scraped """ logging.debug(u"username: "+unicode(user)) self.user=user logging.debug(u"Set up selenium") self.setup_selenium() logging.debug(u"Scrape data") self.scrape_data() logging.debug(u"store data") self.store_data() logging.debug(u"tear down selenium") self.tear_down_selenium() def setup_selenium(self): logging.debug(u"Open browser") #self.browser = webdriver.Firefox() self.browser = webdriver.Chrome() logging.debug(u"Browser is open") logging.debug(u"url: "+unicode(self.make_url())) self.browser.get(self.make_url()) logging.debug(u"Page is accessed") def tear_down_selenium(self): self.browser.quit()
mit
Sudwood/AdvancedUtilities
java/com/sudwood/advancedutilities/blocks/BlockCompressorBlock.java
4683
package com.sudwood.advancedutilities.blocks; import java.util.Random; import com.sudwood.advancedutilities.AdvancedUtilities; import com.sudwood.advancedutilities.tileentity.TileEntityCompressor; import com.sudwood.advancedutilities.tileentity.TileEntityCompressor; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; public class BlockCompressorBlock extends BlockContainer { private final Random field_149933_a = new Random(); private IIcon[] icons = new IIcon[3]; protected BlockCompressorBlock(Material mat) { super(mat); } @Override public TileEntity createNewTileEntity(World world, int p_149915_2_) { return new TileEntityCompressor(); } @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister icon) { icons[0] = icon.registerIcon("advancedutilities:compressor"); } @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { return icons[0]; } @Override public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { if (par1World.isRemote) { return true; } else { TileEntity var10 = par1World.getTileEntity(par2, par3, par4); if(var10 == null || par5EntityPlayer.isSneaking()){ return false; } if (var10 != null&& var10 instanceof TileEntityCompressor) { par5EntityPlayer.openGui(AdvancedUtilities.instance, AdvancedUtilities.compressorGui, par1World, par2, par3, par4); } return true; } } public void breakBlock(World p_149749_1_, int p_149749_2_, int p_149749_3_, int p_149749_4_, Block p_149749_5_, int p_149749_6_) { if (!false) { TileEntityCompressor tileentityfurnace = (TileEntityCompressor)p_149749_1_.getTileEntity(p_149749_2_, p_149749_3_, p_149749_4_); if (tileentityfurnace != null) { for (int i1 = 0; i1 < tileentityfurnace.getSizeInventory(); ++i1) { ItemStack itemstack = tileentityfurnace.getStackInSlot(i1); if (itemstack != null) { float f = this.field_149933_a.nextFloat() * 0.8F + 0.1F; float f1 = this.field_149933_a.nextFloat() * 0.8F + 0.1F; float f2 = this.field_149933_a.nextFloat() * 0.8F + 0.1F; while (itemstack.stackSize > 0) { int j1 = this.field_149933_a.nextInt(21) + 10; if (j1 > itemstack.stackSize) { j1 = itemstack.stackSize; } itemstack.stackSize -= j1; EntityItem entityitem = new EntityItem(p_149749_1_, (double)((float)p_149749_2_ + f), (double)((float)p_149749_3_ + f1), (double)((float)p_149749_4_ + f2), new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage())); if (itemstack.hasTagCompound()) { entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy()); } float f3 = 0.05F; entityitem.motionX = (double)((float)this.field_149933_a.nextGaussian() * f3); entityitem.motionY = (double)((float)this.field_149933_a.nextGaussian() * f3 + 0.2F); entityitem.motionZ = (double)((float)this.field_149933_a.nextGaussian() * f3); p_149749_1_.spawnEntityInWorld(entityitem); } } } p_149749_1_.func_147453_f(p_149749_2_, p_149749_3_, p_149749_4_, p_149749_5_); } } super.breakBlock(p_149749_1_, p_149749_2_, p_149749_3_, p_149749_4_, p_149749_5_, p_149749_6_); } }
mit
tomzx/laravex
src/Illuminate/Console/GeneratorCommand.php
3840
<?php namespace Illuminate\Console; use Illuminate\Filesystem\Filesystem; use Symfony\Component\Console\Input\InputArgument; abstract class GeneratorCommand extends Command { use AppNamespaceDetectorTrait; /** * The filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * The type of class being generated. * * @var string */ protected $type; /** * Create a new controller creator command instance. * * @param \Illuminate\Filesystem\Filesystem $files * @return void */ public function __construct(Filesystem $files) { parent::__construct(); $this->files = $files; } /** * Get the stub file for the generator. * * @return string */ abstract protected function getStub(); /** * Execute the console command. * * @return void */ public function fire() { $name = $this->parseName($this->getNameInput()); if ($this->files->exists($path = $this->getPath($name))) { return $this->error($this->type.' already exists!'); } $this->makeDirectory($path); $this->files->put($path, $this->buildClass($name)); $this->info($this->type.' created successfully.'); } /** * Get the destination class path. * * @param string $name * @return string */ protected function getPath($name) { $name = str_replace($this->getAppNamespace(), '', $name); return $this->laravel['path'].'/'.str_replace('\\', '/', $name).'.php'; } /** * Parse the name and format according to the root namespace. * * @param string $name * @return string */ protected function parseName($name) { $rootNamespace = $this->getAppNamespace(); if (starts_with($name, $rootNamespace)) { return $name; } return $this->parseName($this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name); } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace; } /** * Build the directory for the class if necessary. * * @param string $path * @return string */ protected function makeDirectory($path) { if ( ! $this->files->isDirectory(dirname($path))) { $this->files->makeDirectory(dirname($path), 0777, true, true); } } /** * Build the class with the given name. * * @param string $name * @return string */ protected function buildClass($name) { $stub = $this->files->get($this->getStub()); return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name); } /** * Replace the namespace for the given stub. * * @param string $stub * @param string $name * @return $this */ protected function replaceNamespace(&$stub, $name) { $stub = str_replace( '{{namespace}}', $this->getNamespace($name), $stub ); $stub = str_replace( '{{rootNamespace}}', $this->getAppNamespace(), $stub ); return $this; } /** * Get the full namespace name for a given class. * * @param string $name * @return string */ protected function getNamespace($name) { return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\'); } /** * Replace the class name for the given stub. * * @param string $stub * @param string $name * @return string */ protected function replaceClass($stub, $name) { $class = str_replace($this->getNamespace($name).'\\', '', $name); return str_replace('{{class}}', $class, $stub); } /** * Get the desired class name from the input. * * @return string */ protected function getNameInput() { return $this->argument('name'); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return [ ['name', InputArgument::REQUIRED, 'The name of the class'], ]; } }
mit
idcf/idcfcloud-cli
lib/idcf/cli/error/init.rb
62
require_relative './api_error' require_relative './cli_error'
mit
steelbrain/declarations
spec/process-spec.js
6446
'use babel' import { processDeclarations, processProvider } from '../lib/process' describe('Process', function() { afterEach(function() { atom.notifications.clear() }) function testResultOf(callback: Function) { callback() return expect(atom.notifications.getNotifications().length === 0) } describe('processDeclarations', function() { it('works well with valid ones', function() { testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: { filePath: '/etc/passwd', position: [0, 1], }, }]) }).toBe(true) }) it('cries if range is invalid', function() { testResultOf(function() { processDeclarations([{ range: false, source: { filePath: '/etc/passwd', position: [0, 1], }, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: null, source: { filePath: '/etc/passwd', position: [0, 1], }, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: true, source: { filePath: '/etc/passwd', position: [0, 1], }, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: 'asd', source: { filePath: '/etc/passwd', position: [0, 1], }, }]) }).toBe(false) }) it('cries if source is invalid', function() { testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: null, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: false, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: true, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: 'asd', }]) }).toBe(false) }) it('cries if source.filePath is invalid', function() { testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: { filePath: false, position: [0, 1], }, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: { filePath: null, position: [0, 1], }, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: { filePath: true, position: [0, 1], }, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: { filePath: {}, position: [0, 1], }, }]) }).toBe(false) }) it('ignores if theres no source.position', function() { testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: { filePath: '/etc/passwd', position: null, }, }]) }).toBe(true) }) it('cries if source.position is provided an invalid', function() { testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: { filePath: '/etc/passwd', position: true, }, }]) }).toBe(false) testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source: { filePath: '/etc/passwd', position: 'asd', }, }]) }).toBe(false) }) it('accepts callback in source', function() { testResultOf(function() { processDeclarations([{ range: [[0, 0], [0, 1]], source() {}, }]) }).toBe(true) }) it('normalizes contents of declarations', function() { const declaration = { range: [[0, 0], [1, 1]], source: { filePath: '/etc/passwd', position: [0, 1], }, } processDeclarations([declaration]) expect(declaration.range.constructor.name).toBe('Range') expect(declaration.source.position.constructor.name).toBe('Point') }) }) describe('validateProvider', function() { it('works with valid providers', function() { testResultOf(function() { processProvider({ grammarScopes: ['*'], getDeclarations() { }, }) }).toBe(true) }) it('cries if grammarScopes is invalid', function() { testResultOf(function() { processProvider({ grammarScopes: null, getDeclarations() {}, }) }).toBe(false) testResultOf(function() { processProvider({ grammarScopes: true, getDeclarations() {}, }) }).toBe(false) testResultOf(function() { processProvider({ grammarScopes: 'asd', getDeclarations() {}, }) }).toBe(false) testResultOf(function() { processProvider({ grammarScopes: {}, getDeclarations() {}, }) }).toBe(false) }) it('cries if getDeclarations is invalid', function() { testResultOf(function() { processProvider({ grammarScopes: ['*'], getDeclarations: true, }) }).toBe(false) testResultOf(function() { processProvider({ grammarScopes: ['*'], getDeclarations: false, }) }).toBe(false) testResultOf(function() { processProvider({ grammarScopes: ['*'], getDeclarations: null, }) }).toBe(false) testResultOf(function() { processProvider({ grammarScopes: ['*'], getDeclarations: 'asd', }) }).toBe(false) testResultOf(function() { processProvider({ grammarScopes: ['*'], getDeclarations: {}, }) }).toBe(false) }) }) })
mit
pierre-haessig/sysdiag
tests/test_sysdiag.py
7646
#!/usr/bin/python # -*- coding: utf-8 -*- """ Test the main module of System Diagram Pierre Haessig — September 2013 """ from nose.tools import assert_equal, assert_true, assert_raises, assert_is # Import sysdiag: import sys try: import sysdiag except ImportError: sys.path.append('..') import sysdiag def test_create_name(): '''error proofing of the `_create_name` routine''' create = sysdiag._create_name # 1) Name creation when the base is not already taken: assert_equal(create([],'abc'), 'abc') assert_equal(create(['def'],'abc'), 'abc') assert_equal(create(['d','e','f'],'abc'), 'abc') # 2) when the basename is empty: with assert_raises(ValueError): create([],'') with assert_raises(ValueError): create([],' ') # 3) when the basename is already taken assert_equal(create(['a'],'a'), 'a0') assert_equal(create(['a', 'a0'],'a'), 'a1') def test_is_similar(): '''check the similarity test of Ports and Wires''' # Ports: p1 = sysdiag.Port('p1', 'type1') p1a = sysdiag.Port('p1', 'type1') p12 = sysdiag.Port('p1', 'type2') p1_in = sysdiag.InputPort('p1', 'type1') p2 = sysdiag.Port('p2', 'type1') # Check similarity assert_true(p1._is_similar(p1)) assert_true(p1._is_similar(p1a)) # Check dissimilarity assert_true(not p1._is_similar(p12)) assert_true(not p1._is_similar(p1_in)) assert_true(not p1._is_similar(p2)) # Wires w1 = sysdiag.Wire('w1', 'type1') w1a = sysdiag.Wire('w1', 'type1') w12 = sysdiag.Wire('w1', 'type2') w1_in = sysdiag.SignalWire('w1', 'type1') w2 = sysdiag.Wire('w2', 'type1') # Check similarity assert_true(w1._is_similar(w1)) assert_true(w1._is_similar(w1a)) # Check dissimilarity assert_true(not w1._is_similar(w12)) assert_true(not w1._is_similar(w1_in)) assert_true(not w1._is_similar(w2)) # TODO: check wires with connected ports: def test_system_eq(): '''test equality of systems''' # Some empty systems: s1 = sysdiag.System('syst1') s1a = sysdiag.System('syst1') s2 = sysdiag.System('syst2') assert_equal(s1,s1) assert_true(not s1 != s1) assert_equal(s1,s1a) assert_true(not s1 != s1a) assert_true(not s1 == s2) assert_true(s1 != s2) def test_is_empty(): '''test definition of the *emptyness* of a System''' s1 = sysdiag.System('syst1') assert_true(s1.is_empty()) # System with one subsystem: s1 = sysdiag.System('syst1') s1.add_subsystem(sysdiag.System('syst2')) assert_true(not s1.is_empty()) # System with one wire: s1 = sysdiag.System('syst1') s1.add_wire(sysdiag.Wire('w1', 'type1')) assert_true(not s1.is_empty()) # System with one subsystem and one wire: s1 = sysdiag.System('syst1') s1.add_wire(sysdiag.Wire('w1', 'type1')) s1.add_subsystem(sysdiag.System('syst2')) assert_true(not s1.is_empty()) def test_add_subsystem(): '''check the add_subsystem machinery''' r = sysdiag.System('root') # a subsystem, assigned with parent.add_subsystem s1 = sysdiag.System('s1') assert_is(s1.parent, None) r.add_subsystem(s1) assert_is(s1.parent, r) # a subsystem, assigned at creation s2 = sysdiag.System('s2', parent=r) assert_is(s2.parent, r) def test_add_ports(): r = sysdiag.System('root') p1 = sysdiag.Port('p1', 'type1') p2 = sysdiag.Port('p2', 'type1') r.add_port(p1) r.add_port(p2) # Check ports list and dict: assert_equal(len(r.ports), 2) assert 'p1' in r.ports_dict.keys() assert 'p2' in r.ports_dict.keys() # duplicate addition: with assert_raises(ValueError): r.add_port(p1) # duplicate name: p11 = sysdiag.Port('p1', 'type1') with assert_raises(ValueError): r.add_port(p11) def test_connect_port(): '''check the connect_port method of Wire''' r = sysdiag.System('root') s1 = sysdiag.System('s1', parent=r) p1 = sysdiag.Port('p1', 'type1') s1.add_port(p1) w1 = sysdiag.Wire('w1', 'type1', parent=r) w2 = sysdiag.Wire('w2', 'type1', parent=r) w3 = sysdiag.Wire('w3', 'other type', parent=r) # failure of wrong type: with assert_raises(TypeError): w3.connect_port(p1) # wire connection that works: w1.connect_port(p1) assert_is(p1.wire, w1) # failure if a port is already taken: with assert_raises(ValueError): w2.connect_port(p1) def test_connect_systems(): '''check the connect_systems routine''' r = sysdiag.System('root') s1 = sysdiag.System('s1', parent=r) s2 = sysdiag.System('s2') # parent is None # add some ports s1.add_port(sysdiag.Port('p1', 'type1')) s2.add_port(sysdiag.Port('p2', 'type1')) p_other = sysdiag.Port('p_other', 'other type') s2.add_port(p_other) # failure if no common parents with assert_raises(ValueError): w1 = sysdiag.connect_systems(s1,s2, 'p1', 'p2') r.add_subsystem(s2) w1 = sysdiag.connect_systems(s1,s2, 'p1', 'p2') assert_equal(len(w1.ports), 2) # failure if wrong types of ports: assert_equal(w1.is_connect_allowed(p_other, 'sibling'), False) with assert_raises(TypeError): w = sysdiag.connect_systems(s1,s2, 'p1', 'p_other') # double connection: no change is performed w2 = sysdiag.connect_systems(s1,s2, 'p1', 'p2') assert_is(w2,w1) assert_equal(len(w1.ports), 2) def test_to_json(): '''basic test of JSON serialization of System, Wire and Port''' # An empty System s = sysdiag.System('syst') s_dict = {'__class__': 'sysdiag.System', '__sysdiagclass__': 'System', 'name': 'syst', 'params': {}, 'ports': [], 'subsystems': [], 'wires': [] } assert_equal(s._to_json(), s_dict) # An empty Wire (no connected ports): w = sysdiag.Wire('w1', 'type1') w_dict = {'__class__': 'sysdiag.Wire', '__sysdiagclass__': 'Wire', 'name': 'w1', 'ports': [], 'type': 'type1' } assert_equal(w._to_json(), w_dict) # A port: p = sysdiag.Port('p1', 'type1') p_dict = {'__class__': 'sysdiag.Port', '__sysdiagclass__': 'Port', 'name': 'p1', 'type': 'type1' } assert_equal(p._to_json(), p_dict) # A system with some ports: s.add_port(p) assert_equal(s._to_json()['ports'], [p]) # A system with "default port" (i.e. created by the system) s.del_port(p) s.add_port(p, created_by_system=True) assert_equal(s._to_json()['ports'], []) # TODO : test a wire with connected ports: def test_from_json(): '''basic test of JSON deserialization''' s_json = '''{ "__class__": "sysdiag.System", "__sysdiagclass__": "System", "name": "my syst", "params": {}, "ports": [], "subsystems": [], "wires": [] }''' s = sysdiag.json_load(s_json) assert_is(type(s), sysdiag.System) assert_equal(s.name, "my syst") # Test a port: p_json = '''{ "__class__": "sysdiag.Port", "__sysdiagclass__": "Port", "name": "my port", "type": "" }''' p = sysdiag.json_load(p_json) assert_is(type(p), sysdiag.Port) assert_equal(p.name, "my port") # Test a wire: w_json = '''{ "__class__": "sysdiag.Wire", "__sysdiagclass__": "Wire", "name": "W2", "ports": [] "type": "" }''' # TODO: implement from_json classmethods
mit
laidig/siri-20-java
src/uk/org/siri/siri/StopVisitTypeEnumeration.java
1864
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.11.30 at 08:24:17 PM JST // package uk.org.siri.siri; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for StopVisitTypeEnumeration. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="StopVisitTypeEnumeration"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="all"/> * &lt;enumeration value="arrivals"/> * &lt;enumeration value="departures"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "StopVisitTypeEnumeration") @XmlEnum public enum StopVisitTypeEnumeration { /** * Return all Stop Visits. * */ @XmlEnumValue("all") ALL("all"), /** * Return only arrival Stop Visits. * */ @XmlEnumValue("arrivals") ARRIVALS("arrivals"), /** * Return only departure Stop Visits. * */ @XmlEnumValue("departures") DEPARTURES("departures"); private final String value; StopVisitTypeEnumeration(String v) { value = v; } public String value() { return value; } public static StopVisitTypeEnumeration fromValue(String v) { for (StopVisitTypeEnumeration c: StopVisitTypeEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
mit
ringingmaster/ringingmaster-engine
src/main/java/org/ringingmaster/engine/notation/persist/PersistableNotationTransformer.java
1844
package org.ringingmaster.engine.notation.persist; import org.ringingmaster.engine.NumberOfBells; import org.ringingmaster.engine.notation.Notation; import org.ringingmaster.engine.notation.NotationBuilder; import org.ringingmaster.persist.generated.v1.LibraryNotationPersist; /** * Manage the conversion of the persistable and engine version of notations. * Attempt to keep the persistable stuff isolated. * * @author Steve Lake */ public class PersistableNotationTransformer { public static NotationBuilder populateBuilderFromPersistableNotation(LibraryNotationPersist persistableNotation) { NotationBuilder notationBuilder = NotationBuilder.getInstance(); notationBuilder.setNumberOfWorkingBells(NumberOfBells.valueOf(persistableNotation.getNumberOfWorkingBells())); if (!persistableNotation.isFoldedPalindrome()) { notationBuilder.setUnfoldedNotationShorthand(persistableNotation.getNotation()); } else { notationBuilder.setFoldedPalindromeNotationShorthand(persistableNotation.getNotation(), persistableNotation.getNotation2()); } notationBuilder.setName(persistableNotation.getName()); return notationBuilder; } public static LibraryNotationPersist buildPersistableNotation(Notation notation) { LibraryNotationPersist persistableNotation = new LibraryNotationPersist(); persistableNotation.setName(notation.getName()); persistableNotation.setNumberOfWorkingBells(notation.getNumberOfWorkingBells().toInt()); persistableNotation.setFoldedPalindrome(notation.isFoldedPalindrome()); persistableNotation.setNotation(notation.getRawNotationDisplayString(0, true)); persistableNotation.setNotation2(notation.getRawNotationDisplayString(1, true)); return persistableNotation; } }
mit
sheldonh/whois
spec/whois/record/parser/responses/whois.iis.se/property_status_ok_spec.rb
909
# encoding: utf-8 # This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # /spec/fixtures/responses/whois.iis.se/property_status_ok.expected # # and regenerate the tests with the following rake task # # $ rake spec:generate # require 'spec_helper' require 'whois/record/parser/whois.iis.se.rb' describe Whois::Record::Parser::WhoisIisSe, "property_status_ok.expected" do subject do file = fixture("responses", "whois.iis.se/property_status_ok.txt") part = Whois::Record::Part.new(body: File.read(file)) described_class.new(part) end describe "#status" do it do expect(subject.status).to eq(:registered) end end describe "#available?" do it do expect(subject.available?).to eq(false) end end describe "#registered?" do it do expect(subject.registered?).to eq(true) end end end
mit
Saytiras/Game-Prototypes
Thanatros/Assets/Scripts/Model/Block.cs
300
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; using Assets.Scripts.Model; public struct Block { private readonly byte _type; public Block(byte type) { _type = type; } public bool IsSolid => BlockTypes.GetBlockType(_type).IsSolid; }
mit
Philo/Umbraco.Elasticsearch
samples/Umbraco.Elasticsearch.Samplev73/Features/Search/Controllers/DtSearchController.cs
957
using System.Web.Mvc; using Nest.Queryify.Extensions; using Umbraco.Elasticsearch.Core; using Umbraco.Elasticsearch.Samplev73.Features.Search.Models; using Umbraco.Elasticsearch.Samplev73.Features.Search.Queries.Article; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Umbraco.Elasticsearch.Samplev73.Features.Search.Controllers { public class DtSearchController : RenderMvcController { [NonAction] public override ActionResult Index(RenderModel model) { return base.Index(model); } public ActionResult Index(ArticleSearchParameters parameters) { var response = UmbracoSearchFactory.Client.Query(new ArticleSearchQuery(parameters)); var model = new SearchResultModel<ArticleSearchResult, ArticleSearchParameters, ArticleDocument>(CurrentPage); model.SetSearchResult(response); return CurrentTemplate(model); } } }
mit
nixel2007/vsc-language-1c-bsl
src/util/bsllsDownloadChannel.ts
151
enum BSLLanguageServerDownloadChannel { Stable = "stable", PreRelease = "prerelease" } export default BSLLanguageServerDownloadChannel;
mit
c3mediagroup/el-dorado
test/functional/subscriptions_controller_test.rb
547
require 'test_helper' class SubscriptionsControllerTest < ActionController::TestCase def setup @controller = SubscriptionsController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_should_get_index end def test_should_get_new end def test_should_create_subscription end def test_should_show_subscription end def test_should_get_edit end def test_should_update_subscription end def test_should_destroy_subscription end end
mit
sharecloud/sharecloud
model/User.class.php
7065
<?php final class User extends ModelBase { /** * User ID * @var int */ private $uid = 0; /** * Username * @var string */ private $username; /** * Firstname * @var string */ private $firstname; /** * Lastname * @var string */ private $lastname; /** * New Password * @var string */ private $password; /** * Current password (hashed) * @var string */ private $curPassword; /** * Salt * @var string */ private $salt; /** * Mail adress * @var string */ private $email; /** * Is Admin? * @var boolean */ private $isAdmin = false; /** * Quota * @var integer */ private $quota; /** * Design * @var string */ private $design = 'normal'; /** * Last login * @var int */ private $last_login; /** * Language * @var string */ private $lang; /** * Constructor * @param mixed An User Identiefier either the numeeric User ID or String username */ public function __construct() { } protected function assign(array $row) { $this->isNewRecord = false; $this->uid = $row['_id']; $this->username = $row['username']; $this->firstname = $row['firstname']; $this->lastname = $row['lastname']; $this->password = NULL; $this->curPassword = $row['password']; $this->salt = $row['salt']; $this->email = $row['email']; $this->isAdmin = (bool)$row['admin']; $this->quota = $row['quota']; $this->last_login = $row['last_login']; $this->lang = $row['lang']; $this->design = $row['design']; } /** * Login with clearpaswd * @param String Cleartext Password * @return bool Success */ public function login($clearPswd) { if(Utils::createPasswordHash($clearPswd, $this->salt) == $this->curPassword) { System::getSession()->setUID($this->uid); $this->last_login = time(); $this->save(); return true; } return false; } /** * Saves changes to DB */ public function save() { $data = array( ':username' => $this->username, ':email' => $this->email, ':lang' => $this->lang, ':last_login' => $this->last_login, ':firstname' => $this->firstname, ':lastname' => $this->lastname, ':admin' => $this->isAdmin, ':quota' => $this->quota, ':design' => $this->design ); if($this->isNewRecord) { // TODO: Check Password! $data[':pswd'] = $this->password; $data[':salt'] = $this->salt; $sql = System::getDatabase()->prepare('INSERT INTO users (username, firstname, lastname, email, admin, lang, quota, password, salt, last_login, design) VALUES(:username, :firstname, :lastname, :email, :admin, :lang, :quota, :pswd, :salt, :last_login, :design)'); $sql->execute($data); $this->uid = System::getDatabase()->lastInsertId(); } else { $data[':uid'] = $this->uid; if($this->password != NULL) { $data[':pswd'] = $this->password; $data[':salt'] = $this->salt; $sql = System::getDatabase()->prepare('UPDATE users SET username = :username, firstname = :firstname, lastname = :lastname, email = :email, admin = :admin, lang = :lang, quota = :quota, password = :pswd, salt = :salt, last_login = :last_login, design = :design WHERE _id = :uid'); } else { $sql = System::getDatabase()->prepare('UPDATE users SET username = :username, firstname = :firstname, lastname = :lastname, email = :email, admin = :admin, lang = :lang, quota = :quota, last_login = :last_login, design = :design WHERE _id = :uid'); } $sql->execute($data); } } public function delete() { // Delete files foreach($this->getFiles() as $file) { $file->delete(); } // Delete folders foreach($this->getFolders() as $folder) { $folder->delete(); } // Delete user $sql = System::getDatabase()->prepare('DELETE FROM users WHERE _id = :id'); $sql->execute(array(':id' => $this->uid)); Log::sysLog("User", "User ".$this->getFullname()." was deleted"); } /** * Global setter * @param string Property name * @param mixed Property value */ public function __set($property, $value) { if($property == 'uid') { throw new InvalidArgumentException('UID is read-only and cannot be set'); } if($property == 'password' && !empty($value)) { $this->salt = Utils::createPasswordSalt(); $value = Utils::createPasswordHash($value, $this->salt); } if(property_exists($this, $property)) { $this->$property = $value; } else { throw new InvalidArgumentException('Property '.$property.' does not exist (class: '.get_class($this).')'); } } /** * Global getter * @param string Property name */ public function __get($property) { if(property_exists($this, $property)) { return $this->$property; } throw new InvalidArgumentException('Property '.$property.' does not exist (class: '.get_class($this).')'); } /** * Returns full name * @return string Fullname */ public function getFullname() { if(empty($this->lastname)) { if(empty($this->firstname)) { return ''; } else { return trim($this->firstname); } } return trim($this->firstname . ' ' . $this->lastname); } public function __toString() { return $this->getFullname(); } public function getFolders() { $list = array(); $folders = Folder::find('user_ID', $this->uid); if(is_array($folders)) { $list = $folders; } else if($folders != NULL) { $list[] = $folders; } return $list; } public function getFiles() { $list = array(); $files = File::find('user_ID', $this->uid); if(is_array($files)) { $list = $files; } else if($files != NULL) { $list[] = $files; } return $list; } public function getUsedSpace() { $space = 0; foreach($this->getFiles() as $file) { $space += $file->size; } return $space; } public function getFreeSpace() { $free = $this->quota - $this->getUsedSpace(); return ($free > 0 ? $free : 0); } public static function find($column = '*', $value = NULL, array $options = array()) { $query = 'SELECT * FROM users'; $params = array(); if($column != '*' && strlen($column) > 0 && $value != NULL) { $query .= ' WHERE '.Database::makeTableOrColumnName($column).' = :value'; $params[':value'] = $value; } if(isset($options['orderby']) && isset($options['sort'])) { $query .= ' ORDER BY '.Database::makeTableOrColumnName($options['orderby']).' ' . strtoupper($options['sort']); } if(isset($options['limit'])) { $query .= ' LIMIT ' . $options['limit']; } $sql = System::getDatabase()->prepare($query); $sql->execute($params); if($sql->rowCount() == 0) { return NULL; } else if($sql->rowCount() == 1) { $user = new User(); $user->assign($sql->fetch()); return $user; } else { $list = array(); while($row = $sql->fetch()) { $user = new User(); $user->assign($row); $list[] = $user; } return $list; } } public static function compare($a, $b) { return strcmp($a->username, $b->username); } } ?>
mit
nesamouzehkesh/felix-rest
src/AppBundle/Library/Base/BaseController.php
611
<?php namespace AppBundle\Library\Base; use FOS\RestBundle\Controller\FOSRestController; class BaseController extends FOSRestController { /** * * @return \AppBundle\Service\AppService */ public function getAppService() { return $this->get('app.service'); } /** * * @return type */ public function getDispatcher() { return $this->get('event_dispatcher'); } /** * * @return \AppBundle\Service\Session */ public function getSession() { return $this->get('app.session.service'); } }
mit
Casecommons/pg_search
spec/lib/pg_search/configuration/foreign_column_spec.rb
1061
# frozen_string_literal: true require "spec_helper" describe PgSearch::Configuration::ForeignColumn do describe "#alias" do with_model :AssociatedModel do table do |t| t.string "title" end end with_model :Model do table do |t| t.string "title" t.belongs_to :another_model, index: false end model do include PgSearch::Model belongs_to :another_model, class_name: 'AssociatedModel' pg_search_scope :with_another, associated_against: { another_model: :title } end end it "returns a consistent string" do association = PgSearch::Configuration::Association.new(Model, :another_model, :title) foreign_column = described_class.new("title", nil, Model, association) column_alias = foreign_column.alias expect(column_alias).to be_a String expect(foreign_column.alias).to eq column_alias end end end
mit
weltenbauer/home-control
src/app/logic/adapter/openhab1/items/itemColorOpenhab1.model.ts
882
/* * brief Implementation of an OpenHAB 1 Color * author Christian Rathemacher (christian@weltenbauer-se.com) * company weltenbauer. Software Entwicklung GmbH * date February 2017 */ //----------------------------------------------------------------------------- import { ItemColor } from '../../../models/items/itemColor.model'; import { Openhab1Adapter } from '../openhab1.adapter'; //----------------------------------------------------------------------------- export class ItemColorOpenhab1 extends ItemColor{ constructor(protected adapter: Openhab1Adapter, private sourceWidget: any){ super(sourceWidget.item.state); this.label = sourceWidget.label; } //------------------------------------------------------------------------- public setColor(color){ super.setColor(color); this.adapter.updateValue(this.sourceWidget.item.link, color); } }
mit
sumocoders/forkcms
src/Frontend/Core/Engine/Base/Block.php
17731
<?php namespace Frontend\Core\Engine\Base; use Common\Core\Header\Priority; use Common\Doctrine\Entity\Meta; use Common\Exception\RedirectException; use ForkCMS\App\KernelLoader; use Frontend\Core\Engine\Breadcrumb; use Frontend\Core\Engine\Exception; use Frontend\Core\Engine\Model; use Frontend\Core\Engine\Url; use Frontend\Core\Header\Header; use Frontend\Core\Engine\TwigTemplate; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\KernelInterface; /** * This class implements a lot of functionality that can be extended by a specific block * * @later Check which methods are the same in FrontendBaseWidget, maybe we should extend from a general class */ class Block extends KernelLoader { /** * The current action * * @var string */ protected $action; /** * The breadcrumb object * * @var Breadcrumb */ protected $breadcrumb; /** * The data * * @var mixed */ protected $data; /** * The header object * * @var Header */ protected $header; /** * The current module * * @var string */ protected $module; /** * Should the current template be replaced with the blocks one? * * @var bool */ private $overwrite; /** * Pagination array * * @var array */ protected $pagination; /** * The path of the template to include, or that replaced the current one * * @var string */ private $templatePath; /** * TwigTemplate instance * * @var TwigTemplate */ protected $template; /** * URL instance * * @var Url */ protected $url; /** * @param KernelInterface $kernel * @param string $module The name of the module. * @param string $action The name of the action. * @param string $data The data that should be available in this block. */ public function __construct(KernelInterface $kernel, string $module, string $action, string $data = null) { parent::__construct($kernel); // get objects from the reference so they are accessible $this->header = $this->getContainer()->get('header'); $this->url = $this->getContainer()->get('url'); $this->template = $this->getContainer()->get('templating'); $this->breadcrumb = $this->getContainer()->get('breadcrumb'); // set properties $this->setModule($module); $this->setAction($action); $this->setData($data); } /** * Add a CSS file into the array * * @param string $file The path for the CSS-file that should be loaded. * @param bool $overwritePath Whether or not to add the module to this path. Module path is added by default. * @param bool $minify Should the CSS be minified? * @param bool $addTimestamp May we add a timestamp for caching purposes? */ public function addCSS( string $file, bool $overwritePath = false, bool $minify = true, bool $addTimestamp = true ): void { // external urls always overwrite the path $overwritePath = $overwritePath || $this->get('fork.validator.url')->isExternalUrl($file); // use module path if (!$overwritePath) { $file = '/src/Frontend/Modules/' . $this->getModule() . '/Layout/Css/' . $file; } // add css to the header $this->header->addCSS( $file, $minify, $addTimestamp, $overwritePath ? Priority::standard() : Priority::forModule($this->getModule()) ); } /** * Add a javascript file into the array * * @param string $file The path to the javascript-file that should be loaded. * @param bool $overwritePath Whether or not to add the module to this path. Module path is added by default. * @param bool $minify Should the file be minified? * @param bool $addTimestamp May we add a timestamp for caching purposes? */ public function addJS( string $file, bool $overwritePath = false, bool $minify = true, bool $addTimestamp = true ): void { // external urls always overwrite the path $overwritePath = $overwritePath || $this->get('fork.validator.url')->isExternalUrl($file); // use module path if (!$overwritePath) { $file = '/src/Frontend/Modules/' . $this->getModule() . '/Js/' . $file; } // add js to the header $this->header->addJS( $file, $minify, $addTimestamp, $overwritePath ? Priority::standard() : Priority::forModule($this->getModule()) ); } /** * Add data that should be available in JS * * @param string $key The key whereunder the value will be stored. * @param mixed $value The value to pass. */ public function addJSData(string $key, $value): void { $this->header->addJsData($this->getModule(), $key, $value); } /** * Execute the action * If a javascript file with the name of the module or action exists it will be loaded. */ public function execute(): void { // build path to the module $frontendModulePath = FRONTEND_MODULES_PATH . '/' . $this->getModule(); // build URL to the module $frontendModuleUrl = '/src/Frontend/Modules/' . $this->getModule() . '/Js'; // add javascript file with same name as module (if the file exists) if (is_file($frontendModulePath . '/Js/' . $this->getModule() . '.js')) { $this->header->addJS( $frontendModuleUrl . '/' . $this->getModule() . '.js', true, true, Priority::module() ); } // add javascript file with same name as the action (if the file exists) if (is_file($frontendModulePath . '/Js/' . $this->getAction() . '.js')) { $this->header->addJS( $frontendModuleUrl . '/' . $this->getAction() . '.js', true, true, Priority::module() ); } } public function getAction(): string { return $this->action; } /** * Get parsed template content. * * @return string */ public function getContent(): string { return $this->template->getContent($this->templatePath); } public function getModule(): string { return $this->module; } /** * Get overwrite mode * * @return bool */ public function getOverwrite(): bool { return $this->overwrite; } public function getTemplate(): TwigTemplate { return $this->template; } public function getTemplatePath(): string { return $this->templatePath; } /** * @param string $path The path for the template to use. * @param bool $overwrite Should the template overwrite the default? */ protected function loadTemplate(string $path = null, bool $overwrite = false): void { // no template given, so we should build the path if ($path === null) { $path = $this->getModule() . '/Layout/Templates/' . $this->getAction() . '.html.twig'; } // set properties $this->setOverwrite($overwrite); $this->setTemplatePath($path); } protected function parsePagination(string $query_parameter = 'page'): void { $pagination = null; $showFirstPages = false; $showLastPages = false; $useQuestionMark = true; // validate pagination array if (!isset($this->pagination['limit'])) { throw new Exception('no limit in the pagination-property.'); } if (!isset($this->pagination['offset'])) { throw new Exception('no offset in the pagination-property.'); } if (!isset($this->pagination['requested_page'])) { throw new Exception('no requested_page available in the pagination-property.'); } if (!isset($this->pagination['num_items'])) { throw new Exception('no num_items available in the pagination-property.'); } if (!isset($this->pagination['num_pages'])) { throw new Exception('no num_pages available in the pagination-property.'); } if (!isset($this->pagination['url'])) { throw new Exception('no url available in the pagination-property.'); } // should we use a questionmark or an ampersand if (mb_strpos($this->pagination['url'], '?') !== false) { $useQuestionMark = false; } // no pagination needed if ($this->pagination['num_pages'] < 1) { return; } // populate count fields $pagination['num_pages'] = $this->pagination['num_pages']; $pagination['current_page'] = $this->pagination['requested_page']; // define anchor $anchor = isset($this->pagination['anchor']) ? '#' . $this->pagination['anchor'] : ''; // as long as we have more then 5 pages and are 5 pages from the end we should show all pages till the end if ($this->pagination['requested_page'] > 5 && $this->pagination['requested_page'] >= ($this->pagination['num_pages'] - 4) ) { $pagesStart = ($this->pagination['num_pages'] > 7) ? $this->pagination['num_pages'] - 5 : $this->pagination['num_pages'] - 6; $pagesEnd = $this->pagination['num_pages']; // fix for page 6 if ($this->pagination['num_pages'] === 6) { $pagesStart = 1; } // show first pages if ($this->pagination['num_pages'] > 7) { $showFirstPages = true; } } elseif ($this->pagination['requested_page'] <= 5) { // as long as we are below page 5 and below 5 from the end we should show all pages starting from 1 $pagesStart = 1; $pagesEnd = 6; // when we have 7 pages, show 7 as end if ($this->pagination['num_pages'] === 7) { $pagesEnd = 7; } elseif ($this->pagination['num_pages'] <= 6) { // when we have less then 6 pages, show the maximum page $pagesEnd = $this->pagination['num_pages']; } // show last pages if ($this->pagination['num_pages'] > 7) { $showLastPages = true; } } else { // page 6 $pagesStart = $this->pagination['requested_page'] - 2; $pagesEnd = $this->pagination['requested_page'] + 2; $showFirstPages = true; $showLastPages = true; } // show previous if ($this->pagination['requested_page'] > 1) { // build URL if ($useQuestionMark) { $url = $this->pagination['url'] . '?' . $query_parameter . '=' . ($this->pagination['requested_page'] - 1); } else { $url = $this->pagination['url'] . '&' . $query_parameter . '=' . ($this->pagination['requested_page'] - 1); } // set $pagination['show_previous'] = true; $pagination['previous_url'] = $url . $anchor; // flip ahead $this->header->addLink( [ 'rel' => 'prev', 'href' => SITE_URL . $url . $anchor, ] ); } // show first pages? if ($showFirstPages) { // init var $pagesFirstStart = 1; $pagesFirstEnd = 1; // loop pages for ($i = $pagesFirstStart; $i <= $pagesFirstEnd; ++$i) { // build URL if ($useQuestionMark) { $url = $this->pagination['url'] . '?' . $query_parameter . '=' . $i; } else { $url = $this->pagination['url'] . '&' . $query_parameter . '=' . $i; } // add $pagination['first'][] = ['url' => $url . $anchor, 'label' => $i]; } } // build array for ($i = $pagesStart; $i <= $pagesEnd; ++$i) { // init var $current = ($i === $this->pagination['requested_page']); // build URL if ($useQuestionMark) { $url = $this->pagination['url'] . '?' . $query_parameter . '=' . $i; } else { $url = $this->pagination['url'] . '&' . $query_parameter . '=' . $i; } // add $pagination['pages'][] = ['url' => $url . $anchor, 'label' => $i, 'current' => $current]; } // show last pages? if ($showLastPages) { // init var $pagesLastStart = $this->pagination['num_pages']; $pagesLastEnd = $this->pagination['num_pages']; // loop pages for ($i = $pagesLastStart; $i <= $pagesLastEnd; ++$i) { // build URL if ($useQuestionMark) { $url = $this->pagination['url'] . '?' . $query_parameter . '=' . $i; } else { $url = $this->pagination['url'] . '&' . $query_parameter . '=' . $i; } // add $pagination['last'][] = ['url' => $url . $anchor, 'label' => $i]; } } // show next if ($this->pagination['requested_page'] < $this->pagination['num_pages']) { // build URL if ($useQuestionMark) { $url = $this->pagination['url'] . '?' . $query_parameter . '=' . ($this->pagination['requested_page'] + 1); } else { $url = $this->pagination['url'] . '&' . $query_parameter . '=' . ($this->pagination['requested_page'] + 1); } // set $pagination['show_next'] = true; $pagination['next_url'] = $url . $anchor; // flip ahead $this->header->addLink( [ 'rel' => 'next', 'href' => SITE_URL . $url . $anchor, ] ); } // multiple pages $pagination['multiple_pages'] = (int) $pagination['num_pages'] !== 1; // assign pagination $this->template->assign('pagination', $pagination); } /** * Redirect to a given URL * * @param string $url The URL whereto will be redirected. * @param int $code The redirect code, default is 302 which means this is a temporary redirect. * * @throws RedirectException */ public function redirect(string $url, int $code = RedirectResponse::HTTP_FOUND): void { throw new RedirectException('Redirect', new RedirectResponse($url, $code)); } private function setAction(string $action) { $this->action = $action; } private function setData(string $data = null): void { // data given? if ($data === null) { return; } $this->data = unserialize($data, ['allowed_classes' => false]); } private function setModule(string $module): void { $this->module = $module; } /** * Set overwrite mode * * @param bool $overwrite true if the template should overwrite the current template, false if not. */ protected function setOverwrite(bool $overwrite): void { $this->overwrite = $overwrite; } /** * Set the path for the template to include or to replace the current one * * @param string $path The path to the template that should be loaded. */ protected function setTemplatePath(string $path): void { $this->templatePath = $path; } protected function setMeta(Meta $meta): void { $this->header->setPageTitle($meta->getTitle(), $meta->isTitleOverwrite()); $this->header->addMetaDescription($meta->getDescription(), $meta->isDescriptionOverwrite()); $this->header->addMetaKeywords($meta->getKeywords(), $meta->isKeywordsOverwrite()); if ($meta->isCanonicalUrlOverwrite() && !empty($meta->getCanonicalUrl())) { $this->header->setCanonicalUrl($meta->getCanonicalUrl()); } $SEO = []; if ($meta->hasSEOFollow()) { $SEO[] = $meta->getSEOFollow(); } if ($meta->hasSEOIndex()) { $SEO[] = $meta->getSEOIndex(); } if (!empty($SEO)) { $this->header->addMetaData( ['name' => 'robots', 'content' => implode(', ', $SEO)], true ); } } /** * Creates and returns a Form instance from the type of the form. * * @param string $type FQCN of the form type class i.e: MyClass::class * @param mixed $data The initial data for the form * @param array $options Options for the form * * @return Form */ public function createForm(string $type, $data = null, array $options = []): Form { return $this->get('form.factory')->create($type, $data, $options); } /** * Get the request from the container. * * @return Request */ public function getRequest(): Request { return Model::getRequest(); } }
mit
Gordon-from-Blumberg/Klax
js/team.js
329
/** * @author Gordon from Blumberg * @description Team module * @version 0.1.0 */ define(['GBL'],function (gbl) { "use strict"; var team = {}; team.name = 'team.js'; team.version = '0.1.0'; team.Team = function Team(opts) { }.inherit(gbl.Collection); team.Team.prototype.extend({},true); });
mit
Azure/azure-sdk-for-go
services/preview/logic/mgmt/2015-08-01-preview/logic/integrationaccountagreements.go
16956
package logic // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // IntegrationAccountAgreementsClient is the REST API for Azure Logic Apps. type IntegrationAccountAgreementsClient struct { BaseClient } // NewIntegrationAccountAgreementsClient creates an instance of the IntegrationAccountAgreementsClient client. func NewIntegrationAccountAgreementsClient(subscriptionID string) IntegrationAccountAgreementsClient { return NewIntegrationAccountAgreementsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewIntegrationAccountAgreementsClientWithBaseURI creates an instance of the IntegrationAccountAgreementsClient // client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI // (sovereign clouds, Azure stack). func NewIntegrationAccountAgreementsClientWithBaseURI(baseURI string, subscriptionID string) IntegrationAccountAgreementsClient { return IntegrationAccountAgreementsClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or updates an integration account agreement. // Parameters: // resourceGroupName - the resource group name. // integrationAccountName - the integration account name. // agreementName - the integration account agreement name. // agreement - the integration account agreement. func (client IntegrationAccountAgreementsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, integrationAccountName string, agreementName string, agreement IntegrationAccountAgreement) (result IntegrationAccountAgreement, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountAgreementsClient.CreateOrUpdate") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, integrationAccountName, agreementName, agreement) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "CreateOrUpdate", resp, "Failure responding to request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client IntegrationAccountAgreementsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, agreementName string, agreement IntegrationAccountAgreement) (*http.Request, error) { pathParameters := map[string]interface{}{ "agreementName": autorest.Encode("path", agreementName), "integrationAccountName": autorest.Encode("path", integrationAccountName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-08-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/agreements/{agreementName}", pathParameters), autorest.WithJSON(agreement), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client IntegrationAccountAgreementsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client IntegrationAccountAgreementsClient) CreateOrUpdateResponder(resp *http.Response) (result IntegrationAccountAgreement, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes an integration account agreement. // Parameters: // resourceGroupName - the resource group name. // integrationAccountName - the integration account name. // agreementName - the integration account agreement name. func (client IntegrationAccountAgreementsClient) Delete(ctx context.Context, resourceGroupName string, integrationAccountName string, agreementName string) (result autorest.Response, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountAgreementsClient.Delete") defer func() { sc := -1 if result.Response != nil { sc = result.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeletePreparer(ctx, resourceGroupName, integrationAccountName, agreementName) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "Delete", nil, "Failure preparing request") return } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "Delete", resp, "Failure sending request") return } result, err = client.DeleteResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "Delete", resp, "Failure responding to request") return } return } // DeletePreparer prepares the Delete request. func (client IntegrationAccountAgreementsClient) DeletePreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, agreementName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "agreementName": autorest.Encode("path", agreementName), "integrationAccountName": autorest.Encode("path", integrationAccountName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-08-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/agreements/{agreementName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client IntegrationAccountAgreementsClient) DeleteSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client IntegrationAccountAgreementsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get gets an integration account agreement. // Parameters: // resourceGroupName - the resource group name. // integrationAccountName - the integration account name. // agreementName - the integration account agreement name. func (client IntegrationAccountAgreementsClient) Get(ctx context.Context, resourceGroupName string, integrationAccountName string, agreementName string) (result IntegrationAccountAgreement, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountAgreementsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, integrationAccountName, agreementName) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client IntegrationAccountAgreementsClient) GetPreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, agreementName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "agreementName": autorest.Encode("path", agreementName), "integrationAccountName": autorest.Encode("path", integrationAccountName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-08-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/agreements/{agreementName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client IntegrationAccountAgreementsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client IntegrationAccountAgreementsClient) GetResponder(resp *http.Response) (result IntegrationAccountAgreement, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets a list of integration account agreements. // Parameters: // resourceGroupName - the resource group name. // integrationAccountName - the integration account name. // top - the number of items to be included in the result. // filter - the filter to apply on the operation. func (client IntegrationAccountAgreementsClient) List(ctx context.Context, resourceGroupName string, integrationAccountName string, top *int32, filter string) (result IntegrationAccountAgreementListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountAgreementsClient.List") defer func() { sc := -1 if result.iaalr.Response.Response != nil { sc = result.iaalr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, integrationAccountName, top, filter) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.iaalr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "List", resp, "Failure sending request") return } result.iaalr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "List", resp, "Failure responding to request") return } if result.iaalr.hasNextLink() && result.iaalr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListPreparer prepares the List request. func (client IntegrationAccountAgreementsClient) ListPreparer(ctx context.Context, resourceGroupName string, integrationAccountName string, top *int32, filter string) (*http.Request, error) { pathParameters := map[string]interface{}{ "integrationAccountName": autorest.Encode("path", integrationAccountName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-08-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if top != nil { queryParameters["$top"] = autorest.Encode("query", *top) } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/agreements", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client IntegrationAccountAgreementsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client IntegrationAccountAgreementsClient) ListResponder(resp *http.Response) (result IntegrationAccountAgreementListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client IntegrationAccountAgreementsClient) listNextResults(ctx context.Context, lastResults IntegrationAccountAgreementListResult) (result IntegrationAccountAgreementListResult, err error) { req, err := lastResults.integrationAccountAgreementListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "logic.IntegrationAccountAgreementsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client IntegrationAccountAgreementsClient) ListComplete(ctx context.Context, resourceGroupName string, integrationAccountName string, top *int32, filter string) (result IntegrationAccountAgreementListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/IntegrationAccountAgreementsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, integrationAccountName, top, filter) return }
mit
Boshen/angular2-components
src/app/app.routes.ts
345
import { RouterConfig } from '@angular/router' import { Home } from './home' import { DatePickerPage } from './date-picker' import { PieChartPage } from './pie-chart' export const routes: RouterConfig = [ { path: '', component: Home }, { path: 'date-picker', component: DatePickerPage }, { path: 'pie-chart', component: PieChartPage } ]
mit
kayler-renslow/arma-intellij-plugin
src/com/kaylerrenslow/armaplugin/lang/sqf/completion/CompletionAdders.java
5604
package com.kaylerrenslow.armaplugin.lang.sqf.completion; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.PrioritizedLookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.lang.ASTNode; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.util.ProcessingContext; import com.kaylerrenslow.armaplugin.ArmaPluginIcons; import com.kaylerrenslow.armaplugin.ArmaPluginUserData; import com.kaylerrenslow.armaplugin.lang.PsiUtil; import com.kaylerrenslow.armaplugin.lang.header.HeaderConfigFunction; import com.kaylerrenslow.armaplugin.lang.sqf.SQFFileType; import com.kaylerrenslow.armaplugin.lang.sqf.SQFStatic; import com.kaylerrenslow.armaplugin.lang.sqf.psi.*; import com.kaylerrenslow.armaplugin.lang.sqf.syntax.CommandDescriptor; import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.List; /** * @author Kayler * @since 12/10/2017 */ public class CompletionAdders { private static int VAR_PRIORITY = 7000; private static int FUNCTION_PRIORITY = 8000; private static int LITERAL_PRIORITY = 9000; public static void addVariables(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result, @NotNull PsiElement cursor, boolean forLocalVars) { HashSet<String> putVars = new HashSet<>(); PsiUtil.traverseDepthFirstSearch(parameters.getOriginalFile().getNode(), astNode -> { PsiElement nodeAsElement = astNode.getPsi(); if (nodeAsElement == cursor) { return false; } if (!(nodeAsElement instanceof SQFVariable)) { return false; } SQFVariable var = (SQFVariable) nodeAsElement; if (((var.isLocal() && forLocalVars) || (!var.isLocal() && !forLocalVars)) && !putVars.contains(var.getVarName().toLowerCase())) { putVars.add(var.getVarName().toLowerCase()); result.addElement(PrioritizedLookupElement.withPriority( LookupElementBuilder.createWithSmartPointer(var.getVarName(), var) .withTailText(var.isMagicVar() ? " (Magic Var)" : ( forLocalVars ? " (Local Variable)" : " (Global Variable)" ) ) .withIcon(var.isMagicVar() ? ArmaPluginIcons.ICON_SQF_MAGIC_VARIABLE : ArmaPluginIcons.ICON_SQF_VARIABLE), VAR_PRIORITY) ); } return false; }); } /** * Adds all literals to completion set for all parent commands expression at the cursor. * * @see CommandDescriptor#getAllLiterals() */ public static void addLiterals(@NotNull PsiElement cursor, @NotNull CompletionResultSet result, boolean trimQuotes) { ASTNode ancestor = PsiUtil.getFirstAncestorOfType(cursor.getNode(), SQFTypes.EXPRESSION_STATEMENT, null); if (ancestor == null) { return; } PsiUtil.traverseDepthFirstSearch(ancestor, astNode -> { PsiElement nodeAsPsi = astNode.getPsi(); if (nodeAsPsi == cursor) { return true; } if (!(nodeAsPsi instanceof SQFCommandExpression)) { return false; } SQFCommandExpression commandExpression = (SQFCommandExpression) nodeAsPsi; SQFExpressionOperator operator = commandExpression.getExprOperator(); CommandDescriptor descriptor = SQFSyntaxHelper.getInstance().getDescriptor(operator.getText()); if (descriptor == null) { return false; } for (String s : descriptor.getAllLiterals()) { result.addElement( PrioritizedLookupElement.withPriority(LookupElementBuilder.create(trimQuotes ? s.substring(1, s.length() - 1) : s) .bold() .withTailText(" (" + SQFStatic.getSQFBundle().getString("CompletionContributors.literal") + ")") , LITERAL_PRIORITY ) ); } return false; }); } /** * Adds all description.ext/config.cpp functions to the completion result */ public static void addFunctions(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) { List<HeaderConfigFunction> allConfigFunctions = ArmaPluginUserData.getInstance().getAllConfigFunctions(parameters.getOriginalFile()); if (allConfigFunctions == null) { return; } for (HeaderConfigFunction function : allConfigFunctions) { result.addElement( PrioritizedLookupElement.withPriority( LookupElementBuilder.create(function) .withIcon(HeaderConfigFunction.getIcon()) .withPresentableText(function.getCallableName()), FUNCTION_PRIORITY ) ); } } /** * Adds all SQF commands to the completion result */ public static void addCommands(@NotNull Project project, @NotNull CompletionResultSet result) { for (String command : SQFStatic.COMMANDS_SET) { SQFCommand cmd = PsiUtil.createElement(project, command, SQFFileType.INSTANCE, SQFCommand.class); if (cmd == null) { continue; } result.addElement(LookupElementBuilder.createWithSmartPointer(command, cmd) .withIcon(ArmaPluginIcons.ICON_SQF_COMMAND) .appendTailText(" (Command)", true) ); } } /** * Adds all SQF BIS functions to the result */ public static void addBISFunctions(@NotNull Project project, @NotNull CompletionResultSet result) { for (String functionName : SQFStatic.LIST_BIS_FUNCTIONS) { SQFVariable fnc = PsiUtil.createElement(project, functionName, SQFFileType.INSTANCE, SQFVariable.class); if (fnc == null) { continue; } result.addElement(LookupElementBuilder.createWithSmartPointer(functionName, fnc) .withIcon(ArmaPluginIcons.ICON_SQF_FUNCTION) .appendTailText(" Bohemia Interactive Function", true) ); } } }
mit
Romakita/ts-express-decorators
packages/core/src/domain/Metadata.spec.ts
4498
import {expect} from "chai"; import {Metadata} from "../../src"; function logger(target: any, method?: any, descriptor?: any) { return descriptor; } @logger class Test { @logger attribut: string = ""; // tslint:disable-next-line: no-unused-variable constructor(private type?: string) {} static methodStatic() {} @logger method(type: string): boolean { return true; } } class Test2 { attribut: any; constructor() {} static methodStatic() {} method() {} } describe("Metadata", () => { describe("has", () => { it("should return false (String)", () => { expect(Metadata.has("testunknow", String)).to.equal(false); }); it("should return false (bad target)", () => { expect(Metadata.has("testunknow", undefined)).to.equal(false); }); }); describe("set", () => { it("should set meta on a class", () => { expect(Metadata.set("metadatakey1", "test1", Test)).to.equal(undefined); expect(Metadata.has("metadatakey1", Test)).to.be.true; }); it("should set meta on instance", () => { expect(Metadata.set("metadatakey2", "test2", new Test())).to.equal(undefined); expect(Metadata.has("metadatakey2", Test)).to.be.true; }); it("should set meta on a method", () => { expect(Metadata.set("metadatakey3", "test1", Test, "method")).to.equal(undefined); expect(Metadata.has("metadatakey3", Test, "method")).to.be.true; }); }); describe("get", () => { it("should get meta on a class", () => { expect(Metadata.get("metadatakey1", Test)).to.equal("test1"); }); it("should get meta on a method", () => { expect(Metadata.get("metadatakey3", Test, "method")).to.equal("test1"); }); }); describe("getOwn", () => { it("should get meta on a class", () => { expect(Metadata.getOwn("metadatakey1", Test)).to.equal("test1"); }); it("should get meta on a method", () => { expect(Metadata.getOwn("metadatakey3", Test, "method")).to.equal("test1"); }); }); describe("delete", () => { it("should remove meta on a class", () => { expect(Metadata.delete("metadatakey1", Test)).to.equal(true); }); }); describe("getType", () => { it("should return attribut type", () => { expect(Metadata.getType(Test.prototype, "attribut")).to.equal(String); }); }); describe("getOwnType", () => { it("should return attribut type", () => { expect(Metadata.getOwnType(Test.prototype, "attribut")).to.equal(String); }); }); describe("getParamTypes", () => { it("should return types on constructor", () => { expect(Metadata.getParamTypes(Test)).to.be.an("array"); expect(Metadata.getParamTypes(Test)[0]).to.equal(String); }); it("should return types on method", () => { expect(Metadata.getParamTypes(Test.prototype, "method")).to.be.an("array"); expect(Metadata.getParamTypes(Test.prototype, "method")[0]).to.equal(String); }); }); describe("getOwnParamTypes", () => { it("should return types on constructor", () => { expect(Metadata.getOwnParamTypes(Test)).to.be.an("array"); expect(Metadata.getOwnParamTypes(Test)[0]).to.equal(String); }); it("should return types on method", () => { expect(Metadata.getOwnParamTypes(Test.prototype, "method")).to.be.an("array"); expect(Metadata.getOwnParamTypes(Test.prototype, "method")[0]).to.equal(String); }); }); describe("getReturnType", () => { it("should return types on method", () => { expect(Metadata.getReturnType(Test.prototype, "method")).to.equal(Boolean); }); }); describe("getOwnReturnType", () => { it("should return types on method", () => { expect(Metadata.getOwnReturnType(Test.prototype, "method")).to.equal(Boolean); }); }); describe("list", () => { it("should return unique provide from property key", () => { Metadata.set("controller", "test", Test); Metadata.set("controller", "test2", Test2); Metadata.set("controller", "test", Test); const result = Metadata.getTargetsFromPropertyKey("controller"); expect(result).to.be.an("array"); // expect(result.length).to.equal(2); expect(result.indexOf(Test) > -1).to.be.true; expect(result.indexOf(Test2) > -1).to.be.true; const result2 = Metadata.getTargetsFromPropertyKey("controller2"); expect(result2).to.be.an("array"); expect(result2.length).to.equal(0); }); }); });
mit
ivandean/junos-python
vpn_ipsec/int_tests/vpnaas_func_test.py
4649
''' Unit tests for VPNaaS ''' import unittest,sys from vpnaas import vpnaas from vpnaas.junos.junos_ike import DeadPeerDetection, LocalIdentity class Test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_add_ipsec_proposal(self): print ' ' print '********* ' + sys._getframe().f_code.co_name + ' *********' ipsecProposal = vpnaas.add_ipsec_proposal('test_name_A', 'esp', 'hmac-md5-96', '3des-cbc', '180 seconds') self.assertEqual('test_name_A', ipsecProposal.name, 'Proposal names must be set') self.assertEqual('esp', ipsecProposal.protocol, 'Protocol must be set') self.assertEqual('hmac-md5-96', ipsecProposal.authentication_algorithm, 'Authentication algorithm must be set') self.assertEqual('3des-cbc', ipsecProposal.encryption_algorithm, 'Encryption algorithm must be set') self.assertEqual(180, ipsecProposal.lifetime_seconds, 'Lifetime-seconds must be set') self.assertEqual(-1, ipsecProposal.lifetime_kilobytes, 'Lifetime-kilobytes must not be set') def test_add_ipsec_policy(self): print ' ' print '********* ' + sys._getframe().f_code.co_name + ' *********' iPsecPolicy = vpnaas.add_ipsec_policy('VPN_NEW', 'test_name_A') self.assertEqual('VPN_NEW', iPsecPolicy.name, 'Policy name must be set') self.assertEqual(1, len(iPsecPolicy.proposals), 'Proposal names must have 1 element') self.assertEqual('test_name_A', iPsecPolicy.proposals[0], 'Proposal name must be set') def test_create_ipsec_tunnel(self): print ' ' print '********* ' + sys._getframe().f_code.co_name + ' *********' ipsecProposal = vpnaas.add_ipsec_proposal('test_proposal', 'esp', 'hmac-md5-96', '3des-cbc', '180 seconds') iPsecPolicy = vpnaas.add_ipsec_policy('test_policy', 'test_proposal') iPsecProxyId = vpnaas.add_ipsec_proxy_id('1.1.1.1/24', '2.2.2.2/29', 'any') iPsecIKE = vpnaas.add_ipsec_ike('test-gateway', iPsecProxyId, iPsecPolicy) iPsecVPN = vpnaas.add_ipsec_vpn('test_vpn', 'st0', iPsecIKE, 'immediately') # TODO create an IKE gateway first. won't work now vpnaas.create_ipsec_tunnel(ipsecProposal, iPsecPolicy, iPsecVPN) def test_create_ike(self): print ' ' print '********* ' + sys._getframe().f_code.co_name + ' *********' ikeProposal = vpnaas.add_ike_proposal('test-ike-proposal', 'pre-shared-keys', 'group1', 'sha1', '3des-cbc', 28800) ikePolicy = vpnaas.add_ike_policy('test-ike-policy', 'main', 'test-ike-proposal', '$9$E4GcyebwgaJDev4aZjPfO1REyK8X-') deadPeerDetection = DeadPeerDetection() deadPeerDetection.always_send = True deadPeerDetection.interval = 10 deadPeerDetection.threshold = 2 localIdentity = LocalIdentity() localIdentity.inet = '1.1.1.1' localIdentity.hostname = 'hostname' localIdentity.user_at_hostname = 'user@hostname' localIdentity.distinguished_name = True ikeGateway = vpnaas.add_ike_gateway('test-gateway', 'test-ike-policy', '2.2.2.2', deadPeerDetection, localIdentity, 'st0') vpnaas.create_ike(ikeProposal, ikePolicy, ikeGateway) def test_create_sec_policies(self): print ' ' print '********* ' + sys._getframe().f_code.co_name + ' *********' policy_rule = vpnaas.add_sec_policy_rule('test-policy-rule', 'any', 'any', 'any', 'permit') vpnaas.create_sec_policies('zone-A', 'zone-B', policy_rule) if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.test_add_ipsec_proposal', # 'Test.test_add_ipsec_policy', # 'Test.test_create_ipsec_tunnel'] unittest.main()
mit
elmar-hinz/Cool
Modules/Cool/Interfaces/Service.php
102
<?php namespace Cool; interface Service { static public function canServe($mixedCriteria); } ?>
mit
MacHu-GWU/sqlite4dummy-project
sqlite4dummy/tests/sqlite3_in_python/tricks/test_count_total_row_in_a_table.py
1222
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from sqlite4dummy.tests.basetest import BaseUnittest import unittest import sqlite3 import time import os dbfile = "test.sqlite3" class Unittest(BaseUnittest): """ 结论: 计算总共有多少列最好的方法是使用: SELECT COUNT(*) FROM (SELECT column FROM table) """ def setUp(self): self.connect_database() def test_all(self): connect = self.connect cursor = self.cursor cursor.execute( "CREATE TABLE test (_int INTEGER PRIMARY KEY, _float REAL, _str TEXT)") data = [(i, 3.14, "Hello World") for i in range(1000)] cursor.executemany("INSERT INTO test VALUES (?,?,?)", data) connect.commit() st = time.clock() res = cursor.execute("SELECT COUNT(*) FROM (SELECT * FROM test)").fetchone() print("SELECT * takes %.6f" % (time.clock() - st)) st = time.clock() res = cursor.execute("SELECT COUNT(*) FROM (SELECT _int FROM test)").fetchone() print("SELECT COUNT(*) takes %.6f" % (time.clock() - st)) if __name__ == "__main__": unittest.main()
mit
dpesheva/QuizFactory
QuizFactory/QuizFactory.MVC/Areas/Users/Controllers/HistoryController.cs
3027
namespace QuizFactory.Mvc.Areas.Users.Controllers { using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AutoMapper.QueryableExtensions; using Microsoft.AspNet.Identity; using MvcPaging; using QuizFactory.Data; using QuizFactory.Data.Models; using QuizFactory.Mvc.Areas.Users.ViewModels; using QuizFactory.Mvc.Controllers; using QuizFactory.Mvc.ViewModels.Play; [Authorize] public class HistoryController : BaseController { private const int PageSize = 10; public HistoryController(IQuizFactoryData data) : base(data) { } // GET: Users/History public ActionResult Index(int? page) { var userId = this.User.Identity.GetUserId(); var allTakenQuizzes = this.Db.TakenQuizzes .All() .Where(q => q.UserId == userId) .Project() .To<TakenQuizViewModel>() .ToList(); this.ViewBag.Pages = Math.Ceiling((double)allTakenQuizzes.Count / PageSize); int currentPageIndex = page.HasValue ? page.Value - 1 : 0; return this.View(allTakenQuizzes.ToPagedList(currentPageIndex, PageSize)); } public ActionResult Details(int? id) { var takenQuiz = this.Db.TakenQuizzes .All() .Where(t => t.Id == id) .FirstOrDefault(); var quizDef = this.Db.QuizzesDefinitions .AllWithDeleted() .Where(q => q.Id == takenQuiz.QuizDefinitionId) .Project() .To<QuizPlayViewModel>() .FirstOrDefault(); if (takenQuiz == null || quizDef == null) { throw new HttpException("Quiz not found"); } Dictionary<int, int> selectedAnswersInt = this.CollectAnswers(takenQuiz); this.TempData["results"] = selectedAnswersInt; this.TempData["scorePercentage"] = takenQuiz.Score; var userId = User.Identity.GetUserId(); ViewBag.Voted = this.Db.Votes.All().Where(v => v.QuizDefinitionId == quizDef.Id && v.UserId == userId).Any(); return this.View("DisplayAnswers", quizDef); } private Dictionary<int, int> CollectAnswers(TakenQuiz takenQuiz) { Dictionary<int, int> result = new Dictionary<int, int>(); var userAnswers = takenQuiz.UsersAnswers; foreach (var item in userAnswers) { result.Add(item.AnswerDefinition.QuestionDefinition.Id, item.AnswerDefinitionId); } return result; } } }
mit
Develman/mmi_graphing
src/main/java/de/develman/mmi/ui/util/UIHelper.java
592
package de.develman.mmi.ui.util; import de.develman.mmi.model.Graph; import de.develman.mmi.model.Vertex; import javafx.scene.control.ComboBox; /** * @author Georg Henkel <georg@develman.de> */ public class UIHelper { public static Vertex loadVertex(Graph graph, ComboBox<Integer> vertexCbx, Vertex defaultValue) { Vertex vertex = defaultValue; Integer selectedKey = vertexCbx.getSelectionModel().selectedItemProperty().get(); if (selectedKey != null) { vertex = graph.getVertex(selectedKey); } return vertex; } }
mit
ishenkoyv/ZF2Skeleton
module/Core/Module.php
336
<?php namespace Core; use IyvZF2Generic\ModuleManager\AbstractModule; use Zend\Console\Adapter\AdapterInterface as Console; class Module extends AbstractModule { public function getConsoleUsage(Console $console) { return array( 'app-provisioning' => 'Prepare application for first run', ); } }
mit
Azure/azure-sdk-for-go
services/costmanagement/mgmt/2019-11-01/costmanagement/dimensions.go
11960
package costmanagement // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // DimensionsClient is the client for the Dimensions methods of the Costmanagement service. type DimensionsClient struct { BaseClient } // NewDimensionsClient creates an instance of the DimensionsClient client. func NewDimensionsClient(subscriptionID string) DimensionsClient { return NewDimensionsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewDimensionsClientWithBaseURI creates an instance of the DimensionsClient client using a custom endpoint. Use this // when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewDimensionsClientWithBaseURI(baseURI string, subscriptionID string) DimensionsClient { return DimensionsClient{NewWithBaseURI(baseURI, subscriptionID)} } // ByExternalCloudProviderType lists the dimensions by the external cloud provider type. // Parameters: // externalCloudProviderType - the external cloud provider type associated with dimension/query operations. // This includes 'externalSubscriptions' for linked account and 'externalBillingAccounts' for consolidated // account. // externalCloudProviderID - this can be '{externalSubscriptionId}' for linked account or // '{externalBillingAccountId}' for consolidated account used with dimension/query operations. // filter - may be used to filter dimensions by properties/category, properties/usageStart, // properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. // expand - may be used to expand the properties/data within a dimension category. By default, data is not // included when listing dimensions. // skiptoken - skiptoken is only used if a previous operation returned a partial result. If a previous response // contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that // specifies a starting point to use for subsequent calls. // top - may be used to limit the number of results to the most recent N dimension data. func (client DimensionsClient) ByExternalCloudProviderType(ctx context.Context, externalCloudProviderType ExternalCloudProviderType, externalCloudProviderID string, filter string, expand string, skiptoken string, top *int32) (result DimensionsListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DimensionsClient.ByExternalCloudProviderType") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: top, Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, }}}}}); err != nil { return result, validation.NewError("costmanagement.DimensionsClient", "ByExternalCloudProviderType", err.Error()) } req, err := client.ByExternalCloudProviderTypePreparer(ctx, externalCloudProviderType, externalCloudProviderID, filter, expand, skiptoken, top) if err != nil { err = autorest.NewErrorWithError(err, "costmanagement.DimensionsClient", "ByExternalCloudProviderType", nil, "Failure preparing request") return } resp, err := client.ByExternalCloudProviderTypeSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "costmanagement.DimensionsClient", "ByExternalCloudProviderType", resp, "Failure sending request") return } result, err = client.ByExternalCloudProviderTypeResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "costmanagement.DimensionsClient", "ByExternalCloudProviderType", resp, "Failure responding to request") return } return } // ByExternalCloudProviderTypePreparer prepares the ByExternalCloudProviderType request. func (client DimensionsClient) ByExternalCloudProviderTypePreparer(ctx context.Context, externalCloudProviderType ExternalCloudProviderType, externalCloudProviderID string, filter string, expand string, skiptoken string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "externalCloudProviderId": autorest.Encode("path", externalCloudProviderID), "externalCloudProviderType": autorest.Encode("path", externalCloudProviderType), } const APIVersion = "2019-11-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) } if len(skiptoken) > 0 { queryParameters["$skiptoken"] = autorest.Encode("query", skiptoken) } if top != nil { queryParameters["$top"] = autorest.Encode("query", *top) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/providers/Microsoft.CostManagement/{externalCloudProviderType}/{externalCloudProviderId}/dimensions", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ByExternalCloudProviderTypeSender sends the ByExternalCloudProviderType request. The method will close the // http.Response Body if it receives an error. func (client DimensionsClient) ByExternalCloudProviderTypeSender(req *http.Request) (*http.Response, error) { return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) } // ByExternalCloudProviderTypeResponder handles the response to the ByExternalCloudProviderType request. The method always // closes the http.Response Body. func (client DimensionsClient) ByExternalCloudProviderTypeResponder(resp *http.Response) (result DimensionsListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List lists the dimensions by the defined scope. // Parameters: // scope - the scope associated with dimension operations. This includes '/subscriptions/{subscriptionId}/' for // subscription scope, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup // scope, '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope, // '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for Department // scope, // '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}' // for EnrollmentAccount scope, '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for // Management Group scope, // '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}' for // billingProfile scope, // 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}' // for invoiceSection scope, and // 'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}' specific for // partners. // filter - may be used to filter dimensions by properties/category, properties/usageStart, // properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le', 'ge'. // expand - may be used to expand the properties/data within a dimension category. By default, data is not // included when listing dimensions. // skiptoken - skiptoken is only used if a previous operation returned a partial result. If a previous response // contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that // specifies a starting point to use for subsequent calls. // top - may be used to limit the number of results to the most recent N dimension data. func (client DimensionsClient) List(ctx context.Context, scope string, filter string, expand string, skiptoken string, top *int32) (result DimensionsListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DimensionsClient.List") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: top, Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, }}}}}); err != nil { return result, validation.NewError("costmanagement.DimensionsClient", "List", err.Error()) } req, err := client.ListPreparer(ctx, scope, filter, expand, skiptoken, top) if err != nil { err = autorest.NewErrorWithError(err, "costmanagement.DimensionsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "costmanagement.DimensionsClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "costmanagement.DimensionsClient", "List", resp, "Failure responding to request") return } return } // ListPreparer prepares the List request. func (client DimensionsClient) ListPreparer(ctx context.Context, scope string, filter string, expand string, skiptoken string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "scope": scope, } const APIVersion = "2019-11-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) } if len(skiptoken) > 0 { queryParameters["$skiptoken"] = autorest.Encode("query", skiptoken) } if top != nil { queryParameters["$top"] = autorest.Encode("query", *top) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/{scope}/providers/Microsoft.CostManagement/dimensions", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client DimensionsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client DimensionsClient) ListResponder(resp *http.Response) (result DimensionsListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
mit
mandino/hotelmilosantabarbara.com
wp-content/plugins/wpml-string-translation/inc/package-translation/inc/wpml-package.class.php
13536
<?php class WPML_Package { public $ID; public $view_link; public $edit_link; public $is_translation; public $string_data; public $title; public $new_title; public $kind_slug; public $kind; public $trid; public $name; public $translation_element_type; public $post_id; private $element_type_prefix; /** * @param stdClass|WPML_Package|array|int $data_item */ function __construct( $data_item ) { $this->element_type_prefix = 'package'; $this->view_link = ''; $this->edit_link = ''; $this->post_id = null; if ( $data_item ) { if ( is_object( $data_item ) ) { $data_item = get_object_vars( $data_item ); } if ( is_numeric( $data_item ) ) { $data_item = $this->init_from_id( $data_item, ARRAY_A ); } if ( isset( $data_item[ 'title' ] ) ) { $this->new_title = $data_item[ 'title' ]; } if ( $data_item && is_array( $data_item ) ) { $this->init_from_array( $data_item ); } $this->new_title = $this->new_title != $this->title ? $this->new_title : null; } } private function init_from_id( $id, $output = OBJECT ) { global $wpdb; $packages_query = "SELECT * FROM {$wpdb->prefix}icl_string_packages WHERE id=%s"; $packages_prepared = $wpdb->prepare( $packages_query, $id ); $package = $wpdb->get_row( $packages_prepared, $output ); return $package; } public function __get( $property ) { if ( $property == 'id' ) { _deprecated_argument( 'id', '0.0.2', "Property 'id' is deprecated. Please use 'ID'." ); return $this->ID; } if ( $property == 'post_id' ) { return $this->ID; } if ( $property == 'post_title' ) { return $this->title; } if ( $property == 'post_type' ) { return $this->kind_slug; } return null; } public function __set( $property, $value ) { if ( $property == 'id' ) { _deprecated_argument( 'id', '0.0.2', "Property 'id' is deprecated. Please use 'ID'." ); $this->ID = $value; } else { $this->$property = $value; } } public function __isset( $property ) { if ( $property == 'id' ) { return isset( $this->ID ); } return false; } public function __unset( $property ) { if ( $property == 'id' ) { unset( $this->$property ); } } public function get_translation_element_type() { return $this->translation_element_type; } public function get_package_post_id() { return $this->get_element_type_prefix() . '_' . $this->kind_slug . '_' . $this->ID; } public function get_element_type_prefix() { return $this->element_type_prefix; } public function set_package_post_data() { $this->translation_element_type = $this->element_type_prefix . '_' . $this->kind_slug; $this->update_strings_data(); } /** * @return array */ public function update_strings_data() { $strings = array(); $package_id = $this->ID; if ( $package_id ) { $results = $this->get_package_strings(); foreach ( $results as $result ) { $string_name = $this->get_package_string_name_from_st_name( $result ); $strings[ $string_name ] = $result->value; } // Add/update any registered strings if ( isset( $package_strings[ $package_id ][ 'strings' ] ) ) { foreach ( $package_strings[ $package_id ][ 'strings' ] as $id => $string_data ) { $strings[ $id ] = $string_data[ 'value' ]; } } $this->string_data = $strings; } } /** * @return mixed */ public function get_package_strings() { global $wpdb; $package_id = $this->ID; $results = false; if ( $package_id ) { $cache = new WPML_WP_Cache( 'WPML_Package' ); $cache_key = 'strings:' . $package_id; $found = false; $results = $cache->get( $cache_key, $found ); if ( ! $found ) { $results_query = "SELECT id, name, value, type FROM {$wpdb->prefix}icl_strings WHERE string_package_id=%d"; $results_prepare = $wpdb->prepare( $results_query, $package_id ); $results = $wpdb->get_results( $results_prepare ); $cache->set( $cache_key, $results ); } } return $results; } public function set_strings_language( $language_code ) { global $wpdb; $package_id = $this->ID; if ( $package_id ) { $update_query = "UPDATE {$wpdb->prefix}icl_strings SET language=%s WHERE string_package_id=%d"; $update_prepare = $wpdb->prepare( $update_query, $language_code, $package_id ); $wpdb->query( $update_prepare ); } } /** * @param $result * * @return string */ private function get_package_string_name_from_st_name( $result ) { // package string name is the same as the string name. return $result->name; } private function sanitize_attributes() { if ( isset( $this->name ) ) { $this->name = $this->sanitize_string_name( $this->name ); } if ( (! isset( $this->title ) || $this->title === '') && isset($this->name) ) { $this->title = $this->name; } if ( ! isset( $this->edit_link ) ) { $this->edit_link = ''; } $this->sanitize_kind(); } public function create_new_package_record() { $this->sanitize_attributes(); $package_id = $this->package_exists(); if ( ! $package_id ) { global $wpdb; $data = array( 'kind_slug' => $this->kind_slug, 'kind' => $this->kind, 'name' => $this->name, 'title' => $this->title, 'edit_link' => $this->edit_link, 'view_link' => $this->view_link, 'post_id' => $this->post_id, ); $wpdb->insert( $wpdb->prefix . 'icl_string_packages', $data ); $package_id = $wpdb->insert_id; $this->ID = $package_id; } return $package_id; } public function update_package_record() { $result = false; if ( $this->ID ) { global $wpdb; $update_data = array( 'kind_slug' => $this->kind_slug, 'kind' => $this->kind, 'name' => $this->name, 'title' => $this->title, 'edit_link' => $this->edit_link, 'view_link' => $this->view_link, ); $update_where = array( 'ID' => $this->ID ); $result = $wpdb->update( $wpdb->prefix . 'icl_string_packages', $update_data, $update_where ); } return $result; } public function get_package_id() { return $this->ID; } public function sanitize_string_name( $string_name ) { $string_name = preg_replace( '/[ \[\]]+/', '-', $string_name ); return $string_name; } function translate_string( $string_value, $sanitized_string_name ) { $package_id = $this->get_package_id(); if ( $package_id ) { $sanitized_string_name = $this->sanitize_string_name( $sanitized_string_name ); $string_context = $this->get_string_context_from_package(); $string_name = $sanitized_string_name; return icl_translate( $string_context, $string_name, $string_value ); } else { return $string_value; } } function get_string_context_from_package() { return $this->kind_slug . '-' . $this->name; } public function get_string_id_from_package( $string_name, $string_value ) { $package_id = $this->get_package_id(); $string_context = $this->get_string_context_from_package(); $string_data = array( 'context' => $string_context, 'name' => $string_name, ); /** * @param int|null $default * @param array $string_data { * * @type string $context * @type string $name Optional * } */ $string_id = apply_filters('wpml_string_id', null, $string_data); if ( ! $string_id ) { $string_id = icl_register_string( $string_context, $string_name, $string_value, null, $this->get_package_language() ); } return $string_id; } function get_translated_strings( $strings ) { $package_id = $this->get_package_id(); if ( $package_id ) { $results = $this->get_package_strings(); foreach ( $results as $result ) { $translations = icl_get_string_translations_by_id( $result->id ); if ( ! empty ( $translations ) ) { $string_name = $this->get_package_string_name_from_st_name( $result ); $strings[ $string_name ] = $translations; } } } return $strings; } function set_translated_strings( $translations ) { global $wpdb; $this->sanitize_attributes(); $package_id = $this->get_package_id(); if ( $package_id ) { foreach ( $translations as $string_name => $languages ) { $string_id_query = "SELECT id FROM {$wpdb->prefix}icl_strings WHERE name='%s'"; $string_id_prepare = $wpdb->prepare( $string_id_query, $string_name ); $string_id = $wpdb->get_var( $string_id_prepare ); foreach ( $languages as $language_code => $language_data ) { icl_add_string_translation( $string_id, $language_code, $language_data[ 'value' ], $language_data[ 'status' ] ); } } } } private function init_from_array( $args ) { foreach ( $args as $key => $value ) { if ( 'id' == $key ) { $key = 'ID'; } $this->$key = $value; } $this->sanitize_attributes(); if ( $this->package_id_exists() || $this->package_name_and_kind_exists() ) { $this->set_package_from_db(); } $this->set_package_post_data(); } public function has_kind_and_name() { return ( isset( $this->kind ) && isset( $this->name ) && $this->kind && $this->name ); } private function set_package_from_db() { $package = false; if ( $this->package_id_exists() ) { $package = $this->get_package_from_id( $this->ID ); } elseif ( $this->package_name_and_kind_exists() ) { $package = $this->get_package_from_name_and_kind(); } if ( $package ) { $this->object_to_package( $package ); } $this->sanitize_kind(); } private function get_package_from_id() { $result = false; if ( $this->has_id() ) { global $wpdb; $package_query = "SELECT * FROM {$wpdb->prefix}icl_string_packages WHERE ID=%d"; $package_prepared = $wpdb->prepare( $package_query, array( $this->ID ) ); $result = $wpdb->get_row( $package_prepared ); } return $result; } private function get_package_from_name_and_kind() { global $wpdb; $cache = new WPML_WP_Cache( 'WPML_Package' ); $cache_key = 'name-kind:' . $this->kind_slug . $this->name; $found = false; $result = $cache->get( $cache_key, $found ); if ( ! $found ) { $package_query = "SELECT * FROM {$wpdb->prefix}icl_string_packages WHERE kind_slug=%s AND name=%s"; $package_prepared = $wpdb->prepare( $package_query, array( $this->kind_slug, $this->name ) ); $result = $wpdb->get_row( $package_prepared ); if ( $result ) { $cache->set( $cache_key, $result ); } } return $result; } private function package_name_and_kind_exists() { $result = false; if ( $this->has_kind_and_name() ) { $result = (bool) $this->get_package_from_name_and_kind(); } return $result; } private function package_id_exists() { $result = false; if ( $this->has_id() ) { global $wpdb; $package_query = "SELECT ID FROM {$wpdb->prefix}icl_string_packages WHERE ID=%d"; $package_prepared = $wpdb->prepare( $package_query, array( $this->ID ) ); $result = $wpdb->get_var( $package_prepared ); } return $result; } /** * @return bool|mixed */ protected function package_exists() { $existing_package = false; if ( $this->has_id() ) { $existing_package = $this->package_id_exists(); } elseif ( $this->has_kind_and_name() ) { $existing_package = $this->package_name_and_kind_exists(); } return $existing_package; } /** * @return bool */ private function has_id() { return isset( $this->ID ) && $this->ID; } /** * @param $package */ private function object_to_package( $package ) { $this->ID = $package->ID; $this->kind_slug = $package->kind_slug; $this->kind = $package->kind; $this->name = $package->name; $this->title = $package->title; $this->edit_link = $package->edit_link; $this->view_link = $package->view_link; } private function get_kind_from_slug() { global $wpdb; $kinds_query = "SELECT kind FROM {$wpdb->prefix}icl_string_packages WHERE kind_slug=%s GROUP BY kind"; $kinds_prepared = $wpdb->prepare( $kinds_query, $this->kind_slug ); $kinds = $wpdb->get_col( $kinds_prepared ); if ( count( $kinds ) > 1 ) { throw new WPML_Package_Exception( 'error', 'Package contains multiple kinds' ); } if ( $kinds ) { return $kinds[ 0 ]; } return null; } private function sanitize_kind() { if ( isset( $this->kind ) && ( ! isset( $this->kind_slug ) || trim( $this->kind_slug ) === '' ) ) { $this->kind_slug = sanitize_title_with_dashes( $this->kind ); } if ( $this->kind == $this->kind_slug ) { $this->kind = $this->get_kind_from_slug(); } } public function get_package_element_type() { return 'package_' . $this->kind_slug; } public function get_package_language() { global $sitepress; if ( $this->post_id ) { $post = get_post( $this->post_id ); $details = $sitepress->get_element_language_details( $this->post_id, 'post_' . $post->post_type ); } else { $element_type = $this->get_package_element_type(); $details = $sitepress->get_element_language_details( $this->ID, $element_type ); } if ( $details ) { return $details->language_code; } else { return null; } } public function are_all_strings_included( $strings ) { // check to see if all the strings in this package are present in $strings $package_strings = $this->get_package_strings(); if ( is_array( $package_strings ) ) { foreach( $package_strings as $string ) { if ( ! in_array( $string->id, $strings ) ) { return false; } } } return true; } }
mit
itowtips/shirasagi
app/controllers/opendata/agents/nodes/dataset/dataset_map_controller.rb
1492
class Opendata::Agents::Nodes::Dataset::DatasetMapController < ApplicationController include Cms::NodeFilter::View include Opendata::UrlHelper private def set_map_points @map_points = {} @datasets = [] @items.each do |item| resources = [] item.resources.each_with_index do |resource, idx| resource.map_resources.each do |map_resource| key = "#{item.id}_#{idx}_#{map_resource["sheet"]}" name = resource.tsv_present? ? resource.name : "#{resource.name} [#{map_resource["sheet"]}]" @map_points[item.id] ||= {} @map_points[item.id][key] = map_resource["map_points"] resources << { resource: resource, key: "#{item.id}_#{idx}_#{map_resource["sheet"]}", name: name } end end @datasets << [item, resources] end end public def index view_context.include_map_api(site: @cur_site, api: "openlayers") end def search @model = Opendata::Dataset @dataset_node = Opendata::Node::Dataset.where(id: @cur_node.parent.id).first if @dataset_node @items = @model.site(@cur_site).node(@dataset_node) else @items = @model.site(@cur_site) end @items = @items.and_public.elem_match(resources: { :map_resources.nin => [[], nil] }).search(params[:s]). order_by(updated: -1).page(params[:page]).per(10) set_map_points @cur_node.layout_id = nil render layout: 'cms/ajax' end end
mit
kulibali/periapsis
GSGL/src/data/data.hpp
3271
#ifndef GSGL_DATA_DATA_H #define GSGL_DATA_DATA_H // // $Id$ // // Copyright (c) 2008, The Periapsis Project. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the The Periapsis Project nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER // OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #ifdef WIN32 #pragma warning (disable:4251) #pragma warning (disable:4996) #ifdef GSGL_DATA_EXPORTS #define DATA_API __declspec(dllexport) #else #define DATA_API __declspec(dllimport) #endif #else #define DATA_API #endif namespace gsgl { namespace io { class text_stream; } /// The type used as indices into data collections. typedef int index_t; /// Used for storing flag bits. typedef unsigned int flags_t; /// Set one or more flags. inline void set_flags(flags_t & flags, const flags_t & flags_to_set) { flags |= flags_to_set; } /// Unset one or more flags. inline void unset_flags(flags_t & flags, const flags_t & flags_to_unset) { flags &= ~flags_to_unset; } /// Check if a flag is set. inline bool flag_is_set(const flags_t & flags, const flags_t & flags_to_test) { return (flags & flags_to_test) != 0; } /// Base class for data data object types. class DATA_API data_object { public: data_object() {} virtual ~data_object() {} }; // data_object() // utility functions template <typename T> const T & min_val(const T & a, const T & b) { return a < b ? a : b; } // min_val() template <typename T> const T & max_val(const T & a, const T & b) { return a < b ? b : a; } // max_val() DATA_API wchar_t *gsgl_wcsdup(const wchar_t *); } // namespace gsgl #endif
mit
onybo/confcal
app/components/flags/Norway.tsx
557
// Based on https://github.com/lipis/flag-icon-css/tree/master/flags/4x3/no.svg // Copyright (c) 2013 Panayiotis Lipiridis import * as React from 'react'; import SvgIcon from 'material-ui/lib/svg-icon'; const Norway = (props) => ( <SvgIcon viewBox="0 0 640 480" {...props}> <path fill="#ef2b2d" d="M0 0h640v480H0z"/> <path fill="#fff" d="M180 0h120v480H180z"/> <path fill="#fff" d="M0 180h640v120H0z"/> <path fill="#002868" d="M210 0h60v480h-60z"/> <path fill="#002868" d="M0 210h640v60H0z"/> </SvgIcon> ) export default Norway;
mit
samwong1990/RoomServiceCommons
RoomServiceCommons/src/hk/samwong/roomservice/commons/parameterEnums/ReturnCode.java
163
package hk.samwong.roomservice.commons.parameterEnums; public enum ReturnCode { NO_RESPONSE, UNRECOVERABLE_EXCEPTION, OK, ILLEGAL_ARGUMENT, NO_SUCH_ALGORITHM; }
mit
aliarham11/volumemonitoringapp
application/models/Monitoringmodel.php
1541
<?php class Monitoringmodel extends CI_Model { public function __construct() { $this->load->database(); } public function getVehicleData() { $sql = "select * from ( SELECT `track_record`.`vehicle_id`, `vehicle_name`, `tank_type`,`driver_contact`, `diameter`, `longsize`, `latitude`, `longitude`, `liquid_level`, `timestamp` FROM `track_record` JOIN `vehicle_master` ON `vehicle_master`.`vehicle_id`=`track_record`.`vehicle_id` JOIn `initial_data` ON `initial_data`.`vehicle_id`=`track_record`.`vehicle_id` Where `is_arrive` = 0 AND `is_going` = 1 ORDER BY `track_record`.`id` DESC ) temp, `initial_data` group by temp.`vehicle_id`"; $query = $this->db->query($sql); return $query->result_array(); } public function getInitialData($id) { $this->db->select('initial_volume'); $query = $this->db->get_where('initial_data',$id,1); return $query->result_array(); } public function getHistory($vid) { $this->db->select('vehicle_name, latitude,longitude,liquid_level,timestamp,diameter,longsize,tank_type,vehicle_master.vehicle_id'); $this->db->from('track_record'); $this->db->join('vehicle_master','track_record.vehicle_id = vehicle_master.vehicle_id'); $this->db->where($vid); $query = $this->db->get(); return $query->result_array(); # code... } }
mit
Iliev88/QA-Automation
DesignPattern/Pages/ResizablePage/ResizablePage.cs
1216
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; namespace DesignPattern.Pages.ResizablePage { public partial class ResizablePage : BasePage { public ResizablePage(IWebDriver driver) : base(driver) { } public int Width { get; set; } public int Height { get; set; } public string URL { get { return url + "resizable/"; } } public void NavigateTo() { this.Driver.Navigate().GoToUrl(this.URL); } public void IncreaseWidthAndHeightBy(int increaseWidth, int increaseHeight) { var builder = new Actions(this.Driver); var resize = builder.DragAndDropToOffset(resizeButton, increaseWidth, increaseHeight); resize.Perform(); } public void ResizeWindowWithoutDropping() { var builder = new Actions(this.Driver); var drag = builder.ClickAndHold(resizeButton).MoveByOffset(10, 10); drag.Perform(); } } }
mit
CoolProp/GUI
cpgui_cycle2.py
25806
# -*- coding: utf-8 -*- # import sys import gettext from tkinter import * from tkinter import ttk import CoolProp from CoolProp.CoolProp import PropsSI from cpgui_all import * import numpy as np from math import exp from PIL import ImageTk, Image from scipy.optimize import bisect class cpg_cycle2(myDialog): def __init__(self, GridFrame,Caller,Debug=False): # self.initcomplete=False # self.Caller=Caller # # by module translations self.language=cpgui_language localedir=find_data_file('locale') self.lang = gettext.translation('cpg_cycle2', localedir=localedir, languages=[self.language]) self.lang.install() # self.euler=exp(1) # self.Debug=Debug # self.VarVal ={'t0':273.15,'dt0h':10,'dp0':10000,'Q0':1000,'tc':273.15+45,'dtu':5,'dpc':10000,'sl_dth':10,'sl_dp':10000,'dl_dtu':18,'dl_dp':10000,'comp_eta':0.6,'hx_kxa':23,'hx_dp':0} self.InputPanels ={'Evaporator':{'Title':_('Evaporator'), 'row':1, # row of Evaporator Frame in InputFrame 'col':1, # coloumn of Evaporator Frame in InputFrame 'order':['t0','dt0h','dp0','Q0'], # Input fields order of appearance 't0':[_('Temperature'),self.VarVal['t0'],GUI_UNIT('T'),'T'], # Input fields, Label, Variable to change, Unit Label / this List will be extended by a tkinter StringVar for callback on change 'dt0h':[_('Superheat'),self.VarVal['dt0h'],GUI_UNIT('dT'),'dT'], 'dp0':[_('Pressure drop'),self.VarVal['dp0'],GUI_UNIT('p'),'p'], 'Q0':[_('Capacity'),self.VarVal['Q0'],GUI_UNIT('P'),'P'], }, 'Condenser':{'Title':_('Condenser'), 'row':1, 'col':2, 'order':['tc','dtu','dpc','empty'], 'tc':[_('Temperature'),self.VarVal['tc'],GUI_UNIT('T'),'T'], 'dtu':[_('Subcooling'),self.VarVal['dtu'],GUI_UNIT('dT'),'dT'], 'dpc':[_('Pressure drop'),self.VarVal['dpc'],GUI_UNIT('p'),'p'], 'empty':[' '], }, 'Pipes':{'Title':_('Suction line SL / Discharge line DL'), 'row':1, 'col':3, 'order':['sl_dth','sl_dp','dl_dtu','dl_dp'], 'sl_dth':[_('SL superheat'),self.VarVal['sl_dth'],GUI_UNIT('dT'),'dT'], 'sl_dp':[_('SL Pressure drop'),self.VarVal['sl_dp'],GUI_UNIT('p'),'p'], 'dl_dtu':[_('DL Temperature loss'),self.VarVal['dl_dtu'],GUI_UNIT('dT'),'dT'], 'dl_dp':[_('DL Pressure drop'),self.VarVal['dl_dp'],GUI_UNIT('p'),'p'], }, 'Compressor':{'Title':_('Compressor'), 'row':2, 'col':1, 'order':['comp_eta'], 'comp_eta':[_('Isentropic efficiency'),self.VarVal['comp_eta'],GUI_UNIT('eta'),'eta'], }, 'InternalHX':{'Title':_('Internal heat exchanger'), 'row':2, 'col':2, 'order':['hx_kxa','hx_dp'], 'hx_kxa':[_('K x A Value'),self.VarVal['hx_kxa'],GUI_UNIT('kxa'),'kxa'], 'hx_dp':[_('Gas pressure drop'),self.VarVal['hx_dp'],GUI_UNIT('p'),'p'],} } # self.dialogframe=GridFrame # self.Caller=Caller self.ref=Caller.get_ref() # self.frameborder=5 # self.statetext=' ' # self.InfoDict={'1' :('1', _('End of SL / compressor intake')), '2s' :('2s', _('Isentropic compression')), '2' :('2', _('Real compression')), '3' :('3', _('Condenser inlet')), '3dew' :('3\'\'', _('Dewpoint inside condenser')), '3dewm4bub' :('3\'\'m4\'', _('Average between 3\'\' and 4\'')), '4bub' :('4\'', _('Bubblepoint inside condenser')), '4' :('4', _('Exit condenser')), '5' :('5', _('Exit Heat exchanger')), '6' :('6', _('Evaporator entry')), '6m7dew' :('6m7\'\'', _('Average between 6 and 7\'\'')), '7dew' :('7\'\'', _('Dewpoint inside evaporator')), '7' :('7', _('Exit evaporator / Intake heat exchanger')), '8' :('8', _('Exit Heat exchanger')), 'order' :('1','2s','2','3','3dew','3dewm4bub','4bub','4','5','6','6m7dew','7dew','7','8'), } # Frames for input and output self.InputFrame= LabelFrame(self.dialogframe,relief=GROOVE,bd=self.frameborder,text=_('Cycle inputs'),font=("Arial", 10, "bold")) self.InputFrame.grid(row=1,column=1,padx=8,pady=5,sticky=W) self.OutputFrame= LabelFrame(self.dialogframe,relief=GROOVE,bd=self.frameborder,text=_('Cycle outputs'),font=("Arial", 10,"bold")) self.OutputFrame.grid(row=3,column=1,padx=8,pady=5,sticky=EW,rowspan=10,columnspan=3) # # Inputs # for key in self.InputPanels : self.GridInputPanel(self.InputFrame,key,Debug=False) # self.Button_1 = Button(self.InputFrame,text=_(' Calculate '),font=("Arial", 12, "bold") ) self.Button_1.grid(row=2,rowspan=1,column=3,pady=5,sticky=W,padx=8) self.Button_1.bind("<ButtonRelease-1>", self.calculate) # # Output # self.out_nb = ttk.Notebook(self.OutputFrame) self.out_nb.pack(fill = 'both', expand = 1, padx = 5, pady = 5) # self.tab1_frame = ttk.Frame(self.OutputFrame) self.tab2_frame = ttk.Frame(self.OutputFrame) self.tab3_frame = ttk.Frame(self.OutputFrame) # tab 1 cycle display and selection self.out_nb.add(self.tab1_frame,text=_('Cycle information')) # self.InfoFrame= LabelFrame(self.tab1_frame,relief=GROOVE,bd=self.frameborder,text=_('Statepoints'),font=("Arial", 10, "bold")) self.InfoFrame.grid(row=1,column=1,padx=8,pady=5,sticky=W) inforow=1 for point in self.InfoDict['order']: pl=Label(self.InfoFrame,text='{:<10}'.format(self.InfoDict[point][0]),font=("Arial", 10) ) pl.grid(row=inforow,rowspan=1,column=1,pady=2,sticky=W,padx=2) tl=Label(self.InfoFrame,text='{:<35}'.format(self.InfoDict[point][1]),font=("Arial", 10) ) tl.grid(row=inforow,rowspan=1,column=2,pady=2,sticky=W,padx=2) inforow+=1 self.cycle1png=find_data_file('cycle2.png') imgfile = Image.open(self.cycle1png) render = ImageTk.PhotoImage(imgfile) img = Label(self.tab1_frame, image=render) img.image = render img.grid(row=1,column=2,pady=5,sticky=NS,padx=8) # self.out_nb.add(self.tab2_frame,text=_('Output table')) # self.statetext=' ' lbframe1 = Frame( self.tab2_frame ) self.Text_1_frame = lbframe1 scrollbar1 = Scrollbar(lbframe1, orient=VERTICAL) self.Text_1 = Text(lbframe1, width="110", height="25", yscrollcommand=scrollbar1.set) scrollbar1.config(command=self.Text_1.yview) scrollbar1.pack(side=RIGHT, fill=Y) self.Text_1.pack(side=LEFT, fill=BOTH, expand=1) self.Text_1_frame.grid(row=1,column=1,columnspan=1,padx=2,sticky=W+E,pady=4) self.Text_1.delete(1.0, END) # self.out_nb.bind_all("<<NotebookTabChanged>>", self.tabChangedEvent) self.initcomplete=True def GridInputPanel(self,GridFrame,PanelKey,Debug=False,tfont=("Arial", 10, "bold"),font=("Arial", 10)): # LineList=self.InputPanels[PanelKey]['order'] GIPanel=LabelFrame(GridFrame,relief=GROOVE,bd=5,text=self.InputPanels[PanelKey]['Title']) GIPanel.grid(row=self.InputPanels[PanelKey]['row'],column=self.InputPanels[PanelKey]['col'],padx=8,pady=5,sticky=W) # i=1 for k in self.InputPanels[PanelKey]['order'] : if self.InputPanels[PanelKey][k][0] != ' ' : self.InputPanels[PanelKey][k].append(StringVar()) outval=SI_TO(self.InputPanels[PanelKey][k][-2], self.InputPanels[PanelKey][k][1]) #print('cycle 2 : GridInputPanel : SI_TO : ',outval) #self.InputPanels[PanelKey][k][-1].set('%f'%self.InputPanels[PanelKey][k][1]) self.InputPanels[PanelKey][k][-1].set(outval) self.InputPanels[PanelKey][k][-1].trace("w", lambda name, index, mode, var=self.InputPanels[PanelKey][k][-1],quantity=self.InputPanels[PanelKey][k][-2], key=k: self.GridInputPanelUpdate(var, key, quantity)) Label(GIPanel, text=self.InputPanels[PanelKey][k][0],font=font).grid(column=1, row=i,padx=8,pady=5,sticky=W) Entry(GIPanel, width=15, textvariable=self.InputPanels[PanelKey][k][-1],font=font).grid(column=2, row=i,padx=8,pady=5,sticky=W) Label(GIPanel, text=self.InputPanels[PanelKey][k][2],font=font).grid(column=3, row=i,padx=8,pady=5,sticky=W) else : Label(GIPanel, text=' ',font=font).grid(column=1, row=i,padx=8,pady=5,sticky=W) # i+=1 # def GridInputPanelUpdate(self, sv,key,quantity): #print(sv, key, sv.get(),quantity) #self.VarVal[key]=sv.get() try : self.VarVal[key]=TO_SI(quantity,float(sv.get().replace(',','.'))) except ValueError : pass #print( key,self.VarVal[key]) def tabChangedEvent(self,event): self.ref=self.Caller.get_ref() def calculate(self,event): # self.ref=self.Caller.get_ref() # self.t0=self.VarVal['t0'] # Evaporation temperature in °C self.dt0h=self.VarVal['dt0h'] # Superheat in K self.dp0=self.VarVal['dp0'] # pressure drop evaporator in bar self.Q0=self.VarVal['Q0'] # refrigeration capacity in kW # self.tc=self.VarVal['tc'] # condensation temperature in °C self.dtu=self.VarVal['dtu'] # subcooling in K self.dpc=self.VarVal['dpc'] # pressure drop condenser in bar # self.sl_dth=self.VarVal['sl_dth'] # superheat suction line in K self.sl_dp=self.VarVal['sl_dp'] # pressure drop suction line in bar self.dl_dtu=self.VarVal['dl_dtu'] # subcooling discharge line in K self.dl_dp=self.VarVal['dl_dp'] # pressure drop discharge line in bar # self.comp_eta=self.VarVal['comp_eta'] # Compressor isentropic efficiency self.hx_kxa=self.VarVal['hx_kxa'] self.hx_dp=self.VarVal['hx_dp'] # self.Qhx=0.0 self.e_hoch_x=0.0 # self.statetext=_('Simple DX cycle statepoint Table for %s\n\n')%self.ref self.statetext+=_(' Point | t | p | v | h | s | x | Description \n') self.datarow= " %6s | %6.2f | %6.2f | %10.5f | %7.2f | %7.4f | %7s | %s \n" self.statetext+=" | {} | {} | {} | {} | {} | {} | \n".format(GUI_UNIT('T'),GUI_UNIT('p'),GUI_UNIT('v'),GUI_UNIT('H'),GUI_UNIT('S'),GUI_UNIT('Q'),) self.statetext+= "-------------------------------------------------------------------------------------------------\n" # self.row={} # dt_gas_out_old=self.iter_run() dt_gas_out=self.iter_run(InitialRun=False) diff=abs(dt_gas_out_old-dt_gas_out) # If gas t out changes by less than a millikelvin we are done while diff > 0.001 : dt_gas_out_old=dt_gas_out dt_gas_out=self.iter_run(InitialRun=False) diff=abs(dt_gas_out_old-dt_gas_out) # self.last_run() def iter_run(self,InitialRun=True): # name='7dew' self.p7dew=PropsSI('P','T',self.t0,'Q',1,self.ref) self.t7dew=self.t0 self.v7dew=1/PropsSI('D','T',self.t0,'Q',1,self.ref) self.h7dew=PropsSI('H','T',self.t0,'Q',1,self.ref) self.s7dew=PropsSI('S','T',self.t0,'Q',1,self.ref) self.x7dew=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t7dew),SI_TO('p',self.p7dew),self.v7dew,SI_TO('H',self.h7dew),SI_TO('S',self.s7dew),self.x7dew,self.InfoDict[name][1]) #print(self.InfoDict[name][0],SI_TO('T',self.t7dew),SI_TO('p',self.p7dew),self.v7dew,SI_TO('H',self.h7dew),SI_TO('S',self.s7dew),self.x7dew,self.InfoDict[name][1]) # # superheat on evaporator exit name='7' self.p7=self.p7dew self.t7=self.t0+self.dt0h self.v7=1/PropsSI('D','T',self.t7,'P',self.p7,self.ref) self.h7=PropsSI('H','T',self.t7,'P',self.p7,self.ref) self.s7=PropsSI('S','T',self.t7,'P',self.p7,self.ref) self.x7=' ' self.cp7=PropsSI('C','P',self.p7,'T',self.t7,self.ref) self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t7),SI_TO('p',self.p7),self.v7,SI_TO('H',self.h7),SI_TO('S',self.s7),self.x7,self.InfoDict[name][1]) # # we ignore the hx for now name='8' if InitialRun : self.p8=self.p7 self.t8=self.t7 self.v8=self.v7 self.h8=self.h7 self.s8=self.s7 else : self.p8=self.p7-self.hx_dp self.t8=self.t7+self.dt_gas_out self.v8=1/PropsSI('D','T',self.t8,'P',self.p8,self.ref) self.h8=PropsSI('H','T',self.t8,'P',self.p8,self.ref) self.s8=PropsSI('S','T',self.t8,'P',self.p8,self.ref) self.x8=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t8),SI_TO('p',self.p8),self.v8,SI_TO('H',self.h8),SI_TO('S',self.s8),self.x8,self.InfoDict[name][1]) self.cp8=PropsSI('C','P',self.p8,'T',self.t8,self.ref) # # + superheat and pressure drop suction line name='1' self.p1=self.p8-self.sl_dp self.t1=self.t8+self.sl_dth self.v1=1/PropsSI('D','T',self.t1,'P',self.p1,self.ref) self.h1=PropsSI('H','T',self.t1,'P',self.p1,self.ref) self.s1=PropsSI('S','T',self.t1,'P',self.p1,self.ref) self.x1=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t1),SI_TO('p',self.p1),self.v1,SI_TO('H',self.h1),SI_TO('S',self.s1),self.x1,self.InfoDict[name][1]) # # isentropic compression name='2s' self.p2s=PropsSI('P','T',self.tc,'Q',1,self.ref)+self.dl_dp self.s2s=self.s1 try : self.t2s=PropsSI('T','P',self.p2s,'S',self.s2s,self.ref) except ValueError : self.t2s=bisect(lambda T: PropsSI('S','T',T,'P',self.p2s,self.ref)-self.s2s,self.t1,493,xtol=0.01) print('t2s : ',self.t2s) self.v2s=1/PropsSI('D','T',self.t2s,'P',self.p2s,self.ref) self.h2s=PropsSI('H','T',self.t2s,'P',self.p2s,self.ref) self.x2s=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t2s),SI_TO('p',self.p2s),self.v2s,SI_TO('H',self.h2s),SI_TO('S',self.s2s),self.x2s,self.InfoDict[name][1]) # # real compression name='2' self.p2=self.p2s self.h2=self.h1+(self.h2s-self.h1)/self.comp_eta try : self.t2=PropsSI('T','P',self.p2,'H',self.h2,self.ref) except ValueError : self.t2=bisect(lambda T: PropsSI('H','T',T,'P',self.p2,self.ref)-self.h2,self.t2s,493,xtol=0.01) print('t2 : ',self.t2) self.v2=1/PropsSI('D','T',self.t2,'P',self.p2,self.ref) self.s2=PropsSI('S','T',self.t2,'P',self.p2,self.ref) self.x2=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t2),SI_TO('p',self.p2),self.v2,SI_TO('H',self.h2),SI_TO('S',self.s2),self.x2,self.InfoDict[name][1]) # # condenser entry name='3' self.p3=self.p2-self.dl_dp self.t3=self.t2-self.dl_dtu self.h3=PropsSI('H','P',self.p3,'T',self.t3,self.ref) self.v3=1/PropsSI('D','T',self.t3,'P',self.p3,self.ref) self.s3=PropsSI('S','T',self.t3,'P',self.p3,self.ref) self.x3=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t3),SI_TO('p',self.p3),self.v3,SI_TO('H',self.h3),SI_TO('S',self.s3),self.x3,self.InfoDict[name][1]) # # inside condenser dewpoint name='3dew' self.t3dew=self.tc self.p3dew=PropsSI('P','T',self.t3dew,'Q',1,self.ref) self.h3dew=PropsSI('H','P',self.p3dew,'Q',1,self.ref) self.v3dew=1/PropsSI('D','P',self.p3dew,'Q',1,self.ref) self.s3dew=PropsSI('S','P',self.p3dew,'Q',1,self.ref) self.x3dew=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t3dew),SI_TO('p',self.p3dew),self.v3dew,SI_TO('H',self.h3dew),SI_TO('S',self.s3dew),self.x3dew,self.InfoDict[name][1]) # # inside condenser bubblepoint name='4bub' self.p4bub=self.p3dew-self.dpc self.t4bub=PropsSI('T','P',self.p4bub,'Q',0,self.ref) self.h4bub=PropsSI('H','P',self.p4bub,'Q',0,self.ref) self.v4bub=1/PropsSI('D','P',self.p4bub,'Q',0,self.ref) self.s4bub=PropsSI('S','P',self.p4bub,'Q',0,self.ref) self.x4bub=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t4bub),SI_TO('p',self.p4bub),self.v4bub,SI_TO('H',self.h4bub),SI_TO('S',self.s4bub),self.x4bub,self.InfoDict[name][1]) # # condenser exit name='4' self.p4=self.p4bub self.t4=self.t4bub-self.dtu self.h4=PropsSI('H','P',self.p4,'T',self.t4,self.ref) self.v4=1/PropsSI('D','P',self.p4,'T',self.t4,self.ref) self.s4=PropsSI('S','P',self.p4,'T',self.t4,self.ref) self.x4=' ' self.cp4=PropsSI('C','P',self.p4,'T',self.t4,self.ref) self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t4),SI_TO('p',self.p4),self.v4,SI_TO('H',self.h4),SI_TO('S',self.s4),self.x4,self.InfoDict[name][1]) # # Exit hx name='5' self.p5=self.p4 if InitialRun : self.t5=self.t4 self.h5=self.h4 self.v5=self.v4 self.s5=self.s4 else : self.t5=self.t4-self.dt_liq_out self.h5=PropsSI('H','P',self.p5,'T',self.t5,self.ref) self.v5=1/PropsSI('D','P',self.p5,'T',self.t5,self.ref) self.s5=PropsSI('S','P',self.p5,'T',self.t5,self.ref) self.x5=' ' self.cp5=PropsSI('C','P',self.p5,'T',self.t5,self.ref) self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t5),SI_TO('p',self.p5),self.v5,SI_TO('H',self.h5),SI_TO('S',self.s5),self.x5,self.InfoDict[name][1]) # # evaporator entry name='6' self.p6=self.p7dew+self.dp0 self.t6=PropsSI('T','P',self.p6,'H',self.h5,self.ref) self.h6=self.h5 self.v6=1/PropsSI('D','P',self.p6,'H',self.h6,self.ref) self.s6=PropsSI('S','P',self.p6,'H',self.h6,self.ref) self.x6=PropsSI('Q','P',self.p6,'H',self.h6,self.ref) self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t6),SI_TO('p',self.p6),self.v6,SI_TO('H',self.h6),SI_TO('S',self.s6),'%5.4f'%self.x6,self.InfoDict[name][1]) # # name='3dewm4bub' self.p3dewm4bub=(self.p4bub+self.p3dew)/2 self.t3dewm4bub=(self.t4bub+self.t3dew)/2 self.h3dewm4bub=(self.h4bub+self.h3dew)/2 self.v3dewm4bub=(self.v4bub+self.v3dew)/2 self.s3dewm4bub=(self.s4bub+self.s3dew)/2 self.x3dewm4bub=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t3dewm4bub),SI_TO('p',self.p3dewm4bub),self.v3dewm4bub,SI_TO('H',self.h3dewm4bub),SI_TO('S',self.s3dewm4bub),self.x3dewm4bub,self.InfoDict[name][1]) # # name='6m7dew' self.p6m7dew=(self.p6+self.p7dew)/2 self.t6m7dew=(self.t6+self.t7dew)/2 self.h6m7dew=(self.h6+self.h7dew)/2 self.v6m7dew=(self.v6+self.v7dew)/2 self.s6m7dew=(self.s6+self.s7dew)/2 self.x6m7dew=' ' self.row[name]=self.datarow%(self.InfoDict[name][0],SI_TO('T',self.t6m7dew),SI_TO('p',self.p6m7dew),self.v6m7dew,SI_TO('H',self.h6m7dew),SI_TO('S',self.s6m7dew),self.x6m7dew,self.InfoDict[name][1]) # self.mdot=SI_TO('P',self.Q0)*1000/(self.h7-self.h6) # average heat capacity of gas and liquid self.cpliq=(self.cp4 + self.cp5)/2000 #print('cp4 %5.4f cp5 %5.4f cpliq %5.4f '%(self.cp4,self.cp4,self.cpliq)) self.cpgas=(self.cp7 + self.cp8)/2000 #print('cp7 %5.4f cp8 %5.4f cpgas %5.4f '%(self.cp7,self.cp8,self.cpgas)) # multiply with mass flow self.mdot_x_cpliq = (self.mdot * self.cpliq) self.mdot_x_cpgas = (self.mdot * self.cpgas) #print('mdot %6.5fkg/s mdot*cpliq %6.5f mdot*cpgas %6.5f '%(self.mdot,self.mdot_x_cpliq,self.mdot_x_cpgas)) self.e_hoch_x=self.euler** ( (self.hx_kxa/(self.mdot_x_cpliq*1000)) - (self.hx_kxa/(self.mdot_x_cpgas*1000)) ) #print('e hoch klammer = ',self.e_hoch_x) self.Qhx=(self.t7-self.t4 + self.e_hoch_x * (self.t4-self.t7)) /((self.e_hoch_x/self.mdot_x_cpliq)-(1/self.mdot_x_cpgas)) #print('Q= %5.2f kW '%self.Qhx) self.dt_gas_out=self.Qhx/self.mdot_x_cpgas self.dt_liq_out=self.Qhx/self.mdot_x_cpliq #print('dt gas out = %5.2f / dt liq out = %5.2f K'%(self.dt_gas_out,self.dt_liq_out)) return self.dt_gas_out def last_run(self): # for point in self.InfoDict['order']: self.statetext+=self.row[point] # # relate massflux back to kW self.mdot=self.mdot/1000 self.statetext+=_('\nPower calculations | Key performance values\n') self.statetext+=_('Evaporator %8.2f kW | Pressure ratio %8.2f\n')%(SI_TO('P',self.Q0),(self.p2/self.p1)) self.statetext+=_('Condenser %8.2f kW | Pressure difference %8.2f %s\n')%(((self.h3-self.h4)*self.mdot),SI_TO('p',self.p2-self.p1),GUI_UNIT('p')) self.statetext+=_('Suction line %8.2f kW | Mass flow %8.6f g/s \n')%(((self.h1-self.h8)*self.mdot),(self.mdot*1000*1000)) self.statetext+=_('Discharge line %8.2f kW | Volume flow (suction line) %8.4f m³/h \n')%(((self.h2-self.h3)*self.mdot),(self.mdot*1000*3600*self.v1)) self.statetext+=_('Compressor %8.2f kW | Volumetric capacity %8.2f kJ/m³ \n')%(((self.h2-self.h1)*self.mdot),(SI_TO('P',self.Q0)/(self.v1*self.mdot*1000))) self.statetext+=_('Internal hx %8.2f kW | COP %8.2f \n')%(((self.h8-self.h7)*self.mdot),SI_TO('P',self.Q0)/((self.h2-self.h1)*self.mdot)) # self.Text_1.delete(1.0, END) #self.statetext='I am not yet ready' self.Text_1.insert(END, self.statetext) self.out_nb.select(1) def Update(self): # pass class _Testdialog: def __init__(self, master): frame = Frame(master) frame.pack() self.Caller = master self.x, self.y, self.w, self.h = -1,-1,-1,-1 # self.ref='R134a' # App=cpg_cycle2(frame,self,Debug=True) def get_ref(self): return 'R134a' def get_language(self): return 'de' def main(): root = Tk() app = _Testdialog(root) root.mainloop() if __name__ == '__main__': main()
mit
johanclasson/Unity.Interception.Serilog
src/Unity.Interception.Serilog/CommonPropertiesEnricher.cs
1382
using System; using Serilog.Core; using Serilog.Events; namespace Unity.Interception.Serilog { internal class CommonPropertiesEnricher : ILogEventEnricher { private readonly ICommonProperties _properties; public CommonPropertiesEnricher(ICommonProperties properties) { _properties = properties; } public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { Add(logEvent, propertyFactory, "ManagedThreadId", _properties.ManagedThreadId, 0); Add(logEvent, propertyFactory, "MachineName", _properties.MachineName, null); Add(logEvent, propertyFactory, "ProcessId", _properties.ProcessId, 0); Add(logEvent, propertyFactory, "ProcessName", _properties.ProcessName, null); Add(logEvent, propertyFactory, "ThreadName", _properties.ThreadName, null); Add(logEvent, propertyFactory, "AppDomainName", _properties.AppDomainName, null); } private static void Add<T>(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, string name, T value, T defaultValue) where T : IComparable { if (value == null) return; if (value.CompareTo(defaultValue) != 0) logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(name, value)); } } }
mit
tsigo/jugglf
app/models/completed_achievement.rb
1609
require 'open-uri' require 'nokogiri' class CompletedAchievement < ActiveRecord::Base attr_accessible :member, :member_id, :achievement, :achievement_id, :completed_on belongs_to :achievement belongs_to :member validates_presence_of :achievement validates_presence_of :member def self.parse_member(member) total_achievements = Achievement.count if total_achievements == 0 or member.completed_achievements.count != total_achievements contents = open("http://www.wowarmory.com/character-achievements.xml?r=Mal%27Ganis&n=#{member.name}&c=168", { 'User-Agent' => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.53 Safari/534.3", 'Accept-language' => 'enUS' }) doc = Nokogiri::XML(contents) # 6th Category = Lich King Heroic Raid # 8th Category = Secrets of Ulduar Heroic # 12th Category = Fall of the Lich King 25 doc.search("category:nth(12) achievement").each do |ach| achievement = Achievement.find_or_initialize_by_armory_id(ach['id']) if achievement.new_record? achievement.armory_id = ach['id'] achievement.category_id = ach['categoryId'] achievement.title = ach['title'] achievement.icon = ach['icon'] achievement.save end if ach['dateCompleted'] and (not achievement.members.include? member) achievement.completed_achievements.create(:member => member, :completed_on => ach['dateCompleted']) end end end end end
mit
gruberro/Sylius
src/Sylius/Component/Core/Promotion/Checker/Rule/CustomerGroupRuleChecker.php
1411
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Promotion\Checker\Rule; use Sylius\Component\Core\Model\CustomerInterface; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Promotion\Checker\Rule\RuleCheckerInterface; use Sylius\Component\Promotion\Exception\UnsupportedTypeException; use Sylius\Component\Promotion\Model\PromotionSubjectInterface; /** * @author Michał Marcinkowski <michal.marcinkowski@lakion.com> */ class CustomerGroupRuleChecker implements RuleCheckerInterface { const TYPE = 'customer_group'; /** * {@inheritdoc} */ public function isEligible(PromotionSubjectInterface $subject, array $configuration) { if (!$subject instanceof OrderInterface) { throw new UnsupportedTypeException($subject, OrderInterface::class); } if (null === $customer = $subject->getCustomer()) { return false; } if (!$customer instanceof CustomerInterface) { return false; } if (null === $customer->getGroup()) { return false; } return $configuration['group_code'] === $customer->getGroup()->getCode(); } }
mit
Wolfy42/EOF-JPA-CompatibilityLayer
JPACompatibilityLayer/Sources/com/webobjects/eocontrol/EOEditingContext.java
869
package com.webobjects.eocontrol; import com.webobjects.foundation.NSArray; public abstract class EOEditingContext { public static final Class<?> _CLASS = EOEditingContext.class; private UndoManager um; private EOObjectStore os; public EOEditingContext() { this.um = new UndoManager(); this.os = new EOObjectStore(); } public UndoManager undoManager() { return um; } public EOObjectStore rootObjectStore() { return os; } public static void setUsesContextRelativeEncoding(boolean value) { } public void lock() { } public void unlock() { } public abstract void insertObject(EOEnterpriseObject eo); public abstract void deleteObject(EOEnterpriseObject eo); public abstract void saveChanges(); public abstract void revert(); public abstract NSArray<?> objectsWithFetchSpecification(EOFetchSpecification fetchSpec); }
mit
Kstro/erpsystem
src/ERP/CRMBundle/Entity/CtlTipoAccion.php
1456
<?php namespace ERP\CRMBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * CtlTipoAccion * * @ORM\Table(name="ctl_tipo_accion") * @ORM\Entity */ class CtlTipoAccion { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="nombre", type="string", length=100, nullable=false) */ private $nombre; /** * @var string * * @ORM\Column(name="icono", type="text", length=65535, nullable=true) */ private $icono; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * @return CtlTipoAccion */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set icono * * @param string $icono * @return CtlTipoAccion */ public function setIcono($icono) { $this->icono = $icono; return $this; } /** * Get icono * * @return string */ public function getIcono() { return $this->icono; } }
mit
micmath/formica
tests/functional/inline_rules.php
1159
<html> <head> <title>Formica Example</title> </head> <body> <?php require_once '../../vendor/autoload.php'; $form = '../fixtures/forms/inline_rules.html'; $ruleSet = Formica::rules($form); $input = count($_POST)? $_POST : array( 'fname' => 'Michael', 'email_address' => 'Bloop' ); $filteredInput = Formica::filter($ruleSet, $input); $resultSet = Formica::validate($ruleSet, $filteredInput); $userfeedback = ''; if ( count($_POST) ) { if ( !$resultSet->isValid() ) { $messages = Formica::messages($resultSet) ->useLabels(array( 'fname' => 'first name', 'lname' => 'last name', )) ->asArray(2); $userfeedback = '<ul id="userfeedback"><li>' . implode('</li><li>', $messages) . '</li></ul>'; } else { $userfeedback = '<p>That\'s valid!</p>'; } } $prefilledForm = Formica::prefill($form, $filteredInput, $resultSet); echo $userfeedback ; echo $prefilledForm; ?> </body> </html>
mit
pu6ki/elsyser
homeworks/serializers.py
2032
from django.contrib.auth.models import User from rest_framework import serializers from students.serializers import ( ClassSerializer, SubjectSerializer, TeacherAuthorSerializer, StudentAuthorSerializer ) from students.utils import send_creation_email from .models import Homework, Submission class SubmissionSerializer(serializers.ModelSerializer): content = serializers.CharField(max_length=2048, allow_blank=False) solution_url = serializers.URLField(required=False, allow_blank=True) class Meta: model = Submission fields = ('id', 'homework', 'student', 'content', 'solution_url', 'checked') depth = 1 def create(self, validated_data): homework = self.context['homework'] request = self.context['request'] student = request.user.student return Submission.objects.create(homework=homework, student=student, **validated_data) class SubmissionReadSerializer(SubmissionSerializer): student = StudentAuthorSerializer(read_only=True) class HomeworkSerializer(serializers.ModelSerializer): details = serializers.CharField(max_length=256, allow_blank=True) class Meta: model = Homework fields = ('id', 'topic', 'subject', 'clazz', 'deadline', 'details', 'author') depth = 1 def create(self, validated_data): request = self.context['request'] author = request.user.teacher subject = author.subject clazz = self.context['clazz'] homework = Homework.objects.create( subject=subject, author=author, clazz=clazz, **validated_data ) recipient_list = User.objects.filter(student__clazz=clazz) for user in recipient_list: send_creation_email(user, model=homework) return homework class HomeworkReadSerializer(HomeworkSerializer): subject = SubjectSerializer(read_only=True) clazz = ClassSerializer(read_only=True) author = TeacherAuthorSerializer(read_only=True)
mit
chadqueen/RedFixGreen
test/RedFixGreen.Tests/Properties/AssemblyInfo.cs
829
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RedFixGreen.Tests")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("91990f45-705b-4f74-989f-613b9e3989ce")]
mit
armaniExchange/work-genius
src/components/ResourceMapTable/ResourceMapTableBody.js
5741
import './ResourceMapTable.css'; import './_color.css'; import React, { Component, PropTypes } from 'react'; import moment from 'moment'; import ResourceMapCellAddButton from './ResourceMapCellAddButton.js'; import ResourceMapCellPto from './ResourceMapCellPto.js'; import ResourceMapCellWorkLog from './ResourceMapCellWorkLog.js'; import ResourceMapCellHoliday from './ResourceMapCellHoliday.js'; import Td from '../A10-UI/Table/Td'; const RESOURCE_MAP_CELLS = { defaults: (config, onModalHander) => { return ( <ResourceMapCellAddButton config={config} onModalHander={onModalHander} /> ); // return (<div/>); }, pto: () => { return (<ResourceMapCellPto />); }, workday: (config, onModalHander, onSubmitStatus, onDeleteItemHander) => { return ( <ResourceMapCellWorkLog config={config} onModalHander={onModalHander} onSubmitStatus={onSubmitStatus} onDeleteItemHander={onDeleteItemHander} /> ); }, holiday: (config) => { // return ( // <ResourceMapCellWorkLog // config={config} // className={'holiday-style'} // onModalHander={onModalHander} // onSubmitStatus={onSubmitStatus} // onDeleteItemHander={onDeleteItemHander} // /> // ); return (<ResourceMapCellHoliday config={config} />); } }; // const RESOURCE_MAP_CELLS_DEFAULT_TYPE = 'defaults'; class ResourceMapTableBody extends Component { constructor() { super(); this._onShowModalHandler = ::this._onShowModalHandler; } _onShowModalHandler(config) { const { onModalHander } = this.props; onModalHander(true, config); } render() { const {data, startDate, totalDays, onModalHander, onSubmitStatus, onDeleteItemHander} = this.props; let bodyHtml = ( <tr> <Td colSpan={ totalDays + 1 } className="table_header_style"> No Match Result! </Td> </tr> ); if (data.length > 0) { // var moreItems = {}; bodyHtml = data.map((resource, bodyIndex) => { let worklogs = resource.jobs; var user = resource.name; var userId = resource.id; let userHtml = (<Td key={0} colSpan={1} className={'cell-layout-style'}>{user}</Td>); let itemsHtml = worklogs.map((itemValue, itemIndex) => { // If the day is weekday, will be show weekday style. let currentDay = moment(startDate).add(itemIndex, 'days'); // Got work log items, and show item cells. // let item = itemValue.worklog_items; let cellFunc = undefined; // Different cell function, show different style. // let config = {}; // The cell need config. var cellHtml = ''; // The style of final. let type = itemValue.day_type; if (RESOURCE_MAP_CELLS.hasOwnProperty(type)) { cellFunc = RESOURCE_MAP_CELLS[type]; } // cellFunc = RESOURCE_MAP_CELLS[type]; // if (type != null) { // config = itemValue; // cellFunc = RESOURCE_MAP_CELLS[type]; // } itemValue.user = user; itemValue.userId = userId; itemValue.date = currentDay; if (cellFunc !== undefined) { cellHtml = cellFunc(itemValue, onModalHander, onSubmitStatus, onDeleteItemHander); } // var defaultCellHtml = RESOURCE_MAP_CELLS[ RESOURCE_MAP_CELLS_DEFAULT_TYPE ](config, onModalHander); let __onShowModalHandler = () => { this._onShowModalHandler(itemValue); }; // let day = currentDay.isoWeekday(); let className = 'cell-layout-style'; // if (day === 6 || day === 7) { // className += '__weekday'; // } else if (type === 'pto') { className += '__pto'; } else if (type === 'holiday') { className += '__holiday'; } return ( <Td key={itemIndex + 1} colSpan={1} className={className} onClick={__onShowModalHandler} > {cellHtml} </Td> ); }); itemsHtml.unshift(userHtml); return ( <tr className={'table-tr'} key={bodyIndex}>{itemsHtml}</tr> ); }); } return ( <tbody className="pto-table__body"> {bodyHtml} </tbody> ); } } ResourceMapTableBody.propTypes = { startDate: PropTypes.string.isRequired, totalDays: PropTypes.number.isRequired, data: PropTypes.array.isRequired, onModalHander: PropTypes.func.isRequired, onSubmitStatus: PropTypes.func.isRequired, onDeleteItemHander: PropTypes.func.isRequired }; ResourceMapTableBody.defaultProps = { totalDays: 7 }; export default ResourceMapTableBody;
mit
kickinrad/healerhealer
cauldron.lua
1894
-- cauldron.lua cauldron = {} testPatient = {"fr","fr","rt","ey","nt"} local sortTreatment = function (a, b) return a < b end function loadCauldron() caulFront = love.graphics.newImage("assets/character/cauldront_front.png") caulBack = love.graphics.newImage("assets/character/cauldron_back.png") logs = love.graphics.newImage("assets/character/logs.png") fire = love.graphics.newImage("assets/character/fire.png") soundGrunt = love.audio.newSource("assets/sounds/grunt.wav", static) end function addToCauldron(x) table.insert(cauldron, x) end function treatPatient() --print("We're gonna treat ya lmao") --table.sort(testPatient, sortTreatment) table.sort(cauldron, sortTreatment) if table.getn(cauldron) == 0 then --print("You didn't do anything!") return end status = false wasCured = false curesNeeded = getCures() for n=1, table.getn(curesNeeded) do for i=1,table.getn(curesNeeded[n])-1 do if curesNeeded[n][i] == cauldron[i] then status = true else status = false break end end if status then print(curesNeeded[n][1]) cure(curesNeeded[n][table.getn(curesNeeded[n])]) wasCured = true end end if wasCured == false then love.audio.play(soundGrunt) killPatient() end cauldron = {} -- empty cauldron end function drawCauldron() love.graphics.draw(logs, 225, 500, 0, 1, 1, 100, 100) love.graphics.draw(caulFront, 225, 500, 0, 1, 1, 100, 100) love.graphics.draw(fire, 225, 500, 0, 1, 1, 100, 100) love.graphics.draw(caulBack, 225, 500, 0, 1, 1, 100, 100) if table.getn(cauldron) >= 5 then love.graphics.setFont(big_gothic) love.graphics.printf("Cauldron is full!", 100, 360, 200) love.graphics.setFont(thin) end end function testDrawCauldron(asd) love.graphics.print(cauldron, 5, 545) --love.graphics.print(testPatient, 550, 300) end
mit
IKende/IKendeLib
KGlue/KGlue/Center.cs
4479
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace KGlue { public class Center { private System.Collections.ArrayList mDomains = new System.Collections.ArrayList(); private System.Collections.ArrayList mFileWatches = new System.Collections.ArrayList(); public event EventDomainExecuting LogEvent; public Center() { CreateWatchTimer(); } public Center(string section) { CreateWatchTimer(); AppSection config = (AppSection)System.Configuration.ConfigurationManager.GetSection(section); foreach(Item item in config.Items) { Add(item.Path,item.Name,item.Args.Split(' ')); } } private System.Threading.Timer mTimer; private void CreateWatchTimer() { mTimer = new System.Threading.Timer(OnFileWatche,null,10000,5000); } public void Add(string virtualpath, string virtualname,string[] args) { if (virtualpath.IndexOf(System.IO.Path.DirectorySeparatorChar) < 0) { virtualpath = AppDomain.CurrentDomain.BaseDirectory + virtualpath; } if (virtualpath.LastIndexOf(System.IO.Path.DirectorySeparatorChar) != virtualpath.Length - 1) { virtualpath += System.IO.Path.DirectorySeparatorChar; } if (System.IO.Directory.Exists(virtualpath)) { AdapterDomain pd = new AdapterDomain(virtualpath, virtualname, null); pd.Args = args; pd.LogEvent += OnLogEvent; mDomains.Add(pd); if (!System.IO.Directory.Exists(pd.CachePath)) { System.IO.Directory.CreateDirectory(pd.CachePath); } mFileWatches.Add(new FileWatcher(pd)); } else { OnLogEvent(this, new DomainExecutingArgs { Status = ExecutingStatus.Warning, Message = string.Format("{0} notfound.", virtualpath) }); } } public System.Collections.ArrayList Domains { get { return mDomains; } } public void Start() { foreach (AdapterDomain item in mDomains) { item.Start(); } } public void Start(string virtualpath) { int index = mDomains.IndexOf(virtualpath); if (index >= 0) ((AdapterDomain)mDomains[index]).Start(); } public void Stop() { foreach (AdapterDomain item in mDomains) { item.Stop(); } } public void Stop(string virtualpath) { int index = mDomains.IndexOf(virtualpath); if (index >= 0) ((AdapterDomain)mDomains[index]).Stop(); } private AdapterDomain GetDomain(string virtualpath) { int index = mDomains.IndexOf(virtualpath); if (index >= 0) return ((AdapterDomain)mDomains[index]); return null; } private void OnLogEvent(object sender, DomainExecutingArgs e) { if (LogEvent != null) LogEvent(this, e); } private long mPingCount = 0; private void OnPingDomian(object state) { foreach (AdapterDomain item in mDomains) { try { if (item.Status == DomainStatus.Started) item.Ping(); } catch (Exception e_) { OnLogEvent(this, new DomainExecutingArgs { Status = ExecutingStatus.Error, Error =e_, Message = string.Format("domain [{0}] ping error.", item.VirtualName) }); } } } private void OnFileWatche(object state) { System.Threading.Interlocked.Increment(ref mPingCount); if (mPingCount % 2 == 0) { OnPingDomian(state); } for (int i = 0; i < mFileWatches.Count; i++) { ((FileWatcher)mFileWatches[i]).Update(); } } } }
mit
jeromeetienne/augmentedgesture.js
vendor/imageprocessing.js
12148
/** * @author jerome etienne jerome.etienne@gmail.com * @author Djordje Lukic lukic.djordje@gmail.com */ /** * @namespace */ var ImgProc = {}; /** * horizontal flip */ ImgProc.fliph = function(imageData) { var p = imageData.data; var w = imageData.width; var h = imageData.height; var tmp; for(var y = 0; y < h; y++){ for(var x = 0; x < w/2; x++){ var i1 = (x + y*w)*4; var i2 = ((w-1-x) + y*w)*4; // swap red tmp = p[i1+0]; p[i1+0] = p[i2+0]; p[i2+0] = tmp; // swap red tmp = p[i1+1]; p[i1+1] = p[i2+1]; p[i2+1] = tmp; // swap green tmp = p[i1+2]; p[i1+2] = p[i2+2]; p[i2+2] = tmp; // swap alpha tmp = p[i1+3]; p[i1+3] = p[i2+3]; p[i2+3] = tmp; } } } /** * Convert the image to luminance */ ImgProc.luminance = function(imageData, ratio) { ratio = ratio !== undefined ? ratio : 1.0; var p = imageData.data; var w = imageData.width; var h = imageData.height; for(var i = 0, y = 0; y < h; y++){ for(var x = 0; x < w; x++, i += 4){ var luminance = (0.2126*(p[i+0]/255)) + (0.7152*(p[i+1]/255)) + (0.0722*(p[i+2]/255)) luminance = Math.floor(luminance*ratio*255); p[i+0] = luminance; p[i+1] = luminance; p[i+2] = luminance; } } } /** * Duplicate the ImgData */ ImgProc.duplicate = function(srcImgData, ctx) { return ImgProc.copy(srcImgData, ctx.createImageData(srcImgData)) /** old but tested version var dstImgData = ctx.createImageData(srcImgData); var pSrc = srcImgData.data; var pDst = dstImgData.data; for(var i = 0; i < pSrc.length; i++){ pDst[i] = pSrc[i]; } return dstImgData; */ } /** * Copy the ImgData */ ImgProc.copy = function(srcImgData, dstImgData) { console.assert(srcImgData.width === dstImgData.width ); console.assert(srcImgData.height === dstImgData.height ); var pSrc = srcImgData.data; var pDst = dstImgData.data; for(var i = 0; i < pSrc.length; i++){ pDst[i] = pSrc[i]; } return dstImgData; } ////////////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////////////// /** * Sobel operator * * see http://en.wikipedia.org/wiki/Sobel_operator */ ImgProc.sobel = function(srcImgProc, dstImgProc) { var pSrc= srcImgProc.data; var w = srcImgProc.width; var h = srcImgProc.height; var pDst= dstImgProc.data; // TODO make be optimized http://en.wikipedia.org/wiki/Sobel_operator#Technical_details var sobel_x = [ [-1,0,1], [-2,0,2], [-1,0,1] ]; var sobel_y = [ [-1,-2,-1], [ 0, 0, 0], [ 1, 2, 1] ]; var greyAt = function(p, x, y) { var offset = x * 4 + y * w * 4; return p[offset] * 0.3 + p[offset + 1] * 0.59 + p[offset + 2] * 0.11; } // TODO instead of recomputing the index everytime, make it incremental for(var x = 1; x < w - 2; x++) { for(var y = 1; y < h - 2; y++) { var px = (sobel_x[0][0] * greyAt(pSrc, x-1,y-1)) + (sobel_x[0][1] * greyAt(pSrc, x,y-1)) + (sobel_x[0][2] * greyAt(pSrc, x+1,y-1)) + (sobel_x[1][0] * greyAt(pSrc, x-1,y)) + (sobel_x[1][1] * greyAt(pSrc, x,y)) + (sobel_x[1][2] * greyAt(pSrc, x+1,y)) + (sobel_x[2][0] * greyAt(pSrc, x-1,y+1)) + (sobel_x[2][1] * greyAt(pSrc, x,y+1)) + (sobel_x[2][2] * greyAt(pSrc, x+1,y+1)) var py = (sobel_y[0][0] * greyAt(pSrc, x-1,y-1)) + (sobel_y[0][1] * greyAt(pSrc, x,y-1)) + (sobel_y[0][2] * greyAt(pSrc, x+1,y-1)) + (sobel_y[1][0] * greyAt(pSrc, x-1,y)) + (sobel_y[1][1] * greyAt(pSrc, x,y)) + (sobel_y[1][2] * greyAt(pSrc, x+1,y)) + (sobel_y[2][0] * greyAt(pSrc, x-1,y+1)) + (sobel_y[2][1] * greyAt(pSrc, x,y+1)) + (sobel_y[2][2] * greyAt(pSrc, x+1,y+1)) var val = Math.ceil(Math.sqrt(px * px + py * py)); var offset = y * w * 4 + x * 4; pDst[offset+0] = val; pDst[offset+1] = val; pDst[offset+2] = val; } } } ////////////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////////////// ImgProc.threshold = function(imageData, r, g, b) { var p = imageData.data; var w = imageData.width; var h = imageData.height; for(var i = 0, y = 0; y < h; y++){ for(var x = 0; x < w; x++, i += 4){ if( (p[i+0] >= r.min && p[i+0] <= r.max) && (p[i+1] >= g.min && p[i+1] <= g.max) && (p[i+2] >= b.min && p[i+2] <= b.max) ){ }else{ p[i+0] = p[i+1] = p[i+2] = 0; } } } } ImgProc.convert = function(imageData, callback) { var p = imageData.data; var w = imageData.width; var h = imageData.height; var i = 0; for(var y = 0; y < h; y++){ for(var x = 0; x < w; x++, i += 4){ callback(p, i, x, y, imageData); } } } ////////////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////////////// ImgProc.hline = function(imageData, y, r, g, b, a) { var p = imageData.data; var w = imageData.width; var i = y * w * 4; r = r !== undefined ? r : 255; g = g !== undefined ? g : 255; b = b !== undefined ? b : 255; a = a !== undefined ? a : 255; for(var x = 0; x < w; x++, i += 4){ p[i+0] = r; p[i+1] = g; p[i+2] = b; p[i+3] = a; } } ImgProc.vline = function(imageData, x, r, g, b, a) { var p = imageData.data; var w = imageData.width; var h = imageData.height; r = r !== undefined ? r : 255; g = g !== undefined ? g : 255; b = b !== undefined ? b : 255; a = a !== undefined ? a : 255; for(var i = x*4, y = 0; y < h; y++, i += w*4){ p[i+0] = r; p[i+1] = g; p[i+2] = b; p[i+3] = a; } } ////////////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////////////// ImgProc.smoothHistogram = function(hist, factor) { var value = 0; for(var i = 0; i < hist.length; i++ ){ value += (hist[i] - value) * factor; hist[i] = value; } } ImgProc.windowedAverageHistogram = function(hist, width) { var halfW = Math.floor(width/2); var winSum = 0; var winLen = 0; var origHist = new Array(hist.length); for(var i = 0; i < hist.length; i++) origHist[i] = hist[i]; // init window for(var i = 0; i < halfW; i++){ winSum += hist[i]; winLen ++; } for(var i = 0; i < hist.length; i++){ // update window forward if( i + halfW < hist.length ){ winSum += origHist[i+halfW]; winLen ++; } // update window backward if( i-halfW >= 0 ){ winSum -= origHist[i-halfW]; winLen --; } // compute the actual value hist[i] = winSum/winLen; } } ImgProc.getMaxHistogram = function(hist, imageData) { var max = -Number.MAX_VALUE; var idx = 0; for(var i = 0; i < hist.length; i++ ){ if( hist[i] > max ){ max = hist[i]; idx = i; } } return {max: max, idx: idx} } ImgProc.filterHistogram = function(hist, filterFn) { for(var i = 0; i < hist.length; i++ ){ var val = hist[i]; filterFn(val, i, hist); } } ////////////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////////////// ImgProc.computeHorizontalHistogram = function(imageData, filter) { var p = imageData.data; var w = imageData.width; var h = imageData.height; var hist= new Float64Array(w); console.assert(filter, "invalid parameter") for(var x = 0; x < w; x++){ for(var i = x*4, y = 0; y < h; y++, i += w*4){ if( filter(p, i, x, y, imageData) ) hist[x]++; } } return hist; } ImgProc.displayHorizontalHistogram = function(imageData, hist) { var p = imageData.data; var w = imageData.width; var h = imageData.height; console.assert(hist.length === w); // create temporary cancas var canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; var ctx = canvas.getContext("2d"); // display the histogram in the canvas ctx.fillStyle = 'red'; for(var x = 0; x < w; x++ ){ ctx.fillRect(x, h-hist[x], 1, hist[x]); } // copy the canvas in imageData var srcImgData = ctx.getImageData(0,0, canvas.width, canvas.height); var pSrc = srcImgData.data; var pDst = imageData.data; for(var i = 0; i < pSrc.length; i += 4){ if( pSrc[i+0] !== 0 || pSrc[i+1] !== 0 || pSrc[i+2] !== 0 ){ pDst[i+0] = pSrc[i+0]; pDst[i+1] = pSrc[i+1]; pDst[i+2] = pSrc[i+2]; } pDst[i+3] = 255; } } ////////////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////////////// ImgProc.computeVerticalHistogram = function(imageData, filter) { var p = imageData.data; var w = imageData.width; var h = imageData.height; var hist= new Float64Array(h); console.assert(filter, "invalid parameter") for(var i = 0, y = 0; y < h; y++){ for(var x = 0; x < w; x++, i += 4){ if( filter(p, i, x, y, imageData) ) hist[y]++; } } return hist; } ImgProc.displayVerticalHistogram = function(imageData, hist) { var p = imageData.data; var w = imageData.width; var h = imageData.height; console.assert(hist.length === h); // create temporary cancas var canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; var ctx = canvas.getContext("2d"); // display the histogram in the canvas ctx.fillStyle = 'red'; for(var y = 0; y < h; y++ ){ ctx.fillRect(0, y, hist[y], 1); } // copy the canvas in imageData var srcImgData = ctx.getImageData(0,0, canvas.width, canvas.height); var pSrc = srcImgData.data; var pDst = imageData.data; for(var i = 0; i < pSrc.length; i += 4){ if( pSrc[i+0] !== 0 || pSrc[i+1] !== 0 || pSrc[i+2] !== 0 ){ pDst[i+0] = pSrc[i+0]; pDst[i+1] = pSrc[i+1]; pDst[i+2] = pSrc[i+2]; } pDst[i+3] = 255; } } ////////////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////////////// ImgProc.computeColorHistogram = function(imageData) { var p = imageData.data; var w = imageData.width; var h = imageData.height; var hist= { r : new Float64Array(256), g : new Float64Array(256), b : new Float64Array(256) }; for(var i = 0, y = 0; y < h; y++){ for(var x = 0; x < w; x++, i += 4){ hist.r[ p[i+0] ]++; hist.g[ p[i+1] ]++; hist.b[ p[i+2] ]++; } } return hist; } ImgProc.normalizeColorHistogram = function(colorHistogram) { var hist= colorHistogram; // get the max value var max = -Number.MAX_VALUE; for (var i = 0; i < 256; i++ ){ max = Math.max(max, hist.r[i]); max = Math.max(max, hist.g[i]); max = Math.max(max, hist.b[i]); } // normalize the histogram for (var i = 0; i < 256; i++ ){ hist.r[i] /= max; hist.g[i] /= max; hist.b[i] /= max; } var sumR = 0; var sumG = 0; var sumB = 0; for (var i = 0; i < 256; i++ ){ sumR += hist.r[i]; sumG += hist.g[i]; sumB += hist.b[i]; } console.log("sum", max, sumR, sumG, sumB) } ImgProc.displayColorHistogram = function(imageData, colorHistogram) { var p = imageData.data; var w = imageData.width; var h = imageData.height; var hist= colorHistogram; var canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; var ctx = canvas.getContext("2d"); var barW = canvas.width / 256; var barH = canvas.height / 3; ctx.fillStyle = 'red'; var barYOffset = 0 * barH; for (var i = 0; i < 256; i++ ){ var valH = Math.floor(hist.r[i]*barH); ctx.fillRect(i*barW, barYOffset+(barH-valH), barW, valH); } ctx.fillStyle = 'green'; var barYOffset = 1 * barH; for (var i = 0; i < 256; i++ ){ var valH = Math.floor(hist.g[i]*barH); ctx.fillRect(i*barW, barYOffset+(barH-valH), barW, valH); } ctx.fillStyle = 'blue'; var barYOffset = 2 * barH; for (var i = 0; i < 256; i++ ){ var valH = Math.floor(hist.b[i]*barH); ctx.fillRect(i*barW, barYOffset+(barH-valH), barW, valH); } var srcImgData = ctx.getImageData(0,0, canvas.width, canvas.height); var pSrc = srcImgData.data; var pDst = imageData.data; for(var i = 0; i < pSrc.length; i += 4){ if( pSrc[i+0] !== 0 || pSrc[i+1] !== 0 || pSrc[i+2] !== 0 ){ pDst[i+0] = pSrc[i+0]; pDst[i+1] = pSrc[i+1]; pDst[i+2] = pSrc[i+2]; } } };
mit
vincenti/csharp.series.one
01.Wstep-do-csharp-i-xaml/Zad01/MainWindow.xaml.cs
702
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MainWindow.xaml.cs" company="KUL.NET"> // Created by Jarosław Wąsik // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Zad01 { using System.Windows; public partial class MainWindow : Window { public MainWindow() { this.InitializeComponent(); } private void PokazKomunikat(object sender, RoutedEventArgs e) { MessageBox.Show("Witaj świecie", "Pierwszy program"); } } }
mit
unicorn-fail/grunt-drupal-bootstrap
index.js
8086
/** * The "grunt-drupal-bootstrap" NPM module. * * The MIT License (MIT) * Copyright (c) 2016 Mark Carver */ (function (exports) { "use strict"; var _ = require('./lib/util/underscore'); var bower = require('./lib/bower'); var cwd = process.cwd(); var endpointParser = require('bower-endpoint-parser'); var file = require('./lib/util/file'); var grunt = require('grunt'); var path = require('path'); var preprocessor = require('./lib/preprocessor'); var Promise = require('grunt-promise').using('bluebird'); /** * @module module:grunt-drupal-bootstrap */ var bootstrap = exports; /** * Contains configuration settings provided in the "drupal-bootstrap" property * from a theme's package.json file. * * Don't use this property directly, you should use bootstrap.getConfig() and * bootstrap.setConfig() respectively. * * @private * @type {Object} */ bootstrap.config = {}; /** * The current grunt task instance. * * @type {grunt.task.current} */ bootstrap.task = null; /** * Contains loaded preprocessors. * * @private * * @type {Object} */ bootstrap.preprocessors = {}; /** * Performs an Promise based asynchronous exec child process. * * @param {string} cmd * The command to execute. * @param {Array} [args] * An array of arguments to use. * @param {Object} [options] * An object of options to pass to child_process.exec. */ bootstrap.spawn = function (cmd, args, options) { options = _.extend({stdio: 'inherit'}, options || {}); grunt.log.debug([].concat([cmd], args).join(' ')); return new Promise(function (resolve, reject) { require('child_process').spawn(cmd, args || [], options) .on('close', function (code) { if (code !== 0) reject(code); resolve(); }); }).catch(function (e) { grunt.fail.fatal(new Error(e)); }); }; /** * Installs the Bootstrap assets and preprocessor dependencies. * * @returns {Promise} */ bootstrap.install = function () { var preprocessor = bootstrap.getPreprocessor(); return preprocessor.install() .then(bower.install.bind(bower)) .map(preprocessor.postInstall.bind(preprocessor)) .then(function (endpoints) { return bootstrap.removeBowerComponents() .return(Promise.resolve(_.filter(endpoints))); }) .map(function (endpoint) { var e = _.clone(endpoint); delete e.name; return endpointParser.compose(e); }) .then(function (endpoints) { if (endpoints.length) grunt.log.writeln().writeln('Successfully installed: ' + endpoints.join(', ')); }); }; bootstrap.removeBowerComponents = function () { return file.exists('bower_components').then(function (exists) { if (exists) return file.remove('bower_components'); return Promise.resolve(); }); }; /** * Retrieves a preprocessor instance. * * @param {String} [name] * The name of the preprocessor to load. * * @returns {Preprocessor} */ bootstrap.getPreprocessor = function (name) { if (!name && this.preprocessor) return this.preprocessor; var preprocessor = name ? require('./lib/preprocessors/' + name) : require('./lib/preprocessor').none; if (!preprocessor.installed) { preprocessor.install(); } if (['less', 'sass'].indexOf(preprocessor.name) === -1) { grunt.fail.fatal("Your theme's package.json file must contain a valid `drupal-bootstrap.preprocessor` type; either `less` or `sass`."); } return this.preprocessor = preprocessor; }; /** * Wraps a grunt.registerPromise to inject the necessary initTask invocation. * * @param {string} name * The name of the Grunt task to register. * @param {string|function} [info] * (Optional) Descriptive text explaining what the task does. Shows up on * `--help`. You may omit this argument and replace it with `fn` instead. * @param {function} [fn] * (Required) The task function. Remember not to pass in your Promise * function directly. Promise resolvers are immediately invoked when they * are created. You should wrap the Promise with an anonymous task function * instead. * * @returns {Function<Promise>|Object<Promise>} */ bootstrap.registerPromise = function (name, info, fn) { var self = this; if (!fn) { fn = info; info = null; } if (typeof fn !== 'function') { grunt.fail.fatal(new Error('The "fn" argument for grunt.registerPromise or grunt.registerMultiPromise must be a function.')); } return grunt.registerPromise.apply(grunt.task, [name, info, function () { self.initTask(this); return fn.apply(this, this.args).finally(self.shutDown.bind(self)); }]); }; /** * Wraps a grunt.registerPromise to inject the necessary initTask invocation. * * @param {string} name * The name of the Grunt task to register. * @param {string|function} [info] * (Optional) Descriptive text explaining what the task does. Shows up on * `--help`. You may omit this argument and replace it with `fn` instead. * @param {function} [fn] * (Required) The task function. Remember not to pass in your Promise * function directly. Promise resolvers are immediately invoked when they * are created. You should wrap the Promise with an anonymous task function * instead. * * @returns {Function<Promise>|Object<Promise>} */ bootstrap.registerMultiPromise = function (name, info, fn) { var self = this; if (!fn) { fn = info; info = null; } if (typeof fn !== 'function') { grunt.fail.fatal(new Error('The "fn" argument for grunt.registerPromise or grunt.registerMultiPromise must be a function.')); } return grunt.registerMultiPromise.apply(grunt.task, [name, info, function () { self.initTask(this); return fn.apply(this, this.args).finally(self.shutDown.bind(self)); }]); }; bootstrap.init = function (config) { this.debug = !!grunt.option('debug'); this.force = !!grunt.option('force'); this.verbose = !!grunt.option('verbose'); this.pkg = grunt.file.readJSON('package.json') || {}; // Merge configuration from "drupal-bootstrap" property from the // theme's package.json file. this.config = _.merge(this.config, this.pkg['drupal-bootstrap'], config); this.originalConfig = _.clone(this.config); // Retrieve the preprocessor. // @todo this should be moved out of the default config and into compiling // so individual sources can be compiled as needed. if (!this.config.preprocessor) this.config.preprocessor = 'less'; var preprocessor = this.getPreprocessor(this.config.preprocessor); // Retrieve the library package and version. // @todo this should be an array/object to allow multiple packages. if (!this.config.package) this.config.package = 'bootstrap' + (preprocessor.name === 'sass' ? '-sass' : ''); if (!this.config.version) this.config.version = '^3.0.0'; // Initialize bower. bower.init(); }; bootstrap.getConfig = function (name, defaultValue) { return _(this.config).getNested(name, defaultValue); }; bootstrap.setConfig = function (name, value) { _(this.config).setNested(name, value); return value; }; bootstrap.initTask = function (currentTask) { return this.task = currentTask; }; /** * Performs cleanup operations after a task has finished. */ bootstrap.shutDown = function () { // If this is a test, don't save config back to this project's package.json. if (grunt.option('is-test')) return; var config = _.deepClean(this.config); if (JSON.stringify(this.originalConfig) === JSON.stringify(config)) return Promise.resolve(); this.pkg['drupal-bootstrap'] = this.originalConfig = config; return file.writeJSON(path.join(cwd, 'package.json'), this.pkg); }; // Initialize the module. bootstrap.init(); })(module.exports);
mit
sallyyoo/ced2
book/code/e-shop/webpack/client.js
435
/** * Created on 2018/1/29. */ const webpack = require('webpack') const merge = require('webpack-merge') const common = require('./common') const VueSSRClientPlugin = require('vue-server-renderer/client-plugin') module.exports = merge(common, { entry: './src/entry-client', plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity, }), new VueSSRClientPlugin(), ], })
mit
bryanphillips/TMDB
MovieDB.Core/ServiceContainer.cs
2640
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MovieDB.Core { /// <summary> /// A simple service container implementation, singleton only /// </summary> public static class ServiceContainer { private static readonly Dictionary<Type, Lazy<object>> _services = new Dictionary<Type, Lazy<object>>(); /// <summary> /// Register the specified service with an instance /// </summary> public static void Register<T>(T service) { _services[typeof(T)] = new Lazy<object>(() => service); } /// <summary> /// Register the specified service for a class with a default constructor /// </summary> public static void Register<T>() where T : new() { _services[typeof(T)] = new Lazy<object>(() => new T()); } /// <summary> /// Register the specified service with a callback to be invoked when requested /// </summary> public static void Register<T>(Func<T> function) { _services[typeof(T)] = new Lazy<object>(() => function()); } /// <summary> /// Register the specified service with an instance /// </summary> public static void Register(Type type, object service) { _services[type] = new Lazy<object>(() => service); } /// <summary> /// Register the specified service with a callback to be invoked when requested /// </summary> public static void Register(Type type, Func<object> function) { _services[type] = new Lazy<object>(function); } /// <summary> /// Resolves the type, throwing an exception if not found /// </summary> public static T Resolve<T>() { return (T)Resolve(typeof(T)); } /// <summary> /// Resolves the type, throwing an exception if not found /// </summary> public static object Resolve(Type type) { Lazy<object> service; if (_services.TryGetValue(type, out service)) { return service.Value; } else { throw new KeyNotFoundException(string.Format("Service not found for type '{0}'", type)); } } /// <summary> /// Mainly for testing, clears the entire container /// </summary> public static void Clear() { _services.Clear(); } } }
mit
ibramos/The-Feed
client/src/index.js
605
import "materialize-css/dist/css/materialize.min.css"; import React from "react"; import ReactDOM from "react-dom"; import { Provider } from "react-redux"; import { createStore, applyMiddleware } from "redux"; import reduxThunk from "redux-thunk"; import App from "./components/App"; import reducers from "./reducers/combine"; //remove later - usage to test out survey routes import axios from 'axios' window.axios = axios const store = createStore(reducers, {}, applyMiddleware(reduxThunk)); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.querySelector("#root") );
mit
kidaa/uw-web
tools/textgenerator/node_modules/generate_tischendorf.js
4955
var fs = require('fs'), path = require('path'), bibleData = require('bible_data'), bibleFormatter = require('bible_formatter'), readline = require('readline'); stream = require('stream'), verseIndexer = require('verse_indexer'); function generate(inputPath, info, createIndex, startProgress, updateProgress) { var breakChar = '\r'; data = { chapterData: [], indexData: {}, indexLemmaData: {}, infoHtml: '' }, validBooks = [], validBookNames = [], validChapters = [], filesInputPath = path.join(inputPath,'Unicode'), bookCodes = ["MT","MR","LU","JOH","AC","RO","1CO","2CO","GA","EPH","PHP","COL","1TH","2TH","1TI","2TI","TIT","PHM","HEB","JAS","1PE","2PE","1JO","2JO","3JO","JUDE","RE"], //["MT"], lastBookNumber = -1, lastChapterNumber = -1, lastVerseNumber = -1, currentChapter = null; startProgress(bookCodes.length, "Books"); // process files bookCodes.forEach(function(bookCode) { var filePath = path.join(filesInputPath, bookCode + '.txt'), rawText = fs.readFileSync(filePath, 'utf8'), lines = rawText.split('\n'), bookIndex = bookCodes.indexOf(bookCode), bookName = '', dbsBookCode = bibleData.NT_BOOKS[bookIndex], isNewBook = true, bookInfo = bibleData.getBookInfoByDbsCode( dbsBookCode ); //console.log(bookCode, lines.length, dbsBookCode); //console.time('processTextFile'); // READ TEXT for (var i=0, il=lines.length; i<il; i++) { var line = lines[i].trim(), parts = line.split(' '); if (parts.length <= 3) { continue; } var verseParts = parts[1].trim().split(/[\.:]/gi), chapterNumber = parseInt(verseParts[0], 10), verseNumber = parseInt(verseParts[1], 10), lineType = parts[2].trim(), word = parts[3].trim(), morph = parts[5].trim(), strongs = parts[6].trim(), chapterCode = dbsBookCode + '' + chapterNumber.toString(), verseCode = chapterCode + '_' + verseNumber.toString(); // new book if (isNewBook) { bookName = bibleData.getBookName(dbsBookCode, info['lang']); if (bookName == null) { bookName = bookInfo['name'].split('/')[0]; } if (validBooks.indexOf(dbsBookCode) == -1) { validBooks.push(dbsBookCode) } if (validBookNames.indexOf(bookName) == -1) { validBookNames.push(bookName) } // reset lastChapterNumber = -1; lastVerseNumber = -1; isNewBook = false; } // new chapter if (chapterNumber != lastChapterNumber) { // close old if (currentChapter != null) { currentChapter.html += '</span>' + bibleFormatter.breakChar + // verse '</div>' + bibleFormatter.breakChar + // paragraph bibleFormatter.closeChapter(); } // create new currentChapter = { id: chapterCode, nextid: bibleData.getNextChapter(chapterCode), previd: bibleData.getPrevChapter(chapterCode), title: bookName + ' ' + chapterNumber, html: '' }; data.chapterData.push( currentChapter ); if (validChapters.indexOf(chapterCode) == -1) { validChapters.push(chapterCode) } // setup new currentChapter.html = bibleFormatter.openChapter(info, currentChapter); if (chapterNumber == 1) { currentChapter.html += '<div class="mt">' + bookName + '</div>' + bibleFormatter.breakChar; } currentChapter.html += '<div class="c">' + chapterNumber + '</div>' + bibleFormatter.breakChar + '<div class="p">' + bibleFormatter.breakChar; lastChapterNumber = chapterNumber; lastVerseNumber = -1; } // new verse if (verseNumber != lastVerseNumber) { if (createIndex) { //verseIndexer.indexVerse(verseCode, text, data.indexData, info.lang); } if (verseNumber > 1) { // close currentChapter.html += bibleFormatter.closeVerse(); if (lineType == 'P') { currentChapter.html += '<p>\n<p>\n'; } } // open currentChapter.html += bibleFormatter.openVerse(verseCode, verseNumber.toString()); // store lastVerseNumber = verseNumber; } // add word currentChapter.html += '<l ' + (strongs != 'undefined' && typeof strongs != 'undefined' ? 's="' + 'G' + strongs + '"' : '') + ( morph ? ' m="' + morph + '"' : '') + '>' + word + '</l> '; if (createIndex && strongs) { verseIndexer.indexStrongs(verseCode, 'G' + strongs, data.indexLemmaData, info.lang); } } updateProgress(); }); currentChapter.html += '</span>' + bibleFormatter.breakChar + '</div>' + bibleFormatter.breakChar + + bibleFormatter.closeChapter(); // copy about if present var aboutPath = path.join(inputPath, 'about.html'); if (fs.existsSync(aboutPath)) { data.aboutHtml = fs.readFileSync( aboutPath , 'utf8'); } // CREATE INFO info.type = 'bible'; info.divisionNames = validBookNames; info.divisions = validBooks; info.sections = validChapters; return data; } module.exports = { generate: generate }
mit
ehartmann/electric_sheep
lib/electric_sheep/command.rb
953
module ElectricSheep module Command extend ActiveSupport::Concern include Runnable attr_reader :shell delegate :stat_file, :stat_directory, :stat_filesystem, to: :shell def initialize(job, logger, shell, input, metadata) @job = job @logger = logger @shell = shell @input = input @metadata = metadata end def run! stat!(input) output = perform! stat!(output) output end protected def host shell.host end def stat!(resource) if resource.stat.size.nil? resource.stat!(send("stat_#{resource.type}", resource)) end rescue Exception => e logger.debug 'Unable to stat resource of type ' \ "#{resource.type}: #{e.message}" end module ClassMethods def register(options = {}) ElectricSheep::Agents::Register.register options.merge(command: self) end end end end
mit
nl-hugo/sqlgraph
src/main/java/nl/hugojanssen/sqlgraph/visitors/TableVisitor.java
4809
package nl.hugojanssen.sqlgraph.visitors; import gudusoft.gsqlparser.ETableSource; import gudusoft.gsqlparser.TBaseType; import gudusoft.gsqlparser.TSourceTokenList; import gudusoft.gsqlparser.nodes.TJoin; import gudusoft.gsqlparser.nodes.TJoinItem; import gudusoft.gsqlparser.nodes.TTable; import gudusoft.gsqlparser.nodes.TTableList; import gudusoft.gsqlparser.stmt.TCreateTableSqlStatement; import gudusoft.gsqlparser.stmt.TInsertSqlStatement; import gudusoft.gsqlparser.stmt.TSelectSqlStatement; import gudusoft.gsqlparser.stmt.TUpdateSqlStatement; import nl.hugojanssen.sqlgraph.model.ParseResult; import nl.hugojanssen.sqlgraph.model.sql.EClauseType; import org.apache.log4j.Logger; /** * Labels all tables in a SQL statement as SOURCE or TARGET, depending on their role in the statement. This applies to * from and joins only. Tables that are used in i.e. where conditions are not considered relevant for data lineage. The * following statement types are currently supported: <br/> * <br/> * - INSERT <br/> * - UPDATE <br/> * * @author hjanssen */ public class TableVisitor extends /*TParseTreeVisitor*/SQLVisitor { /** The logger */ private final static Logger LOG = Logger.getLogger( TableVisitor.class ); /** Is the next table a SOURCE or TARGET table? */ private EClauseType currRole; /** * @param aInterface */ public TableVisitor( VisitorListener aInterface ) { super( aInterface ); // this.parent = aInterface; } @Override public void preVisit( TInsertSqlStatement statement ) { this.currRole = EClauseType.TARGET; } @Override public void preVisit( TJoin join ) { int type = join.getKind(); switch ( type ) { case TBaseType.join_source_fake: // LOG.info( "FAKE" ); // LOG.info( join ); join.getTable().accept( this ); break; case TBaseType.join_source_join: // LOG.info( "SOURCE J" ); // LOG.info( join ); break; case TBaseType.join_source_table: // LOG.info( "SOURCE T" ); //LOG.info( join ); join.getTable().accept( this ); //join.getJoinItems().accept( this ); break; default: LOG.warn( "Unexpected join type: " + type + ", " + join ); break; } } @Override public void preVisit( TJoinItem joinItem ) { // LOG.info( "PRE joinItem" ); int kind = joinItem.getKind(); switch ( kind ) { case TBaseType.join_source_table: // LOG.info( "joinItem ST" ); //LOG.info( joinItem ); joinItem.getTable().accept( this ); break; case TBaseType.join_source_join: // LOG.info( "joinItem SJ" ); //joinItem.getJoin().accept( this ); break; default: LOG.warn( "Unknown TJoinItem kind: " + kind ); break; } } @Override public void preVisit( TSelectSqlStatement statement ) { this.currRole = EClauseType.SOURCE; } @Override public void preVisit( TTable table ) { // LOG.debug( "TABLE: " + table.getTableType() ); ETableSource type = table.getTableType(); switch ( type ) { case objectname: this.addParseResult( table ); break; case subquery: table.getSubquery().accept( this ); break; default: LOG.warn( "Unsupported TTable type: " + type ); break; } } public void analyzeTableList( TTableList tableList ) { this.currRole = EClauseType.SOURCE; for ( int i = 1; i < tableList.size(); i++ ) { tableList.getTable( i ).accept( this ); } } @Override public void preVisit( TUpdateSqlStatement statement ) { this.currRole = EClauseType.TARGET; } private void setTableRole( TSourceTokenList list ) { if ( TVisitorUtil.containsTempToken( list ) ) { this.currRole = EClauseType.TEMP_TARGET; } else { this.currRole = EClauseType.TARGET; } } @Override public void preVisit( TCreateTableSqlStatement statement ) { this.setTableRole( statement.sourcetokenlist ); TTable target = statement.getTargetTable(); target.accept( this ); } /* @Override public void preVisit( TCreateIndexSqlStatement statement ) { LOG.debug( "Skip TCreateIndexSqlStatement on table " + statement.getTableName() ); // statement.accept( null ); } @Override public void preVisit( TDropIndexSqlStatement statement ) { LOG.warn( "Skip TDropIndexSqlStatement on table " + statement.getIndexName() ); } */ @Override public void postVisit( TUpdateSqlStatement statement ) { this.analyzeTableList( statement.tables ); } /** * Creates a new ParseResult from the TTable object and passes it to the parent interface. * * @param table */ private void addParseResult( TTable table ) { ParseResult result = new ParseResult( this, table.getPrefixSchema(), table.getName(), this.currRole, table.getLineNo(), table.getColumnNo() ); LOG.debug( "### " + result ); super.getListener().update( result ); } }
mit
mirazmac/Saika
system/core/Session.php
2093
<?php /** * Saika - The PHP Framework for KIDS * * The Session Wrapper Class * * @version 1.0 * @since 1.0 */ class Session { /** * Start the session if not started already * * @return */ public static function start() { if (session_id() == '') { session_start(); } } /** * Close the session * * @return */ public static function close() { session_write_close(); } /** * Set a key, value to session array * * @param mixed $key The Key * @param mixed $value The Value */ public static function set($key, $value = '') { $_SESSION[$key] = $value; } /** * Get a value from session array by its key * * @param mixed $key The key * @param mixed $default Fall-back/default value to return * @return mixed */ public static function get($key, $default = false) { if (isset($_SESSION[$key])) return $_SESSION[$key]; return $default; } /** * Unset a session key * * @param mixed $key The key * @return */ public static function remove($key) { unset($_SESSION[$key]); } /** * adds a value as a new array element to the key. * useful for collecting error messages etc * * @param mixed $key * @param mixed $value */ public static function add($key, $value) { $_SESSION[$key][] = $value; } /** * Destroy the session completely * * @return */ public static function destroy() { session_destroy(); } /** * Regenerate the session ID * * @param boolean $destroy Whether to destroy the session or not. * Defaults to FALSE * @return */ public static function regenerate($destroy = false) { session_regenerate_id($destroy); } }
mit
antimattr/shipment-tracking
src/AntiMattr/ShipmentTracking/Exception/InvalidException.php
624
<?php /* * This file is part of the AntiMattr Shipment Tracking Library, a library by Matthew Fitzgerald. * * (c) 2015 Matthew Fitzgerald * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace AntiMattr\ShipmentTracking\Exception; /** * @author Matthew Fitzgerald <matthewfitz@gmail.com> */ class InvalidException extends AbstractShipmentTrackingException { private $data; public function setData($data) { $this->data = $data; } public function getData() { return $this->data; } }
mit
kompyang/UnityGamePlayPocketLab
LeapMotionTest/Assets/LeapMotion/Modules/InteractionEngine/Scripts/Editor/InteractionBehaviourEditor.cs
9109
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Query; using UnityEditor; using UnityEngine; namespace Leap.Unity.Interaction { [CanEditMultipleObjects] [CustomEditor(typeof(InteractionBehaviour), editorForChildClasses: true)] public class InteractionBehaviourEditor : CustomEditorBase<InteractionBehaviour> { private EnumEventTableEditor _tableEditor; protected override void OnEnable() { base.OnEnable(); // Interaction Manager hookup. specifyCustomDecorator("_manager", drawInteractionManagerDecorator); deferProperty("_eventTable"); specifyCustomDrawer("_eventTable", drawEventTable); specifyConditionalDrawing(() => !targets.Query().All(intObj => intObj.ignoreContact), "_contactForceMode"); specifyConditionalDrawing(() => !targets.Query().All(intObj => intObj.ignoreGrasping), "_allowMultiGrasp", "_moveObjectWhenGrasped", "graspedMovementType", "graspHoldWarpingEnabled__curIgnored"); // Layer Overrides specifyConditionalDrawing(() => targets.Query().Any(intObj => intObj.overrideInteractionLayer), "_interactionLayer"); specifyCustomDecorator("_interactionLayer", drawInteractionLayerDecorator); specifyConditionalDrawing(() => targets.Query().Any(intObj => intObj.overrideNoContactLayer), "_noContactLayer"); specifyCustomDecorator("_noContactLayer", drawNoContactLayerDecorator); } private void drawInteractionManagerDecorator(SerializedProperty property) { bool shouldDrawInteractionManagerNotSetWarning = false; foreach (var target in targets) { if (PrefabUtility.GetPrefabType(target) == PrefabType.Prefab) continue; if (target.manager == null) { shouldDrawInteractionManagerNotSetWarning = true; break; } } if (shouldDrawInteractionManagerNotSetWarning) { bool pluralTargets = targets.Length > 1; string noManagerSetWarningMessage = ""; if (pluralTargets) { noManagerSetWarningMessage = "One or more of the currently selected interaction " + "objects doesn't have its Interaction Manager set. "; } else { noManagerSetWarningMessage = "The currently selected interaction object doesn't " + "have its Interaction Manager set. "; } noManagerSetWarningMessage += " Object validation requires a configured manager " + "property."; drawSetManagerWarningBox(noManagerSetWarningMessage, MessageType.Error); } } private void drawSetManagerWarningBox(string warningMessage, MessageType messageType) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.HelpBox(warningMessage, messageType); Rect buttonRect = EditorGUILayout.GetControlRect(GUILayout.MaxWidth(100F), GUILayout.ExpandHeight(true), GUILayout.MaxHeight(40F)); InteractionManager manager = InteractionManager.instance; EditorGUI.BeginDisabledGroup(manager == null); if (GUI.Button(buttonRect, new GUIContent("Auto-Fix", manager == null ? "Please add an Interaction Manager to " + "your scene." : "Use InteractionManager.instance to " + "automatically set the manager of the " + "selected interaction objects."))) { if (manager == null) { Debug.LogError("Attempt to find an InteractionManager instance failed. Is there " + "an InteractionManager in your scene?"); } else { foreach (var target in targets) { if (PrefabUtility.GetPrefabType(target) == PrefabType.Prefab) continue; Undo.RecordObject(target, "Auto-set Interaction Manager"); target.manager = manager; } } } EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); } private void drawInteractionLayerDecorator(SerializedProperty property) { bool shouldDrawWarning = false; foreach (var target in targets) { if (target.manager == null) continue; // Can't check. if (target.overrideInteractionLayer && !target.manager.autoGenerateLayers && Physics.GetIgnoreLayerCollision(target.interactionLayer.layerIndex, target.manager.contactBoneLayer.layerIndex)) { shouldDrawWarning = true; break; } } if (shouldDrawWarning) { bool pluralTargets = targets.Length > 1; string message; if (pluralTargets) { message = "One or more of the selected interaction objects has its " + "Interaction layer set NOT to collide with the contact bone " + "layer. "; } else { message = "The selected interaction object has its Interaction layer set " + "NOT to collide with the contact bone layer. "; } message += "This will prevent an interaction object from supporting contact with " + "any hands or controllers."; EditorGUILayout.HelpBox(message, MessageType.Warning); } } private void drawNoContactLayerDecorator(SerializedProperty property) { bool shouldDrawCollisionWarning = false; foreach (var target in targets) { if (target.manager == null) continue; // Can't check. if (target.overrideNoContactLayer && !target.manager.autoGenerateLayers && !Physics.GetIgnoreLayerCollision(target.noContactLayer.layerIndex, target.manager.contactBoneLayer.layerIndex)) { shouldDrawCollisionWarning = true; break; } } if (shouldDrawCollisionWarning) { bool pluralTargets = targets.Length > 1; string noContactErrorMessage; if (pluralTargets) { noContactErrorMessage = "One or more selected interaction objects has its No " + "Contact layer set to collide with the contact bone " + "layer. "; } else { noContactErrorMessage = "This interaction object has its No Contact layer set " + "to collide with the contact bone layer. "; } noContactErrorMessage += "Please ensure the Interaction Manager's contact bone " + "layer is set not to collide with any interaction " + "object's No Contact layer."; EditorGUILayout.HelpBox(noContactErrorMessage, MessageType.Error); } } public override void OnInspectorGUI() { checkHasColliders(); base.OnInspectorGUI(); } private void checkHasColliders() { bool anyMissingColliders = false; foreach (var singleTarget in targets) { if (singleTarget.GetComponentsInChildren<Collider>().Length == 0) { anyMissingColliders = true; break; } } if (anyMissingColliders) { bool pluralObjects = targets.Length > 1; string message; if (pluralObjects) { message = "One or more of the currently selected interaction objects have no " + "colliders. Interaction objects without any Colliders cannot be " + "interacted with."; } else { message = "This interaction object has no Colliders. Interaction objects " + "without any Colliders cannot be interacted with."; } EditorGUILayout.HelpBox(message, MessageType.Warning); } } private void drawEventTable(SerializedProperty property) { if (_tableEditor == null) { _tableEditor = new EnumEventTableEditor(property, typeof(InteractionBehaviour.EventType)); } _tableEditor.DoGuiLayout(); } } }
mit
inaturalist/inaturalist
spec/lib/darwin_core/simple_multimedia_spec.rb
2294
# frozen_string_literal: true require "spec_helper" describe DarwinCore::SimpleMultimedia do elastic_models( Observation, Taxon ) let( :o ) { make_research_grade_observation } let( :photo ) do first_photo = o.photos.first first_photo.update( license: Photo::CC_BY ) DarwinCore::SimpleMultimedia.adapt( first_photo, observation: o ) end it "should return StillImage for dwc_type" do expect( photo.dwc_type ).to eq "StillImage" end it "should return MIME type for format" do expect( photo.format ).to eq "image/jpeg" end it "should return original_url for identifier if available" do expect( photo.original_url ).not_to be_blank expect( photo.identifier ).to eq photo.original_url end it "should return photo page URL for references" do expect( photo.references ).to eq photo.native_page_url end # it "should return EXIF date_time_original for created" it "should return user name for creator" do expect( photo.creator ).to eq photo.user.name end it "should return user login for creator if name blank" do photo.update( native_realname: nil ) photo.user.update( name: nil ) expect( photo.creator ).to eq photo.user.login end it "should return iNaturalist for publisher of LocalPhoto" do expect( photo.publisher ).to eq "iNaturalist" end # getting these to work would require more stubbing than I'm up for right now it "should return Flickr for publisher of FlickrPhoto" it "should return Facebook for publisher of FacebookPhoto" it "should return Picasa for publisher of PicasaPhoto" it "should return CC license URI for dwc_license" do expect( photo.dwc_license ).to match( /creativecommons.org/ ) end it "should return user name for rightsHolder" do expect( photo.rightsHolder ).to eq photo.user.name end it "should return user login for rightsHolder if name blank" do photo.update( native_realname: "" ) photo.user.update( name: "" ) photo.reload expect( photo.native_realname ).to be_blank expect( photo.user.name ).to be_blank expect( photo.rightsHolder ).not_to be_blank expect( photo.rightsHolder ).to eq photo.user.login end it "should return photo ID as the catalogNumber" do expect( photo.catalogNumber ).to eq photo.id end end
mit
vaughanbrittonsage/device_wizard
lib/device_wizard/resolvers/internet_explorer.rb
865
# frozen_string_literal: true module DeviceWizard module Resolvers class InternetExplorer < Base NAME = 'Internet Explorer' KEYWORD = 'msie' KEYWORD2 = ' rv:' REGEX = Regexp.new('msie ([0-9]+.[0-9])') REGEX2 = Regexp.new('rv:([0-9]+.[0-9])') def get_version(user_agent) user_agent.downcase! result = UNKNOWN return result = $1 if REGEX =~ user_agent return result = $1 if REGEX2 =~ user_agent end def identify(user_agent) user_agent.downcase! unless user_agent.include? KEYWORD return unless user_agent.include? KEYWORD2 end result = details_klass.new result.name = NAME result.version = get_version(user_agent) result end def details_klass Details::Browser end end end end
mit
hikrishn/ssu-starter-kit-master
node_modules/vuelidate/src/params.js
1335
const stack = [] // exported for tests export let target = null export const _setTarget = x => { target = x } export function pushParams () { if (target !== null) { stack.push(target) } target = {} } export function popParams () { const lastTarget = target const newTarget = target = stack.pop() || null if (newTarget) { if (!Array.isArray(newTarget.$sub)) { newTarget.$sub = [] } newTarget.$sub.push(lastTarget) } return lastTarget } function addParams (params) { if (typeof params === 'object' && !Array.isArray(params)) { target = {...target, ...params} } else { throw new Error('params must be an object') } } function withParamsDirect (params, validator) { return withParamsClosure(add => { return function (...args) { add(params) return validator.apply(this, args) } }) } function withParamsClosure (closure) { const validator = closure(addParams) return function (...args) { pushParams() try { return validator.apply(this, args) } finally { popParams() } } } export function withParams (paramsOrClosure, maybeValidator) { if (typeof paramsOrClosure === 'object' && maybeValidator !== undefined) { return withParamsDirect(paramsOrClosure, maybeValidator) } return withParamsClosure(paramsOrClosure) }
mit
msawczyn/EFDesigner
src/Testing/Sandbox/Sandbox_EF6_Test/Entity1.generated.cs
2335
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // // Produced by Entity Framework Visual Editor v3.0.4.7 // Source: https://github.com/msawczyn/EFDesigner // Visual Studio Marketplace: https://marketplace.visualstudio.com/items?itemName=michaelsawczyn.EFDesigner // Documentation: https://msawczyn.github.io/EFDesigner/ // License (MIT): https://github.com/msawczyn/EFDesigner/blob/master/LICENSE // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Runtime.CompilerServices; namespace Sandbox_EF6_Test { public partial class Entity1 { partial void Init(); /// <summary> /// Default constructor /// </summary> public Entity1() { Entity2 = new System.Collections.Generic.HashSet<global::Sandbox_EF6_Test.Entity2>(); Init(); } /************************************************************************* * Properties *************************************************************************/ /// <summary> /// Identity, Indexed, Required /// </summary> [Key] [Required] public int Id { get; set; } /************************************************************************* * Navigation properties *************************************************************************/ /// <summary> /// Backing field for Entity2 /// </summary> protected ICollection<global::Sandbox_EF6_Test.Entity2> _entity2; public virtual ICollection<global::Sandbox_EF6_Test.Entity2> Entity2 { get { return _entity2; } private set { _entity2 = value; } } } }
mit
MESD/JasperReportBundle
InputControl/MultiSelectCheckbox.php
3070
<?php namespace Mesd\Jasper\ReportBundle\InputControl; use Symfony\Component\Form\FormBuilder; /** * Multiselect Checkbox */ class MultiSelectCheckbox extends AbstractReportBundleInputControl { /////////////// // VARIABLES // /////////////// /** * The options list * * @var array */ protected $optionList; ////////////////// // BASE METHODS // ////////////////// /** * Constructor * * @param string $id Input Control Id * @param string $label Input Controls Label * @param string $mandatory Whether an input control is mandatory * @param string $readOnly Whether an input control is read only * @param string $type Input Control Type * @param string $uri Uri of the input control on the report server * @param string $visible Whether an input control is visible * @param object $state State of the input control * @param string $getICFrom How to handle getting the options * @param OptionsHandlerInterface $optionsHandler Symfony Security Context */ public function __construct($id, $label, $mandatory, $readOnly, $type, $uri, $visible, $state, $getICFrom, $optionsHandler) { parent::__construct($id, $label, $mandatory, $readOnly, $type, $uri, $visible, $state, $getICFrom, $optionsHandler); $this->optionList = $this->createOptionList(); } /////////////////////// // IMPLEMENT METHODS // /////////////////////// /** * Convert this field into a symfony form object and attach it the form builder * * @param FormBuilder $formBuilder Form Builder object to attach this input control to * @param mixed $data The data for this input control if available */ public function attachInputToFormBuilder(FormBuilder $formBuilder, $data = null) { //Convert the options to an array for the form builder $choices = array(); $selected = array(); foreach ($this->optionList as $option) { $choices[$option->getId()] = $option->getLabel(); if ($option->getSelected()) { $selected[] = $option->getId(); } } //Add a new multi choice field to the builder $formBuilder->add( $this->id, 'choice', array( 'label' => $this->label, 'choices' => $choices, 'multiple' => true, 'data' => $selected, 'required' => $this->mandatory, 'read_only' => $this->readOnly, 'expanded' => true, 'data_class'=> null ) ); } //////////////////// // CLASS METHODS // //////////////////// /** * Get the generated option list * * @return array The generated option list */ public function getOptionList() { return $this->optionList; } }
mit