code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/usr/bin/python2.7 #-*- coding: utf-8 -*- import numpy as np import gl def testkf(input1,Q,R): print gl.X_i_1 print gl.P_i_1 #rang(1,N) do not contain N K_i = gl.P_i_1 / (gl.P_i_1 + R) X_i = gl.X_i_1 + K_i * (input1 - gl.X_i_1) P_i = gl.P_i_1 - K_i * gl.P_i_1 + Q #print (X[i]) #Update gl.P_i_1 = P_i gl.X_i_1 = X_i return X_i
zharuosi/2017
pythonNRC/modules/testkf.py
Python
mit
379
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PipeMongoShell.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PipeMongoShell.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
BetterExamples/PipeMongoShell
PipeMongoShell/Properties/Resources.Designer.cs
C#
mit
2,786
use {SqliteResult, SqliteConnection}; pub use SqliteTransactionBehavior::{ SqliteTransactionDeferred, SqliteTransactionImmediate, SqliteTransactionExclusive}; /// Options for transaction behavior. See [BEGIN /// TRANSACTION](http://www.sqlite.org/lang_transaction.html) for details. #[derive(Copy)] pub enum SqliteTransactionBehavior { SqliteTransactionDeferred, SqliteTransactionImmediate, SqliteTransactionExclusive, } /// Represents a transaction on a database connection. /// /// ## Note /// /// Transactions will roll back by default. Use the `set_commit` or `commit` methods to commit the /// transaction. /// /// ## Example /// /// ```rust,no_run /// # use rusqlite::{SqliteConnection, SqliteResult}; /// # fn do_queries_part_1(conn: &SqliteConnection) -> SqliteResult<()> { Ok(()) } /// # fn do_queries_part_2(conn: &SqliteConnection) -> SqliteResult<()> { Ok(()) } /// fn perform_queries(conn: &SqliteConnection) -> SqliteResult<()> { /// let tx = try!(conn.transaction()); /// /// try!(do_queries_part_1(conn)); // tx causes rollback if this fails /// try!(do_queries_part_2(conn)); // tx causes rollback if this fails /// /// tx.commit() /// } /// ``` pub struct SqliteTransaction<'conn> { conn: &'conn SqliteConnection, depth: u32, commit: bool, finished: bool, } impl<'conn> SqliteTransaction<'conn> { /// Begin a new transaction. Cannot be nested; see `savepoint` for nested transactions. pub fn new(conn: &SqliteConnection, behavior: SqliteTransactionBehavior) -> SqliteResult<SqliteTransaction> { let query = match behavior { SqliteTransactionDeferred => "BEGIN DEFERRED", SqliteTransactionImmediate => "BEGIN IMMEDIATE", SqliteTransactionExclusive => "BEGIN EXCLUSIVE", }; conn.execute_batch(query).map(|_| { SqliteTransaction{ conn: conn, depth: 0, commit: false, finished: false } }) } /// Starts a new [savepoint](http://www.sqlite.org/lang_savepoint.html), allowing nested /// transactions. /// /// ## Note /// /// Just like outer level transactions, savepoint transactions rollback by default. /// /// ## Example /// /// ```rust,no_run /// # use rusqlite::{SqliteConnection, SqliteResult}; /// # fn perform_queries_part_1_succeeds(conn: &SqliteConnection) -> bool { true } /// fn perform_queries(conn: &SqliteConnection) -> SqliteResult<()> { /// let tx = try!(conn.transaction()); /// /// { /// let sp = try!(tx.savepoint()); /// if perform_queries_part_1_succeeds(conn) { /// try!(sp.commit()); /// } /// // otherwise, sp will rollback /// } /// /// tx.commit() /// } /// ``` pub fn savepoint<'a>(&'a self) -> SqliteResult<SqliteTransaction<'a>> { self.conn.execute_batch("SAVEPOINT sp").map(|_| { SqliteTransaction{ conn: self.conn, depth: self.depth + 1, commit: false, finished: false } }) } /// Returns whether or not the transaction is currently set to commit. pub fn will_commit(&self) -> bool { self.commit } /// Returns whether or not the transaction is currently set to rollback. pub fn will_rollback(&self) -> bool { !self.commit } /// Set the transaction to commit at its completion. pub fn set_commit(&mut self) { self.commit = true } /// Set the transaction to rollback at its completion. pub fn set_rollback(&mut self) { self.commit = false } /// A convenience method which consumes and commits a transaction. pub fn commit(mut self) -> SqliteResult<()> { self.commit_() } fn commit_(&mut self) -> SqliteResult<()> { self.finished = true; self.conn.execute_batch(if self.depth == 0 { "COMMIT" } else { "RELEASE sp" }) } /// A convenience method which consumes and rolls back a transaction. pub fn rollback(mut self) -> SqliteResult<()> { self.rollback_() } fn rollback_(&mut self) -> SqliteResult<()> { self.finished = true; self.conn.execute_batch(if self.depth == 0 { "ROLLBACK" } else { "ROLLBACK TO sp" }) } /// Consumes the transaction, committing or rolling back according to the current setting /// (see `will_commit`, `will_rollback`). /// /// Functionally equivalent to the `Drop` implementation, but allows callers to see any /// errors that occur. pub fn finish(mut self) -> SqliteResult<()> { self.finish_() } fn finish_(&mut self) -> SqliteResult<()> { match (self.finished, self.commit) { (true, _) => Ok(()), (false, true) => self.commit_(), (false, false) => self.rollback_(), } } } #[unsafe_destructor] #[allow(unused_must_use)] impl<'conn> Drop for SqliteTransaction<'conn> { fn drop(&mut self) { self.finish_(); } } #[cfg(test)] mod test { extern crate test; use SqliteConnection; fn checked_memory_handle() -> SqliteConnection { let db = SqliteConnection::open_in_memory().unwrap(); db.execute_batch("CREATE TABLE foo (x INTEGER)").unwrap(); db } #[test] fn test_drop() { let db = checked_memory_handle(); { let _tx = db.transaction().unwrap(); db.execute_batch("INSERT INTO foo VALUES(1)").unwrap(); // default: rollback } { let mut tx = db.transaction().unwrap(); db.execute_batch("INSERT INTO foo VALUES(2)").unwrap(); tx.set_commit() } { let _tx = db.transaction().unwrap(); assert_eq!(2i32, db.query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0))); } } #[test] fn test_explicit_rollback_commit() { let db = checked_memory_handle(); { let tx = db.transaction().unwrap(); db.execute_batch("INSERT INTO foo VALUES(1)").unwrap(); tx.rollback().unwrap(); } { let tx = db.transaction().unwrap(); db.execute_batch("INSERT INTO foo VALUES(2)").unwrap(); tx.commit().unwrap(); } { let _tx = db.transaction().unwrap(); assert_eq!(2i32, db.query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0))); } } #[test] fn test_savepoint() { let db = checked_memory_handle(); { let mut tx = db.transaction().unwrap(); db.execute_batch("INSERT INTO foo VALUES(1)").unwrap(); tx.set_commit(); { let mut sp1 = tx.savepoint().unwrap(); db.execute_batch("INSERT INTO foo VALUES(2)").unwrap(); sp1.set_commit(); { let sp2 = sp1.savepoint().unwrap(); db.execute_batch("INSERT INTO foo VALUES(4)").unwrap(); // will rollback sp2 { let sp3 = sp2.savepoint().unwrap(); db.execute_batch("INSERT INTO foo VALUES(8)").unwrap(); sp3.commit().unwrap(); // committed sp3, but will be erased by sp2 rollback } } } } assert_eq!(3i32, db.query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0))); } #[bench] fn test_no_transaction_insert(bencher: &mut test::Bencher) { let db = checked_memory_handle(); let mut stmt = db.prepare("INSERT INTO foo VALUES(1)").unwrap(); bencher.iter(|| { for _ in 0i32 .. 1000 { stmt.execute(&[]).unwrap(); } }) } #[bench] fn test_transaction_insert(bencher: &mut test::Bencher) { let db = checked_memory_handle(); let mut stmt = db.prepare("INSERT INTO foo VALUES(1)").unwrap(); bencher.iter(|| { let mut tx = db.transaction().unwrap(); tx.set_commit(); for _ in 0i32 .. 1000 { stmt.execute(&[]).unwrap(); } }) } }
huonw/rusqlite
src/transaction.rs
Rust
mit
8,307
using System; using System.Collections.Generic; using System.Text; namespace Nucleo.Web.EventsManagement { public class ProviderErrorEvent : WebMonitoringEventBase { private const string EVENT_MESSAGE = "An error occurred within the provider '{0}', with an exception of: {1}"; private const int EVENT_CODE = 100101; #region " Constructors " public ProviderErrorEvent(Type providerType, object source, Exception ex) : base(string.Format(EVENT_MESSAGE, providerType.FullName, ex.ToString()), source, EVENT_CODE) { } #endregion } }
brianmains/Nucleo.NET
src/Nucleo.Web/Web/EventsManagement/ProviderErrorEvent.cs
C#
mit
550
version https://git-lfs.github.com/spec/v1 oid sha256:e63ec89c8bce1f67a79c0a8042e7ad0f2197f9bf615c88fd1ce36266c4050e1b size 5126
yogeshsaroya/new-cdnjs
ajax/libs/backbone.layoutmanager/0.7.0/backbone.layoutmanager.min.js
JavaScript
mit
129
<?php use Illuminate\Database\Seeder; use App\System\System; /** * @author Setiadi, 20 Agustus 2017 */ class RoleUserTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('t_role_user')->delete(); DB::table('t_role_user')->insert([ [ 'user_id' => 1, 'role_id' => 1, 'flg_default' => 'Y', 'create_datetime' => System::dateTime(), 'update_datetime' => System::dateTime(), 'create_user_id' => -99, 'update_user_id' => -99 ], [ 'user_id' => 2, 'role_id' => 2, 'flg_default' => 'Y', 'create_datetime' => System::dateTime(), 'update_datetime' => System::dateTime(), 'create_user_id' => -99, 'update_user_id' => -99 ] ]); } }
setiadi01/Office-Attendance-System-Rest
database/seeds/RoleUserTableSeeder.php
PHP
mit
917
<html><body> <h4>Windows 10 x64 (18362.116)</h4><br> <h2>_HMAP_ENTRY</h2> <font face="arial"> +0x000 BlockOffset : Uint8B<br> +0x008 PermanentBinAddress : Uint8B<br> +0x010 MemAlloc : Uint4B<br> </font></body></html>
epikcraw/ggool
public/Windows 10 x64 (18362.116)/_HMAP_ENTRY.html
HTML
mit
237
class AndroidController < ApplicationController def index end def create app = RailsPushNotifications::GCMApp.new app.gcm_key = params[:gcm_api_key] app.save if app.save notif = app.notifications.build( destinations: [params[:destination]], data: { text: params[:message] } ) if notif.save app.push_notifications notif.reload flash[:notice] = "Notification successfully pushed through!. Results #{notif.results.success} succeded, #{notif.results.failed} failed" redirect_to :android_index else flash.now[:error] = notif.errors.full_messages render :index end else flash.now[:error] = app.errors.full_messages render :index end end end
calonso/rails_push_notifications_test
app/controllers/android_controller.rb
Ruby
mit
776
module tsp { export interface IDOMBinder { attributes?: { [name: string]: string; }; contentEditable?: bool; dynamicAttributes?: { [name: string]: { (el: IElX): string; }; }; dynamicClasses?: { [name: string]: { (el: IElX): bool; }; }; dynamicStyles?: { [name: string]: { (el: IElX): string; }; }; classes?: string[]; id?: string; kids?: IRenderable[]; kidsGet? (el: IElX): IElX[]; styles?: { [name: string]: string; }; tag?: string; //Inner Content - used if textGet is null text?: string; //Dynamic Inner Content textGet? (el: IElX): string; //child elements - used if kidsGet is null toggleKidsOnParentClick?: bool; collapsed?: bool; dataContext?: any; selectSettings?: ISelectBinder; container?: any; onNotifyAddedToDom? (el: IElX): any; } export interface IRenderable { parentElement: IRenderable; doRender(context: IRenderContext); ID: string; } export interface IElX extends IRenderable { bindInfo: IDOMBinder; //parentElement: IElX; //doRender(context: IRenderContext); //ID: string; el: HTMLElement; kidElements: IElX[]; selected: bool; _rendered: bool; innerRender(settings: IRenderContextProps); removeClass(className: string); ensureClass(className: string); } export interface IRenderContext { output: string; elements: IElX[]; settings: IRenderContextProps; } export interface ISelectBinder { //static selected?: bool; //dynamic selectGet? (elX: IElX): bool; selectSet? (elX: IElX, newVal: bool): void; group?: string; selClassName?: string; partialSelClassName?: string; unselClassName?: string; conformWithParent?: bool; } export interface IListenForTopic { topicName: string; conditionForNotification? (tEvent: ITopicEvent): bool; callback(tEvent: ITopicEvent): void; /** element extension listening for the event */ elX?: IElX; elXID?: string; } export interface ITopicEvent extends IListenForTopic { topicEvent: Event; } export interface IRenderContextProps { targetDomID?: string; targetDom?: HTMLElement; } }
bahrus/teaspoon
TypeStrictTests/Interface_ElX.ts
TypeScript
mit
2,489
package ee.tuleva.onboarding.user.exception; public class UserAlreadyAMemberException extends RuntimeException { public UserAlreadyAMemberException(String message) { super(message); } }
TulevaEE/onboarding-service
src/main/java/ee/tuleva/onboarding/user/exception/UserAlreadyAMemberException.java
Java
mit
196
namespace ImageGallery.Data.Common.Models { using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public abstract class BaseModel<TKey> : IAuditInfo, IDeletableEntity { public DateTime CreatedOn { get; set; } public DateTime? DeletedOn { get; set; } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public TKey Id { get; set; } [Index] public bool IsDeleted { get; set; } public DateTime? ModifiedOn { get; set; } } }
atanas-georgiev/ImageGallery
src/ImageGallery.Data.Common/Models/BaseModel{TKey}.cs
C#
mit
581
package org.psliwa.idea.composerJson.util import java.net.{HttpURLConnection, URL} import scala.io.{Codec, Source} import scala.util.Try object IO { def loadUrl(uri: String): Try[String] = { Try { val connection = new URL(uri).openConnection() match { case c: HttpURLConnection => c.setConnectTimeout(5000) c.setReadTimeout(15000) // packages list might be very heavy, take it enough time to complete c.setRequestProperty("User-Agent", "idea-composer-plugin") c case c => c } val in = Source.fromInputStream(connection.getInputStream, Codec.UTF8.charSet.name()) try { in.getLines().mkString } finally { in.close() } } } }
psliwa/idea-composer-plugin
src/main/scala/org/psliwa/idea/composerJson/util/IO.scala
Scala
mit
746
<!--main content start--> <section id="main-content"> <section class="wrapper"> <!--overview start--> <div class="row"> <div class="col-lg-12"> <h3 class="page-header"><i class="fa fa-laptop"></i> 한글제품 현재사용내역</h3> </div> </div> <br/> <div class="row"> <div class="col-lg-12"> <section class="panel"> <header class="panel-heading"> 목록 </header> <table class="table table-striped table-advance table-hover"> <thead> <tr> <th scope="col">사용자</th> <th scope="col">제품명</th> <th scope="col">버전</th> <th scope="col">제조사</th> </tr> </thead> <tbody> <?php foreach ($use_hangul as $lt) { ?> <tr> <td> <b><?php echo $lt->user_name; ?></b> </td> <td> <?php echo $lt->product_number; ?> </td> <td> <?php echo $lt->gian_num; ?> </td> <td> <?php echo $lt->duration; ?> </td> </tr> <?php } ?> </tbody> </table> </div> </section>
jangmac/CodeIgniter
application/views/list/computational/using_soft/use_hangul.php
PHP
mit
1,961
//----------------------------------------- // Grunt configuration //----------------------------------------- module.exports = function(grunt) { // Init config grunt.initConfig({ // environment constant ngconstant: { options: { space: ' ', name: 'envConstant', dest: 'public/js/envConstant.js' }, dev: { constants: { ENV: { appURI: 'http://localhost:3000/', instagramClientId: 'yourDevClientId' } } }, prod:{ constants: { ENV: { appURI: 'http://instalurker-andreavitali.rhcloud.com/', instagramClientId: 'yourProdClientId' } } } }, // concat concat: { options: { separator: ';' // useful for following uglify }, app: { src: 'public/js/**/*.js', dest: 'public/instalurker.js' }, vendor: { src: ['public/vendor/jquery.min.js','public/vendor/angular.min.js','public/vendor/*.min.js'], // order is important! dest: 'public/vendor.min.js' } }, // uglify (only app JS because vendor's are already minified) uglify: { options: { mangle: false }, app: { src: 'public/instalurker.js', dest: 'public/instalurker.min.js', ext: '.min.js' } }, // CSS minification cssmin: { prod: { files: { 'public/stylesheets/app.min.css' : ['public/stylesheets/app.css'] } } }, // Change index.html to use minified files targethtml: { prod: { files: { 'public/index.html': 'public/index.html' } } } // SASS compilation made by IDE }); // Load plugins grunt.loadNpmTasks('grunt-ng-constant'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-targethtml'); // Dev task grunt.registerTask('dev', ['ngconstant:dev']); // no // Default (prod) task grunt.registerTask('default', ['ngconstant:prod','concat:vendor','concat:app','uglify:app','cssmin','targethtml']); }
andreavitali/instalurker
gruntfile.js
JavaScript
mit
2,712
<ul class="usersMedium clearit" id="users" odd="1"> <li ng-repeat="friend in friends" ng-class="{ first: $first, odd: ($index + 1) % 2 }" class="user friend" id="r4_{{friend.id}}"> <div class="userContainer"> <div id="hcard-reframe-music" class="vcard"> <strong> <a ng-href="{{friend.url}}" title="{{friend.realname}}, {{friend.age}}, {{friend.country|country}}"> <span class="userImage"> <img height="64" width="64" alt="" ng-src="{{friend.image.medium}}" /> </span> {{friend.name}} </a> </strong> <p class="info"> <strong class="fn">{{friend.realname || friend.name}}</strong>, {{friend.age || '–'}}, {{friend.country|country}} </p> </div> <p class="lastTrack"> Last track: <a ng-href="{{friend.recenttrack.artist.url}}">{{friend.recenttrack.artist.name}}</a> – <a ng-href="{{friend.recenttrack.url}}">{{friend.recenttrack.name}}</a> </p> </div> <form action="friends" method="post"> <input name="formtoken" type="hidden" value="eda4ce4635e8dc41a544e5150d83211e0d9ac562"/> <input type="hidden" name="id" value="38256316" class="friend" /> <a class="delete"> <img class="icon dismiss_icon" width="16" height="16" src="http://cdn.last.fm/flatness/clear.gif" style="" /> </a> </form> </li> <!-- <li class="findfriends" ng-class="{odd: friends.length % 2}"> <div class="userContainer"> <a href="/findfriends" class="icon"> <img class="icon act_befriended_icon" width="20" height="20" src="http://cdn.last.fm/flatness/clear.gif" style="" /> </a> <h2>Friend Finder</h2> <p><a href="/findfriends">Find more friends on Last.fm</a></p> </div> </li> --> </ul>
jessethegame/lastfm
src/app/lastfm/views/user/friends/gallery.tpl.html
HTML
mit
1,805
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 4.1.1; ru-kz; HTC_Butterfly Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="../circle.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 4.1.1; ru-kz; HTC_Butterfly Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">HTC</td><td>Butterfly</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59">Detail</a> <!-- Modal Structure --> <div id="modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (Linux; U; Android 4.1.1; ru-kz; HTC_Butterfly Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 [family] => HTC Butterfly [brand] => HTC [model] => Butterfly ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.1</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.0156</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-47a9cd06-e213-4882-bc34-db6aed664223">Detail</a> <!-- Modal Structure --> <div id="modal-47a9cd06-e213-4882-bc34-db6aed664223" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapFull result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.1.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?4.1* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 4.1 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [isfake] => [isanonymized] => [ismodified] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td><td>Android 4.0</td><td><i class="material-icons">close</i></td><td>Android </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-42bb56ba-b834-47c5-bea0-c0270e9ab371">Detail</a> <!-- Modal Structure --> <div id="modal-42bb56ba-b834-47c5-bea0-c0270e9ab371" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapLite result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => unknown [browser_bits] => 0 [browser_maker] => unknown [browser_modus] => unknown [version] => 4.0 [majorver] => 0 [minorver] => 0 [platform] => Android [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => false [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => unknown [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td><td>Android 4.0</td><td><i class="material-icons">close</i></td><td>Android </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.0468</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68">Detail</a> <!-- Modal Structure --> <div id="modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => unknown [browser_bits] => 0 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a> <!-- Modal Structure --> <div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td>AndroidOS 4.1.1</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a> <!-- Modal Structure --> <div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>JenssegersAgent result detail</h4> <p><pre><code class="php">Array ( [browserName] => Safari [browserVersion] => 4.0 [osName] => AndroidOS [osVersion] => 4.1.1 [deviceModel] => HTC [isMobile] => 1 [isRobot] => [botName] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555">HTC</td><td>HTL21</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.2652</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a> <!-- Modal Structure --> <div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 1920 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => HTC [mobile_model] => HTL21 [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 4.1.1 [is_ios] => [producer] => Google Inc. [operating_system] => Android 4.1.x Jelly Bean [mobile_screen_width] => 1080 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td>Android Browser </td><td>WebKit </td><td>Android 4.1</td><td style="border-left: 1px solid #555">HTC</td><td>Butterfly</td><td>smartphone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a> <!-- Modal Structure --> <div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 4.1 [platform] => ) [device] => Array ( [brand] => HT [brandName] => HTC [model] => Butterfly [device] => 1 [deviceName] => smartphone ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => 1 [isTablet] => [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ec1cd248-02b0-457e-8a9d-35bb99af008c">Detail</a> <!-- Modal Structure --> <div id="modal-ec1cd248-02b0-457e-8a9d-35bb99af008c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.1.1; ru-kz; HTC_Butterfly Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => [isFacebookWebView:Sinergi\BrowserDetector\Browser:private] => [isCompatibilityMode:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 4.1.1 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.1.1; ru-kz; HTC_Butterfly Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.1.1; ru-kz; HTC_Butterfly Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td>Android 4.1.1</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555">HTC</td><td>Butterfly</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a> <!-- Modal Structure --> <div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 4 [minor] => 1 [patch] => 1 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 4 [minor] => 1 [patch] => 1 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => HTC [model] => Butterfly [family] => HTC Butterfly ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 4.1.1; ru-kz; HTC_Butterfly Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td>Safari 534.30</td><td>WebKit 534.30</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.1404</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a> <!-- Modal Structure --> <div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [platform_name] => HTC [platform_version] => 03 [platform_type] => Mobile [browser_name] => Safari [browser_version] => 534.30 [engine_name] => WebKit [engine_version] => 534.30 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.078</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee">Detail</a> <!-- Modal Structure --> <div id="modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 4.1.1 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => Russian [agent_languageTag] => ru-kz ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>Android Browser 4.0</td><td>WebKit 534.30</td><td>Android 4.1.1</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.2496</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a> <!-- Modal Structure --> <div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android (Jelly Bean) [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => HTC [extra_info_table] => stdClass Object ( [System Build] => JRO03C ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => Jelly Bean [simple_operating_platform_string] => HTC [is_abusive] => [layout_engine_version] => 534.30 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Jelly Bean) [operating_system_version_full] => 4.1.1 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 4.1.1; ru-kz; HTC_Butterfly Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td>Android Browser </td><td>Webkit 534.30</td><td>Android 4.1.1</td><td style="border-left: 1px solid #555">HTC</td><td>J Butterfly</td><td>mobile:smart</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a> <!-- Modal Structure --> <div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 534.30 ) [os] => Array ( [name] => Android [version] => 4.1.1 ) [device] => Array ( [type] => mobile [subtype] => smart [manufacturer] => HTC [model] => J Butterfly ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9">Detail</a> <!-- Modal Structure --> <div id="modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 4.1.1 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td>Android Webkit 4.1.1</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555">HTC</td><td>HTL21</td><td>Smartphone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.0156</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a> <!-- Modal Structure --> <div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => true [is_mobile] => true [is_robot] => false [is_smartphone] => true [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 4.1.1 [advertised_browser] => Android Webkit [advertised_browser_version] => 4.1.1 [complete_device_name] => HTC HTL21 (Butterfly) [device_name] => HTC Butterfly [form_factor] => Smartphone [is_phone] => true [is_app_webview] => false ) [all] => Array ( [brand_name] => HTC [model_name] => HTL21 [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => http://uaprof.vtext.com/pcd/adr6435/adr6435.xml [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 4.1 [pointing_method] => touchscreen [release_date] => 2012_november [marketing_name] => Butterfly [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => true [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => none [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 1080 [resolution_height] => 1920 [columns] => 60 [max_image_width] => 360 [max_image_height] => 640 [rows] => 40 [physical_screen_width] => 63 [physical_screen_height] => 111 [dual_orientation] => true [density_class] => 3.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => true [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => true [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 3600 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => apple_live_streaming [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => true [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => true [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.1.1</td><td style="border-left: 1px solid #555">HTC</td><td>Butterfly</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a> <!-- Modal Structure --> <div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Zsxsoft result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [link] => http://developer.android.com/reference/android/webkit/package-summary.html [title] => Android Webkit 4.0 [name] => Android Webkit [version] => 4.0 [code] => android-webkit [image] => img/16/browser/android-webkit.png ) [os] => Array ( [link] => http://www.android.com/ [name] => Android [version] => 4.1.1 [code] => android [x64] => [title] => Android 4.1.1 [type] => os [dir] => os [image] => img/16/os/android.png ) [device] => Array ( [link] => http://en.wikipedia.org/wiki/High_Tech_Computer_Corporation [title] => HTC Butterfly [model] => Butterfly [brand] => HTC [code] => htc [dir] => device [type] => device [image] => img/16/device/htc.png ) [platform] => Array ( [link] => http://en.wikipedia.org/wiki/High_Tech_Computer_Corporation [title] => HTC Butterfly [model] => Butterfly [brand] => HTC [code] => htc [dir] => device [type] => device [image] => img/16/device/htc.png ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-05-10 07:50:57</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
ThaDafinser/UserAgentParserComparison
v5/user-agent-detail/08/f5/08f5720a-3ad9-4782-b701-7e1790cacdf4.html
HTML
mit
56,671
<?php namespace Smath\VentasBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Smath\VentasBundle\Entity\Pedido; use Smath\VentasBundle\Form\PedidoType; /** * Pedido controller. * * @Route("/pedido") */ class PedidoController extends Controller { /** * Lists all Pedido entities. * * @Route("/", name="pedido") * @Method("GET") * @Template() */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('SmathVentasBundle:Pedido')->findAll(); return array( 'entities' => $entities, ); } /** * Lists all Pedido entities. * * @Route("/list", name="pedido_list") * @Method("GET") */ public function listAction(Request $request) { $em = $this->getDoctrine()->getManager(); $qb = $em->getRepository('SmathVentasBundle:Pedido')->createQueryBuilder('p') ->add('select','p.id, p.fechaCreacion, p.fechaEntrega, pv.nombre as puntoVenta, e.nombre as empleado, c.razonSocial') ->leftJoin('p.puntoVenta','pv') ->leftJoin('pv.cliente', 'c') ->leftJoin('p.usuario','u') ->leftJoin('u.empleado','e'); $fields = array ( 'id' => 'p.id', 'fechaCreacion' => 'p.fechaCreacion', 'fechaEntrega' => 'p.fechaEntrega', 'empleado' => 'empleado', 'puntoVenta' => 'puntoVenta', 'empleado' => 'e.nombre', 'cliente' => 'c.razonSocial', ); $paginator = $this->get('knp_paginator'); $r = $this->get('smath_helpers')->jqGridJson($request, $em, $qb, $fields, $paginator); $response = new Response(); return $response->setContent($r); } /** * Creates a new Pedido entity. * * @Route("/", name="pedido_create") * @Method("POST") * @Template("SmathVentasBundle:Pedido:new.html.twig") */ public function createAction(Request $request) { $entity = new Pedido(); $entity->setFechaCreacion(new \DateTime()); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('pedido_edit', array('id' => $entity->getId()))); } return array( 'entity' => $entity, 'form' => $form->createView() ); } /** * Creates a form to create a Pedido entity. * * @param Pedido $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(Pedido $entity) { $form = $this->createForm(new PedidoType(), $entity, array( 'action' => $this->generateUrl('pedido_create'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Create')); return $form; } /** * Displays a form to create a new Pedido entity. * * @Route("/new", name="pedido_new") * @Method("GET") * @Template() */ public function newAction() { $entity = new Pedido(); $form = $this->createCreateForm($entity); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Finds and displays a Pedido entity. * * @Route("/{id}", name="pedido_show") * @Method("GET") * @Template() */ public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Pedido entity.'); } $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), ); } /** * Displays a form to edit an existing Pedido entity. * * @Route("/{id}/edit", name="pedido_edit") * @Method("GET") * @Template() */ public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Pedido entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), 'pedidoId' => $entity->getId() ); } /** * Creates a form to edit a Pedido entity. * * @param Pedido $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(Pedido $entity) { $form = $this->createForm(new PedidoType(), $entity, array( 'action' => $this->generateUrl('pedido_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; } /** * Edits an existing Pedido entity. * * @Route("/{id}", name="pedido_update") * @Method("PUT") * @Template("SmathVentasBundle:Pedido:edit.html.twig") */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Pedido entity.'); } $deleteForm = $this->createDeleteForm($id); $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { $em->flush(); return $this->redirect($this->generateUrl('pedido')); } return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Deletes a Pedido entity. * * @Route("/{id}", name="pedido_delete") * @Method("DELETE") */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Pedido entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('pedido')); } /** * Creates a form to delete a Pedido entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('pedido_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete')) ->getForm() ; } }
rsuarezdeveloper/smath
src/Smath/VentasBundle/Controller/PedidoController.php
PHP
mit
7,983
package com.backusnaurparser.helper; import java.io.PrintStream; import java.io.PrintWriter; /** * Runtime Exception thrown when something goes wrong with parsing the EBNF * grammar. A reason is always given (automatically printed via every * printStackTrace(...) permutation) * * @author Dominik Horn * */ public class LanguageParseException extends RuntimeException { private static final long serialVersionUID = 1L; private String reason; public LanguageParseException() { this("Unknown cause"); } public LanguageParseException(String reason) { this.reason = reason; } @Override public void printStackTrace() { super.printStackTrace(); System.err.println("\nReason: " + this.reason); } @Override public void printStackTrace(PrintStream s) { super.printStackTrace(s); s.println("\nReason: " + this.reason); } @Override public void printStackTrace(PrintWriter s) { super.printStackTrace(s); s.print("\nReason: " + this.reason); } }
DominikHorn/FormalLanguageParser
src/com/backusnaurparser/helper/LanguageParseException.java
Java
mit
981
<div id="wrap"> <header data-bind="compose: { view: 'nav' }"></header> <section class="container" data-bind="router: { transition: 'entrance', cacheViews: true }"> </section> <div id="push"></div> </div> <div id="footer"> </div>
ddisalvo/FreeDB
Source/Web/App/views/shell.html
HTML
mit
247
require 'spec_helper' describe Skywriter::Resource::CloudFormation::Authentication do it "is a Resource" do expect(Skywriter::Resource::CloudFormation::Authentication.new('name')).to be_a(Skywriter::Resource) end describe "#as_json" do it "allows the user to define the keyspace" do resource = Skywriter::Resource::CloudFormation::Authentication.new( 'name', Foo: { access_key_id: 'some kind of key' }, Bar: { access_key_id: 'some other kind of key' } ) expect(resource.as_json).to eq( { 'name' => { 'Type' => "AWS::CloudFormation::Authentication", 'Foo' => { 'accessKeyId' => 'some kind of key', }, 'Bar' => { 'accessKeyId' => 'some other kind of key', }, 'DependsOn' => [], } } ) end end end
otherinbox/skywriter
spec/skywriter/resource/cloud_formation/authentication_spec.rb
Ruby
mit
937
/*! * vue-i18n v9.0.0-beta.13 * (c) 2020 kazuya kawaguchi * Released under the MIT License. */ import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue'; /** * Original Utilities * written by kazuya kawaguchi */ const inBrowser = typeof window !== 'undefined'; let mark; let measure; { const perf = inBrowser && window.performance; if (perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures) { mark = (tag) => perf.mark(tag); measure = (name, startTag, endTag) => { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); }; } } const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g; /* eslint-disable */ function format(message, ...args) { if (args.length === 1 && isObject(args[0])) { args = args[0]; } if (!args || !args.hasOwnProperty) { args = {}; } return message.replace(RE_ARGS, (match, identifier) => { return args.hasOwnProperty(identifier) ? args[identifier] : ''; }); } const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; /** @internal */ const makeSymbol = (name) => hasSymbol ? Symbol(name) : name; /** @internal */ const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source }); /** @internal */ const friendlyJSONstringify = (json) => JSON.stringify(json) .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') .replace(/\u0027/g, '\\u0027'); const isNumber = (val) => typeof val === 'number' && isFinite(val); const isDate = (val) => toTypeString(val) === '[object Date]'; const isRegExp = (val) => toTypeString(val) === '[object RegExp]'; const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0; function warn(msg, err) { if (typeof console !== 'undefined') { const label = 'vue-i18n' ; console.warn(`[${label}] ` + msg); /* istanbul ignore if */ if (err) { console.warn(err.stack); } } } let _globalThis; const getGlobalThis = () => { // prettier-ignore return (_globalThis || (_globalThis = typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {})); }; function escapeHtml(rawText) { return rawText .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); } /* eslint-enable */ /** * Useful Utilites By Evan you * Modified by kazuya kawaguchi * MIT License * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts */ const isArray = Array.isArray; const isFunction = (val) => typeof val === 'function'; const isString = (val) => typeof val === 'string'; const isBoolean = (val) => typeof val === 'boolean'; const isObject = (val) => // eslint-disable-line val !== null && typeof val === 'object'; const objectToString = Object.prototype.toString; const toTypeString = (value) => objectToString.call(value); const isPlainObject = (val) => toTypeString(val) === '[object Object]'; // for converting list and named values to displayed strings. const toDisplayString = (val) => { return val == null ? '' : isArray(val) || (isPlainObject(val) && val.toString === objectToString) ? JSON.stringify(val, null, 2) : String(val); }; const RANGE = 2; function generateCodeFrame(source, start = 0, end = source.length) { const lines = source.split(/\r?\n/); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start) { for (let j = i - RANGE; j <= i + RANGE || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`); const lineLength = lines[j].length; if (j === i) { // push underline const pad = start - (count - lineLength) + 1; const length = Math.max(1, end > count ? lineLength - pad : end - start); res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + '^'.repeat(length)); } count += lineLength + 1; } } break; } } return res.join('\n'); } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, basedir, module) { return module = { path: basedir, exports: {}, require: function (path, base) { return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); } }, fn(module, module.exports), module.exports; } function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); } var env = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.hook = exports.target = exports.isBrowser = void 0; exports.isBrowser = typeof navigator !== 'undefined'; exports.target = exports.isBrowser ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : {}; exports.hook = exports.target.__VUE_DEVTOOLS_GLOBAL_HOOK__; }); var _const = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.ApiHookEvents = void 0; var ApiHookEvents; (function (ApiHookEvents) { ApiHookEvents["SETUP_DEVTOOLS_PLUGIN"] = "devtools-plugin:setup"; })(ApiHookEvents = exports.ApiHookEvents || (exports.ApiHookEvents = {})); }); var api = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); }); var app = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); }); var component = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); }); var context = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); }); var hooks = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.Hooks = void 0; var Hooks; (function (Hooks) { Hooks["TRANSFORM_CALL"] = "transformCall"; Hooks["GET_APP_RECORD_NAME"] = "getAppRecordName"; Hooks["GET_APP_ROOT_INSTANCE"] = "getAppRootInstance"; Hooks["REGISTER_APPLICATION"] = "registerApplication"; Hooks["WALK_COMPONENT_TREE"] = "walkComponentTree"; Hooks["WALK_COMPONENT_PARENTS"] = "walkComponentParents"; Hooks["INSPECT_COMPONENT"] = "inspectComponent"; Hooks["GET_COMPONENT_BOUNDS"] = "getComponentBounds"; Hooks["GET_COMPONENT_NAME"] = "getComponentName"; Hooks["GET_ELEMENT_COMPONENT"] = "getElementComponent"; Hooks["GET_INSPECTOR_TREE"] = "getInspectorTree"; Hooks["GET_INSPECTOR_STATE"] = "getInspectorState"; })(Hooks = exports.Hooks || (exports.Hooks = {})); }); var api$1 = createCommonjsModule(function (module, exports) { var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); __exportStar(api, exports); __exportStar(app, exports); __exportStar(component, exports); __exportStar(context, exports); __exportStar(hooks, exports); }); var lib = createCommonjsModule(function (module, exports) { var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.setupDevtoolsPlugin = void 0; __exportStar(api$1, exports); function setupDevtoolsPlugin(pluginDescriptor, setupFn) { if (env.hook) { env.hook.emit(_const.ApiHookEvents.SETUP_DEVTOOLS_PLUGIN, pluginDescriptor, setupFn); } else { const list = env.target.__VUE_DEVTOOLS_PLUGINS__ = env.target.__VUE_DEVTOOLS_PLUGINS__ || []; list.push({ pluginDescriptor, setupFn }); } } exports.setupDevtoolsPlugin = setupDevtoolsPlugin; }); const pathStateMachine = []; pathStateMachine[0 /* BEFORE_PATH */] = { ["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */], ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */], ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */], ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */] }; pathStateMachine[1 /* IN_PATH */] = { ["w" /* WORKSPACE */]: [1 /* IN_PATH */], ["." /* DOT */]: [2 /* BEFORE_IDENT */], ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */], ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */] }; pathStateMachine[2 /* BEFORE_IDENT */] = { ["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */], ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */], ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */] }; pathStateMachine[3 /* IN_IDENT */] = { ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */], ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */], ["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */], ["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */], ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */], ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */] }; pathStateMachine[4 /* IN_SUB_PATH */] = { ["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */], ["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */], ["[" /* LEFT_BRACKET */]: [ 4 /* IN_SUB_PATH */, 2 /* INC_SUB_PATH_DEPTH */ ], ["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */], ["o" /* END_OF_FAIL */]: 8 /* ERROR */, ["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */] }; pathStateMachine[5 /* IN_SINGLE_QUOTE */] = { ["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */], ["o" /* END_OF_FAIL */]: 8 /* ERROR */, ["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */] }; pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = { ["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */], ["o" /* END_OF_FAIL */]: 8 /* ERROR */, ["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */] }; /** * Check if an expression is a literal value. */ const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/; function isLiteral(exp) { return literalValueRE.test(exp); } /** * Strip quotes from a string */ function stripQuotes(str) { const a = str.charCodeAt(0); const b = str.charCodeAt(str.length - 1); return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; } /** * Determine the type of a character in a keypath. */ function getPathCharType(ch) { if (ch === undefined || ch === null) { return "o" /* END_OF_FAIL */; } const code = ch.charCodeAt(0); switch (code) { case 0x5b: // [ case 0x5d: // ] case 0x2e: // . case 0x22: // " case 0x27: // ' return ch; case 0x5f: // _ case 0x24: // $ case 0x2d: // - return "i" /* IDENT */; case 0x09: // Tab (HT) case 0x0a: // Newline (LF) case 0x0d: // Return (CR) case 0xa0: // No-break space (NBSP) case 0xfeff: // Byte Order Mark (BOM) case 0x2028: // Line Separator (LS) case 0x2029: // Paragraph Separator (PS) return "w" /* WORKSPACE */; } return "i" /* IDENT */; } /** * Format a subPath, return its plain form if it is * a literal string or number. Otherwise prepend the * dynamic indicator (*). */ function formatSubPath(path) { const trimmed = path.trim(); // invalid leading 0 if (path.charAt(0) === '0' && isNaN(parseInt(path))) { return false; } return isLiteral(trimmed) ? stripQuotes(trimmed) : "*" /* ASTARISK */ + trimmed; } /** * Parse a string path into an array of segments */ function parse(path) { const keys = []; let index = -1; let mode = 0 /* BEFORE_PATH */; let subPathDepth = 0; let c; let key; // eslint-disable-line let newChar; let type; let transition; let action; let typeMap; const actions = []; actions[0 /* APPEND */] = () => { if (key === undefined) { key = newChar; } else { key += newChar; } }; actions[1 /* PUSH */] = () => { if (key !== undefined) { keys.push(key); key = undefined; } }; actions[2 /* INC_SUB_PATH_DEPTH */] = () => { actions[0 /* APPEND */](); subPathDepth++; }; actions[3 /* PUSH_SUB_PATH */] = () => { if (subPathDepth > 0) { subPathDepth--; mode = 4 /* IN_SUB_PATH */; actions[0 /* APPEND */](); } else { subPathDepth = 0; if (key === undefined) { return false; } key = formatSubPath(key); if (key === false) { return false; } else { actions[1 /* PUSH */](); } } }; function maybeUnescapeQuote() { const nextChar = path[index + 1]; if ((mode === 5 /* IN_SINGLE_QUOTE */ && nextChar === "'" /* SINGLE_QUOTE */) || (mode === 6 /* IN_DOUBLE_QUOTE */ && nextChar === "\"" /* DOUBLE_QUOTE */)) { index++; newChar = '\\' + nextChar; actions[0 /* APPEND */](); return true; } } while (mode !== null) { index++; c = path[index]; if (c === '\\' && maybeUnescapeQuote()) { continue; } type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */; // check parse error if (transition === 8 /* ERROR */) { return; } mode = transition[0]; if (transition[1] !== undefined) { action = actions[transition[1]]; if (action) { newChar = c; if (action() === false) { return; } } } // check parse finish if (mode === 7 /* AFTER_PATH */) { return keys; } } } // path token cache const cache = new Map(); function resolveValue(obj, path) { // check object if (!isObject(obj)) { return null; } // parse path let hit = cache.get(path); if (!hit) { hit = parse(path); if (hit) { cache.set(path, hit); } } // check hit if (!hit) { return null; } // resolve path value const len = hit.length; let last = obj; let i = 0; while (i < len) { const val = last[hit[i]]; if (val === undefined) { return null; } last = val; i++; } return last; } const DEFAULT_MODIFIER = (str) => str; const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line const DEFAULT_MESSAGE_DATA_TYPE = 'text'; const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join(''); const DEFAULT_INTERPOLATE = toDisplayString; function pluralDefault(choice, choicesLength) { choice = Math.abs(choice); if (choicesLength === 2) { // prettier-ignore return choice ? choice > 1 ? 1 : 0 : 1; } return choice ? Math.min(choice, 2) : 0; } function getPluralIndex(options) { // prettier-ignore const index = isNumber(options.pluralIndex) ? options.pluralIndex : -1; // prettier-ignore return options.named && (isNumber(options.named.count) || isNumber(options.named.n)) ? isNumber(options.named.count) ? options.named.count : isNumber(options.named.n) ? options.named.n : index : index; } function normalizeNamed(pluralIndex, props) { if (!props.count) { props.count = pluralIndex; } if (!props.n) { props.n = pluralIndex; } } function createMessageContext(options = {}) { const locale = options.locale; const pluralIndex = getPluralIndex(options); const pluralRule = isObject(options.pluralRules) && isString(locale) && isFunction(options.pluralRules[locale]) ? options.pluralRules[locale] : pluralDefault; const orgPluralRule = isObject(options.pluralRules) && isString(locale) && isFunction(options.pluralRules[locale]) ? pluralDefault : undefined; const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)]; const _list = options.list || []; const list = (index) => _list[index]; // eslint-disable-next-line @typescript-eslint/no-explicit-any const _named = options.named || {}; isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named); const named = (key) => _named[key]; // TODO: need to design resolve message function? function message(key) { // prettier-ignore const msg = isFunction(options.messages) ? options.messages(key) : isObject(options.messages) ? options.messages[key] : false; return !msg ? options.parent ? options.parent.message(key) // resolve from parent messages : DEFAULT_MESSAGE : msg; } const _modifier = (name) => options.modifiers ? options.modifiers[name] : DEFAULT_MODIFIER; const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize) ? options.processor.normalize : DEFAULT_NORMALIZE; const interpolate = isPlainObject(options.processor) && isFunction(options.processor.interpolate) ? options.processor.interpolate : DEFAULT_INTERPOLATE; const type = isPlainObject(options.processor) && isString(options.processor.type) ? options.processor.type : DEFAULT_MESSAGE_DATA_TYPE; const ctx = { ["list" /* LIST */]: list, ["named" /* NAMED */]: named, ["plural" /* PLURAL */]: plural, ["linked" /* LINKED */]: (key, modifier) => { // TODO: should check `key` const msg = message(key)(ctx); return isString(modifier) ? _modifier(modifier)(msg) : msg; }, ["message" /* MESSAGE */]: message, ["type" /* TYPE */]: type, ["interpolate" /* INTERPOLATE */]: interpolate, ["normalize" /* NORMALIZE */]: normalize }; return ctx; } /** @internal */ const errorMessages = { // tokenizer error messages [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`, [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`, [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`, [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`, [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`, [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`, [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`, [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`, [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`, [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`, // parser error messages [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`, [11 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'` }; /** @internal */ function createCompileError(code, loc, optinos = {}) { const { domain, messages, args } = optinos; const msg = format((messages || errorMessages)[code] || '', ...(args || [])) ; const error = new SyntaxError(String(msg)); error.code = code; if (loc) { error.location = loc; } error.domain = domain; return error; } /** @internal */ function defaultOnError(error) { throw error; } function createPosition(line, column, offset) { return { line, column, offset }; } function createLocation(start, end, source) { const loc = { start, end }; if (source != null) { loc.source = source; } return loc; } const CHAR_SP = ' '; const CHAR_CR = '\r'; const CHAR_LF = '\n'; const CHAR_LS = String.fromCharCode(0x2028); const CHAR_PS = String.fromCharCode(0x2029); function createScanner(str) { const _buf = str; let _index = 0; let _line = 1; let _column = 1; let _peekOffset = 0; const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF; const isLF = (index) => _buf[index] === CHAR_LF; const isPS = (index) => _buf[index] === CHAR_PS; const isLS = (index) => _buf[index] === CHAR_LS; const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index); const index = () => _index; const line = () => _line; const column = () => _column; const peekOffset = () => _peekOffset; const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset]; const currentChar = () => charAt(_index); const currentPeek = () => charAt(_index + _peekOffset); function next() { _peekOffset = 0; if (isLineEnd(_index)) { _line++; _column = 0; } if (isCRLF(_index)) { _index++; } _index++; _column++; return _buf[_index]; } function peek() { if (isCRLF(_index + _peekOffset)) { _peekOffset++; } _peekOffset++; return _buf[_index + _peekOffset]; } function reset() { _index = 0; _line = 1; _column = 1; _peekOffset = 0; } function resetPeek(offset = 0) { _peekOffset = offset; } function skipToPeek() { const target = _index + _peekOffset; // eslint-disable-next-line no-unmodified-loop-condition while (target !== _index) { next(); } _peekOffset = 0; } return { index, line, column, peekOffset, charAt, currentChar, currentPeek, next, peek, reset, resetPeek, skipToPeek }; } const EOF = undefined; const LITERAL_DELIMITER = "'"; const ERROR_DOMAIN = 'tokenizer'; function createTokenizer(source, options = {}) { const location = !options.location; const _scnr = createScanner(source); const currentOffset = () => _scnr.index(); const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index()); const _initLoc = currentPosition(); const _initOffset = currentOffset(); const _context = { currentType: 14 /* EOF */, offset: _initOffset, startLoc: _initLoc, endLoc: _initLoc, lastType: 14 /* EOF */, lastOffset: _initOffset, lastStartLoc: _initLoc, lastEndLoc: _initLoc, braceNest: 0, inLinked: false, text: '' }; const context = () => _context; const { onError } = options; function emitError(code, pos, offset, ...args) { const ctx = context(); pos.column += offset; pos.offset += offset; if (onError) { const loc = createLocation(ctx.startLoc, pos); const err = createCompileError(code, loc, { domain: ERROR_DOMAIN, args }); onError(err); } } function getToken(context, type, value) { context.endLoc = currentPosition(); context.currentType = type; const token = { type }; if (location) { token.loc = createLocation(context.startLoc, context.endLoc); } if (value != null) { token.value = value; } return token; } const getEndToken = (context) => getToken(context, 14 /* EOF */); function eat(scnr, ch) { if (scnr.currentChar() === ch) { scnr.next(); return ch; } else { emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch); return ''; } } function peekSpaces(scnr) { let buf = ''; while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) { buf += scnr.currentPeek(); scnr.peek(); } return buf; } function skipSpaces(scnr) { const buf = peekSpaces(scnr); scnr.skipToPeek(); return buf; } function isIdentifierStart(ch) { if (ch === EOF) { return false; } const cc = ch.charCodeAt(0); return ((cc >= 97 && cc <= 122) || // a-z (cc >= 65 && cc <= 90)); // A-Z } function isNumberStart(ch) { if (ch === EOF) { return false; } const cc = ch.charCodeAt(0); return cc >= 48 && cc <= 57; // 0-9 } function isNamedIdentifierStart(scnr, context) { const { currentType } = context; if (currentType !== 2 /* BraceLeft */) { return false; } peekSpaces(scnr); const ret = isIdentifierStart(scnr.currentPeek()); scnr.resetPeek(); return ret; } function isListIdentifierStart(scnr, context) { const { currentType } = context; if (currentType !== 2 /* BraceLeft */) { return false; } peekSpaces(scnr); const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek(); const ret = isNumberStart(ch); scnr.resetPeek(); return ret; } function isLiteralStart(scnr, context) { const { currentType } = context; if (currentType !== 2 /* BraceLeft */) { return false; } peekSpaces(scnr); const ret = scnr.currentPeek() === LITERAL_DELIMITER; scnr.resetPeek(); return ret; } function isLinkedDotStart(scnr, context) { const { currentType } = context; if (currentType !== 8 /* LinkedAlias */) { return false; } peekSpaces(scnr); const ret = scnr.currentPeek() === "." /* LinkedDot */; scnr.resetPeek(); return ret; } function isLinkedModifierStart(scnr, context) { const { currentType } = context; if (currentType !== 9 /* LinkedDot */) { return false; } peekSpaces(scnr); const ret = isIdentifierStart(scnr.currentPeek()); scnr.resetPeek(); return ret; } function isLinkedDelimiterStart(scnr, context) { const { currentType } = context; if (!(currentType === 8 /* LinkedAlias */ || currentType === 12 /* LinkedModifier */)) { return false; } peekSpaces(scnr); const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */; scnr.resetPeek(); return ret; } function isLinkedReferStart(scnr, context) { const { currentType } = context; if (currentType !== 10 /* LinkedDelimiter */) { return false; } const fn = () => { const ch = scnr.currentPeek(); if (ch === "{" /* BraceLeft */) { return isIdentifierStart(scnr.peek()); } else if (ch === "@" /* LinkedAlias */ || ch === "%" /* Modulo */ || ch === "|" /* Pipe */ || ch === ":" /* LinkedDelimiter */ || ch === "." /* LinkedDot */ || ch === CHAR_SP || !ch) { return false; } else if (ch === CHAR_LF) { scnr.peek(); return fn(); } else { // other charactors return isIdentifierStart(ch); } }; const ret = fn(); scnr.resetPeek(); return ret; } function isPluralStart(scnr) { peekSpaces(scnr); const ret = scnr.currentPeek() === "|" /* Pipe */; scnr.resetPeek(); return ret; } function isTextStart(scnr, reset = true) { const fn = (hasSpace = false, prev = '', detectModulo = false) => { const ch = scnr.currentPeek(); if (ch === "{" /* BraceLeft */) { return prev === "%" /* Modulo */ ? false : hasSpace; } else if (ch === "@" /* LinkedAlias */ || !ch) { return prev === "%" /* Modulo */ ? true : hasSpace; } else if (ch === "%" /* Modulo */) { scnr.peek(); return fn(hasSpace, "%" /* Modulo */, true); } else if (ch === "|" /* Pipe */) { return prev === "%" /* Modulo */ || detectModulo ? true : !(prev === CHAR_SP || prev === CHAR_LF); } else if (ch === CHAR_SP) { scnr.peek(); return fn(true, CHAR_SP, detectModulo); } else if (ch === CHAR_LF) { scnr.peek(); return fn(true, CHAR_LF, detectModulo); } else { return true; } }; const ret = fn(); reset && scnr.resetPeek(); return ret; } function takeChar(scnr, fn) { const ch = scnr.currentChar(); if (ch === EOF) { return EOF; } if (fn(ch)) { scnr.next(); return ch; } return null; } function takeIdentifierChar(scnr) { const closure = (ch) => { const cc = ch.charCodeAt(0); return ((cc >= 97 && cc <= 122) || // a-z (cc >= 65 && cc <= 90) || // A-Z (cc >= 48 && cc <= 57) || // 0-9 cc === 95 || cc === 36); // _ $ }; return takeChar(scnr, closure); } function takeDigit(scnr) { const closure = (ch) => { const cc = ch.charCodeAt(0); return cc >= 48 && cc <= 57; // 0-9 }; return takeChar(scnr, closure); } function takeHexDigit(scnr) { const closure = (ch) => { const cc = ch.charCodeAt(0); return ((cc >= 48 && cc <= 57) || // 0-9 (cc >= 65 && cc <= 70) || // A-F (cc >= 97 && cc <= 102)); // a-f }; return takeChar(scnr, closure); } function getDigits(scnr) { let ch = ''; let num = ''; while ((ch = takeDigit(scnr))) { num += ch; } return num; } function readText(scnr) { const fn = (buf) => { const ch = scnr.currentChar(); if (ch === "{" /* BraceLeft */ || ch === "}" /* BraceRight */ || ch === "@" /* LinkedAlias */ || !ch) { return buf; } else if (ch === "%" /* Modulo */) { if (isTextStart(scnr)) { buf += ch; scnr.next(); return fn(buf); } else { return buf; } } else if (ch === "|" /* Pipe */) { return buf; } else if (ch === CHAR_SP || ch === CHAR_LF) { if (isTextStart(scnr)) { buf += ch; scnr.next(); return fn(buf); } else if (isPluralStart(scnr)) { return buf; } else { buf += ch; scnr.next(); return fn(buf); } } else { buf += ch; scnr.next(); return fn(buf); } }; return fn(''); } function readNamedIdentifier(scnr) { skipSpaces(scnr); let ch = ''; let name = ''; while ((ch = takeIdentifierChar(scnr))) { name += ch; } if (scnr.currentChar() === EOF) { emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); } return name; } function readListIdentifier(scnr) { skipSpaces(scnr); let value = ''; if (scnr.currentChar() === '-') { scnr.next(); value += `-${getDigits(scnr)}`; } else { value += getDigits(scnr); } if (scnr.currentChar() === EOF) { emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); } return value; } function readLiteral(scnr) { skipSpaces(scnr); eat(scnr, `\'`); let ch = ''; let literal = ''; const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF; while ((ch = takeChar(scnr, fn))) { if (ch === '\\') { literal += readEscapeSequence(scnr); } else { literal += ch; } } const current = scnr.currentChar(); if (current === CHAR_LF || current === EOF) { emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0); // TODO: Is it correct really? if (current === CHAR_LF) { scnr.next(); eat(scnr, `\'`); } return literal; } eat(scnr, `\'`); return literal; } function readEscapeSequence(scnr) { const ch = scnr.currentChar(); switch (ch) { case '\\': case `\'`: scnr.next(); return `\\${ch}`; case 'u': return readUnicodeEscapeSequence(scnr, ch, 4); case 'U': return readUnicodeEscapeSequence(scnr, ch, 6); default: emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch); return ''; } } function readUnicodeEscapeSequence(scnr, unicode, digits) { eat(scnr, unicode); let sequence = ''; for (let i = 0; i < digits; i++) { const ch = takeHexDigit(scnr); if (!ch) { emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`); break; } sequence += ch; } return `\\${unicode}${sequence}`; } function readInvalidIdentifier(scnr) { skipSpaces(scnr); let ch = ''; let identifiers = ''; const closure = (ch) => ch !== "{" /* BraceLeft */ && ch !== "}" /* BraceRight */ && ch !== CHAR_SP && ch !== CHAR_LF; while ((ch = takeChar(scnr, closure))) { identifiers += ch; } return identifiers; } function readLinkedModifier(scnr) { let ch = ''; let name = ''; while ((ch = takeIdentifierChar(scnr))) { name += ch; } return name; } function readLinkedRefer(scnr) { const fn = (detect = false, buf) => { const ch = scnr.currentChar(); if (ch === "{" /* BraceLeft */ || ch === "%" /* Modulo */ || ch === "@" /* LinkedAlias */ || ch === "|" /* Pipe */ || !ch) { return buf; } else if (ch === CHAR_SP) { return buf; } else if (ch === CHAR_LF) { buf += ch; scnr.next(); return fn(detect, buf); } else { buf += ch; scnr.next(); return fn(true, buf); } }; return fn(false, ''); } function readPlural(scnr) { skipSpaces(scnr); const plural = eat(scnr, "|" /* Pipe */); skipSpaces(scnr); return plural; } // TODO: We need refactoring of token parsing ... function readTokenInPlaceholder(scnr, context) { let token = null; const ch = scnr.currentChar(); switch (ch) { case "{" /* BraceLeft */: if (context.braceNest >= 1) { emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0); } scnr.next(); token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */); skipSpaces(scnr); context.braceNest++; return token; case "}" /* BraceRight */: if (context.braceNest > 0 && context.currentType === 2 /* BraceLeft */) { emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0); } scnr.next(); token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); context.braceNest--; context.braceNest > 0 && skipSpaces(scnr); if (context.inLinked && context.braceNest === 0) { context.inLinked = false; } return token; case "@" /* LinkedAlias */: if (context.braceNest > 0) { emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); } token = readTokenInLinked(scnr, context) || getEndToken(context); context.braceNest = 0; return token; default: let validNamedIdentifier = true; let validListIdentifier = true; let validLeteral = true; if (isPluralStart(scnr)) { if (context.braceNest > 0) { emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); } token = getToken(context, 1 /* Pipe */, readPlural(scnr)); // reset context.braceNest = 0; context.inLinked = false; return token; } if (context.braceNest > 0 && (context.currentType === 5 /* Named */ || context.currentType === 6 /* List */ || context.currentType === 7 /* Literal */)) { emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0); context.braceNest = 0; return readToken(scnr, context); } if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) { token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr)); skipSpaces(scnr); return token; } if ((validListIdentifier = isListIdentifierStart(scnr, context))) { token = getToken(context, 6 /* List */, readListIdentifier(scnr)); skipSpaces(scnr); return token; } if ((validLeteral = isLiteralStart(scnr, context))) { token = getToken(context, 7 /* Literal */, readLiteral(scnr)); skipSpaces(scnr); return token; } if (!validNamedIdentifier && !validListIdentifier && !validLeteral) { // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ... token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr)); emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value); skipSpaces(scnr); return token; } break; } return token; } // TODO: We need refactoring of token parsing ... function readTokenInLinked(scnr, context) { const { currentType } = context; let token = null; const ch = scnr.currentChar(); if ((currentType === 8 /* LinkedAlias */ || currentType === 9 /* LinkedDot */ || currentType === 12 /* LinkedModifier */ || currentType === 10 /* LinkedDelimiter */) && (ch === CHAR_LF || ch === CHAR_SP)) { emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); } switch (ch) { case "@" /* LinkedAlias */: scnr.next(); token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */); context.inLinked = true; return token; case "." /* LinkedDot */: skipSpaces(scnr); scnr.next(); return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */); case ":" /* LinkedDelimiter */: skipSpaces(scnr); scnr.next(); return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */); default: if (isPluralStart(scnr)) { token = getToken(context, 1 /* Pipe */, readPlural(scnr)); // reset context.braceNest = 0; context.inLinked = false; return token; } if (isLinkedDotStart(scnr, context) || isLinkedDelimiterStart(scnr, context)) { skipSpaces(scnr); return readTokenInLinked(scnr, context); } if (isLinkedModifierStart(scnr, context)) { skipSpaces(scnr); return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr)); } if (isLinkedReferStart(scnr, context)) { skipSpaces(scnr); if (ch === "{" /* BraceLeft */) { // scan the placeholder return readTokenInPlaceholder(scnr, context) || token; } else { return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr)); } } if (currentType === 8 /* LinkedAlias */) { emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0); } context.braceNest = 0; context.inLinked = false; return readToken(scnr, context); } } // TODO: We need refactoring of token parsing ... function readToken(scnr, context) { let token = { type: 14 /* EOF */ }; if (context.braceNest > 0) { return readTokenInPlaceholder(scnr, context) || getEndToken(context); } if (context.inLinked) { return readTokenInLinked(scnr, context) || getEndToken(context); } const ch = scnr.currentChar(); switch (ch) { case "{" /* BraceLeft */: return readTokenInPlaceholder(scnr, context) || getEndToken(context); case "}" /* BraceRight */: emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0); scnr.next(); return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */); case "@" /* LinkedAlias */: return readTokenInLinked(scnr, context) || getEndToken(context); default: if (isPluralStart(scnr)) { token = getToken(context, 1 /* Pipe */, readPlural(scnr)); // reset context.braceNest = 0; context.inLinked = false; return token; } if (isTextStart(scnr)) { return getToken(context, 0 /* Text */, readText(scnr)); } if (ch === "%" /* Modulo */) { scnr.next(); return getToken(context, 4 /* Modulo */, "%" /* Modulo */); } break; } return token; } function nextToken() { const { currentType, offset, startLoc, endLoc } = _context; _context.lastType = currentType; _context.lastOffset = offset; _context.lastStartLoc = startLoc; _context.lastEndLoc = endLoc; _context.offset = currentOffset(); _context.startLoc = currentPosition(); if (_scnr.currentChar() === EOF) { return getToken(_context, 14 /* EOF */); } return readToken(_scnr, _context); } return { nextToken, currentOffset, currentPosition, context }; } const ERROR_DOMAIN$1 = 'parser'; // Backslash backslash, backslash quote, uHHHH, UHHHHHH. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g; function fromEscapeSequence(match, codePoint4, codePoint6) { switch (match) { case `\\\\`: return `\\`; case `\\\'`: return `\'`; default: { const codePoint = parseInt(codePoint4 || codePoint6, 16); if (codePoint <= 0xd7ff || codePoint >= 0xe000) { return String.fromCodePoint(codePoint); } // invalid ... // Replace them with U+FFFD REPLACEMENT CHARACTER. return '�'; } } } function createParser(options = {}) { const location = !options.location; const { onError } = options; function emitError(tokenzer, code, start, offset, ...args) { const end = tokenzer.currentPosition(); end.offset += offset; end.column += offset; if (onError) { const loc = createLocation(start, end); const err = createCompileError(code, loc, { domain: ERROR_DOMAIN$1, args }); onError(err); } } function startNode(type, offset, loc) { const node = { type, start: offset, end: offset }; if (location) { node.loc = { start: loc, end: loc }; } return node; } function endNode(node, offset, pos, type) { node.end = offset; if (type) { node.type = type; } if (location && node.loc) { node.loc.end = pos; } } function parseText(tokenizer, value) { const context = tokenizer.context(); const node = startNode(3 /* Text */, context.offset, context.startLoc); node.value = value; endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); return node; } function parseList(tokenizer, index) { const context = tokenizer.context(); const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc const node = startNode(5 /* List */, offset, loc); node.index = parseInt(index, 10); tokenizer.nextToken(); // skip brach right endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); return node; } function parseNamed(tokenizer, key) { const context = tokenizer.context(); const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc const node = startNode(4 /* Named */, offset, loc); node.key = key; tokenizer.nextToken(); // skip brach right endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); return node; } function parseLiteral(tokenizer, value) { const context = tokenizer.context(); const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc const node = startNode(9 /* Literal */, offset, loc); node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence); tokenizer.nextToken(); // skip brach right endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); return node; } function parseLinkedModifier(tokenizer) { const token = tokenizer.nextToken(); const context = tokenizer.context(); // check token if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc const node = startNode(8 /* LinkedModifier */, offset, loc); node.value = token.value || ''; endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); return node; } function parseLinkedKey(tokenizer, value) { const context = tokenizer.context(); const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc); node.value = value; endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); return node; } function parseLinked(tokenizer) { const context = tokenizer.context(); const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc); let token = tokenizer.nextToken(); if (token.type === 9 /* LinkedDot */) { linkedNode.modifier = parseLinkedModifier(tokenizer); token = tokenizer.nextToken(); } // asset check token if (token.type !== 10 /* LinkedDelimiter */) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } token = tokenizer.nextToken(); // skip brace left if (token.type === 2 /* BraceLeft */) { token = tokenizer.nextToken(); } switch (token.type) { case 11 /* LinkedKey */: if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } linkedNode.key = parseLinkedKey(tokenizer, token.value || ''); break; case 5 /* Named */: if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } linkedNode.key = parseNamed(tokenizer, token.value || ''); break; case 6 /* List */: if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } linkedNode.key = parseList(tokenizer, token.value || ''); break; case 7 /* Literal */: if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } linkedNode.key = parseLiteral(tokenizer, token.value || ''); break; } endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition()); return linkedNode; } function parseMessage(tokenizer) { const context = tokenizer.context(); const startOffset = context.currentType === 1 /* Pipe */ ? tokenizer.currentOffset() : context.offset; const startLoc = context.currentType === 1 /* Pipe */ ? context.endLoc : context.startLoc; const node = startNode(2 /* Message */, startOffset, startLoc); node.items = []; do { const token = tokenizer.nextToken(); switch (token.type) { case 0 /* Text */: if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } node.items.push(parseText(tokenizer, token.value || '')); break; case 6 /* List */: if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } node.items.push(parseList(tokenizer, token.value || '')); break; case 5 /* Named */: if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } node.items.push(parseNamed(tokenizer, token.value || '')); break; case 7 /* Literal */: if (token.value == null) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type); } node.items.push(parseLiteral(tokenizer, token.value || '')); break; case 8 /* LinkedAlias */: node.items.push(parseLinked(tokenizer)); break; } } while (context.currentType !== 14 /* EOF */ && context.currentType !== 1 /* Pipe */); // adjust message node loc const endOffset = context.currentType === 1 /* Pipe */ ? context.lastOffset : tokenizer.currentOffset(); const endLoc = context.currentType === 1 /* Pipe */ ? context.lastEndLoc : tokenizer.currentPosition(); endNode(node, endOffset, endLoc); return node; } function parsePlural(tokenizer, offset, loc, msgNode) { const context = tokenizer.context(); let hasEmptyMessage = msgNode.items.length === 0; const node = startNode(1 /* Plural */, offset, loc); node.cases = []; node.cases.push(msgNode); do { const msg = parseMessage(tokenizer); if (!hasEmptyMessage) { hasEmptyMessage = msg.items.length === 0; } node.cases.push(msg); } while (context.currentType !== 14 /* EOF */); if (hasEmptyMessage) { emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0); } endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); return node; } function parseResource(tokenizer) { const context = tokenizer.context(); const { offset, startLoc } = context; const msgNode = parseMessage(tokenizer); if (context.currentType === 14 /* EOF */) { return msgNode; } else { return parsePlural(tokenizer, offset, startLoc, msgNode); } } function parse(source) { const tokenizer = createTokenizer(source, { ...options }); const context = tokenizer.context(); const node = startNode(0 /* Resource */, context.offset, context.startLoc); if (location && node.loc) { node.loc.source = source; } node.body = parseResource(tokenizer); // assert wheather achieved to EOF if (context.currentType !== 14 /* EOF */) { emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, context.currentType); } endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition()); return node; } return { parse }; } function createTransformer(ast, options = {} // eslint-disable-line ) { const _context = { ast, helpers: new Set() }; const context = () => _context; const helper = (name) => { _context.helpers.add(name); return name; }; return { context, helper }; } function traverseNodes(nodes, transformer) { for (let i = 0; i < nodes.length; i++) { traverseNode(nodes[i], transformer); } } function traverseNode(node, transformer) { // TODO: if we need pre-hook of transform, should be implemeted to here switch (node.type) { case 1 /* Plural */: traverseNodes(node.cases, transformer); transformer.helper("plural" /* PLURAL */); break; case 2 /* Message */: traverseNodes(node.items, transformer); break; case 6 /* Linked */: const linked = node; traverseNode(linked.key, transformer); transformer.helper("linked" /* LINKED */); break; case 5 /* List */: transformer.helper("interpolate" /* INTERPOLATE */); transformer.helper("list" /* LIST */); break; case 4 /* Named */: transformer.helper("interpolate" /* INTERPOLATE */); transformer.helper("named" /* NAMED */); break; } // TODO: if we need post-hook of transform, should be implemeted to here } // transform AST function transform(ast, options = {} // eslint-disable-line ) { const transformer = createTransformer(ast); transformer.helper("normalize" /* NORMALIZE */); // traverse ast.body && traverseNode(ast.body, transformer); // set meta information const context = transformer.context(); ast.helpers = [...context.helpers]; } function createCodeGenerator(ast, options) { const { sourceMap, filename } = options; const _context = { source: ast.loc.source, filename, code: '', column: 1, line: 1, offset: 0, map: undefined, indentLevel: 0 }; const context = () => _context; function push(code, node) { _context.code += code; } function _newline(n) { push('\n' + ` `.repeat(n)); } function indent() { _newline(++_context.indentLevel); } function deindent(withoutNewLine) { if (withoutNewLine) { --_context.indentLevel; } else { _newline(--_context.indentLevel); } } function newline() { _newline(_context.indentLevel); } const helper = (key) => `_${key}`; return { context, push, indent, deindent, newline, helper }; } function generateLinkedNode(generator, node) { const { helper } = generator; generator.push(`${helper("linked" /* LINKED */)}(`); generateNode(generator, node.key); if (node.modifier) { generator.push(`, `); generateNode(generator, node.modifier); } generator.push(`)`); } function generateMessageNode(generator, node) { const { helper } = generator; generator.push(`${helper("normalize" /* NORMALIZE */)}([`); generator.indent(); const length = node.items.length; for (let i = 0; i < length; i++) { generateNode(generator, node.items[i]); if (i === length - 1) { break; } generator.push(', '); } generator.deindent(); generator.push('])'); } function generatePluralNode(generator, node) { const { helper } = generator; if (node.cases.length > 1) { generator.push(`${helper("plural" /* PLURAL */)}([`); generator.indent(); const length = node.cases.length; for (let i = 0; i < length; i++) { generateNode(generator, node.cases[i]); if (i === length - 1) { break; } generator.push(', '); } generator.deindent(); generator.push(`])`); } } function generateResource(generator, node) { if (node.body) { generateNode(generator, node.body); } else { generator.push('null'); } } function generateNode(generator, node) { const { helper } = generator; switch (node.type) { case 0 /* Resource */: generateResource(generator, node); break; case 1 /* Plural */: generatePluralNode(generator, node); break; case 2 /* Message */: generateMessageNode(generator, node); break; case 6 /* Linked */: generateLinkedNode(generator, node); break; case 8 /* LinkedModifier */: generator.push(JSON.stringify(node.value), node); break; case 7 /* LinkedKey */: generator.push(JSON.stringify(node.value), node); break; case 5 /* List */: generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node); break; case 4 /* Named */: generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node); break; case 9 /* Literal */: generator.push(JSON.stringify(node.value), node); break; case 3 /* Text */: generator.push(JSON.stringify(node.value), node); break; default: { throw new Error(`unhandled codegen node type: ${node.type}`); } } } // generate code from AST const generate = (ast, options = {} // eslint-disable-line ) => { const mode = isString(options.mode) ? options.mode : 'normal'; const filename = isString(options.filename) ? options.filename : 'message.intl'; const sourceMap = isBoolean(options.sourceMap) ? options.sourceMap : false; const helpers = ast.helpers || []; const generator = createCodeGenerator(ast, { mode, filename, sourceMap }); generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`); generator.indent(); if (helpers.length > 0) { generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`); generator.newline(); } generator.push(`return `); generateNode(generator, ast); generator.deindent(); generator.push(`}`); const { code, map } = generator.context(); return { ast, code, map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any }; }; function baseCompile(source, options = {}) { // parse source codes const parser = createParser({ ...options }); const ast = parser.parse(source); // transform ASTs transform(ast, { ...options }); // generate javascript codes return generate(ast, { ...options }); } /** @internal */ const warnMessages = { [0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`, [1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`, [2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`, [3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`, [4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`, [5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.` }; /** @internal */ function getWarnMessage(code, ...args) { return format(warnMessages[code], ...args); } /** @internal */ const NOT_REOSLVED = -1; /** @internal */ const MISSING_RESOLVE_VALUE = ''; function getDefaultLinkedModifiers() { return { upper: (val) => (isString(val) ? val.toUpperCase() : val), lower: (val) => (isString(val) ? val.toLowerCase() : val), // prettier-ignore capitalize: (val) => (isString(val) ? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}` : val) }; } let _compiler; /** @internal */ function registerMessageCompiler(compiler) { _compiler = compiler; } /** @internal */ function createCoreContext(options = {}) { // setup options const locale = isString(options.locale) ? options.locale : 'en-US'; const fallbackLocale = isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || isString(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : locale; const messages = isPlainObject(options.messages) ? options.messages : { [locale]: {} }; const datetimeFormats = isPlainObject(options.datetimeFormats) ? options.datetimeFormats : { [locale]: {} }; const numberFormats = isPlainObject(options.numberFormats) ? options.numberFormats : { [locale]: {} }; const modifiers = Object.assign({}, options.modifiers || {}, getDefaultLinkedModifiers()); const pluralRules = options.pluralRules || {}; const missing = isFunction(options.missing) ? options.missing : null; const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn) ? options.missingWarn : true; const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) ? options.fallbackWarn : true; const fallbackFormat = !!options.fallbackFormat; const unresolving = !!options.unresolving; const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : null; const processor = isPlainObject(options.processor) ? options.processor : null; const warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true; const escapeParameter = !!options.escapeParameter; const messageCompiler = isFunction(options.messageCompiler) ? options.messageCompiler : _compiler; const onWarn = isFunction(options.onWarn) ? options.onWarn : warn; // setup internal options const internalOptions = options; const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters) ? internalOptions.__datetimeFormatters : new Map(); const __numberFormatters = isObject(internalOptions.__numberFormatters) ? internalOptions.__numberFormatters : new Map(); const context = { locale, fallbackLocale, messages, datetimeFormats, numberFormats, modifiers, pluralRules, missing, missingWarn, fallbackWarn, fallbackFormat, unresolving, postTranslation, processor, warnHtmlMessage, escapeParameter, messageCompiler, onWarn, __datetimeFormatters, __numberFormatters }; // for vue-devtools timeline event { context.__emitter = internalOptions.__emitter != null ? internalOptions.__emitter : undefined; } return context; } /** @internal */ function isTranslateFallbackWarn(fallback, key) { return fallback instanceof RegExp ? fallback.test(key) : fallback; } /** @internal */ function isTranslateMissingWarn(missing, key) { return missing instanceof RegExp ? missing.test(key) : missing; } /** @internal */ function handleMissing(context, key, locale, missingWarn, type) { const { missing, onWarn } = context; // for vue-devtools timeline event { const emitter = context.__emitter; if (emitter) { emitter.emit("missing" /* MISSING */, { locale, key, type }); } } if (missing !== null) { const ret = missing(context, locale, key, type); return isString(ret) ? ret : key; } else { if ( isTranslateMissingWarn(missingWarn, key)) { onWarn(getWarnMessage(0 /* NOT_FOUND_KEY */, { key, locale })); } return key; } } /** @internal */ function getLocaleChain(ctx, fallback, start = '') { const context = ctx; if (start === '') { return []; } if (!context.__localeChainCache) { context.__localeChainCache = new Map(); } let chain = context.__localeChainCache.get(start); if (!chain) { chain = []; // first block defined by start let block = [start]; // while any intervening block found while (isArray(block)) { block = appendBlockToChain(chain, block, fallback); } // prettier-ignore // last block defined by default const defaults = isArray(fallback) ? fallback : isPlainObject(fallback) ? fallback['default'] ? fallback['default'] : null : fallback; // convert defaults to array block = isString(defaults) ? [defaults] : defaults; if (isArray(block)) { appendBlockToChain(chain, block, false); } context.__localeChainCache.set(start, chain); } return chain; } function appendBlockToChain(chain, block, blocks) { let follow = true; for (let i = 0; i < block.length && isBoolean(follow); i++) { const locale = block[i]; if (isString(locale)) { follow = appendLocaleToChain(chain, block[i], blocks); } } return follow; } function appendLocaleToChain(chain, locale, blocks) { let follow; const tokens = locale.split('-'); do { const target = tokens.join('-'); follow = appendItemToChain(chain, target, blocks); tokens.splice(-1, 1); } while (tokens.length && follow === true); return follow; } function appendItemToChain(chain, target, blocks) { let follow = false; if (!chain.includes(target)) { follow = true; if (target) { follow = target[target.length - 1] !== '!'; const locale = target.replace(/!/g, ''); chain.push(locale); if ((isArray(blocks) || isPlainObject(blocks)) && blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any ) { // eslint-disable-next-line @typescript-eslint/no-explicit-any follow = blocks[locale]; } } } return follow; } /** @internal */ function updateFallbackLocale(ctx, locale, fallback) { const context = ctx; context.__localeChainCache = new Map(); getLocaleChain(ctx, fallback, locale); } const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/; const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`; function checkHtmlMessage(source, options) { const warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true; if (warnHtmlMessage && RE_HTML_TAG.test(source)) { warn(format(WARN_MESSAGE, { source })); } } const defaultOnCacheKey = (source) => source; let compileCache = Object.create(null); /** @internal */ function compileToFunction(source, options = {}) { { // check HTML message checkHtmlMessage(source, options); // check caches const onCacheKey = options.onCacheKey || defaultOnCacheKey; const key = onCacheKey(source); const cached = compileCache[key]; if (cached) { return cached; } // compile error detecting let occured = false; const onError = options.onError || defaultOnError; options.onError = (err) => { occured = true; onError(err); }; // compile const { code } = baseCompile(source, options); // evaluate function const msg = new Function(`return ${code}`)(); // if occured compile error, don't cache return !occured ? (compileCache[key] = msg) : msg; } } /** @internal */ function createCoreError(code) { return createCompileError(code, null, { messages: errorMessages$1 } ); } /** @internal */ const errorMessages$1 = { [12 /* INVALID_ARGUMENT */]: 'Invalid arguments', [13 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' + 'Make sure your Date represents a valid date.', [14 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string' }; const NOOP_MESSAGE_FUNCTION = () => ''; const isMessageFunction = (val) => isFunction(val); // implementationo of `translate` function /** @internal */ function translate(context, ...args) { const { fallbackFormat, postTranslation, unresolving, fallbackLocale } = context; const [key, options] = parseTranslateArgs(...args); const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn; const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn; const escapeParameter = isBoolean(options.escapeParameter) ? options.escapeParameter : context.escapeParameter; // prettier-ignore const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option ? !isBoolean(options.default) ? options.default : key : fallbackFormat // default by `fallbackFormat` option ? key : ''; const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== ''; const locale = isString(options.locale) ? options.locale : context.locale; // escape params escapeParameter && escapeParams(options); // resolve message format // eslint-disable-next-line prefer-const let [format, targetLocale, message] = resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn); // if you use default message, set it as message format! let cacheBaseKey = key; if (!(isString(format) || isMessageFunction(format))) { if (enableDefaultMsg) { format = defaultMsgOrKey; cacheBaseKey = format; } } // checking message format and target locale if (!(isString(format) || isMessageFunction(format)) || !isString(targetLocale)) { return unresolving ? NOT_REOSLVED : key; } // setup compile error detecting let occured = false; const errorDetector = () => { occured = true; }; // compile message format const msg = compileMessasgeFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector); // if occured compile error, return the message format if (occured) { return format; } // evaluate message with context const ctxOptions = getMessageContextOptions(context, targetLocale, message, options); const msgContext = createMessageContext(ctxOptions); const messaged = evaluateMessage(context, msg, msgContext); // if use post translation option, procee it with handler return postTranslation ? postTranslation(messaged) : messaged; } function escapeParams(options) { if (isArray(options.list)) { options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item); } else if (isObject(options.named)) { Object.keys(options.named).forEach(key => { if (isString(options.named[key])) { options.named[key] = escapeHtml(options.named[key]); } }); } } function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) { const { messages, onWarn } = context; const locales = getLocaleChain(context, fallbackLocale, locale); let message = {}; let targetLocale; let format = null; let from = locale; let to = null; const type = 'translate'; for (let i = 0; i < locales.length; i++) { targetLocale = to = locales[i]; if ( locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) { onWarn(getWarnMessage(1 /* FALLBACK_TO_TRANSLATE */, { key, target: targetLocale })); } // for vue-devtools timeline event if ( locale !== targetLocale) { const emitter = context.__emitter; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type, key, from, to }); } } message = messages[targetLocale] || {}; // for vue-devtools timeline event let start = null; let startTag; let endTag; if ( inBrowser) { start = window.performance.now(); startTag = 'intlify-message-resolve-start'; endTag = 'intlify-message-resolve-end'; mark && mark(startTag); } if ((format = resolveValue(message, key)) === null) { // if null, resolve with object key path format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any } // for vue-devtools timeline event if ( inBrowser) { const end = window.performance.now(); const emitter = context.__emitter; if (emitter && start && format) { emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, { type: "message-resolve" /* MESSAGE_RESOLVE */, key, message: format, time: end - start }); } if (startTag && endTag && mark && measure) { mark(endTag); measure('intlify message resolve', startTag, endTag); } } if (isString(format) || isFunction(format)) break; const missingRet = handleMissing(context, key, targetLocale, missingWarn, type); if (missingRet !== key) { format = missingRet; } from = to; } return [format, targetLocale, message]; } function compileMessasgeFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) { const { messageCompiler, warnHtmlMessage } = context; if (isMessageFunction(format)) { const msg = format; msg.locale = msg.locale || targetLocale; msg.key = msg.key || key; return msg; } // for vue-devtools timeline event let start = null; let startTag; let endTag; if ( inBrowser) { start = window.performance.now(); startTag = 'intlify-message-compilation-start'; endTag = 'intlify-message-compilation-end'; mark && mark(startTag); } const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector)); // for vue-devtools timeline event if ( inBrowser) { const end = window.performance.now(); const emitter = context.__emitter; if (emitter && start) { emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, { type: "message-compilation" /* MESSAGE_COMPILATION */, message: format, time: end - start }); } if (startTag && endTag && mark && measure) { mark(endTag); measure('intlify message compilation', startTag, endTag); } } msg.locale = targetLocale; msg.key = key; msg.source = format; return msg; } function evaluateMessage(context, msg, msgCtx) { // for vue-devtools timeline event let start = null; let startTag; let endTag; if ( inBrowser) { start = window.performance.now(); startTag = 'intlify-message-evaluation-start'; endTag = 'intlify-message-evaluation-end'; mark && mark(startTag); } const messaged = msg(msgCtx); // for vue-devtools timeline event if ( inBrowser) { const end = window.performance.now(); const emitter = context.__emitter; if (emitter && start) { emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, { type: "message-evaluation" /* MESSAGE_EVALUATION */, value: messaged, time: end - start }); } if (startTag && endTag && mark && measure) { mark(endTag); measure('intlify message evaluation', startTag, endTag); } } return messaged; } /** @internal */ function parseTranslateArgs(...args) { const [arg1, arg2, arg3] = args; const options = {}; if (!isString(arg1)) { throw createCoreError(12 /* INVALID_ARGUMENT */); } const key = arg1; if (isNumber(arg2)) { options.plural = arg2; } else if (isString(arg2)) { options.default = arg2; } else if (isPlainObject(arg2) && !isEmptyObject(arg2)) { options.named = arg2; } else if (isArray(arg2)) { options.list = arg2; } if (isNumber(arg3)) { options.plural = arg3; } else if (isString(arg3)) { options.default = arg3; } else if (isPlainObject(arg3)) { Object.assign(options, arg3); } return [key, options]; } function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) { return { warnHtmlMessage, onError: (err) => { errorDetector && errorDetector(err); { const message = `Message compilation error: ${err.message}`; const codeFrame = err.location && generateCodeFrame(source, err.location.start.offset, err.location.end.offset); const emitter = context.__emitter; if (emitter) { emitter.emit("compile-error" /* COMPILE_ERROR */, { message: source, error: err.message, start: err.location && err.location.start.offset, end: err.location && err.location.end.offset }); } console.error(codeFrame ? `${message}\n${codeFrame}` : message); } }, onCacheKey: (source) => generateFormatCacheKey(locale, key, source) }; } function getMessageContextOptions(context, locale, message, options) { const { modifiers, pluralRules } = context; const resolveMessage = (key) => { const val = resolveValue(message, key); if (isString(val)) { let occured = false; const errorDetector = () => { occured = true; }; const msg = compileMessasgeFormat(context, key, locale, val, key, errorDetector); return !occured ? msg : NOOP_MESSAGE_FUNCTION; } else if (isMessageFunction(val)) { return val; } else { // TODO: should be implemented warning message return NOOP_MESSAGE_FUNCTION; } }; const ctxOptions = { locale, modifiers, pluralRules, messages: resolveMessage }; if (context.processor) { ctxOptions.processor = context.processor; } if (options.list) { ctxOptions.list = options.list; } if (options.named) { ctxOptions.named = options.named; } if (isNumber(options.plural)) { ctxOptions.pluralIndex = options.plural; } return ctxOptions; } const intlDefined = typeof Intl !== 'undefined'; const Availabilities = { dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined', numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined' }; // implementation of `datetime` function /** @internal */ function datetime(context, ...args) { const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context; const { __datetimeFormatters } = context; if ( !Availabilities.dateTimeFormat) { onWarn(getWarnMessage(4 /* CANNOT_FORMAT_DATE */)); return MISSING_RESOLVE_VALUE; } const [key, value, options, orverrides] = parseDateTimeArgs(...args); const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn; const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn; const part = !!options.part; const locale = isString(options.locale) ? options.locale : context.locale; const locales = getLocaleChain(context, fallbackLocale, locale); if (!isString(key) || key === '') { return new Intl.DateTimeFormat(locale).format(value); } // resolve format let datetimeFormat = {}; let targetLocale; let format = null; let from = locale; let to = null; const type = 'datetime format'; for (let i = 0; i < locales.length; i++) { targetLocale = to = locales[i]; if ( locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) { onWarn(getWarnMessage(5 /* FALLBACK_TO_DATE_FORMAT */, { key, target: targetLocale })); } // for vue-devtools timeline event if ( locale !== targetLocale) { const emitter = context.__emitter; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type, key, from, to }); } } datetimeFormat = datetimeFormats[targetLocale] || {}; format = datetimeFormat[key]; if (isPlainObject(format)) break; handleMissing(context, key, targetLocale, missingWarn, type); from = to; } // checking format and target locale if (!isPlainObject(format) || !isString(targetLocale)) { return unresolving ? NOT_REOSLVED : key; } let id = `${targetLocale}__${key}`; if (!isEmptyObject(orverrides)) { id = `${id}__${JSON.stringify(orverrides)}`; } let formatter = __datetimeFormatters.get(id); if (!formatter) { formatter = new Intl.DateTimeFormat(targetLocale, Object.assign({}, format, orverrides)); __datetimeFormatters.set(id, formatter); } return !part ? formatter.format(value) : formatter.formatToParts(value); } /** @internal */ function parseDateTimeArgs(...args) { const [arg1, arg2, arg3, arg4] = args; let options = {}; let orverrides = {}; let value; if (isString(arg1)) { // Only allow ISO strings - other date formats are often supported, // but may cause different results in different browsers. if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) { throw createCoreError(14 /* INVALID_ISO_DATE_ARGUMENT */); } value = new Date(arg1); try { // This will fail if the date is not valid value.toISOString(); } catch (e) { throw createCoreError(14 /* INVALID_ISO_DATE_ARGUMENT */); } } else if (isDate(arg1)) { if (isNaN(arg1.getTime())) { throw createCoreError(13 /* INVALID_DATE_ARGUMENT */); } value = arg1; } else if (isNumber(arg1)) { value = arg1; } else { throw createCoreError(12 /* INVALID_ARGUMENT */); } if (isString(arg2)) { options.key = arg2; } else if (isPlainObject(arg2)) { options = arg2; } if (isString(arg3)) { options.locale = arg3; } else if (isPlainObject(arg3)) { orverrides = arg3; } if (isPlainObject(arg4)) { orverrides = arg4; } return [options.key || '', value, options, orverrides]; } /** @internal */ function clearDateTimeFormat(ctx, locale, format) { const context = ctx; for (const key in format) { const id = `${locale}__${key}`; if (!context.__datetimeFormatters.has(id)) { continue; } context.__datetimeFormatters.delete(id); } } // implementation of `number` function /** @internal */ function number(context, ...args) { const { numberFormats, unresolving, fallbackLocale, onWarn } = context; const { __numberFormatters } = context; if ( !Availabilities.numberFormat) { onWarn(getWarnMessage(2 /* CANNOT_FORMAT_NUMBER */)); return MISSING_RESOLVE_VALUE; } const [key, value, options, orverrides] = parseNumberArgs(...args); const missingWarn = isBoolean(options.missingWarn) ? options.missingWarn : context.missingWarn; const fallbackWarn = isBoolean(options.fallbackWarn) ? options.fallbackWarn : context.fallbackWarn; const part = !!options.part; const locale = isString(options.locale) ? options.locale : context.locale; const locales = getLocaleChain(context, fallbackLocale, locale); if (!isString(key) || key === '') { return new Intl.NumberFormat(locale).format(value); } // resolve format let numberFormat = {}; let targetLocale; let format = null; let from = locale; let to = null; const type = 'number format'; for (let i = 0; i < locales.length; i++) { targetLocale = to = locales[i]; if ( locale !== targetLocale && isTranslateFallbackWarn(fallbackWarn, key)) { onWarn(getWarnMessage(3 /* FALLBACK_TO_NUMBER_FORMAT */, { key, target: targetLocale })); } // for vue-devtools timeline event if ( locale !== targetLocale) { const emitter = context.__emitter; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type, key, from, to }); } } numberFormat = numberFormats[targetLocale] || {}; format = numberFormat[key]; if (isPlainObject(format)) break; handleMissing(context, key, targetLocale, missingWarn, type); from = to; } // checking format and target locale if (!isPlainObject(format) || !isString(targetLocale)) { return unresolving ? NOT_REOSLVED : key; } let id = `${targetLocale}__${key}`; if (!isEmptyObject(orverrides)) { id = `${id}__${JSON.stringify(orverrides)}`; } let formatter = __numberFormatters.get(id); if (!formatter) { formatter = new Intl.NumberFormat(targetLocale, Object.assign({}, format, orverrides)); __numberFormatters.set(id, formatter); } return !part ? formatter.format(value) : formatter.formatToParts(value); } /** @internal */ function parseNumberArgs(...args) { const [arg1, arg2, arg3, arg4] = args; let options = {}; let orverrides = {}; if (!isNumber(arg1)) { throw createCoreError(12 /* INVALID_ARGUMENT */); } const value = arg1; if (isString(arg2)) { options.key = arg2; } else if (isPlainObject(arg2)) { options = arg2; } if (isString(arg3)) { options.locale = arg3; } else if (isPlainObject(arg3)) { orverrides = arg3; } if (isPlainObject(arg4)) { orverrides = arg4; } return [options.key || '', value, options, orverrides]; } /** @internal */ function clearNumberFormat(ctx, locale, format) { const context = ctx; for (const key in format) { const id = `${locale}__${key}`; if (!context.__numberFormatters.has(id)) { continue; } context.__numberFormatters.delete(id); } } const DevToolsLabels = { ["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools', ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources', ["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]: 'Vue I18n: Compile Errors', ["vue-i18n-missing" /* TIMELINE_MISSING */]: 'Vue I18n: Missing', ["vue-i18n-fallback" /* TIMELINE_FALLBACK */]: 'Vue I18n: Fallback', ["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]: 'Vue I18n: Performance' }; const DevToolsPlaceholders = { ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...' }; const DevToolsTimelineColors = { ["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]: 0xff0000, ["vue-i18n-missing" /* TIMELINE_MISSING */]: 0xffcd19, ["vue-i18n-fallback" /* TIMELINE_FALLBACK */]: 0xffcd19, ["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]: 0xffcd19 }; const DevToolsTimelineLayerMaps = { ["compile-error" /* COMPILE_ERROR */]: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */, ["missing" /* MISSING */]: "vue-i18n-missing" /* TIMELINE_MISSING */, ["fallback" /* FALBACK */]: "vue-i18n-fallback" /* TIMELINE_FALLBACK */, ["message-resolve" /* MESSAGE_RESOLVE */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */, ["message-compilation" /* MESSAGE_COMPILATION */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */, ["message-evaluation" /* MESSAGE_EVALUATION */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */ }; /** * Event emitter, forked from the below: * - original repository url: https://github.com/developit/mitt * - code url: https://github.com/developit/mitt/blob/master/src/index.ts * - author: Jason Miller (https://github.com/developit) * - license: MIT */ /** * Create a event emitter * * @returns An event emitter */ function createEmitter() { const events = new Map(); const emitter = { events, on(event, handler) { const handlers = events.get(event); const added = handlers && handlers.push(handler); if (!added) { events.set(event, [handler]); } }, off(event, handler) { const handlers = events.get(event); if (handlers) { handlers.splice(handlers.indexOf(handler) >>> 0, 1); } }, emit(event, payload) { (events.get(event) || []) .slice() .map(handler => handler(payload)); (events.get('*') || []) .slice() .map(handler => handler(event, payload)); } }; return emitter; } let devtools; function setDevtoolsHook(hook) { devtools = hook; } function devtoolsRegisterI18n(i18n, version) { if (!devtools) { return; } devtools.emit("intlify:register" /* REGISTER */, i18n, version); } let devtoolsApi; async function enableDevTools(app, i18n) { return new Promise((resolve, reject) => { try { lib.setupDevtoolsPlugin({ id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, label: DevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], app }, api => { devtoolsApi = api; api.on.inspectComponent(payload => { const componentInstance = payload.componentInstance; if (componentInstance.vnode.el.__INTLIFY__ && payload.instanceData) { inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__); } }); api.addInspector({ id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, label: DevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], icon: 'language', treeFilterPlaceholder: DevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] }); api.on.getInspectorTree(payload => { if (payload.app === app && payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { registerScope(payload, i18n); } }); api.on.getInspectorState(payload => { if (payload.app === app && payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { inspectScope(payload, i18n); } }); api.addTimelineLayer({ id: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */, label: DevToolsLabels["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */], color: DevToolsTimelineColors["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */] }); api.addTimelineLayer({ id: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */, label: DevToolsLabels["vue-i18n-performance" /* TIMELINE_PERFORMANCE */], color: DevToolsTimelineColors["vue-i18n-performance" /* TIMELINE_PERFORMANCE */] }); api.addTimelineLayer({ id: "vue-i18n-missing" /* TIMELINE_MISSING */, label: DevToolsLabels["vue-i18n-missing" /* TIMELINE_MISSING */], color: DevToolsTimelineColors["vue-i18n-missing" /* TIMELINE_MISSING */] }); api.addTimelineLayer({ id: "vue-i18n-fallback" /* TIMELINE_FALLBACK */, label: DevToolsLabels["vue-i18n-fallback" /* TIMELINE_FALLBACK */], color: DevToolsTimelineColors["vue-i18n-fallback" /* TIMELINE_FALLBACK */] }); resolve(true); }); } catch (e) { console.error(e); reject(false); } }); } function inspectComposer(instanceData, composer) { const type = 'vue-i18n: composer properties'; instanceData.state.push({ type, key: 'locale', editable: false, value: composer.locale.value }); instanceData.state.push({ type, key: 'availableLocales', editable: false, value: composer.availableLocales }); instanceData.state.push({ type, key: 'fallbackLocale', editable: false, value: composer.fallbackLocale.value }); instanceData.state.push({ type, key: 'inheritLocale', editable: false, value: composer.inheritLocale }); instanceData.state.push({ type, key: 'messages', editable: false, value: composer.messages.value }); instanceData.state.push({ type, key: 'datetimeFormats', editable: false, value: composer.datetimeFormats.value }); instanceData.state.push({ type, key: 'numberFormats', editable: false, value: composer.numberFormats.value }); } function registerScope(payload, i18n) { const children = []; for (const [keyInstance, instance] of i18n.__instances) { // prettier-ignore const composer = i18n.mode === 'composition' ? instance : instance.__composer; const label = keyInstance.type.name || keyInstance.type.displayName || keyInstance.type.__file; children.push({ id: composer.id.toString(), label: `${label} Scope` }); } payload.rootNodes.push({ id: 'global', label: 'Global Scope', children }); } function inspectScope(payload, i18n) { if (payload.nodeId === 'global') { payload.state = makeScopeInspectState(i18n.mode === 'composition' ? i18n.global : i18n.global.__composer); } else { const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === payload.nodeId); if (instance) { const composer = i18n.mode === 'composition' ? instance : instance.__composer; payload.state = makeScopeInspectState(composer); } } } function makeScopeInspectState(composer) { const state = {}; const localeType = 'Locale related info'; const localeStates = [ { type: localeType, key: 'locale', editable: false, value: composer.locale.value }, { type: localeType, key: 'fallbackLocale', editable: false, value: composer.fallbackLocale.value }, { type: localeType, key: 'availableLocales', editable: false, value: composer.availableLocales }, { type: localeType, key: 'inheritLocale', editable: false, value: composer.inheritLocale } ]; state[localeType] = localeStates; const localeMessagesType = 'Locale messages info'; const localeMessagesStates = [ { type: localeMessagesType, key: 'messages', editable: false, value: composer.messages.value } ]; state[localeMessagesType] = localeMessagesStates; const datetimeFormatsType = 'Datetime formats info'; const datetimeFormatsStates = [ { type: datetimeFormatsType, key: 'datetimeFormats', editable: false, value: composer.datetimeFormats.value } ]; state[datetimeFormatsType] = datetimeFormatsStates; const numberFormatsType = 'Datetime formats info'; const numberFormatsStates = [ { type: numberFormatsType, key: 'numberFormats', editable: false, value: composer.numberFormats.value } ]; state[numberFormatsType] = numberFormatsStates; return state; } function addTimelineEvent(event, payload) { if (devtoolsApi) { devtoolsApi.addTimelineEvent({ layerId: DevToolsTimelineLayerMaps[event], event: { time: Date.now(), meta: {}, data: payload || {} } }); } } /** * Vue I18n Version * * @remarks * Semver format. Same format as the package.json `version` field. * * @VueI18nGeneral */ const VERSION = '9.0.0-beta.13'; /** * This is only called development env * istanbul-ignore-next */ function initDev() { const target = getGlobalThis(); target.__INTLIFY__ = true; setDevtoolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__); { console.info(`You are running a development build of vue-i18n.\n` + `Make sure to use the production build (*.prod.js) when deploying for production.`); } } const warnMessages$1 = { [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supportted 'preserve'.`, [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supportted 'formatter'.`, [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supportted 'preserveDirectiveContent'.`, [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supportted 'getChoiceIndex'.`, [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` }; function getWarnMessage$1(code, ...args) { return format(warnMessages$1[code], ...args); } function createI18nError(code, ...args) { return createCompileError(code, null, { messages: errorMessages$2, args } ); } const errorMessages$2 = { [12 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', [13 /* INVALID_ARGUMENT */]: 'Invalid argument', [14 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', [15 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', [20 /* UNEXPECTED_ERROR */]: 'Unexpected error', [16 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', [17 /* REQUIRED_VALUE */]: `Required in value: {0}`, [18 /* INVALID_VALUE */]: `Invalid value`, [19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` }; /** * Composer * * Composer is offered composable API for Vue 3 * This module is offered new style vue-i18n API */ const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); const DatetimePartsSymbol = makeSymbol('__datetimeParts'); const NumberPartsSymbol = makeSymbol('__numberParts'); const EnableEmitter = makeSymbol('__enableEmitter'); const DisableEmitter = makeSymbol('__disableEmitter'); let composerID = 0; function defineCoreMissingHandler(missing) { return ((ctx, locale, key, type) => { return missing(locale, key, getCurrentInstance() || undefined, type); }); } function getLocaleMessages(locale, options) { const { messages, __i18n } = options; // prettier-ignore const ret = isPlainObject(messages) ? messages : isArray(__i18n) ? {} : { [locale]: {} }; // merge locale messages of i18n custom block if (isArray(__i18n)) { __i18n.forEach(raw => { deepCopy(isString(raw) ? JSON.parse(raw) : raw, ret); }); return ret; } if (isFunction(__i18n)) { const { functions } = __i18n(); addPreCompileMessages(ret, functions); } return ret; } const hasOwnProperty = Object.prototype.hasOwnProperty; // eslint-disable-next-line @typescript-eslint/no-explicit-any function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } // eslint-disable-next-line @typescript-eslint/no-explicit-any function deepCopy(source, destination) { for (const key in source) { if (hasOwn(source, key)) { if (!isObject(source[key])) { destination[key] = destination[key] != null ? destination[key] : {}; destination[key] = source[key]; } else { destination[key] = destination[key] != null ? destination[key] : {}; deepCopy(source[key], destination[key]); } } } } function addPreCompileMessages(messages, functions) { const keys = Object.keys(functions); keys.forEach(key => { const compiled = functions[key]; const { l, k } = JSON.parse(key); if (!messages[l]) { messages[l] = {}; } const targetLocaleMessage = messages[l]; const paths = parse(k); if (paths != null) { const len = paths.length; let last = targetLocaleMessage; // eslint-disable-line @typescript-eslint/no-explicit-any let i = 0; while (i < len) { const path = paths[i]; if (i === len - 1) { last[path] = compiled; break; } else { let val = last[path]; if (!val) { last[path] = val = {}; } last = val; i++; } } } }); } /** * Create composer interface factory * * @internal */ function createComposer(options = {}) { const { __root } = options; const _isGlobal = __root === undefined; let _inheritLocale = isBoolean(options.inheritLocale) ? options.inheritLocale : true; const _locale = ref( // prettier-ignore __root && _inheritLocale ? __root.locale.value : isString(options.locale) ? options.locale : 'en-US'); const _fallbackLocale = ref( // prettier-ignore __root && _inheritLocale ? __root.fallbackLocale.value : isString(options.fallbackLocale) || isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : _locale.value); const _messages = ref(getLocaleMessages(_locale.value, options)); const _datetimeFormats = ref(isPlainObject(options.datetimeFormats) ? options.datetimeFormats : { [_locale.value]: {} }); const _numberFormats = ref(isPlainObject(options.numberFormats) ? options.numberFormats : { [_locale.value]: {} }); // warning suppress options // prettier-ignore let _missingWarn = __root ? __root.missingWarn : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) ? options.missingWarn : true; // prettier-ignore let _fallbackWarn = __root ? __root.fallbackWarn : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) ? options.fallbackWarn : true; let _fallbackRoot = isBoolean(options.fallbackRoot) ? options.fallbackRoot : true; // configure fall bakck to root let _fallbackFormat = !!options.fallbackFormat; // runtime missing let _missing = isFunction(options.missing) ? options.missing : null; let _runtimeMissing = isFunction(options.missing) ? defineCoreMissingHandler(options.missing) : null; // postTranslation handler let _postTranslation = isFunction(options.postTranslation) ? options.postTranslation : null; let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true; let _escapeParameter = !!options.escapeParameter; // custom linked modifiers // prettier-ignore const _modifiers = __root ? __root.modifiers : isPlainObject(options.modifiers) ? options.modifiers : {}; // pluralRules const _pluralRules = options.pluralRules; // runtime context // eslint-disable-next-line prefer-const let _context; function getCoreContext() { return createCoreContext({ locale: _locale.value, fallbackLocale: _fallbackLocale.value, messages: _messages.value, datetimeFormats: _datetimeFormats.value, numberFormats: _numberFormats.value, modifiers: _modifiers, pluralRules: _pluralRules, missing: _runtimeMissing === null ? undefined : _runtimeMissing, missingWarn: _missingWarn, fallbackWarn: _fallbackWarn, fallbackFormat: _fallbackFormat, unresolving: true, postTranslation: _postTranslation === null ? undefined : _postTranslation, warnHtmlMessage: _warnHtmlMessage, escapeParameter: _escapeParameter, __datetimeFormatters: isPlainObject(_context) ? _context.__datetimeFormatters : undefined, __numberFormatters: isPlainObject(_context) ? _context.__numberFormatters : undefined, __emitter: isPlainObject(_context) ? _context.__emitter : undefined }); } _context = getCoreContext(); updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); /*! * define properties */ // locale const locale = computed({ get: () => _locale.value, set: val => { _locale.value = val; _context.locale = _locale.value; } }); // fallbackLocale const fallbackLocale = computed({ get: () => _fallbackLocale.value, set: val => { _fallbackLocale.value = val; _context.fallbackLocale = _fallbackLocale.value; updateFallbackLocale(_context, _locale.value, val); } }); // messages const messages = computed(() => _messages.value); // datetimeFormats const datetimeFormats = computed(() => _datetimeFormats.value); // numberFormats const numberFormats = computed(() => _numberFormats.value); /** * define methods */ // getPostTranslationHandler function getPostTranslationHandler() { return isFunction(_postTranslation) ? _postTranslation : null; } // setPostTranslationHandler function setPostTranslationHandler(handler) { _postTranslation = handler; _context.postTranslation = handler; } // getMissingHandler function getMissingHandler() { return _missing; } // setMissingHandler function setMissingHandler(handler) { if (handler !== null) { _runtimeMissing = defineCoreMissingHandler(handler); } _missing = handler; _context.missing = _runtimeMissing; } function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { const context = getCoreContext(); const ret = fn(context); // track reactive dependency, see the getRuntimeContext if (isNumber(ret) && ret === NOT_REOSLVED) { const key = argumentParser(); if ( _fallbackRoot && __root) { warn(getWarnMessage$1(6 /* FALLBACK_TO_ROOT */, { key, type: warnType })); // for vue-devtools timeline event { const { __emitter: emitter } = context; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type: warnType, key, to: 'global' }); } } } return _fallbackRoot && __root ? fallbackSuccess(__root) : fallbackFail(key); } else if (successCondition(ret)) { return ret; } else { /* istanbul ignore next */ throw createI18nError(12 /* UNEXPECTED_RETURN_TYPE */); } } // t function t(...args) { return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args)[0], 'translate', root => root.t(...args), key => key, val => isString(val)); } // d function d(...args) { return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); } // n function n(...args) { return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); } // for custom processor function normalize(values) { return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val); } const interpolate = (val) => val; const processor = { normalize, interpolate, type: 'vnode' }; // __transrateVNode, using for `i18n-t` component function __transrateVNode(...args) { return wrapWithDeps(context => { let ret; const _context = context; try { _context.processor = processor; ret = translate(_context, ...args); } finally { _context.processor = null; } return ret; }, () => parseTranslateArgs(...args)[0], 'translate', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val)); } // __numberParts, using for `i18n-n` component function __numberParts(...args) { return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); } // __datetimeParts, using for `i18n-d` component function __datetimeParts(...args) { return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); } // te function te(key, locale) { const targetLocale = isString(locale) ? locale : _locale.value; const message = getLocaleMessage(targetLocale); return resolveValue(message, key) !== null; } // tm function tm(key) { const messages = _messages.value[_locale.value] || {}; const target = resolveValue(messages, key); // prettier-ignore return target != null ? target : __root ? __root.tm(key) || {} : {}; } // getLocaleMessage function getLocaleMessage(locale) { return (_messages.value[locale] || {}); } // setLocaleMessage function setLocaleMessage(locale, message) { _messages.value[locale] = message; _context.messages = _messages.value; } // mergeLocaleMessage function mergeLocaleMessage(locale, message) { _messages.value[locale] = Object.assign(_messages.value[locale] || {}, message); _context.messages = _messages.value; } // getDateTimeFormat function getDateTimeFormat(locale) { return _datetimeFormats.value[locale] || {}; } // setDateTimeFormat function setDateTimeFormat(locale, format) { _datetimeFormats.value[locale] = format; _context.datetimeFormats = _datetimeFormats.value; clearDateTimeFormat(_context, locale, format); } // mergeDateTimeFormat function mergeDateTimeFormat(locale, format) { _datetimeFormats.value[locale] = Object.assign(_datetimeFormats.value[locale] || {}, format); _context.datetimeFormats = _datetimeFormats.value; clearDateTimeFormat(_context, locale, format); } // getNumberFormat function getNumberFormat(locale) { return _numberFormats.value[locale] || {}; } // setNumberFormat function setNumberFormat(locale, format) { _numberFormats.value[locale] = format; _context.numberFormats = _numberFormats.value; clearNumberFormat(_context, locale, format); } // mergeNumberFormat function mergeNumberFormat(locale, format) { _numberFormats.value[locale] = Object.assign(_numberFormats.value[locale] || {}, format); _context.numberFormats = _numberFormats.value; clearNumberFormat(_context, locale, format); } // for debug composerID++; // watch root locale & fallbackLocale if (__root) { watch(__root.locale, (val) => { if (_inheritLocale) { _locale.value = val; _context.locale = val; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }); watch(__root.fallbackLocale, (val) => { if (_inheritLocale) { _fallbackLocale.value = val; _context.fallbackLocale = val; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }); } // export composition API! const composer = { // properties id: composerID, locale, fallbackLocale, get inheritLocale() { return _inheritLocale; }, set inheritLocale(val) { _inheritLocale = val; if (val && __root) { _locale.value = __root.locale.value; _fallbackLocale.value = __root.fallbackLocale.value; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }, get availableLocales() { return Object.keys(_messages.value).sort(); }, messages, datetimeFormats, numberFormats, get modifiers() { return _modifiers; }, get pluralRules() { return _pluralRules || {}; }, get isGlobal() { return _isGlobal; }, get missingWarn() { return _missingWarn; }, set missingWarn(val) { _missingWarn = val; _context.missingWarn = _missingWarn; }, get fallbackWarn() { return _fallbackWarn; }, set fallbackWarn(val) { _fallbackWarn = val; _context.fallbackWarn = _fallbackWarn; }, get fallbackRoot() { return _fallbackRoot; }, set fallbackRoot(val) { _fallbackRoot = val; }, get fallbackFormat() { return _fallbackFormat; }, set fallbackFormat(val) { _fallbackFormat = val; _context.fallbackFormat = _fallbackFormat; }, get warnHtmlMessage() { return _warnHtmlMessage; }, set warnHtmlMessage(val) { _warnHtmlMessage = val; _context.warnHtmlMessage = val; }, get escapeParameter() { return _escapeParameter; }, set escapeParameter(val) { _escapeParameter = val; _context.escapeParameter = val; }, // methods t, d, n, te, tm, getLocaleMessage, setLocaleMessage, mergeLocaleMessage, getDateTimeFormat, setDateTimeFormat, mergeDateTimeFormat, getNumberFormat, setNumberFormat, mergeNumberFormat, getPostTranslationHandler, setPostTranslationHandler, getMissingHandler, setMissingHandler, [TransrateVNodeSymbol]: __transrateVNode, [NumberPartsSymbol]: __numberParts, [DatetimePartsSymbol]: __datetimeParts }; // for vue-devtools timeline event { composer[EnableEmitter] = (emitter) => { _context.__emitter = emitter; }; composer[DisableEmitter] = () => { _context.__emitter = undefined; }; } return composer; } /** * Legacy * * This module is offered legacy vue-i18n API compatibility */ /** * Convert to I18n Composer Options from VueI18n Options * * @internal */ function convertComposerOptions(options) { const locale = isString(options.locale) ? options.locale : 'en-US'; const fallbackLocale = isString(options.fallbackLocale) || isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : locale; const missing = isFunction(options.missing) ? options.missing : undefined; const missingWarn = isBoolean(options.silentTranslationWarn) || isRegExp(options.silentTranslationWarn) ? !options.silentTranslationWarn : true; const fallbackWarn = isBoolean(options.silentFallbackWarn) || isRegExp(options.silentFallbackWarn) ? !options.silentFallbackWarn : true; const fallbackRoot = isBoolean(options.fallbackRoot) ? options.fallbackRoot : true; const fallbackFormat = !!options.formatFallbackMessages; const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; const pluralizationRules = options.pluralizationRules; const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : undefined; const warnHtmlMessage = isString(options.warnHtmlInMessage) ? options.warnHtmlInMessage !== 'off' : true; const escapeParameter = !!options.escapeParameterHtml; const inheritLocale = isBoolean(options.sync) ? options.sync : true; if ( options.formatter) { warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */)); } if ( options.preserveDirectiveContent) { warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); } let messages = options.messages; if (isPlainObject(options.sharedMessages)) { const sharedMessages = options.sharedMessages; const locales = Object.keys(sharedMessages); messages = locales.reduce((messages, locale) => { const message = messages[locale] || (messages[locale] = {}); Object.assign(message, sharedMessages[locale]); return messages; }, (messages || {})); } const { __i18n, __root } = options; const datetimeFormats = options.datetimeFormats; const numberFormats = options.numberFormats; return { locale, fallbackLocale, messages, datetimeFormats, numberFormats, missing, missingWarn, fallbackWarn, fallbackRoot, fallbackFormat, modifiers, pluralRules: pluralizationRules, postTranslation, warnHtmlMessage, escapeParameter, inheritLocale, __i18n, __root }; } /** * create VueI18n interface factory * * @internal */ function createVueI18n(options = {}) { const composer = createComposer(convertComposerOptions(options)); // defines VueI18n const vueI18n = { /** * properties */ // id id: composer.id, // locale get locale() { return composer.locale.value; }, set locale(val) { composer.locale.value = val; }, // fallbackLocale get fallbackLocale() { return composer.fallbackLocale.value; }, set fallbackLocale(val) { composer.fallbackLocale.value = val; }, // messages get messages() { return composer.messages.value; }, // datetimeFormats get datetimeFormats() { return composer.datetimeFormats.value; }, // numberFormats get numberFormats() { return composer.numberFormats.value; }, // availableLocales get availableLocales() { return composer.availableLocales; }, // formatter get formatter() { warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */)); // dummy return { interpolate() { return []; } }; }, set formatter(val) { warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */)); }, // missing get missing() { return composer.getMissingHandler(); }, set missing(handler) { composer.setMissingHandler(handler); }, // silentTranslationWarn get silentTranslationWarn() { return isBoolean(composer.missingWarn) ? !composer.missingWarn : composer.missingWarn; }, set silentTranslationWarn(val) { composer.missingWarn = isBoolean(val) ? !val : val; }, // silentFallbackWarn get silentFallbackWarn() { return isBoolean(composer.fallbackWarn) ? !composer.fallbackWarn : composer.fallbackWarn; }, set silentFallbackWarn(val) { composer.fallbackWarn = isBoolean(val) ? !val : val; }, // modifiers get modifiers() { return composer.modifiers; }, // formatFallbackMessages get formatFallbackMessages() { return composer.fallbackFormat; }, set formatFallbackMessages(val) { composer.fallbackFormat = val; }, // postTranslation get postTranslation() { return composer.getPostTranslationHandler(); }, set postTranslation(handler) { composer.setPostTranslationHandler(handler); }, // sync get sync() { return composer.inheritLocale; }, set sync(val) { composer.inheritLocale = val; }, // warnInHtmlMessage get warnHtmlInMessage() { return composer.warnHtmlMessage ? 'warn' : 'off'; }, set warnHtmlInMessage(val) { composer.warnHtmlMessage = val !== 'off'; }, // escapeParameterHtml get escapeParameterHtml() { return composer.escapeParameter; }, set escapeParameterHtml(val) { composer.escapeParameter = val; }, // preserveDirectiveContent get preserveDirectiveContent() { warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); return true; }, set preserveDirectiveContent(val) { warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); }, // pluralizationRules get pluralizationRules() { return composer.pluralRules || {}; }, // for internal __composer: composer, /** * methods */ // t t(...args) { const [arg1, arg2, arg3] = args; const options = {}; let list = null; let named = null; if (!isString(arg1)) { throw createI18nError(13 /* INVALID_ARGUMENT */); } const key = arg1; if (isString(arg2)) { options.locale = arg2; } else if (isArray(arg2)) { list = arg2; } else if (isPlainObject(arg2)) { named = arg2; } if (isArray(arg3)) { list = arg3; } else if (isPlainObject(arg3)) { named = arg3; } return composer.t(key, list || named || {}, options); }, // tc tc(...args) { const [arg1, arg2, arg3] = args; const options = { plural: 1 }; let list = null; let named = null; if (!isString(arg1)) { throw createI18nError(13 /* INVALID_ARGUMENT */); } const key = arg1; if (isString(arg2)) { options.locale = arg2; } else if (isNumber(arg2)) { options.plural = arg2; } else if (isArray(arg2)) { list = arg2; } else if (isPlainObject(arg2)) { named = arg2; } if (isString(arg3)) { options.locale = arg3; } else if (isArray(arg3)) { list = arg3; } else if (isPlainObject(arg3)) { named = arg3; } return composer.t(key, list || named || {}, options); }, // te te(key, locale) { return composer.te(key, locale); }, // tm tm(key) { return composer.tm(key); }, // getLocaleMessage getLocaleMessage(locale) { return composer.getLocaleMessage(locale); }, // setLocaleMessage setLocaleMessage(locale, message) { composer.setLocaleMessage(locale, message); }, // mergeLocaleMessasge mergeLocaleMessage(locale, message) { composer.mergeLocaleMessage(locale, message); }, // d d(...args) { return composer.d(...args); }, // getDateTimeFormat getDateTimeFormat(locale) { return composer.getDateTimeFormat(locale); }, // setDateTimeFormat setDateTimeFormat(locale, format) { composer.setDateTimeFormat(locale, format); }, // mergeDateTimeFormat mergeDateTimeFormat(locale, format) { composer.mergeDateTimeFormat(locale, format); }, // n n(...args) { return composer.n(...args); }, // getNumberFormat getNumberFormat(locale) { return composer.getNumberFormat(locale); }, // setNumberFormat setNumberFormat(locale, format) { composer.setNumberFormat(locale, format); }, // mergeNumberFormat mergeNumberFormat(locale, format) { composer.mergeNumberFormat(locale, format); }, // getChoiceIndex // eslint-disable-next-line @typescript-eslint/no-unused-vars getChoiceIndex(choice, choicesLength) { warn(getWarnMessage$1(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); return -1; }, // for internal __onComponentInstanceCreated(target) { const { componentInstanceCreatedListener } = options; if (componentInstanceCreatedListener) { componentInstanceCreatedListener(target, vueI18n); } } }; // for vue-devtools timeline event { vueI18n.__enableEmitter = (emitter) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const __composer = composer; __composer[EnableEmitter] && __composer[EnableEmitter](emitter); }; vueI18n.__disableEmitter = () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const __composer = composer; __composer[DisableEmitter] && __composer[DisableEmitter](); }; } return vueI18n; } const baseFormatProps = { tag: { type: [String, Object] }, locale: { type: String }, scope: { type: String, validator: (val) => val === 'parent' || val === 'global', default: 'parent' } }; /** * Translation Component * * @remarks * See the following items for property about details * * @VueI18nSee [TranslationProps](component#translationprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Component Interpolation](../advanced/component) * * @example * ```html * <div id="app"> * <!-- ... --> * <i18n path="term" tag="label" for="tos"> * <a :href="url" target="_blank">{{ $t('tos') }}</a> * </i18n> * <!-- ... --> * </div> * ``` * ```js * import { createApp } from 'vue' * import { createI18n } from 'vue-i18n' * * const messages = { * en: { * tos: 'Term of Service', * term: 'I accept xxx {0}.' * }, * ja: { * tos: '利用規約', * term: '私は xxx の{0}に同意します。' * } * } * * const i18n = createI18n({ * locale: 'en', * messages * }) * * const app = createApp({ * data: { * url: '/term' * } * }).use(i18n).mount('#app') * ``` * * @VueI18nComponent */ const Translation = { /* eslint-disable */ name: 'i18n-t', props: { ...baseFormatProps, keypath: { type: String, required: true }, plural: { type: [Number, String], // eslint-disable-next-line @typescript-eslint/no-explicit-any validator: (val) => isNumber(val) || !isNaN(val) } }, /* eslint-enable */ setup(props, context) { const { slots, attrs } = context; const i18n = useI18n({ useScope: props.scope }); const keys = Object.keys(slots).filter(key => key !== '_'); return () => { const options = {}; if (props.locale) { options.locale = props.locale; } if (props.plural !== undefined) { options.plural = isString(props.plural) ? +props.plural : props.plural; } const arg = getInterpolateArg(context, keys); // eslint-disable-next-line @typescript-eslint/no-explicit-any const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); // prettier-ignore return isString(props.tag) ? h(props.tag, { ...attrs }, children) : isObject(props.tag) ? h(props.tag, { ...attrs }, children) : h(Fragment, { ...attrs }, children); }; } }; function getInterpolateArg({ slots }, keys) { if (keys.length === 1 && keys[0] === 'default') { // default slot only return slots.default ? slots.default() : []; } else { // named slots return keys.reduce((arg, key) => { const slot = slots[key]; if (slot) { arg[key] = slot(); } return arg; }, {}); } } function renderFormatter(props, context, slotKeys, partFormatter) { const { slots, attrs } = context; return () => { const options = { part: true }; let orverrides = {}; if (props.locale) { options.locale = props.locale; } if (isString(props.format)) { options.key = props.format; } else if (isObject(props.format)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any if (isString(props.format.key)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any options.key = props.format.key; } // Filter out number format options only orverrides = Object.keys(props.format).reduce((options, prop) => { return slotKeys.includes(prop) ? Object.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any : options; }, {}); } const parts = partFormatter(...[props.value, options, orverrides]); let children = [options.key]; if (isArray(parts)) { children = parts.map((part, index) => { const slot = slots[part.type]; return slot ? slot({ [part.type]: part.value, index, parts }) : [part.value]; }); } else if (isString(parts)) { children = [parts]; } // prettier-ignore return isString(props.tag) ? h(props.tag, { ...attrs }, children) : isObject(props.tag) ? h(props.tag, { ...attrs }, children) : h(Fragment, { ...attrs }, children); }; } const NUMBER_FORMAT_KEYS = [ 'localeMatcher', 'style', 'unit', 'unitDisplay', 'currency', 'currencyDisplay', 'useGrouping', 'numberingSystem', 'minimumIntegerDigits', 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits', 'notation', 'formatMatcher' ]; /** * Number Format Component * * @remarks * See the following items for property about details * * @VueI18nSee [FormattableProps](component#formattableprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Custom Formatting](../essentials/number#custom-formatting) * * @VueI18nDanger * Not supported IE, due to no support `Intl.NumberForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) * * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) * * @VueI18nComponent */ const NumberFormat = { /* eslint-disable */ name: 'i18n-n', props: { ...baseFormatProps, value: { type: Number, required: true }, format: { type: [String, Object] } }, /* eslint-enable */ setup(props, context) { const i18n = useI18n({ useScope: 'parent' }); return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => // eslint-disable-next-line @typescript-eslint/no-explicit-any i18n[NumberPartsSymbol](...args)); } }; const DATETIME_FORMAT_KEYS = [ 'dateStyle', 'timeStyle', 'fractionalSecondDigits', 'calendar', 'dayPeriod', 'numberingSystem', 'localeMatcher', 'timeZone', 'hour12', 'hourCycle', 'formatMatcher', 'weekday', 'era', 'year', 'month', 'day', 'hour', 'minute', 'second', 'timeZoneName' ]; /** * Datetime Format Component * * @remarks * See the following items for property about details * * @VueI18nSee [FormattableProps](component#formattableprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Custom Formatting](../essentials/datetime#custom-formatting) * * @VueI18nDanger * Not supported IE, due to no support `Intl.DateTimeForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) * * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) * * @VueI18nComponent */ const DatetimeFormat = { /* eslint-disable */ name: 'i18n-d', props: { ...baseFormatProps, value: { type: [Number, Date], required: true }, format: { type: [String, Object] } }, /* eslint-enable */ setup(props, context) { const i18n = useI18n({ useScope: 'parent' }); return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => // eslint-disable-next-line @typescript-eslint/no-explicit-any i18n[DatetimePartsSymbol](...args)); } }; function getComposer(i18n, instance) { const i18nInternal = i18n; if (i18n.mode === 'composition') { return (i18nInternal.__getInstance(instance) || i18n.global); } else { const vueI18n = i18nInternal.__getInstance(instance); return vueI18n != null ? vueI18n.__composer : i18n.global.__composer; } } function vTDirective(i18n) { const bind = (el, { instance, value, modifiers }) => { /* istanbul ignore if */ if (!instance || !instance.$) { throw createI18nError(20 /* UNEXPECTED_ERROR */); } const composer = getComposer(i18n, instance.$); if ( modifiers.preserve) { warn(getWarnMessage$1(7 /* NOT_SUPPORTED_PRESERVE */)); } const parsedValue = parseValue(value); el.textContent = composer.t(...makeParams(parsedValue)); }; return { beforeMount: bind, beforeUpdate: bind }; } function parseValue(value) { if (isString(value)) { return { path: value }; } else if (isPlainObject(value)) { if (!('path' in value)) { throw createI18nError(17 /* REQUIRED_VALUE */, 'path'); } return value; } else { throw createI18nError(18 /* INVALID_VALUE */); } } function makeParams(value) { const { path, locale, args, choice, plural } = value; const options = {}; const named = args || {}; if (isString(locale)) { options.locale = locale; } if (isNumber(choice)) { options.plural = choice; } if (isNumber(plural)) { options.plural = plural; } return [path, named, options]; } function apply(app, i18n, ...options) { const pluginOptions = isPlainObject(options[0]) ? options[0] : {}; const useI18nComponentName = !!pluginOptions.useI18nComponentName; const globalInstall = isBoolean(pluginOptions.globalInstall) ? pluginOptions.globalInstall : true; if ( globalInstall && useI18nComponentName) { warn(getWarnMessage$1(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { name: Translation.name })); } if (globalInstall) { // install components app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); app.component(NumberFormat.name, NumberFormat); app.component(DatetimeFormat.name, DatetimeFormat); } // install directive app.directive('t', vTDirective(i18n)); } // supports compatibility for legacy vue-i18n APIs function defineMixin(vuei18n, composer, i18n) { return { beforeCreate() { const instance = getCurrentInstance(); /* istanbul ignore if */ if (!instance) { throw createI18nError(20 /* UNEXPECTED_ERROR */); } const options = this.$options; if (options.i18n) { const optionsI18n = options.i18n; if (options.__i18n) { optionsI18n.__i18n = options.__i18n; } optionsI18n.__root = composer; if (this === this.$root) { this.$i18n = mergeToRoot(vuei18n, optionsI18n); } else { this.$i18n = createVueI18n(optionsI18n); } } else if (options.__i18n) { if (this === this.$root) { this.$i18n = mergeToRoot(vuei18n, options); } else { this.$i18n = createVueI18n({ __i18n: options.__i18n, __root: composer }); } } else { // set global this.$i18n = vuei18n; } vuei18n.__onComponentInstanceCreated(this.$i18n); i18n.__setInstance(instance, this.$i18n); // defines vue-i18n legacy APIs this.$t = (...args) => this.$i18n.t(...args); this.$tc = (...args) => this.$i18n.tc(...args); this.$te = (key, locale) => this.$i18n.te(key, locale); this.$d = (...args) => this.$i18n.d(...args); this.$n = (...args) => this.$i18n.n(...args); this.$tm = (key) => this.$i18n.tm(key); }, mounted() { /* istanbul ignore if */ { this.$el.__INTLIFY__ = this.$i18n.__composer; const emitter = (this.__emitter = createEmitter()); const _vueI18n = this.$i18n; _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); emitter.on('*', addTimelineEvent); } }, beforeUnmount() { const instance = getCurrentInstance(); /* istanbul ignore if */ if (!instance) { throw createI18nError(20 /* UNEXPECTED_ERROR */); } /* istanbul ignore if */ { if (this.__emitter) { this.__emitter.off('*', addTimelineEvent); delete this.__emitter; } const _vueI18n = this.$i18n; _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); delete this.$el.__INTLIFY__; } delete this.$t; delete this.$tc; delete this.$te; delete this.$d; delete this.$n; delete this.$tm; i18n.__deleteInstance(instance); delete this.$i18n; } }; } function mergeToRoot(root, optoins) { root.locale = optoins.locale || root.locale; root.fallbackLocale = optoins.fallbackLocale || root.fallbackLocale; root.missing = optoins.missing || root.missing; root.silentTranslationWarn = optoins.silentTranslationWarn || root.silentFallbackWarn; root.silentFallbackWarn = optoins.silentFallbackWarn || root.silentFallbackWarn; root.formatFallbackMessages = optoins.formatFallbackMessages || root.formatFallbackMessages; root.postTranslation = optoins.postTranslation || root.postTranslation; root.warnHtmlInMessage = optoins.warnHtmlInMessage || root.warnHtmlInMessage; root.escapeParameterHtml = optoins.escapeParameterHtml || root.escapeParameterHtml; root.sync = optoins.sync || root.sync; const messages = getLocaleMessages(root.locale, { messages: optoins.messages, __i18n: optoins.__i18n }); Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); if (optoins.datetimeFormats) { Object.keys(optoins.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, optoins.datetimeFormats[locale])); } if (optoins.numberFormats) { Object.keys(optoins.numberFormats).forEach(locale => root.mergeNumberFormat(locale, optoins.numberFormats[locale])); } return root; } /** * Vue I18n factory * * @param options - An options, see the {@link I18nOptions} * * @returns {@link I18n} instance * * @remarks * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. * * If you use composition API mode, you need to specify {@link ComposerOptions}. * * @VueI18nSee [Getting Started](../essentials/started) * @VueI18nSee [Composition API](../advanced/composition) * * @example * case: for Legacy API * ```js * import { createApp } from 'vue' * import { createI18n } from 'vue-i18n' * * // call with I18n option * const i18n = createI18n({ * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * * const App = { * // ... * } * * const app = createApp(App) * * // install! * app.use(i18n) * app.mount('#app') * ``` * * @example * case: for composition API * ```js * import { createApp } from 'vue' * import { createI18n, useI18n } from 'vue-i18n' * * // call with I18n option * const i18n = createI18n({ * legacy: false, // you must specify 'lagacy: false' option * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * * const App = { * setup() { * // ... * const { t } = useI18n({ ... }) * return { ... , t } * } * } * * const app = createApp(App) * * // install! * app.use(i18n) * app.mount('#app') * ``` * * @VueI18nGeneral */ function createI18n(options = {}) { // prettier-ignore const __legacyMode = isBoolean(options.legacy) ? options.legacy : true; const __globalInjection = !!options.globalInjection; const __instances = new Map(); // prettier-ignore const __global = __legacyMode ? createVueI18n(options) : createComposer(options); const symbol = makeSymbol( 'vue-i18n' ); const i18n = { // mode get mode() { // prettier-ignore return __legacyMode ? 'legacy' : 'composition' ; }, // install plugin async install(app, ...options) { { app.__VUE_I18N__ = i18n; } // setup global provider app.__VUE_I18N_SYMBOL__ = symbol; app.provide(app.__VUE_I18N_SYMBOL__, i18n); // global method and properties injection for Composition API if (!__legacyMode && __globalInjection) { injectGlobalFields(app, i18n.global); } // install built-in components and directive { apply(app, i18n, ...options); } // setup mixin for Legacy API if ( __legacyMode) { app.mixin(defineMixin(__global, __global.__composer, i18n)); } // setup vue-devtools plugin { const ret = await enableDevTools(app, i18n); if (!ret) { throw createI18nError(19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); } const emitter = createEmitter(); if (__legacyMode) { const _vueI18n = __global; _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = __global; _composer[EnableEmitter] && _composer[EnableEmitter](emitter); } emitter.on('*', addTimelineEvent); } }, // global accsessor get global() { return __global; }, // @internal __instances, // @internal __getInstance(component) { return __instances.get(component) || null; }, // @internal __setInstance(component, instance) { __instances.set(component, instance); }, // @internal __deleteInstance(component) { __instances.delete(component); } }; { devtoolsRegisterI18n(i18n, VERSION); } return i18n; } /** * Use Composition API for Vue I18n * * @param options - An options, see {@link UseI18nOptions} * * @returns {@link Composer} instance * * @remarks * This function is mainly used by `setup`. * * If options are specified, Composer instance is created for each component and you can be localized on the component. * * If options are not specified, you can be localized using the global Composer. * * @example * case: Component resource base localization * ```html * <template> * <form> * <label>{{ t('language') }}</label> * <select v-model="locale"> * <option value="en">en</option> * <option value="ja">ja</option> * </select> * </form> * <p>message: {{ t('hello') }}</p> * </template> * * <script> * import { useI18n } from 'vue-i18n' * * export default { * setup() { * const { t, locale } = useI18n({ * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * // Something to do ... * * return { ..., t, locale } * } * } * </script> * ``` * * @VueI18nComposition */ function useI18n(options = {}) { const instance = getCurrentInstance(); if (instance == null) { throw createI18nError(14 /* MUST_BE_CALL_SETUP_TOP */); } if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { throw createI18nError(15 /* NOT_INSLALLED */); } const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__); /* istanbul ignore if */ if (!i18n) { throw createI18nError(20 /* UNEXPECTED_ERROR */); } // prettier-ignore const global = i18n.mode === 'composition' ? i18n.global : i18n.global.__composer; // prettier-ignore const scope = isEmptyObject(options) ? ('__i18n' in instance.type) ? 'local' : 'global' : !options.useScope ? 'local' : options.useScope; if (scope === 'global') { let messages = isObject(options.messages) ? options.messages : {}; if ('__i18nGlobal' in instance.type) { messages = getLocaleMessages(global.locale.value, { messages, __i18n: instance.type.__i18nGlobal }); } // merge locale messages const locales = Object.keys(messages); if (locales.length) { locales.forEach(locale => { global.mergeLocaleMessage(locale, messages[locale]); }); } // merge datetime formats if (isObject(options.datetimeFormats)) { const locales = Object.keys(options.datetimeFormats); if (locales.length) { locales.forEach(locale => { global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); }); } } // merge number formats if (isObject(options.numberFormats)) { const locales = Object.keys(options.numberFormats); if (locales.length) { locales.forEach(locale => { global.mergeNumberFormat(locale, options.numberFormats[locale]); }); } } return global; } if (scope === 'parent') { let composer = getComposer$1(i18n, instance); if (composer == null) { { warn(getWarnMessage$1(12 /* NOT_FOUND_PARENT_SCOPE */)); } composer = global; } return composer; } // scope 'local' case if (i18n.mode === 'legacy') { throw createI18nError(16 /* NOT_AVAILABLE_IN_LEGACY_MODE */); } const i18nInternal = i18n; let composer = i18nInternal.__getInstance(instance); if (composer == null) { const type = instance.type; const composerOptions = { ...options }; if (type.__i18n) { composerOptions.__i18n = type.__i18n; } if (global) { composerOptions.__root = global; } composer = createComposer(composerOptions); setupLifeCycle(i18nInternal, instance, composer); i18nInternal.__setInstance(instance, composer); } return composer; } function getComposer$1(i18n, target) { let composer = null; const root = target.root; let current = target.parent; while (current != null) { const i18nInternal = i18n; if (i18n.mode === 'composition') { composer = i18nInternal.__getInstance(current); } else { const vueI18n = i18nInternal.__getInstance(current); if (vueI18n != null) { composer = vueI18n .__composer; } } if (composer != null) { break; } if (root === current) { break; } current = current.parent; } return composer; } function setupLifeCycle(i18n, target, composer) { let emitter = null; onMounted(() => { // inject composer instance to DOM for intlify-devtools if ( target.vnode.el) { target.vnode.el.__INTLIFY__ = composer; emitter = createEmitter(); // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = composer; _composer[EnableEmitter] && _composer[EnableEmitter](emitter); emitter.on('*', addTimelineEvent); } }, target); onUnmounted(() => { // remove composer instance from DOM for intlify-devtools if ( target.vnode.el && target.vnode.el.__INTLIFY__) { emitter && emitter.off('*', addTimelineEvent); // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = composer; _composer[DisableEmitter] && _composer[DisableEmitter](); delete target.vnode.el.__INTLIFY__; } i18n.__deleteInstance(target); }, target); } const globalExportProps = [ 'locale', 'fallbackLocale', 'availableLocales' ]; const globalExportMethods = ['t', 'd', 'n', 'tm']; function injectGlobalFields(app, composer) { const i18n = Object.create(null); globalExportProps.forEach(prop => { const desc = Object.getOwnPropertyDescriptor(composer, prop); if (!desc) { throw createI18nError(20 /* UNEXPECTED_ERROR */); } const wrap = isRef(desc.value) // check computed props ? { get() { return desc.value.value; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any set(val) { desc.value.value = val; } } : { get() { return desc.get && desc.get(); } }; Object.defineProperty(i18n, prop, wrap); }); app.config.globalProperties.$i18n = i18n; globalExportMethods.forEach(method => { const desc = Object.getOwnPropertyDescriptor(composer, method); if (!desc) { throw createI18nError(20 /* UNEXPECTED_ERROR */); } Object.defineProperty(app.config.globalProperties, `$${method}`, desc); }); } // register message compiler at vue-i18n registerMessageCompiler(compileToFunction); initDev(); export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };
cdnjs/cdnjs
ajax/libs/vue-i18n/9.0.0-beta.13/vue-i18n.esm-browser.js
JavaScript
mit
168,066
SHELL:=/bin/bash -euo pipefail CTXDIR=../.. MCCORTEX=$(CTXDIR)/bin/mccortex31 DNACAT=$(CTXDIR)/libs/seq_file/bin/dnacat K=7 KEEP=$(shell echo genome.fa genome.k$(K).{ctx,ctp} reads.1.fa.gz reads.2.fa.gz reads.{se,pe}.k$(K).ctp) PLOTS=genome.k$(K).dot genome.k$(K).pdf all: $(KEEP) plots: $(PLOTS) clean: rm -rf $(KEEP) $(PLOTS) # Sample random genome genome.fa: $(DNACAT) -F -n 200 > genome.fa genome.k$(K).ctx: genome.fa $(MCCORTEX) build -q -m 10M -k $(K) --sample MssrGenome --seq $< $@ genome.k$(K).dot: genome.k$(K).ctx $(MCCORTEX) unitigs -q --dot $< > $@ genome.k$(K).pdf: genome.k$(K).dot dot -Tpdf $< > $@ reads.1.fa.gz reads.2.fa.gz: ../../libs/readsim/readsim -r genome.fa -l 10 -i 20 -v 0.1 -d 2 reads genome.k$(K).ctp: genome.k$(K).ctx $(MCCORTEX) thread -q -m 10M -t 1 --seq genome.fa -o $@ $< reads.se.k$(K).ctp: genome.k$(K).ctx reads.1.fa.gz reads.2.fa.gz $(MCCORTEX) thread -q -m 10M -t 1 --seq reads.1.fa.gz --seq reads.2.fa.gz -o reads.se.k$(K).ctp genome.k$(K).ctx reads.pe.k$(K).ctp: genome.k$(K).ctx reads.1.fa.gz reads.2.fa.gz $(MCCORTEX) thread -q -m 10M -t 1 --seq2 reads.1.fa.gz:reads.2.fa.gz -o reads.pe.k$(K).ctp genome.k$(K).ctx .PHONY: all plots clean
mcveanlab/mccortex
tests/path_check/Makefile
Makefile
mit
1,205
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/msg/Motors.msg" services_str = "/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/srv/AddTwoInts.srv" pkg_name = "er1_motor_driver" dependencies_str = "std_msgs" langs = "gencpp;genlisp;genpy" dep_include_paths_str = "er1_motor_driver;/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/msg;std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg" PYTHON_EXECUTABLE = "/usr/bin/python" package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = "/opt/ros/indigo/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
arvindpereira/clover_hack_day
er1_robot/build/er1_motor_driver/cmake/er1_motor_driver-genmsg-context.py
Python
mit
677
export default { name: 'selfie-card', type: 'text', render() { return '[ :) ]'; } };
atonse/mobiledoc-kit
demo/app/mobiledoc-cards/text/selfie.js
JavaScript
mit
97
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("ChallengeAccepted.Models")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ChallengeAccepted.Models")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("186858b4-52b9-4a17-84aa-f4946a821fa2")] // 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")]
NativeScriptHybrids/ChallengeAccepted
ChallengeAccepted.Service/ChallengeAccepted.Models/Properties/AssemblyInfo.cs
C#
mit
1,424
from mimetypes import guess_type def get_git_info(): """ Parses the git info and returns a tuple containg the owner and repo :deprecated: :rtype: tuple :return: (owner name, repo name) """ repo = '' with open('.git/config') as f: for line in f.readlines(): if 'url' in line: repo = line.replace('url = ', '').strip() r = repo.split('/') # Return a tuple containing the owner and the repo name return r[-2], r[-1] def detect_mimetype(file_): """ Detects the provided file's mimetype. Used to determine if we should read the file line-by-line. :param str file_: The name of the file to guess the mimetype of :rtype: str :return: The mimetype of the file provided """ return guess_type(file_)
GrappigPanda/pygemony
pyg/utils.py
Python
mit
811
#include "ticTacToeFunc.h" #include <cstdio> TicTacToeFunc::TicTacToeFunc() { size = 3; winSize = 3; field = new States *[size]; for (int i = 0; i < size; i++) field[i] = new States[size]; for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) field[i][j] = stateFree; move = moveX; state = inProcess; } TicTacToeFunc::~TicTacToeFunc() { for (int i = 0; i < size; i++) delete[] field[i]; delete[] field; } TicTacToeFunc::States TicTacToeFunc::getCell(int x, int y) { return field[x][y]; } void TicTacToeFunc::horizontalWin() { for (int i = 0; i < size; i++) for (int j = 0; j < size - winSize + 1; j++) { bool win = true; for (int k = 0; k < winSize - 1; k++) if (field[i][j + k] == TicTacToeFunc::stateFree || field[i][j + k] != field[i][j + k + 1]) { win = false; break; } if (!win) continue; state = (field[i][j] == stateX) ? winX : winO; return; } } void TicTacToeFunc::verticalWin() { for (int i = 0; i < size; i++) for (int j = 0; j < size - winSize + 1; j++) { bool win = true; for (int k = 0; k < winSize - 1; k++) if (field[j + k][i] == TicTacToeFunc::stateFree || field[j + k][i] != field[j + k + 1][i]) { win = false; break; } if (!win) continue; state = (field[j][i] == stateX) ? winX : winO; return; } } void TicTacToeFunc::mainDiagonalWin() { for (int i = 0; i < size - winSize + 1; i++) for (int j = 0; j < size - winSize + 1; j++) { bool win = true; for (int k = 0; k < winSize - 1; k++) if (field[i + k][j + k] == TicTacToeFunc::stateFree || field[i + k][j + k] != field[i + k + 1][j + k + 1]) { win = false; break; } if (!win) continue; state = (field[i][j] == stateX) ? winX : winO; return; } } void TicTacToeFunc::secondaryDiagonalWin() { for (int i = 0; i < size - winSize + 1; i++) for (int j = winSize - 1; j < size; j++) { bool win = true; for (int k = 0; k < winSize - 1; k++) if (field[i + k][j - k] == TicTacToeFunc::stateFree || field[i + k][j - k] != field[i + k + 1][j - k - 1]) { win = false; break; } if (!win) continue; state = (field[j][i] == stateX) ? winX : winO; } } void TicTacToeFunc::updateState() { if (state != inProcess) return; horizontalWin(); if (state != inProcess) return; verticalWin(); if (state != inProcess) return; mainDiagonalWin(); if (state != inProcess) return; secondaryDiagonalWin(); } TicTacToeFunc::Moves TicTacToeFunc::nextMove() { if (move == moveX) return moveO; return moveX; } TicTacToeFunc::States TicTacToeFunc::changeState(Moves m) { if (m == moveX) return stateX; return stateO; } void TicTacToeFunc::makeMove(int x, int y) { if (isFinished()) return; field[x][y] = changeState(move); updateState(); move = nextMove(); } TicTacToeFunc::CurrentState TicTacToeFunc::getState() { return state; } bool TicTacToeFunc::isFinished() { if (state == winX || state == winO) return true; for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) if (field[i][j] == stateFree) return false; return true; } void TicTacToeFunc::changeSize(int newSize) { for (int i = 0; i < size; i++) delete[] field[i]; delete[] field; field = new States*[newSize]; for (int i = 0; i < newSize; i++) field[i] = new TicTacToeFunc::States[newSize]; for (int i = 0; i < newSize; i++) for (int j = 0; j < newSize; j++) field[i][j] = TicTacToeFunc::stateFree; size = newSize; winSize = 5; move = TicTacToeFunc::moveX; } int TicTacToeFunc::getSize() { return size; }
Sergey-Pravdyukov/Homeworks
term2/hw7/3/tictactoefunc.cpp
C++
mit
4,600
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> TheFragebogen - Test UIElements and QuestionnaireItems </title> <link rel="stylesheet" href="../node_modules/qunit/qunit/qunit.css"> <script src="../node_modules/qunit/qunit/qunit.js"> </script> <script src="../dist/thefragebogen.es5.js"> </script> <script src="qunit_basic.js"> </script> <script src="qunit_screen.js"> </script> <script src="qunit_questionnaireitem.js"> </script> <script src="qunit_screencontroller.js"> </script> </head> <body> <div id="qunit"></div> <div id="qunit-fixture"></div> </body> </html>
TheFragebogen/TheFragebogen
tests/qunit_es5.html
HTML
mit
760
#import "ZYTheme.h" @interface ZYThemeManager : NSObject { NSMutableDictionary *allThemes; ZYTheme *currentTheme; } + (instancetype)sharedInstance; - (ZYTheme*)currentTheme; - (NSArray*)allThemes; - (void)invalidateCurrentThemeAndReload:(NSString*)currentIdentifier; @end
Shade-Zepheri/Zypen
Theming/ZYThemeManager.h
C
mit
278
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} module Data.WebsiteContent ( WebsiteContent (..) , StackRelease (..) , Post (..) , loadWebsiteContent ) where import ClassyPrelude.Yesod import CMarkGFM import Data.GhcLinks import Data.Yaml import System.FilePath (takeFileName) import Text.Blaze.Html (preEscapedToHtml) import Types data WebsiteContent = WebsiteContent { wcHomepage :: !Html , wcAuthors :: !Html , wcOlderReleases :: !Html , wcGhcLinks :: !GhcLinks , wcStackReleases :: ![StackRelease] , wcPosts :: !(Vector Post) , wcSpamPackages :: !(Set PackageNameP) -- ^ Packages considered spam which should not be displayed. } data Post = Post { postTitle :: !Text , postSlug :: !Text , postAuthor :: !Text , postTime :: !UTCTime , postDescription :: !Text , postBody :: !Html } loadWebsiteContent :: FilePath -> IO WebsiteContent loadWebsiteContent dir = do wcHomepage <- readHtml "homepage.html" wcAuthors <- readHtml "authors.html" wcOlderReleases <- readHtml "older-releases.html" `catchIO` \_ -> readMarkdown "older-releases.md" wcGhcLinks <- readGhcLinks $ dir </> "stackage-cli" wcStackReleases <- decodeFileEither (dir </> "stack" </> "releases.yaml") >>= either throwIO return wcPosts <- loadPosts (dir </> "posts") `catchAny` \e -> do putStrLn $ "Error loading posts: " ++ tshow e return mempty wcSpamPackages <- decodeFileEither (dir </> "spam-packages.yaml") >>= either throwIO (return . setFromList) return WebsiteContent {..} where readHtml fp = fmap preEscapedToMarkup $ readFileUtf8 $ dir </> fp readMarkdown fp = fmap (preEscapedToHtml . commonmarkToHtml [optSmart] [extTable, extAutolink]) $ readFileUtf8 $ dir </> fp loadPosts :: FilePath -> IO (Vector Post) loadPosts dir = fmap (sortBy (\x y -> postTime y `compare` postTime x)) $ runConduitRes $ sourceDirectory dir .| concatMapC (stripSuffix ".md") .| mapMC loadPost .| sinkVector where loadPost :: FilePath -> ResourceT IO Post loadPost noExt = handleAny (\e -> throwString $ "Could not parse " ++ noExt ++ ".md: " ++ show e) $ do bs <- readFile $ noExt ++ ".md" let slug = pack $ takeFileName noExt text = filter (/= '\r') $ decodeUtf8 bs (frontmatter, body) <- case lines text of "---":rest -> case break (== "---") rest of (frontmatter, "---":body) -> return (unlines frontmatter, unlines body) _ -> error "Missing closing --- on frontmatter" _ -> error "Does not start with --- frontmatter" case Data.Yaml.decodeEither' $ encodeUtf8 frontmatter of Left e -> throwIO e Right mkPost -> return $ mkPost slug $ preEscapedToHtml $ commonmarkToHtml [optSmart] [extTable, extAutolink] body instance (slug ~ Text, body ~ Html) => FromJSON (slug -> body -> Post) where parseJSON = withObject "Post" $ \o -> do postTitle <- o .: "title" postAuthor <- o .: "author" postTime <- o .: "timestamp" postDescription <- o .: "description" return $ \postSlug postBody -> Post {..} data StackRelease = StackRelease { srName :: !Text , srPattern :: !Text } instance FromJSON StackRelease where parseJSON = withObject "StackRelease" $ \o -> StackRelease <$> o .: "name" <*> o .: "pattern"
fpco/stackage-server
src/Data/WebsiteContent.hs
Haskell
mit
3,666
#!/bin/bash if [ -z "${BASH_VERSION+Defined?}" ]; then echo "bash-pack: No shell interpreter other than Bash is supported" exit 1 fi # enable / disable bash-debug based on environment variable. # # Globals: # bash_debug set to 1 to enable xtrace enable_bash_debug() { [ "${bash_debug:-0}" = 0 ] || set -x } # Check major version of bash to be at least a given number # # Arguments: # 1. major_version version to check against # # Returns: # 0 if greater than or equal to major_version, otherwise 1 is_bash_version() { (( ${BASH_VERSION%%.*} >= "$1" )) } # initialise and load specified scripts; fenced by __bash_pack_loaded [ -n "${__bash_pack_loaded:-}" ] || { __bash_pack_loaded=1 modules_loading=(init) in_array() { for ((i=2; i<=$#; ++i)); do [ "${!i}" != "$1" ] || return 0 done return 1 } # Locate components of a module (also the bash version is taken into account) bash_pack_module_locate_scripts() { [[ ${BASH_VERSION} =~ ^([0-9]+)\.([0-9]+)\.([0-9]+) ]] local version_Mmp="${BASH_REMATCH[0]}" \ version_Mm="${BASH_REMATCH[1]}.${BASH_REMATCH[2]}" \ version_M="${BASH_REMATCH[1]}" local paths=( $(printf "${BASH_PACK_DIR}/${1}-bv%s.sh\n" "${version_Mmp}" "${version_Mm}" "${version_M}") "${BASH_PACK_DIR}/${1}.sh" ) local path for path in "${paths[@]}"; do if [ -f "$path" ] && [ -r "$path" ]; then echo -n "$path" return 0 fi done return 1 } bash_pack_module_get_new_required_modules() { local module all_new_required_modules new_required_modules=() all_new_required_modules=( $(sed -nr 's/.*^#require (.*)$.*/\1/p' "$@") ) for module in "${all_new_required_modules[@]+"${all_new_required_modules[@]}"}"; do in_array "$module" "${modules_loading[@]}" "${new_required_modules[@]+"${new_required_modules[@]}"}" || new_required_modules+=("$module") done printf '%s\n' "${new_required_modules[@]+"${new_required_modules[@]}"}" } bash_pack_module_load_by_name() { local path pre_path post_path this_module_paths=() if in_array "$1" "${modules_loading[@]}"; then return 0 fi if ! path="$( bash_pack_module_locate_scripts "${1}" )"; then echo "Could not find module: ${1}" exit 1 fi # locate and load the module modules_loading+=("${1}") if pre_path="$( bash_pack_module_locate_scripts "${1}-pre" )"; then this_module_paths+=("$pre_path") fi this_module_paths+=( "$path" ) if post_path="$( bash_pack_module_locate_scripts "${1}-post" )"; then this_module_paths+=("$post_path") fi # look for direct deps local required_modules=( $(bash_pack_module_get_new_required_modules "${this_module_paths[@]}") ) local module for module in "${required_modules[@]+"${required_modules[@]}"}"; do bash_pack_module_load_by_name "$module" done printf '%s\n' "${this_module_paths[@]}" } BASH_PACK_DIR="${BASH_SOURCE[0]%/*}" [ -d "$BASH_PACK_DIR" ] || BASH_PACK_DIR=. enable_bash_debug scripts_loading=() # Find files to load for any module-names given as args for ((i=1; i<=$#; ++i)); do scripts_loading+=($(bash_pack_module_load_by_name "${!i}")) done # once all of them are found, load them for script in "${scripts_loading[@]+"${scripts_loading[@]}"}"; do # shellcheck disable=SC1090 . "$script" done }
codemedic/bash-pack
init.sh
Shell
mit
3,702
# Hoboexpress - [Hoboexpress](http://hoboexpress.ca) - Setup - Start the development server with this command: -compile
ravi-shah/Hoboexpress
README.md
Markdown
mit
124
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace QrF.Core.Admin.Dto { public class BasePageInput { public BasePageInput() { this.Page = 1; this.PageSize = 20; } /// <summary> /// 当前分页 /// </summary> public int Page { set; get; } /// <summary> /// 每页数量 /// </summary> public int PageSize { set; get; } } }
ren8179/QrF.Core
src/apis/QrF.Core.Admin/Dto/BasePageInput.cs
C#
mit
507
package com.paratussoftware.ui.cli; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class GrimoireCLI { private static final String TITLE_FILE_NAME = "./lib/grimoire_title.txt"; public static void startGrimoireCLI(String[] args){ showTitle(); CLIMenuManager cliMenuManager = new CLIMenuManager(); while (true){ cliMenuManager.showMainMenu(); } } public static void showTitle(){ try (BufferedReader br = new BufferedReader(new FileReader(TITLE_FILE_NAME))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) {} } }
JArthurJohnston/Grimoire-V2
Demo/src/main/java/com/paratussoftware/ui/cli/GrimoireCLI.java
Java
mit
754
<?php namespace BDN\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20170820234613 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf( $this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.' ); $this->addSql( 'CREATE TABLE cron_task (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, commands LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', `interval` INT NOT NULL, lastrun DATETIME DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE orders (id INT AUTO_INCREMENT NOT NULL, number VARCHAR(255) DEFAULT NULL, additional_information VARCHAR(1000) DEFAULT NULL, state VARCHAR(255) NOT NULL, completed_at DATETIME DEFAULT NULL, items_total INT NOT NULL, adjustments_total INT NOT NULL, total INT NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, deleted_at DATETIME DEFAULT NULL, email VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_E52FFDEE96901F54 (number), UNIQUE INDEX UNIQ_E52FFDEEE7927C74 (email), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE order_items (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, quantity INT NOT NULL, unit_price INT NOT NULL, units_total INT NOT NULL, adjustments_total INT NOT NULL, total INT NOT NULL, is_immutable TINYINT(1) NOT NULL, INDEX IDX_62809DB08D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_group (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(180) NOT NULL, roles LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', community_id INT NOT NULL, UNIQUE INDEX UNIQ_8F02BF9D5E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE login_access_tokens (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, t_key VARCHAR(255) NOT NULL, expired TINYINT(1) NOT NULL, date DATETIME NOT NULL, redirect VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_7EC367D32CCFDC5D (t_key), INDEX IDX_7EC367D3A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE oauth2_access_tokens (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D247A21B5F37A13B (token), INDEX IDX_D247A21B19EB6921 (client_id), INDEX IDX_D247A21BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE oauth2_auth_codes (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, redirect_uri LONGTEXT NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_A018A10D5F37A13B (token), INDEX IDX_A018A10D19EB6921 (client_id), INDEX IDX_A018A10DA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE oauth2_clients (id INT AUTO_INCREMENT NOT NULL, random_id VARCHAR(255) NOT NULL, redirect_uris LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', secret VARCHAR(255) NOT NULL, allowed_grant_types LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE oauth2_refresh_tokens (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D394478C5F37A13B (token), INDEX IDX_D394478C19EB6921 (client_id), INDEX IDX_D394478CA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE session (id INT AUTO_INCREMENT NOT NULL, ip VARCHAR(45) NOT NULL, date DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(180) NOT NULL, username_canonical VARCHAR(180) NOT NULL, email VARCHAR(180) NOT NULL, email_canonical VARCHAR(180) NOT NULL, enabled TINYINT(1) NOT NULL, salt VARCHAR(255) DEFAULT NULL, password VARCHAR(255) NOT NULL, last_login DATETIME DEFAULT NULL, confirmation_token VARCHAR(180) DEFAULT NULL, password_requested_at DATETIME DEFAULT NULL, roles LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', api_key VARCHAR(255) DEFAULT NULL, google_authenticator_secret VARCHAR(255) DEFAULT NULL, forums_id INT NOT NULL, forums_access_token INT NOT NULL, community_id INT NOT NULL, UNIQUE INDEX UNIQ_8D93D64992FC23A8 (username_canonical), UNIQUE INDEX UNIQ_8D93D649A0D96FBF (email_canonical), UNIQUE INDEX UNIQ_8D93D649C05FB297 (confirmation_token), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_user_group (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_28657971A76ED395 (user_id), INDEX IDX_28657971FE54D947 (group_id), PRIMARY KEY(user_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_oauth_clients (user_id INT NOT NULL, client_id INT NOT NULL, INDEX IDX_FD402C51A76ED395 (user_id), INDEX IDX_FD402C5119EB6921 (client_id), PRIMARY KEY(user_id, client_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE slack_invite (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, date DATETIME NOT NULL, INDEX IDX_738D77CA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE language (id INT AUTO_INCREMENT NOT NULL, active TINYINT(1) NOT NULL, language_key VARCHAR(15) NOT NULL, language VARCHAR(64) NOT NULL, UNIQUE INDEX UNIQ_D4DB71B55B160485 (language_key), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE library (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, version DOUBLE PRECISION NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script (id INT AUTO_INCREMENT NOT NULL, git_id INT DEFAULT NULL, creator_id INT DEFAULT NULL, name VARCHAR(255) NOT NULL, product LONGTEXT NOT NULL COMMENT \'(DC2Type:object)\', description LONGTEXT NOT NULL, forum INT DEFAULT NULL, active TINYINT(1) NOT NULL, build_type_id VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_1C81873A5E237E06 (name), UNIQUE INDEX UNIQ_1C81873A4D4CA094 (git_id), INDEX IDX_1C81873A61220EA6 (creator_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script_authors (script_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_D304ED1BA1C01850 (script_id), INDEX IDX_D304ED1BA76ED395 (user_id), PRIMARY KEY(script_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script_users (script_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_78458A76A1C01850 (script_id), INDEX IDX_78458A76A76ED395 (user_id), PRIMARY KEY(script_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script_groups (script_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_90B1718AA1C01850 (script_id), INDEX IDX_90B1718AFE54D947 (group_id), PRIMARY KEY(script_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script_categories (script_id INT NOT NULL, category_id INT NOT NULL, INDEX IDX_CD9E8798A1C01850 (script_id), INDEX IDX_CD9E879812469DE2 (category_id), PRIMARY KEY(script_id, category_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE category (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE git (id INT AUTO_INCREMENT NOT NULL, url VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE releases (id INT AUTO_INCREMENT NOT NULL, script_id INT DEFAULT NULL, changelog LONGTEXT DEFAULT NULL, version DOUBLE PRECISION NOT NULL, date DATETIME NOT NULL, INDEX IDX_7896E4D1A1C01850 (script_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE review (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, script_id INT DEFAULT NULL, review LONGTEXT NOT NULL, stars INT NOT NULL, date DATETIME NOT NULL, accepted TINYINT(1) NOT NULL, INDEX IDX_794381C6A76ED395 (user_id), INDEX IDX_794381C6A1C01850 (script_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE hook (id INT AUTO_INCREMENT NOT NULL, server_id INT DEFAULT NULL, accessor VARCHAR(255) DEFAULT NULL, methodname VARCHAR(255) DEFAULT NULL, desctype VARCHAR(255) DEFAULT NULL, callclass VARCHAR(255) DEFAULT NULL, callmethod VARCHAR(255) DEFAULT NULL, calldesc VARCHAR(255) DEFAULT NULL, callargs VARCHAR(255) DEFAULT NULL, field VARCHAR(255) DEFAULT NULL, descfield VARCHAR(255) DEFAULT NULL, intoclass VARCHAR(255) DEFAULT NULL, classname VARCHAR(255) DEFAULT NULL, interface VARCHAR(255) DEFAULT NULL, invokemethod VARCHAR(255) DEFAULT NULL, argsdesc VARCHAR(255) DEFAULT NULL, type VARCHAR(255) NOT NULL, version DOUBLE PRECISION NOT NULL, INDEX IDX_A45843551844E6B7 (server_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server (id INT AUTO_INCREMENT NOT NULL, server_id INT DEFAULT NULL, name VARCHAR(255) NOT NULL, active TINYINT(1) NOT NULL, version DOUBLE PRECISION NOT NULL, description LONGTEXT NOT NULL, provider_id INT DEFAULT NULL, INDEX IDX_5A6DD5F6A53A8AA (provider_id), UNIQUE INDEX UNIQ_5A6DD5F61844E6B7 (server_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_groups (server_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_891100B61844E6B7 (server_id), INDEX IDX_891100B6FE54D947 (group_id), PRIMARY KEY(server_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_authors (server_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_FC7231ED1844E6B7 (server_id), INDEX IDX_FC7231EDA76ED395 (user_id), PRIMARY KEY(server_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_details (server_id INT NOT NULL, serverdetail_id INT NOT NULL, INDEX IDX_5810361844E6B7 (server_id), INDEX IDX_58103634B5C767 (serverdetail_id), PRIMARY KEY(server_id, serverdetail_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_detail (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_slack_channel (id INT AUTO_INCREMENT NOT NULL, channel VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_use (id INT AUTO_INCREMENT NOT NULL, datetime DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_serveruses (serveruse_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_2E513393EB1E3248 (serveruse_id), INDEX IDX_2E513393A76ED395 (user_id), PRIMARY KEY(serveruse_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_serveruse (serveruse_id INT NOT NULL, server_id INT NOT NULL, INDEX IDX_28A1B5EAEB1E3248 (serveruse_id), INDEX IDX_28A1B5EA1844E6B7 (server_id), PRIMARY KEY(serveruse_id, server_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_signature (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(255) NOT NULL, abstract_signature_id INT DEFAULT NULL, INDEX IDX_AE688CA57E0AA10B (abstract_signature_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_client (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_default_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_dreamscape_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_osscape_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_pkhonor_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_randoms (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_sequence (id INT AUTO_INCREMENT NOT NULL, idx INT NOT NULL, type VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_AD3D8CC48CDE5729 (type), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_adjustment (id INT AUTO_INCREMENT NOT NULL, order_id INT DEFAULT NULL, order_item_id INT DEFAULT NULL, order_item_unit_id INT DEFAULT NULL, type VARCHAR(255) NOT NULL, label VARCHAR(255) DEFAULT NULL, amount INT NOT NULL, is_neutral TINYINT(1) NOT NULL, is_locked TINYINT(1) NOT NULL, origin_id INT DEFAULT NULL, origin_type VARCHAR(255) DEFAULT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, INDEX IDX_ACA6E0F28D9F6D38 (order_id), INDEX IDX_ACA6E0F2E415FB15 (order_item_id), INDEX IDX_ACA6E0F2F720C233 (order_item_unit_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_order_comment (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, state VARCHAR(255) NOT NULL, comment LONGTEXT DEFAULT NULL, notify_customer TINYINT(1) NOT NULL, author VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, INDEX IDX_8EA9CF098D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_order_identity (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(255) DEFAULT NULL, INDEX IDX_5757A18E8D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_order_item_unit (id INT AUTO_INCREMENT NOT NULL, order_item_id INT NOT NULL, adjustments_total INT NOT NULL, INDEX IDX_82BF226EE415FB15 (order_item_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'ALTER TABLE order_items ADD CONSTRAINT FK_62809DB08D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE' ); $this->addSql( 'ALTER TABLE login_access_tokens ADD CONSTRAINT FK_7EC367D3A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE oauth2_access_tokens ADD CONSTRAINT FK_D247A21B19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)' ); $this->addSql( 'ALTER TABLE oauth2_access_tokens ADD CONSTRAINT FK_D247A21BA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE oauth2_auth_codes ADD CONSTRAINT FK_A018A10D19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)' ); $this->addSql( 'ALTER TABLE oauth2_auth_codes ADD CONSTRAINT FK_A018A10DA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE oauth2_refresh_tokens ADD CONSTRAINT FK_D394478C19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)' ); $this->addSql( 'ALTER TABLE oauth2_refresh_tokens ADD CONSTRAINT FK_D394478CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE user_user_group ADD CONSTRAINT FK_28657971A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE user_user_group ADD CONSTRAINT FK_28657971FE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)' ); $this->addSql( 'ALTER TABLE user_oauth_clients ADD CONSTRAINT FK_FD402C51A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE user_oauth_clients ADD CONSTRAINT FK_FD402C5119EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)' ); $this->addSql( 'ALTER TABLE slack_invite ADD CONSTRAINT FK_738D77CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql('ALTER TABLE script ADD CONSTRAINT FK_1C81873A4D4CA094 FOREIGN KEY (git_id) REFERENCES git (id)'); $this->addSql( 'ALTER TABLE script ADD CONSTRAINT FK_1C81873A61220EA6 FOREIGN KEY (creator_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE script_authors ADD CONSTRAINT FK_D304ED1BA1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE script_authors ADD CONSTRAINT FK_D304ED1BA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE script_users ADD CONSTRAINT FK_78458A76A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE script_users ADD CONSTRAINT FK_78458A76A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE script_groups ADD CONSTRAINT FK_90B1718AA1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE script_groups ADD CONSTRAINT FK_90B1718AFE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)' ); $this->addSql( 'ALTER TABLE script_categories ADD CONSTRAINT FK_CD9E8798A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE script_categories ADD CONSTRAINT FK_CD9E879812469DE2 FOREIGN KEY (category_id) REFERENCES category (id)' ); $this->addSql( 'ALTER TABLE releases ADD CONSTRAINT FK_7896E4D1A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE review ADD CONSTRAINT FK_794381C6A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE review ADD CONSTRAINT FK_794381C6A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE hook ADD CONSTRAINT FK_A45843551844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE server ADD CONSTRAINT FK_5A6DD5F61844E6B7 FOREIGN KEY (server_id) REFERENCES server_slack_channel (id)' ); $this->addSql( 'ALTER TABLE server_groups ADD CONSTRAINT FK_891100B61844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE server_groups ADD CONSTRAINT FK_891100B6FE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)' ); $this->addSql( 'ALTER TABLE server_authors ADD CONSTRAINT FK_FC7231ED1844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE server_authors ADD CONSTRAINT FK_FC7231EDA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE server_details ADD CONSTRAINT FK_5810361844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE server_details ADD CONSTRAINT FK_58103634B5C767 FOREIGN KEY (serverdetail_id) REFERENCES server_detail (id)' ); $this->addSql( 'ALTER TABLE user_serveruses ADD CONSTRAINT FK_2E513393EB1E3248 FOREIGN KEY (serveruse_id) REFERENCES server_use (id)' ); $this->addSql( 'ALTER TABLE user_serveruses ADD CONSTRAINT FK_2E513393A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE server_serveruse ADD CONSTRAINT FK_28A1B5EAEB1E3248 FOREIGN KEY (serveruse_id) REFERENCES server_use (id)' ); $this->addSql( 'ALTER TABLE server_serveruse ADD CONSTRAINT FK_28A1B5EA1844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F28D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE' ); $this->addSql( 'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F2E415FB15 FOREIGN KEY (order_item_id) REFERENCES order_items (id) ON DELETE CASCADE' ); $this->addSql( 'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F2F720C233 FOREIGN KEY (order_item_unit_id) REFERENCES sylius_order_item_unit (id) ON DELETE CASCADE' ); $this->addSql( 'ALTER TABLE sylius_order_comment ADD CONSTRAINT FK_8EA9CF098D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id)' ); $this->addSql( 'ALTER TABLE sylius_order_identity ADD CONSTRAINT FK_5757A18E8D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id)' ); $this->addSql( 'ALTER TABLE sylius_order_item_unit ADD CONSTRAINT FK_82BF226EE415FB15 FOREIGN KEY (order_item_id) REFERENCES order_items (id) ON DELETE CASCADE' ); } /** * @param Schema $schema */ public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs $this->abortIf( $this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.' ); $this->addSql('ALTER TABLE order_items DROP FOREIGN KEY FK_62809DB08D9F6D38'); $this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F28D9F6D38'); $this->addSql('ALTER TABLE sylius_order_comment DROP FOREIGN KEY FK_8EA9CF098D9F6D38'); $this->addSql('ALTER TABLE sylius_order_identity DROP FOREIGN KEY FK_5757A18E8D9F6D38'); $this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F2E415FB15'); $this->addSql('ALTER TABLE sylius_order_item_unit DROP FOREIGN KEY FK_82BF226EE415FB15'); $this->addSql('ALTER TABLE user_user_group DROP FOREIGN KEY FK_28657971FE54D947'); $this->addSql('ALTER TABLE script_groups DROP FOREIGN KEY FK_90B1718AFE54D947'); $this->addSql('ALTER TABLE server_groups DROP FOREIGN KEY FK_891100B6FE54D947'); $this->addSql('ALTER TABLE oauth2_access_tokens DROP FOREIGN KEY FK_D247A21B19EB6921'); $this->addSql('ALTER TABLE oauth2_auth_codes DROP FOREIGN KEY FK_A018A10D19EB6921'); $this->addSql('ALTER TABLE oauth2_refresh_tokens DROP FOREIGN KEY FK_D394478C19EB6921'); $this->addSql('ALTER TABLE user_oauth_clients DROP FOREIGN KEY FK_FD402C5119EB6921'); $this->addSql('ALTER TABLE login_access_tokens DROP FOREIGN KEY FK_7EC367D3A76ED395'); $this->addSql('ALTER TABLE oauth2_access_tokens DROP FOREIGN KEY FK_D247A21BA76ED395'); $this->addSql('ALTER TABLE oauth2_auth_codes DROP FOREIGN KEY FK_A018A10DA76ED395'); $this->addSql('ALTER TABLE oauth2_refresh_tokens DROP FOREIGN KEY FK_D394478CA76ED395'); $this->addSql('ALTER TABLE user_user_group DROP FOREIGN KEY FK_28657971A76ED395'); $this->addSql('ALTER TABLE user_oauth_clients DROP FOREIGN KEY FK_FD402C51A76ED395'); $this->addSql('ALTER TABLE slack_invite DROP FOREIGN KEY FK_738D77CA76ED395'); $this->addSql('ALTER TABLE script DROP FOREIGN KEY FK_1C81873A61220EA6'); $this->addSql('ALTER TABLE script_authors DROP FOREIGN KEY FK_D304ED1BA76ED395'); $this->addSql('ALTER TABLE script_users DROP FOREIGN KEY FK_78458A76A76ED395'); $this->addSql('ALTER TABLE review DROP FOREIGN KEY FK_794381C6A76ED395'); $this->addSql('ALTER TABLE server_authors DROP FOREIGN KEY FK_FC7231EDA76ED395'); $this->addSql('ALTER TABLE user_serveruses DROP FOREIGN KEY FK_2E513393A76ED395'); $this->addSql('ALTER TABLE script_authors DROP FOREIGN KEY FK_D304ED1BA1C01850'); $this->addSql('ALTER TABLE script_users DROP FOREIGN KEY FK_78458A76A1C01850'); $this->addSql('ALTER TABLE script_groups DROP FOREIGN KEY FK_90B1718AA1C01850'); $this->addSql('ALTER TABLE script_categories DROP FOREIGN KEY FK_CD9E8798A1C01850'); $this->addSql('ALTER TABLE releases DROP FOREIGN KEY FK_7896E4D1A1C01850'); $this->addSql('ALTER TABLE review DROP FOREIGN KEY FK_794381C6A1C01850'); $this->addSql('ALTER TABLE script_categories DROP FOREIGN KEY FK_CD9E879812469DE2'); $this->addSql('ALTER TABLE script DROP FOREIGN KEY FK_1C81873A4D4CA094'); $this->addSql('ALTER TABLE hook DROP FOREIGN KEY FK_A45843551844E6B7'); $this->addSql('ALTER TABLE server_groups DROP FOREIGN KEY FK_891100B61844E6B7'); $this->addSql('ALTER TABLE server_authors DROP FOREIGN KEY FK_FC7231ED1844E6B7'); $this->addSql('ALTER TABLE server_details DROP FOREIGN KEY FK_5810361844E6B7'); $this->addSql('ALTER TABLE server_serveruse DROP FOREIGN KEY FK_28A1B5EA1844E6B7'); $this->addSql('ALTER TABLE server_details DROP FOREIGN KEY FK_58103634B5C767'); $this->addSql('ALTER TABLE server DROP FOREIGN KEY FK_5A6DD5F61844E6B7'); $this->addSql('ALTER TABLE user_serveruses DROP FOREIGN KEY FK_2E513393EB1E3248'); $this->addSql('ALTER TABLE server_serveruse DROP FOREIGN KEY FK_28A1B5EAEB1E3248'); $this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F2F720C233'); $this->addSql('DROP TABLE cron_task'); $this->addSql('DROP TABLE orders'); $this->addSql('DROP TABLE order_items'); $this->addSql('DROP TABLE user_group'); $this->addSql('DROP TABLE login_access_tokens'); $this->addSql('DROP TABLE oauth2_access_tokens'); $this->addSql('DROP TABLE oauth2_auth_codes'); $this->addSql('DROP TABLE oauth2_clients'); $this->addSql('DROP TABLE oauth2_refresh_tokens'); $this->addSql('DROP TABLE session'); $this->addSql('DROP TABLE user'); $this->addSql('DROP TABLE user_user_group'); $this->addSql('DROP TABLE user_oauth_clients'); $this->addSql('DROP TABLE slack_invite'); $this->addSql('DROP TABLE language'); $this->addSql('DROP TABLE library'); $this->addSql('DROP TABLE script'); $this->addSql('DROP TABLE script_authors'); $this->addSql('DROP TABLE script_users'); $this->addSql('DROP TABLE script_groups'); $this->addSql('DROP TABLE script_categories'); $this->addSql('DROP TABLE category'); $this->addSql('DROP TABLE git'); $this->addSql('DROP TABLE releases'); $this->addSql('DROP TABLE review'); $this->addSql('DROP TABLE hook'); $this->addSql('DROP TABLE server'); $this->addSql('DROP TABLE server_groups'); $this->addSql('DROP TABLE server_authors'); $this->addSql('DROP TABLE server_details'); $this->addSql('DROP TABLE server_detail'); $this->addSql('DROP TABLE server_slack_channel'); $this->addSql('DROP TABLE server_use'); $this->addSql('DROP TABLE user_serveruses'); $this->addSql('DROP TABLE server_serveruse'); $this->addSql('DROP TABLE user_signature'); $this->addSql('DROP TABLE type_client'); $this->addSql('DROP TABLE type_default_provider'); $this->addSql('DROP TABLE type_dreamscape_provider'); $this->addSql('DROP TABLE type_osscape_provider'); $this->addSql('DROP TABLE type_pkhonor_provider'); $this->addSql('DROP TABLE type_randoms'); $this->addSql('DROP TABLE sylius_sequence'); $this->addSql('DROP TABLE sylius_adjustment'); $this->addSql('DROP TABLE sylius_order_comment'); $this->addSql('DROP TABLE sylius_order_identity'); $this->addSql('DROP TABLE sylius_order_item_unit'); } }
Parabot/BDN-V3
app/Migrations/Version20170820234613.php
PHP
mit
32,193
package com.openknowl.okhttpexample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { public static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.github.com/users/KimKyung-man") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { Log.i(TAG, "" + response.body().string()); } }); } }
openknowl/android-prototyper-tutorials
android/android_tutorial_8/OkHttpExample/app/src/main/java/com/openknowl/okhttpexample/MainActivity.java
Java
mit
1,171
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./5fe6ce7f3769222d015404ce55e3969363e8ca463dcbc38273278839e8fff26f.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/8e8c4edff5c0066bfcd8acdd9334efa8b137ce8b3ddf889c88ad7bede2970d9f.html
HTML
mit
550
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-algebra-tactics: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.1 / mathcomp-algebra-tactics - 0.1.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-algebra-tactics <small> 0.1.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-10-18 13:00:49 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-10-18 13:00:49 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;sakaguchi@coins.tsukuba.ac.jp&quot; homepage: &quot;https://github.com/math-comp/algebra-tactics&quot; dev-repo: &quot;git+https://github.com/math-comp/algebra-tactics.git&quot; bug-reports: &quot;https://github.com/math-comp/algebra-tactics/issues&quot; license: &quot;CECILL-B&quot; synopsis: &quot;Ring and field tactics for Mathematical Components&quot; description: &quot;&quot;&quot; This library provides `ring` and `field` tactics for Mathematical Components, that work with any `comRingType` and `fieldType` instances, respectively. Their instance resolution is done through canonical structure inference. Therefore, they work with abstract rings and do not require `Add Ring` and `Add Field` commands. Another key feature of this library is that they automatically push down ring morphisms and additive functions to leaves of ring/field expressions before normalization to the Horner form.&quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot; ] install: [make &quot;install&quot;] depends: [ &quot;coq&quot; {(&gt;= &quot;8.13&quot; &amp; &lt; &quot;8.15~&quot;)} &quot;coq-mathcomp-algebra&quot; {(&gt;= &quot;1.12&quot; &amp; &lt; &quot;1.13~&quot;)} &quot;coq-mathcomp-zify&quot; {(&gt;= &quot;1.1.0&quot;)} &quot;coq-elpi&quot; {(&gt;= &quot;1.10.1&quot;)} ] tags: [ &quot;logpath:mathcomp.algebra_tactics&quot; ] authors: [ &quot;Kazuhiko Sakaguchi&quot; ] url { src: &quot;https://github.com/math-comp/algebra-tactics/archive/refs/tags/0.1.0.tar.gz&quot; checksum: &quot;sha256=aca9d33fec72a9e2fb37ccbc91c492ceae9b75d3cdce37ddd9a224ea3cef0f3f&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-algebra-tactics.0.1.0 coq.8.11.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1). The following dependencies couldn&#39;t be met: - coq-mathcomp-algebra-tactics -&gt; coq &gt;= 8.13 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-algebra-tactics.0.1.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.09.1-2.0.6/released/8.11.1/mathcomp-algebra-tactics/0.1.0.html
HTML
mit
7,294
/* global describe, it */ var assert = require('assert') var constantCase = require('./') describe('constant case', function () { it('should upper case a single word', function () { assert.equal(constantCase('test'), 'TEST') assert.equal(constantCase('TEST'), 'TEST') }) it('should constant case regular sentence cased strings', function () { assert.equal(constantCase('test string'), 'TEST_STRING') assert.equal(constantCase('Test String'), 'TEST_STRING') }) it('should constant case non-alphanumeric separators', function () { assert.equal(constantCase('dot.case'), 'DOT_CASE') assert.equal(constantCase('path/case'), 'PATH_CASE') }) it('should constant case pascal cased strings', function () { assert.equal(constantCase('TestString'), 'TEST_STRING') }) it('should support locales', function () { assert.equal(constantCase('myString', 'tr'), 'MY_STRİNG') }) })
blakeembrey/constant-case
test.js
JavaScript
mit
922
(function($){ $.fn.onImagesLoaded = function(_cb,_ca) { return this.each(function() { var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this), _cont = this, i = 0, _loading=function() { if( typeof _cb === 'function') _cb(_cont); }, _done=function() { if( typeof _ca === 'function' ) _ca(_cont); }; if( $imgs.length ) { $imgs.each(function() { var _img = this; _loading(); $(_img).load(function(){ _done(); }); }); } }); } })(jQuery)
flashycud/timestack
static/js/lib.js
JavaScript
mit
614
--- layout: post title: "Kindling a Fire" date: 2016-10-01 19:45:31 +0530 categories: ["design"] --- <img src="http://static.boredpanda.com/blog/wp-content/uuuploads/life-hacks/life-hacks-8.jpg" alt="Doritos">
higfig/HigFig.github.io
_posts/2016-10-01-simple3.markdown
Markdown
mit
213
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | http://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'order/all'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE;
z32556601/90ping_backend
application/config/routes.php
PHP
mit
1,971
# Aid Programming Language ![](sketch.png) Author: Ian Byrd <ian@byrd.im> Last updated: 13 December 2015 ## Abstract This document is a starting point for a new programming language called Aid. First of all, it's not a spec or any sort of a spec draft. This document isn't supposed to specify anything. Yet it's here to show where Aid comes from, where it goes and what are its fundamental aims. ## Background Aid is experiencing heavy influence by Go, C++, Swift and Erlang (listed in the order of significance). Go is an amazing language for what it's already being used for, albeit it totally ignores all the last twenty years of PL research. Go is a language for corporations, massive software and rapidly changing teams, not programmers. I am not saying it's bad. I'm however trying to say there is a huge room for improvements, albeit it requires some tradeoffs. Unfortunately, the Go team would never ever accept some of these. C++ is adorable, stable and expressive, yet crazy, unfriednly and slow on compile time. C++17 looks promising, but you can't really do anything with the legacy and BC issues—they'll stay forever. C++ is already behind, future versions of the language won't change anything, but make existing C++ programmers' lives easier. On the other hand, C++ has some neat underappreciated concepts and abstractions we mustn't ignore. Python has batteries and we need them. Still we don't need all the rubbish that comes along with dynamic typing (massive runtime assertions, monkey patching, whatever). ## Language Aid is a strong statically typed language, which literally means that variable types are known at compile-time and can't be changed. Aid looks pretty similiar to Go, yet makes some syntax changes (commas, "template"-o-syntax, etc). Needless to say, Aid does provide huge idiomatic changes: e.g. it doesn't have arrays at all, slices only. Don't worry, it's usually just all about abstracting away from any low-level aka C-style stuff.
aid-lang/design
README.md
Markdown
mit
1,984
Profiling ========= Various notes from some early profiling, not expected to be useful to anyone but me. Finding potential hotspots with valgrind callgrind -------------------------------------------------- valgrind --tool=callgrind ./plot t/examples/fibo.scm then inspect the output `callgrind.out.nnnn` file using kcachegrind kcachegrind callgrind.out.9003 Finding potential hotspots with gprof ------------------------------------- compile and link with -pg run program as normal, this products a gmon.out file in current dir run 'gprof plot' and it will generate some pretty output Timing ------ time ./plot t/examples/fibo.scm consider changing CFLAGS in config.mk to include `-O3` (see commented line above CFLAGS) pre gc: (fibo 31) 2.9s 6731342 plot_values post gc: favouring arena over recycling: (fibo 31) 2.3s 4038805 plot_values favouring recycling over arena (correct behavior): (fibo 31) 2.7s 4038805 plot_values however after making many changes the figures were: plot GC stats: Max in use '4038826' Still had in the bank: '61174' num recycled '2692537', reclaimed '2692537' used - reclaimed '1346289' non-reclaimed (still in use at cleanup) '0' real 0m3.131s user 0m2.936s sys 0m0.188s after implementing collection on (temp) values generated as args to functions: (NB: this is the same as the previous stats + func-call tmp-reclamation) (fibo 31) 2.9s plot GC stats: Max in use '2692574' Still had in the bank: '1407426' num recycled '4038789', reclaimed '4038805' used - reclaimed '-1346231' non-reclaimed (still in use at cleanup) '16' real 0m2.866s user 0m2.692s sys 0m0.164s This means: (4038826 - 2692574) / 4038826 * 100 == 33% improvement in max memory use (3.1 - 2.9) / 3.1 * 100 = 6.5% improvement in run-time implementing env memory management: before: 2692537 * 32 / 1024 / 1024 = 82MB after: 31 * 32 = 992 Bytes this should be freeing more values, need to look into that. sadly this has also increased runtime: plot GC stats: ##### plot_value stats ##### Max in use '2692574' Still had in the bank: '7426' num recycled '4038789', reclaimed '4038805' used - reclaimed = '-1346231' non-reclaimed (still in use at cleanup) '16' ##### plot_env stats ##### Max in use '31' Still had in the bank: '2699969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '30' real 0m3.056s user 0m2.896s sys 0m0.148s implementing correct handling of values in define and lambda: before: 2692574 * 48 / 1024 / 1024 = 123MB after: 52 * 48 / 1024 = 2.5KB plot GC stats: ##### plot_value stats ##### Max in use '52' Still had in the bank: '948' num recycled '6731311', reclaimed '6731341' used - reclaimed = '-6731289' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' real 0m2.895s user 0m2.856s sys 0m0.032s added arena allocation for plot_hash_entry(s): memory usage (total) : 100MB plot GC stats: ##### plot_value stats ##### Max in use '52' Still had in the bank: '948' num recycled '6731311', reclaimed '6731341' used - reclaimed = '-6731289' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' ##### plot_hash_entry stats ##### Max in use '2692556' Still had in the bank: '7444' num recycled '0', reclaimed '0' used - reclaimed = '2692556' non-reclaimed (still in use at cleanup) '2692556' real 0m3.240s user 0m3.200s sys 0m0.032s correctly decr hash_entry(s): memory usage (total): 132 KB plot GC stats: ##### plot_value stats ##### Max in use '52' Still had in the bank: '948' num recycled '6731311', reclaimed '6731341' used - reclaimed = '-6731289' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' ##### plot_hash_entry stats ##### Max in use '49' Still had in the bank: '951' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692488' non-reclaimed (still in use at cleanup) '19' real 0m2.809s user 0m2.804s sys 0m0.000s before: ##### plot_value stats ##### Max in use '52' Still had in the bank: '948' num recycled '6731311', reclaimed '6731341' used - reclaimed = '-6731289' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' ##### plot_hash_entry stats ##### Max in use '49' Still had in the bank: '951' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692488' non-reclaimed (still in use at cleanup) '19' real 0m3.706s user 0m3.696s sys 0m0.004s removing subform tests from plot_eval_func_call, instead calling plot_eval_expr: plot GC stats: ##### plot_value stats ##### Max in use '52' Still had in the bank: '948' num recycled '6731311', reclaimed '6731341' used - reclaimed = '-6731289' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' ##### plot_hash_entry stats ##### Max in use '49' Still had in the bank: '951' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692488' non-reclaimed (still in use at cleanup) '19' real 0m3.089s user 0m3.080s sys 0m0.000s After adding a gazilion features: 1346269 plot GC stats: ##### plot_value stats ##### Max in use '82' Still had in the bank: '918' num recycled '9423820', reclaimed '9423880' used - reclaimed = '-9423798' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' ##### plot_hash_entry stats ##### Max in use '97' Still had in the bank: '903' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692440' non-reclaimed (still in use at cleanup) '67' real 0m3.793s user 0m3.780s sys 0m0.008s same as above but compiled with -O3: 1346269 plot GC stats: ##### plot_value stats ##### Max in use '82' Still had in the bank: '918' num recycled '9423820', reclaimed '9423880' used - reclaimed = '-9423798' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' ##### plot_hash_entry stats ##### Max in use '97' Still had in the bank: '903' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692440' non-reclaimed (still in use at cleanup) '67' real 0m3.146s user 0m3.140s sys 0m0.000s After combining is_form and eval_form, adding hashing and using it for eval_form NB: not yet using it within hash or env: 1346269 plot GC stats: ##### plot_value stats ##### Max in use '52' Still had in the bank: '948' num recycled '6731313', reclaimed '6731343' used - reclaimed = '-6731291' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' ##### plot_hash_entry stats ##### Max in use '97' Still had in the bank: '903' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692440' non-reclaimed (still in use at cleanup) '67' real 0m3.727s user 0m3.712s sys 0m0.008s NB: our max in use has gone back down, this is due to me previously allocating a plot_value at the start of plot_eval_form, sometimes simply to throw it away (on return = stack unwinding). same as above but compiled with -O3: 1346269 plot GC stats: ##### plot_value stats ##### Max in use '52' Still had in the bank: '948' num recycled '6731313', reclaimed '6731343' used - reclaimed = '-6731291' non-reclaimed (still in use at cleanup) '22' ##### plot_env stats ##### Max in use '31' Still had in the bank: '969' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692506' non-reclaimed (still in use at cleanup) '1' ##### plot_hash_entry stats ##### Max in use '97' Still had in the bank: '903' num recycled '2692507', reclaimed '2692537' used - reclaimed = '-2692440' non-reclaimed (still in use at cleanup) '67' real 0m2.063s user 0m2.052s sys 0m0.004s NB: without -O3 the above hashing change made no difference, with -O3 it is down from 3.2 to 2.1, that is an awesome improvement. after making plot_hash_get use the hash (NB: set does not yet): real 0m2.903s user 0m2.896s sys 0m0.000s same with -O3: real 0m1.396s user 0m1.388s sys 0m0.004s NB: serious improvement again from pre-hashing-o3 to post-hashing-o3 still have to make plot_hash_set use hashes moving plot_hash_set to our new scheme real 0m3.929s user 0m3.920s sys 0m0.000s unexpected! huge slowdown! same as above with with -O3 real 0m1.964s user 0m1.960s sys 0m0.000s I cannot explain this, wow. FIXME: unit tests give a hint: t/test_hash.c:43:F:test_hash:test_hash:0: Assertion 'hash.n_elems == 3' failed it may be my usage in _set has an error :) PANIC OVER, above was due to inefficient search inside get (not stopping early) and due to signed long long overflow causing us to stop either way too early or not early enough. Both have been fixed and pushed to current master real 0m2.604s user 0m2.592s sys 0m0.000s with -O3: real 0m1.259s user 0m1.252s sys 0m0.000s MUCH BETTER!!
mkfifo/plot
docs/profiling.md
Markdown
mit
13,055
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <!-- This is the personal blog of Carlo Sciolla, a.k.a. skuro. Thank you oh so much for peeking around the source code of my blog! I'm an experienced software developer, but as I usually hang around the server side of the world, the markup, JS and CSS here might not be the most beautiful thing you have ever seen. Also, most of it is a cut'n'paste, or strongly inspired by half of the Internet, so if you recognize any of your work in this site please let me know if you want any public endorsement, as I have eternal gratitude for you! Some of the projects that were used in the making of this side are: - [Twitter Bootstrap](http://getbootstrap.com) - [Bootswatch Cyborg theme](http://bootswatch.com/cyborg/) Truly yours, c. --> <meta charset="utf-8" /> <meta name="generator" content="skuro.tk/0.1 | jekyll/2.0.3" /> <meta name="description" content="Personal Blog of Carlo Sciolla (skuro)" /> <meta name="keywords" content="clojure,java,scala,alfresco,lambdalf,performance,programming,developer,backbase" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- Twitter Cards --> <meta name="twitter:card" content="summary"> <meta name="twitter:image" content="http://skuro.tk/img/avatar.jpg"> <meta name="twitter:title" content="subversion"> <meta name="twitter:description" content="Personal Blog of Carlo Sciolla (skuro)"> <meta name="twitter:creator" content="@skuro"> <!-- Open Graph --> <meta property="og:locale" content="en_US"> <meta property="og:type" content="article"> <meta property="og:title" content="subversion"> <meta property="og:description" content="Personal Blog of Carlo Sciolla (skuro)"> <meta property="og:url" content="http://skuro.tk/category/subversion/index.html"> <meta property="og:site_name" content="SKURO! -- Shading lights"> <!-- <link rel="stylesheet" href="/stylesheets/styles.css" type="text/css" /> --> <!-- <link rel="stylesheet" href="/stylesheets/pygment_trac.css" type="text/css" /> --> <!-- Bootstrap --> <link rel="stylesheet" href="/stylesheets/bootstrap.min.css" type="text/css" /> <!-- Personal CSS --> <link rel="stylesheet" href="/stylesheets/skuro.css" type="text/css" /> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <title>subversion @ SKURO! -- Shading lights</title> </head> <body> <!-- Main content --> <div class="navbar navbar-default navbar-fixed-top"> <div class="container"><!-- containers restrict width --> <span class="navbar-header"> <a class="navbar-brand" href="/">SKURO!</a> </span> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/archive"><strong>Archive</strong></a></li> <li><a href="/category"><strong>Categories</strong></a></li> <li><a href="/about"><strong>About me</strong></a></li> </ul> <div id="social-links" class="nav navbar-nav navbar-right"> <div class="btn-toolbar"> <div class="btn-group"> <button type="button" class="btn btn-default"><a href="https://github.com/skuro"><img src="/img/github.png" /></a></button> <button type="button" class="btn btn-default"><a href="http://nl.linkedin.com/in/carlosciolla"><img src="/img/linkedin.png" /></a></button> <button type="button" class="btn btn-default"><a href="https://twitter.com/skuro"><img src="/img/twitter.png" /></a></button> <button type="button" class="btn btn-default"><a href="/rss2.xml"><img src="/img/rss.png" /></a></button> </div> </div> </div> </div> </div> </div> <div class="container post-content"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-7"> <div> <h1> Posts filed under <a href="/category/subversion/index.html">#subversion</a> </h1> <div> <ul> <li> <a href="/2013/02/18/svn-postcommit-hook-jira-comments">A svn post commit hook to comment on Jira</a> <h6>18 February 2013 <span> <span class="label label-primary category"><a href="/category/subversion">#subversion</a></span> <span class="label label-primary category"><a href="/category/jira">#jira</a></span> <span class="label label-primary category"><a href="/category/development">#development</a></span> <span class="label label-primary category"><a href="/category/software">#software</a></span> </span> </h6> </li> </ul> </div> </div> </div><!-- col-md-6 --> <div class="span5">&nbsp;</div> </div><!-- row --> </div> <!-- Footer --> <footer> <div class="container foot-info"> <div class="row"> <div class="col-md-12"> <p> <span rel="dct:type" property="dct:title" href="http://purl.org/dc/dcmitype/Text">SKURO! blog</span> by <a rel="cc:attributionURL" property="cc:attributionName" href="http://skuro.tk"> Carlo Sciolla </a> </p> <p> All text licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/" rel="license">CC BY 3.0</a> <br /> All code licensed under <a href="https://raw.githubusercontent.com/skuro/skuro.github.com/sources/LICENSE.txt">MIT</a> unless otherwise specified </div> </div> </div> </footer> <!-- end Footer --> <!-- end Main content --> <!-- Advertisement --> <div class="google-ads"> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- ghpages-skyscraper --> <ins class="adsbygoogle" style="display:inline-block;width:120px;height:600px" data-ad-client="ca-pub-5536661153340295" data-ad-slot="1277668326"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> <!-- end Advertisement --> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="/js/bootstrap.min.js"></script> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try{ var pageTracker = _gat._getTracker("UA-6754361-1"); pageTracker._trackPageview(); } catch(err) {} </script> </body> </html>
skuro/skuro.github.com
category/subversion/index.html
HTML
mit
7,472
@NodeEntity public class Country{ @GraphId private Long id; @Indexed(unique=true) private String coutryName; @RelatedTo private Set<City> cities; public Country(){} public Country(String countryName){ this.countryName = countryName; } }
yanisIk/Hobdy
Domain/Country.java
Java
mit
254
/*! normalize.css v6.0.0 | MIT License | github.com/necolas/normalize.css */ /* Document ========================================================================== */ /** * 1. Correct the line height in all browsers. * 2. Prevent adjustments of font size after orientation changes in * IE on Windows Phone and in iOS. */ @import url(http://fonts.googleapis.com/css?family=Open+Sans:300,400,800); @import url(http://fonts.googleapis.com/css?family=PT+Serif:400,700,400italic,700italic); html { line-height: 1.15; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ } /* Sections ========================================================================== */ /** * Add the correct display in IE 9-. */ article, aside, footer, header, nav, section { display: block; } /** * Correct the font size and margin on `h1` elements within `section` and * `article` contexts in Chrome, Firefox, and Safari. */ h1 { font-size: 2em; margin: 0.67em 0; } /* Grouping content ========================================================================== */ /** * Add the correct display in IE 9-. * 1. Add the correct display in IE. */ figcaption, figure, main { /* 1 */ display: block; } /** * Add the correct margin in IE 8. */ figure { margin: 1em 40px; } /** * 1. Add the correct box sizing in Firefox. * 2. Show the overflow in Edge and IE. */ hr { box-sizing: content-box; /* 1 */ height: 0; /* 1 */ overflow: visible; /* 2 */ } /** * 1. Correct the inheritance and scaling of font size in all browsers. * 2. Correct the odd `em` font sizing in all browsers. */ pre { font-family: monospace, monospace; /* 1 */ font-size: 1em; /* 2 */ } /* Text-level semantics ========================================================================== */ /** * 1. Remove the gray background on active links in IE 10. * 2. Remove gaps in links underline in iOS 8+ and Safari 8+. */ a { background-color: transparent; /* 1 */ -webkit-text-decoration-skip: objects; /* 2 */ } /** * 1. Remove the bottom border in Chrome 57- and Firefox 39-. * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari. */ abbr[title] { border-bottom: none; /* 1 */ text-decoration: underline; /* 2 */ text-decoration: underline dotted; /* 2 */ } /** * Prevent the duplicate application of `bolder` by the next rule in Safari 6. */ b, strong { font-weight: inherit; } /** * Add the correct font weight in Chrome, Edge, and Safari. */ b, strong { font-weight: bolder; } /** * 1. Correct the inheritance and scaling of font size in all browsers. * 2. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp { font-family: monospace, monospace; /* 1 */ font-size: 1em; /* 2 */ } /** * Add the correct font style in Android 4.3-. */ dfn { font-style: italic; } /** * Add the correct background and color in IE 9-. */ mark { background-color: #ff0; color: #000; } /** * Add the correct font size in all browsers. */ small { font-size: 80%; } /** * Prevent `sub` and `sup` elements from affecting the line height in * all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* Embedded content ========================================================================== */ /** * Add the correct display in IE 9-. */ audio, video { display: inline-block; } /** * Add the correct display in iOS 4-7. */ audio:not([controls]) { display: none; height: 0; } /** * Remove the border on images inside links in IE 10-. */ img { border-style: none; } /** * Hide the overflow in IE. */ svg:not(:root) { overflow: hidden; } /* Forms ========================================================================== */ /** * Remove the margin in Firefox and Safari. */ button, input, optgroup, select, textarea { margin: 0; } /** * Show the overflow in IE. * 1. Show the overflow in Edge. */ button, input { /* 1 */ overflow: visible; } /** * Remove the inheritance of text transform in Edge, Firefox, and IE. * 1. Remove the inheritance of text transform in Firefox. */ button, select { /* 1 */ text-transform: none; } /** * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video` * controls in Android 4. * 2. Correct the inability to style clickable types in iOS and Safari. */ button, html [type="button"], [type="reset"], [type="submit"] { -webkit-appearance: button; /* 2 */ } /** * Remove the inner border and padding in Firefox. */ button::-moz-focus-inner, [type="button"]::-moz-focus-inner, [type="reset"]::-moz-focus-inner, [type="submit"]::-moz-focus-inner { border-style: none; padding: 0; } /** * Restore the focus styles unset by the previous rule. */ button:-moz-focusring, [type="button"]:-moz-focusring, [type="reset"]:-moz-focusring, [type="submit"]:-moz-focusring { outline: 1px dotted ButtonText; } /** * 1. Correct the text wrapping in Edge and IE. * 2. Correct the color inheritance from `fieldset` elements in IE. * 3. Remove the padding so developers are not caught out when they zero out * `fieldset` elements in all browsers. */ legend { box-sizing: border-box; /* 1 */ color: inherit; /* 2 */ display: table; /* 1 */ max-width: 100%; /* 1 */ padding: 0; /* 3 */ white-space: normal; /* 1 */ } /** * 1. Add the correct display in IE 9-. * 2. Add the correct vertical alignment in Chrome, Firefox, and Opera. */ progress { display: inline-block; /* 1 */ vertical-align: baseline; /* 2 */ } /** * Remove the default vertical scrollbar in IE. */ textarea { overflow: auto; } /** * 1. Add the correct box sizing in IE 10-. * 2. Remove the padding in IE 10-. */ [type="checkbox"], [type="radio"] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } /** * Correct the cursor style of increment and decrement buttons in Chrome. */ [type="number"]::-webkit-inner-spin-button, [type="number"]::-webkit-outer-spin-button { height: auto; } /** * 1. Correct the odd appearance in Chrome and Safari. * 2. Correct the outline style in Safari. */ [type="search"] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /** * Remove the inner padding and cancel buttons in Chrome and Safari on macOS. */ [type="search"]::-webkit-search-cancel-button, [type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /** * 1. Correct the inability to style clickable types in iOS and Safari. * 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Interactive ========================================================================== */ /* * Add the correct display in IE 9-. * 1. Add the correct display in Edge, IE, and Firefox. */ details, menu { display: block; } /* * Add the correct display in all browsers. */ summary { display: list-item; } /* Scripting ========================================================================== */ /** * Add the correct display in IE 9-. */ canvas { display: inline-block; } /** * Add the correct display in IE. */ template { display: none; } /* Hidden ========================================================================== */ /** * Add the correct display in IE 10-. */ [hidden] { display: none; } /*************** COLOR VARIABLES ***************/ /*************** CONSISTENT SETTINGS ***************/ /*************** TYPE SETTINGS ***************/ /*************** A MORE MODERN SCALE http://typecast.com/blog/a-more-modern-scale-for-web-typography ***************/ body { font-size: 1em; /* equivalent to 16px */ line-height: 1.45; /* equivalent to 20px */ } body .intro { font-size: 1.25em; line-height: 1.7; } @media (min-width: 43.75em) { body { font-size: 1em; /* equivalent to 16px */ line-height: 1.375; /* equivalent to 22px */ } } h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 { margin: .5rem 0 1.5rem; font-family: "Open Sans", Helvetica, Arial, sans-serif; } h1, .h1 { font-size: 2em; line-height: 1.25; } @media (min-width: 43.75em) { h1, .h1 { font-size: 2.5em; line-height: 1.125; } } @media (min-width: 56.25em) { h1, .h1 { font-size: 3em; line-height: 1.05; } } h2, .h2 { font-size: 1.625em; line-height: 1.15384615; } @media (min-width: 43.75em) { h2, .h2 { font-size: 2em; line-height: 1.25; } } @media (min-width: 56.25em) { h2, .h2 { font-size: 2.25em; line-height: 1.25; } } h3, .h3 { font-size: 1.375em; line-height: 1.13636364; } @media (min-width: 43.75em) { h3, .h3 { font-size: 1.5em; line-height: 1.25; } } @media (min-width: 56.25em) { h3, .h3 { font-size: 1.75em; line-height: 1.25; } } h4, .h4 { font-size: 1.125em; line-height: 1.11111111; } @media (min-width: 43.75em) { h4, .h4 { line-height: 1.22222222; } } blockquote { font-size: 1.25em; line-height: 1.25; padding: 0; } @media (min-width: 43.75em) { blockquote { font-size: 1.5em; line-height: 1.45833333; } } /*************** TRANSITION ***************/ /* @include transition(all 0.2s ease-in-out); */ /*************** BOX SIZING ***************/ /* @include box-sizing(border-box); */ /*************** CLEAR AFTER FLOATS ***************/ .clearfix { zoom: 1; } .clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; } .clearfix:after { clear: both; } /*************** BUTTON DEFAULTS ***************/ .button, .button-secondary, .button-tertiary, .button__outline { background-color: seagreen; display: inline-block; position: relative; font-family: "Open Sans", Helvetica, Arial, sans-serif; text-decoration: none; color: #fff; font-size: 1em; line-height: 1.2em; font-weight: normal; padding: .5em 1.5em; border: 0; border-radius: 4px; cursor: pointer; margin-bottom: .5em; transition: background-color 0.14s ease-in-out; } .button:hover, .button-secondary:hover, .button-tertiary:hover, .button__outline:hover, .button:focus, .button-secondary:focus, .button-tertiary:focus, .button__outline:focus { color: #fff; text-decoration: none; background-color: #21653f; } .button:active, .button-secondary:active, .button-tertiary:active, .button__outline:active { top: 1px; } .button-secondary { background-color: #233E5B; } .button-secondary:hover { background-color: #152536; } .button-tertiary { background-color: #aaa; } .button-tertiary:hover { background-color: #919191; } .button__outline { background-color: transparent; border: 3px solid seagreen; color: seagreen; } .button__outline:hover { background-color: seagreen; color: #fff; } /*************** FORM STYLING ***************/ label { display: block; margin-bottom: 5px; } input[type=text], input[type=email], input[type=phone], input[type=password], input[type=number], input[type=search], textarea { background: #e6e6e6; padding: 5px; outline: none; border: none; height: 44px; width: 300px; margin-bottom: .5rem; } input[type=text]:focus, input[type=email]:focus, input[type=phone]:focus, input[type=password]:focus, input[type=number]:focus, input[type=search]:focus, textarea:focus { border: 1px solid seagreen; } input[type=text].full-width, input[type=email].full-width, input[type=phone].full-width, input[type=password].full-width, input[type=number].full-width, input[type=search].full-width, textarea.full-width { width: 100%; } textarea { height: 132px; } form { margin-bottom: 40px; } form .field { margin-bottom: 20px; } form .note { margin-top: 5px; color: #aaa; } form .req { font-style: italic; } form .error .reason { margin-top: 5px; color: #FF4136; } form .error input[type=text], form .error input[type=email], form .error input[type=phone], form .error input[type=password], form .error input[type=number], form .error input[type=search], form .error textarea { border-color: #FF4136; } /*************** TABLE STYLES ***************/ table { width: 100%; border: 1px solid #d0d0d0; margin-bottom: 1.5em; } table caption { margin: 0 0 7px; font-size: 0.75em; color: #aaa; text-transform: uppercase; letter-spacing: 1px; } tr { border-bottom: 1px solid #d0d0d0; } tr:nth-child(even) { background-color: #f7f7f7; } td { padding: 7px; border-right: 1px solid #d0d0d0; } td:last-child { border-right: 0; } th { background-color: #f7f7f7; border-bottom: 1px solid #d0d0d0; border-right: 1px solid #d0d0d0; } th:last-child { border-right: 0; } /*************** Darkly Pygments Theme (c) 2014 Sourcey http://sourcey.com ***************/ .highlight { white-space: pre; overflow: auto; word-wrap: normal; /* horizontal scrolling */ border-radius: 3px; padding: 20px; background: #343642; color: #C1C2C3; } .highlight .hll { background-color: #ffc; } .highlight .gd { color: #2e3436; background-color: #0e1416; } .highlight .gr { color: #eeeeec; background-color: #c00; } .highlight .gi { color: #babdb6; background-color: #1f2b2d; } .highlight .go { color: #2c3032; background-color: #2c3032; } .highlight .kt { color: #e3e7df; } .highlight .ni { color: #888a85; } .highlight .c, .highlight .cm, .highlight .c1, .highlight .cs { color: #8D9684; } .highlight .err, .highlight .g, .highlight .l, .highlight .n, .highlight .x, .highlight .p, .highlight .ge, .highlight .gp, .highlight .gs, .highlight .gt, .highlight .ld, .highlight .s, .highlight .nc, .highlight .nd, .highlight .ne, .highlight .nl, .highlight .nn, .highlight .nx, .highlight .py, .highlight .ow, .highlight .w, .highlight .sb, .highlight .sc, .highlight .sd, .highlight .s2, .highlight .se, .highlight .sh, .highlight .si, .highlight .sx, .highlight .sr, .highlight .s1, .highlight .ss, .highlight .bp { color: #C1C2C3; } .highlight .k, .highlight .kc, .highlight .kd, .highlight .kn, .highlight .kp, .highlight .kr, .highlight .nt { color: #729fcf; } .highlight .cp, .highlight .gh, .highlight .gu, .highlight .na, .highlight .nf { color: #E9A94B; } .highlight .m, .highlight .nb, .highlight .no, .highlight .mf, .highlight .mh, .highlight .mi, .highlight .mo, .highlight .il { color: #8ae234; } .highlight .o { color: #989DAA; } .highlight .nv, .highlight .vc, .highlight .vg, .highlight .vi { color: #fff; } /*************** GLOBAL STYLES ***************/ html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; } body { font-family: "PT Serif", Georgia, Times, serif; line-height: 1.75; font-size: 112.5%; color: #111; overflow-x: hidden; margin: 0; } body p, body ul { margin: 0 0 2rem; } ::-moz-selection { background: seagreen; color: white; } ::selection { background: seagreen; color: white; } img, video, audio, iframe, object { max-width: 100%; } .container { max-width: 610px; padding: 0 20px; } /*************** LINK STYLING ***************/ a { color: seagreen; } a:hover { color: #1b5233; } /*************** MENU STYLING ***************/ .nav-collapse { z-index: 1; } .nav-collapse ul { margin: 0; padding: 0; width: 100%; display: block; list-style: none; } .nav-collapse ul li { width: 100%; display: block; background: seagreen; border-bottom: 2px solid #349e63; } .nav-collapse ul li a { color: white; text-decoration: none; display: block; padding: 5px 2rem; } .js .nav-collapse { clip: rect(0 0 0 0); max-height: 0; position: absolute; display: block; overflow: hidden; zoom: 1; clear: both; width: 100%; } .nav-collapse.opened { max-height: 9999px; } .nav-toggle { -webkit-tap-highlight-color: transparent; -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; float: right; line-height: 2em; margin-top: .5em; background-color: seagreen; border-radius: 4px; padding: 0 .5em; color: white; text-decoration: none; position: relative; right: 2rem; transition: all 0.2s ease-in-out; } .nav-toggle:hover { color: white; background-color: #21653f; } /*************** LIST STYLING ***************/ .noList { list-style: none; padding-left: 0; margin-left: 0; } dt { font-weight: bold; } dd { margin: 0 0 1.5rem; } .post ul ul, .post ul ol, .post ol ul, .post ol ol { margin: 0; } /*************** PAGE STYLES ***************/ .pageTitle { margin: 2rem auto 1em; text-align: center; } .content { padding-top: 1em; overflow: hidden; } /*************** HEADER STYLING ***************/ .header { background-color: seagreen; background-image: url("../img/dosomethingbig.jpg"); background-size: cover; background-position: center center; color: white; padding: 0; height: 3em; } .header .container { padding: 0; max-width: 100%; } .header h1 { margin: 0; float: left; padding-left: 2rem; font-size: 1em; line-height: 3em; font-family: "Open Sans", Helvetica, Arial, sans-serif; font-weight: 800; text-transform: uppercase; } .header h1 a { color: white; text-decoration: none; } /*************** POST STYLING ***************/ .post .postTitle { text-align: center; margin-top: 2rem; margin-bottom: 1rem; } .post blockquote { clear: both; margin: 2.5em 0; padding: 0; line-height: 1.8; position: relative; } .post blockquote:before { content: ""; position: absolute; top: -1.25em; background: seagreen; display: block; height: 2px; width: 150px; left: calc(50% - 75px); } .post blockquote:after { content: ""; position: absolute; bottom: -1.25em; background: seagreen; display: block; height: 2px; width: 150px; left: calc(50% - 75px); } .post .meta { text-align: center; color: gray; font-family: "Open Sans", Helvetica, Arial, sans-serif; font-weight: 300; } .post figure { margin: 3rem 0; } .post figure figcaption { text-align: center; font-size: .9em; font-style: italic; color: #5e5e5e; } .post figure img { margin: 0 auto; display: block; } .post img { margin-bottom: 2rem; } .post .highlight { clear: both; margin-bottom: 2rem; } .post .dropcap { color: seagreen; margin-right: .45rem; } .post .featuredImage { position: relative; margin-top: 2rem; } .post .featuredImage img { margin-bottom: 0; } /*************** POST NAV STYLING ***************/ .postNav { border-top: 1px solid #e6e6e6; border-bottom: 1px solid #e6e6e6; overflow: hidden; } .postNav .prev, .postNav .next { display: block; width: 100%; height: 5rem; overflow: hidden; position: relative; font-family: "Open Sans", Helvetica, Arial, sans-serif; font-weight: 800; font-size: .9em; text-transform: uppercase; text-align: center; } .postNav .prev img, .postNav .next img { z-index: 1; display: block; position: absolute; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); left: 0; width: 100%; height: auto; } .postNav .prev span, .postNav .next span { z-index: 10; position: relative; padding: .5rem; position: absolute; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); width: 100%; line-height: 1.4; } .postNav .prev.image, .postNav .next.image { text-decoration: none; color: white; text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.8); padding: 0 .5rem; position: relative; transition: all 0.2s ease-in-out; } .postNav .prev:hover.image, .postNav .next:hover.image { opacity: .8; } .postNav .prev span { left: 0; } .postNav .next span { right: 0; } /*************** FOOTER STYLING ***************/ .footer { text-align: center; padding: 2rem 0; } .footer .container { border-top: 4px solid #d9d9d9; padding-top: .5em; max-width: 90%; } .footer .copy, .footer .footer-links { font-size: .8em; } .footer .copy { margin-bottom: 1rem; } .footer-links ul { text-align: center; } .footer-links ul li { display: inline-block; } .footer-links ul li a { display: inline-block; width: 30px; height: 30px; transition: all 0.2s ease-in-out; } .footer-links ul li a svg { display: block; width: 100%; height: 100%; } .footer-links ul li a svg .outer-shape { fill: seagreen; } .footer-links ul li a svg .inner-shape { fill: white; } .footer-links ul li:hover a svg .outer-shape { fill: #21653f; } /*************** PAGINATION STYLING ***************/ .pagination .next { float: left; } .pagination .previous { float: right; } /*************** POST LIST STYLING ***************/ .posts li { margin-bottom: 4rem; position: relative; } .posts li:before { content: ""; position: absolute; bottom: -2rem; left: 0; background: #e6e6e6; height: 2px; width: 60px; } .posts li a { text-decoration: none; } .posts li a:hover { text-decoration: underline; } .posts li .date { color: gray; font-family: "Open Sans", Helvetica, Arial, sans-serif; font-weight: 300; font-size: .8em; } .posts li h3 { margin: 0 0 .5em; } @media only screen and (min-width: 800px) { /*************** GLOBAL STYLES ***************/ .content { padding-top: 0; position: relative; z-index: 1; } .content:after { z-index: -1; background: white; content: ""; display: block; width: 100%; height: 10em; position: absolute; top: -2em; left: 0; -webkit-transform: skewY(-2deg); transform: skewY(-2deg); -webkit-transform-origin: bottom left; transform-origin: bottom left; } .container { max-width: 800px; margin-left: auto; margin-right: auto; padding: 0; overflow: hidden; } /*************** HOMEPAGE STYLING ***************/ #home .posts, #home .pageTitle, #home .pagination { width: 75%; float: none; margin: 0 auto 1.5em; } #home .pageTitle { margin: 2rem auto 1em; } /*************** HEADER STYLING ***************/ .header { height: 15em; position: relative; padding-bottom: 2em; } .header .container { position: relative; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); max-width: 800px; } .header h1 { font-size: 3em; line-height: 1; letter-spacing: -3px; padding-left: 0; } .header nav { float: left; clear: left; } .header nav ul { margin: 0; } .header nav ul li { display: inline; line-height: 3em; background: none; padding: 0 5px; border: none; } .header nav ul li a { color: white; font-size: .9em; text-decoration: none; padding: 0 .25em; } .header nav ul li a:hover { color: #cccccc; } .header nav ul li.current { padding-bottom: .25em; border-bottom: 4px solid rgba(255, 255, 255, 0.4); } /*************** MENU STYLING ***************/ .js .nav-collapse { position: relative; max-height: none; } .js .nav-collapse.closed { max-height: none; } .js .nav-collapse ul li a { display: inline-block; } .nav-toggle { display: none; } /*************** POST STYLING ***************/ .post h1, .post h2, .post h3, .post h4, .post h5, .post h6, .post p, .post ul, .post ol, .post dl, .post .pageTitle { width: 75%; float: none; margin: 0 auto 2rem; } .post h1, .post .h1, .post h2, .post .h2, .post h3, .post .h3, .post h4, .post .h4, .post h5, .post .h5, .post h6, .post .h6 { margin: 1rem auto; } .post .pageTitle { margin: 2rem auto 1em; } .post .featuredImage { position: relative; margin-top: 2rem; } .post .featuredImage:before { background: white; content: ""; display: block; width: 100%; height: 4em; position: absolute; top: -2em; left: 0; -webkit-transform: skewY(-2deg); transform: skewY(-2deg); -webkit-transform-origin: bottom left; transform-origin: bottom left; } /*************** POST NAV STYLING ***************/ .postNav .prev, .postNav .next { width: 50%; } .postNav .prev { float: left; text-align: left; } .postNav .next { text-align: right; float: right; } /*************** FOOTER STYLES ***************/ .footer-links { float: right; } .footer .copy { float: left; } .footer .container { padding: 1rem 0; max-width: 800px; } /*************** CONTACT PAGE STYLING ***************/ .contactContent { max-width: 48%; margin-right: 2%; float: left; } #contact form { max-width: 48%; width: 48%; float: right; margin-right: 0; } }
TechTalentSouthES/blog.techtalentsouth.es
css/style.css
CSS
mit
25,571
<?php use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\RequestContext; /** * appDevUrlMatcher * * This class has been auto-generated * by the Symfony Routing Component. */ class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher { /** * Constructor. */ public function __construct(RequestContext $context) { $this->context = $context; } public function match($pathinfo) { $allow = array(); $pathinfo = rawurldecode($pathinfo); if (0 === strpos($pathinfo, '/_')) { // _wdt if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',)); } if (0 === strpos($pathinfo, '/_profiler')) { // _profiler_home if (rtrim($pathinfo, '/') === '/_profiler') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_profiler_home'); } return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',); } if (0 === strpos($pathinfo, '/_profiler/search')) { // _profiler_search if ($pathinfo === '/_profiler/search') { return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',); } // _profiler_search_bar if ($pathinfo === '/_profiler/search_bar') { return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '_profiler_search_bar',); } } // _profiler_purge if ($pathinfo === '/_profiler/purge') { return array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', '_route' => '_profiler_purge',); } if (0 === strpos($pathinfo, '/_profiler/i')) { // _profiler_info if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',)); } // _profiler_import if ($pathinfo === '/_profiler/import') { return array ( '_controller' => 'web_profiler.controller.profiler:importAction', '_route' => '_profiler_import',); } } // _profiler_export if (0 === strpos($pathinfo, '/_profiler/export') && preg_match('#^/_profiler/export/(?P<token>[^/\\.]++)\\.txt$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_export')), array ( '_controller' => 'web_profiler.controller.profiler:exportAction',)); } // _profiler_phpinfo if ($pathinfo === '/_profiler/phpinfo') { return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',); } // _profiler_search_results if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',)); } // _profiler if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',)); } // _profiler_router if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',)); } // _profiler_exception if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',)); } // _profiler_exception_css if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',)); } } if (0 === strpos($pathinfo, '/_configurator')) { // _configurator_home if (rtrim($pathinfo, '/') === '/_configurator') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_configurator_home'); } return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', '_route' => '_configurator_home',); } // _configurator_step if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',)); } // _configurator_final if ($pathinfo === '/_configurator/final') { return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', '_route' => '_configurator_final',); } } } // application_sonata_super_market_homepage if (0 === strpos($pathinfo, '/hello') && preg_match('#^/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'application_sonata_super_market_homepage')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\DefaultController::indexAction',)); } // application_sonata_supermarket_price if ($pathinfo === '/price') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PriceController::getPriceAction', '_route' => 'application_sonata_supermarket_price',); } if (0 === strpos($pathinfo, '/admin')) { // sonata_admin_redirect if (rtrim($pathinfo, '/') === '/admin') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', 'sonata_admin_redirect'); } return array ( '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::redirectAction', 'route' => 'sonata_admin_dashboard', 'permanent' => 'true', '_route' => 'sonata_admin_redirect',); } // sonata_admin_dashboard if ($pathinfo === '/admin/dashboard') { return array ( '_controller' => 'Sonata\\AdminBundle\\Controller\\CoreController::dashboardAction', '_route' => 'sonata_admin_dashboard',); } if (0 === strpos($pathinfo, '/admin/core')) { // sonata_admin_retrieve_form_element if ($pathinfo === '/admin/core/get-form-field-element') { return array ( '_controller' => 'sonata.admin.controller.admin:retrieveFormFieldElementAction', '_route' => 'sonata_admin_retrieve_form_element',); } // sonata_admin_append_form_element if ($pathinfo === '/admin/core/append-form-field-element') { return array ( '_controller' => 'sonata.admin.controller.admin:appendFormFieldElementAction', '_route' => 'sonata_admin_append_form_element',); } // sonata_admin_short_object_information if (0 === strpos($pathinfo, '/admin/core/get-short-object-description') && preg_match('#^/admin/core/get\\-short\\-object\\-description(?:\\.(?P<_format>html|json))?$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'sonata_admin_short_object_information')), array ( '_controller' => 'sonata.admin.controller.admin:getShortObjectDescriptionAction', '_format' => 'html',)); } // sonata_admin_set_object_field_value if ($pathinfo === '/admin/core/set-object-field-value') { return array ( '_controller' => 'sonata.admin.controller.admin:setObjectFieldValueAction', '_route' => 'sonata_admin_set_object_field_value',); } } if (0 === strpos($pathinfo, '/admin/s')) { // sonata_admin_search if ($pathinfo === '/admin/search') { return array ( '_controller' => 'Sonata\\AdminBundle\\Controller\\CoreController::searchAction', '_route' => 'sonata_admin_search',); } if (0 === strpos($pathinfo, '/admin/sonata/supermarket')) { if (0 === strpos($pathinfo, '/admin/sonata/supermarket/brand')) { // admin_sonata_supermarket_brand_list if ($pathinfo === '/admin/sonata/supermarket/brand/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_list', '_route' => 'admin_sonata_supermarket_brand_list',); } // admin_sonata_supermarket_brand_create if ($pathinfo === '/admin/sonata/supermarket/brand/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_create', '_route' => 'admin_sonata_supermarket_brand_create',); } // admin_sonata_supermarket_brand_batch if ($pathinfo === '/admin/sonata/supermarket/brand/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_batch', '_route' => 'admin_sonata_supermarket_brand_batch',); } // admin_sonata_supermarket_brand_edit if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_edit',)); } // admin_sonata_supermarket_brand_delete if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_delete',)); } // admin_sonata_supermarket_brand_show if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_show',)); } // admin_sonata_supermarket_brand_export if ($pathinfo === '/admin/sonata/supermarket/brand/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_export', '_route' => 'admin_sonata_supermarket_brand_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/category')) { // admin_sonata_supermarket_category_list if ($pathinfo === '/admin/sonata/supermarket/category/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_list', '_route' => 'admin_sonata_supermarket_category_list',); } // admin_sonata_supermarket_category_create if ($pathinfo === '/admin/sonata/supermarket/category/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_create', '_route' => 'admin_sonata_supermarket_category_create',); } // admin_sonata_supermarket_category_batch if ($pathinfo === '/admin/sonata/supermarket/category/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_batch', '_route' => 'admin_sonata_supermarket_category_batch',); } // admin_sonata_supermarket_category_edit if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_edit',)); } // admin_sonata_supermarket_category_delete if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_delete',)); } // admin_sonata_supermarket_category_show if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_show',)); } // admin_sonata_supermarket_category_export if ($pathinfo === '/admin/sonata/supermarket/category/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_export', '_route' => 'admin_sonata_supermarket_category_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/product')) { // admin_sonata_supermarket_product_list if ($pathinfo === '/admin/sonata/supermarket/product/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_list', '_route' => 'admin_sonata_supermarket_product_list',); } // admin_sonata_supermarket_product_create if ($pathinfo === '/admin/sonata/supermarket/product/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_create', '_route' => 'admin_sonata_supermarket_product_create',); } // admin_sonata_supermarket_product_batch if ($pathinfo === '/admin/sonata/supermarket/product/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_batch', '_route' => 'admin_sonata_supermarket_product_batch',); } // admin_sonata_supermarket_product_edit if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_edit',)); } // admin_sonata_supermarket_product_delete if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_delete',)); } // admin_sonata_supermarket_product_show if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_show',)); } // admin_sonata_supermarket_product_export if ($pathinfo === '/admin/sonata/supermarket/product/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_export', '_route' => 'admin_sonata_supermarket_product_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/customer')) { // admin_sonata_supermarket_customer_list if ($pathinfo === '/admin/sonata/supermarket/customer/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_list', '_route' => 'admin_sonata_supermarket_customer_list',); } // admin_sonata_supermarket_customer_create if ($pathinfo === '/admin/sonata/supermarket/customer/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_create', '_route' => 'admin_sonata_supermarket_customer_create',); } // admin_sonata_supermarket_customer_batch if ($pathinfo === '/admin/sonata/supermarket/customer/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_batch', '_route' => 'admin_sonata_supermarket_customer_batch',); } // admin_sonata_supermarket_customer_edit if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_edit',)); } // admin_sonata_supermarket_customer_delete if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_delete',)); } // admin_sonata_supermarket_customer_show if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_show',)); } // admin_sonata_supermarket_customer_export if ($pathinfo === '/admin/sonata/supermarket/customer/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_export', '_route' => 'admin_sonata_supermarket_customer_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/purchaseorder')) { // admin_sonata_supermarket_purchaseorder_list if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_list', '_route' => 'admin_sonata_supermarket_purchaseorder_list',); } // admin_sonata_supermarket_purchaseorder_create if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_create', '_route' => 'admin_sonata_supermarket_purchaseorder_create',); } // admin_sonata_supermarket_purchaseorder_batch if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_batch', '_route' => 'admin_sonata_supermarket_purchaseorder_batch',); } // admin_sonata_supermarket_purchaseorder_edit if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_edit',)); } // admin_sonata_supermarket_purchaseorder_delete if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_delete',)); } // admin_sonata_supermarket_purchaseorder_show if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_show',)); } // admin_sonata_supermarket_purchaseorder_export if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_export', '_route' => 'admin_sonata_supermarket_purchaseorder_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/orderitem')) { // admin_sonata_supermarket_orderitem_list if ($pathinfo === '/admin/sonata/supermarket/orderitem/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_list', '_route' => 'admin_sonata_supermarket_orderitem_list',); } // admin_sonata_supermarket_orderitem_create if ($pathinfo === '/admin/sonata/supermarket/orderitem/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_create', '_route' => 'admin_sonata_supermarket_orderitem_create',); } // admin_sonata_supermarket_orderitem_batch if ($pathinfo === '/admin/sonata/supermarket/orderitem/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_batch', '_route' => 'admin_sonata_supermarket_orderitem_batch',); } // admin_sonata_supermarket_orderitem_edit if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_edit',)); } // admin_sonata_supermarket_orderitem_delete if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_delete',)); } // admin_sonata_supermarket_orderitem_show if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_show',)); } // admin_sonata_supermarket_orderitem_export if ($pathinfo === '/admin/sonata/supermarket/orderitem/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_export', '_route' => 'admin_sonata_supermarket_orderitem_export',); } } } } } if (0 === strpos($pathinfo, '/shtumi_')) { // shtumi_ajaxautocomplete if ($pathinfo === '/shtumi_ajaxautocomplete') { return array ( '_controller' => 'Shtumi\\UsefulBundle\\Controller\\AjaxAutocompleteJSONController::getJSONAction', '_route' => 'shtumi_ajaxautocomplete',); } // shtumi_dependent_filtered_entity if ($pathinfo === '/shtumi_dependent_filtered_entity') { return array ( '_controller' => 'ShtumiUsefulBundle:DependentFilteredEntity:getOptions', '_route' => 'shtumi_dependent_filtered_entity',); } } // _welcome if (rtrim($pathinfo, '/') === '') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_welcome'); } return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\WelcomeController::indexAction', '_route' => '_welcome',); } if (0 === strpos($pathinfo, '/demo')) { if (0 === strpos($pathinfo, '/demo/secured')) { if (0 === strpos($pathinfo, '/demo/secured/log')) { if (0 === strpos($pathinfo, '/demo/secured/login')) { // _demo_login if ($pathinfo === '/demo/secured/login') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction', '_route' => '_demo_login',); } // _security_check if ($pathinfo === '/demo/secured/login_check') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction', '_route' => '_security_check',); } } // _demo_logout if ($pathinfo === '/demo/secured/logout') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction', '_route' => '_demo_logout',); } } if (0 === strpos($pathinfo, '/demo/secured/hello')) { // acme_demo_secured_hello if ($pathinfo === '/demo/secured/hello') { return array ( 'name' => 'World', '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', '_route' => 'acme_demo_secured_hello',); } // _demo_secured_hello if (preg_match('#^/demo/secured/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',)); } // _demo_secured_hello_admin if (0 === strpos($pathinfo, '/demo/secured/hello/admin') && preg_match('#^/demo/secured/hello/admin/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello_admin')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction',)); } } } // _demo if (rtrim($pathinfo, '/') === '/demo') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_demo'); } return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction', '_route' => '_demo',); } // _demo_hello if (0 === strpos($pathinfo, '/demo/hello') && preg_match('#^/demo/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction',)); } // _demo_contact if ($pathinfo === '/demo/contact') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction', '_route' => '_demo_contact',); } } throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); } }
rangakomarthicomo/SuperMarket
app/cache/dev/appDevUrlMatcher.php
PHP
mit
39,321
// The MIT License (MIT) // // Copyright (c) 2015-2018 Rasmus Mikkelsen // Copyright (c) 2015-2018 eBay Software Foundation // https://github.com/eventflow/EventFlow // // 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.IO; using System.Threading; using System.Threading.Tasks; using EventFlow.Aggregates; using EventFlow.Configuration; using EventFlow.Core; using EventFlow.EventStores.Files; using EventFlow.Extensions; using EventFlow.TestHelpers; using EventFlow.TestHelpers.Aggregates; using EventFlow.TestHelpers.Aggregates.Commands; using EventFlow.TestHelpers.Aggregates.Queries; using EventFlow.TestHelpers.Aggregates.ValueObjects; using FluentAssertions; using NUnit.Framework; namespace EventFlow.Tests.IntegrationTests { [Category(Categories.Integration)] public class BackwardCompatibilityTests : Test { private readonly ThingyId _thingyId = ThingyId.With("thingy-1acea1eb-3e11-45c0-83c1-bc32e57ee8e7"); private IResolver _resolver; private ICommandBus _commandBus; private IAggregateStore _aggregateStore; [SetUp] public void SetUp() { var codeBase = ReflectionHelper.GetCodeBase(GetType().Assembly); var filesEventStoreDirectory = Path.GetFullPath(Path.Combine(codeBase, "..", "..", "..", "TestData", "FilesEventStore")); _resolver = EventFlowOptions.New .UseFilesEventStore(FilesEventStoreConfiguration.Create(filesEventStoreDirectory)) .AddEvents(EventFlowTestHelpers.Assembly) .AddCommandHandlers(EventFlowTestHelpers.Assembly) .RegisterServices(sr => sr.Register<IScopedContext, ScopedContext>(Lifetime.Scoped)) .CreateResolver(); _commandBus = _resolver.Resolve<ICommandBus>(); _aggregateStore = _resolver.Resolve<IAggregateStore>(); } [Test] public async Task ValidateTestAggregate() { // Act var testAggregate = await _aggregateStore.LoadAsync<ThingyAggregate, ThingyId>(_thingyId, CancellationToken.None); // Assert testAggregate.Version.Should().Be(2); testAggregate.PingsReceived.Should().Contain(PingId.With("95433aa0-11f7-4128-bd5f-18e0ecc4d7c1")); testAggregate.PingsReceived.Should().Contain(PingId.With("2352d09b-4712-48cc-bb4f-5560d7c52558")); } [Test, Explicit] public void CreateEventHelper() { _commandBus.Publish(new ThingyPingCommand(_thingyId, PingId.New), CancellationToken.None); } } }
rasmus/EventFlow
Source/EventFlow.Tests/IntegrationTests/BackwardCompatibilityTests.cs
C#
mit
3,638
<!doctype html> <html class="theme-next muse use-motion" lang="zh-Hans"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/> <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3"> <meta http-equiv="Cache-Control" content="no-transform" /> <meta http-equiv="Cache-Control" content="no-siteapp" /> <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" /> <link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" /> <link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" /> <meta name="keywords" content="Hexo, NexT" /> <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" /> <meta name="description" content="In me the tiger sniffs the rose."> <meta property="og:type" content="website"> <meta property="og:title" content="Jermmy&#39;s Lazy Blog"> <meta property="og:url" content="https://jermmy.github.io/tags/内存优化/index.html"> <meta property="og:site_name" content="Jermmy&#39;s Lazy Blog"> <meta property="og:description" content="In me the tiger sniffs the rose."> <meta property="og:locale" content="zh-Hans"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="Jermmy&#39;s Lazy Blog"> <meta name="twitter:description" content="In me the tiger sniffs the rose."> <script type="text/javascript" id="hexo.configurations"> var NexT = window.NexT || {}; var CONFIG = { root: '/', scheme: 'Muse', sidebar: {"position":"left","display":"hide","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false}, fancybox: true, motion: true, duoshuo: { userId: '0', author: '博主' }, algolia: { applicationID: '', apiKey: '', indexName: '', hits: {"per_page":10}, labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"} } }; </script> <link rel="canonical" href="https://jermmy.github.io/tags/内存优化/"/> <title>标签: 内存优化 | Jermmy's Lazy Blog</title> </head> <body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-84659849-1', 'auto'); ga('send', 'pageview'); </script> <script type="text/javascript"> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?4d053879042f439aeb8fc5996a907b6b"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> <div class="container sidebar-position-left "> <div class="headband"></div> <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"> <div class="header-inner"><div class="site-brand-wrapper"> <div class="site-meta "> <div class="custom-logo-site-title"> <a href="/" class="brand" rel="start"> <span class="logo-line-before"><i></i></span> <span class="site-title">Jermmy's Lazy Blog</span> <span class="logo-line-after"><i></i></span> </a> </div> <p class="site-subtitle"></p> </div> <div class="site-nav-toggle"> <button> <span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span> </button> </div> </div> <nav class="site-nav"> <ul id="menu" class="menu"> <li class="menu-item menu-item-home"> <a href="/" rel="section"> <i class="menu-item-icon fa fa-fw fa-home"></i> <br /> 首页 </a> </li> <li class="menu-item menu-item-categories"> <a href="/categories" rel="section"> <i class="menu-item-icon fa fa-fw fa-th"></i> <br /> 分类 </a> </li> <li class="menu-item menu-item-archives"> <a href="/archives" rel="section"> <i class="menu-item-icon fa fa-fw fa-archive"></i> <br /> 归档 </a> </li> <li class="menu-item menu-item-tags"> <a href="/tags" rel="section"> <i class="menu-item-icon fa fa-fw fa-tags"></i> <br /> 标签 </a> </li> </ul> </nav> </div> </header> <main id="main" class="main"> <div class="main-inner"> <div class="content-wrap"> <div id="content" class="content"> <div id="posts" class="posts-collapse"> <div class="collection-title"> <h2 > 内存优化 <small>标签</small> </h2> </div> <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"> <header class="post-header"> <h1 class="post-title"> <a class="post-title-link" href="/2016/10/04/2016-10-4-Android-内存泄漏那些事/" itemprop="url"> <span itemprop="name">Android内存泄漏那些事</span> </a> </h1> <div class="post-meta"> <time class="post-time" itemprop="dateCreated" datetime="2016-10-04T18:15:52+08:00" content="2016-10-04" > 10-04 </time> </div> </header> </article> </div> </div> </div> <div class="sidebar-toggle"> <div class="sidebar-toggle-line-wrap"> <span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span> </div> </div> <aside id="sidebar" class="sidebar"> <div class="sidebar-inner"> <section class="site-overview sidebar-panel sidebar-panel-active"> <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="Jermmy" /> <p class="site-author-name" itemprop="name">Jermmy</p> <p class="site-description motion-element" itemprop="description">In me the tiger sniffs the rose.</p> </div> <nav class="site-state motion-element"> <div class="site-state-item site-state-posts"> <a href="/archives"> <span class="site-state-item-count">96</span> <span class="site-state-item-name">日志</span> </a> </div> <div class="site-state-item site-state-categories"> <a href="/categories/index.html"> <span class="site-state-item-count">19</span> <span class="site-state-item-name">分类</span> </a> </div> <div class="site-state-item site-state-tags"> <a href="/tags/index.html"> <span class="site-state-item-count">43</span> <span class="site-state-item-name">标签</span> </a> </div> </nav> <div class="links-of-author motion-element"> <span class="links-of-author-item"> <a href="https://github.com/jermmy" target="_blank" title="GitHub"> <i class="fa fa-fw fa-github"></i> GitHub </a> </span> </div> <div class="links-of-blogroll motion-element links-of-blogroll-inline"> <div class="links-of-blogroll-title"> <i class="fa fa-fw fa-globe"></i> Links </div> <ul class="links-of-blogroll-list"> <li class="links-of-blogroll-item"> <a href="http://www.ruanyifeng.com/blog/" title="阮一峰" target="_blank">阮一峰</a> </li> <li class="links-of-blogroll-item"> <a href="http://freemind.pluskid.org/" title="pluskid" target="_blank">pluskid</a> </li> </ul> </div> </section> </div> </aside> </div> </main> <footer id="footer" class="footer"> <div class="footer-inner"> <div class="copyright" > &copy; 2016 - <span itemprop="copyrightYear">2020</span> <span class="with-love"> <i class="fa fa-heart"></i> </span> <span class="author" itemprop="copyrightHolder">Jermmy</span> </div> <div class="powered-by"> 由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动 </div> <div class="theme-info"> 主题 - <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next"> NexT.Muse </a> </div> </div> </footer> <div class="back-to-top"> <i class="fa fa-arrow-up"></i> </div> </div> <script type="text/javascript"> if (Object.prototype.toString.call(window.Promise) !== '[object Function]') { window.Promise = null; } </script> <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script> <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script> <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script> <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script> <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script> <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script> <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script> <script id="dsq-count-scr" src="https://jermmy.disqus.com/count.js" async></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [ ['$','$'], ["\\(","\\)"] ], processEscapes: true, skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] } }); </script> <script type="text/x-mathjax-config"> MathJax.Hub.Queue(function() { var all = MathJax.Hub.getAllJax(), i; for (i=0; i < all.length; i += 1) { all[i].SourceElement().parentNode.className += ' has-jax'; } }); </script> <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> </body> </html>
Jermmy/jermmy.github.io
tags/内存优化/index.html
HTML
mit
12,054
# Cognitive Services Custom Search SDK > see https://aka.ms/autorest Configuration for generating Custom Search SDK. The current release is `release_1_0`. ``` yaml tag: release_1_0 add-credentials: true openapi-type: data-plane ``` # Releases ### Release 1.0 These settings apply only when `--tag=release_1_0` is specified on the command line. ``` yaml $(tag) == 'release_1_0' input-file: stable/v1.0/CustomImageSearch.json ``` ## Swagger to SDK This section describes what SDK should be generated by the automatic system. This is not used by Autorest itself. ``` yaml $(swagger-to-sdk) swagger-to-sdk: - repo: azure-sdk-for-python - repo: azure-sdk-for-java - repo: azure-sdk-for-go - repo: azure-sdk-for-node ``` ## CSharp Settings These settings apply only when `--csharp` is specified on the command line. ``` yaml $(csharp) csharp: namespace: Microsoft.Azure.CognitiveServices.Search.CustomImageSearch output-folder: $(csharp-sdks-folder)/CognitiveServices/dataPlane/Search/BingCustomImageSearch/BingCustomImageSearch/Generated/CustomImageSearch sync-methods: none ``` ## Python These settings apply only when `--python` is specified on the command line. Please also specify `--python-sdks-folder=<path to the root directory of your azure-sdk-for-python clone>`. Use `--python-mode=update` if you already have a setup.py and just want to update the code itself. ``` yaml $(python) python-mode: create python: license-header: MICROSOFT_MIT_NO_VERSION add-credentials: true payload-flattening-threshold: 2 namespace: azure.cognitiveservices.search.customimagesearch package-name: azure-cognitiveservices-search-customimagesearch clear-output-folder: true ``` ``` yaml $(python) && $(python-mode) == 'update' python: no-namespace-folders: true output-folder: $(python-sdks-folder)/azure-cognitiveservices-search-customimagesearch/azure/cognitiveservices/search/customimagesearch ``` ``` yaml $(python) && $(python-mode) == 'create' python: basic-setup-py: true output-folder: $(python-sdks-folder)/azure-cognitiveservices-search-customimagesearch ``` ## Go These settings apply only when `--go` is specified on the command line. ``` yaml $(go) go: license-header: MICROSOFT_APACHE_NO_VERSION namespace: customimagesearch clear-output-folder: true ``` ### Go multi-api ``` yaml $(go) && $(multiapi) batch: - tag: release_1_0 ``` ### Tag: release_1_0 and go These settings apply only when `--tag=release_1_0 --go` is specified on the command line. Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`. ``` yaml $(tag) == 'release_1_0' && $(go) output-folder: $(go-sdk-folder)/services/cognitiveservices/v1.0/customimagesearch ``` ## Suppressions Suppressing errors due to API design: ``` yaml directive: - suppress: R3016 reason: _type is a polymorphic discriminator that can't be changed. ``` ## Java These settings apply only when `--java` is specified on the command line. Please also specify `--azure-libraries-for-java-folder=<path to the root directory of your azure-libraries-for-java clone>`. ``` yaml $(java) java: azure-arm: true namespace: com.microsoft.azure.cognitiveservices.search.customimagesearch license-header: MICROSOFT_MIT_NO_CODEGEN payload-flattening-threshold: 1 output-folder: $(azure-libraries-for-java-folder)/cognitiveservices/data-plane/search/bingcustomimagesearch with-optional-parameters: true prefix-model-type: Bing with-single-async-method: true ```
kiwidev/azure-rest-api-specs
specification/cognitiveservices/data-plane/CustomImageSearch/readme.md
Markdown
mit
3,523
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>ICLC2016 - Molly IDE</title> <script type="application/dart" src="main.dart"></script> <script data-pub-inline src="packages/browser/dart.js"></script> </head> <body> <div id='visualisation-container' style='width:1000px; height:500px'> </div> <button id="add-button" class="plus-button"> <svg width="45" height="45" viewBox="0 0 45 45" xmlns="http://www.w3.org/2000/svg"> <rect x="15" y="0" width="15" height="45" rx="5" ry="5"/> <rect x="0" y="15" width="45" height="15" rx="5" ry="5"/> </svg> </button> </body> </html>
lukechurch/iclc2016
web-editor/web/index.html
HTML
mit
802
// Generated from ./Select.g4 by ANTLR 4.5 // jshint ignore: start var antlr4 = require('../../index'); var serializedATN = ["\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd", "\2\17\177\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t", "\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\3\2\3\2\3\2\3", "\2\3\2\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3", "\7\3\7\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\3", "\n\5\nD\n\n\3\13\3\13\3\13\3\f\5\fJ\n\f\3\f\6\fM\n\f\r\f\16\fN\3\f\7", "\fR\n\f\f\f\16\fU\13\f\3\f\7\fX\n\f\f\f\16\f[\13\f\3\f\3\f\3\f\3\f\3", "\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\7\fl\n\f\f\f\16\fo\13\f\3", "\f\5\fr\n\f\3\r\6\ru\n\r\r\r\16\rv\3\16\6\16z\n\16\r\16\16\16{\3\16", "\3\16\3m\2\17\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31", "\16\33\17\3\2\7\4\2--//\3\2\62;\3\2\60\60\5\2C\\aac|\5\2\13\f\17\17", "\"\"\u008d\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2", "\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2", "\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\3\35\3\2\2\2\5$\3\2\2\2\7&\3", "\2\2\2\t(\3\2\2\2\13*\3\2\2\2\r/\3\2\2\2\17\63\3\2\2\2\21\66\3\2\2\2", "\23C\3\2\2\2\25E\3\2\2\2\27q\3\2\2\2\31t\3\2\2\2\33y\3\2\2\2\35\36\7", "u\2\2\36\37\7g\2\2\37 \7n\2\2 !\7g\2\2!\"\7e\2\2\"#\7v\2\2#\4\3\2\2", "\2$%\7.\2\2%\6\3\2\2\2&\'\7*\2\2\'\b\3\2\2\2()\7+\2\2)\n\3\2\2\2*+\7", "h\2\2+,\7t\2\2,-\7q\2\2-.\7o\2\2.\f\3\2\2\2/\60\7c\2\2\60\61\7p\2\2", "\61\62\7f\2\2\62\16\3\2\2\2\63\64\7q\2\2\64\65\7t\2\2\65\20\3\2\2\2", "\66\67\7y\2\2\678\7j\2\289\7g\2\29:\7t\2\2:;\7g\2\2;\22\3\2\2\2<D\7", ">\2\2=>\7>\2\2>D\7?\2\2?D\7@\2\2@A\7@\2\2AD\7?\2\2BD\7?\2\2C<\3\2\2", "\2C=\3\2\2\2C?\3\2\2\2C@\3\2\2\2CB\3\2\2\2D\24\3\2\2\2EF\7k\2\2FG\7", "p\2\2G\26\3\2\2\2HJ\t\2\2\2IH\3\2\2\2IJ\3\2\2\2JL\3\2\2\2KM\t\3\2\2", "LK\3\2\2\2MN\3\2\2\2NL\3\2\2\2NO\3\2\2\2OS\3\2\2\2PR\t\4\2\2QP\3\2\2", "\2RU\3\2\2\2SQ\3\2\2\2ST\3\2\2\2TY\3\2\2\2US\3\2\2\2VX\t\3\2\2WV\3\2", "\2\2X[\3\2\2\2YW\3\2\2\2YZ\3\2\2\2Zr\3\2\2\2[Y\3\2\2\2\\]\7v\2\2]^\7", "t\2\2^_\7w\2\2_r\7g\2\2`a\7h\2\2ab\7c\2\2bc\7n\2\2cd\7u\2\2dr\7g\2\2", "ef\7p\2\2fg\7w\2\2gh\7n\2\2hr\7n\2\2im\7)\2\2jl\13\2\2\2kj\3\2\2\2l", "o\3\2\2\2mn\3\2\2\2mk\3\2\2\2np\3\2\2\2om\3\2\2\2pr\7)\2\2qI\3\2\2\2", "q\\\3\2\2\2q`\3\2\2\2qe\3\2\2\2qi\3\2\2\2r\30\3\2\2\2su\t\5\2\2ts\3", "\2\2\2uv\3\2\2\2vt\3\2\2\2vw\3\2\2\2w\32\3\2\2\2xz\t\6\2\2yx\3\2\2\2", "z{\3\2\2\2{y\3\2\2\2{|\3\2\2\2|}\3\2\2\2}~\b\16\2\2~\34\3\2\2\2\f\2", "CINSYmqv{\3\b\2\2"].join(""); var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN); var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); }); function SelectLexer(input) { antlr4.Lexer.call(this, input); this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache()); return this; } SelectLexer.prototype = Object.create(antlr4.Lexer.prototype); SelectLexer.prototype.constructor = SelectLexer; SelectLexer.EOF = antlr4.Token.EOF; SelectLexer.T__0 = 1; SelectLexer.T__1 = 2; SelectLexer.T__2 = 3; SelectLexer.T__3 = 4; SelectLexer.T__4 = 5; SelectLexer.T__5 = 6; SelectLexer.T__6 = 7; SelectLexer.T__7 = 8; SelectLexer.OPERATOR = 9; SelectLexer.ARRAYOPERATOR = 10; SelectLexer.CONSTANT = 11; SelectLexer.FIELD = 12; SelectLexer.WS = 13; SelectLexer.modeNames = [ "DEFAULT_MODE" ]; SelectLexer.literalNames = [ 'null', "'select'", "','", "'('", "')'", "'from'", "'and'", "'or'", "'where'", 'null', "'in'" ]; SelectLexer.symbolicNames = [ 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null', "OPERATOR", "ARRAYOPERATOR", "CONSTANT", "FIELD", "WS" ]; SelectLexer.ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "OPERATOR", "ARRAYOPERATOR", "CONSTANT", "FIELD", "WS" ]; SelectLexer.grammarFileName = "Select.g4"; exports.SelectLexer = SelectLexer;
bvellacott/papu-force-adapter
lib/antlr4/parsers/select/SelectLexer.js
JavaScript
mit
4,185
using System; using Microsoft.VisualStudio.Shell.Interop; using NUnit.Framework; using Telerik.JustMock; using VisualStudioSync.Controllers; namespace VisualStudioSync.Tests { [TestFixture] public class SettingsControllerTest { private const string Path = "path"; private const string Value = "test"; private IVsProfileDataManager _manager; private IVsSettingsErrorInformation _errorInformation; private IVsProfileSettingsFileCollection _files; private IXmlRepository _xmlRepository; private IVsProfileSettingsFileInfo _settingsFileInfo; private IVsProfileSettingsTree _sets; [SetUp] public void Setup() { _manager = Mock.Create<IVsProfileDataManager>(); _errorInformation = Mock.Create<IVsSettingsErrorInformation>(); _files = Mock.Create<IVsProfileSettingsFileCollection>(); _xmlRepository = Mock.Create<IXmlRepository>(); _settingsFileInfo = Mock.Create<IVsProfileSettingsFileInfo>(); _sets = Mock.Create<IVsProfileSettingsTree>(); } [Test] public void Get_CheckManager_CalledExportAllSettings() { //Arrange Mock.Arrange(() => _manager.ExportAllSettings( Arg.Matches<string>(path => path.StartsWith(Path)), out _errorInformation)) .MustBeCalled(); //Act CreateController().Get(); //Assert Mock.AssertAll(_manager); } [Test] public void Get_CheckRepository_CalledGetXml() { //Arrange Mock.Arrange(() => _xmlRepository.GetXml( Arg.Matches<string>(path => path.StartsWith(Path)))) .MustBeCalled(); //Act CreateController().Get(); //Assert Mock.AssertAll(_xmlRepository); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void Set_ValueIsNull_ExpectedException() { //Act CreateController().Set(null); } [Test] public void Set_ValueIsntNull_CalledSetXml() { //Arrange Mock.Arrange(() => _xmlRepository.SetXml( Arg.Matches<string>(path => path.StartsWith(Path)), Value)) .MustBeCalled(); Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing(); Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } [Test] public void Set_ValueIsntNull_CalleGetSettingsFiles() { //Arrange Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)) .MustBeCalled(); Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing(); Mock.Arrange(() => _settingsFileInfo.GetSettingsForImport(out _sets)).DoNothing(); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } [Test] public void Set_ValueIsntNull_CalleAddBrowseFile() { //Arrange Mock.Arrange(() => _files.AddBrowseFile( Arg.Matches<string>(path => path.StartsWith(Path)), out _settingsFileInfo)) .MustBeCalled(); Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } [Test] public void Set_ValueIsntNull_CalleGetSettingsForImport() { //Arrange Mock.Arrange(() => _settingsFileInfo.GetSettingsForImport(out _sets)) .MustBeCalled(); Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)); Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } [Test] public void Set_ValueIsntNull_CalleImportSettings() { //Arrange Mock.Arrange(() => _manager.ImportSettings(_sets, out _errorInformation)) .MustBeCalled(); Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)); Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing(); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } private SettingsController CreateController() { return new SettingsController(Path, _manager, _xmlRepository); } } }
aquiladev/Coding4Fun.VisualStudioSync
VisualStudioSync.Tests/SettingsControllerTest.cs
C#
mit
4,052
import styled from 'styled-components'; const Wrapper = styled.div` width: 100%; height: 100%; display: block; align-items: space-between; `; export default Wrapper;
andyfrith/weather.goodapplemedia.com
app/containers/ForecastListItem/Wrapper.js
JavaScript
mit
176
<?php /** * Low Seg2Cat Language file * * @package low_seg2cat * @author Lodewijk Schutte <hi@gotolow.com> * @link http://gotolow.com/addons/low-seg2cat * @license http://creativecommons.org/licenses/by-sa/3.0/ */ $lang = array( 'category_groups' => 'Category groups', 'all_groups' => '-- All --', 'uri_pattern' => 'URI pattern', 'set_all_segments' => 'Set all segments', 'ignore_pagination' => 'Ignore pagination', 'parse_file_paths' => 'Parse file paths' ); /* End of file low_seg2cat_lang.php */
noslouch/pa
core/expressionengine/third_party/low_seg2cat/language/english/low_seg2cat_lang.php
PHP
mit
547
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Reflection; namespace AKDK.Messages.DockerEvents.Converters { /// <summary> /// JSON converter that that enables custom selection logic during deserialisation of the object to create based on the JSON encountered. /// </summary> /// <typeparam name="TBase"> /// The base type of object that the converter can deserialise. /// </typeparam> public abstract class JsonCreationConverter<TBase> : JsonConverter { /// <summary> /// Create a new <see cref="JsonCreationConverter{T}"/>. /// </summary> protected JsonCreationConverter() { } /// <summary> /// Can the converter write JSON? /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Determine whether the converter can convert an object of the specified type. /// </summary> /// <param name="objectType"> /// The object type. /// </param> /// <returns> /// <c>true</c>, if the converter can convert an object of the specified type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { if (objectType == null) throw new ArgumentNullException(nameof(objectType)); return typeof(TBase).IsAssignableFrom(objectType); } /// <summary> /// Deserialise an object from JSON. /// </summary> /// <param name="reader"> /// The <see cref="JsonReader"/> to read from. /// </param><param name="objectType"> /// Type (or base type) of the object being deserialised. /// </param><param name="existingValue"> /// The existing value of the object being read. /// </param> /// <param name="serializer"> /// The calling serializer. /// </param> /// <returns> /// The deserialised object. /// </returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (objectType == null) throw new ArgumentNullException(nameof(objectType)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); if (reader.TokenType == JsonToken.Null) return null; if (reader.TokenType != JsonToken.StartObject) { throw new FormatException( String.Format( "Unexpected token '{0}' encountered while deserialising object of type '{1}'.", reader.TokenType, typeof(TBase).FullName ) ); } JObject json = JObject.Load(reader); TBase target = Create(json); if (target == null) throw new InvalidOperationException("JsonCreationConverter.Create returned null."); // Populate the object properties serializer.Populate( json.CreateReader(), target ); return target; } /// <summary> /// Serialise an object to JSON. /// </summary> /// <param name="writer"> /// The <see cref="JsonWriter"/> to which serialised object data will be written. /// </param> /// <param name="value"> /// The object to serialise. /// </param> /// <param name="serializer"> /// The calling serialiser. /// </param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); throw new NotImplementedException("JsonCreationConverter cannot write JSON."); } /// <summary> /// Create an instance of to be populated, based properties in the JSON. /// </summary> /// <param name="json"> /// The JSON containing serialised object data. /// </param> /// <returns> /// The object instance to be populated. /// </returns> protected abstract TBase Create(JObject json); } }
tintoy/aykay-deekay
src/AKDK/Messages/DockerEvents/Converters/JsonCreationConverter.cs
C#
mit
3,851
<?php $files = array('global', 'module', 'admin', 'bootstrap', 'bootstrap-responsive', 'bootstrap-wysihtml5','datetimepicker'); $extended = array('install' => 'installation css', 'mailer' => 'Custom mailer css'); /* Do not edit below this line //-------------------------------*/ header("Content-Type: text/css; charset: UTF-8"); header("Cache-Control: must-revalidate"); header("Last-Modified: " . date(DateTime::RFC1123)); header("Expires: " . date(DateTime::RFC1123, time() + 600)); $css_file = '/* ------------------------------------------------------------ Expanse http://expansecms.org Content management for the web deisgner, by the web designer Written, with love, by Ian Tearle @iantearle Based on original work by Nate Cavanaugh and Jason Morrison All rights reserved. ============================================================ */ '; $folder = dirname(__FILE__).'/'; echo $css_file; ob_start("compress"); function compress($buffer) { /* remove comments */ $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); /* remove tabs, spaces, newlines, etc. */ $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); return $buffer; } $get_extended = isset($_GET['extend']) && ctype_alnum($_GET['extend']) ? $_GET['extend'] : ''; /* your css files */ foreach($files as $include) { $include = trim($include); if(!empty($get_extended) && isset($extended[$get_extended])) { $the_file = $folder.$get_extended.'.css'; } else { $the_file = $folder.$include.'.css'; } if(empty($include) || !file_exists($the_file)) { continue; } include($the_file); } ob_end_flush();
iantearle/Expanse-CMS-Public
expanse/css/expanse.css.php
PHP
mit
1,657
module.exports={ setup(context, cb){ //context.sigslot.signalAt('* * * * * *', 'sayHello') cb() }, sep(msg,next){ console.log(msg); return next() }, route(req, next){ switch(req.method){ case 'POST': return next() case 'GET': this.setOutput(this.time) default: return next(null, this.sigslot.abort()) } }, help(next){ next(this.error(404, `api ${this.api} is not supported yet`)) }, sayNow(next){ console.log(Date.now()) next() } }
ldarren/pico-api
test/util.js
JavaScript
mit
464
fencing-devices ===============
jrafidi/fencing-devices
README.md
Markdown
mit
32
# template-react
wrariza/candado
README.md
Markdown
mit
16
<?php namespace Murky\HomeBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/hello/Fabien'); $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0); } }
rlbaltha/biblio
src/Murky/HomeBundle/Tests/Controller/DefaultControllerTest.php
PHP
mit
399
/*********************************************** * MIT License * * Copyright (c) 2016 珠峰课堂,Ramroll * 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. * */ export * from "./ZButton" export * from "./BButton" export * from "./navbar/ZNavbar" export * from "./tabbar/Tabbar" export * from "./tabbar/TabbarItem" export * from "./ZBottomButton" export * from "./NetworkError" export * from "./CourseCardBig" export * from "./CourseCardSmall" export * from "./ZInput" export * from "./ZSwitch" export * from "./ZVCode" export * from "./ZImgCode" export * from "./NavBar" export * from "./HomeMenuView" export * from "./HomeMenuItem" export * from "./HomeGridView" export * from "./HomeGridItem" export * from "./QrImage"
njxiaohan/TransPal
app/domain/component/index.js
JavaScript
mit
1,752
goog.provide('ngeo.CreatefeatureController'); goog.provide('ngeo.createfeatureDirective'); goog.require('ngeo'); goog.require('ngeo.EventHelper'); /** @suppress {extraRequire} */ goog.require('ngeo.filters'); goog.require('ngeo.interaction.MeasureArea'); goog.require('ngeo.interaction.MeasureLength'); goog.require('ol.Feature'); goog.require('ol.geom.GeometryType'); goog.require('ol.interaction.Draw'); goog.require('ol.style.Style'); /** * A directive used to draw vector features of a single geometry type using * either a 'draw' or 'measure' interaction. Once a feature is finished being * drawn, it is added to a collection of features. * * The geometry types supported are: * - Point * - LineString * - Polygon * * Example: * * <a * href * translate * ngeo-btn * ngeo-createfeature * ngeo-createfeature-active="ctrl.createPointActive" * ngeo-createfeature-features="ctrl.features" * ngeo-createfeature-geom-type="ctrl.pointGeomType" * ngeo-createfeature-map="::ctrl.map" * class="btn btn-default ngeo-createfeature-point" * ng-class="{active: ctrl.createPointActive}" * ng-model="ctrl.createPointActive"> * </a> * * @htmlAttribute {boolean} ngeo-createfeature-active Whether the directive is * active or not. * @htmlAttribute {ol.Collection} ngeo-createfeature-features The collection of * features where to add those created by this directive. * @htmlAttribute {string} ngeo-createfeature-geom-type Determines the type * of geometry this directive should draw. * @htmlAttribute {ol.Map} ngeo-createfeature-map The map. * @return {angular.Directive} The directive specs. * @ngInject * @ngdoc directive * @ngname ngeoCreatefeature */ ngeo.createfeatureDirective = function() { return { controller: 'ngeoCreatefeatureController as cfCtrl', bindToController: true, scope: { 'active': '=ngeoCreatefeatureActive', 'features': '=ngeoCreatefeatureFeatures', 'geomType': '=ngeoCreatefeatureGeomType', 'map': '=ngeoCreatefeatureMap' } }; }; ngeo.module.directive('ngeoCreatefeature', ngeo.createfeatureDirective); /** * @param {gettext} gettext Gettext service. * @param {angular.$compile} $compile Angular compile service. * @param {angular.$filter} $filter Angular filter * @param {!angular.Scope} $scope Scope. * @param {angular.$timeout} $timeout Angular timeout service. * @param {ngeo.EventHelper} ngeoEventHelper Ngeo event helper service * @constructor * @struct * @ngInject * @ngdoc controller * @ngname ngeoCreatefeatureController */ ngeo.CreatefeatureController = function(gettext, $compile, $filter, $scope, $timeout, ngeoEventHelper) { /** * @type {boolean} * @export */ this.active = this.active === true; /** * @type {ol.Collection.<ol.Feature>|ol.source.Vector} * @export */ this.features; /** * @type {string} * @export */ this.geomType; /** * @type {ol.Map} * @export */ this.map; /** * @type {angular.$timeout} * @private */ this.timeout_ = $timeout; /** * @type {ngeo.EventHelper} * @private */ this.ngeoEventHelper_ = ngeoEventHelper; // Create the draw or measure interaction depending on the geometry type var interaction; var helpMsg; var contMsg; if (this.geomType === ngeo.GeometryType.POINT || this.geomType === ngeo.GeometryType.MULTI_POINT ) { interaction = new ol.interaction.Draw({ type: ol.geom.GeometryType.POINT }); } else if (this.geomType === ngeo.GeometryType.LINE_STRING || this.geomType === ngeo.GeometryType.MULTI_LINE_STRING ) { helpMsg = gettext('Click to start drawing length'); contMsg = gettext( 'Click to continue drawing<br/>' + 'Double-click or click last point to finish' ); interaction = new ngeo.interaction.MeasureLength( $filter('ngeoUnitPrefix'), { style: new ol.style.Style(), startMsg: $compile('<div translate>' + helpMsg + '</div>')($scope)[0], continueMsg: $compile('<div translate>' + contMsg + '</div>')($scope)[0] } ); } else if (this.geomType === ngeo.GeometryType.POLYGON || this.geomType === ngeo.GeometryType.MULTI_POLYGON ) { helpMsg = gettext('Click to start drawing area'); contMsg = gettext( 'Click to continue drawing<br/>' + 'Double-click or click starting point to finish' ); interaction = new ngeo.interaction.MeasureArea( $filter('ngeoUnitPrefix'), { style: new ol.style.Style(), startMsg: $compile('<div translate>' + helpMsg + '</div>')($scope)[0], continueMsg: $compile('<div translate>' + contMsg + '</div>')($scope)[0] } ); } goog.asserts.assert(interaction); interaction.setActive(this.active); this.map.addInteraction(interaction); /** * The draw or measure interaction responsible of drawing the vector feature. * The actual type depends on the geometry type. * @type {ol.interaction.Interaction} * @private */ this.interaction_ = interaction; // == Event listeners == $scope.$watch( function() { return this.active; }.bind(this), function(newVal) { this.interaction_.setActive(newVal); }.bind(this) ); var uid = ol.getUid(this); if (interaction instanceof ol.interaction.Draw) { this.ngeoEventHelper_.addListenerKey( uid, ol.events.listen( interaction, ol.interaction.Draw.EventType.DRAWEND, this.handleDrawEnd_, this ), true ); } else if (interaction instanceof ngeo.interaction.MeasureLength || interaction instanceof ngeo.interaction.MeasureArea) { this.ngeoEventHelper_.addListenerKey( uid, ol.events.listen( interaction, ngeo.MeasureEventType.MEASUREEND, this.handleDrawEnd_, this ), true ); } $scope.$on('$destroy', this.handleDestroy_.bind(this)); }; /** * Called when a feature is finished being drawn. Add the feature to the * collection. * @param {ol.interaction.Draw.Event|ngeo.MeasureEvent} event Event. * @export */ ngeo.CreatefeatureController.prototype.handleDrawEnd_ = function(event) { var feature = new ol.Feature(event.feature.getGeometry()); if (this.features instanceof ol.Collection) { this.features.push(feature); } else { this.features.addFeature(feature); } }; /** * Cleanup event listeners and remove the interaction from the map. * @private */ ngeo.CreatefeatureController.prototype.handleDestroy_ = function() { this.timeout_(function() { var uid = ol.getUid(this); this.ngeoEventHelper_.clearListenerKey(uid); this.interaction_.setActive(false); this.map.removeInteraction(this.interaction_); }.bind(this), 0); }; ngeo.module.controller( 'ngeoCreatefeatureController', ngeo.CreatefeatureController);
ger-benjamin/ngeo
src/directives/createfeature.js
JavaScript
mit
6,955
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width initial-scale=1" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Welcome to the Macroevolution Group!</title> <meta name="description" content="Thomas lab at the University of Sheffield"> <meta name="author" content="Gavin Thomas"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="Macroevolution Group"> <meta name="twitter:description" content="Thomas lab at the University of Sheffield"> <meta property="og:type" content="article"> <meta property="og:title" content="Macroevolution Group"> <meta property="og:description" content="Thomas lab at the University of Sheffield"> <link rel="apple-touch-icon" sizes="57x57" href="/ghthomas.github.io/images/favicons/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/ghthomas.github.io/images/favicons/apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/ghthomas.github.io/images/favicons/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/ghthomas.github.io/images/favicons/apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/ghthomas.github.io/images/favicons/apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/ghthomas.github.io/images/favicons/apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/ghthomas.github.io/images/favicons/apple-touch-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/ghthomas.github.io/images/favicons/apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/ghthomas.github.io/images/favicons/apple-touch-icon-180x180.png"> <link rel="icon" type="image/png" href="/ghthomas.github.io/images/favicons/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="/ghthomas.github.io/images/favicons/favicon-194x194.png" sizes="194x194"> <link rel="icon" type="image/png" href="/ghthomas.github.io/images/favicons/favicon-96x96.png" sizes="96x96"> <link rel="icon" type="image/png" href="/ghthomas.github.io/images/favicons/android-chrome-192x192.png" sizes="192x192"> <link rel="icon" type="image/png" href="/ghthomas.github.io/images/favicons/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="/ghthomas.github.io/images/favicons/manifest.json"> <link rel="shortcut icon" href="/ghthomas.github.io/images/favicons/favicon.ico"> <meta name="msapplication-TileColor" content="#ffc40d"> <meta name="msapplication-TileImage" content="/ghthomas.github.io/images/favicons/mstile-144x144.png"> <meta name="theme-color" content="#ffffff"> <link rel="stylesheet" href="/ghthomas.github.io/css/main.css"> <link rel="canonical" href="http://joshgerdes.com/jekyll-uno/ghthomas.github.io//2016/a-test/"> <link rel="alternate" type="application/rss+xml" title="Macroevolution Group" href="/ghthomas.github.io/feed.xml"> </head> <body> <span class="mobile btn-mobile-menu"> <i class="icon icon-list btn-mobile-menu__icon"></i> <i class="icon icon-x-circle btn-mobile-close__icon hidden"></i> </span> <header class="panel-cover" style="background-image: url(/ghthomas.github.io/images/Vangas.jpg)"> <div class="panel-main"> <div class="panel-main__inner panel-inverted"> <div class="panel-main__content"> <a href="/ghthomas.github.io/" title="link to home of Macroevolution Group"> <img src="/ghthomas.github.io/images/profile.jpg" class="user-image" alt="My Profile Photo"> <h1 class="panel-cover__title panel-title">Macroevolution Group</h1> </a> <hr class="panel-cover__divider"> <p class="panel-cover__description">Thomas lab at the University of Sheffield</p> <hr class="panel-cover__divider panel-cover__divider--secondary"> <div class="navigation-wrapper"> <nav class="cover-navigation cover-navigation--primary"> <ul class="navigation"> <li class="navigation__item"><a href="/ghthomas.github.io/#blog" title="link to Macroevolution Group blog" class="blog-button">About</a></li> </ul> <ul class="navigation"> <li class="navigation__item"><a href="/ghthomas.github.io/people" title="link to Macroevolution Group blog" class="blog-button">People</a></li> </ul> </nav> <nav class="cover-navigation navigation--social"> <ul class="navigation"> <!-- Twitter --> <li class="navigation__item"> <a href="http://twitter.com/gavothomas" title="@gavothomas on Twitter" target="_blank"> <i class="icon icon-social-twitter"></i> <span class="label">Twitter</span> </a> </li> <!-- GitHub --> <li class="navigation__item"> <a href="https://www.github.com/ghthomas" title="ghthomas on GitHub" target="_blank"> <i class="icon icon-social-github"></i> <span class="label">GitHub</span> </a> </li> <!-- Email --> <li class="navigation__item"> <a href="mailto:gavin.thomas@sheffield.ac.uk" title="Email gavin.thomas@sheffield.ac.uk" target="_blank"> <i class="icon icon-mail"></i> <span class="label">Email</span> </a> </li> <!-- RSS --> <li class="navigation__item"> <a href="/ghthomas.github.io/feed.xml" title="Subscribe" target="_blank"> <i class="icon icon-rss"></i> <span class="label">RSS</span> </a> </li> </ul> </nav> </div> </div> </div> <div class="panel-cover--overlay"></div> </div> </header> <div class="content-wrapper"> <div class="content-wrapper__inner"> <article class="post-container post-container--single"> <header class="post-header"> <div class="post-meta"> <time datetime="8 Jan 2016" class="post-meta__date date">8 Jan 2016</time> &#8226; <span class="post-meta__tags">on <a href="/ghthomas.github.io/tags/#jekyll">jekyll</a> </span> </div> <h1 class="post-title">Welcome to the Macroevolution Group!</h1> </header> <section class="post"> <p>Welcome to the Macroevolution research group website. Our research focuses on modelling the diversification of species and traits at a macroevolutionary scale.</p> <p>We are currently preoccupied with collecting a large database of bill shapes and plumage colours from all extant bird species (~10,000 species) using museum study skins (mainly the NHM at Tring and also the University of Manchester Museum). More about this ERC funded project from the links below.</p> </section> </article> </div> <footer class="footer"> <span class="footer__copyright">&copy; 2017 Gavin Thomas. All rights reserved.</span> </footer> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript" src="/ghthomas.github.io/js/main.js"></script> </div> </body> </html>
ghthomas/ghthomas.github.io
_site/2016/a-test/index.html
HTML
mit
7,847
/* * RAForm * (c) Red Ant <mobile.support@redant.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <UIKit/UIKit.h> @interface RAFormSecureTextEntryCell:UITableViewCell @property (nonatomic, weak) IBOutlet UITextField *textField; @property (weak, nonatomic) IBOutlet UILabel *messageField; @property (weak, nonatomic) IBOutlet UIButton *infoButton; - (IBAction)showInfo:(id)sender; @end
redant-mobile/raformview
RAFormViewSampleApp/RAFormViewKit/Cells/RAFormSecureTextEntryCell.h
C
mit
490
using System.Collections.Generic; using System.Security.Claims; namespace FujiyBlog.Web.Areas.Admin.ViewModels { public class AdminRoleSave { public string Id { get; set; } public string Name { get; set; } public IEnumerable<string> Claims { get; set; } } }
fujiy/FujiyBlog
src/FujiyBlog.Web/Areas/Admin/ViewModels/AdminRoleSave.cs
C#
mit
302
## Synopsis WMI-Query class/module is a nodejs package enabling "Web-Based Enterprise Management" on microsoft OS using "Windows Management Instrumentation" and more precisely **wmic** command line tools. Thus **it needs to be run on a microsoft OS**. ## Code Example ``` //requiring module var wmi = require("wmi-query"); //log os of localhost wmi.get({format:'JSON' , alias:'os', field:'Name'}, function(r) { console.log('OS is', r.data[0].Name); }); //list of available alias on remote server wmi.listAlias({node : 'remote_computer', format:'JSON' }, function(r) { for(var i=0; i<r.data.length; i++) { console.log(r.data[i].alias); } }); //start a service named example on remote_computer wmi.call({node:"remote_computer", alias:'service', where: 'Name="example"', action:'startservice', format:'JSON'}, function(r) { if (r.err) { console.log("Start service failed with message:", r.err); } else { console.log("Command has returned } }); ``` ## Motivation I needed a way to check state, start/stop services on a couple of remote computer from a web interface. Then Microsoft announced there nano server edition which is heavily relying on wmi so I though it was a good time to start learning more about it. ## Installation Since I haven't publish this to npm yet and there is no dependency, just download wmi-query file and require it. I'm really planning on publishing this to npm, so when it will be done just do: ``` npm install wmi-query ``` ## API Reference [Documentation](http://anapajari.github.io/wmi-query/docs.html) can be found [here](http://anapajari.github.io/wmi-query/docs.html). ## Contributors Feel like you can improve this, go for it! I did mt best to write clean code but if you have any question just ask. ## License MIT. ## Author Matthieu Bourgeois
Anapajari/wmi-query
README.md
Markdown
mit
1,917
# rewrites the expressions generated by clang using DataStructures # node: the input obuff has the type annotations in the function signature and the types in the ccall as references to the same Expr object. A deepcopy and overwrite is needed to fix hthis # dictionary to map pointer types to desired type # isdefined(modulename, :name) -> Bool # use wrap_contex.commonbuf for dictionary of names that have been defined # used to modify function signatures type_dict = Dict{Any, Any} ( :PetscScalar => :Float64, :PetscReal => :Float64, :PetscInt => :Int64, ) const petsc_libname = :petscRealDouble val_tmp = type_dict[:PetscScalar] type_dict_single = Dict{Any, Any} ( :(Ptr{UInt8}) => Union{Cstring, ByteString, Symbol, Array{UInt8}, Ptr{UInt8}} ) # used to convert typealiases to immutable type definionts # currently, if the key exists, it is converted # if value == 1, create new immutable type # otherwise replace key with value # also used for function signatures new_type_dict = Dict{Any, Any} ( :Vec => :(Vec{$val_tmp}), :Mat => :(Mat{$val_tmp}), :KSP => :(KSP{$val_tmp}), :PC => :(PC{$val_tmp}), :PetscViewer => :(PetscViewer{$val_tmp}), :PetscOption => :(PetscOption{$val_tmp}), :IS => :(IS{$val_tmp}), :ISLocalToGlobalMapping => :(ISLocalToGlobalMapping{$val_tmp}), :ISColoring => :(ISColoring{$val_tmp}), :PetscLayout => :(PetscLayout{$val_tmp}), :VecScatter => :(VecScatter{$val_tmp}), ) # definitions that will be provided, but don't come from Petsc # mostly MPI stuff const_defs = Dict{Any, Any} ( :MPI_COMM_SELF => 1, :MPI_Comm => 1, :comm_type => 1, ) # dictionary to hold names of types # that are aliased to Symbol symbol_type_dict = Dict{Any, Any} () # create a string array mirroring a symbol array function send_symbol(x::AbstractArray) string_arr = similar(x, ASCIIString) for i=1:length(x) if isdefined(x[i]) string_arr[i] = copy(x[i]) end end return string_arr end # get a string array and turn it into a symbol array function return_symbol(string_array::AbstractArray, x::AbstractArray) for i=1:length(x) x[i] = bytestring(string_array[i]) end end # things to be recursively replaced in function signatures sig_rec_dict = Dict{Any, Any} () for i in keys(type_dict) get!(sig_rec_dict, i, type_dict[i]) end for i in keys(new_type_dict) get!(sig_rec_dict, i, new_type_dict[i]) end # things to be replaced in function signatures only if they # are top level (ie. this does a non recursive replace) sig_single_dict = Dict{Any, Any} ( :(Ptr{UInt8}) => :(Union{ByteString, Symbol, Array{UInt8}}), :Int32 => :Integer, :Int64 => :Integer, :Cint => :Integer, :PetscInt => :Integer, ) # list of symbols to search for # if none are found, then a dummy argument is added sig_dummyarg_dict = Dict{Any, Any}( :PetscScalar => 1, ) # add keys from new_type_dict because dummy arg check # is done after type replacement for i in values(new_type_dict) get!(sig_dummyarg_dict, i, 1) end # things to be recursively replaced in the ccall argument list ccall_rec_dict = Dict{Any, Any} ( :MPI_Comm => :comm_type ) for i in keys(type_dict) get!(ccall_rec_dict, i, type_dict[i]) end for i in keys(new_type_dict) get!(ccall_rec_dict, i, new_type_dict[i]) end # things to be replace in the ccall argument list only if # they are top level (ie. this does a non recursive replace) ccall_single_dict = Dict{Any, Any} ( :(Ptr{UInt8}) => :Cstring, ) # things to be replaced recurisvely in typealias rhs typealias_rec_dict = Dict{Any, Any} () for i in keys(type_dict) get!(typealias_rec_dict, i, type_dict[i]) end for i in keys(new_type_dict) get!(typealias_rec_dict, i, new_type_dict[i]) end # dictionary of typealiases to exclude based on the lhs argument typealias_lhs_dict = Dict{Any, Any} () for i in keys(type_dict) get!(typealias_lhs_dict, i, i) end # things to be replaced in typealias rhs, non recursive # this creates a potential loophole for string handling # because a Ptr{typealias} == Ptr{Ptr{UInt8}} will be # handled incorrectly typealias_single_dict = Dict{Any, Any} ( :(Ptr{UInt8}) => :Symbol ) # key = typealias rhs values to exclude # if values == 1, then create an immutable type typealias_exclude_dict = Dict{Any, Any} ( ) for i in keys(new_type_dict) get!(typealias_exclude_dict, i, 1) end # things to be recurisvely replace in constant declaration rhs const_rec_dict = Dict{Any, Any} ( :NULL => :C_NULL ) for i in keys(type_dict) get!(const_rec_dict, i, type_dict[i]) end for i in keys(new_type_dict) get!(const_rec_dict, i, new_type_dict[i]) end function petsc_rewriter(obuf) for i=1:length(obuf) ex_i = obuf[i] # obuf is an array of expressions if typeof(ex_i) == Expr head_i = ex_i.head # function # each ex_i has 2 args, a function signature and a function body # figure out what kind of expression it is, do the right modification if head_i == :function # function declaration obuf[i] = process_func(ex_i) elseif ex_i.head == :const # constant declaration obuf[i] = process_const(ex_i) elseif ex_i.head == :typealias # typealias definition obuf[i] = fix_typealias(ex_i) elseif ex_i.head == :type obuf[i] = process_type(ex_i) else # some other kind of expression println("not processing expression", ex_i) # convert to concrete types for j in keys(type_dict) obuf[i] = replace_symbol(ex_i, j, type_dict[j]) end # purge anything unknown # this will always omit the expression because a newly declared name # will be unknown tmp = are_syms_defined(ex_i) if tmp != 0 obuf[i] = "#= skipping undefined expression $ex_i =#" end # for types at least, arg[2] is the type name obj_name = ex_i.args[2] if haskey(wc.common_buf, obj_name) delete!(wc.common_buf, obj_name) end end elseif typeof(ex_i) == ASCIIString obuf[i] = process_string(ex_i) else println("not processing ", typeof(ex_i)) end # end if Expr end return obuf # return modified obuf end ##### functions to rewrite function signature ##### function process_func(ex) @assert ex.head == :function # this is a function declaration ex.args[1] = rewrite_sig(ex.args[1]) # function signature ex.args[2] = rewrite_body(ex.args[2]) # function body # now check if any undefined type annotations remain sum = 0 ex_sig = ex.args[1] ex_body = ex.args[2] for i=2:length(ex_sig.args) # loop over all arguments to the function # get the type annotation Expr or symbol of argument i-1 ex_sig_i = ex_sig.args[i].args[2] sum += are_syms_defined(ex_sig_i) end # now check ccall argument types ex_ccall = ex_body.args[1] ex_ccall_types = ex_ccall.args[3] # the tuple of argument types sum += are_syms_defined(ex_ccall_types) if sum != 0 return "#= skipping function with undefined symbols: \n $ex \n=#" end # now add any extra expression needed ex = add_body(ex) return ex end # add any needed expressions to the body of the function # this is post rewrite_sig, rewrite_body function add_body(ex) ex_sig = ex.args[1] ex_body = ex.args[2] fname = ex_sig.args[1] @assert typeof(fname) == Symbol fname_str = string(fname) # check if a type annotation == Union(Ptr{symbol_type}...) println("checking function ", fname_str, " for symbols-string conversions") # check number of ccall args vs. function signature args numargs_ccall = length(ex_body.args[1].args) - 3 numargs_func = length(ex_sig.args) - 1 offset = numargs_func - numargs_ccall # skip any function args in excess of ccall args for i in keys(symbol_type_dict) for j=(2 + offset):length(ex_sig.args) # loop over arguments to function println("j = ", j) type_annot_j = ex_sig.args[j].args[2] # get the teyp annotation argname_j = ex_sig.args[j].args[1] # check for arrays of symbols that need to be copied into a string array if type_annot_j == :(Union{Ptr{$i}, StridedArray{$i}, Ptr{$i}, Ref{$i}}) if contains(fname_str, "Get") # array is to be populated # add calls to function body resize!(ex_body.args, length(ex_body.args) + 2) for i=2:(length(ex_body.args) - 1) ex_body.args[i] = deepcopy(ex_body.args[i-1]) # shift ccall to 2nd arg end ex_body.args[1] = nothing ex_body.args[end] = nothing # figure out where the ccall is ccall_index = get_ccall_index(ex_body) # construct the before function call call_ex = Expr(:call, :symbol_get_before, argname_j) new_argname = symbol(string( argname_j, "_")) # add underscore ex_body.args[1] = Expr(:(=), :($new_argname, tmp), deepcopy(call_ex)) # construct the after call ex_body.args[length(ex_body.args)] = Expr(:call, :symbol_get_after, new_argname, argname_j) # modify the ccall argument name println("ccall_index = ", ccall_index) ccall_ex = ex_body.args[ccall_index] @assert ccall_ex.head == :ccall ccall_ex.args[j + 3 - 1 - offset] = new_argname elseif contains(fname_str, "Set") # array is already populated # add calls to function body resize!(ex_body.args, length(ex_body.args) + 1) for i=2:(length(ex_body.args)) ex_body.args[i] = deepcopy(ex_body.args[i-1]) # shift ccall to 2nd arg end ex_body.args[1] = nothing # figure out where the ccall is ccall_index = get_ccall_index(ex_body) # construct the before function call call_ex = Expr(:call, :symbol_set_before, argname_j) new_argname = symbol(string( argname_j, "_")) # add underscore ex_body.args[1] = Expr(:(=), new_argname, deepcopy(call_ex)) # modify the ccall argument name ccall_ex = ex_body.args[ccall_index] @assert ccall_ex.head == :ccall ccall_ex.args[j + 3 - 1 - offset] = new_argname else println(STDERR, "Warning, symbol type conversion not handled in function ", fname_str) end # end if contains(get) end # end if type_annot_j == ... end # end for j end # end loop over symbol_type_dict # assign ccall error code to a variable, then return the variable # this should be the last modification made, because get_ccall_index # won't work after this ccall_index = get_ccall_index(ex_body) ccall_ex = deepcopy(ex_body.args[ccall_index]) ex_body.args[ccall_index] = :(err = $ccall_ex) resize!(ex_body.args, length(ex_body.args) + 1) ex_body.args[end] = :(return err) # convert array of symbols to array of strings # check signature for return deepcopy(ex) end function get_ccall_index(ex) # returns the index of the first ccall in the arguments of ex index = 0 for i=1:length(ex.args) if typeof(ex.args[i]) == Expr if ex.args[i].head == :ccall index = i break end end end if index == 0 println("Warning, ccall not found") end return index end function rewrite_sig(ex) # rewrite the function signature @assert ex.head == :call # verify this is a function signature expression # ex.args[1] = function name, as a symbol # check if function contains a PetscScalar # if yes, add paramterization, do search and replace PetscScalar -> S # also add macro println("rewrite_sig ex = ", ex) # Process all arguments of the function # Replace all pointers with Unions(Ptr, AbstractArray...) # do any other transformations in ptr_dict for i=2:length(ex.args) # each of ex.args is an expression containing arg name, argtype println("typeof(ex.args[$i]) = ", typeof(ex.args[i])) @assert typeof(ex.args[i]) == Expr || typeof(ex.args[i]) == Symbol # verify these are all expressions ex.args[i] = process_sig_arg(ex.args[i]) # process each expression end # check for any symbol that will uniquely identify which # version of petsc to call println("checking for uniqueness of signature") println("ex = ", ex) val = contains_symbol(ex, :PetscScalar) for i in keys(sig_dummyarg_dict) val += contains_symbol(ex, i) end println("contains_symbol = ", val) if val == 0 # if no arguments will make the function signature unique println("adding dummy arg") ex = add_dummy_arg(ex) end #= println("replacing typealiases") println("ex = ", ex) # do second pass to replace Petsc typealiases with a specific type for i=2:length(ex.args) for j in keys(type_dict) # check for all types println("replacing ", j, ", with ", type_dict[j]) ex.args[i] = replace_symbol(ex.args[i], j, type_dict[j]) end end println("after modification rewrite_sig ex = ", ex) =# return ex end function process_sig_arg(ex) # take the expression that is an argument to the function and rewrite it @assert ex.head == :(::) # modify args here # arg_name = ex.args[1] # symbol # arg_type = ex.args[2] # Expr contianing type tag println("ex.args[2] = ", ex.args[2]) println("type = ", typeof(ex.args[2])) # if typeof(ex.args[1]) == Symbol # get only typetag expression, modify it ex.args[2] = modify_typetag(ex.args[2]) return ex end function modify_typetag(ex) # do non recursive replace first ex = get(sig_single_dict, ex, ex) # now do recursive search and replace for i in keys(sig_rec_dict) ex = replace_symbol(ex, i, sig_rec_dict[i]) end # should make sure there are no nested pointers? # @assert ex.head == :curly || ex.head == :symbol # verify this is a typetag if typeof(ex) == Expr # replace pointer with Union of ptr, array, c_null if ex.head == :curly && ex.args[1] == :Ptr ptr_type = ex.args[2] ex = :(Union{Ptr{$ptr_type}, StridedArray{$ptr_type}, Ptr{$ptr_type}, Ref{$ptr_type}}) end end return ex end function add_param(ex) # add the {S <: PetscScalar} to a function declaration @assert typeof(ex) == Symbol # make sure we don't already have a paramaterization # could do more extensive operations here return :($ex{S <: PetscScalars}) end function add_dummy_arg(ex) # add a dummy argument to the function argument list # ex is the function name + args (ie. the entire function signature) println("adding dummy argument to ", ex) @assert ex.head == :call len = length(ex.args) resize!(ex.args, len + 1) println("length(ex.args) = ", length(ex.args)) println("ex.args = ", ex.args) # shift args up by one # first arg is function name, so don't modify it if length(ex.args) >= 3 # if there are any args to shift println("shifting arguments, length(ex.args) = ", length(ex.args)) for i=length(ex.args):(-1):3 ex.args[i] = ex.args[i-1] println("ex.args[$i] = ", ex.args[i]) end end # insert dummy argument into first position # the PetscScalar will get rewritten to # appropriate type later val = type_dict[:PetscScalar] ex.args[2] = :(arg0::Type{$val}) println("finished adding dummy arg, ex = ", ex) return ex end ##### function to rewrite the body of the function ##### function rewrite_body(ex) # rewrite body of a function @assert ex.head == :block # ex has only one argument, the ccall # could insert other statements arond the ccall here? ex.args[1] = process_ccall(ex.args[1]) return ex end function process_ccall(ex) @assert ex.head == :ccall # verify this is the ccall statement # args[1] = Expr, tuple of fname, libname # args[2] = return type, symbol # args[3] = Expr, tuple of types to ccall # args[4] = symbol, first argument name, # ... println("processing ccall ", ex) ex.args[1] = modify_libname(ex.args[1]) # change the library name ex.args[3] = modify_types(ex.args[3]) println("changing argument names") ex3 = ex.args[3] # get expression of argument types # ex4 = ex.args[4] # get expression argument names @assert ex3.head == :tuple return ex end function modify_types(ex) @assert ex.head == :tuple # do non recursive replace first for i=1:length(ex.args) println("checking if ", ex.args[i], " has entry in ccall_single_dict") println("ex.args[$i] before = ", ex.args[i]) ex.args[i] = get(ccall_single_dict, ex.args[i], ex.args[i]) println(" after = ", ex.args[i]) end # do recursive replacement for i in keys(ccall_rec_dict) for j=1:length(ex.args) ex.args[j] = replace_symbol(ex.args[j], i, ccall_rec_dict[i]) end end return deepcopy(ex) end function modify_libname(ex) @assert ex.head == :tuple ex.args[2] = petsc_libname # replace libname with a new one return ex end ##### functions to make consts into global consts ##### function process_const(ex) @assert ex.head == :const # do any replacements for j in keys(const_rec_dict) replace_symbol(ex, j, const_rec_dict[j]) end ex2 = ex.args[1] # get the assignment rhs = ex2.args[2] tmp = are_syms_defined(rhs) if tmp != 0 # something is undefined lhs = ex2.args[1] delete!(wc.common_buf, lhs) # remove lh from list of defined symbols return "#skipping undefined $ex" # replace expression with constant end # turn strings into symbols if typeof(rhs) <: AbstractString ex2.args[2] = :(symbol($rhs)) end return deepcopy(ex) end function fix_typealias(ex) @assert ex.head == :typealias new_type = ex.args[1] if haskey(typealias_exclude_dict, new_type) if typealias_exclude_dict[new_type] == 1 # construct immutable type definition fields = Expr(:(::), :pobj, :(Ptr{Void})) body = Expr(:block, fields) typename = Expr(:curly, new_type, :T) # add static parameter T ex_new = Expr(:type, false, typename, body) return ex_new else if haskey(wc.common_buf, new_type) delete!(wc.common_buf, new_type) # record that symbol is now undefined end return "# excluding $ex" end end # if we didn't create immutable type, transform the rhs according to the # dictionaries lhs = deepcopy(ex.args[1]) rhs = deepcopy(ex.args[2]) # check lhs for exclusion criteria if haskey(typealias_lhs_dict, lhs) # record that symbol is now undefined delete!(wc.common_buf, lhs) return "# excluding lhs of $ex" end # do non recursive replacement rhs = get(typealias_single_dict, rhs, rhs) if rhs == :Symbol get!(ccall_rec_dict, lhs, :(Ptr{UInt8})) # make the ccall argument a UInt8 recursive get!(ccall_single_dict, lhs, :Cstring) # make it a cstring for single level replacement get!(symbol_type_dict, lhs, 1) # record that this type is a symbol end # do recursive replacement for i in keys(typealias_rec_dict) rhs = replace_symbol(rhs, i, typealias_rec_dict[i]) end # check for undefined symbols tmp = are_syms_defined(rhs) if tmp != 0 delete!(wc.common_buf, lhs) # record that the lhs symbol is now undefined return "# skipping undefined typealias $ex" end # if no conditions met # construct a new typealias return :(typealias $lhs $rhs) end # string processing function process_string(ex) return "#= $ex =#" end ##### Type declaration functions ##### function process_type(ex) # make all types (structs) immutable ex.args[1] = false ex_body = ex.args[3] # body of type declaration # check that every type annotation is fully defined for i=1:length(ex_body.args) # if this is a type annotation expression if typeof(ex_body.args[i]) == Expr && ex_body.args[i].head == :(::) type_sym = ex_body.args[i].args[2] tmp = are_syms_defined(type_sym) if tmp != 0 new_name = ex.args[2] # get the name of the type being declared delete!(wc.common_buf, new_name) return "#= skipping type declaration with undefined symbols:\n$ex \n=#" end end end return ex end ##### Misc. functions #### function contains_symbol(ex, sym) # recursively check symbol in expression ex to see if sym is present sum = 0 if ex == sym return 1 elseif typeof(ex) == Expr #check the arguments of the exprssion for i=1:length(ex.args) sum += contains_symbol(ex.args[i], sym) end else # something unknown return 0 # assuming we did not find the symbol end return sum end function check_annot(ex, sym::Symbol) # check a type annotation for i=1:length(ex.args) if ex.args[i] == sym return true end end return false end function replace_symbol(ex, sym_old, sym_new) if ex == sym_old return deepcopy(sym_new) elseif typeof(ex) == Expr # recurse the arguments for i=1:length(ex.args) ex.args[i] = replace_symbol(ex.args[i], sym_old,sym_new) end else # don't know/care what this is return deepcopy(ex) end return deepcopy(ex) end function count_depth(seed::Integer, ex) # primitive attempt to count number of nodes on tree if typeof(ex) == Expr for i=1:length(ex.args) seed += count_depth(seed, ex.args[i]) end else println("ex = ", ex, " returning 1") return 1 end return seed end function are_syms_defined(ex) # check all symbols, see if they are defined by julia or by # the wrap contex undefined_syms = 0 # approximate counter of undefined symbols found if typeof(ex) == Expr # keep recursing for i=1:length(ex.args) undefined_syms += are_syms_defined(ex.args[i]) end # end loop over args elseif typeof(ex) == Symbol # if this is a symbol if isdefined(ex) || haskey(wc.common_buf, ex) || haskey(const_defs, ex) return 0 # symbol is defined else return 1 end else # we don't know/care what this expression is println(" not counting unknown expression ", ex) return undefined_syms end # end if ... elseifa return undefined_syms end
stevengj/PETSc.jl
src/generated/rewriter.jl
Julia
mit
22,005
using UnityEngine; using System.Collections; using UnityEngine.UI; public class StartMenuUIControl : MonoBehaviour { /*===================== GameObjects =====================================================================================*/ public GameObject characterCreationMenuPrefab; /*===================== Menus =====================================================================================*/ public GameObject characterCreationMenu; /*===================== UI Elements =====================================================================================*/ public Button StartNewGameButton; public Button LoadGameButton; public Button GameInfoButton; public Button ExitGameButton; /*===================== Methods =====================================================================================*/ /*===================== Start() =====================================================================================*/ void Start(){ // Setup the characterCreationMenu // Get reference for menu because it was instantiated characterCreationMenu = GameObject.FindWithTag ("CharacterCreationMenu"); // Set characterCreationMenu's aphla to 0 (Makes transperent) characterCreationMenu.GetComponent<CanvasGroup> ().alpha = 0; // Block raycasts - making the menu not clickable characterCreationMenu.GetComponent<CanvasGroup> ().blocksRaycasts = false; // Activate CharacterCreationMenu characterCreationMenu.gameObject.SetActive (true); // Activate CharacterTraitsMenu characterCreationMenu.GetComponent<CharacterCreationUIControl> ().characterTraitsMenu.gameObject.SetActive (true); } // Start() /*===================== NewGame() =====================================================================================*/ // Fires when player clicks "StartNewGameButton" public void NewGame(){ // Deactivates MainMenu gameObject.SetActive(false); // Activates Character Creation Menu characterCreationMenu.gameObject.SetActive(true); // Runs setup needed for characterCreationMenu characterCreationMenu.GetComponent<CharacterCreationUIControl> ().SetUp (); } // NewGame() /*===================== LoadGame() =====================================================================================*/ // Fires when player clicks "LoadGameButton" public void LoadGame(){ Application.LoadLevel (1); } // LoadGame() /*===================== GameInfo() =====================================================================================*/ // Fires when player clicks "GameInfoButton" public void GameInfo(){ } // GameInfo() /*===================== ExitGame() =====================================================================================*/ // Fires when player clicks "ExitGameButton" public void ExitGame(){ // Exits the game Application.Quit(); } // ExitGame() } // class
Ross-Byrne/Management_Mayhem
Assets/Scripts/UI/StartMenu/StartMenuUIControl.cs
C#
mit
2,906
Mini.define('layerTemplate', function(){ var $detail = $('#t-detail').html() return { detail: _.template($detail) } }); Mini.define('serviceLayer', [ 'layerTemplate' ], function(layerTemplate){ return { ctn: function(e) { layer.open({ title: '箱动态列表', type: 1, skin: 'layui-layer-rim my-layer-skin', //加上边框 area: ['480px', 'auto'], //宽高 content: layerTemplate.detail(e.data) }) } } })
hoozi/hyd2
js/site/components/serviceLayer.js
JavaScript
mit
559
# frozen_string_literal: true Rails.application.routes.draw do match "lock/login", to: "lock#login", as: "lock_login", via: :get match "lock/refused", to: "lock#refused", as: "unlock_refused", via: :get match "lock/unlock", to: "lock#unlock", as: "unlock", via: :post end
charlotte-ruby/lock
config/routes.rb
Ruby
mit
279
#!/bin/bash if [ -z "$BACKEND_ID" -o -z "$SERVER_ID" -o -z "$URL" -o -z "$VULCAN_URL" -o -z "$TIMEOUT_SECS" ]; then echo "register-healthcheck requires the following variables:" >&2 echo ' $BACKEND_ID $SERVER_ID $URL $VULCAN_URL $TIMEOUT_SECS' >&2 exit 1 fi function ttl_param { if [ -n "$FRONTEND_TTL_SECS" ]; then echo "--ttl ${FRONTEND_TTL_SECS}s" fi } function disableBackend { vctl server rm --backend $BACKEND_ID --id $SERVER_ID --vulcan $VULCAN_URL } function enableBackend { vctl server upsert \ --id $SERVER_ID \ --backend $BACKEND_ID \ --url $URL \ --vulcan $VULCAN_URL \ $(ttl_param) } echo 'Adding backend, server, and frontend to vulcand' vctl backend upsert --id $BACKEND_ID --vulcan $VULCAN_URL while true; do curl --silent -I $URL/healthcheck | head -n 1 | awk '{print $2}' | grep '200' HEALTHCHECK_STATUS=$? if [ $HEALTHCHECK_STATUS -eq 0 ]; then enableBackend else disableBackend fi sleep $TIMEOUT_SECS done
octoblu/docker-register-sidekick
register-healthcheck.sh
Shell
mit
1,004
// For vendors for example jQuery, Lodash, angular2-jwt just import them here unless you plan on // chunking vendors files for async loading. You would need to import the async loaded vendors // at the entry point of the async loaded file. Also see custom-typings.d.ts as you also need to // run `typings install x` where `x` is your module // Angular 2 import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; import '@angular/router'; import '@angular/forms'; import '@angular/common'; import '@angular/core'; import '@angular/http'; import '@angularclass/form-validators'; // RxJS import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; if ('production' === ENV) { // Production } else { // Development }
katallaxie/generator-angular2-starter
template/src/vendor.ts
TypeScript
mit
756
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Internal function to process the separation of a physics body from a tile. * * @function Phaser.Physics.Arcade.Tilemap.ProcessTileSeparationX * @since 3.0.0 * * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. * @param {number} x - The x separation amount. */ var ProcessTileSeparationX = function (body, x) { if (x < 0) { body.blocked.left = true; } else if (x > 0) { body.blocked.right = true; } body.position.x -= x; if (body.bounce.x === 0) { body.velocity.x = 0; } else { body.velocity.x = -body.velocity.x * body.bounce.x; } }; module.exports = ProcessTileSeparationX;
rblopes/phaser
src/physics/arcade/tilemap/ProcessTileSeparationX.js
JavaScript
mit
901
# wms-downloader-mngr ## Installation ### 01 NodeJS and NPM Windows: Use the installer from <https://nodejs.org/> Ubuntu / Debian: ```sh sudo apt install nodejs npm ``` ### 02 GraphicsMagick Windows: Use the installer from <http://www.graphicsmagick.org/> Ubuntu / Debian: ```sh sudo apt install graphicsmagick ``` ### 03 7-Zip Windows: Use the installer from <http://www.7-zip.org/> Subsequent register the path of the "7z.exe" ("C:\Program Files\7-Zip" or "C:\Program Files (x86)\7-Zip") into the "PATH" environment variable. Ubuntu / Debian: ```sh sudo apt-get install p7zip-full ``` ### 04 wms-downloader-mngr Use terminal: ```sh npm install wms-downloader-mngr ``` ## Get started ### Example #### Download ```js const mngr = require('wms-download-mngr'); /* * Init options for wms-downloader-mngr */ const initOptions = { "mngr" : { "workspace" : __dirname + "/example1_workspace", "logs": __dirname + "/example.log", "maxOfSimultaneousTasks" : 1, "deletionTimeoutOfCompletedTasks" : 600000, "taskCacheExpiration" : 10000 }, "request" : { "userAgent" : "wms-downloader", "timeout" : 30000 } } /* * Init the wms-downloader-mngr */ mngr.init(initOptions); /* * Task 1 for wms-downloader-mngr */ const task1 = { "task" : { "id" : "id_of_task1", "title" : "Stadtbezirke 1:15000 96DPI", "format" : "image/png", "area" : { "bbox" : { "xmin" : 455000, "ymin" : 5750000, "xmax" : 479000, "ymax" : 5774000 } } }, "tiles" : { "maxSizePx" : 2500, "gutterPx" : 250, "resolutions" : [ { "id" : "15000", "scale" : 15000, "dpi" : 96 } ] }, "wms" : [ { "id" : "wms_stadtbezirke", "getmap" : { "url" : "http://www.bielefeld01.de/geodaten/geo_dienste/wms.php?url=gebietsgliederung_wms_stadtbezirke_641&", "kvp" : { "SERVICE" : "WMS", "REQUEST" : "GetMap", "VERSION" : "1.3.0", "LAYERS" : "stadtbezirke_wms", "STYLES" : "", "CRS" : "EPSG:25832", "FORMAT" : "image/png", "TRANSPARENT" : "TRUE" } } } ] }; /* * Task 2 for wms-downloader-mngr */ const task2 = { "task" : { "id" : "id_of_task2", "title" : "Bebauungsplanübersicht 1:25000 96DPI", "format" : "image/png", "area" : { "bbox" : { "xmin" : 455000, "ymin" : 5750000, "xmax" : 479000, "ymax" : 5774000 } } }, "tiles" : { "maxSizePx" : 2500, "gutterPx" : 250, "resolutions" : [ { "id" : "25000", "scale" : 25000, "dpi" : 96 } ] }, "wms" : [ { "id" : "wms_bplan_uebersicht", "getmap" : { "url" : "http://www.bielefeld01.de/geodaten/geo_dienste/wms.php?url=bplan_wms_uebersicht_641&", "kvp" : { "SERVICE" : "WMS", "REQUEST" : "GetMap", "VERSION" : "1.3.0", "LAYERS" : "bebauungsplanuebersicht_wms", "STYLES" : "", "CRS" : "EPSG:25832", "FORMAT" : "image/png", "TRANSPARENT" : "TRUE" } } } ] }; /* * Task 3 for wms-downloader-mngr */ const task3 = { "task" : { "id" : "id_of_task3", "title" : "Bebauungsplanübersicht 1:2500 72DPI", "format" : "image/png", "area" : { "bbox" : { "xmin" : 455000, "ymin" : 5750000, "xmax" : 479000, "ymax" : 5774000 } } }, "tiles" : { "maxSizePx" : 25000, "gutterPx" : 250, "resolutions" : [ { "id" : "25000", "scale" : 25000, "dpi" : 96 } ] }, "wms" : [ { "id" : "wms_bplan_uebersicht", "getmap" : { "url" : "http://www.bielefeld01.de/geodaten/geo_dienste/wms.php?url=bplan_wms_uebersicht_641&", "kvp" : { "SERVICE" : "WMS", "REQUEST" : "GetMap", "VERSION" : "1.3.0", "LAYERS" : "bebauungsplanuebersicht_wms", "STYLES" : "", "CRS" : "EPSG:25832", "FORMAT" : "image/png", "TRANSPARENT" : "TRUE" } } } ] }; /* * Add task 1 to wms-downloader-mngr */ mngr.addTask(task1, function(err) { if (err) { console.log('Can\'t add task 1: ' + err.message); } else { console.log('Added task 1.'); } }); /* * Add task 2 to wms-downloader-mngr */ mngr.addTask(task2, function(err) { if (err) { console.log('Can\'t add task 2: ' + err.message); } else { console.log('Added task 2.'); } }); /* * Add task 3 to wms-downloader-mngr */ mngr.addTask(task3, function(err) { if (err) { console.log('Can\'t add task 3: ' + err.message); } else { console.log('Added task 3.'); } }); /* * Remove task 3 after 19 seconds */ setTimeout(function() { mngr.removeTask(task3.task.id, function(err) { if (err) { console.log(err); } else { console.log(task3.task.id + ' was removed.'); } }); }, 19000); ``` #### Download with proxy ```js const mngr = require('wms-download-mngr'); /* * Init options for wms-downloader-mngr */ const initOptions = { "mngr" : { "workspace" : __dirname + "/example1_workspace", "logs": __dirname + "/example.log", "maxOfSimultaneousTasks" : 1, "deletionTimeoutOfCompletedTasks" : 600000, "taskCacheExpiration" : 10000 }, "request" : { "userAgent" : "wms-downloader", "timeout" : 30000, "proxy" : { "http" : { "host" : "10.208.20.71", "port" : 4239, "user" : "NameOfUser", "password" : "PasswordOfUser", "exclude" : [ "http://12.101.20.18/", "http://12.208.28.48/" ] } } } } /* * Init the wms-downloader-mngr */ mngr.init(initOptions); /* * Task 1 for wms-downloader-mngr */ const task1 = { "task" : { "id" : "id_of_task1", "title" : "Stadtbezirke 1:15000 96DPI", "format" : "image/png", "area" : { "bbox" : { "xmin" : 455000, "ymin" : 5750000, "xmax" : 479000, "ymax" : 5774000 } } }, "tiles" : { "maxSizePx" : 2500, "gutterPx" : 250, "resolutions" : [ { "id" : "15000", "scale" : 15000, "dpi" : 96 } ] }, "wms" : [ { "id" : "wms_stadtbezirke", "getmap" : { "url" : "http://www.bielefeld01.de/geodaten/geo_dienste/wms.php?url=gebietsgliederung_wms_stadtbezirke_641&", "kvp" : { "SERVICE" : "WMS", "REQUEST" : "GetMap", "VERSION" : "1.3.0", "LAYERS" : "stadtbezirke_wms", "STYLES" : "", "CRS" : "EPSG:25832", "FORMAT" : "image/png", "TRANSPARENT" : "TRUE" } } } ] }; /* * Task 2 for wms-downloader-mngr */ const task2 = { "task" : { "id" : "id_of_task2", "title" : "Bebauungsplanübersicht 1:25000 96DPI", "format" : "image/png", "area" : { "bbox" : { "xmin" : 455000, "ymin" : 5750000, "xmax" : 479000, "ymax" : 5774000 } } }, "tiles" : { "maxSizePx" : 2500, "gutterPx" : 250, "resolutions" : [ { "id" : "25000", "scale" : 25000, "dpi" : 96 } ] }, "wms" : [ { "id" : "wms_bplan_uebersicht", "getmap" : { "url" : "http://www.bielefeld01.de/geodaten/geo_dienste/wms.php?url=bplan_wms_uebersicht_641&", "kvp" : { "SERVICE" : "WMS", "REQUEST" : "GetMap", "VERSION" : "1.3.0", "LAYERS" : "bebauungsplanuebersicht_wms", "STYLES" : "", "CRS" : "EPSG:25832", "FORMAT" : "image/png", "TRANSPARENT" : "TRUE" } } } ] }; /* * Task 3 for wms-downloader-mngr */ const task3 = { "task" : { "id" : "id_of_task3", "title" : "Bebauungsplanübersicht 1:2500 72DPI", "format" : "image/png", "area" : { "bbox" : { "xmin" : 455000, "ymin" : 5750000, "xmax" : 479000, "ymax" : 5774000 } } }, "tiles" : { "maxSizePx" : 25000, "gutterPx" : 250, "resolutions" : [ { "id" : "25000", "scale" : 25000, "dpi" : 96 } ] }, "wms" : [ { "id" : "wms_bplan_uebersicht", "getmap" : { "url" : "http://www.bielefeld01.de/geodaten/geo_dienste/wms.php?url=bplan_wms_uebersicht_641&", "kvp" : { "SERVICE" : "WMS", "REQUEST" : "GetMap", "VERSION" : "1.3.0", "LAYERS" : "bebauungsplanuebersicht_wms", "STYLES" : "", "CRS" : "EPSG:25832", "FORMAT" : "image/png", "TRANSPARENT" : "TRUE" } } } ] }; /* * Add task 1 to wms-downloader-mngr */ mngr.addTask(task1, function(err) { if (err) { console.log('Can\'t add task 1: ' + err.message); } else { console.log('Added task 1.'); } }); /* * Add task 2 to wms-downloader-mngr */ mngr.addTask(task2, function(err) { if (err) { console.log('Can\'t add task 2: ' + err.message); } else { console.log('Added task 2.'); } }); /* * Add task 3 to wms-downloader-mngr */ mngr.addTask(task3, function(err) { if (err) { console.log('Can\'t add task 3: ' + err.message); } else { console.log('Added task 3.'); } }); /* * Remove task 3 after 19 seconds */ setTimeout(function() { mngr.removeTask(task3.task.id, function(err) { if (err) { console.log(err); } else { console.log(task3.task.id + ' was removed.'); } }); }, 19000); ``` ## Supported formats - image/png - image/jpeg - image/gif - image/tiff ## License MIT
stadt-bielefeld/wms-downloader-mngr
README.md
Markdown
mit
9,448
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>User agent detail - Mozilla/5.0 (Linux; Android 4.0.4; XT862 Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="../circle.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; Android 4.0.4; XT862 Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Motorola</td><td>XT862</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59">Detail</a> <!-- Modal Structure --> <div id="modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (Linux; Android 4.0.4; XT862 Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19 [family] => XT862 [brand] => Motorola [model] => XT862 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Chrome 18.0</td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.10101</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-47a9cd06-e213-4882-bc34-db6aed664223">Detail</a> <!-- Modal Structure --> <div id="modal-47a9cd06-e213-4882-bc34-db6aed664223" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapFull result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.0.*\) applewebkit\/.* \(khtml.* like gecko\) chrome\/18\..*safari\/.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?4.0*) applewebkit/* (khtml* like gecko) chrome/18.*safari/* [parent] => Chrome 18.0 for Android [comment] => Chrome 18.0 [browser] => Chrome [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 18.0 [majorver] => 18 [minorver] => 0 [platform] => Android [platform_version] => 4.0 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [isfake] => [isanonymized] => [ismodified] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td><td>Chrome </td><td><i class="material-icons">close</i></td><td>Android </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.008</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-42bb56ba-b834-47c5-bea0-c0270e9ab371">Detail</a> <!-- Modal Structure --> <div id="modal-42bb56ba-b834-47c5-bea0-c0270e9ab371" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapLite result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.*\) applewebkit\/.* \(khtml.* like gecko\) chrome\/.*safari\/.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android*) applewebkit/* (khtml* like gecko) chrome/*safari/* [parent] => Chrome Generic for Android [comment] => Chrome Generic [browser] => Chrome [browser_type] => unknown [browser_bits] => 0 [browser_maker] => unknown [browser_modus] => unknown [version] => 0.0 [majorver] => 0 [minorver] => 0 [platform] => Android [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => false [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => unknown [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td><td>Chrome 18.0</td><td><i class="material-icons">close</i></td><td>Android </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.024</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68">Detail</a> <!-- Modal Structure --> <div id="modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.*\) applewebkit\/.* \(khtml.* like gecko\) chrome\/18\..*safari\/.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android*) applewebkit/* (khtml* like gecko) chrome/18.*safari/* [parent] => Chrome 18.0 for Android [comment] => Chrome 18.0 [browser] => Chrome [browser_type] => unknown [browser_bits] => 0 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 18.0 [majorver] => 18 [minorver] => 0 [platform] => Android [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>Chrome 18.0.1025.166</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a> <!-- Modal Structure --> <div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Chrome [version] => 18.0.1025.166 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td>Chrome 18.0.1025.166</td><td><i class="material-icons">close</i></td><td>AndroidOS 4.0.4</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a> <!-- Modal Structure --> <div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>JenssegersAgent result detail</h4> <p><pre><code class="php">Array ( [browserName] => Chrome [browserVersion] => 18.0.1025.166 [osName] => AndroidOS [osVersion] => 4.0.4 [deviceModel] => Motorola [isMobile] => 1 [isRobot] => [botName] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>Chrome Mobile 18.0.1025.166</td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555">Motorola</td><td>XT862</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.28302</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a> <!-- Modal Structure --> <div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 960 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Motorola [mobile_model] => XT862 [version] => 18.0.1025.166 [is_android] => 1 [browser_name] => Chrome Mobile [operating_system_family] => Android [operating_system_version] => 4.0.4 [is_ios] => [producer] => Google Inc. [operating_system] => Android 4.0.x Ice Cream Sandwich [mobile_screen_width] => 540 [mobile_browser] => Chrome Mobile ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td>Chrome Mobile 18.0</td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555">Motorola</td><td>XT862</td><td>smartphone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.004</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a> <!-- Modal Structure --> <div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Chrome Mobile [short_name] => CM [version] => 18.0 [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 4.0 [platform] => ) [device] => Array ( [brand] => MR [brandName] => Motorola [model] => XT862 [device] => 1 [deviceName] => smartphone ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => 1 [isTablet] => [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td><td>Chrome 18.0.1025.166</td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ec1cd248-02b0-457e-8a9d-35bb99af008c">Detail</a> <!-- Modal Structure --> <div id="modal-ec1cd248-02b0-457e-8a9d-35bb99af008c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; Android 4.0.4; XT862 Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19 ) [name:Sinergi\BrowserDetector\Browser:private] => Chrome [version:Sinergi\BrowserDetector\Browser:private] => 18.0.1025.166 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => [isFacebookWebView:Sinergi\BrowserDetector\Browser:private] => [isCompatibilityMode:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 4.0.4 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; Android 4.0.4; XT862 Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; Android 4.0.4; XT862 Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td>Chrome Mobile 18.0.1025</td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555">Motorola</td><td>XT862</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a> <!-- Modal Structure --> <div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 18 [minor] => 0 [patch] => 1025 [family] => Chrome Mobile ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 4 [minor] => 0 [patch] => 4 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => Motorola [model] => XT862 [family] => XT862 ) [originalUserAgent] => Mozilla/5.0 (Linux; Android 4.0.4; XT862 Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td>Chrome 18.0.1025.166</td><td>WebKit 535.19</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.15301</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a> <!-- Modal Structure --> <div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [platform_name] => Android [platform_version] => 4.0.4 [platform_type] => Mobile [browser_name] => Chrome [browser_version] => 18.0.1025.166 [engine_name] => WebKit [engine_version] => 535.19 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.066</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee">Detail</a> <!-- Modal Structure --> <div id="modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 4.0.4 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => [agent_languageTag] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>Chrome 18.0.1025.166</td><td>WebKit 535.19</td><td>Android 4.0.4</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.23401</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a> <!-- Modal Structure --> <div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Chrome 18 on Android (Ice Cream Sandwich) [browser_version] => 18 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => stdClass Object ( [System Build] => IML74K ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => chrome [operating_system_version] => Ice Cream Sandwich [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 535.19 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Ice Cream Sandwich) [operating_system_version_full] => 4.0.4 [operating_platform_code] => [browser_name] => Chrome [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; Android 4.0.4; XT862 Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19 [browser_version_full] => 18.0.1025.166 [browser] => Chrome 18 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td>Chrome 18</td><td>Webkit 535.19</td><td>Android 4.0.4</td><td style="border-left: 1px solid #555">Motorola</td><td>Droid 3</td><td>mobile:smart</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a> <!-- Modal Structure --> <div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Chrome [version] => 18 [type] => browser ) [engine] => Array ( [name] => Webkit [version] => 535.19 ) [os] => Array ( [name] => Android [version] => 4.0.4 ) [device] => Array ( [type] => mobile [subtype] => smart [manufacturer] => Motorola [model] => Droid 3 ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td><td>Chrome 18.0.1025.166</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9">Detail</a> <!-- Modal Structure --> <div id="modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Chrome [vendor] => Google [version] => 18.0.1025.166 [category] => smartphone [os] => Android [os_version] => 4.0.4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td>Chrome 18.0.1025.166</td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555">Motorola</td><td>XT862</td><td>Smartphone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.025</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a> <!-- Modal Structure --> <div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => true [is_mobile] => true [is_robot] => false [is_smartphone] => true [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 4.0.4 [advertised_browser] => Chrome [advertised_browser_version] => 18.0.1025.166 [complete_device_name] => Motorola XT862 (Droid 3) [device_name] => Motorola Droid 3 [form_factor] => Smartphone [is_phone] => true [is_app_webview] => false ) [all] => Array ( [brand_name] => Motorola [model_name] => XT862 [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Chrome Mobile [mobile_browser_version] => 18 [device_os_version] => 4.0 [pointing_method] => touchscreen [release_date] => 2011_july [marketing_name] => Droid 3 [model_extra_info] => Verizon [nokia_feature_pack] => 0 [can_assign_phone_number] => true [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => none [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 540 [resolution_height] => 960 [columns] => 60 [max_image_width] => 540 [max_image_height] => 960 [rows] => 40 [physical_screen_width] => 50 [physical_screen_height] => 89 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => false [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => false [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 384 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => progressive_download [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => false [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td>Google Chrome 18.0.1025.166</td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a> <!-- Modal Structure --> <div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Zsxsoft result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [link] => http://google.com/chrome/ [title] => Google Chrome 18.0.1025.166 [name] => Google Chrome [version] => 18.0.1025.166 [code] => chrome [image] => img/16/browser/chrome.png ) [os] => Array ( [link] => http://www.android.com/ [name] => Android [version] => 4.0.4 [code] => android [x64] => [title] => Android 4.0.4 [type] => os [dir] => os [image] => img/16/os/android.png ) [device] => Array ( [link] => [title] => [model] => [brand] => [code] => null [dir] => device [type] => device [image] => img/16/device/null.png ) [platform] => Array ( [link] => http://www.android.com/ [name] => Android [version] => 4.0.4 [code] => android [x64] => [title] => Android 4.0.4 [type] => os [dir] => os [image] => img/16/os/android.png ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-05-10 08:05:30</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
ThaDafinser/UserAgentParserComparison
v5/user-agent-detail/b1/e4/b1e4fe5b-aac1-4d31-a73b-2862f9949a87.html
HTML
mit
56,523
// // XMCommunityViewController.h // XMLolGames // // Created by montnets on 2016/12/22. // Copyright © 2016年 montnets. All rights reserved. // #import <UIKit/UIKit.h> @interface XMCommunityViewController : UITableViewController @end
LoveCcheng/XMLolGames
XMLolGames/Community(four)/controller/XMCommunityViewController.h
C
mit
244
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Mindmapp</title> <base href="/"> <meta content="width=device-width, initial-scale=1" name="viewport"> <meta content="yes" name="apple-mobile-web-app-capable"> <meta content="yes" name="mobile-web-app-capable"> <meta content="Web application to draw mind maps." name="description"> <meta content="Web application to draw mind maps." property="og:description"> <meta content="Mindmapp" property="og:title"> <meta content="https://mindmapp.cedoor.dev" property="og:url"> <link href="./assets/icons/icon-72x72.png" rel="icon" type="image/png"/> <link href="manifest.webmanifest" rel="manifest"> <meta content="#37474f" name="theme-color"> </head> <body> <mindmapp-root></mindmapp-root> <noscript>Please enable JavaScript to continue using this application.</noscript> </body> </html>
Mindmapp/mindmapp
src/index.html
HTML
mit
903
<?php namespace Oro\Bundle\UserBundle\Tests\Unit\Type; use Oro\Bundle\UserBundle\Form\Type\ChangePasswordType; use Symfony\Component\Form\Test\FormIntegrationTestCase; class ChangePasswordTypeTest extends FormIntegrationTestCase { /** @var \PHPUnit_Framework_MockObject_MockObject */ protected $subscriber; /** @var ChangePasswordType */ protected $type; public function setUp() { parent::setUp(); $this->subscriber = $this->getMockBuilder('Oro\Bundle\UserBundle\Form\EventListener\ChangePasswordSubscriber') ->disableOriginalConstructor() ->getMock(); $this->type = new ChangePasswordType($this->subscriber); } /** * Test buildForm */ public function testBuildForm() { $builder = $this->getMock('Symfony\Component\Form\Test\FormBuilderInterface'); $options = array(); $builder->expects($this->once()) ->method('addEventSubscriber') ->with($this->isInstanceOf('Oro\Bundle\UserBundle\Form\EventListener\ChangePasswordSubscriber')); $builder->expects($this->exactly(2)) ->method('add') ->will($this->returnSelf()); $this->type->buildForm($builder, $options); } /** * Test defaults */ public function testSetDefaultOptions() { $resolver = $this->getMock('Symfony\Component\OptionsResolver\OptionsResolverInterface'); $resolver->expects($this->once()) ->method('setDefaults') ->with($this->isType('array')); $this->type->configureOptions($resolver); } /** * Test name */ public function testName() { $this->assertEquals('oro_change_password', $this->type->getName()); } }
akeneo/platform
src/Oro/Bundle/UserBundle/Tests/Unit/Form/Type/ChangePasswordTypeTest.php
PHP
mit
1,781
export function mergeUsers({ props, state, uuid }) { if (props.response.result.users && props.response.result.users.length !== 0) { let orderKey = 1 for (const user of props.response.result.users) { user.orderKey = orderKey const usersInState = state.get('admin.users') const uidInState = Object.keys(usersInState).filter((uid) => { return usersInState[uid].email === user.email })[0] if (uidInState) { state.merge(`admin.users.${uidInState}`, user) } else { state.set(`admin.users.${uuid()}`, user) } orderKey++ } } else { return { noUsersFound: true } } } export function getNextPage({ props, state }) { let nextPage = 1 switch (props.nextPage) { case 'previous': nextPage = parseInt(state.get('admin.currentPage')) - 1 break case 'next': nextPage = parseInt(state.get('admin.currentPage')) + 1 break case 'last': nextPage = state.get('admin.pages') break default: if (typeof props.nextPage === 'number') { nextPage = Math.floor(props.nextPage) } } return { nextPage } }
yacoma/auth-boilerplate
client/app/modules/admin/actions.js
JavaScript
mit
1,148
<?php namespace Dodici\Fansworld\WebBundle\Controller; use Doctrine\ORM\EntityManager; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use JMS\SecurityExtraBundle\Annotation\Secure; use Dodici\Fansworld\WebBundle\Controller\SiteController; use Dodici\Fansworld\WebBundle\Entity\Comment; use Dodici\Fansworld\WebBundle\Entity\Contest; use Dodici\Fansworld\WebBundle\Entity\ContestParticipant; use Dodici\Fansworld\WebBundle\Entity\ContestVote; use Dodici\Fansworld\WebBundle\Entity\Privacy; use Symfony\Component\HttpFoundation\Request; /** * Home controller. */ class ContestController extends SiteController { const commentsLimit = 6; const contestLimit = 20; const participantsLimit = 5; /** * Site's home * * @Template */ public function indexAction() { return array( ); } /** * My Contests * * @Route("/my-contests", name="contest_mycontests") * @Template */ public function myContestsAction() { $user = $this->getUser(); $participating = $this->getRepository('ContestParticipant')->userParticipating($user); $contests = array(); foreach ($participating as $item) { $contest = $this->getRepository('Contest')->find($item->getContest()->getId()); $contests[] = $contest; } return array( 'user' => $user, 'contests' => $contests ); } /** * * @Route("/ajax/contest/comments", name="contest_ajaxcomments") */ public function ajaxCommentsAction() { $request = $this->getRequest(); $contestId = $request->get('contestId'); $page = $request->get('page', 0); $page--; $contestRepo = $this->getRepository('Contest'); $contestComments = $contestRepo->findOneBy(array('id' => $contestId))->getComments(); $chunked = array_chunk($contestComments, self::commentsLimit); $response = new Response(json_encode($chunked[$page])); $response->headers->set('Content-Type', 'application/json'); return $response; } /** * @Route("/ajax/contest/add_comment", name = "contest_ajaxaddcomment") */ public function ajaxAddCommentAction() { $response = null; try { $request = $this->getRequest(); $contestId = $request->get('contestId'); $content = $request->get('content'); $contest = $this->getRepository('Contest')->findOneBy(array('id' => $contestId)); $user = $this->getUser(); $newComment = new Comment(); $newComment->setAuthor($user); $newComment->setContent($content); $newComment->setContest($contest); $newComment->setActive(true); $newComment->setPrivacy(Privacy::EVERYONE); $em = $this->getDoctrine()->getEntityManager(); $em->persist($newComment); $em->flush(); $response = array( 'saved' => true, 'comment' => array( 'id' => $newComment->getId(), 'name' => (string) $user, 'content' => $content, 'avatar' => $this->getImageUrl($user->getImage()), 'createdAt' => $newComment->getCreatedAt(), 'like' => $this->renderView('DodiciFansworldWebBundle:Default:like_button.html.twig', array( 'showcount' => false, 'entity' => $newComment )) ) ); } catch (\Exception $exc) { $response = array('saved' => false, 'exception' => $exc->getMessage()); } $response = new Response(json_encode($response)); $response->headers->set('Content-Type', 'application/json'); return $response; } /** * @Route("/ajax/contest/participate", name="contest_ajaxparticipate") */ public function ajaxParticipateAction() { $request = $this->getRequest(); $contest = $request->get('contestId'); $user = $this->getUser(); $contest = $this->getRepository('Contest')->findOneBy(array('id' => $contest)); $isParticipant = $this->getRepository('ContestParticipant')->findOneBy(array('author' => $user, 'contest' => $contest)); if (!$isParticipant) { try { $newParticipant = new ContestParticipant(); $newParticipant->setAuthor($user); switch ($contest->getType()) { case Contest::TYPE_TEXT: $newParticipant->setText($request->get('text')); break; case Contest::TYPE_PHOTO: $photoId = $request->get('photo'); $photo = $this->getRepository('Photo')->find($photoId); $newParticipant->setPhoto($photo); break; case Contest::TYPE_VIDEO: $videoId = $request->get('video'); $video = $this->getRepository('Video')->find($videoId); $newParticipant->setVideo($video); break; } $newParticipant->setContest($contest); $newParticipant->setWinner(false); $em = $this->getDoctrine()->getEntityManager(); $em->persist($newParticipant); $em->flush(); $response = true; } catch (\Exception $exc) { echo $exc->getMessage(); $response = false; } } else { $response = false; } $response = new Response(json_encode($response)); $response->headers->set('Content-Type', 'application/json'); return $response; } /** * @Route("/contests", name="contest_list") * * @Template */ public function listAction() { $contests = $this->getRepository('Contest')->findBy(array('active' => true), array('createdAt' => 'desc'), self::contestLimit); $countContests = $this->getRepository('Contest')->countBy(array('active' => true)); $addMore = $countContests > self::contestLimit ? true : false; $filterType = array( 'TYPE_PARTICIPATE' => Contest::TYPE_PARTICIPATE, 'TYPE_TEXT' => Contest::TYPE_TEXT, 'TYPE_PHOTO' => Contest::TYPE_PHOTO, 'TYPE_VIDEO' => Contest::TYPE_VIDEO ); return array('contests' => $contests, 'addMore' => $addMore, 'filterType' => $filterType); } /** * @Route("/ajax/contest/list", name="contest_ajaxlist") */ public function ajaxListAction() { $request = $this->getRequest(); $filter = $request->get('filter', false); $page = $request->get('page', 1); $page--; $offset = $page * self::contestLimit; if ($filter && $filter !== 'null') { $criteria = array( 'active' => true, 'type' => $filter ); } else { $criteria = array( 'active' => true ); } $contests = $this->getRepository('Contest')->findBy($criteria, array('createdAt' => 'desc'), self::contestLimit, $offset); $contestsCount = $this->getRepository('Contest')->countBy($criteria); $contestsCount = $contestsCount / self::contestLimit; $addMore = $contestsCount > $page ? true : false; $response = array(); foreach ($contests as $contest) { $response[] = array( 'id' => $contest->getId(), 'title' => $contest->getTitle(), 'active' => $contest->getActive(), 'content' => $contest->getContent(), 'image' => $this->getImageUrl($contest->getImage()), 'createdAt' => $contest->getCreatedAt(), 'endDate' => $contest->getEndDate(), 'type' => $contest->getType(), 'slug' => $contest->getSlug() ); } $response = new Response(json_encode(array('contests' => $response, 'addMore' => $addMore))); $response->headers->set('Content-Type', 'application/json'); return $response; } /** * @Route("/contest/{id}/{slug}", name= "contest_show", defaults = {"id" = 0}, requirements={"id"="\d+"}) * @Template * @Secure(roles="ROLE_USER") */ public function showAction($id) { if ($id > 0) { $contest = $this->getRepository('Contest')->findOneBy(array('id' => $id)); } else { $contest = false; } $user = $this->getUser(); $isParticipant = $this->getRepository('ContestParticipant')->findOneBy(array('contest' => $contest->getId(), 'author' => $user->getId())); $participants = $this->getRepository('ContestParticipant')->findBy(array('contest' => $contest->getId()), array('createdAt' => 'desc'), self::participantsLimit); $countAllParticipants = $this->getRepository('ContestParticipant')->countBy(array('contest' => $contest->getId())); $addMoreParticipants = $countAllParticipants > self::participantsLimit ? true : false; $winners = $this->getRepository('ContestParticipant')->findBy(array('contest' => $contest->getId(), 'winner' => true)); $filesUploaded = array(); $textUploaded = array(); $participants = $this->getRepository('ContestParticipant')->findBy(array('contest' => $contest->getId()), array('createdAt' => 'desc'), self::participantsLimit); $alreadyVoted = $this->getRepository('ContestVote')->byUserAndContest($user, $contest); switch ($contest->getType()) { case Contest::TYPE_TEXT: foreach ($participants as $participant) { $cantVotes = $this->getRepository('ContestVote')->countBy(array('contestparticipant' => $participant->getId())); array_push($textUploaded, array( 'participantId' => $participant->getId(), 'text' => $participant->getText(), 'author' => $participant->getAuthor(), 'votes' => $cantVotes )); } break; case Contest::TYPE_PHOTO: foreach ($participants as $participant) { if($participant->getPhoto()){ $cantVotes = $this->getRepository('ContestVote')->countBy(array('contestparticipant' => $participant->getId())); array_push($filesUploaded, array( 'participantId' => $participant->getId(), 'file' => $participant->getPhoto(), 'author' => $participant->getAuthor(), 'votes' => $cantVotes )); } } break; case Contest::TYPE_VIDEO: foreach ($participants as $participant) { if($participant->getVideo()){ $cantVotes = $this->getRepository('ContestVote')->countBy(array('contestparticipant' => $participant->getId())); array_push($filesUploaded, array( 'participantId' => $participant->getId(), 'file' => $participant->getVideo(), 'author' => $participant->getAuthor(), 'votes' => $cantVotes )); } } } return array('contest' => $contest, 'voted' => $alreadyVoted, 'isParticipant' => $isParticipant, 'participants' => $participants, 'winners' => $winners, 'files' => $filesUploaded, 'texts' => $textUploaded, 'addMoreParticipants' => $addMoreParticipants); } /** * @Route("/ajax/contest/participants", name="contest_pagerParticipants") */ public function pagerParticipants() { $request = $this->getRequest(); $contestId = $request->get('contest'); $page = $request->get('page', 1); $offset = ($page - 1) * self::participantsLimit; $response = array(); $countAllParticipants = $this->getRepository('ContestParticipant')->countBy(array('contest' => $contestId)); $participantsCount = $countAllParticipants / self::participantsLimit; $response['addMore'] = $participantsCount > $page ? true : false; $participants = $this->getRepository('ContestParticipant')->findBy(array('contest' => $contestId), array('createdAt' => 'desc'), self::participantsLimit, $offset); foreach ($participants as $participant) { $author = $participant->getAuthor(); $element = array(); $cantVotes = $this->getRepository('ContestVote')->countBy(array('contestparticipant' => $participant->getId())); switch ($participant->getContest()->getType()) { case Contest::TYPE_TEXT: $element = array( 'id' => $participant->getId(), 'text' => $participant->getText(), 'votes' => $cantVotes ); break; case Contest::TYPE_PHOTO: $element = array( 'id' => $participant->getPhoto()->getId(), 'image' => $this->getImageUrl($participant->getPhoto()), 'votes' => $cantVotes ); break; case Contest::TYPE_VIDEO: $element = array( 'id' => $participant->getVideo()->getId(), 'votes' => $cantVotes ); break; } $response['participants'][] = array( 'id' => $author->getId(), 'name' => (string) $author, 'avatar' => $this->getImageUrl($author->getImage()), 'contestType' => $participant->getContest()->getType(), 'element' => $element ); } return $this->jsonResponse($response); } /** * @Route("/ajax/contest/participant/vote", name="contest_voteParticipant") */ public function voteParticipant() { $request = $this->getRequest(); $contestId = $request->get('contest', false); $participantId = $request->get('participant', false); $author = $this->getUser(); $response = array(); $participant = $this->getRepository('ContestParticipant')->find($participantId); $contest = $this->getRepository('Contest')->find($contestId); $alreadyVoted = $this->getRepository('ContestVote')->byUserAndContest($author, $contest); if (!$alreadyVoted) { try { $entity = new ContestVote; $entity->setAuthor($author); $entity->setContestparticipant($participant); $em = $this->getDoctrine()->getEntityManager(); $em->persist($entity); $em->flush(); $response['voted'] = true; } catch (Exception $exc) { $response['voted'] = false; $response['error'] = $exc->getMessage(); } } else { $response['voted'] = false; $response['error'] = 'already voted'; } return $this->jsonResponse($response); } }
FansWorldTV/web
src/Dodici/Fansworld/WebBundle/Controller/ContestController.php
PHP
mit
16,104
QuakeMap::Application.configure do # Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Print deprecation notices to the stderr config.active_support.deprecation = :stderr # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = 'public, max-age=3600' # Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets config.assets.allow_debugging = true end
QuakeMap/quakemap
config/environments/test.rb
Ruby
mit
1,814
package errors import ( "net/http" "fmt" ) // NewValidationError creates a new APIError with 422 Unprocessable entity http status code to be used as reporting the validation failure func NewValidationError(e ... error) APIError { return APIError{ StatusCode: http.StatusUnprocessableEntity, Title: "Request data validation error", LocalizationKey: "validation_error", Errors: e, } } // NewParameterRequiredError returns a new native error reporting that a specified parameter is missing func NewParameterRequiredError(param string) error { return New(fmt.Sprintf("Parameter %s is required", param)) } // NewParameterRequiredError returns a new native error reporting that a specified parameter is invalid func NewParameterInvalidError(param string) error { return New(fmt.Sprintf("Parameter %s failed to pass validation", param)) }
uroshercog/kanban-board-backend
http/errors/validation.go
GO
mit
874
VBA ===
jifarooq/VBA
README.md
Markdown
mit
8
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { customElement, html, LitElement, property, } from "lit-element"; import { fireEvent } from "./util/fire-event"; import { getMouseTouchLocation } from "./util/get-mouse-touch-location"; import { getTouchIdentifier } from "./util/get-touch-identifier"; import { matchesSelectorAndParentsTo } from "./util/match-selector"; let LitDraggable = class LitDraggable extends LitElement { constructor() { super(...arguments); this.disabled = false; this._dragging = false; } firstUpdated() { this.addEventListener("mousedown", this._dragStart.bind(this), { capture: true, passive: false, }); this.addEventListener("touchstart", this._dragStart.bind(this), { capture: true, passive: false, }); document.addEventListener("mousemove", this._drag.bind(this), { capture: true, passive: false, }); document.addEventListener("touchmove", this._drag.bind(this), { capture: true, passive: false, }); document.addEventListener("mouseup", this._dragEnd.bind(this), { capture: true, passive: false, }); document.addEventListener("touchcancel", this._dragEnd.bind(this), { capture: true, passive: false, }); document.addEventListener("touchend", this._dragEnd.bind(this), { capture: true, passive: false, }); } render() { return html `<slot></slot>`; } _dragStart(ev) { if ((ev.type.startsWith("mouse") && ev.button !== 0) || this.disabled) { return; } console.log(ev); if (this.handle && !matchesSelectorAndParentsTo(ev.currentTarget, this.handle, this.offsetParent)) { return; } ev.preventDefault(); ev.stopPropagation(); if (ev.type === "touchstart") { this._touchIdentifier = getTouchIdentifier(ev); } const pos = getMouseTouchLocation(ev, this._touchIdentifier); if (!pos) { return; } this.startX = pos.x; this.startY = pos.y; this._dragging = true; fireEvent(this, "dragStart", { startX: this.startX, startY: this.startY, }); } _drag(ev) { if (!this._dragging || this.disabled) { return; } ev.preventDefault(); ev.stopPropagation(); const pos = getMouseTouchLocation(ev, this._touchIdentifier); if (!pos) { return; } let deltaX = pos.x - this.startX; let deltaY = pos.y - this.startY; if (this.grid) { deltaX = Math.round(deltaX / this.grid[0]) * this.grid[0]; deltaY = Math.round(deltaY / this.grid[1]) * this.grid[1]; } if (!deltaX && !deltaY) { return; } fireEvent(this, "dragging", { deltaX, deltaY, }); } _dragEnd(ev) { if (!this._dragging || this.disabled) { return; } ev.preventDefault(); ev.stopPropagation(); this._touchIdentifier = undefined; this._dragging = false; fireEvent(this, "dragEnd"); } }; __decorate([ property({ type: Array }) ], LitDraggable.prototype, "grid", void 0); __decorate([ property({ type: Boolean, reflect: true }) ], LitDraggable.prototype, "disabled", void 0); __decorate([ property() ], LitDraggable.prototype, "handle", void 0); LitDraggable = __decorate([ customElement("lit-draggable") ], LitDraggable); export { LitDraggable }; //# sourceMappingURL=lit-draggable.js.map
cdnjs/cdnjs
ajax/libs/lit-grid-layout/1.1.4/lit-draggable.js
JavaScript
mit
4,479
using System; class A { internal string S; internal void Say() { Console.WriteLine(S); } } class Program { private static void doit(Action sayit) { sayit(); } static void Main(string[] args) { A a = new A(); a.S = "I am one"; A b = new A(); b.S = "I am two"; doit(a.Say); doit(b.Say); } }
autumn009/TanoCSharpSamples
Chap4/デリゲート型はインスタンスを区別する/デリゲート型はインスタンスを区別する/Program.cs
C#
mit
398
require 'commander' require 'applyrics/project' require 'applyrics/lyricsfile' module Applyrics class Setup def run(config = {}) platform = nil if is_ios? platform = :ios elsif is_android? platform = :android elsif is_unity? platform = :unity else return end Applyrics::Lyricsfile.generate(config) Applyrics::Project.new(platform) end def is_ios? (Dir["*.xcodeproj"] + Dir["*.xcworkspace"]).count > 0 end def is_android? Dir["*.gradle"].count > 0 end def is_unity? false end end end
applyrics/applyrics-gem
lib/applyrics/setup.rb
Ruby
mit
622
<?php /* Safe sample input : backticks interpretation, reading the file /tmp/tainted.txt sanitize : use mysql_real_escape_string via an object and a classic getter construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = `cat /tmp/tainted.txt`; class Sanitize{ private $data; public function __construct($input){ $this->data = $input ; } public function getData(){ return $this->data; } public function sanitize(){ $this->data = mysql_real_escape_string($this->data) ; } } $sanitizer = new Sanitize($tainted) ; $sanitizer->sanitize(); $tainted = $sanitizer->getData(); $query = "SELECT * FROM ' $tainted '"; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_89/safe/CWE_89__backticks__object-func_mysql_real_escape_stringGetter__select_from-interpretation_simple_quote.php
PHP
mit
1,889
#include <Python.h> #include <maya/MFnPlugin.h> #include <maya/MGlobal.h> #include <maya/MPxNode.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnGenericAttribute.h> #include <maya/MFnNumericData.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnNumericData.h> #include <maya/MFnMatrixData.h> #include <maya/MDataBlock.h> #include <maya/MArrayDataHandle.h> #include <maya/MVector.h> #include <maya/MMatrix.h> #include <maya/MFnDependencyNode.h> #ifdef _WIN32 #pragma warning(disable: 4127) #endif #define EXPRESPY_NODE_ID 0x00070004 // ‚à‚µ‰½‚©‚ƏՓ˂·‚é‚Ȃ珑‚«Š·‚¦‚邱‚ƁB(Free: 0x00000000 ` 0x0007ffff) #if PY_MAJOR_VERSION < 3 // py2 ‚Å‚Í io.StringIO ‚ł͂Ȃ­ StringIO.StringIO ‚ðŽg—p‚·‚邱‚ƂŠstr ‚Æ unicode ‚É—¼‘Ήž‚³‚¹‚éB // cStringIO ‚É‚µ‚È‚¢‚Ì‚Í unicode ‚ð’Ê‚·‚½‚߁B #define STRINGIO_MODULE "StringIO" #define BUILTINS_MODULE_NAME "__builtin__" #define PYINT_fromLong PyInt_FromLong #define PYSTR_fromChar PyString_FromString #define PYBYTES_asChar PyString_AsString #define PYBYTES_check PyString_Check #define PYBYTES_SIZE PyString_GET_SIZE #else // py3 ‚Å‚Í io.StringIO ‚ðŽg—p‚µ unicode ‚݂̂ɑΉž‚·‚éB #define STRINGIO_MODULE "io" #define BUILTINS_MODULE_NAME "builtins" #define PYINT_fromLong PyLong_FromLong #define PYSTR_fromChar PyUnicode_FromString #define PYBYTES_asChar PyBytes_AsString #define PYBYTES_check PyBytes_Check #define PYBYTES_SIZE PyBytes_GET_SIZE #endif //============================================================================= /// Functions. //============================================================================= /// ƒ‚ƒWƒ…[ƒ‹‚ðƒCƒ“ƒ|[ƒg‚·‚éBPyImport_ImportModule ‚æ‚荂…€B static inline PyObject* _importModule(const char* name) { PyObject* nameo = PYSTR_fromChar(name); if (nameo) { PyObject* mod = PyImport_Import(nameo); Py_DECREF(nameo); return mod; } return NULL; } /// dict ‚©‚ç type ƒIƒuƒWƒFƒNƒg‚𓾂éB static inline PyObject* _getTypeObject(PyObject* dict, const char* name) { PyObject* o = PyDict_GetItemString(dict, name); return PyType_Check(o) ? o : NULL; } /// ’l‚ÌŽQÆ‚ð’D‚¢‚‚ dict ‚É’l‚ðƒZƒbƒg‚·‚éB static inline void _setDictStealValue(PyObject* dic, const char* key, PyObject* valo) { if (valo) { PyDict_SetItemString(dic, key, valo); Py_DECREF(valo); } else { PyDict_SetItemString(dic, key, Py_None); } } /// ƒL[‚Æ’l‚ÌŽQÆ‚ð’D‚¢‚‚ I/O —p dict ‚É’l‚ðƒZƒbƒg‚·‚éB static inline void _setIODictStealValue(PyObject* dic, PyObject* keyo, PyObject* valo) { if (valo) { PyDict_SetItem(dic, keyo, valo); Py_DECREF(valo); } else { PyDict_SetItem(dic, keyo, Py_None); } Py_DECREF(keyo); } /// dict ‚É int ‚ðƒL[‚Æ‚µ‚Ä PyObject* ‚ðƒZƒbƒg‚·‚éB static inline void _setDictValue(PyObject* dic, int key, PyObject* valo) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { PyDict_SetItem(dic, keyo, valo); Py_DECREF(keyo); } } /// dict ‚©‚ç int ‚ðƒL[‚Æ‚µ‚Ä PyObject* ‚𓾂éB static inline PyObject* _getDictValue(PyObject* dic, int key) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { PyObject* valo = PyDict_GetItem(dic, keyo); Py_DECREF(keyo); return valo; } return NULL; } /// Œ^”»•ÊÏ‚Ý‚Ì sequence ‚Ì PyObject* ‚©‚ç double3 ‚Ì data ‚𓾂éB static inline MObject _getDouble3Value(PyObject* valo) { MFnNumericData fnOutData; MObject data = fnOutData.create(MFnNumericData::k3Double); fnOutData.setData( PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2)) ); return data; } /// Œ^”»•ÊÏ‚Ý‚Ì sequence ‚Ì PyObject* ‚©‚ç double4 ‚Ì data ‚𓾂éB static inline MObject _getDouble4Value(PyObject* valo) { MFnNumericData fnOutData; MObject data = fnOutData.create(MFnNumericData::k3Double); fnOutData.setData( PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 3)) ); return data; } /// Œ^”»•ÊÏ‚Ý‚Ì sequence ‚Ì PyObject* ‚©‚ç float3 ‚Ì data ‚𓾂éB static inline MObject _getFloat3Value(PyObject* valo) { MFnNumericData fnOutData; MObject data = fnOutData.create(MFnNumericData::k3Float); fnOutData.setData( static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0))), static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1))), static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2))) ); return data; } /// sequence ‚Ì PyObject* ‚©‚ç double2, double3, double4, long2, long3 ‚Ì‚¢‚¸‚ê‚©‚𓾂éB static inline MObject _getTypedSequence(PyObject* valo) { MObject data; Py_ssize_t num = PySequence_Length(valo); if (num < 2 || 4 < num) return data; bool hasFloat = false; int ival[4]; double fval[4]; for (Py_ssize_t i=0; i<num; ++i) { PyObject* v = PySequence_GetItem(valo, i); if (PyFloat_Check(v)) { hasFloat = true; fval[i] = PyFloat_AS_DOUBLE(v); #if PY_MAJOR_VERSION < 3 } else if (PyInt_Check(v)) { ival[i] = PyInt_AS_LONG(v); fval[i] = static_cast<double>(ival[i]); #endif } else if (PyLong_Check(v)) { ival[i] = static_cast<int>(PyLong_AsLong(v)); // TODO: OverflowError ‘΍ôB fval[i] = static_cast<double>(ival[i]); } else { return data; } } MFnNumericData fnOutData; switch (num) { case 2: if (hasFloat) { data = fnOutData.create(MFnNumericData::k2Double); fnOutData.setData(fval[0], fval[1]); } else { data = fnOutData.create(MFnNumericData::k2Long); fnOutData.setData(ival[0], ival[1]); } break; case 3: if (hasFloat) { data = fnOutData.create(MFnNumericData::k3Double); fnOutData.setData(fval[0], fval[1], fval[2]); } else { data = fnOutData.create(MFnNumericData::k3Long); fnOutData.setData(ival[0], ival[1], ival[2]); } break; case 4: data = fnOutData.create(MFnNumericData::k4Double); fnOutData.setData(fval[0], fval[1], fval[2], fval[3]); break; } return data; } /// Œ^”»•ÊÏ‚Ý‚Ì PyObject* ‚Ì’l‚ð MMatrix ‚É“¾‚éB static inline void _getMatrixValueFromPyObject(MMatrix& mat, PyObject* valo) { PyObject* getElement = PyObject_GetAttrString(valo, "getElement"); if (getElement) { PyObject* idxs[] = { PYINT_fromLong(0), PYINT_fromLong(1), PYINT_fromLong(2), PYINT_fromLong(3) }; PyObject* args = PyTuple_New(2); for (unsigned i=0; i<4; ++i) { PyTuple_SET_ITEM(args, 0, idxs[i]); for (unsigned j=0; j<4; ++j) { PyTuple_SET_ITEM(args, 1, idxs[j]); PyObject* vo = PyObject_CallObject(getElement, args); //PyObject* vo = PyObject_CallFunction(getElement, "(ii)", i, j); if (vo) { mat.matrix[i][j] = PyFloat_AS_DOUBLE(vo); Py_DECREF(vo); } else { mat.matrix[i][j] = MMatrix::identity[i][j]; } } } PyTuple_SET_ITEM(args, 0, idxs[0]); PyTuple_SET_ITEM(args, 1, idxs[1]); Py_DECREF(args); Py_DECREF(idxs[2]); Py_DECREF(idxs[3]); } else { mat.setToIdentity(); } } //============================================================================= /// Exprespy node class. //============================================================================= class Exprespy : public MPxNode { PyObject* _base_globals; PyObject* _input; PyObject* _output; PyObject* _globals; PyCodeObject* _codeobj; PyObject* _mplug2_input; PyObject* _mplug2_output; PyObject* _mplug1_input; PyObject* _mplug1_output; PyObject* _api2_dict; PyObject* _type2_MVector; PyObject* _type2_MPoint; PyObject* _type2_MEulerRotation; PyObject* _type2_MMatrix; PyObject* _type2_MObject; PyObject* _type2_MQuaternion; PyObject* _type2_MColor; PyObject* _type2_MFloatVector; PyObject* _type2_MFloatPoint; PyObject* _api1_dict; PyObject* _type1_MObject; PyObject* _type_StringIO; PyObject* _sys_dict; PyObject* _sys_stdout; PyObject* _sys_stderr; int _count; MStatus _compileCode(MDataBlock&); MStatus _executeCode(MDataBlock&); void _printPythonError(); void _setInputScalar(int key, const double& val); void _setInputString(int key, const MString& str); void _setInputShort2(int key, MObject& data); void _setInputShort3(int key, MObject& data); void _setInputLong2(int key, MObject& data); void _setInputLong3(int key, MObject& data); void _setInputFloat2(int key, MObject& data); void _setInputFloat3(int key, MObject& data); void _setInputDouble2(int key, MObject& data); void _setInputDouble3(int key, MObject& data); void _setInputDouble4(int key, MObject& data); void _setInputVector3(int key, MObject& data); void _setInputMatrix(int key, MObject& data); void _setInputMObject2(int key); void _setOutputMObject2(int key, PyObject* valo); void _preparePyPlug2(); void _setInputMObject1(int key); void _setOutputMObject1(int key, PyObject* valo); void _preparePyPlug1(); public: static MTypeId id; static MString name; static MObject aCode; static MObject aInputsAsApi1Object; static MObject aCompiled; static MObject aInput; static MObject aOutput; static void* creator() { return new Exprespy; } static MStatus initialize(); Exprespy(); virtual ~Exprespy(); MStatus compute(const MPlug&, MDataBlock&); #if MAYA_API_VERSION >= 20160000 SchedulingType schedulingType () const { return MPxNode::kGloballySerial; } #endif }; MTypeId Exprespy::id(EXPRESPY_NODE_ID); MString Exprespy::name("exprespy"); MObject Exprespy::aCode; MObject Exprespy::aInputsAsApi1Object; MObject Exprespy::aCompiled; MObject Exprespy::aInput; MObject Exprespy::aOutput; //------------------------------------------------------------------------------ /// Static: Initialization. //------------------------------------------------------------------------------ MStatus Exprespy::initialize() { MFnTypedAttribute fnTyped; MFnNumericAttribute fnNumeric; MFnGenericAttribute fnGeneric; // code aCode = fnTyped.create("code", "cd", MFnData::kString); fnTyped.setConnectable(false); CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aCode) ); // inputsAsApi1Object aInputsAsApi1Object = fnNumeric.create("inputsAsApi1Object", "iaa1o", MFnNumericData::kBoolean, false); fnTyped.setConnectable(false); CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aInputsAsApi1Object) ); // compiled aCompiled = fnNumeric.create("compile", "cm", MFnNumericData::kBoolean, false); fnNumeric.setWritable(false); fnNumeric.setStorable(false); fnNumeric.setHidden(true); CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aCompiled) ); // input aInput = fnGeneric.create("input", "i"); // “ü—͂̏ꍇ‚Í kAny ‚¾‚¯‚ŃRƒlƒNƒg‚Í‘S‚Ä‹–—e‚³‚ê‚邪 setAttr ‚ł͒e‚©‚ê‚Ä‚µ‚Ü‚¤‚̂ŁAŒ‹‹Ç‘S‚Ă̗ñ‹“‚ª•K—vB fnGeneric.addDataAccept(MFnData::kAny); fnGeneric.addDataAccept(MFnData::kNumeric); // ‚±‚ê‚Í–³‚­‚Ä‚à‘åä•v‚»‚¤‚¾‚ªˆê‰žB fnGeneric.addNumericDataAccept(MFnNumericData::k2Short); fnGeneric.addNumericDataAccept(MFnNumericData::k3Short); fnGeneric.addNumericDataAccept(MFnNumericData::k2Long); fnGeneric.addNumericDataAccept(MFnNumericData::k3Long); fnGeneric.addNumericDataAccept(MFnNumericData::k2Float); fnGeneric.addNumericDataAccept(MFnNumericData::k3Float); fnGeneric.addNumericDataAccept(MFnNumericData::k2Double); fnGeneric.addNumericDataAccept(MFnNumericData::k3Double); fnGeneric.addNumericDataAccept(MFnNumericData::k4Double); fnGeneric.addDataAccept(MFnData::kPlugin); fnGeneric.addDataAccept(MFnData::kPluginGeometry); fnGeneric.addDataAccept(MFnData::kString); fnGeneric.addDataAccept(MFnData::kMatrix); fnGeneric.addDataAccept(MFnData::kStringArray); fnGeneric.addDataAccept(MFnData::kDoubleArray); fnGeneric.addDataAccept(MFnData::kIntArray); fnGeneric.addDataAccept(MFnData::kPointArray); fnGeneric.addDataAccept(MFnData::kVectorArray); fnGeneric.addDataAccept(MFnData::kComponentList); fnGeneric.addDataAccept(MFnData::kMesh); fnGeneric.addDataAccept(MFnData::kLattice); fnGeneric.addDataAccept(MFnData::kNurbsCurve); fnGeneric.addDataAccept(MFnData::kNurbsSurface); fnGeneric.addDataAccept(MFnData::kSphere); fnGeneric.addDataAccept(MFnData::kDynArrayAttrs); fnGeneric.addDataAccept(MFnData::kSubdSurface); // ˆÈ‰º‚̓Nƒ‰ƒbƒVƒ…‚·‚éB //fnGeneric.addDataAccept(MFnData::kDynSweptGeometry); //fnGeneric.addDataAccept(MFnData::kNObject); //fnGeneric.addDataAccept(MFnData::kNId); fnGeneric.setArray(true); CHECK_MSTATUS_AND_RETURN_IT(addAttribute(aInput)); // output aOutput = fnGeneric.create("output", "o"); // o—͂̏ꍇ‚Í kAny ‚¾‚¯‚Å‚Í Numeric ‚Æ NumericData ˆÈŠO‚̃RƒlƒNƒg‚Í‹–—e‚³‚ê‚È‚¢B // setAttr ‚Í•s—v‚Ȃ̂ŁA“ü—͂ƈႢ NumericData ‚Ì—ñ‹“‚܂ł͕s—v‚Æ‚·‚éB fnGeneric.addDataAccept(MFnData::kAny); //fnGeneric.addDataAccept(MFnData::kNumeric); //fnGeneric.addNumericDataAccept(MFnNumericData::k2Short); //fnGeneric.addNumericDataAccept(MFnNumericData::k3Short); //fnGeneric.addNumericDataAccept(MFnNumericData::k2Long); //fnGeneric.addNumericDataAccept(MFnNumericData::k3Long); //fnGeneric.addNumericDataAccept(MFnNumericData::k2Float); //fnGeneric.addNumericDataAccept(MFnNumericData::k3Float); //fnGeneric.addNumericDataAccept(MFnNumericData::k2Double); //fnGeneric.addNumericDataAccept(MFnNumericData::k3Double); //fnGeneric.addNumericDataAccept(MFnNumericData::k4Double); fnGeneric.addDataAccept(MFnData::kPlugin); fnGeneric.addDataAccept(MFnData::kPluginGeometry); fnGeneric.addDataAccept(MFnData::kString); fnGeneric.addDataAccept(MFnData::kMatrix); fnGeneric.addDataAccept(MFnData::kStringArray); fnGeneric.addDataAccept(MFnData::kDoubleArray); fnGeneric.addDataAccept(MFnData::kIntArray); fnGeneric.addDataAccept(MFnData::kPointArray); fnGeneric.addDataAccept(MFnData::kVectorArray); fnGeneric.addDataAccept(MFnData::kComponentList); fnGeneric.addDataAccept(MFnData::kMesh); fnGeneric.addDataAccept(MFnData::kLattice); fnGeneric.addDataAccept(MFnData::kNurbsCurve); fnGeneric.addDataAccept(MFnData::kNurbsSurface); fnGeneric.addDataAccept(MFnData::kSphere); fnGeneric.addDataAccept(MFnData::kDynArrayAttrs); fnGeneric.addDataAccept(MFnData::kSubdSurface); // ˆÈ‰º‚Í input ‚ƈá‚Á‚ăNƒ‰ƒbƒVƒ…‚Í‚µ‚È‚¢‚悤‚¾‚ª•s—v‚¾‚낤B //fnGeneric.addDataAccept(MFnData::kDynSweptGeometry); //fnGeneric.addDataAccept(MFnData::kNObject); //fnGeneric.addDataAccept(MFnData::kNId); fnGeneric.setWritable(false); fnGeneric.setStorable(false); fnGeneric.setArray(true); fnGeneric.setDisconnectBehavior(MFnAttribute::kDelete); CHECK_MSTATUS_AND_RETURN_IT(addAttribute(aOutput)); // Set the attribute dependencies. attributeAffects(aCode, aCompiled); attributeAffects(aCode, aOutput); attributeAffects(aInputsAsApi1Object, aOutput); attributeAffects(aInput, aOutput); return MS::kSuccess; } //------------------------------------------------------------------------------ /// Constructor. //------------------------------------------------------------------------------ Exprespy::Exprespy() : _base_globals(NULL), _input(NULL), _output(NULL), _globals(NULL), _codeobj(NULL), _mplug2_input(NULL), _mplug2_output(NULL), _mplug1_input(NULL), _mplug1_output(NULL), _api2_dict(NULL), _type2_MVector(NULL), _type2_MPoint(NULL), _type2_MEulerRotation(NULL), _type2_MMatrix(NULL), _type2_MObject(NULL), _type2_MQuaternion(NULL), _type2_MColor(NULL), _type2_MFloatVector(NULL), _type2_MFloatPoint(NULL), _api1_dict(NULL), _type1_MObject(NULL), _type_StringIO(NULL), _sys_dict(NULL), _sys_stdout(NULL), _sys_stderr(NULL), _count(0) { } //------------------------------------------------------------------------------ /// Destructor. //------------------------------------------------------------------------------ Exprespy::~Exprespy() { if (_base_globals) { PyGILState_STATE gil = PyGILState_Ensure(); Py_XDECREF(_sys_stdout); Py_XDECREF(_sys_stderr); Py_XDECREF(_mplug2_input); Py_XDECREF(_mplug2_output); Py_XDECREF(_mplug1_input); Py_XDECREF(_mplug1_output); Py_XDECREF(_codeobj); Py_XDECREF(_globals); Py_DECREF(_output); Py_DECREF(_input); Py_DECREF(_base_globals); PyGILState_Release(gil); } } //------------------------------------------------------------------------------ /// Computation. //------------------------------------------------------------------------------ MStatus Exprespy::compute(const MPlug& plug, MDataBlock& block) { if (plug == aCompiled) { return _compileCode(block); } else if (plug == aOutput) { return _executeCode(block); } return MS::kUnknownParameter; } //------------------------------------------------------------------------------ /// Compile a code. //------------------------------------------------------------------------------ MStatus Exprespy::_compileCode(MDataBlock& block) { MString code = block.inputValue(aCode).asString(); //MGlobal::displayInfo("COMPILE"); // Python ‚̏ˆ—ŠJŽniGILŽæ“¾jB PyGILState_STATE gil = PyGILState_Ensure(); // ˆê“x\’zÏ‚݂ȂçŒÃ‚¢ƒRƒ“ƒpƒCƒ‹Ï‚݃R[ƒh‚ð”jŠüB if (_base_globals) { Py_CLEAR(_codeobj); Py_CLEAR(_globals); // ‰‚߂ĂȂçŠÂ‹«\’z‚·‚éB } else { PyObject* builtins = PyImport_ImportModule(BUILTINS_MODULE_NAME); if (builtins) { // ƒ[ƒJƒ‹ŠÂ‹« (globals) ‚̃x[ƒX‚ð\’z‚·‚éB // ‚±‚ê‚͏‘‚«Š·‚¦‚ç‚ê‚È‚¢‚悤‚ɕێ‚µAŠeƒR[ƒhŒü‚¯‚ɂ͂±‚ê‚𕡐»‚µ‚Ä—˜—p‚·‚éB _base_globals = PyDict_New(); _input = PyDict_New(); _output = PyDict_New(); if (_base_globals && _input && _output) { // ‘g‚ݍž‚ÝŽ«‘‚ðƒZƒbƒgB _setDictStealValue(_base_globals, "__builtins__", builtins); _setDictStealValue(_base_globals, "__name__", PYSTR_fromChar("__exprespy__")); // ƒm[ƒh‚Ì“üo—͂̂½‚ß‚Ì dict ‚𐶐¬B PyDict_SetItemString(_base_globals, "IN", _input); PyDict_SetItemString(_base_globals, "OUT", _output); // ƒ‚ƒWƒ…[ƒ‹‚ðƒCƒ“ƒ|[ƒg‚µ globals ‚ɃZƒbƒgB PyObject* mod_api2 = _importModule("maya.api.OpenMaya"); _setDictStealValue(_base_globals, "api", mod_api2); _setDictStealValue(_base_globals, "math", _importModule("math")); _setDictStealValue(_base_globals, "cmds", _importModule("maya.cmds")); _setDictStealValue(_base_globals, "mel", _importModule("maya.mel")); PyObject* mod_api1 = _importModule("maya.OpenMaya"); _setDictStealValue(_base_globals, "api1", mod_api1); PyObject* mod_sys = _importModule("sys"); _setDictStealValue(_base_globals, "sys", mod_sys); // Python API ‚©‚çƒNƒ‰ƒX‚ðŽæ“¾‚µ‚Ä‚¨‚­Bu–³‚­‚È‚ç‚È‚¢‘O’ñv‚Å INCREF ‚¹‚¸‚ɕێ‚·‚éB // NOTE: –³‚­‚Ȃ邱‚Æ‚à—L‚蓾‚éi—Ⴆ‚΁AŽQÆ‚ð”jŠü‚µ‚ăCƒ“ƒ|[ƒg‚µ’¼‚µj‚ƍl‚¦‚邯­XŠëŒ¯‚ł͂ ‚éB if (mod_api2) { _api2_dict = PyModule_GetDict(mod_api2); _type2_MVector = _getTypeObject(_api2_dict, "MVector"); _type2_MPoint = _getTypeObject(_api2_dict, "MPoint"); _type2_MEulerRotation = _getTypeObject(_api2_dict, "MEulerRotation"); _type2_MMatrix = _getTypeObject(_api2_dict, "MMatrix"); _type2_MObject = _getTypeObject(_api2_dict, "MObject"); _type2_MQuaternion = _getTypeObject(_api2_dict, "MQuaternion"); _type2_MColor = _getTypeObject(_api2_dict, "MColor"); _type2_MFloatVector = _getTypeObject(_api2_dict, "MFloatVector"); _type2_MFloatPoint = _getTypeObject(_api2_dict, "MFloatPoint"); } if (mod_api1) { _api1_dict = PyModule_GetDict(mod_api1); _type1_MObject = _getTypeObject(_api1_dict, "MObject"); } // o—̓XƒgƒŠ[ƒ€‚ðæ‚ÁŽæ‚邽‚߂̏€”õB if (mod_sys) { PyObject* mod_StringIO = _importModule(STRINGIO_MODULE); if (mod_StringIO) { _type_StringIO = PyDict_GetItemString(PyModule_GetDict(mod_StringIO), "StringIO"); if (_type_StringIO) { // stdout ‚Æ stdin ‚Í INCREF ‚µ‚Ä‚¨‚©‚È‚¢‚ƁAæ‚ÁŽæ‚Á‚½Žž‚ɃNƒ‰ƒbƒVƒ…‚µ‚½‚è‚·‚éB _sys_dict = PyModule_GetDict(mod_sys); _sys_stdout = PyDict_GetItemString(_sys_dict, "stdout"); if (_sys_stdout) Py_INCREF(_sys_stdout); _sys_stderr = PyDict_GetItemString(_sys_dict, "stderr"); if (_sys_stderr) Py_INCREF(_sys_stderr); } } } } else { // ŠÂ‹«\’z‚ÉŽ¸”sB Py_CLEAR(_base_globals); Py_CLEAR(_input); Py_CLEAR(_output); } } } // ƒ[ƒJƒ‹ŠÂ‹«‚Ì•¡»‚ƁAƒ\[ƒXƒR[ƒh‚̃Rƒ“ƒpƒCƒ‹B if (_base_globals) { _globals = PyDict_Copy(_base_globals); if (_globals) { _codeobj = reinterpret_cast<PyCodeObject*>(Py_CompileString(code.asChar(), "exprespy_code", Py_file_input)); if(PyErr_Occurred()){ //MGlobal::displayInfo("Compile: error!"); Py_CLEAR(_codeobj); _printPythonError(); } } _count = 0; } // Python ‚̏ˆ—I—¹iGIL‰ð•újB PyGILState_Release(gil); // ƒRƒ“ƒpƒCƒ‹‚̐¬”Û‚ðƒZƒbƒgB //MGlobal::displayInfo(_codeobj ? "successfull" : "failed"); block.outputValue(aCompiled).set(_codeobj ? true : false); return MS::kSuccess; } //------------------------------------------------------------------------------ /// Execute a code. //------------------------------------------------------------------------------ MStatus Exprespy::_executeCode(MDataBlock& block) { block.inputValue(aCompiled); MArrayDataHandle hArrOutput = block.outputArrayValue(aOutput); if (_codeobj) { //MGlobal::displayInfo("EXECUTE"); // GILŽæ“¾‘O‚ɏ㗬•]‰¿‚ðI‚¦‚éB const bool inputsAsApi1Object = block.inputValue(aInputsAsApi1Object).asBool(); MArrayDataHandle hArrInput = block.inputArrayValue(aInput); // ‚±‚Ì’iŠK‚ŏ㗬‚ª•]‰¿‚³‚êI‚í‚Á‚Ä‚¢‚éB // Python ‚̏ˆ—ŠJŽniGILŽæ“¾jB PyGILState_STATE gil = PyGILState_Ensure(); // .input[i] ‚©‚ç’l‚ð“¾‚Ä IN[i] ‚ɃZƒbƒg‚·‚éB if (hArrInput.elementCount()) { do { const unsigned idx = hArrInput.elementIndex(); MDataHandle hInput = hArrInput.inputValue(); if (hInput.type() == MFnData::kNumeric) { // generic ‚ł́AŽc”O‚È‚ª‚琔’lŒ^‚̏ڍׂ͔»•ʂł«‚È‚¢B _setInputScalar(idx, hInput.asGenericDouble()); } else { MObject data = hInput.data(); switch (data.apiType()) { case MFn::kMatrixData: // matrix --> MMatrix (API2) _setInputMatrix(idx, data); break; case MFn::kStringData: // string --> unicode _setInputString(idx, hInput.asString()); break; case MFn::kData2Short: // short2 --> list _setInputShort2(idx, data); break; case MFn::kData3Short: // short3 --> list _setInputShort3(idx, data); break; case MFn::kData2Long: // long2 --> list _setInputLong2(idx, data); break; case MFn::kData3Long: // long3 --> list _setInputLong3(idx, data); break; case MFn::kData2Float: // float2 --> list _setInputFloat2(idx, data); break; case MFn::kData3Float: // float3 --> list _setInputFloat3(idx, data); break; case MFn::kData2Double: // double2 --> list _setInputDouble2(idx, data); break; case MFn::kData3Double: // double3 --> MVector (API2) _setInputVector3(idx, data); break; case MFn::kData4Double: // double3 --> list _setInputDouble4(idx, data); break; default: // other data --> MObject (API2 or 1) //MGlobal::displayInfo(data.apiTypeStr()); if (! data.hasFn(MFn::kData)) { // Ú‘±‚Ì undo Žž‚È‚Ç‚É kInvalid ‚ª—ˆ‚éBisNull() ‚Å‚à”»’èo—ˆ‚½‚ªAˆê‰ž data ‚¾‚¯’Ê‚·‚悤‚É‚·‚éB _setDictValue(_input, idx, Py_None); } else if (inputsAsApi1Object) { _setInputMObject1(idx); } else { _setInputMObject2(idx); } } } } while (hArrInput.next()); } // ƒJƒEƒ“ƒ^[‚ðƒZƒbƒgB _setDictStealValue(_globals, "COUNT", PYINT_fromLong(_count)); ++_count; // sys.stdout ‚ð StringIO ‚Å’D‚¤B // ‰½ŒÌ‚© print ‚̏o—͍s‚ª‹t“]‚·‚邱‚Æ‚ª‚ ‚é‚̂ŁAƒoƒbƒtƒ@‚É—­‚߂Ĉê‰ñ‚Å write ‚·‚邿‚¤‚É‚·‚éB // python ‚Ì print ‚à MGloba::displayInfo ‚à Maya ‚ɐ§Œä‚ª•Ô‚³‚ê‚È‚¢ŒÀ‚è flush ‚³‚ê‚È‚¢‚̂ŁA‚»‚Ì“_‚͕ςí‚ç‚È‚¢B // ‚È‚¨A‚±‚Ì‹t“]Œ»Û‚Í‹N‚«‚½‚è‹N‚«‚È‚©‚Á‚½‚肵AðŒ‚͂悭•ª‚©‚ç‚È‚¢BMaya 2017 win64 ‚Å‚¢‚­‚ç‚©ŽŽ‚·‚ÆŠÈ’P‚ɍČ»o—ˆ‚½B PyObject* stream = NULL; if (_sys_stdout && _type_StringIO) { stream = PyObject_CallObject(_type_StringIO, NULL); if (stream) { PyDict_SetItemString(_sys_dict, "stdout", stream); } } // ƒRƒ“ƒpƒCƒ‹Ï‚݃R[ƒhƒIƒuƒWƒFƒNƒg‚ðŽÀsB #if PY_MAJOR_VERSION < 3 PyEval_EvalCode(_codeobj, _globals, NULL); #else PyEval_EvalCode(reinterpret_cast<PyObject*>(_codeobj), _globals, NULL); #endif if(PyErr_Occurred()){ //MGlobal::displayInfo("PyEval_EvalCode: error!"); _printPythonError(); } // NOTE: py3 ‚ł̓Gƒ‰[ƒCƒ“ƒWƒP[ƒ^‚ðƒNƒŠƒA‚·‚é‘O‚É open Ï‚Ý StringIO ‚ðŽg—p‚·‚邯ƒNƒ‰ƒbƒVƒ…‚·‚é‚̂ŒˆÓ!! // StringIO ‚Ì’†g‚ð–{“–‚Ì sys.stdout ‚ɏ‘‚«o‚µAsys.stdout ‚ðŒ³‚É–ß‚·B // MGlobal::displayInfo ‚ð—p‚¢‚È‚¢‚̂́AƒRƒƒ“ƒg‰»‚ð‚³‚¹‚¸‚Ƀ_ƒCƒŒƒNƒg‚É print ‚³‚¹‚邽‚߁B if (stream) { PyObject* str = PyObject_CallMethod(stream, "getvalue", NULL); if (str) { #if PY_MAJOR_VERSION < 3 if ((PyUnicode_Check(str) && PyUnicode_GET_SIZE(str)) || PYBYTES_SIZE(str)) #else if (PyUnicode_GET_SIZE(str)) #endif PyObject_CallMethod(_sys_stdout, "write", "(O)", str); Py_DECREF(str); } PyDict_SetItemString(_sys_dict, "stdout", _sys_stdout); PyObject_CallMethod(stream, "close", NULL); Py_DECREF(stream); } // .output[i] ‚É OUT[i] ‚Ì’l‚ðƒZƒbƒg‚·‚éB‘¶Ý‚µ‚È‚¢‚à‚̂∵‚¦‚È‚¢‚à‚̏ꍇ‚Í–³Ž‹‚·‚éB if (hArrOutput.elementCount()) { MMatrix mat; do { const unsigned idx = hArrOutput.elementIndex(); PyObject* valo = _getDictValue(_output, idx); // •ÛŽ‚µ‚È‚¢‚̂ŠINCREF ‚µ‚È‚¢B if (! valo) continue; // float --> double if (PyFloat_Check(valo)) { hArrOutput.outputValue().setGenericDouble(PyFloat_AS_DOUBLE(valo), true); #if PY_MAJOR_VERSION < 3 // int --> int } else if (PyInt_Check(valo)) { hArrOutput.outputValue().setGenericInt(PyInt_AS_LONG(valo), true); #endif // long int --> int } else if (PyLong_Check(valo)) { hArrOutput.outputValue().setGenericInt(PyLong_AsLong(valo), true); // TODO: OverflowError ‘΍ôB // bool --> bool } else if (PyBool_Check(valo)) { hArrOutput.outputValue().setGenericBool(valo == Py_True, true); // str(bytes) --> string } else if (PYBYTES_check(valo)) { hArrOutput.outputValue().set(MString(PYBYTES_asChar(valo))); // unicode(str) --> string } else if (PyUnicode_Check(valo)) { // ‚±‚ꂾ‚Æ py3 ‚¾‚ÆŒ‹‰Ê‚ª‚¨‚©‚µ‚­Apy2 ‚Å‚àƒR[ƒh‚̃Gƒ“ƒR[ƒhƒ^ƒCƒv‚Ɉˑ¶‚·‚邱‚ƂɂȂéB // ƒAƒgƒŠƒrƒ…[ƒg‚́AOS‚ÆŒ¾Œê‚²‚Ƃɒè‚ß‚ç‚ꂽMayaƒV[ƒ“‚̃Gƒ“ƒR[ƒhƒ^ƒCƒv‚ª³‚µ‚¢B // Linux or Mac: utf-8, Windows“ú–{Œê=cp932(SJIS), WindowsŠÈ‘Ì’†‘Œê=cp936(GBK) //PyObject* es = PyUnicode_AsEncodedString(valo, Py_FileSystemDefaultEncoding, NULL); //if (es) { // hArrOutput.outputValue().set(MString(PYBYTES_asChar(es))); // Py_DECREF(es); //} // wchar_t ‚Ì‚Ü‚Ü MString ‰»‚·‚邪 3.2 –¢–ž‚¾‚Æ API ‚ªŒÃ‚¢‚̂Ő؂蕪‚¯‚éB #if PY_MAJOR_VERSION < 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 2) wchar_t* ws = 0; Py_ssize_t siz = PyUnicode_GET_SIZE(valo); if (siz) { ++siz; ws = reinterpret_cast<wchar_t*>(PyMem_Malloc(siz * sizeof(wchar_t))); } if (ws) { PyUnicode_AsWideChar(reinterpret_cast<PyUnicodeObject*>(valo), ws, siz); #else wchar_t* ws = PyUnicode_AsWideCharString(valo, NULL); if (ws) { #endif hArrOutput.outputValue().set(MString(ws)); PyMem_Free(ws); } else hArrOutput.outputValue().set(MString()); // MMatrix (API2) --> matrix } else if (_type2_MMatrix && PyObject_IsInstance(valo, _type2_MMatrix)) { _getMatrixValueFromPyObject(mat, valo); hArrOutput.outputValue().set(MFnMatrixData().create(mat)); // MVector, MPoint, MEulerRotation (API2) --> double3 } else if ((_type2_MVector && PyObject_IsInstance(valo, _type2_MVector)) || (_type2_MPoint && PyObject_IsInstance(valo, _type2_MPoint)) || (_type2_MEulerRotation && PyObject_IsInstance(valo, _type2_MEulerRotation))) { hArrOutput.outputValue().set(_getDouble3Value(valo)); // MQuaternion (API2) --> double4 } else if (_type2_MQuaternion && PyObject_IsInstance(valo, _type2_MQuaternion)) { hArrOutput.outputValue().set(_getDouble4Value(valo)); // MFloatVector, MFloatPoint, MColor (API2) --> float3 } else if ((_type2_MFloatVector && PyObject_IsInstance(valo, _type2_MFloatVector)) || (_type2_MFloatPoint && PyObject_IsInstance(valo, _type2_MFloatPoint)) || (_type2_MColor && PyObject_IsInstance(valo, _type2_MColor))) { hArrOutput.outputValue().set(_getFloat3Value(valo)); // sequence --> double2, double3, double4, long2, long3, or null } else if (PySequence_Check(valo)) { hArrOutput.outputValue().set(_getTypedSequence(valo)); // MObject (API2 or 1) --> data } else if (_type2_MObject && PyObject_IsInstance(valo, _type2_MObject)) { _setOutputMObject2(idx, valo); } else if (_type1_MObject && PyObject_IsInstance(valo, _type1_MObject)) { _setOutputMObject1(idx, valo); } } while (hArrOutput.next()); } // ŽŸ‰ñ‚Ì‚½‚ß‚É IN ‚Æ OUT ‚ðƒNƒŠƒA‚µ‚Ä‚¨‚­B PyDict_Clear(_input); PyDict_Clear(_output); // Python ‚̏ˆ—I—¹iGIL‰ð•újB PyGILState_Release(gil); } return hArrOutput.setAllClean(); } //------------------------------------------------------------------------------ /// Python ‚̃Gƒ‰[‚ð Maya ‚̃Gƒ‰[ƒƒbƒZ[ƒW‚Æ‚µ‚ďo—Í‚·‚éB /// ƒƒbƒZ[ƒW‚ðÔ‚­‚·‚鋤‚ɁA‰½ŒÌ‚©s‚̏‡˜‚ª‹t“]‚·‚éê‡‚ª‚ ‚é‚Ì‚ð‰ñ”ð‚·‚éB //------------------------------------------------------------------------------ #if PY_MAJOR_VERSION < 3 void Exprespy::_printPythonError() { // “–‘R‚È‚ª‚çAƒRƒ“ƒpƒCƒ‹ƒGƒ‰[‚Å‚Í traceback ƒIƒuƒWƒFƒNƒg‚Í“¾‚ç‚ꂸAƒ‰ƒ“ƒ^ƒCƒ€ƒGƒ‰[‚ł͓¾‚ç‚ê‚éB //PyObject *errtyp, *errval, *tb; //PyErr_Fetch(&errtyp, &errval, &tb); //MGlobal::displayInfo( // MString("errtyp=") + (errtyp ? "1" : "0") // + ", errval=" + (errval ? "1" : "0") // + ", tb=" + (tb ? "1" : "0") //); //PyErr_Restore(errtyp, errval, tb); // sys.stderr ‚ð StringIO ‚Å’D‚¤B PyObject* stream = NULL; if (_sys_stderr && _type_StringIO) { stream = PyObject_CallObject(_type_StringIO, NULL); if (stream) { PyDict_SetItemString(_sys_dict, "stderr", stream); } } // Œ»Ý‚̃Gƒ‰[î•ñ‚ð stderr ‚ɏ‘‚«o‚·B PyErr_Print(); // StringIO ‚Ì’†g‚ð–{“–‚Ì sys.stderr ‚ɏ‘‚«o‚µAsys.stderr ‚ðŒ³‚É–ß‚·B if (stream) { PyObject* str = PyObject_CallMethod(stream, "getvalue", NULL); if (str) { if (PYBYTES_SIZE(str)) { MGlobal::displayError(PYBYTES_asChar(str)); } Py_DECREF(str); } PyDict_SetItemString(_sys_dict, "stderr", _sys_stderr); PyObject_CallMethod(stream, "close", NULL); Py_DECREF(stream); } } //------------------------------------------------------------------------------ #else void Exprespy::_printPythonError() { // py3 ‚ł́Atraceback ƒIƒuƒWƒFƒNƒg‚̓Rƒ“ƒpƒCƒ‹ƒGƒ‰[‚Å‚àƒ‰ƒ“ƒ^ƒCƒ€ƒGƒ‰[‚Å‚à“¾‚ç‚ê‚È‚¢B // StringIO ‚𐶐¬‚µ‚悤‚Æ‚·‚邯 SystemError: <class '_io.StringIO'> returned a result with an error set ‚ƂȂéB // traceback.format_exc() ‚Å‚àƒGƒ‰[ƒeƒLƒXƒg‚𓾂ç‚ê‚È‚¢B // ‚Ç‚¤‚µ‚Ă悢‚©•ª‚©‚ç‚È‚¢‚̂ŠPyErr_Print ‚𒼐ڌĂԂ݂̂ƂµA‚»‚ÌŒã‚Ì displayError ‚ŐԂ­‚·‚éB PyErr_Print(); MGlobal::displayError("An error has occured."); #if 0 #if 0 PyObject *errtyp, *errval, *tb; PyErr_Fetch(&errtyp, &errval, &tb); MGlobal::displayInfo( MString("errtyp=") + (errtyp ? "1" : "0") + ", errval=" + (errval ? "1" : "0") + ", tb=" + (tb ? "1" : "0") ); if (! tb) { PyErr_Restore(errtyp, errval, tb); PyErr_Print(); return; } #endif MGlobal::displayInfo("import traceback"); PyObject* mod_traceback = PyImport_ImportModule("traceback"); if (mod_traceback) { #if 0 MGlobal::displayInfo("get format_tb"); PyObject* format_tb = PyDict_GetItemString(PyModule_GetDict(mod_traceback), "format_tb"); // borrow MGlobal::displayInfo(MString("format_tb=") + (format_tb ? "1" : "0")); PyObject* str = PyObject_CallFunction(format_tb, "(O)", tb); #else MGlobal::displayInfo("get format_exc"); PyObject* format_exc = PyDict_GetItemString(PyModule_GetDict(mod_traceback), "format_exc"); // borrow MGlobal::displayInfo(MString("format_exc=") + (format_exc ? "1" : "0")); PyObject* str = PyObject_CallObject(format_exc, NULL); #endif MGlobal::displayInfo(MString("str=") + (str ? "1" : "0")); if (str) { MGlobal::displayInfo("asUTF8"); PyObject* bs = PyUnicode_AsUTF8String(str); MString mstr; mstr.setUTF8(PYBYTES_asChar(bs)); MGlobal::displayError(mstr); Py_DECREF(bs); Py_DECREF(str); } Py_DECREF(mod_traceback); } //Py_DECREF(errtyp); //Py_DECREF(errval); //Py_DECREF(tb); #endif } #endif //------------------------------------------------------------------------------ /// _input dict ‚ɃXƒJƒ‰[”’l‚ðƒZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputScalar(int key, const double& val) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { // “ü—Í‚©‚çŒ^”»•ʏo—ˆ‚È‚¢‚½‚߁A‚¹‚߂Đ®”‚ÆŽÀ”‚ð”»•Ê‚·‚éB int i = static_cast<int>(val); if (static_cast<double>(i) == val) { _setIODictStealValue(_input, keyo, PYINT_fromLong(i)); } else { _setIODictStealValue(_input, keyo, PyFloat_FromDouble(val)); } } } //------------------------------------------------------------------------------ /// _input dict ‚É•¶Žš—ñ‚ðƒZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputString(int key, const MString& str) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { _setIODictStealValue(_input, keyo, PyUnicode_FromString(str.asUTF8())); } } //------------------------------------------------------------------------------ /// _input dict ‚É—v‘f‚ª 2`4 ŒÂ‚Ì’l‚ð list ‚É‚µ‚ăZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputShort2(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { short x, y; MFnNumericData(data).getData(x, y); _setIODictStealValue(_input, keyo, Py_BuildValue("[hh]", x, y)); } } void Exprespy::_setInputShort3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { short x, y, z; MFnNumericData(data).getData(x, y, z); _setIODictStealValue(_input, keyo, Py_BuildValue("[hhh]", x, y, z)); } } void Exprespy::_setInputLong2(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { int x, y; MFnNumericData(data).getData(x, y); _setIODictStealValue(_input, keyo, Py_BuildValue("[ii]", x, y)); } } void Exprespy::_setInputLong3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { int x, y, z; MFnNumericData(data).getData(x, y, z); _setIODictStealValue(_input, keyo, Py_BuildValue("[iii]", x, y, z)); } } void Exprespy::_setInputFloat2(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { float x, y; MFnNumericData(data).getData(x, y); _setIODictStealValue(_input, keyo, Py_BuildValue("[ff]", x, y)); } } void Exprespy::_setInputFloat3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { float x, y, z; MFnNumericData(data).getData(x, y, z); _setIODictStealValue(_input, keyo, Py_BuildValue("[fff]", x, y, z)); } } void Exprespy::_setInputDouble2(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { double x, y; MFnNumericData(data).getData(x, y); _setIODictStealValue(_input, keyo, Py_BuildValue("[dd]", x, y)); } } void Exprespy::_setInputDouble3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { double x, y, z; MFnNumericData(data).getData(x, y, z); _setIODictStealValue(_input, keyo, Py_BuildValue("[ddd]", x, y, z)); } } void Exprespy::_setInputDouble4(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { double x, y, z, w; MFnNumericData(data).getData(x, y, z, w); _setIODictStealValue(_input, keyo, Py_BuildValue("[dddd]", x, y, z, w)); } } //------------------------------------------------------------------------------ /// _input dict ‚É double3 ‚ð MVector ‚© list ‚É‚µ‚ăZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputVector3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { double x, y, z; MFnNumericData(data).getData(x, y, z); if (_type2_MVector) { _setIODictStealValue(_input, keyo, PyObject_CallFunction(_type2_MVector, "(ddd)", x, y, z)); } else { _setIODictStealValue(_input, keyo, Py_BuildValue("[ddd]", x, y, z)); } } } //------------------------------------------------------------------------------ /// _input dict ‚É matrix ‚ð MMatrix ‚© list ‚É‚µ‚ăZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputMatrix(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { MMatrix m = MFnMatrixData(data).matrix(); if (_type2_MMatrix) { _setIODictStealValue(_input, keyo, PyObject_CallFunction(_type2_MMatrix, "(N)", Py_BuildValue( "(dddddddddddddddd)", m.matrix[0][0], m.matrix[0][1], m.matrix[0][2], m.matrix[0][3], m.matrix[1][0], m.matrix[1][1], m.matrix[1][2], m.matrix[1][3], m.matrix[2][0], m.matrix[2][1], m.matrix[2][2], m.matrix[2][3], m.matrix[3][0], m.matrix[3][1], m.matrix[3][2], m.matrix[3][3] ))); } else { _setIODictStealValue(_input, keyo, Py_BuildValue( "[dddddddddddddddd]", m.matrix[0][0], m.matrix[0][1], m.matrix[0][2], m.matrix[0][3], m.matrix[1][0], m.matrix[1][1], m.matrix[1][2], m.matrix[1][3], m.matrix[2][0], m.matrix[2][1], m.matrix[2][2], m.matrix[2][3], m.matrix[3][0], m.matrix[3][1], m.matrix[3][2], m.matrix[3][3] )); } } } //------------------------------------------------------------------------------ /// _input dict ‚É Python API 2 MObject ƒf[ƒ^‚ðƒZƒbƒg‚·‚éB /// MObjet ‚ð C++ ‚©‚ç Python ‚ɕϊ·‚·‚éŽè’i‚ª–³‚¢‚̂ŁA•s–{ˆÓ‚È‚ª‚ç MPlug ‚ð—˜—pB //------------------------------------------------------------------------------ void Exprespy::_setInputMObject2(int key) { _preparePyPlug2(); if (! _mplug2_input) return; PyObject* keyo = PYINT_fromLong(key); if (! keyo) return; PyObject* mplug = PyObject_CallMethod(_mplug2_input, "elementByLogicalIndex", "(O)", keyo); if (mplug) { _setIODictStealValue(_input, keyo, PyObject_CallMethod(mplug, "asMObject", NULL)); Py_DECREF(mplug); } else { Py_DECREF(keyo); } } //------------------------------------------------------------------------------ /// _output dict ‚©‚瓾‚½ Python API 2 MObject ƒf[ƒ^‚ðo—̓vƒ‰ƒO‚ɃZƒbƒg‚·‚éB /// MObjet ‚ð Python ‚©‚ç C++ ‚ɕϊ·‚·‚éŽè’i‚ª–³‚¢‚̂ŁA•s–{ˆÓ‚È‚ª‚ç MPlug ‚ð—˜—pB //------------------------------------------------------------------------------ void Exprespy::_setOutputMObject2(int key, PyObject* valo) { _preparePyPlug2(); if (! _mplug2_output) return; PyObject* mplug = PyObject_CallMethod(_mplug2_output, "elementByLogicalIndex", "(i)", key); if (mplug) { PyObject_CallMethod(mplug, "setMObject", "(O)", valo); Py_DECREF(mplug); } } //------------------------------------------------------------------------------ /// MObject ƒf[ƒ^“üo—͂̂½‚ß‚Ì Python API 2 MPlug ‚ðŽæ“¾‚µ‚Ä‚¨‚­B //------------------------------------------------------------------------------ void Exprespy::_preparePyPlug2() { if (_mplug2_input || ! _api2_dict) return; PyObject* pysel = PyObject_CallObject(PyDict_GetItemString(_api2_dict, "MSelectionList"), NULL); if (! pysel) return; MString nodename = MFnDependencyNode(thisMObject()).name(); PyObject_CallMethod(pysel, "add", "(s)", nodename.asChar()); PyObject* pynode = PyObject_CallMethod(pysel, "getDependNode", "(i)", 0); Py_DECREF(pysel); if (! pynode) return; PyObject* pyfn = PyObject_CallFunction(PyDict_GetItemString(_api2_dict, "MFnDependencyNode"), "(O)", pynode); Py_DECREF(pynode); if (! pyfn) return; PyObject* findPlug = PyObject_GetAttrString(pyfn, "findPlug"); // DECREF •s—vB _mplug2_input = PyObject_CallFunction(findPlug, "(sO)", "i", Py_False); _mplug2_output = PyObject_CallFunction(findPlug, "(sO)", "o", Py_False); Py_DECREF(pyfn); } //------------------------------------------------------------------------------ /// _input dict ‚É Python API 1 MObject ƒf[ƒ^‚ðƒZƒbƒg‚·‚éB /// MObjet ‚ð C++ ‚©‚ç Python ‚ɕϊ·‚·‚éŽè’i‚ª–³‚¢‚̂ŁA•s–{ˆÓ‚È‚ª‚ç MPlug ‚ð—˜—pB //------------------------------------------------------------------------------ void Exprespy::_setInputMObject1(int key) { _preparePyPlug1(); if (! _mplug1_input) return; PyObject* keyo = PYINT_fromLong(key); if (! keyo) return; PyObject* mplug = PyObject_CallMethod(_mplug1_input, "elementByLogicalIndex", "(O)", keyo); if (! mplug) { Py_DECREF(keyo); return; } PyObject* valo = PyObject_CallMethod(mplug, "asMObject", NULL); Py_DECREF(mplug); _setIODictStealValue(_input, keyo, valo); } //------------------------------------------------------------------------------ /// _output dict ‚©‚瓾‚½ Python API 1 MObject ƒf[ƒ^‚ðo—̓vƒ‰ƒO‚ɃZƒbƒg‚·‚éB /// MObjet ‚ð Python ‚©‚ç C++ ‚ɕϊ·‚·‚éŽè’i‚ª–³‚¢‚̂ŁA•s–{ˆÓ‚È‚ª‚ç MPlug ‚ð—˜—pB //------------------------------------------------------------------------------ void Exprespy::_setOutputMObject1(int key, PyObject* valo) { _preparePyPlug1(); if (! _mplug1_output) return; PyObject* mplug = PyObject_CallMethod(_mplug1_output, "elementByLogicalIndex", "(i)", key); if (mplug) { PyObject_CallMethod(mplug, "setMObject", "(O)", valo); Py_DECREF(mplug); } } //------------------------------------------------------------------------------ /// MObject ƒf[ƒ^“üo—͂̂½‚ß‚Ì Python API 1 MPlug ‚ðŽæ“¾‚µ‚Ä‚¨‚­B //------------------------------------------------------------------------------ void Exprespy::_preparePyPlug1() { if (_mplug1_input || ! _api1_dict) return; PyObject* pysel = PyObject_CallObject(PyDict_GetItemString(_api1_dict, "MSelectionList"), NULL); if (! pysel) return; MString nodename = MFnDependencyNode(thisMObject()).name(); PyObject_CallMethod(pysel, "add", "(s)", nodename.asChar()); PyObject* pynode = PyObject_CallObject(_type1_MObject, NULL); if (! pynode) return; PyObject_CallMethod(pysel, "getDependNode", "(iO)", 0, pynode); Py_DECREF(pysel); if (PyObject_CallMethod(pynode, "isNull", NULL) != Py_True) { PyObject* pyfn = PyObject_CallFunction(PyDict_GetItemString(_api1_dict, "MFnDependencyNode"), "(O)", pynode); PyObject* findPlug = PyObject_GetAttrString(pyfn, "findPlug"); // DECREF •s—vB if (findPlug) { _mplug1_input = PyObject_CallFunction(findPlug, "(sO)", "i", Py_False); _mplug1_output = PyObject_CallFunction(findPlug, "(sO)", "o", Py_False); if (PyObject_CallMethod(_mplug1_input, "isNull", NULL) == Py_True) Py_CLEAR(_mplug1_input); if (PyObject_CallMethod(_mplug1_output, "isNull", NULL) == Py_True) Py_CLEAR(_mplug1_output); } Py_DECREF(pyfn); } Py_DECREF(pynode); } //============================================================================= // ENTRY POINT FUNCTIONS //============================================================================= MStatus initializePlugin(MObject obj) { static const char* VERSION = "3.0.0.20210411"; static const char* VENDER = "Ryusuke Sasaki"; MFnPlugin plugin(obj, VENDER, VERSION, "Any"); MStatus stat = plugin.registerNode(Exprespy::name, Exprespy::id, Exprespy::creator, Exprespy::initialize); CHECK_MSTATUS_AND_RETURN_IT(stat); return MS::kSuccess; } MStatus uninitializePlugin(MObject obj) { MStatus stat = MFnPlugin(obj).deregisterNode(Exprespy::id); CHECK_MSTATUS_AND_RETURN_IT(stat); return MS::kSuccess; }
ryusas/maya_exprespy
srcs/exprespy.cpp
C++
mit
49,535
import logging logging.basicConfig(level=logging.DEBUG) import nengo import nengo_spinnaker import numpy as np def test_probe_ensemble_voltages(): with nengo.Network("Test Network") as network: # Create an Ensemble with 2 neurons that have known gain and bias. The # result is that we know how the membrane voltage should change over # time even with no external stimulus. ens = nengo.Ensemble(2, 1) ens.bias = [0.5, 1.0] ens.gain = [0.0, 0.0] # Add the voltage probe probe = nengo.Probe(ens.neurons, "voltage") # Compute the rise time to 95% max_t = -ens.neuron_type.tau_rc * np.log(0.05) # Run the simulation for this period of time sim = nengo_spinnaker.Simulator(network) with sim: sim.run(max_t) # Compute the ideal voltage curves c = 1.0 - np.exp(-sim.trange() / ens.neuron_type.tau_rc) ideal = np.dot(ens.bias[:, np.newaxis], c[np.newaxis, :]).T # Assert that the ideal curves match the retrieved curves well assert np.allclose(ideal, sim.data[probe], atol=1e-3) if __name__ == "__main__": test_probe_ensemble_voltages()
project-rig/nengo_spinnaker
regression-tests/test_voltage_probing.py
Python
mit
1,158
using System; namespace Proxy { class RealPhoto : IPhoto { private string fileName; public RealPhoto(string fileName) { this.fileName = fileName; LoadPhoto(fileName); } public void Display() { Console.WriteLine("Displaying " + fileName); } private void LoadPhoto(String fileName) { Console.WriteLine("Loading " + fileName); } } }
IvayloP/TelerikAcademy2016-2017
HQC/04.DesingPatterns/02.StructuralPatterns/Proxy/RealPhoto.cs
C#
mit
477
<div class="workplace"> <div class="row-fluid"> <div class="span12"> <?php $this->load->view('admin/includes/message'); ?> <div class="head clearfix"> <div class="isw-grid"></div> <h1>API Manager</h1> </div> <div class="block-fluid table-sorting clearfix"> <table cellpadding="0" cellspacing="0" width="100%" class="table" id="TableDeferLoading"> <thead> <tr> <th width="5%">ID</th> <th width="13%">Title</th> <th width="24%">Host</th> <th width="12%">Username</th> <th width="8%">Api Type</th> <th width="14%">Updated Date Time</th> <th width="14%">Created Date Time</th> <th width="10%">Options</th> </tr> </thead> </table> </div> <a href="<?php echo site_url('admin/apimanager/add') ?>"><button class="btn" type="button">Add an api</button></a> </div> </div> <div class="dr"><span></span></div> <div class="row-fluid"> <div class="span3"> <div class="head clearfix"> <div class="isw-brush"></div> <h1>Options Icons</h1> </div> <div class="block"> <ul class="the-icons clearfix"> <li><i class="isb-cloud"></i> Services List</li> <li><i class="isb-edit"></i> Edit Record</li> <li><i class="isb-delete"></i> Delete Record</li> </ul> </div> </div> </div> </div> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#TableDeferLoading').dataTable ({ 'bProcessing' : true, 'bServerSide' : true, 'bAutoWidth' : false, 'sPaginationType': 'full_numbers', 'sAjaxSource' : '<?php echo site_url('admin/apimanager/listener'); ?>', 'aoColumnDefs': [ { "bSortable": false, "aTargets": [ 7 ] } ], 'sDom' : 'T<"clear">lfrtip', //datatable export buttons 'oTableTools' : { //datatable export buttons "sSwfPath": "<?php echo $this->config->item('assets_url');?>js/plugins/dataTables/media/swf/copy_csv_xls_pdf.swf", "sRowSelect": "multi" }, 'aoColumns' : [ { 'bSearchable': false, 'bVisible' : true }, null, null, null, null, null, null, null ], 'fnServerData': function(sSource, aoData, fnCallback) { <?php if($this->config->item('csrf_protection') === TRUE){ ?> aoData.push({ name : '<?php echo $this->config->item('csrf_token_name'); ?>', value : $.cookie('<?php echo $this->config->item('csrf_cookie_name'); ?>') }); <?php } ?> $.ajax ({ 'dataType': 'json', 'type' : 'POST', 'url' : sSource, 'data' : aoData, 'success' : fnCallback }); } }); }); </script>
muhammad-shariq/exclusiveunlock
application/views/admin/apimanager/list.php
PHP
mit
3,622
<div class="nav_menu"> <div> <div class="top_menu" style="padding-left: 20px;"> <div class="container"><div class="row"><div class="col-md-12"> <div class="top_info"><span><i class="fa fa-phone-square"></i>+91 9829211106</span><span> <i class="fa fa-envelope-o"></i> <a href="mailto:info@vidhyarthidarpan.com" style="color: #ffffff;"> info@vidhyarthidarpan.com</a></span></div> <div class="right_top_menu"> <button type="button" class="top_m1 navbar-toggle" data-toggle="collapse" data-target=".top_menu2"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> </div></div></div> </div> <div class="logo_panel" style="padding-left: 20px;"> <div class="container"> <div class="row"> <div class="col-md-2 col-xs-4 logo1"> <div class="logo"><a href="http://www.vidhyarthidarpan.com/" title="Go to Vidhyarthi Darpan"><img src="http://www.vidhyarthidarpan.com/images/logo.png" class="img-responsive" alt="logo"></a></div> </div> <div class="col-md-8"> <div class="clearfix"></div> </div> </div> </div> </div> </div> <nav> <div class="nav toggle"> <a id="menu_toggle"><i class="fa fa-bars"></i></a> </div> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <img src="<?php /* echo profilepic($_SESSION['manage_session']['profilePhoto']); */ ?>" alt=""><?php echo $_SESSION['manage_session']['iName']; ?> <span class=" fa fa-angle-down"></span> </a> <ul class="dropdown-menu dropdown-usermenu pull-right"> <li><a href="<?php echo base_url('manage/user'); ?>"> Profile</a></li> <li> <a href="javascript:;"> <span class="badge bg-red pull-right">50%</span> <span>Settings</span> </a> </li> <li><a href="javascript:;">Help</a></li> <li><a href="<?php echo base_url('manage_logout'); ?>"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li> </ul> </li> <!-- <li role="presentation" class="dropdown"> <a href="javascript:;" class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false"> <i class="fa fa-envelope-o"></i> <span class="badge bg-green">6</span> </a> <ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu"> <li> <a> <span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <div class="text-center"> <a> <strong>See All Alerts</strong> <i class="fa fa-angle-right"></i> </a> </div> </li> </ul> </li>--> </ul> </nav> </div>
ajaykumarparashar11/VD
application/views/manage/layout/header.php
PHP
mit
6,983
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for CESA-2013:0831 # # Security announcement date: 2013-05-17 00:35:37 UTC # Script generation date: 2017-01-01 21:10:45 UTC # # Operating System: CentOS 6 # Architecture: x86_64 # # Vulnerable packages fix on version: # - libvirt-client.i686:0.10.2-18.el6_4.5 # - libvirt-devel.i686:0.10.2-18.el6_4.5 # - libvirt.x86_64:0.10.2-18.el6_4.5 # - libvirt-client.x86_64:0.10.2-18.el6_4.5 # - libvirt-devel.x86_64:0.10.2-18.el6_4.5 # - libvirt-lock-sanlock.x86_64:0.10.2-18.el6_4.5 # - libvirt-python.x86_64:0.10.2-18.el6_4.5 # # Last versions recommanded by security team: # - libvirt-client.i686:0.10.2-46.el6_6.2 # - libvirt-devel.i686:0.10.2-46.el6_6.2 # - libvirt.x86_64:0.10.2-46.el6_6.2 # - libvirt-client.x86_64:0.10.2-46.el6_6.2 # - libvirt-devel.x86_64:0.10.2-46.el6_6.2 # - libvirt-lock-sanlock.x86_64:0.10.2-46.el6_6.2 # - libvirt-python.x86_64:0.10.2-46.el6_6.2 # # CVE List: # - CVE-2013-1962 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo yum install libvirt-client.i686-0.10.2 -y sudo yum install libvirt-devel.i686-0.10.2 -y sudo yum install libvirt.x86_64-0.10.2 -y sudo yum install libvirt-client.x86_64-0.10.2 -y sudo yum install libvirt-devel.x86_64-0.10.2 -y sudo yum install libvirt-lock-sanlock.x86_64-0.10.2 -y sudo yum install libvirt-python.x86_64-0.10.2 -y
Cyberwatch/cbw-security-fixes
CentOS_6/x86_64/2013/CESA-2013:0831.sh
Shell
mit
1,462
'use strict'; var Lab = require('lab'), Hapi = require('hapi'), Plugin = require('../../../lib/plugins/sugendran'); var describe = Lab.experiment; var it = Lab.test; var expect = Lab.expect; var before = Lab.before; var after = Lab.after; describe('sugendran', function() { var server = new Hapi.Server(); it('Plugin successfully loads', function(done) { server.pack.register(Plugin, function(err) { expect(err).to.not.exist; done(); }); }); it('Plugin registers routes', function(done) { var table = server.table(); expect(table).to.have.length(1); expect(table[0].path).to.equal('/sugendran'); done(); }); it('Plugin route responses', function(done) { var table = server.table(); expect(table).to.have.length(1); expect(table[0].path).to.equal('/sugendran'); var request = { method: 'GET', url: '/sugendran' }; server.inject(request, function(res) { expect(res.statusCode).to.equal(200); expect(res.result).to.equal('don\'t worry, be hapi!'); done(); }); }); });
nvcexploder/hapi-lxjs
test/plugins/sugendran/index.js
JavaScript
mit
1,090
import app from 'flarum/forum/app'; import { extend } from 'flarum/common/extend'; import DiscussionControls from 'flarum/forum/utils/DiscussionControls'; import DiscussionPage from 'flarum/forum/components/DiscussionPage'; import Button from 'flarum/common/components/Button'; export default function addStickyControl() { extend(DiscussionControls, 'moderationControls', function (items, discussion) { if (discussion.canSticky()) { items.add( 'sticky', Button.component( { icon: 'fas fa-thumbtack', onclick: this.stickyAction.bind(discussion), }, app.translator.trans( discussion.isSticky() ? 'flarum-sticky.forum.discussion_controls.unsticky_button' : 'flarum-sticky.forum.discussion_controls.sticky_button' ) ) ); } }); DiscussionControls.stickyAction = function () { this.save({ isSticky: !this.isSticky() }).then(() => { if (app.current.matches(DiscussionPage)) { app.current.get('stream').update(); } m.redraw(); }); }; }
flarum/sticky
js/src/forum/addStickyControl.js
JavaScript
mit
1,121
from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier from skTMVA import convert_bdt_sklearn_tmva import cPickle import numpy as np from numpy.random import RandomState RNG = RandomState(21) # Construct an example dataset for binary classification n_vars = 2 n_events = 10000 signal = RNG.multivariate_normal( np.ones(n_vars), np.diag(np.ones(n_vars)), n_events) background = RNG.multivariate_normal( np.ones(n_vars) * -1, np.diag(np.ones(n_vars)), n_events) X = np.concatenate([signal, background]) y = np.ones(X.shape[0]) w = RNG.randint(1, 10, n_events * 2) y[signal.shape[0]:] *= -1 permute = RNG.permutation(y.shape[0]) X = X[permute] y = y[permute] # Use all dataset for training X_train, y_train, w_train = X, y, w # Declare BDT - we are going to use AdaBoost Decision Tree dt = DecisionTreeClassifier(max_depth=3, min_samples_leaf=int(0.05*len(X_train))) bdt = AdaBoostClassifier(dt, algorithm='SAMME', n_estimators=800, learning_rate=0.5) # Train BDT bdt.fit(X_train, y_train) # Save BDT to pickle file with open('bdt_sklearn_to_tmva_example.pkl', 'wb') as fid: cPickle.dump(bdt, fid) # Save BDT to TMVA xml file # Note: # - declare input variable names and their type # - variable order is important for TMVA convert_bdt_sklearn_tmva(bdt, [('var1', 'F'), ('var2', 'F')], 'bdt_sklearn_to_tmva_example.xml')
yuraic/koza4ok
examples/bdt_sklearn_to_tmva_AdaBoost.py
Python
mit
1,493
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2020_08_01 module Models # # Defines values for ProcessorArchitecture # module ProcessorArchitecture Amd64 = "Amd64" X86 = "X86" end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2020-08-01/generated/azure_mgmt_network/models/processor_architecture.rb
Ruby
mit
371
'use strict' import assert from 'assert' import { btoa } from 'Base64' import decode from 'jwt-decode' import token from './data/token' import tokenTimezone from './data/token-timezone' import ls from 'local-storage' import bluebird from 'bluebird' import sinon from 'sinon' const setTokenExp = (timestamp) => { // hacky adjustment of expiration of the token const decoded = decode(token) decoded.exp = timestamp / 1000 const [head, , sig] = token.split('.') return `${head}.${btoa(JSON.stringify(decoded))}.${sig}` } describe('Token Store', () => { const localStorageKey = 'coolKey' let updatedToken beforeEach(() => { // HACK around https://github.com/auth0/jwt-decode/issues/5 global.window = global // HACK around cookie monster returning undefined when document isn't there global.document = {} }) beforeEach(() => { updatedToken = setTokenExp(Date.now() + 1000) }) afterEach(() => { delete global.window delete global.document ls.remove(localStorageKey) }) it('should set user after no token is present', () => { const tokenStore = require('../src')() tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') }) tokenStore.init() tokenStore.setToken(token) }) it('should get the token out of local storage', () => { ls.set(localStorageKey, token) const tokenStore = require('../src')({localStorageKey}) tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') }) tokenStore.init() }) it('should catch an exception token is not present in local storage', () => { ls.set(localStorageKey, undefined) const tokenStore = require('../src')({localStorageKey}) tokenStore.on('Token received', assert.fail) tokenStore.init() }) it('if no token call refresh & set token', done => { const tokenStore = require('../src')({refresh: () => bluebird.resolve(updatedToken) }) tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') done() }) tokenStore.init() }) it('if token is expired, call refresh with expired token', done => { ls.set(localStorageKey, token) require('../src')({ localStorageKey, refresh: (t) => { assert.equal(t, token) done() return bluebird.resolve(updatedToken) } }).init() }) it('if token is expired, call refresh & set token', done => { ls.set(localStorageKey, token) const tokenStore = require('../src')({ localStorageKey, refresh: () => bluebird.resolve(updatedToken) }) let callCount = 0 tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') if (++callCount === 2) { done() } }) tokenStore.init() }) it('if token valid, leave as is', () => { ls.set(localStorageKey, setTokenExp(Date.now() + 100 * 60 * 1000)) const tokenStore = require('../src')({ localStorageKey, refresh: () => assert.fail('should not be called') }) tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') }) tokenStore.init() }) it('if token to expire soon, refresh after interval', done => { ls.set(localStorageKey, updatedToken) const tokenStore = require('../src')({ localStorageKey, refresh: () => bluebird.resolve(updatedToken), refreshInterval: 1000 }) let callCount = 0 tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') if (++callCount === 2) { done() } }) tokenStore.init() }) describe('with fake timers', () => { let clock beforeEach(() => { clock = sinon.useFakeTimers() }) afterEach(() => { clock.restore() }) it('doesn\'t refresh if still outside the expiry window', () => { ls.set(localStorageKey, updatedToken) const tokenStore = require('../src')({ localStorageKey, refresh: () => bluebird.resolve(updatedToken), expiryWindow: 1, refreshInterval: 10 }) const spy = sinon.spy() tokenStore.on('Token received', spy) tokenStore.init() clock.tick(11) assert.equal(spy.callCount, 1) }) }) it('refreshes the token and sets it', done => { ls.set(localStorageKey, setTokenExp(Date.now() + 100 * 60 * 1000)) const tokenStore = require('../src')({ localStorageKey, refresh: () => bluebird.resolve(tokenTimezone) }) let callCount = 0 tokenStore.on('Token received', (_, user) => { callCount++ if (callCount === 1) { assert(!user.timezone) } else if (callCount === 2) { assert.equal(user.timezone, 'UTC') done() } else { assert.fail('shouldn\'t be called more than twice') } }) tokenStore.init() tokenStore.refreshToken() }) describe('sad path', () => { it('should not blow up when cookie is not present', () => { let tokenStore assert.doesNotThrow(() => tokenStore = require('../src')()) assert.doesNotThrow(() => tokenStore.init()) }) it('should not blow up when cookie is invalid', () => { const token = 'g4rBaG3' require('cookie-monster').set('XSRF-TOKEN', token) let tokenStore assert.doesNotThrow(() => tokenStore = require('../src')()) assert.doesNotThrow(() => tokenStore.init()) }) }) describe('default cookie key', () => { let tokenFromStore let user beforeEach(() => { require('cookie-monster').set('XSRF-TOKEN', token) const tokenStore = require('../src')() tokenStore.on('Token received', (t, u) => { tokenFromStore = t user = u }) tokenStore.init() }) it('should get the XSRF-TOKEN and return it', () => { assert.equal(tokenFromStore, token) }) it('should return user', () => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') }) }) describe('override cookie key', () => { let tokenFromStore beforeEach(() => { require('cookie-monster').set('NOT-XSRF-TOKEN', token) const tokenStore = require('../src')({ cookie: 'NOT-XSRF-TOKEN' }) tokenStore.on('Token received', (t) => { tokenFromStore = t }) tokenStore.init() }) it('should get the NOT-XSRF-TOKEN and return it', () => { assert.equal(tokenFromStore, token) }) }) describe('terminate', () => { let cookieMonster beforeEach(() => { cookieMonster = require('cookie-monster') cookieMonster.set('XSRF-TOKEN', token) }) it('should set token to undefined on explicit termination', done => { let callCount = 0 const tokenStore = require('../src')({ refresh: (t) => { if (callCount === 0) { cookieMonster.set('XSRF-TOKEN', token, {expires: 'Thu, 01 Jan 1970 00:00:01 GMT'}) assert.equal(t, token) } if (callCount === 1) { assert.equal(t, undefined) } callCount++ return bluebird.resolve(t) } }) tokenStore.init() tokenStore.terminate() tokenStore.refreshToken() done() }) it('should not set token to undefined when no explicit termination', done => { let callCount = 0 const tokenStore = require('../src')({ refresh: (t) => { if (!t) { return bluebird.resolve() } if (callCount === 0) { cookieMonster.set('XSRF-TOKEN', token, {expires: 'Thu, 01 Jan 1970 00:00:01 GMT'}) assert.equal(t, token) } if (callCount === 1) { assert.equal(t, token) } callCount++ return bluebird.resolve(t) } }) tokenStore.init() tokenStore.refreshToken() done() }) }) })
lanetix/react-jwt-store
test/index.js
JavaScript
mit
8,273