code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.lab603.picencyclopedias; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.view.KeyEvent; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.lab603.picencyclopedias.MainActivity; import com.lab603.picencyclopedias.R; /** * Created by FutureApe on 2017/9/26. */ public class SplashActivity extends Activity { private final int SPLASH_DISPLAY_LENGTH = 3000; private Handler hander; private TextView textView; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // getWindow().requestFeature(Window.FEATURE_NO_TITLE); //透明状态栏 // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); Window window = getWindow(); //定义全屏参数 int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN; //设置当前窗体为全屏显示 window.setFlags(flag, flag); setContentView(R.layout.activity_splash); textView = (TextView)findViewById(R.id.textView2); textView.setText("<Picencyclopedias/>"); hander = new Handler(); //延迟SPLASH_DISPLAY_LENGTH时间然后跳转到MainActivity hander.postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashActivity.this,MainActivity.class); startActivity(intent); SplashActivity.this.finish(); } },SPLASH_DISPLAY_LENGTH); } /** * 禁用返回键 * @param keyCode * @param event * @return */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) return true; return super.onKeyDown(keyCode, event); } }
Lab603/PicEncyclopedias
app/src/main/java/com/lab603/picencyclopedias/SplashActivity.java
Java
mit
2,001
/* Resource.cpp Resource base class (c)2005 Palestar, Richard Lyle */ #define RESOURCE_DLL #include "Resource/Resource.h" #include "Factory/FactoryTypes.h" //------------------------------------------------------------------------------- IMPLEMENT_RESOURCE_FACTORY( Resource, Widget ); Resource::Resource() {} //------------------------------------------------------------------------------- // EOF
palestar/medusa
Resource/Resource.cpp
C++
mit
408
$.widget( "alexandra.panelSlider", { options: { currentView: null, // The panel currently in focus panels:[] // All panels added to the navigation system }, //The constructor of the panelSLide widget _create: function() { var tempThis=this; this.element.addClass("panelSlider"); this.options.currentView=this.options.panels[0]; $.each(this.options.panels, function(i, val){ $("#"+val).hide(); tempThis._checkLinks(val); }); $("#"+this.options.currentView).show(); }, _checkLinks: function(val){ var tempThis=this; $("#"+val+" a").click(function (event) { event.preventDefault(); event.stopPropagation(); var url = $(this).attr('href'); var urlRegex = '/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/'; var res = url.match(urlRegex); if(res==null){ var newView=$.inArray(url,tempThis.options.panels); if(newView>-1){ var curView=$.inArray(tempThis.options.currentView,tempThis.options.panels); console.log("new: "+newView+", current: "+curView); if(newView>curView) tempThis.slide(url,false); else if(newView<curView) tempThis.slide(url,true); return; } } window.location = url; }); }, //It's possible to add a panel in runtime addPanel: function(panel) { this.options.panels.push(panel); $("#"+panel).hide(); this._checkLinks(panel); }, //A panel can be removed runtime removePanel: function(panel){ for(var i=0;i<this.options.panels.length;i++){ if(this.options.panels[i]==panel){ if(panel==this.options.currentView){ $("#"+panel).hide(); this.options.currentView= i-1<0 ? this.options.panels[1] : this.options.panels[i-1]; $("#"+this.options.currentView).show(); } this.options.panels.splice(i, 1); break; } } }, //The function that actually does all the sliding //If the goingBack variable is true the sliding will happen from left to right, and vice versa slide: function(panelToShow, goingBack){ /* Making sure that only registered objects can act as panels. Might be a little to rough to make such a hard return statement. */ if($.inArray(panelToShow,this.options.panels)<0) return "Not a registered panel"; var tempThis=this; var tempCurrentView=this.options.currentView; /* Temporary absolute positioned div for doing sliding of dfferent panels on same line. This is the wrapper for the panel to slide off the screen */ var currentPanel=$("<div/>",{ css:{ "position":"absolute", "top":0, "left":0, "width":"100%" } }); //Needed for keeping padding and margin while transition happens var innerWrapper=$("<div/>"); this.element.append(currentPanel); currentPanel.append(innerWrapper); innerWrapper.append($("#"+this.options.currentView)); innerWrapper.hide("slide",{direction: goingBack ? "right" : "left"}, function(){ $("#"+tempCurrentView).hide(); tempThis.element.append($("#"+tempCurrentView)); currentPanel.remove(); }); /* Temporary absolute positioned div for doing sliding of dfferent panels on same line. This is the wrapper for the panel to slide onto the screen */ var newPanel=$("<div/>",{ css:{ "position":"absolute", "top":0, "left":0, "width":"100%" } }); //Needed for keeping padding and margin while transition happens var innerWrapper2=$("<div/>"); innerWrapper2.hide(); this.element.append(newPanel); newPanel.append(innerWrapper2); innerWrapper2.append($("#"+panelToShow)); $("#"+panelToShow).show(); innerWrapper2.show("slide",{direction: goingBack ? "left" : "right"},function(){ tempThis.element.append($("#"+panelToShow)); newPanel.remove(); }); this.options.currentView=panelToShow; } });
alexandrainst/jQuery_panelSlider
panelSlider.js
JavaScript
mit
4,880
import numpy as np from astropy.coordinates import EarthLocation, SkyCoord __all__ = ['MWA_LOC', 'MWA_FIELD_EOR0', 'MWA_FIELD_EOR1', 'MWA_FIELD_EOR2', 'MWA_FREQ_EOR_ALL_40KHZ', 'MWA_FREQ_EOR_ALL_80KHZ', 'MWA_FREQ_EOR_HI_40KHZ', 'MWA_FREQ_EOR_HI_80KHZ', 'MWA_FREQ_EOR_LOW_40KHZ', 'MWA_FREQ_EOR_LOW_80KHZ', 'HERA_ANT_DICT', 'F21'] F21 = 1420.405751786e6 MWA_LOC = EarthLocation(lat='−26d42m11.94986s', lon='116d40m14.93485s', height=377.827) MWA_FIELD_EOR0 = SkyCoord(ra='0.0h', dec='-30.0d') MWA_FIELD_EOR1 = SkyCoord(ra='4.0h', dec='-30.0d') MWA_FIELD_EOR2 = SkyCoord(ra='10.33h', dec='-10.0d') MWA_FREQ_EOR_LOW_40KHZ = np.arange(138.895, 167.055, 0.04) MWA_FREQ_EOR_HI_40KHZ = np.arange(167.055, 195.255, 0.04) MWA_FREQ_EOR_ALL_40KHZ = np.arange(138.895, 195.255, 0.04) MWA_FREQ_EOR_LOW_80KHZ = np.arange(138.915, 167.075, 0.08) MWA_FREQ_EOR_HI_80KHZ = np.arange(167.075, 195.275, 0.08) MWA_FREQ_EOR_ALL_80KHZ = np.arange(138.915, 195.275, 0.08) HERA_ANT_DICT = {'hera19': 3, 'hera37': 4, 'hera61': 5, 'hera91': 6, 'hera127': 7, 'hera169': 8, 'hera217': 9, 'hera271': 10, 'hera331': 11}
piyanatk/sim
opstats/utils/settings.py
Python
mit
1,196
/********************************************************************************* * (Remove duplicates) Write a method that removes the duplicate elements from * * an array list of integers using the following header: * * * * public static void removeDuplicate(ArrayList<Integer> list) * * * * Write a test program that prompts the user to enter 10 integers to a list and * * displays the distinct integers separated by exactly one space. * *********************************************************************************/ import java.util.Scanner; import java.util.ArrayList; public class Exercise_11_13 { /** Main method */ public static void main(String[] args) { // Create a scanner Scanner input = new Scanner(System.in); // Create an ArrayList ArrayList<Integer> list = new ArrayList<Integer>(); // Prompt ther user to enter 10 integers System.out.print("Enter 10 integers: "); for (int i = 0; i < 10; i++) { list.add(input.nextInt()); } // Invoke removeDuplicate method removeDuplicate(list); // Display the distinct integers System.out.print("The distinct integers are "); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + " "); } System.out.println(); } /** Removes the duplicate elements from an array list of integers */ public static void removeDuplicate(ArrayList<Integer> list) { for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i) == list.get(j)) list.remove(j); } } } }
jsquared21/Intro-to-Java-Programming
Exercise_11/Exercise_11_13/Exercise_11_13.java
Java
mit
1,749
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); //i will add uuid $table->string('names'); $table->string('email')->nullable(); $table->string('phone'); $table->string('idnumber')->nullable(); $table->string('password'); $table->boolean('active')->default(0); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
mucyomiller/goohs
database/migrations/2016_10_12_000000_create_users_table.php
PHP
mit
899
(function() { 'use strict'; function movieDetail(movieDetailService) { return { restrict: 'EA', replace: true, templateUrl: './src/app/movieDetail/template.html', scope: {}, controllerAs: 'vm', bindToController: true, /*jshint unused:false*/ controller: function($log, $stateParams) { var vm = this; movieDetailService.getMovie().then(function(response){ vm.movie = response.data; vm.movie.vote = (vm.movie.vote_average*10); vm.movie.genres_name = []; vm.movie.production_companies_name = []; vm.movie.production_countries_name = []; for (var i = 0; i <= vm.movie.genres.length-1; i++) { vm.movie.genres_name.push(vm.movie.genres[i].name); vm.movie.genres_name.sort(); } for (var i = 0; i <= vm.movie.production_companies.length-1; i++) { vm.movie.production_companies_name.push(vm.movie.production_companies[i].name); vm.movie.production_companies_name.sort(); } for (var i = 0; i <= vm.movie.production_countries.length-1; i++) { vm.movie.production_countries_name.push(vm.movie.production_countries[i].name); vm.movie.production_countries_name.sort(); } }); }, link: function(scope, elm, attrs) { } }; } angular.module('movieDetailDirective', ['services.movieDetail']) .directive('movieDetail', movieDetail); })();
gonzalesm/AngularProject
client/src/app/movieDetail/directive.js
JavaScript
mit
1,513
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("Forum.Data.Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Forum.Data.Common")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("d166223e-04a3-4728-b893-0f29e22fc161")] // 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")]
zachdimitrov/Learning_2017
Databases/EntityFramework/RepositoryTest/Forum.Data.Common/Properties/AssemblyInfo.cs
C#
mit
1,410
/* * The MIT License * * Copyright (c) 2015, SmartBear Software * * 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. */ package com.smartbear.jenkins.plugins.testcomplete; import hudson.model.Action; import hudson.model.Api; import hudson.model.Run; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.io.File; import java.util.*; /** * @author Igor Filin */ @ExportedBean public class TcSummaryAction implements Action { private final Run<?, ?> build; private LinkedHashMap<String, TcReportAction> reports = new LinkedHashMap<>(); private ArrayList<TcReportAction> reportsOrder = new ArrayList<>(); private final TcDynamicReportAction dynamic; TcSummaryAction(Run<?, ?> build) { this.build = build; String buildDir = build.getRootDir().getAbsolutePath(); String reportsPath = buildDir + File.separator + Constants.REPORTS_DIRECTORY_NAME + File.separator; dynamic = new TcDynamicReportAction(reportsPath); } public String getIconFileName() { return "/plugin/" + Constants.PLUGIN_NAME + "/images/tc-48x48.png"; } public String getDisplayName() { return Messages.TcSummaryAction_DisplayName(); } public String getUrlName() { return Constants.PLUGIN_NAME; } public Run<?, ?> getBuild() { return build; } public void addReport(TcReportAction report) { if (!reports.containsValue(report)) { report.setParent(this); reports.put(report.getId(), report); reportsOrder.add(report); } } @Exported(name="reports", inline = true) public ArrayList<TcReportAction> getReportsOrder() { return reportsOrder; } public HashMap<String, TcReportAction> getReports() { return reports; } @SuppressWarnings("unused") public TcReportAction getNextReport(TcReportAction report) { if (report == null || !reportsOrder.contains(report)) { return null; } int index = reportsOrder.indexOf(report); if (index + 1 >= reportsOrder.size()) { return null; } return reportsOrder.get(index + 1); } @SuppressWarnings("unused") public TcReportAction getPreviousReport(TcReportAction report) { if (report == null || !reportsOrder.contains(report)) { return null; } int index = reportsOrder.indexOf(report); if (index <= 0) { return null; } return reportsOrder.get(index - 1); } public TcDynamicReportAction getDynamic() { return dynamic; } public String getPluginName() { return Constants.PLUGIN_NAME; } public Api getApi() { return new Api(this); } }
jenkinsci/testcomplete-plugin
src/main/java/com/smartbear/jenkins/plugins/testcomplete/TcSummaryAction.java
Java
mit
3,844
/* See license.txt for terms of usage */ require.def("domplate/toolTip", [ "domplate/domplate", "core/lib", "core/trace" ], function(Domplate, Lib, Trace) { with (Domplate) { // ************************************************************************************************ // Globals var mouseEvents = "mousemove mouseover mousedown click mouseout"; var currentToolTip = null; // ************************************************************************************************ // Tooltip function ToolTip() { this.element = null; } ToolTip.prototype = domplate( { tag: DIV({"class": "toolTip"}, DIV() ), show: function(target, options) { if (currentToolTip) currentToolTip.hide(); this.target = target; this.addListeners(); // Render the tooltip. var body = Lib.getBody(document); this.element = this.tag.append({options: options}, body, this); // Compute coordinates and show. var box = Lib.getElementBox(this.target); this.element.style.top = box.top + box.height + "px"; this.element.style.left = box.left + box.width + "px"; this.element.style.display = "block"; currentToolTip = this; return this.element; }, hide: function() { if (!this.element) return; this.removeListeners(); // Remove UI this.element.parentNode.removeChild(this.element); currentToolTip = this.element = null; }, addListeners: function() { this.onMouseEvent = Lib.bind(this.onMouseEvent, this); // Register listeners for all mouse events. $(document).bind(mouseEvents, this.onMouseEvent, true); }, removeListeners: function() { // Remove listeners for mouse events. $(document).unbind(mouseEvents, this.onMouseEvent, this, true); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Listeners onMouseEvent: function(event) { var e = Lib.fixEvent(event); // If the mouse is hovering within the tooltip pass the event further to it. var ancestor = Lib.getAncestorByClass(e.target, "toolTip"); if (ancestor) return; var x = event.clientX, y = event.clientY; var box = Lib.getElementBox(this.element); if (event.type != "click" && event.type != "mousedown") box = Lib.inflateRect(box, 10, 10); // If the mouse is hovering within near neighbourhood, ignore it. if (Lib.pointInRect(box, x, y)) { Lib.cancelEvent(e); return; } // If the mouse is hovering over the target, ignore it too. if (Lib.isAncestor(e.target, this.target)) { Lib.cancelEvent(e); return; } // The mouse is hovering far away, let's destroy the the tooltip. this.hide(); Lib.cancelEvent(e); } }); // ************************************************************************************************ return ToolTip; // **********************************************************************************************// }});
modjs/mod-pageload-reporter
harviewer/scripts/domplate/toolTip.js
JavaScript
mit
3,280
package synapticloop.linode.api.response; /* * Copyright (c) 2016-2017 Synapticloop. * * All rights reserved. * * This code may contain contributions from other parties which, where * applicable, will be listed in the default build file for the project * ~and/or~ in a file named CONTRIBUTORS.txt in the root of the project. * * This source code and any derived binaries are covered by the terms and * conditions of the Licence agreement ("the Licence"). You may not use this * source code or any derived binaries except in compliance with the Licence. * A copy of the Licence is available in the file named LICENSE.txt shipped with * this source code or binaries. */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import synapticloop.linode.api.helper.ResponseHelper; import synapticloop.linode.api.response.bean.Datacenter; public class AvailDatacentersResponse extends BaseResponse { private static final Logger LOGGER = LoggerFactory.getLogger(AvailDatacentersResponse.class); private List<Datacenter> datacenters = new ArrayList<Datacenter>(); private Map<Long, Datacenter> datacenterIdLookup = new HashMap<Long, Datacenter>(); private Map<String, Datacenter> datacenterAbbreviationLookup = new HashMap<String, Datacenter>(); /** * * The json should have been formed by the following: * * <pre> * { * "ERRORARRAY":[], * "ACTION":"avail.datacenters", * "DATA":[ * { * "DATACENTERID":2, * "LOCATION":"Dallas, TX, USA", * "ABBR":"dallas" * }, * { * "DATACENTERID":3, * "LOCATION":"Fremont, CA, USA", * "ABBR":"fremont" * }, * { * "DATACENTERID":4, * "LOCATION":"Atlanta, GA, USA", * "ABBR":"atlanta" * }, * { * "DATACENTERID":6, * "LOCATION":"Newark, NJ, USA", * "ABBR":"newark" * }, * { * "DATACENTERID":7, * "LOCATION":"London, England, UK", * "ABBR":"london" * }, * { * "DATACENTERID":8, * "LOCATION":"Tokyo, JP", * "ABBR":"tokyo" * }, * { * "DATACENTERID":9, * "LOCATION":"Singapore, SG", * "ABBR":"singapore" * }, * { * "DATACENTERID":10, * "LOCATION":"Frankfurt, DE", * "ABBR":"frankfurt" * } * ] * } * </pre> * * @param jsonObject the json object to parse */ public AvailDatacentersResponse(JSONObject jsonObject) { super(jsonObject); if(!hasErrors()) { JSONArray dataArray = jsonObject.getJSONArray(JSON_KEY_DATA); for (Object datacentreObject : dataArray) { Datacenter datacenter = new Datacenter((JSONObject)datacentreObject); datacenters.add(datacenter); datacenterIdLookup.put(datacenter.getDatacenterId(), datacenter); datacenterAbbreviationLookup.put(datacenter.getAbbreviation(), datacenter); } } jsonObject.remove(JSON_KEY_DATA); ResponseHelper.warnOnMissedKeys(LOGGER, jsonObject); } public List<Datacenter> getDatacenters() { return(datacenters); } public Datacenter getDatacenterById(Long id) { return(datacenterIdLookup.get(id)); } public Datacenter getDatacenterByAbbreviation(String abbreviation) { return(datacenterAbbreviationLookup.get(abbreviation)); } }
synapticloop/linode-api
src/main/java/synapticloop/linode/api/response/AvailDatacentersResponse.java
Java
mit
3,584
package com.nikitakozlov.pury_example.profilers; public final class StartApp { public static final String PROFILER_NAME = "App Start"; public static final String TOP_STAGE ="App Start"; public static final int TOP_STAGE_ORDER = 0; public static final String SPLASH_SCREEN = "Splash Screen"; public static final int SPLASH_SCREEN_ORDER = TOP_STAGE_ORDER + 1; public static final String SPLASH_LOAD_DATA = "Splash Load Data"; public static final int SPLASH_LOAD_DATA_ORDER = SPLASH_SCREEN_ORDER + 1; public static final String MAIN_ACTIVITY_LAUNCH = "Main Activity Launch"; public static final int MAIN_ACTIVITY_LAUNCH_ORDER = SPLASH_SCREEN_ORDER + 1; public static final String MAIN_ACTIVITY_CREATE = "onCreate()"; public static final int MAIN_ACTIVITY_CREATE_ORDER = MAIN_ACTIVITY_LAUNCH_ORDER + 1; public static final String MAIN_ACTIVITY_START = "onStart()"; public static final int MAIN_ACTIVITY_START_ORDER = MAIN_ACTIVITY_LAUNCH_ORDER + 1; }
NikitaKozlov/Pury
example/src/main/java/com/nikitakozlov/pury_example/profilers/StartApp.java
Java
mit
1,006
import robot from 'robotjs' import sleep from 'sleep' import orifice from './fc8_orifice_map.json' var fs = require('fs') /*//set speed robot.setKeyboardDelay(150) robot.setMouseDelay(100)*/ let type = [ "Orifice", "Venturi", "Nozzle", "Fixed Geometry", "V-Cone", "Segmental Meters", "Linear Meters" ] exports.startFC8 = function(){ robot.keyTap('command') robot.typeString('FC8') sleep.msleep(500) robot.keyTap('enter') sleep.msleep(500) } exports.selectType = function(request){ robot.keyTap('tab') let i = 0 for(i=0; i<type.indexOf(request); i++){ robot.keyTap('down') } robot.keyTap('tab') robot.keyTap('enter') } exports.autoCompileGas = function(){ let i = 0 for(i=0; i<9; i++){ robot.keyTap('tab') } robot.keyTap('enter') for(i=0; i<7; i++){ robot.keyTap('tab') } robot.keyTap('enter') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('enter') } exports.calculation = function(object) { //select dp flow size let i = 0 if(object.method == "dp"){ robot.keyTap('enter') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.percMaxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.maxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.dp.normalFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.borePrimaryElement) robot.keyTap('tab') robot.keyTap('enter') } else if (object.method == "flow"){ robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.flow.differentialPressure) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.borePrimaryElement) robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') } else if (object.method == "size"){ robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('tab') /*for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.percMaxFlow)*/ robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.maxFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.normalFlow) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.size.differential) robot.keyTap('tab') for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(object.base.pipeDiameter) robot.keyTap('tab') robot.keyTap('tab') robot.keyTap('enter') } if(object.checkVentDrainHole!="off"){ /* robot.keyTap('tab') robot.keyTap('tab') let ind = orifice.FlangeTaps.VentDrainHole.indexOf(object.ventDrainHole) let indStd = orifice.FlangeTaps.VentDrainHole.indexOf('No Vent/Drain Hole') if(ind<indStd){ for (i=0; i<indStd-ind; i++){ robot.keyTap('up') } } else { for (i=0; i<ind-indStd; i++){ robot.keyTap('down') } }*/ if(object.ventDrainHole=="FC8"){ robot.keyTap('enter') } else if (object.ventDrainHole=="userdefined"){ robot.keyTap('tab') robot.keyTap('tab') for(i=0;i<17;i++){ robot.keyTap('down') } robot.typeString(object.userDefinedDiameters) robot.keyTap('tab') robot.keyTap('enter') robot.keyTap('tab') robot.keyTap('enter') } for(i=0; i<2; i++){ robot.keyTap('tab', 'shift') } } } exports.printPDF = function(fileName, customer, tag){ let i=0 robot.keyTap('enter') for(i=0; i<7; i++){ robot.keyTap('tab') } for(i=0; i<10; i++){ robot.keyTap('delete') } robot.typeString(customer) robot.keyTap('tab') robot.keyTap('tab') robot.typeString(tag) for(i=0; i<15; i++){ robot.keyTap('tab') } robot.keyTap('enter') sleep.msleep(500) robot.typeString(fileName) robot.keyTap('enter') sleep.msleep(500) } exports.existFile = function (fileName, errors) { fs.exists('../Documents/'+fileName, function(exists) { if(!exists){ errors.push(fileName) console.log(fileName, "ha presentato un errore") console.log(errors) } }); }
volcano-group/desktop-automata
fc8_helpers.js
JavaScript
mit
5,602
/** * Simple re-export of frost-detail-tabs-more-tabs in the app namespace */ export {default} from 'ember-frost-tabs/components/frost-detail-tabs-more-tabs'
ciena-frost/ember-frost-tabs
app/components/frost-detail-tabs-more-tabs.js
JavaScript
mit
160
import { Pipe, PipeTransform } from '@angular/core'; import { Issue } from './issue'; @Pipe({ name: 'issueFilter' }) export class IssueFilterPipe implements PipeTransform { transform(value: Issue[], filterBy: string): Issue[] { filterBy = filterBy ? filterBy.toLocaleLowerCase() : null; return filterBy ? value.filter((issue: Issue) => issue.title.toLocaleLowerCase().indexOf(filterBy) !== -1) : value; } }
AKouki/AspNetCore-ITrackerSPA
ITrackerSPA/ClientApp/src/app/issues/shared/issue-filter.pipe.ts
TypeScript
mit
430
package commands import ( "bytes" "errors" "fmt" "io" "time" key "github.com/ipfs/go-ipfs/blocks/key" cmds "github.com/ipfs/go-ipfs/commands" notif "github.com/ipfs/go-ipfs/notifications" path "github.com/ipfs/go-ipfs/path" ipdht "github.com/ipfs/go-ipfs/routing/dht" u "github.com/ipfs/go-ipfs/util" peer "gx/ipfs/QmUBogf4nUefBjmYjn6jfsfPJRkmDGSeMhNj4usRKq69f4/go-libp2p/p2p/peer" ) var ErrNotDHT = errors.New("routing service is not a DHT") var DhtCmd = &cmds.Command{ Helptext: cmds.HelpText{ Tagline: "Issue commands directly through the DHT.", ShortDescription: ``, }, Subcommands: map[string]*cmds.Command{ "query": queryDhtCmd, "findprovs": findProvidersDhtCmd, "findpeer": findPeerDhtCmd, "get": getValueDhtCmd, "put": putValueDhtCmd, }, } var queryDhtCmd = &cmds.Command{ Helptext: cmds.HelpText{ Tagline: "Run a 'findClosestPeers' query through the DHT.", ShortDescription: ``, }, Arguments: []cmds.Argument{ cmds.StringArg("peerID", true, true, "The peerID to run the query against."), }, Options: []cmds.Option{ cmds.BoolOption("verbose", "v", "Write extra information."), }, Run: func(req cmds.Request, res cmds.Response) { n, err := req.InvocContext().GetNode() if err != nil { res.SetError(err, cmds.ErrNormal) return } dht, ok := n.Routing.(*ipdht.IpfsDHT) if !ok { res.SetError(ErrNotDHT, cmds.ErrNormal) return } events := make(chan *notif.QueryEvent) ctx := notif.RegisterForQueryEvents(req.Context(), events) closestPeers, err := dht.GetClosestPeers(ctx, key.Key(req.Arguments()[0])) if err != nil { res.SetError(err, cmds.ErrNormal) return } go func() { defer close(events) for p := range closestPeers { notif.PublishQueryEvent(ctx, &notif.QueryEvent{ ID: p, Type: notif.FinalPeer, }) } }() outChan := make(chan interface{}) res.SetOutput((<-chan interface{})(outChan)) go func() { defer close(outChan) for e := range events { outChan <- e } }() }, Marshalers: cmds.MarshalerMap{ cmds.Text: func(res cmds.Response) (io.Reader, error) { outChan, ok := res.Output().(<-chan interface{}) if !ok { return nil, u.ErrCast() } marshal := func(v interface{}) (io.Reader, error) { obj, ok := v.(*notif.QueryEvent) if !ok { return nil, u.ErrCast() } verbose, _, _ := res.Request().Option("v").Bool() buf := new(bytes.Buffer) printEvent(obj, buf, verbose, nil) return buf, nil } return &cmds.ChannelMarshaler{ Channel: outChan, Marshaler: marshal, Res: res, }, nil }, }, Type: notif.QueryEvent{}, } var findProvidersDhtCmd = &cmds.Command{ Helptext: cmds.HelpText{ Tagline: "Run a 'FindProviders' query through the DHT.", ShortDescription: ` FindProviders will return a list of peers who are able to provide the value requested. `, }, Arguments: []cmds.Argument{ cmds.StringArg("key", true, true, "The key to find providers for."), }, Options: []cmds.Option{ cmds.BoolOption("verbose", "v", "Write extra information."), }, Run: func(req cmds.Request, res cmds.Response) { n, err := req.InvocContext().GetNode() if err != nil { res.SetError(err, cmds.ErrNormal) return } dht, ok := n.Routing.(*ipdht.IpfsDHT) if !ok { res.SetError(ErrNotDHT, cmds.ErrNormal) return } numProviders := 20 outChan := make(chan interface{}) res.SetOutput((<-chan interface{})(outChan)) events := make(chan *notif.QueryEvent) ctx := notif.RegisterForQueryEvents(req.Context(), events) pchan := dht.FindProvidersAsync(ctx, key.B58KeyDecode(req.Arguments()[0]), numProviders) go func() { defer close(outChan) for e := range events { outChan <- e } }() go func() { defer close(events) for p := range pchan { np := p notif.PublishQueryEvent(ctx, &notif.QueryEvent{ Type: notif.Provider, Responses: []*peer.PeerInfo{&np}, }) } }() }, Marshalers: cmds.MarshalerMap{ cmds.Text: func(res cmds.Response) (io.Reader, error) { outChan, ok := res.Output().(<-chan interface{}) if !ok { return nil, u.ErrCast() } verbose, _, _ := res.Request().Option("v").Bool() pfm := pfuncMap{ notif.FinalPeer: func(obj *notif.QueryEvent, out io.Writer, verbose bool) { if verbose { fmt.Fprintf(out, "* closest peer %s\n", obj.ID) } }, notif.Provider: func(obj *notif.QueryEvent, out io.Writer, verbose bool) { prov := obj.Responses[0] if verbose { fmt.Fprintf(out, "provider: ") } fmt.Fprintf(out, "%s\n", prov.ID.Pretty()) if verbose { for _, a := range prov.Addrs { fmt.Fprintf(out, "\t%s\n", a) } } }, } marshal := func(v interface{}) (io.Reader, error) { obj, ok := v.(*notif.QueryEvent) if !ok { return nil, u.ErrCast() } buf := new(bytes.Buffer) printEvent(obj, buf, verbose, pfm) return buf, nil } return &cmds.ChannelMarshaler{ Channel: outChan, Marshaler: marshal, Res: res, }, nil }, }, Type: notif.QueryEvent{}, } var findPeerDhtCmd = &cmds.Command{ Helptext: cmds.HelpText{ Tagline: "Run a 'FindPeer' query through the DHT.", ShortDescription: ``, }, Arguments: []cmds.Argument{ cmds.StringArg("peerID", true, true, "The peer to search for."), }, Run: func(req cmds.Request, res cmds.Response) { n, err := req.InvocContext().GetNode() if err != nil { res.SetError(err, cmds.ErrNormal) return } dht, ok := n.Routing.(*ipdht.IpfsDHT) if !ok { res.SetError(ErrNotDHT, cmds.ErrNormal) return } pid, err := peer.IDB58Decode(req.Arguments()[0]) if err != nil { res.SetError(err, cmds.ErrNormal) return } outChan := make(chan interface{}) res.SetOutput((<-chan interface{})(outChan)) events := make(chan *notif.QueryEvent) ctx := notif.RegisterForQueryEvents(req.Context(), events) go func() { defer close(outChan) for v := range events { outChan <- v } }() go func() { defer close(events) pi, err := dht.FindPeer(ctx, pid) if err != nil { notif.PublishQueryEvent(ctx, &notif.QueryEvent{ Type: notif.QueryError, Extra: err.Error(), }) return } notif.PublishQueryEvent(ctx, &notif.QueryEvent{ Type: notif.FinalPeer, Responses: []*peer.PeerInfo{&pi}, }) }() }, Marshalers: cmds.MarshalerMap{ cmds.Text: func(res cmds.Response) (io.Reader, error) { outChan, ok := res.Output().(<-chan interface{}) if !ok { return nil, u.ErrCast() } pfm := pfuncMap{ notif.FinalPeer: func(obj *notif.QueryEvent, out io.Writer, verbose bool) { pi := obj.Responses[0] fmt.Fprintf(out, "%s\n", pi.ID) for _, a := range pi.Addrs { fmt.Fprintf(out, "\t%s\n", a) } }, } marshal := func(v interface{}) (io.Reader, error) { obj, ok := v.(*notif.QueryEvent) if !ok { return nil, u.ErrCast() } buf := new(bytes.Buffer) printEvent(obj, buf, true, pfm) return buf, nil } return &cmds.ChannelMarshaler{ Channel: outChan, Marshaler: marshal, Res: res, }, nil }, }, Type: notif.QueryEvent{}, } var getValueDhtCmd = &cmds.Command{ Helptext: cmds.HelpText{ Tagline: "Run a 'GetValue' query through the DHT.", ShortDescription: ` GetValue will return the value stored in the dht at the given key. `, }, Arguments: []cmds.Argument{ cmds.StringArg("key", true, true, "The key to find a value for."), }, Options: []cmds.Option{ cmds.BoolOption("verbose", "v", "Write extra information."), }, Run: func(req cmds.Request, res cmds.Response) { n, err := req.InvocContext().GetNode() if err != nil { res.SetError(err, cmds.ErrNormal) return } dht, ok := n.Routing.(*ipdht.IpfsDHT) if !ok { res.SetError(ErrNotDHT, cmds.ErrNormal) return } outChan := make(chan interface{}) res.SetOutput((<-chan interface{})(outChan)) events := make(chan *notif.QueryEvent) ctx := notif.RegisterForQueryEvents(req.Context(), events) dhtkey, err := escapeDhtKey(req.Arguments()[0]) if err != nil { res.SetError(err, cmds.ErrNormal) return } go func() { defer close(outChan) for e := range events { outChan <- e } }() go func() { defer close(events) val, err := dht.GetValue(ctx, dhtkey) if err != nil { notif.PublishQueryEvent(ctx, &notif.QueryEvent{ Type: notif.QueryError, Extra: err.Error(), }) } else { notif.PublishQueryEvent(ctx, &notif.QueryEvent{ Type: notif.Value, Extra: string(val), }) } }() }, Marshalers: cmds.MarshalerMap{ cmds.Text: func(res cmds.Response) (io.Reader, error) { outChan, ok := res.Output().(<-chan interface{}) if !ok { return nil, u.ErrCast() } verbose, _, _ := res.Request().Option("v").Bool() pfm := pfuncMap{ notif.Value: func(obj *notif.QueryEvent, out io.Writer, verbose bool) { if verbose { fmt.Fprintf(out, "got value: '%s'\n", obj.Extra) } else { fmt.Fprintln(out, obj.Extra) } }, } marshal := func(v interface{}) (io.Reader, error) { obj, ok := v.(*notif.QueryEvent) if !ok { return nil, u.ErrCast() } buf := new(bytes.Buffer) printEvent(obj, buf, verbose, pfm) return buf, nil } return &cmds.ChannelMarshaler{ Channel: outChan, Marshaler: marshal, Res: res, }, nil }, }, Type: notif.QueryEvent{}, } var putValueDhtCmd = &cmds.Command{ Helptext: cmds.HelpText{ Tagline: "Run a 'PutValue' query through the DHT.", ShortDescription: ` PutValue will store the given key value pair in the dht. `, }, Arguments: []cmds.Argument{ cmds.StringArg("key", true, false, "The key to store the value at."), cmds.StringArg("value", true, false, "The value to store.").EnableStdin(), }, Options: []cmds.Option{ cmds.BoolOption("verbose", "v", "Write extra information."), }, Run: func(req cmds.Request, res cmds.Response) { n, err := req.InvocContext().GetNode() if err != nil { res.SetError(err, cmds.ErrNormal) return } dht, ok := n.Routing.(*ipdht.IpfsDHT) if !ok { res.SetError(ErrNotDHT, cmds.ErrNormal) return } outChan := make(chan interface{}) res.SetOutput((<-chan interface{})(outChan)) events := make(chan *notif.QueryEvent) ctx := notif.RegisterForQueryEvents(req.Context(), events) key, err := escapeDhtKey(req.Arguments()[0]) if err != nil { res.SetError(err, cmds.ErrNormal) return } data := req.Arguments()[1] go func() { defer close(outChan) for e := range events { outChan <- e } }() go func() { defer close(events) err := dht.PutValue(ctx, key, []byte(data)) if err != nil { notif.PublishQueryEvent(ctx, &notif.QueryEvent{ Type: notif.QueryError, Extra: err.Error(), }) } }() }, Marshalers: cmds.MarshalerMap{ cmds.Text: func(res cmds.Response) (io.Reader, error) { outChan, ok := res.Output().(<-chan interface{}) if !ok { return nil, u.ErrCast() } verbose, _, _ := res.Request().Option("v").Bool() pfm := pfuncMap{ notif.FinalPeer: func(obj *notif.QueryEvent, out io.Writer, verbose bool) { if verbose { fmt.Fprintf(out, "* closest peer %s\n", obj.ID) } }, notif.Value: func(obj *notif.QueryEvent, out io.Writer, verbose bool) { fmt.Fprintf(out, "storing value at %s\n", obj.ID) }, } marshal := func(v interface{}) (io.Reader, error) { obj, ok := v.(*notif.QueryEvent) if !ok { return nil, u.ErrCast() } buf := new(bytes.Buffer) printEvent(obj, buf, verbose, pfm) return buf, nil } return &cmds.ChannelMarshaler{ Channel: outChan, Marshaler: marshal, Res: res, }, nil }, }, Type: notif.QueryEvent{}, } type printFunc func(obj *notif.QueryEvent, out io.Writer, verbose bool) type pfuncMap map[notif.QueryEventType]printFunc func printEvent(obj *notif.QueryEvent, out io.Writer, verbose bool, override pfuncMap) { if verbose { fmt.Fprintf(out, "%s: ", time.Now().Format("15:04:05.000")) } if override != nil { if pf, ok := override[obj.Type]; ok { pf(obj, out, verbose) return } } switch obj.Type { case notif.SendingQuery: if verbose { fmt.Fprintf(out, "* querying %s\n", obj.ID) } case notif.Value: if verbose { fmt.Fprintf(out, "got value: '%s'\n", obj.Extra) } else { fmt.Fprint(out, obj.Extra) } case notif.PeerResponse: fmt.Fprintf(out, "* %s says use ", obj.ID) for _, p := range obj.Responses { fmt.Fprintf(out, "%s ", p.ID) } fmt.Fprintln(out) case notif.QueryError: fmt.Fprintf(out, "error: %s\n", obj.Extra) case notif.DialingPeer: if verbose { fmt.Fprintf(out, "dialing peer: %s\n", obj.ID) } case notif.AddingPeer: if verbose { fmt.Fprintf(out, "adding peer to query: %s\n", obj.ID) } default: fmt.Fprintf(out, "unrecognized event type: %d\n", obj.Type) } } func escapeDhtKey(s string) (key.Key, error) { parts := path.SplitList(s) switch len(parts) { case 1: return key.B58KeyDecode(s), nil case 3: k := key.B58KeyDecode(parts[2]) return key.Key(path.Join(append(parts[:2], k.String()))), nil default: return "", errors.New("invalid key") } }
palkeo/go-ipfs
core/commands/dht.go
GO
mit
13,375
package petrichor; import behavior.Aggressive; import behavior.Behavior; import robocode.*; import java.awt.Color; /** * Petrichor - a robot by Piper Chester and Michael Timbrook */ public class Petrichor extends AdvancedRobot { private Behavior active; /** * Petrichor's default behavior. Initialization of robot occurs here. */ public void run() { setColors(Color.blue, Color.cyan, Color.green); // Body, gun, radar // Set behavior active = new Aggressive(this); // Sit in the behaviors run loop while (active.runLoop()); } /** * What to do when you see another robot. */ public void onScannedRobot(ScannedRobotEvent e) { active.onScannedRobot(e); } /** * What to do when you're hit by a bullet. */ public void onHitByBullet(HitByBulletEvent e) { active.onHitByBullet(e); } /** * onHitWall: What to do when you hit a wall */ public void onHitWall(HitWallEvent e) { active.onHitWall(e); } }
piperchester/petrichor
src/petrichor/Petrichor.java
Java
mit
1,021
################################################################################ # # Copyright (C) 2006-2007 pmade inc. (Peter Jones pjones@pmade.com) # # 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. # ################################################################################ module Admin::RolesHelper end ################################################################################
codemer/devalot
app/helpers/admin/roles_helper.rb
Ruby
mit
1,406
<?php declare(strict_types=1); namespace Gos\Bundle\WebSocketBundle\Tests\Server\App; use Gos\Bundle\WebSocketBundle\Server\App\Registry\OriginRegistry; use Gos\Bundle\WebSocketBundle\Server\App\ServerBuilder; use Gos\Bundle\WebSocketBundle\Server\App\Stack\BlockedIpCheck; use Gos\Bundle\WebSocketBundle\Server\App\Stack\OriginCheck; use Gos\Bundle\WebSocketBundle\Topic\TopicManager; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Ratchet\Http\HttpServer; use Ratchet\Session\SessionProvider; use Ratchet\WebSocket\WsServer; use React\EventLoop\LoopInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class ServerBuilderTest extends TestCase { /** * @var MockObject|LoopInterface */ private $loop; /** * @var MockObject|TopicManager */ private $topicManager; /** * @var OriginRegistry */ private $originRegistry; /** * @var MockObject|EventDispatcherInterface */ private $eventDispatcher; /** * @var ServerBuilder */ private $builder; protected function setUp(): void { parent::setUp(); $this->loop = $this->createMock(LoopInterface::class); $this->topicManager = $this->createMock(TopicManager::class); $this->originRegistry = new OriginRegistry(); $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); $this->builder = new ServerBuilder( $this->loop, $this->topicManager, $this->originRegistry, $this->eventDispatcher, false, false, 30, false, [] ); } public function testTheMessageStackIsBuiltWithoutOptionalDecorators(): void { $server = $this->builder->buildMessageStack(); self::assertInstanceOf(HttpServer::class, $server, 'The assembled message stack should be returned.'); self::assertInstanceOf( WsServer::class, $this->getPropertyFromClassInstance($server, '_httpServer'), 'The assembled message stack should decorate the correct class.' ); } /** * @runInSeparateProcess */ public function testTheMessageStackIsBuiltWithTheSessionProviderDecorator(): void { $this->builder->setSessionHandler($this->createMock(\SessionHandlerInterface::class)); $server = $this->builder->buildMessageStack(); self::assertInstanceOf(HttpServer::class, $server, 'The assembled message stack should be returned.'); $decoratedServer = $this->getPropertyFromClassInstance($server, '_httpServer'); self::assertInstanceOf( SessionProvider::class, $decoratedServer, 'The assembled message stack should decorate the correct class.' ); self::assertInstanceOf( WsServer::class, $this->getPropertyFromClassInstance($decoratedServer, '_app'), 'The assembled message stack should decorate the correct class.' ); } public function testTheMessageStackIsBuiltWithTheOriginCheckDecorator(): void { $builder = new ServerBuilder( $this->loop, $this->topicManager, $this->originRegistry, $this->eventDispatcher, true, false, 30, false, [] ); $server = $builder->buildMessageStack(); self::assertInstanceOf(HttpServer::class, $server, 'The assembled message stack should be returned.'); $decoratedServer = $this->getPropertyFromClassInstance($server, '_httpServer'); self::assertInstanceOf( OriginCheck::class, $decoratedServer, 'The assembled message stack should decorate the correct class.' ); self::assertInstanceOf( WsServer::class, $this->getPropertyFromClassInstance($decoratedServer, '_component'), 'The assembled message stack should decorate the correct class.' ); } public function testTheMessageStackIsBuiltWithTheIpAddressCheckDecorator(): void { $builder = new ServerBuilder( $this->loop, $this->topicManager, $this->originRegistry, $this->eventDispatcher, false, false, 30, true, ['192.168.1.1'] ); $server = $builder->buildMessageStack(); self::assertInstanceOf(BlockedIpCheck::class, $server, 'The assembled message stack should be returned.'); $decoratedServer = $this->getPropertyFromClassInstance($server, '_decorating'); self::assertInstanceOf( HttpServer::class, $decoratedServer, 'The assembled message stack should decorate the correct class.' ); self::assertInstanceOf( WsServer::class, $this->getPropertyFromClassInstance($decoratedServer, '_httpServer'), 'The assembled message stack should decorate the correct class.' ); } /** * @return mixed * * @throws \InvalidArgumentException if the requested property does not exist on the given class instance */ private function getPropertyFromClassInstance(object $classInstance, string $property) { $reflClass = new \ReflectionClass($classInstance); if (!$reflClass->hasProperty($property)) { throw new \InvalidArgumentException(sprintf('The %s class does not have a property named "%s".', \get_class($classInstance), $property)); } $reflProperty = $reflClass->getProperty($property); $reflProperty->setAccessible(true); return $reflProperty->getValue($classInstance); } }
GeniusesOfSymfony/WebSocketBundle
tests/Server/App/ServerBuilderTest.php
PHP
mit
5,866
'use strict'; /** * Module dependencies */ var citiesPolicy = require('../policies/cities.server.policy'), cities = require('../controllers/cities.server.controller'); module.exports = function (app) { // City collection routes app.route('/api/cities').all(citiesPolicy.isAllowed) .get(cities.list) .post(cities.create); // Single city routes app.route('/api/cities/:cityId').all(citiesPolicy.isAllowed) .get(cities.read) .put(cities.update) .delete(cities.delete); // Finish by binding the city middleware app.param('cityId', cities.cityByID); };
ravikumargh/Infy
modules/cities/server/routes/cities.server.routes.js
JavaScript
mit
588
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("Draw a Filled Square")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Draw a Filled Square")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("733aa5af-694d-464c-9cb6-ee192841242a")] // 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")]
flyelmos/Software-University
02. Programming Fundamentals Course on C#/Methods Debugging and Troubleshooting Code Lab Exercises/Draw a Filled Square/Properties/AssemblyInfo.cs
C#
mit
1,416
<?xml version="1.0" ?><!DOCTYPE TS><TS language="eo" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About BitTor</source> <translation>Pri BitTor</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;BitTor&lt;/b&gt; version</source> <translation>&lt;b&gt;BitTor&lt;/b&gt;-a versio</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The BitTor developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresaro</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Duoble-klaku por redakti adreson aŭ etikedon</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Kreu novan adreson</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiu elektitan adreson al la tondejo</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nova Adreso</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your BitTor addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopiu Adreson</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a BitTor address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified BitTor address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Forviŝu</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your BitTor addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopiu &amp;Etikedon</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Redaktu</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Eksportu Adresarajn Datumojn</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Diskoma dosiero (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Eraro dum eksportado</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ne eblis skribi al dosiero %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etikedo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adreso</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ne etikedo)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Enigu pasfrazon</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova pasfrazo</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ripetu novan pasfrazon</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Enigu novan pasfrazon por la monujo.&lt;br/&gt;Bonvolu, uzu pasfrazon kun &lt;b&gt;10 aŭ pli hazardaj signoj&lt;/b&gt;, aŭ &lt;b&gt;ok aŭ pli vortoj&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Ĉifru monujon</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ĉi tiu operacio devas vian monujan pasfrazon, por malŝlosi la monujon.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Malŝlosu monujon</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ĉi tiu operacio devas vian monujan pasfrazon, por malĉifri la monujon.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Malĉifru monujon</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Anstataŭigu pasfrazon</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Enigu la malnovan kaj novan monujan pasfrazon.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Konfirmu ĉifrado de monujo</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITTORS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Monujo ĉifrita</translation> </message> <message> <location line="-56"/> <source>BitTor will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bittors from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Monujo ĉifrado fiaskis</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Ĉifrado de monujo fiaskis, kaŭze de interna eraro. Via monujo ne ĉifritas.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>La pasfrazoj enigitaj ne samas.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Monujo malŝlosado fiaskis</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La pasfrazo enigita por ĉifrado de monujo ne konformas.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Monujo malĉifrado fiaskis</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Subskribu &amp;mesaĝon...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sinkronigante kun reto...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Superrigardo</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakcioj</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Esploru historion de transakcioj</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Eliru</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Eliru de aplikaĵo</translation> </message> <message> <location line="+4"/> <source>Show information about BitTor</source> <translation>Vidigu informaĵon pri Bitmono</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Pri &amp;QT</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Vidigu informaĵon pri Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opcioj...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Ĉifru Monujon...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Anstataŭigu pasfrazon...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a BitTor address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for BitTor</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Kontrolu mesaĝon...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>BitTor</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Monujo</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About BitTor</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your BitTor addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified BitTor addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Dosiero</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Agordoj</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Helpo</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>BitTor client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to BitTor network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n horo</numerusform><numerusform>%n horoj</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n tago</numerusform><numerusform>%n tagoj</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n semajno</numerusform><numerusform>%n semajnoj</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Eraro</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Ĝisdata</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Ĝisdatigante...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Sendita transakcio</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Envenanta transakcio</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid BitTor address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Monujo estas &lt;b&gt;ĉifrita&lt;/b&gt; kaj nun &lt;b&gt;malŝlosita&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Monujo estas &lt;b&gt;ĉifrita&lt;/b&gt; kaj nun &lt;b&gt;ŝlosita&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. BitTor can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Reta Averto</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Redaktu Adreson</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etikedo</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>La etikedo interrilatita kun ĉi tiun adreso</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adreso</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>La adreso enigita &quot;%1&quot; jam ekzistas en la adresaro.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid BitTor address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Ne eblis malŝlosi monujon</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>BitTor-Qt</source> <translation>BitTor-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versio</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opcioj</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start BitTor after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start BitTor on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the BitTor client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the BitTor network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting BitTor.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show BitTor addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Nuligu</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Apliku</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting BitTor.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the BitTor network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Nekonfirmita:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Monujo</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Lastaj transakcioj&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start bittor: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etikedo:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>Reto</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Malfermu</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the BitTor-Qt help message to get a list with possible BitTor command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>BitTor - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>BitTor Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the BitTor debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the BitTor RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Sendu Monojn</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Sendu samtempe al multaj ricevantoj</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123,456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; al %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ĉu vi vere volas sendi %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>kaj</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etikedo:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Elektu adreson el adresaro</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Algluu adreson de tondejo</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Forigu ĉi tiun ricevanton</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a BitTor address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Algluu adreson de tondejo</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this BitTor address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified BitTor address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a BitTor address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter BitTor signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The BitTor developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nekonfirmita</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 konfirmoj</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Sumo</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ankoraŭ ne elsendita sukcese</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nekonata</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transakciaj detaloj</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adreso</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Sumo</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ricevita kun</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ricevita de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Sendita al</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pago al vi mem</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minita</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Transakcia tipo.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Ĉiuj</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hodiaŭ</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ricevita kun</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Sendita al</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Al vi mem</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minita</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopiu adreson</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Redaktu etikedon</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Diskoma dosiero (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Konfirmita</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etikedo</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adreso</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Sumo</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Eraro dum eksportado</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Ne eblis skribi al dosiero %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>BitTor version</source> <translation>BitTor-a versio</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or bittord</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listigu instrukciojn</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opcioj:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: bittor.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: bittord.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 4693 or testnet: 14693)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 4694 or testnet: 14694)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bittorrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;BitTor Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. BitTor is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong BitTor will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the BitTor Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Ŝarĝante adresojn...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of BitTor</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart BitTor to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Ŝarĝante blok-indekson...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. BitTor is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Ŝarĝante monujon...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Ŝarĝado finitas</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Por uzi la opcion %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Eraro</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
BitTorCrypto/BitTor
src/qt/locale/bitcoin_eo.ts
TypeScript
mit
98,404
package net.techcable.jstruct.visitor; import net.techcable.jstruct.StructData; import net.techcable.jstruct.StructManager; import org.objectweb.asm.*; import org.objectweb.asm.commons.AnalyzerAdapter; import org.objectweb.asm.commons.InstructionAdapter; import org.objectweb.asm.commons.LocalVariablesSorter; import java.util.*; public class PassByValueMethodVisitor extends InstructionAdapter { private final StructManager structManager; private final LocalVariablesSorter localVariables; private final AnalyzerAdapter analyzer; private final Type declaringType; public PassByValueMethodVisitor(StructManager structManager, Type declaringType, MethodVisitor parent, LocalVariablesSorter localVariables, AnalyzerAdapter analyzer) { super(parent); this.structManager = structManager; this.analyzer = analyzer; this.localVariables = localVariables; this.declaringType = declaringType; } @Override public void invokevirtual(String owner, String name, String desc, boolean itf) { String[] array = onInvoke(owner, name, desc); owner = array[0]; name = array[1]; desc = array[2]; super.invokevirtual(owner, name, desc, itf); } @Override public void invokestatic(String owner, String name, String desc, boolean itf) { String[] array = onInvoke(owner, name, desc); owner = array[0]; name = array[1]; desc = array[2]; super.invokestatic(owner, name, desc, itf); } @Override public void invokeinterface(String owner, String name, String desc) { String[] array = onInvoke(owner, name, desc); owner = array[0]; name = array[1]; desc = array[2]; super.invokeinterface(owner, name, desc); } @Override public void invokespecial(String owner, String name, String desc, boolean itf) { String[] array = onInvoke(owner, name, desc); owner = array[0]; name = array[1]; desc = array[2]; super.invokespecial(owner, name, desc, itf); } private String[] onInvoke(String owner, String name, String desc) { if (structManager.isStruct(getTopOfStack())) { // Do some sanity checks for structs if ("wait".equals(name) || "notify".equals(name) && Type.getInternalName(Object.class).equals(owner)) { throwNewException(UnsupportedOperationException.class, "Can't call " + name + " on a struct"); return new String[] {owner, name, desc}; } } Type methodType = Type.getMethodType(desc); for (Type structType : methodType.getArgumentTypes()) { if (!structManager.isStruct(structType)) continue; int structVar = localVariables.newLocal(structType); // Create a local variable which will hold the struct StructData structData = structManager.getStruct(structType); for (StructData.FieldStructData fieldData : structData.getFieldTypes()) { load(structVar, structType); // Load the struct onto the stack Type fieldType = fieldData.getFieldType(); getfield(structType.getInternalName(), fieldData.getName(), fieldType.getDescriptor()); // Now get the field from the type } // Duplicate the fields on the stack } return new String[] {owner, name, desc}; } @Override public void monitorenter() { if (structManager.isStruct(getTopOfStack())) throwNewException(UnsupportedOperationException.class, "Cant synchronize on a monitor"); } @Override public void ificmpeq(Label label) { onCompare(label, true); super.ificmpeq(label); } @Override public void ificmpne(Label label) { onCompare(label, false); super.ificmpne(label); } private void onCompare(Label label, boolean equals) { Queue<Type> stack = getStack(); boolean comparingStructs; Type t = stack.poll(); comparingStructs = structManager.isStruct(t); t = stack.poll(); // Right below the top comparingStructs = comparingStructs || structManager.isStruct(t); if (comparingStructs) throwNewException(UnsupportedOperationException.class, "Can't compare structs"); } private void throwNewException(Class<? extends Throwable> exceptionType, String msg) { throwNewException(Type.getType(exceptionType), msg); } private void throwNewException(Type exceptionType, String msg) { anew(exceptionType); Type desc = msg == null ? Type.getMethodType(Type.VOID_TYPE) : Type.getMethodType(Type.VOID_TYPE, Type.getType(String.class)); if (msg != null) { aconst(msg); } invokespecial(exceptionType.getInternalName(), "<init>", desc.getDescriptor(), false); // Call the constructor athrow(); } private Type getTopOfStack() { return getStack().poll(); } private Queue<Type> getStack() { List<Object> stackList = analyzer.stack; Queue<Object> objStack = new LinkedList<>(); Collections.reverse(stackList); // bottom -> top, top -> bottom stackList.forEach(objStack::add); // Since it is a FIFO queue, adding the top first will cause the top to be last out Queue<Type> typeStack = new LinkedList<>(); Object obj; while ((obj = objStack.poll()) != null) { Type type; if (obj instanceof Integer) { int id = ((Integer) obj); if (id == Opcodes.INTEGER) { type = Type.INT_TYPE; } else if (id == Opcodes.FLOAT) { type = Type.FLOAT_TYPE; } else if (id == Opcodes.LONG) { type = Type.LONG_TYPE; } else if (id == Opcodes.DOUBLE) { type = Type.DOUBLE_TYPE; } else if (id == Opcodes.NULL) { type = null; // } else if (id == Opcodes.UNINITIALIZED_THIS) { type = declaringType; } else continue; // Doesn't matter } else if (obj instanceof String) { String internalName = ((String) obj); type = Type.getObjectType(internalName); } else type = null; // Unknown type typeStack.add(type); } return typeStack; } }
Techcable/JStruct
src/main/java/net/techcable/jstruct/visitor/PassByValueMethodVisitor.java
Java
mit
6,480
<?php namespace Oro\Bundle\TagBundle\Form\Type; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Oro\Bundle\UserBundle\Form\EventListener\PatchSubscriber; class TagApiType extends TagType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder->addEventSubscriber(new PatchSubscriber()); } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Oro\Bundle\TagBundle\Entity\Tag', 'intention' => 'tag', 'csrf_protection' => false ) ); } }
umpirsky/platform
src/Oro/Bundle/TagBundle/Form/Type/TagApiType.php
PHP
mit
858
(function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["jquery", "../jquery.validate"], factory ); } else if (typeof exports === "object") { factory(require("jquery")); } else { factory( jQuery ); } }(function( $ ) { /* * Translated default messages for the jQuery validation plugin. * Locale: ET (Estonian; eesti, eesti keel) */ $.extend($.validator.messages, { required: "See väli peab olema täidetud.", maxlength: $.validator.format("Palun sisestage vähem kui {0} tähemärki."), minlength: $.validator.format("Palun sisestage vähemalt {0} tähemärki."), rangelength: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1} tähemärki."), email: "Palun sisestage korrektne e-maili aadress.", url: "Palun sisestage korrektne URL.", date: "Palun sisestage korrektne kuupäev.", dateISO: "Palun sisestage korrektne kuupäev (YYYY-MM-DD).", number: "Palun sisestage korrektne number.", digits: "Palun sisestage ainult numbreid.", equalTo: "Palun sisestage sama väärtus uuesti.", range: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1}."), max: $.validator.format("Palun sisestage väärtus, mis on väiksem või võrdne arvuga {0}."), min: $.validator.format("Palun sisestage väärtus, mis on suurem või võrdne arvuga {0}."), creditcard: "Palun sisestage korrektne krediitkaardi number." }); }));
Badalik/jquery-validation
dist/localization/messages_et.js
JavaScript
mit
1,398
<?php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class LocationType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('companyId') ->add('name') ->add('address1') ->add('address2') ->add('state') ->add('zip') ->add('country') ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\Location' )); } /** * @return string */ public function getName() { return 'appbundle_location'; } }
chrisciampoli/swiftly
src/AppBundle/Form/LocationType.php
PHP
mit
1,016
require "rails_helper" RSpec.describe Dorsale::CommentsController, type: :routing do routes { Dorsale::Engine.routes } describe "routing" do it "routes to #create" do expect(post: "/comments").to route_to("dorsale/comments#create") end it "routes to #edit" do expect(get: "/comments/3/edit").to route_to("dorsale/comments#edit", id: "3") end it "routes to #update" do expect(patch: "/comments/3").to route_to("dorsale/comments#update", id: "3") end it "routes to #destroy" do expect(delete: "/comments/3").to route_to("dorsale/comments#destroy", id: "3") end end end
agilidee/dorsale
spec/routing/dorsale/comments_routing_spec.rb
Ruby
mit
634
using System; using System.Diagnostics; using System.Net; using System.Threading; namespace Conreign.Server.Host.Console.Silo { public class Program { private static void Main(string[] args) { var exitEvent = new ManualResetEvent(false); System.Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; exitEvent.Set(); }; ServicePointManager.DefaultConnectionLimit = 10000; try { using (Runner.Run(args)) { exitEvent.WaitOne(); } } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); if (Debugger.IsAttached) { System.Console.WriteLine("Press enter to exit..."); System.Console.ReadLine(); } Environment.Exit(-1); } } } }
smolyakoff/conreign
src/Conreign.Server.Host.Console.Silo/Program.cs
C#
mit
1,044
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // 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. #endregion using System; using System.Collections.Generic; using System.Linq; using Hotcakes.CommerceDTO.v1.Catalog; namespace Hotcakes.Commerce.Catalog { /// <summary> /// This is the primary class used for option selection in the main application. /// </summary> /// <remarks>The REST API equivalent is OptionSelectionDTO.</remarks> [Serializable] public class OptionSelection { private string _OptionBvin = string.Empty; private string _SelectionData = string.Empty; public OptionSelection() { } public OptionSelection(string optionBvin, string selectionData) { _OptionBvin = CleanBvin(optionBvin); _SelectionData = CleanBvin(selectionData); } /// <summary> /// The unique ID or primary key of the option. /// </summary> public string OptionBvin { get { return _OptionBvin; } set { _OptionBvin = CleanBvin(value); } } /// <summary> /// The options or choices selected for the product. /// </summary> public string SelectionData { get { return _SelectionData; } set { Guid bvin; if (Guid.TryParse(value, out bvin)) { _SelectionData = CleanBvin(value); } else { _SelectionData = value; } } } /// <summary> /// Removes the hyphens from the Bvin (GUID). /// </summary> /// <param name="input">String - the original GUID or Bvin</param> /// <returns>String - te GUID without the hypens</returns> public static string CleanBvin(string input) { return input.Replace("-", string.Empty); } /// <summary> /// Allows you to generate a unique key for the OptionSelection using the given choices. /// </summary> /// <param name="selections">The chosen selections for the product.</param> /// <returns>String - a unique key generated from the given selections</returns> public static string GenerateUniqueKeyForSelections(List<OptionSelection> selections) { var result = string.Empty; if (selections == null) return result; if (selections.Count < 1) return result; var sorted = selections.OrderBy(y => y.OptionBvin); foreach (var s in sorted) { result += s.OptionBvin + "-" + s.SelectionData + "|"; } return result; } /// <summary> /// Checks to see if a list of selection data contains a selection that isn't a valid variant in a list of options. /// </summary> /// <param name="options">The available options for the product.</param> /// <param name="selections">The options that have been selected.</param> /// <returns>If true, the selected options all match that available choices.</returns> public static bool ContainsInvalidSelectionForOptions(OptionList options, List<OptionSelection> selections) { var result = false; foreach (var sel in selections) { if (!options.ContainsVariantSelection(sel)) { return true; } } return result; } #region DTO /// <summary> /// Allows you to convert the current open selection object to the DTO equivalent for use with the REST API /// </summary> /// <returns>A new instance of OptionSelectionDTO</returns> public OptionSelectionDTO ToDto() { var dto = new OptionSelectionDTO(); dto.OptionBvin = OptionBvin; dto.SelectionData = SelectionData; return dto; } /// <summary> /// Allows you to populate the current option selection object using a OptionSelectionDTO instance /// </summary> /// <param name="dto">An instance of the option selection from the REST API</param> public void FromDto(OptionSelectionDTO dto) { if (dto == null) return; OptionBvin = dto.OptionBvin ?? string.Empty; SelectionData = dto.SelectionData ?? string.Empty; } #endregion } }
HotcakesCommerce/core
Libraries/Hotcakes.Commerce/Catalog/OptionSelection.cs
C#
mit
5,665
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfValidatorDoctrineUnique validates that the uniqueness of a column. * * Warning: sfValidatorDoctrineUnique is susceptible to race conditions. * To avoid this issue, wrap the validation process and the model saving * inside a transaction. * * @package symfony * @subpackage validator * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id: sfValidatorDoctrineUnique.class.php 8807 2008-05-06 14:12:28Z fabien $ */ class sfValidatorDoctrineUnique extends sfValidatorSchema { /** * Constructor. * * @param array An array of options * @param array An array of error messages * * @see sfValidatorSchema */ public function __construct($options = array(), $messages = array()) { parent::__construct(null, $options, $messages); } /** * Configures the current validator. * * Available options: * * * model: The model class (required) * * column: The unique column name in Doctrine field name format (required) * If the uniquess is for several columns, you can pass an array of field names * * primary_key: The primary key column name in Doctrine field name format (optional, will be introspected if not provided) * You can also pass an array if the table has several primary keys * * connection: The Doctrine connection to use (null by default) * * throw_global_error: Whether to throw a global error (false by default) or an error tied to the first field related to the column option array * * @see sfValidatorBase */ protected function configure($options = array(), $messages = array()) { $this->addRequiredOption('model'); $this->addRequiredOption('column'); $this->addOption('primary_key', null); $this->addOption('connection', null); $this->addOption('throw_global_error', true); $this->setMessage('invalid', 'An object with the same "%column%" already exist.'); } /** * @see sfValidatorBase */ protected function doClean($values) { $originalValues = $values; $table = Doctrine::getTable($this->getOption('model')); if (!is_array($this->getOption('column'))) { $this->setOption('column', array($this->getOption('column'))); } //if $values isn't an array, make it one if (!is_array($values)) { //use first column for key $columns = $this->getOption('column'); $values = array($columns[0] => $values); } $q = Doctrine_Query::create() ->from($this->getOption('model') . ' a'); foreach ($this->getOption('column') as $column) { $colName = $table->getColumnName($column); $q->addWhere('a.' . $colName . ' = ?', $values[$column]); } $object = $q->fetchOne(); // if no object or if we're updating the object, it's ok if (!$object || $this->isUpdate($object, $values)) { return $originalValues; } $error = new sfValidatorError($this, 'invalid', array('column' => implode(', ', $this->getOption('column')), 'value' => implode (', ', $values))); if ($this->getOption('throw_global_error')) { throw $error; } $columns = $this->getOption('column'); throw new sfValidatorErrorSchema($this, array($columns[0] => $error)); } /** * Returns whether the object is being updated. * * @param BaseObject A Doctrine object * @param array An array of values * * @param Boolean true if the object is being updated, false otherwise */ protected function isUpdate(Doctrine_Record $object, $values) { // check each primary key column foreach ($this->getPrimaryKeys() as $column) { if (!isset($values[$column]) || $object->$column != $values[$column]) { return false; } } return true; } /** * Returns the primary keys for the model. * * @return array An array of primary keys */ protected function getPrimaryKeys() { if (is_null($this->getOption('primary_key'))) { $primaryKeys = Doctrine::getTable($this->getOption('model'))->getIdentifier(); $this->setOption('primary_key', $primaryKeys); } if (!is_array($this->getOption('primary_key'))) { $this->setOption('primary_key', array($this->getOption('primary_key'))); } return $this->getOption('primary_key'); } }
liding211/hotels
plugins/sfDoctrine/lib/validator/sfValidatorDoctrineUnique.class.php
PHP
mit
4,680
import { TASK_STATUS_ACTIVE, TASK_STATUS_COMPLETED } from 'modules/task/constants'; export class RouterService { constructor($state, $stateParams) { this.state = $state; this.params = $stateParams; } isActiveTasks() { return this.state.is('app.tasks', {filter: TASK_STATUS_ACTIVE}); } isCompletedTasks() { return this.state.is('app.tasks', {filter: TASK_STATUS_COMPLETED}); } isTasks() { return this.state.is('app.tasks', {filter: ''}); } toActiveTasks() { return this.state.go('app.tasks', {filter: TASK_STATUS_ACTIVE}); } toCompletedTasks() { return this.state.go('app.tasks', {filter: TASK_STATUS_COMPLETED}); } toTasks() { return this.state.go('app.tasks'); } }
r-park/todo-angular-rx
src/modules/router/router-service.js
JavaScript
mit
738
module.exports = { description: 'deconflict entry points with the same name in different directories', command: 'rollup --input main.js --input sub/main.js --format esm --dir _actual --experimentalCodeSplitting' };
corneliusweig/rollup
test/cli/samples/deconflict-entry-point-in-subdir/_config.js
JavaScript
mit
219
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'github_sniffer'
rails-kung-foo/github-sniffer
spec/spec_helper.rb
Ruby
mit
84
package org.dol.json; import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.type.MapType; import lombok.Data; import org.dol.model.FieldProperty; import org.dol.util.StringUtil; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class JSON { public static final ObjectMapper DEFAULT_OBJECT_MAPPER; static { DEFAULT_OBJECT_MAPPER = createDefault(); } public static ObjectMapper createDefault() { ObjectMapper objectMapper = new ObjectMapper(); AnnotationIntrospector dimensionFieldSerializer = new CustomJacksonAnnotationIntrospector(); objectMapper.setAnnotationIntrospector(dimensionFieldSerializer); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); objectMapper.disable(SerializationFeature.FAIL_ON_SELF_REFERENCES); objectMapper.disable(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS); objectMapper.enable(JsonParser.Feature.ALLOW_MISSING_VALUES); objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS); objectMapper.enable(JsonParser.Feature.ALLOW_COMMENTS); DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig().withHandler(BooleanDeserializationProblemHandler.INSTANCE); objectMapper.setConfig(deserializationConfig); return objectMapper; } public static <T> T parseObject(String json, Class<T> resultClazz) { try { return DEFAULT_OBJECT_MAPPER .readerFor(resultClazz) .readValue(json); } catch (IOException e) { throw new RuntimeException(e); } } public static Object parseObject(String json, Type type) { try { JavaType javaType = DEFAULT_OBJECT_MAPPER.getTypeFactory().constructType(type); return DEFAULT_OBJECT_MAPPER.readerFor(javaType).readValue(json); } catch (IOException e) { throw new RuntimeException(e); } } public static <T> T parseObject(String json, Class<T> parametrized, Class<?>... parameterClasses) { try { JavaType javaType = DEFAULT_OBJECT_MAPPER .getTypeFactory() .constructParametricType(parametrized, parameterClasses); return DEFAULT_OBJECT_MAPPER.readerFor(javaType).readValue(json); } catch (IOException e) { throw new RuntimeException(e); } } public static <T> T[] parseJavaArray(String json, Class<T> elementType) { try { JavaType javaType = DEFAULT_OBJECT_MAPPER.getTypeFactory().constructArrayType(elementType); return DEFAULT_OBJECT_MAPPER.readerFor(javaType).readValue(json); } catch (IOException e) { throw new RuntimeException(e); } } public static <T> List<T> parseArray(String json, Class<T> elementType) { return parseList(json, elementType); } public static JSONArray parseArray(String json) { List<Object> items = parseList(json, Object.class); return new JSONArray(items); } public static String toJSONString(Object value) { try { return DEFAULT_OBJECT_MAPPER.writeValueAsString(value); } catch (IOException e) { throw new RuntimeException(e); } } public static String toJSONString(Object value, boolean pretty) { if (pretty) { try { return DEFAULT_OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(value); } catch (IOException e) { throw new RuntimeException(e); } } return toJSONString(value); } public static <T> List<T> parseList(String json, Class<T> elementClass) { try { JavaType javaType = DEFAULT_OBJECT_MAPPER .getTypeFactory() .constructCollectionType(ArrayList.class, elementClass); return DEFAULT_OBJECT_MAPPER.readValue(json, javaType); } catch (IOException e) { throw new RuntimeException(e); } } public static <T> List<T> parseList(String json) { try { JavaType javaType = DEFAULT_OBJECT_MAPPER .getTypeFactory() .constructCollectionType(ArrayList.class, Object.class); return DEFAULT_OBJECT_MAPPER.readValue(json, javaType); } catch (IOException e) { throw new RuntimeException(e); } } public static <K, V> Map<K, V> parseMap(String json, Class<V> valueClass) { try { MapType mapType = DEFAULT_OBJECT_MAPPER.getTypeFactory().constructMapType( HashMap.class, String.class, valueClass); return DEFAULT_OBJECT_MAPPER.readValue(json, mapType); } catch (IOException e) { throw new RuntimeException(e); } } public static <K, V> Map<K, V> parseMap(String json, Class<? extends Map> mapClass, Class<String> keyClass, Class<V> valueClass) { try { MapType mapType = DEFAULT_OBJECT_MAPPER.getTypeFactory().constructMapType( mapClass, keyClass, valueClass); return DEFAULT_OBJECT_MAPPER.readValue(json, mapType); } catch (IOException e) { throw new RuntimeException(e); } } public static Map<String, Object> parseMap(String json) { return parseMap(json, Object.class); } public static JSONObject parseObject(String json) { Map<String, Object> stringObjectMap = parseMap(json); return new JSONObject(stringObjectMap); } @Data public static class TestData { private String name; } public static class BooleanDeserializationProblemHandler extends DeserializationProblemHandler { private static final BooleanDeserializationProblemHandler INSTANCE = new BooleanDeserializationProblemHandler(); @Override public Object handleWeirdStringValue(DeserializationContext ctxt, Class<?> targetType, String valueToConvert, String failureMsg) throws IOException { if (Boolean.class.equals(targetType)) { return "1".equals(valueToConvert) || "true".equalsIgnoreCase(valueToConvert); } if (String.class.equals(targetType)) { return "1".equals(valueToConvert) || "true".equalsIgnoreCase(valueToConvert); } return super.handleWeirdStringValue(ctxt, targetType, valueToConvert, failureMsg); } @Override public Object handleWeirdNumberValue(DeserializationContext ctxt, Class<?> targetType, Number valueToConvert, String failureMsg) throws IOException { if (Boolean.class.equals(targetType)) { return valueToConvert.equals(1); } else if (String.class.equals(targetType)) { return valueToConvert.equals(1); } return super.handleWeirdNumberValue(ctxt, targetType, valueToConvert, failureMsg); } @Override public Object handleWeirdNativeValue(DeserializationContext ctxt, JavaType targetType, Object valueToConvert, JsonParser p) throws IOException { return super.handleWeirdNativeValue(ctxt, targetType, valueToConvert, p); } @Override public Object handleUnexpectedToken(DeserializationContext ctxt, Class<?> targetType, JsonToken t, JsonParser p, String failureMsg) throws IOException { if (Boolean.class.equals(targetType)) { if (t == JsonToken.VALUE_NUMBER_FLOAT) { return p.getFloatValue() > 0; } } return super.handleUnexpectedToken(ctxt, targetType, t, p, failureMsg); } } public static class CustomJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector { public static String toJSONString(Object obj) { try { return DEFAULT_OBJECT_MAPPER.writeValueAsString(obj); } catch (IOException e) { throw new RuntimeException(e); } } @Override public PropertyName findNameForSerialization(Annotated a) { PropertyName propertyName = getPropertyName(a); return propertyName != null ? propertyName : super.findNameForSerialization(a); } @Override public PropertyName findNameForDeserialization(Annotated a) { PropertyName propertyName = getPropertyName(a); return propertyName != null ? propertyName : super.findNameForDeserialization(a); } @Override public boolean isAnnotationBundle(Annotation ann) { Class<?> type = ann.annotationType(); Boolean b = _annotationsInside.get(type); if (b == null) { b = type.getAnnotation(JacksonAnnotationsInside.class) != null || type.getAnnotation(FieldProperty.class) != null; _annotationsInside.putIfAbsent(type, b); } return b; } private PropertyName getPropertyName(Annotated a) { FieldProperty FieldProperty = a.getAnnotation(FieldProperty.class); if (FieldProperty != null && !FieldProperty.ignore()) { if (StringUtil.notEmpty(FieldProperty.value())) { return PropertyName.construct(FieldProperty.value()); } if (StringUtil.notEmpty(FieldProperty.name())) { return PropertyName.construct(FieldProperty.name()); } } return null; } @Override public JsonProperty.Access findPropertyAccess(Annotated m) { JsonProperty.Access propertyAccess = super.findPropertyAccess(m); if (propertyAccess != null) { return propertyAccess; } FieldProperty annotation = m.getAnnotation(FieldProperty.class); if (annotation != null && !annotation.ignore()) { if (!annotation.serialize() && annotation.deserialize()) { return JsonProperty.Access.WRITE_ONLY; } else if (annotation.serialize() && !annotation.deserialize()) { return JsonProperty.Access.READ_ONLY; } } return null; } @Override protected boolean _isIgnorable(Annotated a) { boolean ignorable = super._isIgnorable(a); if (ignorable) { return ignorable; } FieldProperty fieldProperty = a.getAnnotation(FieldProperty.class); if (fieldProperty != null) { return fieldProperty.ignore() || (!fieldProperty.serialize() && !fieldProperty.deserialize()); } return ignorable; } @Override public Object findDeserializer(Annotated a) { Object deserializer = super.findDeserializer(a); if (deserializer == null && (a instanceof AnnotatedMethod)) { AnnotatedMethod method = (AnnotatedMethod) a; if (method.getParameterCount() == 1 && method.getRawParameterType(0) == String.class) { FieldProperty annRaw = _findAnnotation(a, FieldProperty.class); if (annRaw != null && annRaw.rowString()) { return JsonRawValueDeserializer.INSTANCE; } if (annRaw == null || annRaw.trim()) { return TrimStringDeserializer.INSTANCE; } } } return null; } } }
dolphinzhang/framework
common/src/main/java/org/dol/json/JSON.java
Java
mit
13,362
<?php namespace DataProcessingProjectBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use UserBundle\Form\UserType; class AccountController extends Controller { public function indexAction(){ $user = $this->getUser(); $em=$this->getDoctrine()->getManager(); $listApplications = $em->getRepository( 'DataProcessingProjectBundle:Application')->findBy( array( 'username' => $user->getId() )); $listAdverts= []; if ( !(empty($listApplications ))){ foreach( $listApplications as $application ){ $titre = $em->getRepository( 'DataProcessingProjectBundle:Advert')->find( $application->getAdvert()->getId() )->getTitle(); # dans un tableau, on associe l'id de la candidature au titre de l'annonce pour laquelle est faite cette candidature $listAdverts[ $application->getId() ] = $titre; } } return $this->render ( 'DataProcessingProjectBundle:Account:index.html.twig', array( 'applications' => $listApplications, 'adverts' => $listAdverts ) ); } public function editInformationsAction( Request $request ){ $user = $this->getUser(); $form = $this->createForm( UserType::class, $user ); $form->handleRequest( $request ); if ( $form->isSubmitted() && $form->isValid() ){ $request->getSession()->getFlashBag()->add( 'notice', 'Personnal Informations modified' ); $encoder = $this->container->get( 'security.password_encoder' ); $encoded = $encoder->encodePassword( $user, $user->getPassword() ); $user->setPassword( $encoded ); $em = $this->getDoctrine()->getManager(); $em->flush(); return $this->redirectToRoute( 'data_processing_project_home' ); } return $this->render( 'DataProcessingProjectBundle:Account:editPersonnalInformations.html.twig', array( 'form' => $form->createView() )); } }
celiatoulza/DataProcessingProject
src/DataProcessingProjectBundle/Controller/AccountController.php
PHP
mit
1,992
/** * @module creatine.transitions **/ (function() { "use strict"; /** * A transition effect to scroll the new scene. * * ## Usage example * * var game = new tine.Game(null, { * create: function() { * var transition = new tine.transitions.Scroll(tine.TOP, null, 1000); * game.replace(new MyScene(), transition); * } * }); * * @class Scroll * @constructor * @param {Constant} [direction=creatine.LEFT] The direction. * @param {Function} [ease=createjs.Ease.linear] An easing function from * `createjs.Ease` (provided by TweenJS). * @param {Number} [time=400] The transition time in milliseconds. **/ var Scroll = function(direction, ease, time) { /** * Direction of the effect. * @property direction * @type {Constant} **/ this.direction = direction || creatine.LEFT; /** * An Easing function from createjs.Ease. * @property ease * @type {Function} **/ this.ease = ease || createjs.Ease.linear; /** * The transition time in milliseconds. * @property time * @type {Number} **/ this.time = time || 400; } var p = Scroll.prototype; /** * Initialize the transition (called by the director). * @method start * @param {Director} director The Director instance. * @param {Scene} outScene The active scene. * @param {Scene} inScene The incoming scene. * @param {Function} callback The callback function called when the * transition is done. * @protected **/ p.start = function(director, outScene, inScene, callback) { this.director = director; this.outScene = outScene; this.inScene = inScene; this.callback = callback; var w = director.stage.canvas.width; var h = director.stage.canvas.height; var dir = this.direction; this.targetX = 0; this.targetY = 0; inScene.x = 0; inScene.y = 0; switch (this.direction) { case creatine.LEFT: inScene.x = w; this.targetX = -w; break; case creatine.RIGHT: inScene.x = -w; this.targetX = w; break; case creatine.TOP: inScene.y = h; this.targetY = -h; break; case creatine.BOTTOM: inScene.y = -h; this.targetY = h; break; } var self = this; createjs.Tween.get(inScene, {override:true}) .to({x:0, y:0}, this.time, this.ease) .call(function() { self.complete(); }) createjs.Tween.get(outScene, {override:true}) .to({x:this.targetX, y:this.targetY}, this.time, this.ease) } /** * Finalize the transition (called by the director). * @method complete * @protected **/ p.complete = function() { createjs.Tween.removeTweens(this.inScene); createjs.Tween.removeTweens(this.outScene); this.inScene.x = 0; this.inScene.x = 0; this.outScene.x = 0; this.outScene.y = 0; this.callback(); } creatine.transitions.Scroll = Scroll; }());
renatopp/creatine
src/scenes/transitions/Scroll.js
JavaScript
mit
3,100
package com.sevenheaven.zoomviewtest; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Point; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; /** * Created by caifangmao on 15/4/7. */ public class MidCircleView extends View { private Bitmap cache; private Canvas cacheCanvas; private ArrayList<Point> cachePoint; private int r = 35; private int downX; private int downY; private int drawX; private int drawY; private int scale = 10; private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); public MidCircleView(Context context) { this(context, null); } public MidCircleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MidCircleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); cache = Bitmap.createBitmap(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels, Bitmap.Config.ARGB_8888); cacheCanvas = new Canvas(cache); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: downX = (int) event.getX(); downY = (int) event.getY(); break; case MotionEvent.ACTION_MOVE: int cX = (int) event.getX(); int cY = (int) event.getY(); int dx = cX - downX; int dy = cY - downY; int distance = (int) Math.sqrt(dx * dx + dy * dy); r = distance / scale; drawX = downX / scale; drawY = downY / scale; break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: break; } invalidate(); return true; } private Point[] drawMidCircle(int centerX, int centerY, Canvas canvas, Paint paint) { ArrayList<Point> cache = new ArrayList<>(); int x, y; double d; x = 0; y = r; // d = (float) 1.25 - r; d = 0; // int upperAlpha = (int) (255 - Math.abs(d) / (float) r * 255.0F) << 24; // int lowerAlpha = 255 - upperAlpha; int lowerAlpha = ((int) (255 * (1 - DC(r, x)))) << 24; int upperAlpha = ((int) (255 * DC(r, x))) << 24; int tx = x; int ty = y - 1; paint.setColor(lowerAlpha | (paint.getColor() & 0xFFFFFF)); canvas.drawRect(x + centerX, y + centerY, x + 1 + centerX, y + 1 + centerY, paint); cache.add(new Point(x + centerX, y + centerY)); while (x < y) { Log.d("d:" + d, "x:" + x + ",y:" + y); Log.e("lowerAlpha" + lowerAlpha, "upperAlpha" + upperAlpha); paint.setColor(lowerAlpha | (paint.getColor() & 0xFFFFFF)); canvas.drawRect(y + centerX, x + centerY, y + 1 + centerX, x + 1 + centerY, paint); canvas.drawRect(y + centerX, -x + centerY, y + 1 + centerX, -x + 1 + centerY, paint); canvas.drawRect(x + centerX, -y + centerY, x + 1 + centerX, -y + 1 + centerY, paint); canvas.drawRect(-x + centerX, -y + centerY, -x + 1 + centerX, -y + 1 + centerY, paint); canvas.drawRect(-y + centerX, -x + centerY, -y + 1 + centerX, -x + 1 + centerY, paint); canvas.drawRect(-y + centerX, x + centerY, -y + 1 + centerX, x + 1 + centerY, paint); canvas.drawRect(-x + centerX, y + centerY, -x + 1 + centerX, y + 1 + centerY, paint); paint.setColor(upperAlpha | (paint.getColor() & 0xFFFFFF)); canvas.drawRect(ty + centerX, tx + centerY, ty + 1 + centerX, tx + 1 + centerY, paint); canvas.drawRect(ty + centerX, -tx + centerY, ty + 1 + centerX, -tx + 1 + centerY, paint); canvas.drawRect(tx + centerX, -ty + centerY, tx + 1 + centerX, -ty + 1 + centerY, paint); canvas.drawRect(-tx + centerX, -ty + centerY, -tx + 1 + centerX, -ty + 1 + centerY, paint); canvas.drawRect(-ty + centerX, -tx + centerY, -ty + 1 + centerX, -tx + 1 + centerY, paint); canvas.drawRect(-ty + centerX, tx + centerY, -ty + 1 + centerX, tx + 1 + centerY, paint); canvas.drawRect(-tx + centerX, ty + centerY, -tx + 1 + centerX, ty + 1 + centerY, paint); cache.add(new Point(y + centerX, x + centerY)); cache.add(new Point(y + centerX, -x + centerY)); cache.add(new Point(x + centerX, -y + centerY)); cache.add(new Point(-x + centerX, -y + centerY)); cache.add(new Point(-y + centerX, -x + centerY)); cache.add(new Point(-y + centerX, x + centerY)); cache.add(new Point(-x + centerX, y + centerY)); // if (d < 0) { // d += 2 * x + 3; // } else { // d += 2 * (x - y) + 5; // y--; // } x++; if(DC(r, x) < d){ y--; } // upperAlpha = (int) (255 - Math.abs(d) / (float) r * 255.0F) << 24; // lowerAlpha = 255 - upperAlpha; lowerAlpha = ((int) (255 * (1 - DC(r, x)))) << 24; upperAlpha = ((int) (255 * DC(r, x))) << 24; paint.setColor(lowerAlpha | (paint.getColor() & 0xFFFFFF)); canvas.drawRect(x + centerX, y + centerY, x + 1 + centerX, y + 1 + centerY, paint); paint.setColor(upperAlpha | (paint.getColor() & 0xFFFFFF)); tx = x; ty = y - 1; canvas.drawRect(tx + centerX, ty + centerY, tx + 1 + centerX, ty + 1 + centerY, paint); cache.add(new Point(x + centerX, y + centerY)); d = DC(r, x); } return cache.toArray(new Point[cache.size()]); } @Override public void onDraw(Canvas canvas) { paint.setColor(0xFFFFFFFF); paint.setStrokeWidth(1); cacheCanvas.drawRect(0, 0, cache.getWidth(), cache.getHeight(), paint); paint.setColor(0xFF0099CC); paint.setStyle(Paint.Style.STROKE); cacheCanvas.drawCircle(drawX, drawY + 30, r, paint); paint.setStyle(Paint.Style.FILL); canvas.scale(scale, scale); canvas.drawBitmap(cache, 0, 0, paint); drawMidCircle(drawX, drawY, canvas, paint); } double DC(int r, int y){ double x = Math.sqrt(r * r - y * y); return Math.ceil(x) - x; } }
7heaven/SHZoomView
app/src/main/java/com/sevenheaven/zoomviewtest/MidCircleView.java
Java
mit
6,738
<?php namespace App\Http\Controllers\Content; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class PostsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
fibers/luffy
app/Http/Controllers/Content/PostsController.php
PHP
mit
1,577
// All code points in the `Sc` category as per Unicode v6.3.0: [ 0x24, 0xA2, 0xA3, 0xA4, 0xA5, 0x58F, 0x60B, 0x9F2, 0x9F3, 0x9FB, 0xAF1, 0xBF9, 0xE3F, 0x17DB, 0x20A0, 0x20A1, 0x20A2, 0x20A3, 0x20A4, 0x20A5, 0x20A6, 0x20A7, 0x20A8, 0x20A9, 0x20AA, 0x20AB, 0x20AC, 0x20AD, 0x20AE, 0x20AF, 0x20B0, 0x20B1, 0x20B2, 0x20B3, 0x20B4, 0x20B5, 0x20B6, 0x20B7, 0x20B8, 0x20B9, 0x20BA, 0xA838, 0xFDFC, 0xFE69, 0xFF04, 0xFFE0, 0xFFE1, 0xFFE5, 0xFFE6 ];
mathiasbynens/unicode-data
6.3.0/categories/Sc-code-points.js
JavaScript
mit
489
require "sauce_whisk" SauceWhisk.data_center = :eu SauceWhisk.logger.level = Logger::DEBUG SauceWhisk::Accounts.concurrency_for "dylanatsauce"
saucelabs/sauce_whisk
test.rb
Ruby
mit
145
package org.javacs.example; /** * A class */ public class AutocompleteDocstring { public void members() { this.; } public void statics() { AutocompleteDocstring.; } /** * A fieldStatic */ public static String fieldStatic; /** * A fields */ public String fields; /** * A methodStatic */ public static String methodStatic() { return "foo"; } /** * A methods */ public String methods() { return "foo"; } }
georgewfraser/vscode-javac
src/test/examples/maven-project/src/org/javacs/example/AutocompleteDocstring.java
Java
mit
535
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package KutzCarRental.WS; import KutzCarRental.DB.DataBase; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.ejb.Stateless; import KutzCarRental.Domain.Car; import KutzCarRental.Domain.Reservation; import KutzCarRental.Utils.Utils; import java.text.ParseException; import java.util.ArrayList; /** * * @author Ileana Ontiveros */ @WebService(serviceName = "KutzCarRentalWS") @Stateless() public class KutzCarRentalWS { /** * Obtener una lista de autos para rentar */ @WebMethod(operationName = "getCars") public ArrayList<Car> getCars() { ArrayList<Car> cars = DataBase.getDB().getCarsTable(); return cars; } /** * Obtener la lista de reservaciones */ @WebMethod(operationName = "getReservations") public ArrayList<Reservation> getReservations() { ArrayList<Reservation> reservations = DataBase.getDB().getReservationsTable(); return reservations; } /** * Reservar un auto */ @WebMethod(operationName = "createReservation") public Reservation createReservation(@WebParam(name = "rentalDate") String rentalDate, @WebParam(name = "returnDate") String returnDate, @WebParam(name = "idCar") int idCar) throws ParseException { boolean isBooked = false; Reservation reservation = new Reservation(); try { Car car = DataBase.getDB().getCarById(idCar); double pricePerDay = car.getPricePerDay(); int totalDays = new Utils().calculateDays(rentalDate, returnDate); double priceTotal = totalDays*pricePerDay; reservation = new Reservation(rentalDate, returnDate, car, priceTotal); isBooked = DataBase.getDB().addReservation(reservation, idCar); return reservation; } catch (Exception e){ return reservation; } } @WebMethod(operationName = "getReservation") public Reservation getReservation(String reservationId) throws ParseException { Reservation reservation = DataBase.getDB().getReservationById(reservationId); return reservation; } /** * Obtener un auto por id */ @WebMethod(operationName = "findCarById") public Car findCarById(@WebParam(name = "idCar") int idCar) { Car car = new Car(); try { car = DataBase.getDB().getCarById(idCar); return car; } catch (Exception e){ return car; } } }
Wirwing/TopicosWeb
KutzCarRentalApplication/src/java/KutzCarRental/WS/KutzCarRentalWS.java
Java
mit
2,666
#include <amqp_tcp_socket.h> #include <amqp.h> #include <amqp_framing.h> #include <iostream> #include <thread> #include <chrono> #include <string.h> #include <signal.h> volatile bool g_running = false; void handler(int) { g_running = true; } int main(int argc, char**argv) { if(argc != 4) { std::cerr<<"usage: " << argv[0] << " <host> <messages> <size>" << std::endl; return -1; } std::string HOST(argv[1]); unsigned long MESSAGES = stoul(std::string(argv[2])); unsigned long SIZE = stoul(std::string(argv[3])); auto pub_conn = amqp_new_connection(); auto pub_socket = amqp_tcp_socket_new(pub_conn); int status = amqp_socket_open(pub_socket, HOST.c_str(), 5672); if(status) { std::cerr << "could not open " << HOST << ":5672" << std::endl; return -1; } char* data = new char[SIZE]; memset(data,'a',SIZE); amqp_bytes_t message_bytes; message_bytes.len = SIZE; message_bytes.bytes = data; amqp_rpc_reply_t response = amqp_login(pub_conn,"/",0,131072,0,AMQP_SASL_METHOD_PLAIN,"guest","guest"); if(response.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION) { std::cerr << "SERVER EXCEPTION" << std::endl; return -1; } else if (response.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION) { std::cerr << "CLIENT EXCEPTION" << std::endl; } amqp_channel_open(pub_conn,1); //amqp_confirm_select(pub_conn,1); amqp_get_rpc_reply(pub_conn); signal(SIGUSR1, handler); while(!g_running) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } auto start = std::chrono::high_resolution_clock::now(); for(int i = 0; i<MESSAGES; ++i) { amqp_basic_properties_t props; props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG; props.content_type = amqp_cstring_bytes("text/plain"); props.delivery_mode = 2; /* persistent delivery mode */ amqp_basic_publish(pub_conn,1,amqp_cstring_bytes("test-exchange"), amqp_cstring_bytes("test-queue"),0,0,&props,message_bytes); } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double,std::milli> elapsed = end-start; std::cout << "\nPublish " << MESSAGES << " complete in " << elapsed.count() << "ms (" << (MESSAGES*1000/elapsed.count()) << "/s)" << std::endl; amqp_channel_close(pub_conn,1,AMQP_REPLY_SUCCESS); amqp_connection_close(pub_conn,AMQP_REPLY_SUCCESS); }
60East/comparison-rabbitmq
rabbitmq/amqp_publisher.cpp
C++
mit
2,378
''' This script demonstrates how to create a periodic Gaussian process using the *gpiso* function. ''' import numpy as np import matplotlib.pyplot as plt from sympy import sin, exp, pi from rbf.basis import get_r, get_eps, RBF from rbf.gproc import gpiso np.random.seed(1) period = 5.0 cls = 0.5 # characteristic length scale var = 1.0 # variance r = get_r() # get symbolic variables eps = get_eps() # create a symbolic expression of the periodic covariance function expr = exp(-sin(r*pi/period)**2/eps**2) # define a periodic RBF using the symbolic expression basis = RBF(expr) # define a Gaussian process using the periodic RBF gp = gpiso(basis, eps=cls, var=var) t = np.linspace(-10, 10, 1000)[:,None] sample = gp.sample(t) # draw a sample mu,sigma = gp(t) # evaluate mean and std. dev. # plot the results fig,ax = plt.subplots(figsize=(6,4)) ax.grid(True) ax.plot(t[:,0], mu, 'b-', label='mean') ax.fill_between( t[:,0], mu - sigma, mu + sigma, color='b', alpha=0.2, edgecolor='none', label='std. dev.') ax.plot(t, sample, 'k', label='sample') ax.set_xlim((-10.0, 10.0)) ax.set_ylim((-2.5*var, 2.5*var)) ax.legend(loc=4, fontsize=10) ax.tick_params(labelsize=10) ax.set_xlabel('time', fontsize=10) ax.set_title('periodic Gaussian process', fontsize=10) fig.tight_layout() plt.savefig('../figures/gproc.e.png') plt.show()
treverhines/RBF
docs/scripts/gproc.e.py
Python
mit
1,343
<?php namespace directapi\services\adextensions\enum; use directapi\components\Enum; class ExtensionStatusSelectionEnum extends Enum { public const ACCEPTED = 'ACCEPTED'; public const DRAFT = 'DRAFT'; public const MODERATION = 'MODERATION'; public const REJECTED = 'REJECTED'; }
sitkoru/yandex-direct-api
src/services/adextensions/enum/ExtensionStatusSelectionEnum.php
PHP
mit
298
import { Node, Store, Cache } from "gatsby" /** * @see https://www.gatsbyjs.org/packages/gatsby-source-filesystem/?=files#createfilepath */ export function createFilePath(args: CreateFilePathArgs): string /** * @see https://www.gatsbyjs.org/packages/gatsby-source-filesystem/?=files#createremotefilenode */ export function createRemoteFileNode( args: CreateRemoteFileNodeArgs ): Promise<FileSystemNode> /** * @see https://www.gatsbyjs.org/packages/gatsby-source-filesystem/?=files#createfilenodefrombuffer */ export function createFileNodeFromBuffer( args: CreateFileNodeFromBufferArgs ): Promise<FileSystemNode> export interface CreateFilePathArgs { node: Node getNode: Function basePath?: string trailingSlash?: boolean } export interface CreateRemoteFileNodeArgs { url: string store: Store cache: Cache["cache"] createNode: Function createNodeId: Function parentNodeId?: string auth?: { htaccess_user: string htaccess_pass: string } httpHeaders?: object ext?: string name?: string reporter: object } export interface CreateFileNodeFromBufferArgs { buffer: Buffer store: Store cache: Cache["cache"] createNode: Function createNodeId: Function parentNodeId?: string hash?: string ext?: string name?: string } export interface FileSystemNode extends Node { absolutePath: string accessTime: string birthTime: Date changeTime: string extension: string modifiedTime: string prettySize: string relativeDirectory: string relativePath: string sourceInstanceName: string // parsed path typings base: string dir: string ext: string name: string root: string // stats atime: Date atimeMs: number birthtime: Date birthtimeMs: number ctime: Date ctimeMs: number gid: number mode: number mtime: Date mtimeMs: number size: number uid: number } export interface FileSystemConfig { resolve: "gatsby-source-filesystem" options: FileSystemOptions } /** * @see https://www.gatsbyjs.org/packages/gatsby-source-filesystem/?=filesy#options */ interface FileSystemOptions { name: string path: string ignore?: string[] }
ChristopherBiscardi/gatsby
packages/gatsby-source-filesystem/index.d.ts
TypeScript
mit
2,147
namespace BioEngine.Core.Users { public class Group { public int Id { get; set; } public string Name { get; set; } = ""; } }
BioWareRu/BioEngine
src/BioEngine.Core/Users/Group.cs
C#
mit
156
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.cmsoft.adapterexample; /** * * Represents a circle electric plug. * * @author carlos mario <carlos_programmer10@hotmail.com> * */ public class CirclePlug{ public String connectToSCircleLeftInput() { return "Circular side Left is connected..."; } public String connectToCircleRightInput() { return "Circular side right is connected..."; } }
carlosdeveloper10/AdapterPatternExample
edu/cmsoft/adapterexample/CirclePlug.java
Java
mit
614
<?php /** * WPSEO Premium plugin file. * * @package WPSEO\Premium\Classes\Redirects */ /** * Represents the filter for removing redirected entries from the sitemaps. */ class WPSEO_Redirect_Sitemap_Filter implements WPSEO_WordPress_Integration { /** * URL to the homepage. * * @var string */ protected $home_url; /** * Constructs the object. * * @param string $home_url The home url. */ public function __construct( $home_url ) { $this->home_url = $home_url; } /** * Registers the hooks. * * @return void */ public function register_hooks() { add_filter( 'wpseo_sitemap_entry', array( $this, 'filter_sitemap_entry' ) ); add_action( 'wpseo_premium_redirects_modified', array( $this, 'clear_sitemap_cache' ) ); } /** * Prevents a redirected URL from being added to the sitemap. * * @param array $url The url data. * * @return bool|array False when entry will be redirected. */ public function filter_sitemap_entry( $url ) { if ( empty( $url['loc'] ) ) { return $url; } $entry_location = str_replace( $this->home_url, '', $url['loc'] ); if ( $this->is_redirect( $entry_location ) !== false ) { return false; } return $url; } /** * Clears the sitemap cache. * * @return void */ public function clear_sitemap_cache() { WPSEO_Sitemaps_Cache::clear(); } /** * Checks if the given entry location already exists as a redirect. * * @param string $entry_location The entry location. * * @return bool Whether the entry location exists as a redirect. */ protected function is_redirect( $entry_location ) { static $redirects = null; if ( $redirects === null ) { $redirects = new WPSEO_Redirect_Option(); } return $redirects->search( $entry_location ) !== false; } }
misfit-inc/misfit.co
wp-content/plugins/wordpress-seo-premium/premium/classes/redirect/redirect-sitemap-filter.php
PHP
mit
1,780
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2013, ITU/ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ITU/ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /** \file TEncSbac.cpp \brief SBAC encoder class */ #include "TEncTop.h" #include "TEncSbac.h" #include <map> #include <algorithm> //! \ingroup TLibEncoder //! \{ // ==================================================================================================================== // Constructor / destructor / create / destroy // ==================================================================================================================== TEncSbac::TEncSbac() // new structure here : m_pcBitIf ( NULL ) , m_pcSlice ( NULL ) , m_pcBinIf ( NULL ) , m_uiCoeffCost ( 0 ) , m_numContextModels ( 0 ) , m_cCUSplitFlagSCModel ( 1, 1, NUM_SPLIT_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels ) , m_cCUSkipFlagSCModel ( 1, 1, NUM_SKIP_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUMergeFlagExtSCModel ( 1, 1, NUM_MERGE_FLAG_EXT_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUMergeIdxExtSCModel ( 1, 1, NUM_MERGE_IDX_EXT_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUPartSizeSCModel ( 1, 1, NUM_PART_SIZE_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUPredModeSCModel ( 1, 1, NUM_PRED_MODE_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUIntraPredSCModel ( 1, 1, NUM_ADI_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUChromaPredSCModel ( 1, 1, NUM_CHROMA_PRED_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUDeltaQpSCModel ( 1, 1, NUM_DELTA_QP_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUInterDirSCModel ( 1, 1, NUM_INTER_DIR_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCURefPicSCModel ( 1, 1, NUM_REF_NO_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUMvdSCModel ( 1, 1, NUM_MV_RES_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUQtCbfSCModel ( 1, 2, NUM_QT_CBF_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUTransSubdivFlagSCModel ( 1, 1, NUM_TRANS_SUBDIV_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUQtRootCbfSCModel ( 1, 1, NUM_QT_ROOT_CBF_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUSigCoeffGroupSCModel ( 1, 2, NUM_SIG_CG_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUSigSCModel ( 1, 1, NUM_SIG_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCuCtxLastX ( 1, 2, NUM_CTX_LAST_FLAG_XY , m_contextModels + m_numContextModels, m_numContextModels) , m_cCuCtxLastY ( 1, 2, NUM_CTX_LAST_FLAG_XY , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUOneSCModel ( 1, 1, NUM_ONE_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUAbsSCModel ( 1, 1, NUM_ABS_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cMVPIdxSCModel ( 1, 1, NUM_MVP_IDX_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cCUAMPSCModel ( 1, 1, NUM_CU_AMP_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cSaoMergeSCModel ( 1, 1, NUM_SAO_MERGE_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cSaoTypeIdxSCModel ( 1, 1, NUM_SAO_TYPE_IDX_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_cTransformSkipSCModel ( 1, 2, NUM_TRANSFORMSKIP_FLAG_CTX , m_contextModels + m_numContextModels, m_numContextModels) , m_CUTransquantBypassFlagSCModel( 1, 1, NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX, m_contextModels + m_numContextModels, m_numContextModels) { assert( m_numContextModels <= MAX_NUM_CTX_MOD ); } TEncSbac::~TEncSbac() { } // ==================================================================================================================== // Public member functions // ==================================================================================================================== Void TEncSbac::resetEntropy () { Int iQp = m_pcSlice->getSliceQp(); SliceType eSliceType = m_pcSlice->getSliceType(); Int encCABACTableIdx = m_pcSlice->getPPS()->getEncCABACTableIdx(); if (!m_pcSlice->isIntra() && (encCABACTableIdx==B_SLICE || encCABACTableIdx==P_SLICE) && m_pcSlice->getPPS()->getCabacInitPresentFlag()) { eSliceType = (SliceType) encCABACTableIdx; } m_cCUSplitFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG ); m_cCUSkipFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG ); m_cCUMergeFlagExtSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT); m_cCUMergeIdxExtSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT); m_cCUPartSizeSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_PART_SIZE ); m_cCUAMPSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS ); m_cCUPredModeSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_PRED_MODE ); m_cCUIntraPredSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE ); m_cCUChromaPredSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE ); m_cCUInterDirSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_INTER_DIR ); m_cCUMvdSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_MVD ); m_cCURefPicSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_REF_PIC ); m_cCUDeltaQpSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_DQP ); m_cCUQtCbfSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_QT_CBF ); m_cCUQtRootCbfSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF ); m_cCUSigCoeffGroupSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG ); m_cCUSigSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG ); m_cCuCtxLastX.initBuffer ( eSliceType, iQp, (UChar*)INIT_LAST ); m_cCuCtxLastY.initBuffer ( eSliceType, iQp, (UChar*)INIT_LAST ); m_cCUOneSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG ); m_cCUAbsSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG ); m_cMVPIdxSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_MVP_IDX ); m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG ); m_cSaoMergeSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG ); m_cSaoTypeIdxSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX ); m_cTransformSkipSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG ); m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG ); // new structure m_uiLastQp = iQp; m_pcBinIf->start(); return; } /** The function does the following: * If current slice type is P/B then it determines the distance of initialisation type 1 and 2 from the current CABAC states and * stores the index of the closest table. This index is used for the next P/B slice when cabac_init_present_flag is true. */ Void TEncSbac::determineCabacInitIdx() { Int qp = m_pcSlice->getSliceQp(); if (!m_pcSlice->isIntra()) { SliceType aSliceTypeChoices[] = {B_SLICE, P_SLICE}; UInt bestCost = MAX_UINT; SliceType bestSliceType = aSliceTypeChoices[0]; for (UInt idx=0; idx<2; idx++) { UInt curCost = 0; SliceType curSliceType = aSliceTypeChoices[idx]; curCost = m_cCUSplitFlagSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_SPLIT_FLAG ); curCost += m_cCUSkipFlagSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_SKIP_FLAG ); curCost += m_cCUMergeFlagExtSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT); curCost += m_cCUMergeIdxExtSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT); curCost += m_cCUPartSizeSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_PART_SIZE ); curCost += m_cCUAMPSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_CU_AMP_POS ); curCost += m_cCUPredModeSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_PRED_MODE ); curCost += m_cCUIntraPredSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE ); curCost += m_cCUChromaPredSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE ); curCost += m_cCUInterDirSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_INTER_DIR ); curCost += m_cCUMvdSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_MVD ); curCost += m_cCURefPicSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_REF_PIC ); curCost += m_cCUDeltaQpSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_DQP ); curCost += m_cCUQtCbfSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_QT_CBF ); curCost += m_cCUQtRootCbfSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_QT_ROOT_CBF ); curCost += m_cCUSigCoeffGroupSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_SIG_CG_FLAG ); curCost += m_cCUSigSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_SIG_FLAG ); curCost += m_cCuCtxLastX.calcCost ( curSliceType, qp, (UChar*)INIT_LAST ); curCost += m_cCuCtxLastY.calcCost ( curSliceType, qp, (UChar*)INIT_LAST ); curCost += m_cCUOneSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_ONE_FLAG ); curCost += m_cCUAbsSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_ABS_FLAG ); curCost += m_cMVPIdxSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_MVP_IDX ); curCost += m_cCUTransSubdivFlagSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG ); curCost += m_cSaoMergeSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG ); curCost += m_cSaoTypeIdxSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_SAO_TYPE_IDX ); curCost += m_cTransformSkipSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG ); curCost += m_CUTransquantBypassFlagSCModel.calcCost( curSliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG ); if (curCost < bestCost) { bestSliceType = curSliceType; bestCost = curCost; } } m_pcSlice->getPPS()->setEncCABACTableIdx( bestSliceType ); } else { m_pcSlice->getPPS()->setEncCABACTableIdx( I_SLICE ); } } /** The function does the followng: Write out terminate bit. Flush CABAC. Intialize CABAC states. Start CABAC. */ Void TEncSbac::updateContextTables( SliceType eSliceType, Int iQp, Bool bExecuteFinish ) { m_pcBinIf->encodeBinTrm(1); if (bExecuteFinish) m_pcBinIf->finish(); m_cCUSplitFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG ); m_cCUSkipFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG ); m_cCUMergeFlagExtSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT); m_cCUMergeIdxExtSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT); m_cCUPartSizeSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_PART_SIZE ); m_cCUAMPSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS ); m_cCUPredModeSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_PRED_MODE ); m_cCUIntraPredSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE ); m_cCUChromaPredSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE ); m_cCUInterDirSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_INTER_DIR ); m_cCUMvdSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_MVD ); m_cCURefPicSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_REF_PIC ); m_cCUDeltaQpSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_DQP ); m_cCUQtCbfSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_QT_CBF ); m_cCUQtRootCbfSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF ); m_cCUSigCoeffGroupSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG ); m_cCUSigSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG ); m_cCuCtxLastX.initBuffer ( eSliceType, iQp, (UChar*)INIT_LAST ); m_cCuCtxLastY.initBuffer ( eSliceType, iQp, (UChar*)INIT_LAST ); m_cCUOneSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG ); m_cCUAbsSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG ); m_cMVPIdxSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_MVP_IDX ); m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG ); m_cSaoMergeSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG ); m_cSaoTypeIdxSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX ); m_cTransformSkipSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG ); m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG ); m_pcBinIf->start(); } Void TEncSbac::codeVPS( TComVPS* pcVPS ) { assert (0); return; } Void TEncSbac::codeSPS( TComSPS* pcSPS ) { assert (0); return; } Void TEncSbac::codePPS( TComPPS* pcPPS ) { assert (0); return; } Void TEncSbac::codeSliceHeader( TComSlice* pcSlice ) { assert (0); return; } Void TEncSbac::codeTilesWPPEntryPoint( TComSlice* pSlice ) { assert (0); return; } Void TEncSbac::codeTerminatingBit( UInt uilsLast ) { m_pcBinIf->encodeBinTrm( uilsLast ); } Void TEncSbac::codeSliceFinish() { m_pcBinIf->finish(); } Void TEncSbac::xWriteUnarySymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset ) { m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[0] ); if( 0 == uiSymbol) { return; } while( uiSymbol-- ) { m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ iOffset ] ); } return; } Void TEncSbac::xWriteUnaryMaxSymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol ) { if (uiMaxSymbol == 0) { return; } m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ 0 ] ); if ( uiSymbol == 0 ) { return; } Bool bCodeLast = ( uiMaxSymbol > uiSymbol ); while( --uiSymbol ) { m_pcBinIf->encodeBin( 1, pcSCModel[ iOffset ] ); } if( bCodeLast ) { m_pcBinIf->encodeBin( 0, pcSCModel[ iOffset ] ); } return; } Void TEncSbac::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount ) { UInt bins = 0; Int numBins = 0; while( uiSymbol >= (UInt)(1<<uiCount) ) { bins = 2 * bins + 1; numBins++; uiSymbol -= 1 << uiCount; uiCount ++; } bins = 2 * bins + 0; numBins++; bins = (bins << uiCount) | uiSymbol; numBins += uiCount; assert( numBins <= 32 ); m_pcBinIf->encodeBinsEP( bins, numBins ); } /** Coding of coeff_abs_level_minus3 * \param uiSymbol value of coeff_abs_level_minus3 * \param ruiGoRiceParam reference to Rice parameter * \returns Void */ Void TEncSbac::xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam ) { Int codeNumber = (Int)symbol; UInt length; if (codeNumber < (COEF_REMAIN_BIN_REDUCTION << rParam)) { length = codeNumber>>rParam; m_pcBinIf->encodeBinsEP( (1<<(length+1))-2 , length+1); m_pcBinIf->encodeBinsEP((codeNumber%(1<<rParam)),rParam); } else { length = rParam; codeNumber = codeNumber - ( COEF_REMAIN_BIN_REDUCTION << rParam); while (codeNumber >= (1<<length)) { codeNumber -= (1<<(length++)); } m_pcBinIf->encodeBinsEP((1<<(COEF_REMAIN_BIN_REDUCTION+length+1-rParam))-2,COEF_REMAIN_BIN_REDUCTION+length+1-rParam); m_pcBinIf->encodeBinsEP(codeNumber,length); } } // SBAC RD Void TEncSbac::load ( TEncSbac* pSrc) { this->xCopyFrom(pSrc); } Void TEncSbac::loadIntraDirModeLuma( TEncSbac* pSrc) { m_pcBinIf->copyState( pSrc->m_pcBinIf ); this->m_cCUIntraPredSCModel .copyFrom( &pSrc->m_cCUIntraPredSCModel ); } Void TEncSbac::store( TEncSbac* pDest) { pDest->xCopyFrom( this ); } Void TEncSbac::xCopyFrom( TEncSbac* pSrc ) { m_pcBinIf->copyState( pSrc->m_pcBinIf ); this->m_uiCoeffCost = pSrc->m_uiCoeffCost; this->m_uiLastQp = pSrc->m_uiLastQp; memcpy( m_contextModels, pSrc->m_contextModels, m_numContextModels * sizeof( ContextModel ) ); } Void TEncSbac::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) { Int iSymbol = pcCU->getMVPIdx(eRefList, uiAbsPartIdx); Int iNum = AMVP_MAX_NUM_CANDS; xWriteUnaryMaxSymbol(iSymbol, m_cMVPIdxSCModel.get(0), 1, iNum-1); } Void TEncSbac::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) { PartSize eSize = pcCU->getPartitionSize( uiAbsPartIdx ); if ( pcCU->isIntra( uiAbsPartIdx ) ) { if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth ) { m_pcBinIf->encodeBin( eSize == SIZE_2Nx2N? 1 : 0, m_cCUPartSizeSCModel.get( 0, 0, 0 ) ); } return; } switch(eSize) { case SIZE_2Nx2N: { m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) ); break; } case SIZE_2NxN: case SIZE_2NxnU: case SIZE_2NxnD: { m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) ); m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) ); if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) ) { if (eSize == SIZE_2NxN) { m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 )); } else { m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 )); m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1)); } } break; } case SIZE_Nx2N: case SIZE_nLx2N: case SIZE_nRx2N: { m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) ); m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) ); if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) ) { m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) ); } if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) ) { if (eSize == SIZE_Nx2N) { m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 )); } else { m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 )); m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1)); } } break; } case SIZE_NxN: { if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) ) { m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) ); m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) ); m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) ); } break; } default: { assert(0); } } } /** code prediction mode * \param pcCU * \param uiAbsPartIdx * \returns Void */ Void TEncSbac::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx ) { // get context function is here Int iPredMode = pcCU->getPredictionMode( uiAbsPartIdx ); m_pcBinIf->encodeBin( iPredMode == MODE_INTER ? 0 : 1, m_cCUPredModeSCModel.get( 0, 0, 0 ) ); } Void TEncSbac::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx ) { UInt uiSymbol = pcCU->getCUTransquantBypass(uiAbsPartIdx); m_pcBinIf->encodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) ); } /** code skip flag * \param pcCU * \param uiAbsPartIdx * \returns Void */ Void TEncSbac::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx ) { // get context function is here UInt uiSymbol = pcCU->isSkipped( uiAbsPartIdx ) ? 1 : 0; UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx ) ; m_pcBinIf->encodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) ); DTRACE_CABAC_VL( g_nSymbolCounter++ ); DTRACE_CABAC_T( "\tSkipFlag" ); DTRACE_CABAC_T( "\tuiCtxSkip: "); DTRACE_CABAC_V( uiCtxSkip ); DTRACE_CABAC_T( "\tuiSymbol: "); DTRACE_CABAC_V( uiSymbol ); DTRACE_CABAC_T( "\n"); } /** code merge flag * \param pcCU * \param uiAbsPartIdx * \returns Void */ Void TEncSbac::codeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx ) { const UInt uiSymbol = pcCU->getMergeFlag( uiAbsPartIdx ) ? 1 : 0; m_pcBinIf->encodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) ); DTRACE_CABAC_VL( g_nSymbolCounter++ ); DTRACE_CABAC_T( "\tMergeFlag: " ); DTRACE_CABAC_V( uiSymbol ); DTRACE_CABAC_T( "\tAddress: " ); DTRACE_CABAC_V( pcCU->getAddr() ); DTRACE_CABAC_T( "\tuiAbsPartIdx: " ); DTRACE_CABAC_V( uiAbsPartIdx ); DTRACE_CABAC_T( "\n" ); } /** code merge index * \param pcCU * \param uiAbsPartIdx * \returns Void */ Void TEncSbac::codeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx ) { UInt uiUnaryIdx = pcCU->getMergeIndex( uiAbsPartIdx ); UInt uiNumCand = pcCU->getSlice()->getMaxNumMergeCand(); if ( uiNumCand > 1 ) { for( UInt ui = 0; ui < uiNumCand - 1; ++ui ) { const UInt uiSymbol = ui == uiUnaryIdx ? 0 : 1; if ( ui==0 ) { m_pcBinIf->encodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) ); } else { m_pcBinIf->encodeBinEP( uiSymbol ); } if( uiSymbol == 0 ) { break; } } } DTRACE_CABAC_VL( g_nSymbolCounter++ ); DTRACE_CABAC_T( "\tparseMergeIndex()" ); DTRACE_CABAC_T( "\tuiMRGIdx= " ); DTRACE_CABAC_V( pcCU->getMergeIndex( uiAbsPartIdx ) ); DTRACE_CABAC_T( "\n" ); } Void TEncSbac::codeSplitFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) { if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth ) return; UInt uiCtx = pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ); UInt uiCurrSplitFlag = ( pcCU->getDepth( uiAbsPartIdx ) > uiDepth ) ? 1 : 0; assert( uiCtx < 3 ); m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) ); DTRACE_CABAC_VL( g_nSymbolCounter++ ) DTRACE_CABAC_T( "\tSplitFlag\n" ) return; } Void TEncSbac::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx ) { m_pcBinIf->encodeBin( uiSymbol, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiCtx ) ); DTRACE_CABAC_VL( g_nSymbolCounter++ ) DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" ) DTRACE_CABAC_T( "\tsymbol=" ) DTRACE_CABAC_V( uiSymbol ) DTRACE_CABAC_T( "\tctx=" ) DTRACE_CABAC_V( uiCtx ) DTRACE_CABAC_T( "\n" ) } Void TEncSbac::codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple) { UInt dir[4],j; Int preds[4][3] = {{-1, -1, -1},{-1, -1, -1},{-1, -1, -1},{-1, -1, -1}}; Int predNum[4], predIdx[4] ={ -1,-1,-1,-1}; PartSize mode = pcCU->getPartitionSize( absPartIdx ); UInt partNum = isMultiple?(mode==SIZE_NxN?4:1):1; UInt partOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2; for (j=0;j<partNum;j++) { dir[j] = pcCU->getLumaIntraDir( absPartIdx+partOffset*j ); predNum[j] = pcCU->getIntraDirLumaPredictor(absPartIdx+partOffset*j, preds[j]); for(UInt i = 0; i < predNum[j]; i++) { if(dir[j] == preds[j][i]) { predIdx[j] = i; } } m_pcBinIf->encodeBin((predIdx[j] != -1)? 1 : 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) ); } for (j=0;j<partNum;j++) { if(predIdx[j] != -1) { m_pcBinIf->encodeBinEP( predIdx[j] ? 1 : 0 ); if (predIdx[j]) { m_pcBinIf->encodeBinEP( predIdx[j]-1 ); } } else { if (preds[j][0] > preds[j][1]) { std::swap(preds[j][0], preds[j][1]); } if (preds[j][0] > preds[j][2]) { std::swap(preds[j][0], preds[j][2]); } if (preds[j][1] > preds[j][2]) { std::swap(preds[j][1], preds[j][2]); } for(Int i = (predNum[j] - 1); i >= 0; i--) { dir[j] = dir[j] > preds[j][i] ? dir[j] - 1 : dir[j]; } m_pcBinIf->encodeBinsEP( dir[j], 5 ); } } return; } Void TEncSbac::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx ) { UInt uiIntraDirChroma = pcCU->getChromaIntraDir( uiAbsPartIdx ); if( uiIntraDirChroma == DM_CHROMA_IDX ) { m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 0 ) ); } else { UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ]; pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir ); for( Int i = 0; i < NUM_CHROMA_MODE - 1; i++ ) { if( uiIntraDirChroma == uiAllowedChromaDir[i] ) { uiIntraDirChroma = i; break; } } m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) ); m_pcBinIf->encodeBinsEP( uiIntraDirChroma, 2 ); } return; } Void TEncSbac::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx ) { const UInt uiInterDir = pcCU->getInterDir( uiAbsPartIdx ) - 1; const UInt uiCtx = pcCU->getCtxInterDir( uiAbsPartIdx ); ContextModel *pCtx = m_cCUInterDirSCModel.get( 0 ); if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N || pcCU->getHeight(uiAbsPartIdx) != 8 ) { m_pcBinIf->encodeBin( uiInterDir == 2 ? 1 : 0, *( pCtx + uiCtx ) ); } if (uiInterDir < 2) { m_pcBinIf->encodeBin( uiInterDir, *( pCtx + 4 ) ); } return; } Void TEncSbac::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) { { Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx ); ContextModel *pCtx = m_cCURefPicSCModel.get( 0 ); m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), *pCtx ); if( iRefFrame > 0 ) { UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2; pCtx++; iRefFrame--; for( UInt ui = 0; ui < uiRefNum; ++ui ) { const UInt uiSymbol = ui == iRefFrame ? 0 : 1; if( ui == 0 ) { m_pcBinIf->encodeBin( uiSymbol, *pCtx ); } else { m_pcBinIf->encodeBinEP( uiSymbol ); } if( uiSymbol == 0 ) { break; } } } } return; } Void TEncSbac::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) { if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefList == REF_PIC_LIST_1 && pcCU->getInterDir(uiAbsPartIdx)==3) { return; } const TComCUMvField* pcCUMvField = pcCU->getCUMvField( eRefList ); const Int iHor = pcCUMvField->getMvd( uiAbsPartIdx ).getHor(); const Int iVer = pcCUMvField->getMvd( uiAbsPartIdx ).getVer(); ContextModel* pCtx = m_cCUMvdSCModel.get( 0 ); m_pcBinIf->encodeBin( iHor != 0 ? 1 : 0, *pCtx ); m_pcBinIf->encodeBin( iVer != 0 ? 1 : 0, *pCtx ); const Bool bHorAbsGr0 = iHor != 0; const Bool bVerAbsGr0 = iVer != 0; const UInt uiHorAbs = 0 > iHor ? -iHor : iHor; const UInt uiVerAbs = 0 > iVer ? -iVer : iVer; pCtx++; if( bHorAbsGr0 ) { m_pcBinIf->encodeBin( uiHorAbs > 1 ? 1 : 0, *pCtx ); } if( bVerAbsGr0 ) { m_pcBinIf->encodeBin( uiVerAbs > 1 ? 1 : 0, *pCtx ); } if( bHorAbsGr0 ) { if( uiHorAbs > 1 ) { xWriteEpExGolomb( uiHorAbs-2, 1 ); } m_pcBinIf->encodeBinEP( 0 > iHor ? 1 : 0 ); } if( bVerAbsGr0 ) { if( uiVerAbs > 1 ) { xWriteEpExGolomb( uiVerAbs-2, 1 ); } m_pcBinIf->encodeBinEP( 0 > iVer ? 1 : 0 ); } return; } Void TEncSbac::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx ) { Int iDQp = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx ); Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY(); iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2); UInt uiAbsDQp = (UInt)((iDQp > 0)? iDQp : (-iDQp)); UInt TUValue = min((Int)uiAbsDQp, CU_DQP_TU_CMAX); xWriteUnaryMaxSymbol( TUValue, &m_cCUDeltaQpSCModel.get( 0, 0, 0 ), 1, CU_DQP_TU_CMAX); if( uiAbsDQp >= CU_DQP_TU_CMAX ) { xWriteEpExGolomb( uiAbsDQp - CU_DQP_TU_CMAX, CU_DQP_EG_k ); } if ( uiAbsDQp > 0) { UInt uiSign = (iDQp > 0 ? 0 : 1); m_pcBinIf->encodeBinEP(uiSign); } return; } Void TEncSbac::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth ) { UInt uiCbf = pcCU->getCbf ( uiAbsPartIdx, eType, uiTrDepth ); UInt uiCtx = pcCU->getCtxQtCbf( eType, uiTrDepth ); m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) ); DTRACE_CABAC_VL( g_nSymbolCounter++ ) DTRACE_CABAC_T( "\tparseQtCbf()" ) DTRACE_CABAC_T( "\tsymbol=" ) DTRACE_CABAC_V( uiCbf ) DTRACE_CABAC_T( "\tctx=" ) DTRACE_CABAC_V( uiCtx ) DTRACE_CABAC_T( "\tetype=" ) DTRACE_CABAC_V( eType ) DTRACE_CABAC_T( "\tuiAbsPartIdx=" ) DTRACE_CABAC_V( uiAbsPartIdx ) DTRACE_CABAC_T( "\n" ) } void TEncSbac::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType ) { if (pcCU->getCUTransquantBypass(uiAbsPartIdx)) { return; } if(width != 4 || height != 4) { return; } UInt useTransformSkip = pcCU->getTransformSkip( uiAbsPartIdx,eTType); m_pcBinIf->encodeBin( useTransformSkip, m_cTransformSkipSCModel.get( 0, eTType? TEXT_CHROMA: TEXT_LUMA, 0 ) ); DTRACE_CABAC_VL( g_nSymbolCounter++ ) DTRACE_CABAC_T("\tparseTransformSkip()"); DTRACE_CABAC_T( "\tsymbol=" ) DTRACE_CABAC_V( useTransformSkip ) DTRACE_CABAC_T( "\tAddr=" ) DTRACE_CABAC_V( pcCU->getAddr() ) DTRACE_CABAC_T( "\tetype=" ) DTRACE_CABAC_V( eTType ) DTRACE_CABAC_T( "\tuiAbsPartIdx=" ) DTRACE_CABAC_V( uiAbsPartIdx ) DTRACE_CABAC_T( "\n" ) } /** Code I_PCM information. * \param pcCU pointer to CU * \param uiAbsPartIdx CU index * \returns Void */ Void TEncSbac::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx ) { UInt uiIPCM = (pcCU->getIPCMFlag(uiAbsPartIdx) == true)? 1 : 0; Bool writePCMSampleFlag = pcCU->getIPCMFlag(uiAbsPartIdx); m_pcBinIf->encodeBinTrm (uiIPCM); if (writePCMSampleFlag) { m_pcBinIf->encodePCMAlignBits(); UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight(); UInt uiLumaOffset = uiMinCoeffSize*uiAbsPartIdx; UInt uiChromaOffset = uiLumaOffset>>2; Pel* piPCMSample; UInt uiWidth; UInt uiHeight; UInt uiSampleBits; UInt uiX, uiY; piPCMSample = pcCU->getPCMSampleY() + uiLumaOffset; uiWidth = pcCU->getWidth(uiAbsPartIdx); uiHeight = pcCU->getHeight(uiAbsPartIdx); uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthLuma(); for(uiY = 0; uiY < uiHeight; uiY++) { for(uiX = 0; uiX < uiWidth; uiX++) { UInt uiSample = piPCMSample[uiX]; m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits); } piPCMSample += uiWidth; } piPCMSample = pcCU->getPCMSampleCb() + uiChromaOffset; uiWidth = pcCU->getWidth(uiAbsPartIdx)/2; uiHeight = pcCU->getHeight(uiAbsPartIdx)/2; uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma(); for(uiY = 0; uiY < uiHeight; uiY++) { for(uiX = 0; uiX < uiWidth; uiX++) { UInt uiSample = piPCMSample[uiX]; m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits); } piPCMSample += uiWidth; } piPCMSample = pcCU->getPCMSampleCr() + uiChromaOffset; uiWidth = pcCU->getWidth(uiAbsPartIdx)/2; uiHeight = pcCU->getHeight(uiAbsPartIdx)/2; uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma(); for(uiY = 0; uiY < uiHeight; uiY++) { for(uiX = 0; uiX < uiWidth; uiX++) { UInt uiSample = piPCMSample[uiX]; m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits); } piPCMSample += uiWidth; } m_pcBinIf->resetBac(); } } Void TEncSbac::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx ) { UInt uiCbf = pcCU->getQtRootCbf( uiAbsPartIdx ); UInt uiCtx = 0; m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) ); DTRACE_CABAC_VL( g_nSymbolCounter++ ) DTRACE_CABAC_T( "\tparseQtRootCbf()" ) DTRACE_CABAC_T( "\tsymbol=" ) DTRACE_CABAC_V( uiCbf ) DTRACE_CABAC_T( "\tctx=" ) DTRACE_CABAC_V( uiCtx ) DTRACE_CABAC_T( "\tuiAbsPartIdx=" ) DTRACE_CABAC_V( uiAbsPartIdx ) DTRACE_CABAC_T( "\n" ) } Void TEncSbac::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth ) { // this function is only used to estimate the bits when cbf is 0 // and will never be called when writing the bistream. do not need to write log UInt uiCbf = 0; UInt uiCtx = pcCU->getCtxQtCbf( eType, uiTrDepth ); m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) ); } Void TEncSbac::codeQtRootCbfZero( TComDataCU* pcCU ) { // this function is only used to estimate the bits when cbf is 0 // and will never be called when writing the bistream. do not need to write log UInt uiCbf = 0; UInt uiCtx = 0; m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) ); } /** Encode (X,Y) position of the last significant coefficient * \param uiPosX X component of last coefficient * \param uiPosY Y component of last coefficient * \param width Block width * \param height Block height * \param eTType plane type / luminance or chrominance * \param uiScanIdx scan type (zig-zag, hor, ver) * This method encodes the X and Y component within a block of the last significant coefficient. */ Void TEncSbac::codeLastSignificantXY( UInt uiPosX, UInt uiPosY, Int width, Int height, TextType eTType, UInt uiScanIdx ) { // swap if( uiScanIdx == SCAN_VER ) { swap( uiPosX, uiPosY ); } UInt uiCtxLast; ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType ); ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType ); UInt uiGroupIdxX = g_uiGroupIdx[ uiPosX ]; UInt uiGroupIdxY = g_uiGroupIdx[ uiPosY ]; Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY; blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2)); blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2)); shiftX= eTType ? g_aucConvertToBit[ width ] :((g_aucConvertToBit[ width ]+3)>>2); shiftY= eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2); // posX for( uiCtxLast = 0; uiCtxLast < uiGroupIdxX; uiCtxLast++ ) { m_pcBinIf->encodeBin( 1, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) ); } if( uiGroupIdxX < g_uiGroupIdx[ width - 1 ]) { m_pcBinIf->encodeBin( 0, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) ); } // posY for( uiCtxLast = 0; uiCtxLast < uiGroupIdxY; uiCtxLast++ ) { m_pcBinIf->encodeBin( 1, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) ); } if( uiGroupIdxY < g_uiGroupIdx[ height - 1 ]) { m_pcBinIf->encodeBin( 0, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) ); } if ( uiGroupIdxX > 3 ) { UInt uiCount = ( uiGroupIdxX - 2 ) >> 1; uiPosX = uiPosX - g_uiMinInGroup[ uiGroupIdxX ]; for (Int i = uiCount - 1 ; i >= 0; i-- ) { m_pcBinIf->encodeBinEP( ( uiPosX >> i ) & 1 ); } } if ( uiGroupIdxY > 3 ) { UInt uiCount = ( uiGroupIdxY - 2 ) >> 1; uiPosY = uiPosY - g_uiMinInGroup[ uiGroupIdxY ]; for ( Int i = uiCount - 1 ; i >= 0; i-- ) { m_pcBinIf->encodeBinEP( ( uiPosY >> i ) & 1 ); } } } Void TEncSbac::codeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) { DTRACE_CABAC_VL( g_nSymbolCounter++ ) DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" ) DTRACE_CABAC_V( eTType ) DTRACE_CABAC_T( "\twidth=" ) DTRACE_CABAC_V( uiWidth ) DTRACE_CABAC_T( "\theight=" ) DTRACE_CABAC_V( uiHeight ) DTRACE_CABAC_T( "\tdepth=" ) DTRACE_CABAC_V( uiDepth ) DTRACE_CABAC_T( "\tabspartidx=" ) DTRACE_CABAC_V( uiAbsPartIdx ) DTRACE_CABAC_T( "\ttoCU-X=" ) DTRACE_CABAC_V( pcCU->getCUPelX() ) DTRACE_CABAC_T( "\ttoCU-Y=" ) DTRACE_CABAC_V( pcCU->getCUPelY() ) DTRACE_CABAC_T( "\tCU-addr=" ) DTRACE_CABAC_V( pcCU->getAddr() ) DTRACE_CABAC_T( "\tinCU-X=" ) DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] ) DTRACE_CABAC_T( "\tinCU-Y=" ) DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] ) DTRACE_CABAC_T( "\tpredmode=" ) DTRACE_CABAC_V( pcCU->getPredictionMode( uiAbsPartIdx ) ) DTRACE_CABAC_T( "\n" ) if( uiWidth > m_pcSlice->getSPS()->getMaxTrSize() ) { uiWidth = m_pcSlice->getSPS()->getMaxTrSize(); uiHeight = m_pcSlice->getSPS()->getMaxTrSize(); } UInt uiNumSig = 0; // compute number of significant coefficients uiNumSig = TEncEntropy::countNonZeroCoeffs(pcCoef, uiWidth * uiHeight); if ( uiNumSig == 0 ) return; if(pcCU->getSlice()->getPPS()->getUseTransformSkip()) { codeTransformSkipFlags( pcCU,uiAbsPartIdx, uiWidth, uiHeight, eTType ); } eTType = eTType == TEXT_LUMA ? TEXT_LUMA : ( eTType == TEXT_NONE ? TEXT_NONE : TEXT_CHROMA ); //----- encode significance map ----- const UInt uiLog2BlockSize = g_aucConvertToBit[ uiWidth ] + 2; UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx)); const UInt *scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize - 1 ]; Bool beValid; if (pcCU->getCUTransquantBypass(uiAbsPartIdx)) { beValid = false; } else { beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0; } // Find position of last coefficient Int scanPosLast = -1; Int posLast; const UInt * scanCG; { scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0 ]; if( uiLog2BlockSize == 3 ) { scanCG = g_sigLastScan8x8[ uiScanIdx ]; } else if( uiLog2BlockSize == 5 ) { scanCG = g_sigLastScanCG32x32; } } UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ]; static const UInt uiShift = MLS_CG_SIZE >> 1; const UInt uiNumBlkSide = uiWidth >> uiShift; ::memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM ); do { posLast = scan[ ++scanPosLast ]; // get L1 sig map UInt uiPosY = posLast >> uiLog2BlockSize; UInt uiPosX = posLast - ( uiPosY << uiLog2BlockSize ); UInt uiBlkIdx = uiNumBlkSide * (uiPosY >> uiShift) + (uiPosX >> uiShift); if( pcCoef[ posLast ] ) { uiSigCoeffGroupFlag[ uiBlkIdx ] = 1; } uiNumSig -= ( pcCoef[ posLast ] != 0 ); } while ( uiNumSig > 0 ); // Code position of last coefficient Int posLastY = posLast >> uiLog2BlockSize; Int posLastX = posLast - ( posLastY << uiLog2BlockSize ); codeLastSignificantXY(posLastX, posLastY, uiWidth, uiHeight, eTType, uiScanIdx); //===== code significance flag ===== ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, eTType ); ContextModel * const baseCtx = (eTType==TEXT_LUMA) ? m_cCUSigSCModel.get( 0, 0 ) : m_cCUSigSCModel.get( 0, 0 ) + NUM_SIG_FLAG_CTX_LUMA; const Int iLastScanSet = scanPosLast >> LOG2_SCAN_SET_SIZE; UInt c1 = 1; UInt uiGoRiceParam = 0; Int iScanPosSig = scanPosLast; for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- ) { Int numNonZero = 0; Int iSubPos = iSubSet << LOG2_SCAN_SET_SIZE; uiGoRiceParam = 0; Int absCoeff[16]; UInt coeffSigns = 0; Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE; if( iScanPosSig == scanPosLast ) { absCoeff[ 0 ] = abs( pcCoef[ posLast ] ); coeffSigns = ( pcCoef[ posLast ] < 0 ); numNonZero = 1; lastNZPosInCG = iScanPosSig; firstNZPosInCG = iScanPosSig; iScanPosSig--; } // encode significant_coeffgroup_flag Int iCGBlkPos = scanCG[ iSubSet ]; Int iCGPosY = iCGBlkPos / uiNumBlkSide; Int iCGPosX = iCGBlkPos - (iCGPosY * uiNumBlkSide); if( iSubSet == iLastScanSet || iSubSet == 0) { uiSigCoeffGroupFlag[ iCGBlkPos ] = 1; } else { UInt uiSigCoeffGroup = (uiSigCoeffGroupFlag[ iCGBlkPos ] != 0); UInt uiCtxSig = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight ); m_pcBinIf->encodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] ); } // encode significant_coeff_flag if( uiSigCoeffGroupFlag[ iCGBlkPos ] ) { Int patternSigCtx = TComTrQuant::calcPatternSigCtx( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight ); UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig; for( ; iScanPosSig >= iSubPos; iScanPosSig-- ) { uiBlkPos = scan[ iScanPosSig ]; uiPosY = uiBlkPos >> uiLog2BlockSize; uiPosX = uiBlkPos - ( uiPosY << uiLog2BlockSize ); uiSig = (pcCoef[ uiBlkPos ] != 0); if( iScanPosSig > iSubPos || iSubSet == 0 || numNonZero ) { uiCtxSig = TComTrQuant::getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, uiLog2BlockSize, eTType ); m_pcBinIf->encodeBin( uiSig, baseCtx[ uiCtxSig ] ); } if( uiSig ) { absCoeff[ numNonZero ] = abs( pcCoef[ uiBlkPos ] ); coeffSigns = 2 * coeffSigns + ( pcCoef[ uiBlkPos ] < 0 ); numNonZero++; if( lastNZPosInCG == -1 ) { lastNZPosInCG = iScanPosSig; } firstNZPosInCG = iScanPosSig; } } } else { iScanPosSig = iSubPos - 1; } if( numNonZero > 0 ) { Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD ); UInt uiCtxSet = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0; if( c1 == 0 ) { uiCtxSet++; } c1 = 1; ContextModel *baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUOneSCModel.get( 0, 0 ) + 4 * uiCtxSet : m_cCUOneSCModel.get( 0, 0 ) + NUM_ONE_FLAG_CTX_LUMA + 4 * uiCtxSet; Int numC1Flag = min(numNonZero, C1FLAG_NUMBER); Int firstC2FlagIdx = -1; for( Int idx = 0; idx < numC1Flag; idx++ ) { UInt uiSymbol = absCoeff[ idx ] > 1; m_pcBinIf->encodeBin( uiSymbol, baseCtxMod[c1] ); if( uiSymbol ) { c1 = 0; if (firstC2FlagIdx == -1) { firstC2FlagIdx = idx; } } else if( (c1 < 3) && (c1 > 0) ) { c1++; } } if (c1 == 0) { baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUAbsSCModel.get( 0, 0 ) + uiCtxSet : m_cCUAbsSCModel.get( 0, 0 ) + NUM_ABS_FLAG_CTX_LUMA + uiCtxSet; if ( firstC2FlagIdx != -1) { UInt symbol = absCoeff[ firstC2FlagIdx ] > 2; m_pcBinIf->encodeBin( symbol, baseCtxMod[0] ); } } if( beValid && signHidden ) { m_pcBinIf->encodeBinsEP( (coeffSigns >> 1), numNonZero-1 ); } else { m_pcBinIf->encodeBinsEP( coeffSigns, numNonZero ); } Int iFirstCoeff2 = 1; if (c1 == 0 || numNonZero > C1FLAG_NUMBER) { for ( Int idx = 0; idx < numNonZero; idx++ ) { UInt baseLevel = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2 ) : 1; if( absCoeff[ idx ] >= baseLevel) { xWriteCoefRemainExGolomb( absCoeff[ idx ] - baseLevel, uiGoRiceParam ); if(absCoeff[idx] > 3*(1<<uiGoRiceParam)) { uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4); } } if(absCoeff[ idx ] >= 2) { iFirstCoeff2 = 0; } } } } } return; } /** code SAO offset sign * \param code sign value */ Void TEncSbac::codeSAOSign( UInt code ) { m_pcBinIf->encodeBinEP( code ); } Void TEncSbac::codeSaoMaxUvlc ( UInt code, UInt maxSymbol ) { if (maxSymbol == 0) { return; } Int i; Bool bCodeLast = ( maxSymbol > code ); if ( code == 0 ) { m_pcBinIf->encodeBinEP( 0 ); } else { m_pcBinIf->encodeBinEP( 1 ); for ( i=0; i<code-1; i++ ) { m_pcBinIf->encodeBinEP( 1 ); } if( bCodeLast ) { m_pcBinIf->encodeBinEP( 0 ); } } } /** Code SAO EO class or BO band position * \param uiLength * \param uiCode */ Void TEncSbac::codeSaoUflc ( UInt uiLength, UInt uiCode ) { m_pcBinIf->encodeBinsEP ( uiCode, uiLength ); } /** Code SAO merge flags * \param uiCode * \param uiCompIdx */ Void TEncSbac::codeSaoMerge ( UInt uiCode ) { if (uiCode == 0) { m_pcBinIf->encodeBin(0, m_cSaoMergeSCModel.get( 0, 0, 0 )); } else { m_pcBinIf->encodeBin(1, m_cSaoMergeSCModel.get( 0, 0, 0 )); } } /** Code SAO type index * \param uiCode */ Void TEncSbac::codeSaoTypeIdx ( UInt uiCode) { if (uiCode == 0) { m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) ); } else { m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) ); m_pcBinIf->encodeBinEP( uiCode <= 4 ? 1 : 0 ); } } /*! **************************************************************************** * \brief * estimate bit cost for CBP, significant map and significant coefficients **************************************************************************** */ Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType ) { estCBFBit( pcEstBitsSbac ); estSignificantCoeffGroupMapBit( pcEstBitsSbac, eTType ); // encode significance map estSignificantMapBit( pcEstBitsSbac, width, height, eTType ); // encode significant coefficients estSignificantCoefficientsBit( pcEstBitsSbac, eTType ); } /*! **************************************************************************** * \brief * estimate bit cost for each CBP bit **************************************************************************** */ Void TEncSbac::estCBFBit( estBitsSbacStruct* pcEstBitsSbac ) { ContextModel *pCtx = m_cCUQtCbfSCModel.get( 0 ); for( UInt uiCtxInc = 0; uiCtxInc < 3*NUM_QT_CBF_CTX; uiCtxInc++ ) { pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 ); pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 ); } pCtx = m_cCUQtRootCbfSCModel.get( 0 ); for( UInt uiCtxInc = 0; uiCtxInc < 4; uiCtxInc++ ) { pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 ); pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 ); } } /*! **************************************************************************** * \brief * estimate SAMBAC bit cost for significant coefficient group map **************************************************************************** */ Void TEncSbac::estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, TextType eTType ) { Int firstCtx = 0, numCtx = NUM_SIG_CG_FLAG_CTX; for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ ) { for( UInt uiBin = 0; uiBin < 2; uiBin++ ) { pcEstBitsSbac->significantCoeffGroupBits[ ctxIdx ][ uiBin ] = m_cCUSigCoeffGroupSCModel.get( 0, eTType, ctxIdx ).getEntropyBits( uiBin ); } } } /*! **************************************************************************** * \brief * estimate SAMBAC bit cost for significant coefficient map **************************************************************************** */ Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType ) { Int firstCtx = 1, numCtx = 8; if (max(width, height) >= 16) { firstCtx = (eTType == TEXT_LUMA) ? 21 : 12; numCtx = (eTType == TEXT_LUMA) ? 6 : 3; } else if (width == 8) { firstCtx = 9; numCtx = (eTType == TEXT_LUMA) ? 12 : 3; } if (eTType == TEXT_LUMA ) { for( UInt bin = 0; bin < 2; bin++ ) { pcEstBitsSbac->significantBits[ 0 ][ bin ] = m_cCUSigSCModel.get( 0, 0, 0 ).getEntropyBits( bin ); } for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ ) { for( UInt uiBin = 0; uiBin < 2; uiBin++ ) { pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get( 0, 0, ctxIdx ).getEntropyBits( uiBin ); } } } else { for( UInt bin = 0; bin < 2; bin++ ) { pcEstBitsSbac->significantBits[ 0 ][ bin ] = m_cCUSigSCModel.get( 0, 0, NUM_SIG_FLAG_CTX_LUMA + 0 ).getEntropyBits( bin ); } for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ ) { for( UInt uiBin = 0; uiBin < 2; uiBin++ ) { pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get( 0, 0, NUM_SIG_FLAG_CTX_LUMA + ctxIdx ).getEntropyBits( uiBin ); } } } Int iBitsX = 0, iBitsY = 0; Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY; blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2)); blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2)); shiftX = eTType ? g_aucConvertToBit[ width ] :((g_aucConvertToBit[ width ]+3)>>2); shiftY = eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2); Int ctx; ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType ); for (ctx = 0; ctx < g_uiGroupIdx[ width - 1 ]; ctx++) { Int ctxOffset = blkSizeOffsetX + (ctx >>shiftX); pcEstBitsSbac->lastXBits[ ctx ] = iBitsX + pCtxX[ ctxOffset ].getEntropyBits( 0 ); iBitsX += pCtxX[ ctxOffset ].getEntropyBits( 1 ); } pcEstBitsSbac->lastXBits[ctx] = iBitsX; ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType ); for (ctx = 0; ctx < g_uiGroupIdx[ height - 1 ]; ctx++) { Int ctxOffset = blkSizeOffsetY + (ctx >>shiftY); pcEstBitsSbac->lastYBits[ ctx ] = iBitsY + pCtxY[ ctxOffset ].getEntropyBits( 0 ); iBitsY += pCtxY[ ctxOffset ].getEntropyBits( 1 ); } pcEstBitsSbac->lastYBits[ctx] = iBitsY; } /*! **************************************************************************** * \brief * estimate bit cost of significant coefficient **************************************************************************** */ Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, TextType eTType ) { if (eTType==TEXT_LUMA) { ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0); ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0); for (Int ctxIdx = 0; ctxIdx < NUM_ONE_FLAG_CTX_LUMA; ctxIdx++) { pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 ); pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 ); } for (Int ctxIdx = 0; ctxIdx < NUM_ABS_FLAG_CTX_LUMA; ctxIdx++) { pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 ); pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 ); } } else { ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0) + NUM_ONE_FLAG_CTX_LUMA; ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0) + NUM_ABS_FLAG_CTX_LUMA; for (Int ctxIdx = 0; ctxIdx < NUM_ONE_FLAG_CTX_CHROMA; ctxIdx++) { pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 ); pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 ); } for (Int ctxIdx = 0; ctxIdx < NUM_ABS_FLAG_CTX_CHROMA; ctxIdx++) { pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 ); pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 ); } } } /** - Initialize our context information from the nominated source. . \param pSrc From where to copy context information. */ Void TEncSbac::xCopyContextsFrom( TEncSbac* pSrc ) { memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0])); } Void TEncSbac::loadContexts ( TEncSbac* pScr) { this->xCopyContextsFrom(pScr); } //! \}
daewook/video_compression
source/Lib/TLibEncoder/TEncSbac.cpp
C++
mit
55,305
var should = require('should'), supertest = require('supertest'), testUtils = require('../../../utils/index'), localUtils = require('./utils'), config = require('../../../../server/config/index'), ghost = testUtils.startGhost, request; describe('Slug API', function () { var accesstoken = '', ghostServer; before(function () { return ghost() .then(function (_ghostServer) { ghostServer = _ghostServer; request = supertest.agent(config.get('url')); }) .then(function () { return localUtils.doAuth(request); }) .then(function (token) { accesstoken = token; }); }); it('should be able to get a post slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/post/a post title/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('a-post-title'); done(); }); }); it('should be able to get a tag slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/post/atag/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('atag'); done(); }); }); it('should be able to get a user slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/user/user name/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('user-name'); done(); }); }); it('should be able to get an app slug', function (done) { request.get(localUtils.API.getApiQuery('slugs/app/cool app/')) .set('Authorization', 'Bearer ' + accesstoken) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); var jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.slugs); jsonResponse.slugs.should.have.length(1); localUtils.API.checkResponse(jsonResponse.slugs[0], 'slug'); jsonResponse.slugs[0].slug.should.equal('cool-app'); done(); }); }); it('should not be able to get a slug for an unknown type', function (done) { request.get(localUtils.API.getApiQuery('slugs/unknown/who knows/')) .set('Authorization', 'Bearer ' + accesstoken) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(400) .end(function (err, res) { if (err) { return done(err); } var jsonResponse = res.body; should.exist(jsonResponse.errors); done(); }); }); });
Gargol/Ghost
core/test/regression/api/v0.1/slugs_spec.js
JavaScript
mit
5,073
package org.usfirst.frc.team2583.robot; import org.usfirst.frc.team2583.robot.commands.JoystickDrive; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command autonomousCommand, drive; SendableChooser chooser; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { chooser = new SendableChooser(); // chooser.addObject("My Auto", new MyAutoCommand()); SmartDashboard.putData("Auto mode", chooser); } /** * This function is called once each time the robot enters Disabled mode. * You can use it to reset any subsystem information you want to clear when * the robot is disabled. */ public void disabledInit(){ } public void disabledPeriodic() { Scheduler.getInstance().run(); } /** * This autonomous (along with the chooser code above) shows how to select between different autonomous modes * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW * Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box * below the Gyro * * You can add additional auto modes by adding additional commands to the chooser code above (like the commented example) * or additional comparisons to the switch structure below with additional strings & commands. */ public void autonomousInit() { autonomousCommand = (Command) chooser.getSelected(); if (autonomousCommand != null) autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) autonomousCommand.cancel(); drive = new JoystickDrive(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { if(!drive.isRunning())drive.start(); Scheduler.getInstance().run(); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
WestwoodRobotics/FRC-2016
2016 FRC Java/src/org/usfirst/frc/team2583/robot/Robot.java
Java
mit
3,165
namespace Magnesium { public enum MgCompareOp : byte { NEVER = 0, LESS = 1, EQUAL = 2, LESS_OR_EQUAL = 3, GREATER = 4, NOT_EQUAL = 5, GREATER_OR_EQUAL = 6, ALWAYS = 7, } }
tgsstdio/Mg
Magnesium/Enums/MgCompareOp.cs
C#
mit
198
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("MouseEvent")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("MouseEvent")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("3d825ceb-1d05-46da-9482-0d0507010b07")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
geesugar/DoubleMouseCursor
DoubleCursor/MouseEvent/Properties/AssemblyInfo.cs
C#
mit
1,362
class PacBioRun < ApplicationRecord include ResourceTools include NestedResourceTools has_associated(:study) has_associated(:sample) json do ignore( :wells ) has_nested_model(:wells) do ignore( :samples ) has_nested_model(:samples) end translate( pac_bio_run_id: :id_pac_bio_run_lims ) end end
sanger/unified_warehouse
app/models/pac_bio_run.rb
Ruby
mit
373
import * as React from 'react'; import { Component } from 'react'; import { Button, Checkbox, Icon, Table, Input, Container } from 'semantic-ui-react' import { observable, action } from "mobx"; import { observer } from "mobx-react"; import { BudgetEditorModal } from '../BudgetEditorModal'; import { lazyInject } from "../../inversify-container"; import { TYPES } from "../../inversify-types"; import { BudgetStore } from "../../stores/budgets/BudgetStore"; import { BudgetTableRow } from "../BudgetTableRow"; import { Budget } from "../../stores/budgets/model/Budget"; import { BudgetRequest } from "../../stores/budgets/model/BudgetRequest"; import * as moment from 'moment'; import { DeleteConfirmModal } from "../DeleteConfirmModal"; import { authorized } from "../authorized"; @authorized({ authenticated: true }) @observer export class BudgetsPage extends Component<{}, {}> { @lazyInject(TYPES.BudgetStore) private budgetStore: BudgetStore; @observable editing?: BudgetRequest | Budget; @observable budgetToDelete?: Budget; @action onBudgetEditClick = (budget: Budget) => { this.editing = budget.copy(); } @action onBudgetDeleteClick = (budget: Budget) => { this.budgetToDelete = budget; } @action onBudgetCreateClick = () => { this.editing = new BudgetRequest({ from: moment().startOf('year'), to: moment().endOf('year') }); } @action onModalClose = (budget: Budget | BudgetRequest) => { this.editing = undefined; } @action onModalSave = (budget: Budget | BudgetRequest) => { this.budgetStore.save(budget); this.editing = undefined; } @action onDeleteAccept = async () => { if (!this.budgetToDelete) { return; } await this.budgetStore.delete(this.budgetToDelete); this.budgetToDelete = undefined; } @action onDeleteReject = () => { this.budgetToDelete = undefined; } render() { const rows = this.budgetStore.budgets.map(it => <BudgetTableRow key={it.id} budget={it} onEditClick={this.onBudgetEditClick} onDeleteClick={this.onBudgetDeleteClick} />) const deleteMessage = this.budgetToDelete ? 'Budget ' + this.budgetToDelete.from.format('YYYY-MM') + ' to ' + this.budgetToDelete.to.format('YYYY-MM') : undefined; return ( <Container className="BudgetsPage"> <BudgetEditorModal budget={this.editing} onSave={this.onModalSave} onCancel={this.onModalClose} /> <DeleteConfirmModal message={deleteMessage} onAccept={this.onDeleteAccept} onReject={this.onDeleteReject} /> <Table celled compact> <Table.Header fullWidth> <Table.Row> <Table.HeaderCell>From</Table.HeaderCell> <Table.HeaderCell>To</Table.HeaderCell> <Table.HeaderCell>Created By</Table.HeaderCell> <Table.HeaderCell /> </Table.Row> </Table.Header> <Table.Body> {rows} </Table.Body> <Table.Footer fullWidth> <Table.Row> <Table.HeaderCell /> <Table.HeaderCell colSpan="4"> <Button icon labelPosition="left" floated="right" primary size="small" onClick={this.onBudgetCreateClick}><Icon name="plus" /> Add Budget</Button> </Table.HeaderCell> </Table.Row> </Table.Footer> </Table> </Container> ) } }
jacob-swanson/budgety
budgety-web/src/components/pages/BudgetsPage.tsx
TypeScript
mit
3,736
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'lu-split-select', templateUrl: './split-select.component.html' }) export class SplitSelectComponent { item = { id: 1, name: 'initial value' }; option = { id: 2, name: 'option' }; formControl = new FormControl(); }
LuccaSA/lucca-front
to-migrate/ng/split-select/split-select.component.ts
TypeScript
mit
333
package com.ricex.cartracker.common.util; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.ricex.cartracker.common.entity.auth.User; import com.ricex.cartracker.common.viewmodel.auth.UserViewModel; import com.ricex.cartracker.common.viewmodel.auth.UserViewModelImpl; public class JsonUserAdapter implements JsonSerializer<User> { public JsonElement serialize(User source, Type type, JsonSerializationContext context) { return context.serialize(source.toViewModel()); } }
mwcaisse/CarTracker
CarTracker.Common/src/main/java/com/ricex/cartracker/common/util/JsonUserAdapter.java
Java
mit
733
function Grid(size) { this.size = size; this.startTiles = 2; this.cells = []; this.build(); this.playerTurn = true; } // pre-allocate these objects (for speed) Grid.prototype.indexes = []; for (var x=0; x<4; x++) { Grid.prototype.indexes.push([]); for (var y=0; y<4; y++) { Grid.prototype.indexes[x].push( {x:x, y:y} ); } } // Build a grid of the specified size Grid.prototype.build = function () { for (var x = 0; x < this.size; x++) { var row = this.cells[x] = []; for (var y = 0; y < this.size; y++) { row.push(null); } } }; // Find the first available random position Grid.prototype.randomAvailableCell = function () { var cells = this.availableCells(); if (cells.length) { return cells[Math.floor(Math.random() * cells.length)]; } }; Grid.prototype.availableCells = function () { var cells = []; var self = this; this.eachCell(function (x, y, tile) { if (!tile) { //cells.push(self.indexes[x][y]); cells.push( {x:x, y:y} ); } }); return cells; }; // Call callback for every cell Grid.prototype.eachCell = function (callback) { for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { callback(x, y, this.cells[x][y]); } } }; // Check if there are any cells available Grid.prototype.cellsAvailable = function () { return !!this.availableCells().length; }; // Check if the specified cell is taken Grid.prototype.cellAvailable = function (cell) { return !this.cellOccupied(cell); }; Grid.prototype.cellOccupied = function (cell) { return !!this.cellContent(cell); }; Grid.prototype.cellContent = function (cell) { if (this.withinBounds(cell)) { return this.cells[cell.x][cell.y]; } else { return null; } }; // Inserts a tile at its position Grid.prototype.insertTile = function (tile) { this.cells[tile.x][tile.y] = tile; }; Grid.prototype.removeTile = function (tile) { this.cells[tile.x][tile.y] = null; }; Grid.prototype.withinBounds = function (position) { return position.x >= 0 && position.x < this.size && position.y >= 0 && position.y < this.size; }; Grid.prototype.clone = function() { newGrid = new Grid(this.size); newGrid.playerTurn = this.playerTurn; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { if (this.cells[x][y]) { newGrid.insertTile(this.cells[x][y].clone()); } } } return newGrid; }; // Set up the initial tiles to start the game with Grid.prototype.addStartTiles = function () { for (var i=0; i<this.startTiles; i++) { this.addRandomTile(); } }; // Adds a tile in a random position Grid.prototype.addRandomTile = function () { if (this.cellsAvailable()) { var value = Math.random() < 0.9 ? 2 : 4; //var value = Math.random() < 0.9 ? 256 : 512; var tile = new Tile(this.randomAvailableCell(), value); this.insertTile(tile); } }; // Save all tile positions and remove merger info Grid.prototype.prepareTiles = function () { this.eachCell(function (x, y, tile) { if (tile) { tile.mergedFrom = null; tile.savePosition(); } }); }; // Move a tile and its representation Grid.prototype.moveTile = function (tile, cell) { this.cells[tile.x][tile.y] = null; this.cells[cell.x][cell.y] = tile; tile.updatePosition(cell); }; Grid.prototype.vectors = { 0: { x: 0, y: -1 }, // up 1: { x: 1, y: 0 }, // right 2: { x: 0, y: 1 }, // down 3: { x: -1, y: 0 } // left } // Get the vector representing the chosen direction Grid.prototype.getVector = function (direction) { // Vectors representing tile movement return this.vectors[direction]; }; // Move tiles on the grid in the specified direction // returns true if move was successful Grid.prototype.move = function (direction) { // 0: up, 1: right, 2:down, 3: left var self = this; var cell, tile; var vector = this.getVector(direction); var traversals = this.buildTraversals(vector); var moved = false; var score = 0; var won = false; // Save the current tile positions and remove merger information this.prepareTiles(); // Traverse the grid in the right direction and move tiles traversals.x.forEach(function (x) { traversals.y.forEach(function (y) { cell = self.indexes[x][y]; tile = self.cellContent(cell); if (tile) { //if (debug) { //console.log('tile @', x, y); //} var positions = self.findFarthestPosition(cell, vector); var next = self.cellContent(positions.next); // Only one merger per row traversal? if (next && next.value === tile.value && !next.mergedFrom) { var merged = new Tile(positions.next, tile.value * 2); merged.mergedFrom = [tile, next]; self.insertTile(merged); self.removeTile(tile); // Converge the two tiles' positions tile.updatePosition(positions.next); // Update the score score += merged.value; // The mighty 2048 tile if (merged.value === 2048) { won = true; } } else { //if (debug) { //console.log(cell); //console.log(tile); //} self.moveTile(tile, positions.farthest); } if (!self.positionsEqual(cell, tile)) { self.playerTurn = false; //console.log('setting player turn to ', self.playerTurn); moved = true; // The tile moved from its original cell! } } }); }); //console.log('returning, playerturn is', self.playerTurn); //if (!moved) { //console.log('cell', cell); //console.log('tile', tile); //console.log('direction', direction); //console.log(this.toString()); //} return {moved: moved, score: score, won: won}; }; Grid.prototype.computerMove = function() { this.addRandomTile(); this.playerTurn = true; } // Build a list of positions to traverse in the right order Grid.prototype.buildTraversals = function (vector) { var traversals = { x: [], y: [] }; for (var pos = 0; pos < this.size; pos++) { traversals.x.push(pos); traversals.y.push(pos); } // Always traverse from the farthest cell in the chosen direction if (vector.x === 1) traversals.x = traversals.x.reverse(); if (vector.y === 1) traversals.y = traversals.y.reverse(); return traversals; }; Grid.prototype.findFarthestPosition = function (cell, vector) { var previous; // Progress towards the vector direction until an obstacle is found do { previous = cell; cell = { x: previous.x + vector.x, y: previous.y + vector.y }; } while (this.withinBounds(cell) && this.cellAvailable(cell)); return { farthest: previous, next: cell // Used to check if a merge is required }; }; Grid.prototype.movesAvailable = function () { return this.cellsAvailable() || this.tileMatchesAvailable(); }; // Check for available matches between tiles (more expensive check) // returns the number of matches Grid.prototype.tileMatchesAvailable = function () { var self = this; //var matches = 0; var tile; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { tile = this.cellContent({ x: x, y: y }); if (tile) { for (var direction = 0; direction < 4; direction++) { var vector = self.getVector(direction); var cell = { x: x + vector.x, y: y + vector.y }; var other = self.cellContent(cell); if (other && other.value === tile.value) { return true; //matches++; // These two tiles can be merged } } } } } //console.log(matches); return false; //matches; }; Grid.prototype.positionsEqual = function (first, second) { return first.x === second.x && first.y === second.y; }; Grid.prototype.toString = function() { string = ''; for (var i=0; i<4; i++) { for (var j=0; j<4; j++) { if (this.cells[j][i]) { string += this.cells[j][i].value + ' '; } else { string += '_ '; } } string += '\n'; } return string; } // counts the number of isolated groups. Grid.prototype.islands = function() { var self = this; var mark = function(x, y, value) { if (x >= 0 && x <= 3 && y >= 0 && y <= 3 && self.cells[x][y] && self.cells[x][y].value == value && !self.cells[x][y].marked ) { self.cells[x][y].marked = true; for (direction in [0,1,2,3]) { var vector = self.getVector(direction); mark(x + vector.x, y + vector.y, value); } } } var islands = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cells[x][y]) { this.cells[x][y].marked = false } } } for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cells[x][y] && !this.cells[x][y].marked) { islands++; mark(x, y , this.cells[x][y].value); } } } return islands; } /// measures how smooth the grid is (as if the values of the pieces // were interpreted as elevations). Sums of the pairwise difference // between neighboring tiles (in log space, so it represents the // number of merges that need to happen before they can merge). // Note that the pieces can be distant Grid.prototype.smoothness = function() { var smoothness = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if ( this.cellOccupied( this.indexes[x][y] )) { var value = Math.log(this.cellContent( this.indexes[x][y] ).value) / Math.log(2); for (var direction=1; direction<=2; direction++) { var vector = this.getVector(direction); var targetCell = this.findFarthestPosition(this.indexes[x][y], vector).next; if (this.cellOccupied(targetCell)) { var target = this.cellContent(targetCell); var targetValue = Math.log(target.value) / Math.log(2); smoothness -= Math.abs(value - targetValue); } } } } } return smoothness; } Grid.prototype.monotonicity = function() { var self = this; var marked = []; var queued = []; var highestValue = 0; var highestCell = {x:0, y:0}; for (var x=0; x<4; x++) { marked.push([]); queued.push([]); for (var y=0; y<4; y++) { marked[x].push(false); queued[x].push(false); if (this.cells[x][y] && this.cells[x][y].value > highestValue) { highestValue = this.cells[x][y].value; highestCell.x = x; highestCell.y = y; } } } increases = 0; cellQueue = [highestCell]; queued[highestCell.x][highestCell.y] = true; markList = [highestCell]; markAfter = 1; // only mark after all queued moves are done, as if searching in parallel var markAndScore = function(cell) { markList.push(cell); var value; if (self.cellOccupied(cell)) { value = Math.log(self.cellContent(cell).value) / Math.log(2); } else { value = 0; } for (direction in [0,1,2,3]) { var vector = self.getVector(direction); var target = { x: cell.x + vector.x, y: cell.y+vector.y } if (self.withinBounds(target) && !marked[target.x][target.y]) { if ( self.cellOccupied(target) ) { targetValue = Math.log(self.cellContent(target).value ) / Math.log(2); if ( targetValue > value ) { //console.log(cell, value, target, targetValue); increases += targetValue - value; } } if (!queued[target.x][target.y]) { cellQueue.push(target); queued[target.x][target.y] = true; } } } if (markAfter == 0) { while (markList.length > 0) { var cel = markList.pop(); marked[cel.x][cel.y] = true; } markAfter = cellQueue.length; } } while (cellQueue.length > 0) { markAfter--; markAndScore(cellQueue.shift()) } return -increases; } // measures how monotonic the grid is. This means the values of the tiles are strictly increasing // or decreasing in both the left/right and up/down directions Grid.prototype.monotonicity2 = function() { // scores for all four directions var totals = [0, 0, 0, 0]; // up/down direction for (var x=0; x<4; x++) { var current = 0; var next = current+1; while ( next<4 ) { while ( next<4 && !this.cellOccupied( this.indexes[x][next] )) { next++; } if (next>=4) { next--; } var currentValue = this.cellOccupied({x:x, y:current}) ? Math.log(this.cellContent( this.indexes[x][current] ).value) / Math.log(2) : 0; var nextValue = this.cellOccupied({x:x, y:next}) ? Math.log(this.cellContent( this.indexes[x][next] ).value) / Math.log(2) : 0; if (currentValue > nextValue) { totals[0] += nextValue - currentValue; } else if (nextValue > currentValue) { totals[1] += currentValue - nextValue; } current = next; next++; } } // left/right direction for (var y=0; y<4; y++) { var current = 0; var next = current+1; while ( next<4 ) { while ( next<4 && !this.cellOccupied( this.indexes[next][y] )) { next++; } if (next>=4) { next--; } var currentValue = this.cellOccupied({x:current, y:y}) ? Math.log(this.cellContent( this.indexes[current][y] ).value) / Math.log(2) : 0; var nextValue = this.cellOccupied({x:next, y:y}) ? Math.log(this.cellContent( this.indexes[next][y] ).value) / Math.log(2) : 0; if (currentValue > nextValue) { totals[2] += nextValue - currentValue; } else if (nextValue > currentValue) { totals[3] += currentValue - nextValue; } current = next; next++; } } return Math.max(totals[0], totals[1]) + Math.max(totals[2], totals[3]); } Grid.prototype.maxValue = function() { var max = 0; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cellOccupied(this.indexes[x][y])) { var value = this.cellContent(this.indexes[x][y]).value; if (value > max) { max = value; } } } } return Math.log(max) / Math.log(2); } // WIP. trying to favor top-heavy distributions (force consolidation of higher value tiles) /* Grid.prototype.valueSum = function() { var valueCount = []; for (var i=0; i<11; i++) { valueCount.push(0); } for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (this.cellOccupied(this.indexes[x][y])) { valueCount[Math.log(this.cellContent(this.indexes[x][y]).value) / Math.log(2)]++; } } } var sum = 0; for (var i=1; i<11; i++) { sum += valueCount[i] * Math.pow(2, i) + i; } return sum; } */ // check for win Grid.prototype.isWin = function() { var self = this; for (var x=0; x<4; x++) { for (var y=0; y<4; y++) { if (self.cellOccupied(this.indexes[x][y])) { if (self.cellContent(this.indexes[x][y]).value == 2048) { return true; } } } } return false; } //Grid.prototype.zobristTable = {} //for //Grid.prototype.hash = function() { //}
Kelly27/my2048
js/grid.js
JavaScript
mit
15,249
/* * Favorites * Favorites landing page */ import React, { Component } from 'react' import NavBar from '../NavBar.react' export default class Favorites extends Component { render() { return ( <div> <div className="p2 overflow-scroll mt4 mb4"> <div className="center mb3"> <button className="btn bg-purple-3 white regular py1 px3">Import from Spotify</button> </div> <div className="h6 caps white">Your favorites</div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Let's Dance</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Lazarus</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Let's Dance</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Lazarus</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Let's Dance</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Lazarus</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Let's Dance</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4 mb1">Lazarus</div> <div className="white muted h6 semibold">David Bowie</div> <span className="white absolute right-0 h2 mr3" style={{top: '23px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>5 events</span> › </span> </div> </div> <NavBar activeTab="favorites"/> </div> ) } }
chexee/karaoke-night
js/components/pages/Favorites.react.js
JavaScript
mit
4,396
// Base Grab Attach|GrabAttachMechanics|50010 namespace VRTK.GrabAttachMechanics { using UnityEngine; /// <summary> /// Provides a base that all grab attach mechanics can inherit from. /// </summary> /// <remarks> /// **Script Usage:** /// > This is an abstract class that is to be inherited to a concrete class that provides grab attach functionality, therefore this script should not be directly used. /// </remarks> public abstract class VRTK_BaseGrabAttach : MonoBehaviour { [Header("Base Settings", order = 1)] [Tooltip("If this is checked then when the Interact Grab grabs the Interactable Object, it will grab it with precision and pick it up at the particular point on the Interactable Object that the Interact Touch is touching.")] public bool precisionGrab; [Tooltip("A Transform provided as an empty GameObject which must be the child of the Interactable Object being grabbed and serves as an orientation point to rotate and position the grabbed Interactable Object in relation to the right handed Interact Grab. If no Right Snap Handle is provided but a Left Snap Handle is provided, then the Left Snap Handle will be used in place. If no Snap Handle is provided then the Interactable Object will be grabbed at its central point. Not required for `Precision Grab`.")] public Transform rightSnapHandle; [Tooltip("A Transform provided as an empty GameObject which must be the child of the Interactable Object being grabbed and serves as an orientation point to rotate and position the grabbed Interactable Object in relation to the left handed Interact Grab. If no Left Snap Handle is provided but a Right Snap Handle is provided, then the Right Snap Handle will be used in place. If no Snap Handle is provided then the Interactable Object will be grabbed at its central point. Not required for `Precision Grab`.")] public Transform leftSnapHandle; [Tooltip("If checked then when the Interactable Object is thrown, the distance between the Interactable Object's attach point and the Interact Grab's attach point will be used to calculate a faster throwing velocity.")] public bool throwVelocityWithAttachDistance = false; [Tooltip("An amount to multiply the velocity of the given Interactable Object when it is thrown. This can also be used in conjunction with the Interact Grab Throw Multiplier to have certain Interactable Objects be thrown even further than normal (or thrown a shorter distance if a number below 1 is entered).")] public float throwMultiplier = 1f; [Tooltip("The amount of time to delay collisions affecting the Interactable Object when it is first grabbed. This is useful if the Interactable Object could get stuck inside another GameObject when it is being grabbed.")] public float onGrabCollisionDelay = 0f; protected bool tracked; protected bool climbable; protected bool kinematic; protected GameObject grabbedObject; protected Rigidbody grabbedObjectRigidBody; protected VRTK_InteractableObject grabbedObjectScript; protected Transform trackPoint; protected Transform grabbedSnapHandle; protected Transform initialAttachPoint; protected Rigidbody controllerAttachPoint; /// <summary> /// The IsTracked method determines if the grab attach mechanic is a track object type. /// </summary> /// <returns>Is true if the mechanic is of type tracked.</returns> public virtual bool IsTracked() { return tracked; } /// <summary> /// The IsClimbable method determines if the grab attach mechanic is a climbable object type. /// </summary> /// <returns>Is true if the mechanic is of type climbable.</returns> public virtual bool IsClimbable() { return climbable; } /// <summary> /// The IsKinematic method determines if the grab attach mechanic is a kinematic object type. /// </summary> /// <returns>Is true if the mechanic is of type kinematic.</returns> public virtual bool IsKinematic() { return kinematic; } /// <summary> /// The ValidGrab method determines if the grab attempt is valid. /// </summary> /// <param name="checkAttachPoint">The rigidbody attach point to check.</param> /// <returns>Always returns `true` for the base check.</returns> public virtual bool ValidGrab(Rigidbody checkAttachPoint) { return true; } /// <summary> /// The SetTrackPoint method sets the point on the grabbed Interactable Object where the grab is happening. /// </summary> /// <param name="givenTrackPoint">The track point to set on the grabbed Interactable Object.</param> public virtual void SetTrackPoint(Transform givenTrackPoint) { trackPoint = givenTrackPoint; } /// <summary> /// The SetInitialAttachPoint method sets the point on the grabbed Interactable Object where the initial grab happened. /// </summary> /// <param name="givenInitialAttachPoint">The point where the initial grab took place.</param> public virtual void SetInitialAttachPoint(Transform givenInitialAttachPoint) { initialAttachPoint = givenInitialAttachPoint; } /// <summary> /// The StartGrab method sets up the grab attach mechanic as soon as an Interactable Object is grabbed. /// </summary> /// <param name="grabbingObject">The GameObject that is doing the grabbing.</param> /// <param name="givenGrabbedObject">The GameObject that is being grabbed.</param> /// <param name="givenControllerAttachPoint">The point on the grabbing object that the grabbed object should be attached to after grab occurs.</param> /// <returns>Returns `true` if the grab is successful, `false` if the grab is unsuccessful.</returns> public virtual bool StartGrab(GameObject grabbingObject, GameObject givenGrabbedObject, Rigidbody givenControllerAttachPoint) { grabbedObject = givenGrabbedObject; if (grabbedObject == null) { return false; } grabbedObjectScript = grabbedObject.GetComponent<VRTK_InteractableObject>(); grabbedObjectRigidBody = grabbedObject.GetComponent<Rigidbody>(); controllerAttachPoint = givenControllerAttachPoint; grabbedSnapHandle = GetSnapHandle(grabbingObject); ProcessSDKTransformModify(VRTK_ControllerReference.GetControllerReference(grabbingObject)); grabbedObjectScript.PauseCollisions(onGrabCollisionDelay); return true; } /// <summary> /// The StopGrab method ends the grab of the current Interactable Object and cleans up the state. /// </summary> /// <param name="applyGrabbingObjectVelocity">If `true` will apply the current velocity of the grabbing object to the grabbed object on release.</param> public virtual void StopGrab(bool applyGrabbingObjectVelocity) { grabbedObject = null; grabbedObjectScript = null; trackPoint = null; grabbedSnapHandle = null; initialAttachPoint = null; controllerAttachPoint = null; } /// <summary> /// The CreateTrackPoint method sets up the point of grab to track on the grabbed object. /// </summary> /// <param name="controllerPoint">The point on the controller where the grab was initiated.</param> /// <param name="currentGrabbedObject">The GameObject that is currently being grabbed.</param> /// <param name="currentGrabbingObject">The GameObject that is currently doing the grabbing.</param> /// <param name="customTrackPoint">A reference to whether the created track point is an auto generated custom object.</param> /// <returns>The Transform of the created track point.</returns> public virtual Transform CreateTrackPoint(Transform controllerPoint, GameObject currentGrabbedObject, GameObject currentGrabbingObject, ref bool customTrackPoint) { customTrackPoint = false; return controllerPoint; } /// <summary> /// The ProcessUpdate method is run in every Update method on the Interactable Object. /// </summary> public virtual void ProcessUpdate() { } /// <summary> /// The ProcessFixedUpdate method is run in every FixedUpdate method on the Interactable Object. /// </summary> public virtual void ProcessFixedUpdate() { } /// <summary> /// The ResetState method re-initializes the grab attach. /// </summary> public virtual void ResetState() { Initialise(); } protected virtual void Awake() { ResetState(); } protected abstract void Initialise(); protected virtual Rigidbody ReleaseFromController(bool applyGrabbingObjectVelocity) { return grabbedObjectRigidBody; } protected virtual void ForceReleaseGrab() { if (grabbedObjectScript) { GameObject grabbingObject = grabbedObjectScript.GetGrabbingObject(); if (grabbingObject != null) { VRTK_InteractGrab grabbingObjectScript = grabbingObject.GetComponentInChildren<VRTK_InteractGrab>(); if (grabbingObjectScript != null) { grabbingObjectScript.ForceRelease(); } } } } protected virtual void ReleaseObject(bool applyGrabbingObjectVelocity) { Rigidbody releasedObjectRigidBody = ReleaseFromController(applyGrabbingObjectVelocity); if (releasedObjectRigidBody != null && applyGrabbingObjectVelocity) { ThrowReleasedObject(releasedObjectRigidBody); } } protected virtual void ThrowReleasedObject(Rigidbody objectRigidbody) { if (grabbedObjectScript != null) { VRTK_ControllerReference controllerReference = VRTK_ControllerReference.GetControllerReference(grabbedObjectScript.GetGrabbingObject()); if (VRTK_ControllerReference.IsValid(controllerReference) && controllerReference.scriptAlias != null) { VRTK_InteractGrab grabbingObjectScript = controllerReference.scriptAlias.GetComponentInChildren<VRTK_InteractGrab>(); if (grabbingObjectScript != null) { Transform origin = VRTK_DeviceFinder.GetControllerOrigin(controllerReference); Vector3 velocity = VRTK_DeviceFinder.GetControllerVelocity(controllerReference); Vector3 angularVelocity = VRTK_DeviceFinder.GetControllerAngularVelocity(controllerReference); float grabbingObjectThrowMultiplier = grabbingObjectScript.throwMultiplier; if (origin != null) { objectRigidbody.velocity = origin.TransformVector(velocity) * (grabbingObjectThrowMultiplier * throwMultiplier); objectRigidbody.angularVelocity = origin.TransformDirection(angularVelocity); } else { objectRigidbody.velocity = velocity * (grabbingObjectThrowMultiplier * throwMultiplier); objectRigidbody.angularVelocity = angularVelocity; } if (throwVelocityWithAttachDistance) { Collider rigidbodyCollider = objectRigidbody.GetComponentInChildren<Collider>(); if (rigidbodyCollider != null) { Vector3 collisionCenter = rigidbodyCollider.bounds.center; objectRigidbody.velocity = objectRigidbody.GetPointVelocity(collisionCenter + (collisionCenter - transform.position)); } else { objectRigidbody.velocity = objectRigidbody.GetPointVelocity(objectRigidbody.position + (objectRigidbody.position - transform.position)); } } } } } } protected virtual Transform GetSnapHandle(GameObject grabbingObject) { if (rightSnapHandle == null && leftSnapHandle != null) { rightSnapHandle = leftSnapHandle; } if (leftSnapHandle == null && rightSnapHandle != null) { leftSnapHandle = rightSnapHandle; } if (VRTK_DeviceFinder.IsControllerRightHand(grabbingObject)) { return rightSnapHandle; } if (VRTK_DeviceFinder.IsControllerLeftHand(grabbingObject)) { return leftSnapHandle; } return null; } protected virtual void ProcessSDKTransformModify(VRTK_ControllerReference controllerReference) { if (VRTK_ControllerReference.IsValid(controllerReference)) { VRTK_SDKTransformModify transformModify = grabbedObject.GetComponentInChildren<VRTK_SDKTransformModify>(); if (transformModify != null) { transformModify.UpdateTransform(controllerReference); } } } } }
Fulby/VRTK
Assets/VRTK/Source/Scripts/Interactions/Interactables/GrabAttachMechanics/VRTK_BaseGrabAttach.cs
C#
mit
14,159
function generateList(people, template){ var i, result = '', len = people.length; result += '<ul>'; for(i = 0; i < len; i += 1){ result += '<li>'; result += template; result = result.replace('-{name}-', people[i]['name']); result = result.replace('-{age}-', people[i]['age']); result += '</li>'; } result += '</ul>'; return result; } var people = [ { name: 'Pehso', age: 20}, { name: 'Gosho', age: 30}, { name: 'Stamat', age: 25} ]; var template = document.getElementById('list-item').innerHTML; document.getElementById('list-item').innerHTML = generateList(people, template);
ni4ka7a/TelerikAcademyHomeworks
JavaScript-Fundamentals/09.Strings/12.GenerateList/script.js
JavaScript
mit
681
class AddWinnerToEvents < ActiveRecord::Migration def change add_column :events, :winner, :integer end end
aceburgess/Food-r
db/migrate/20150503185302_add_winner_to_events.rb
Ruby
mit
115
const admin = require('firebase-admin'); const DATABASE_URL = process.env.DATABASE_URL || 'https://dailyjack-8a930.firebaseio.com'; // const DATABASE_URL = 'https://dailyjack-d2fa0.firebaseio.com'; const jackDB = (config = {}) => { const app = admin.initializeApp({ credential: admin.credential.cert({ projectId: config.projectId, clientEmail: config.clientEmail, privateKey: config.privateKey, }), databaseURL: DATABASE_URL, }); const db = admin.database(); const jacksRef = db.ref('jacks'); const totalJacksRef = db.ref('totalJacks'); const usersRef = db.ref('users'); const insert = jack => ( jacksRef .child(jack.id) .set({ id: jack.id, title: jack.title, contents: jack.contents || [], author: jack.author || null, createdTime: Date.now(), isLimited: Boolean(jack.isLimited), isSpecial: Boolean(jack.isSpecial), }) .then(() => ( totalJacksRef.transaction(total => (total || 0) + 1) )) ); const filter = (jacks = [], filterOptions = {}) => jacks.filter( jack => (!filterOptions.shouldExcludeLimited || !jack.isLimited) && (!filterOptions.shouldExcludeSpecial || !jack.isSpecial) ); const all = (filterOptions = {}) => ( jacksRef.once('value') .then(snapshot => snapshot.val()) .then(jacks => (jacks || []).filter(Boolean)) .then(jacks => filter(jacks, filterOptions)) ); const get = id => ( jacksRef.child(id) .once('value') .then(snapshot => snapshot.val()) ); const random = (filterOptions = {}) => ( all(filterOptions) .then(jacks => jacks[Math.floor(Math.random() * jacks.length)]) ); const upvote = (id, user) => ( jacksRef.child(id) .child('ratedUsers') .child(user) .set(true) ); const downvote = (id, user) => ( jacksRef.child(id) .child('ratedUsers') .remove(user) ); const togglevote = (id, user) => ( jacksRef.child(id) .child('ratedUsers') .child(user) .transaction(rate => (rate ? null : true)) ); const getRate = id => ( jacksRef.child(id) .child('ratedUsers') .once('value') .then(snapshot => snapshot.val()) .then(rate => Object.keys(rate || {}) .filter(Boolean) .length ) ); const setUser = user => ( usersRef.child(user.name) .set(user) ); const updateUser = user => ( usersRef.child(user.name) .update(user) ); const getUser = userName => ( usersRef.child(userName) .once('value') .then(snapshot => snapshot.val()) ); const exit = () => { db.goOffline(); app.delete(); }; return { all, get, random, insert, exit, upvote, downvote, togglevote, getRate, setUser, updateUser, getUser, }; }; module.exports = { default: jackDB, };
kevin940726/dailyjack
packages/dailyjack-core/index.js
JavaScript
mit
2,926
package com.thoughtworks.securityinourdna; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class JdbcInvoiceRepo implements InvoiceRepo { private final Connection connection; public JdbcInvoiceRepo(Connection connection) { this.connection = connection; } @Override public void add(String invoiceText) throws Exception { final String query = "insert into invoices values (?)"; final PreparedStatement stmt = connection.prepareStatement(query); stmt.setString(1, invoiceText); stmt.execute(); } @Override public List<String> all() throws Exception { final String query = "select * from invoices"; final PreparedStatement stmt = connection.prepareStatement(query); final ResultSet resultSet = stmt.executeQuery(); final List<String> invoices = new ArrayList<>(); while (resultSet.next()) { invoices.add(resultSet.getString("text")); } return invoices; } }
jacksingleton/campr-xss-workshop
src/main/java/com/thoughtworks/securityinourdna/JdbcInvoiceRepo.java
Java
mit
1,136
package compiler import ( "bytes" "fmt" "net/http" "github.com/go-on/lib/html/element" "github.com/go-on/lib/misc/replacer" ) func mkPhHandler(e *element.Element, key string, buf *bytes.Buffer) (phdl []*placeholderHandler) { phdl = []*placeholderHandler{} element.Pre(e, buf) // fmt.Printf("checking %s\n", e.Tag()) if len(e.Children) == 0 || element.Is(e, element.SelfClosing) { // fmt.Printf("no children\n") element.Post(e, buf) return } // fmt.Printf("no children %d\n", len(e.Children)) for i, in := range e.Children { // fmt.Printf("children %T\n", in) switch ch := in.(type) { case *element.Element: phdl = append( phdl, mkPhHandler(ch, fmt.Sprintf("%s/%d", key, i), buf)..., ) case http.Handler: // fmt.Printf("is http.Handler: %T\n", ch) pha := replacer.Placeholder(fmt.Sprintf("%s-%d", key, i)) phdl = append(phdl, &placeholderHandler{pha, ch}) buf.WriteString(pha.String()) default: buf.WriteString(in.String()) } } element.Post(e, buf) return } type placeholderHandler struct { replacer.Placeholder http.Handler }
go-on/lib
html/element/compiler/placeholderhandler.go
GO
mit
1,098
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExactSumOfRealNums { class Program { static void Main(string[] args) { int numbersCount = int.Parse(Console.ReadLine()); decimal sum = 0; for (int i = 0; i < numbersCount; i++) { decimal number = decimal.Parse(Console.ReadLine()); sum += number; } Console.WriteLine(sum); } } }
vesopk/TechModule-Exercises
DataTypeLab/ExactSumOfRealNums/Program.cs
C#
mit
548
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package telas; import dados.Produto; import javax.swing.JOptionPane; import repositorio.RepositorioProduto; /** * * @author fabio */ public class TelaEditarProduto extends javax.swing.JFrame { RepositorioProduto repositorioProduto ; private Produto produto = null; /** Creates new form TelaEditarProduto */ public TelaEditarProduto(Produto produto) { initComponents(); this.produto = produto; // atualiza os campos caso exista um Produto para editar if (this.produto != null) { jTextField1.setText(produto.getNome()); jTextField2.setText(produto.getDesc()); jTextField3.setText(String.valueOf(produto.getPrecoVenda())); jTextField4.setText(String.valueOf(produto.getPrecoCusto())); } repositorioProduto = new RepositorioProduto(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Editar Produto"); setResizable(false); jButton1.setText("Confirmar !"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Cancelar !"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel1.setText("Digite O Novo Nome : "); jLabel2.setText("Digite A Nova Descrição : "); jLabel3.setText("Digite O Novo Preço de Venda :"); jLabel4.setText("Digite O Novo Preço de Custo : "); jLabel5.setFont(new java.awt.Font("Droid Sans", 3, 18)); // NOI18N jLabel5.setText("Tela De Edição"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField2) .addComponent(jTextField3) .addComponent(jTextField4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(60, 60, 60)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(77, 77, 77) .addComponent(jButton1) .addGap(77, 77, 77) .addComponent(jButton2)) .addGroup(layout.createSequentialGroup() .addGap(173, 173, 173) .addComponent(jLabel5))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel5) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed //Botão Para SAIR this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // Botão Para Editar if (jTextField1.getText().length() > 0 && jTextField2.getText().length() >0 && jTextField3.getText().length() >0 && jTextField4.getText().length() > 0){ String nome = jTextField1.getText(); String desc = jTextField2.getText(); double pv = Double.parseDouble(jTextField3.getText()); double pc = Double.parseDouble(jTextField4.getText()); if (this.produto != null) { // atualizar o produto existente this.produto.setNome(nome); this.produto.setDesc(desc); this.produto.setPrecoCusto(pc); this.produto.setPrecoVenda(pv); repositorioProduto.editarProduto(this.produto); JOptionPane.showMessageDialog(this,"Clique Na Linha Respectiva Para Aparecer Os Novos Valores"+"\nAtualizado Com Sucesso"); this.dispose(); repositorioProduto.AtualizaTablep(); } }else{ JOptionPane.showMessageDialog(this, "Campo(s) Em Branco"); } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaEditarProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaEditarProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaEditarProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaEditarProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaEditarProduto(null).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; // End of variables declaration//GEN-END:variables }
fabinhow12/provaSistemaVenda
sistemaVendaProva/src/telas/TelaEditarProduto.java
Java
mit
11,347
// eslint-disable-next-line import/prefer-default-export export const serializePlaylist = model => ({ _id: model.id, name: model.name, author: model.author, createdAt: model.createdAt, description: model.description, shared: model.shared, nsfw: model.nsfw, size: model.media.length, });
u-wave/api-v1
src/utils/serialize.js
JavaScript
mit
303
using CleanCode.Resources; using CleanCode.Settings; using JetBrains.Application.Settings; using JetBrains.ReSharper.Daemon.Stages.Dispatcher; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Tree; namespace CleanCode.Features.ClassTooBig { [ElementProblemAnalyzer(typeof(IClassDeclaration), HighlightingTypes = new [] { typeof(ClassTooBigHighlighting) })] public class ClassTooBigCheck : ElementProblemAnalyzer<IClassDeclaration> { protected override void Run(IClassDeclaration element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer) { var maxLength = data.SettingsStore.GetValue((CleanCodeSettings s) => s.MaximumMethodsInClass); var statementCount = element.CountChildren<IMethodDeclaration>(); if (statementCount > maxLength) { var declarationIdentifier = element.NameIdentifier; var documentRange = declarationIdentifier.GetDocumentRange(); var highlighting = new ClassTooBigHighlighting(Warnings.ClassTooBig, documentRange); consumer.AddHighlighting(highlighting); } } } }
hhariri/CleanCode
CleanCode/src/CleanCode/Features/ClassTooBig/ClassTooBigCheck.cs
C#
mit
1,253
class NotFoundError extends Error { constructor(message) { super(); if (Error.hasOwnProperty('captureStackTrace')) { Error.captureStackTrace(this, this.constructor); } else { Object.defineProperty(this, 'stack', { value : (new Error()).stack }); } Object.defineProperty(this, 'message', { value : message }); } get name() { return this.constructor.name; } } export default { NotFoundError }
CalebMorris/false-bookshelf
src/errors.js
JavaScript
mit
441
# 1417. Weighing Problem # Gives nn coins, each weighing 10g, but the weight of one coin is 11g. There # is now a balance that can be accurately weighed. Ask at least a few times # to be sure to find the 11g gold coin. # # Example # Given n = 3, return 1. # # Explanation: # Select two gold coins on the two ends of the balance. If the two ends of # the balance are level, the third gold coin is 11g, otherwise the heavy one # is 11g. # Given n = 4, return 2. # # Explanation: # Four gold coins can be divided into two groups and placed on both ends of # the scale. According to the weighing results, select the two heavy gold # coins and place them on the two ends of the balance for the second # weighing. The gold coin at the heavy end is 11g gold coins. # class Solution: # """ # @param n: The number of coins # @return: The Minimum weighing times int worst case # """ # def minimumtimes(self, n): # # Write your code here
kingdaa/LC-python
lintc/1417_Weighing_Problem.py
Python
mit
958
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; namespace RD_AAOW { /// <summary> /// Класс описывает кодек для изображений типа ZSoft Paintbrush image /// </summary> public class PCXCodec:ICodec, IPaletteCodec { [DllImport (ProgramDescription.AssemblyCodecsLibrary)] private static extern Int16 PCX_Load (string FileName, out UInt16 Width, out UInt16 Height, out IntPtr Buffer); [DllImport (ProgramDescription.AssemblyCodecsLibrary)] private static extern Int16 PCX_Save (string FileName, UInt16 Width, UInt16 Height, byte[] Buffer); [DllImport (ProgramDescription.AssemblyCodecsLibrary)] private static extern Int16 PCX_LoadPalette (string FileName, out IntPtr Buffer, out UInt16 ColorsCount); // RGB [DllImport (ProgramDescription.AssemblyCodecsLibrary)] private static extern Int16 PCX_SavePalette (string FileName, byte[] Buffer, UInt16 ColorsCount); // RGB [DllImport (ProgramDescription.AssemblyCodecsLibrary)] private static extern void BIC_ReleaseBuffer (IntPtr Buffer); /// <summary> /// Метод загружает указанное изображение и возвращает его в виде объекта Bitmap /// </summary> /// <param name="FilePath">Путь к файлу изображения</param> /// <param name="LoadedImage">Загруженное изображение</param> /// <returns>Возвращает преобразованное изображение или null в случае ошибки</returns> public ProgramErrorCodes LoadImage (string FilePath, out Bitmap LoadedImage) { // Загрузка изображения UInt16 width, height; IntPtr buffer = IntPtr.Zero; ProgramErrorCodes error = (ProgramErrorCodes)PCX_Load (FilePath, out width, out height, out buffer); if (error != ProgramErrorCodes.EXEC_OK) { LoadedImage = null; return error; } // Извлечение массива данных и сборка изображения LoadedImage = new Bitmap (width, height, PixelFormat.Format32bppArgb); unsafe { byte* a = (byte*)buffer.ToPointer (); for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { LoadedImage.SetPixel (w, h, Color.FromArgb (a[3 * (h * width + w) + 0], a[3 * (h * width + w) + 1], a[3 * (h * width + w) + 2])); } } } // Завершено BIC_ReleaseBuffer (buffer); // Давно пора! return ProgramErrorCodes.EXEC_OK; } /// <summary> /// Метод сохраняет указанное изображение в требуемом формате /// </summary> /// <param name="Image">Сохраняемое изображение</param> /// <param name="FilePath">Имя и путь к файлу изображения без расширения</param> /// <param name="Parameters">Неиспользуемый параметр</param> /// <param name="ImageColorFormat">Цветовое представление выходного изображения</param> /// <param name="BitmapEdge">Порог яркости для чёрно-белого преобразования</param> /// <returns>Возвращает true в случае успеха</returns> public ProgramErrorCodes SaveImage (Bitmap Image, string FilePath, OutputImageColorFormat ImageColorFormat, byte BitmapEdge, object Parameters) { // Контроль (блок параметров не используется) if (Image == null) { return ProgramErrorCodes.EXEC_INVALID_PARAMETERS; } // Контроль наличия файла (защита от перезаписи) string fullPath = TestOutputFile (FilePath, Parameters); if (fullPath == "") { return ProgramErrorCodes.EXEC_FILE_UNAVAILABLE; } // Подготовка параметров byte[] array = new byte[Image.Width * Image.Height * 3]; for (int h = 0; h < Image.Height; h++) { for (int w = 0; w < Image.Width; w++) { Color c; switch (ImageColorFormat) { case OutputImageColorFormat.Bitmap: c = ColorTransition.ToBitmap (Image.GetPixel (w, h), BitmapEdge); break; case OutputImageColorFormat.Greyscale: c = ColorTransition.ToGreyscale (Image.GetPixel (w, h)); break; case OutputImageColorFormat.Color: default: c = Image.GetPixel (w, h); break; } array[(h * Image.Width + w) * 3 + 0] = c.R; array[(h * Image.Width + w) * 3 + 1] = c.G; array[(h * Image.Width + w) * 3 + 2] = c.B; } } // Обращение ProgramErrorCodes res = (ProgramErrorCodes)PCX_Save (fullPath, (UInt16)Image.Width, (UInt16)Image.Height, array); // Инициирование очистки памяти array = null; //GC.Collect (); return res; } /// <summary> /// Метод определяет, может ли быть создан указанный файл с заданными параметрами сохранения /// </summary> /// <param name="FilePath">Имя и путь к файлу изображения без расширения</param> /// <param name="Parameters">Дополнительные параметры (если требуются)</param> /// <returns>Возвращает полное имя файла в случае допустимости записи</returns> public string TestOutputFile (string FilePath, object Parameters) { string fullPath = FilePath + FileExtensions[0].Substring (1); if (File.Exists (fullPath)) { return ""; } return fullPath; } /// <summary> /// Возвращает список соответствующих формату расширений файлов /// </summary> public string[] FileExtensions { get { return new string[] { "*.pcx", "*.pcc" }; } } /// <summary> /// Метод загружает указанную палитру и возвращает его в виде объекта List of Color /// </summary> /// <param name="Palette">Загруженная палитра</param> /// <param name="FilePath">Путь к файлу палитры</param> /// <returns>Возвращает преобразованное изображение или null в случае ошибки</returns> public ProgramErrorCodes LoadPalette (string FilePath, out List<Color> Palette) { // Загрузка изображения IntPtr buffer; UInt16 colorsCount; Palette = new List<Color> (); ProgramErrorCodes error = (ProgramErrorCodes)PCX_LoadPalette (FilePath, out buffer, out colorsCount); if (error != ProgramErrorCodes.EXEC_OK) { return error; } // Извлечение массива данных и сборка изображения unsafe { byte* a = (byte*)buffer.ToPointer (); for (int c = 0; c < colorsCount; c++) { Palette.Add (Color.FromArgb (a[3 * c + 0], a[3 * c + 1], a[3 * c + 2])); } } // Завершено return ProgramErrorCodes.EXEC_OK; } /// <summary> /// Метод сохраняет указанную палитру /// </summary> /// <param name="Palette">Сохраняемая палитра</param> /// <param name="FilePath">Имя и путь к файлу палитры без расширения</param> /// <returns>Возвращает true в случае успеха</returns> public ProgramErrorCodes SavePalette (string FilePath, List<Color> Palette) { // Контроль (блок параметров не используется) if ((Palette == null) || (Palette.Count == 0) || (Palette.Count > MaxColors)) { return ProgramErrorCodes.EXEC_INVALID_PARAMETERS; } // Подготовка параметров byte[] array = new byte[Palette.Count * 3]; for (int c = 0; c < Palette.Count; c++) { array[c * 3 + 0] = Palette[c].R; array[c * 3 + 1] = Palette[c].G; array[c * 3 + 2] = Palette[c].B; } // Обращение return (ProgramErrorCodes)PCX_SavePalette (FilePath, array, (UInt16)Palette.Count); } /// <summary> /// Возвращает максимально допустимое количество цветов в палитре /// </summary> public uint MaxColors { get { return 256; } } } }
adslbarxatov/BatchImageConvertor
src/PCXCodec.cs
C#
mit
8,600
package main import ( "github.com/james4k/terminal" ) // ScreenInfo type type ScreenInfo struct { Width int Height int Chars []rune Fcolors []terminal.Color Bcolors []terminal.Color CursorX int CursorY int CursorVisible bool top int bottom int left int right int } // NewScreenInfo returns ScreenInfo instance func NewScreenInfo() *ScreenInfo { return &ScreenInfo{ Width: -1, Height: -1, Chars: []rune{}, Fcolors: []terminal.Color{}, Bcolors: []terminal.Color{}, CursorX: -1, CursorY: -1, CursorVisible: false, top: -1, bottom: -1, left: -1, right: -1, } } func (s *ScreenInfo) save(width int, height int, state *terminal.State) { if s.Width != width || s.Height != height { s.Width = width s.Height = height s.Chars = make([]rune, width*height) s.Fcolors = make([]terminal.Color, width*height) s.Bcolors = make([]terminal.Color, width*height) } for row := 0; row < s.Height; row++ { for col := 0; col < s.Width; col++ { ch, fg, bg := state.Cell(col, row) s.Chars[row*s.Width+col] = ch s.Fcolors[row*s.Width+col] = fg s.Bcolors[row*s.Width+col] = bg } } s.CursorX, s.CursorY = state.Cursor() s.CursorVisible = state.CursorVisible() } func (s *ScreenInfo) updateRedrawRange(x int, y int) { if y < s.top { s.top = y } if s.bottom < y+1 { s.bottom = y + 1 } if x < s.left { s.left = x } if s.right < x+1 { s.right = x + 1 } } // GetRedrawRange returns redraw range. func (s *ScreenInfo) GetRedrawRange(width int, height int, state *terminal.State) (left int, top int, right int, bottom int) { defer s.save(width, height, state) if s.Width != width || s.Height != height { return 0, 0, width, height } s.top = height s.bottom = 0 s.left = width s.right = 0 for row := 0; row < height; row++ { for col := 0; col < width; col++ { ch, fg, bg := state.Cell(col, row) ch0 := s.Chars[row*width+col] fg0 := s.Fcolors[row*width+col] bg0 := s.Bcolors[row*width+col] if ch != ch0 || fg != fg0 || bg != bg0 { s.updateRedrawRange(col, row) } } } cursorVisible := state.CursorVisible() cursorX, cursorY := state.Cursor() if s.CursorVisible && !cursorVisible { s.updateRedrawRange(s.CursorX, s.CursorY) } if !s.CursorVisible && cursorVisible { s.updateRedrawRange(cursorX, cursorY) } if s.CursorVisible && cursorVisible && (s.CursorX != cursorX || s.CursorY != cursorY) { s.updateRedrawRange(s.CursorX, s.CursorY) s.updateRedrawRange(cursorX, cursorY) } return s.left, s.top, s.right, s.bottom }
sugyan/ttyrec2gif
screenInfo.go
GO
mit
2,695
"use strict"; /* global describe it before */ const { assert } = require("chai"); const Database = require("./lib/database"); const testcases = (env) => { describe("Basic operations", () => { before(async () => { await Database.start(); }); it("should list zero objects", async () => { const list = await env.client.list("thing"); assert.isArray(list); assert.equal(list.length, 0); }); it("should create one object", async () => { const thing = await env.client.create("thing", { _id: "1", thingy: "Hello" }); assert.equal(thing.type, "scom.thing"); assert.equal(thing.thingy, "Hello"); }); it("should list one object", async () => { const list = await env.client.list("thing"); assert.isArray(list); assert.equal(list.length, 1); }); it("should update one object", async () => { const thing = await env.client.update("thing", "1", { thingy: "World" }); assert.equal(thing.type, "scom.thing"); assert.equal(thing.thingy, "World"); }); it("should delete one object", async () => { const thing = await env.client.remove("thing", "1"); assert.equal(thing.type, "scom.thing"); assert.equal(thing.thingy, "World"); }); it("should list zero objects", async () => { const list = await env.client.list("thing"); assert.isArray(list); assert.equal(list.length, 0); }); }); describe("Action operations", () => { before(async () => { await Database.start(); }); it("should create an object and tag it", async () => { await env.client.create("thing", { _id: "1", thingy: "Hello" }); const thing2 = await env.client.tag("thing", "1", { tag: [ "tag1", "tag2" ] }); assert.equal(thing2.type, "scom.thing"); assert.equal(thing2.thingy, "Hello"); assert.deepEqual(thing2.tags, [ "tag1", "tag2" ]); }); it("should get error with invalid action", async () => { try { await env.client.stuff("thing", "1", { 1: 0 }); assert(false, "Should have thrown"); } catch (error) { assert.equal(error.status, 400); } }); }); describe("Getter operations", () => { before(async () => { await Database.start(); }); it("should create an object and get something on it", async () => { await env.client.create("thing", { _id: "1", thingy: "Hello" }); const value = await env.client.thingy("thing", "1"); assert.equal(value, "Hello"); }); it("should get error with invalid getter", async () => { try { await env.client.stuff("thing", "1"); assert(false, "Should have thrown"); } catch (error) { assert.equal(error.status, 400); } }); }); }; module.exports = testcases;
Combitech/codefarm
src/lib/servicecom/test/testcases.js
JavaScript
mit
3,396
var fs = require('fs') var parseTorrent = require('parse-torrent') var test = require('tape') var WebTorrent = require('../') var DHT = require('bittorrent-dht/client') var parallel = require('run-parallel') var bufferEqual = require('buffer-equal') var leaves = fs.readFileSync(__dirname + '/torrents/leaves.torrent') var leavesTorrent = parseTorrent(leaves) var leavesBook = fs.readFileSync(__dirname + '/content/Leaves of Grass by Walt Whitman.epub') var leavesMagnetURI = 'magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36&dn=Leaves+of+Grass+by+Walt+Whitman.epub&tr=http%3A%2F%2Ftracker.thepiratebay.org%2Fannounce&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ffr33domtracker.h33t.com%3A3310%2Fannounce&tr=http%3A%2F%2Ftracker.bittorrent.am%2Fannounce' test('client.add (magnet uri, torrent file, info hash, and parsed torrent)', function (t) { // magnet uri (utf8 string) var client1 = new WebTorrent({ dht: false, tracker: false }) var torrent1 = client1.add('magnet:?xt=urn:btih:' + leavesTorrent.infoHash) t.equal(torrent1.infoHash, leavesTorrent.infoHash) t.equal(torrent1.magnetURI, 'magnet:?xt=urn:btih:' + leavesTorrent.infoHash) client1.destroy() // torrent file (buffer) var client2 = new WebTorrent({ dht: false, tracker: false }) var torrent2 = client2.add(leaves) t.equal(torrent2.infoHash, leavesTorrent.infoHash) t.equal(torrent2.magnetURI, leavesMagnetURI) client2.destroy() // info hash (hex string) var client3 = new WebTorrent({ dht: false, tracker: false }) var torrent3 = client3.add(leavesTorrent.infoHash) t.equal(torrent3.infoHash, leavesTorrent.infoHash) t.equal(torrent3.magnetURI, 'magnet:?xt=urn:btih:' + leavesTorrent.infoHash) client3.destroy() // info hash (buffer) var client4 = new WebTorrent({ dht: false, tracker: false }) var torrent4 = client4.add(new Buffer(leavesTorrent.infoHash, 'hex')) t.equal(torrent4.infoHash, leavesTorrent.infoHash) t.equal(torrent4.magnetURI, 'magnet:?xt=urn:btih:' + leavesTorrent.infoHash) client4.destroy() // parsed torrent (from parse-torrent) var client5 = new WebTorrent({ dht: false, tracker: false }) var torrent5 = client5.add(leavesTorrent) t.equal(torrent5.infoHash, leavesTorrent.infoHash) t.equal(torrent5.magnetURI, leavesMagnetURI) client5.destroy() t.end() }) test('client.seed (Buffer, Blob)', function (t) { t.plan(typeof Blob !== 'undefined' ? 4 : 2) var opts = { name: 'Leaves of Grass by Walt Whitman.epub', announce: [ 'http://tracker.thepiratebay.org/announce', 'udp://tracker.openbittorrent.com:80', 'udp://tracker.ccc.de:80', 'udp://tracker.publicbt.com:80', 'udp://fr33domtracker.h33t.com:3310/announce', 'http://tracker.bittorrent.am/announce' ] } // torrent file (Buffer) var client1 = new WebTorrent({ dht: false, tracker: false }) client1.seed(leavesBook, opts, function (torrent1) { t.equal(torrent1.infoHash, leavesTorrent.infoHash) t.equal(torrent1.magnetURI, leavesMagnetURI) client1.destroy() }) // Blob if (typeof Blob !== 'undefined') { var client2 = new WebTorrent({ dht: false, tracker: false }) client2.seed(new Blob([ leavesBook ]), opts, function (torrent2) { t.equal(torrent2.infoHash, leavesTorrent.infoHash) t.equal(torrent2.magnetURI, leavesMagnetURI) client2.destroy() }) } else { console.log('Skipping Blob test because missing `Blob` constructor') } }) test('after client.destroy(), throw on client.add() or client.seed()', function (t) { t.plan(3) var client = new WebTorrent({ dht: false, tracker: false }) client.destroy(function () { t.pass('client destroyed') }) t.throws(function () { client.add('magnet:?xt=urn:btih:' + leavesTorrent.infoHash) }) t.throws(function () { client.seed(new Buffer('sup')) }) }) test('after client.destroy(), no "torrent" or "ready" events emitted', function (t) { t.plan(1) var client = new WebTorrent({ dht: false, tracker: false }) client.add(leaves, function () { t.fail('unexpected "torrent" event (from add)') }) client.seed(leavesBook, function () { t.fail('unexpected "torrent" event (from seed)') }) client.on('ready', function () { t.fail('unexpected "ready" event') }) client.destroy(function () { t.pass('client destroyed') }) }) test('download via DHT', function (t) { t.plan(2) var data = new Buffer('blah blah') var dhts = [] // need 3 because nodes don't advertise themselves as peers for (var i = 0; i < 3; i++) { dhts.push(new DHT({ bootstrap: false })) } parallel(dhts.map(function (dht) { return function (cb) { dht.listen(function (port) { cb(null, port) }) } }), function () { for (var i = 0; i < dhts.length; i++) { for (var j = 0; j < dhts.length; j++) { if (i !== j) dhts[i].addNode('127.0.0.1:' + getDHTPort(dhts[j]), dhts[j].nodeId) } } var client1 = new WebTorrent({ dht: dhts[0], tracker: false }) var client2 = new WebTorrent({ dht: dhts[1], tracker: false }) client1.seed(data, { name: 'blah' }, function (torrent1) { client2.download(torrent1.infoHash, function (torrent2) { t.equal(torrent2.infoHash, torrent1.infoHash) torrent2.on('done', function () { t.ok(bufferEqual(getFileData(torrent2), data)) dhts.forEach(function (d) { d.destroy() }) client1.destroy() client2.destroy() }) }) }) }) }) test('don\'t kill passed in DHT on destroy', function (t) { t.plan(1) var dht = new DHT({ bootstrap: false }) var destroy = dht.destroy var okToDie dht.destroy = function () { t.equal(okToDie, true) dht.destroy = destroy.bind(dht) dht.destroy() } var client = new WebTorrent({ dht: dht, tracker: false }) client.destroy(function () { okToDie = true dht.destroy() }) }) function getFileData (torrent) { var pieces = torrent.files[0].pieces return Buffer.concat(pieces.map( function (piece) { return piece.buffer } )) } function getDHTPort (dht) { return dht.address().port }
tradle/webtorrent
test/basic.js
JavaScript
mit
6,281
#include <chrono> #include <thread> #include "./input.h" #include "../common/SharedState.h" #include "../common/Logger.h" #include "./FaceDetector.h" using namespace std; void inputLoop() { SharedState& state = SharedState::getInstance(); Logger& logger = Logger::getInstance(); double posX = 0.5; FaceDetector fd; fd.load(); while(true) { if(state.isGameOver()) break; bool isSmilingOld = fd.isSmiling; fd.read(); fd.detect(); state.setHeadPositionX(fd.headPosX); state.setHeadPositionY(fd.headPosY); if (!isSmilingOld && fd.isSmiling) state.pushCommand(Command::SHOOT); this_thread::sleep_for(chrono::milliseconds(10)); } fd.cleanup(); }
Thegaram/falling-blocks-cam
src/input/input.cpp
C++
mit
774
export const state = () => ({ visits:[] }) export const mutations = { ADD_VISIT (state,path) { state.visits.push({ path, date:new Date().toJSON() }) } }
choukin/learnjavascript
vue/nuxt/helloworld/store/index.js
JavaScript
mit
166
Menubar.Add = function ( editor ) { var meshCount = 0; var lightCount = 0; // event handlers function onObject3DOptionClick () { var mesh = new THREE.Object3D(); mesh.name = 'Object3D ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Plane function onPlaneOptionClick () { var width = 200; var height = 200; var widthSegments = 1; var heightSegments = 1; var geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); var material = new THREE.MeshPhongMaterial(); var mesh = new THREE.Mesh( geometry, material ); mesh.name = 'Plane ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); }; //Triangle function onTriangleOptionClick (){ var geometry = new THREE.Geometry(); var v1 = new THREE.Vector3(-100,0,0); var v2 = new THREE.Vector3(100,0,0); var v3 = new THREE.Vector3(0,100,0); geometry.vertices.push(v1); geometry.vertices.push(v2); geometry.vertices.push(v3); geometry.faces.push(new THREE.Face3(0,2,1)); var material = new THREE.MeshBasicMaterial({color:0xff0000}); var mesh = new THREE.Mesh(geometry, material); mesh.name = 'Triangle ' + (++ meshCount); editor.addObject( mesh ); editor.select(mesh); }; //Box function onBoxOptionClick () { var width = 100; var height = 100; var depth = 100; var widthSegments = 1; var heightSegments = 1; var depthSegments = 1; var geometry = new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Box ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Circle function onCircleOptionClick () { var radius = 20; var segments = 32; var geometry = new THREE.CircleGeometry( radius, segments ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Circle ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Cylinder function onCylinderOptionClick () { var radiusTop = 20; var radiusBottom = 20; var height = 100; var radiusSegments = 32; var heightSegments = 1; var openEnded = false; var geometry = new THREE.CylinderGeometry( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Cylinder ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Sphere function onSphereOptionClick () { var radius = 75; var widthSegments = 32; var heightSegments = 16; var geometry = new THREE.SphereGeometry( radius, widthSegments, heightSegments ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Sphere ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Icosahedron function onIcosahedronOptionClick () { var radius = 75; var detail = 2; var geometry = new THREE.IcosahedronGeometry ( radius, detail ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Icosahedron ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Torus function onTorusOptionClick () { var radius = 100; var tube = 40; var radialSegments = 8; var tubularSegments = 6; var arc = Math.PI * 2; var geometry = new THREE.TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'Torus ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Torus Knot function onTorusKnotOptionClick () { var radius = 100; var tube = 40; var radialSegments = 64; var tubularSegments = 8; var p = 2; var q = 3; var heightScale = 1; var geometry = new THREE.TorusKnotGeometry( radius, tube, radialSegments, tubularSegments, p, q, heightScale ); var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() ); mesh.name = 'TorusKnot ' + ( ++ meshCount ); editor.addObject( mesh ); editor.select( mesh ); } //Sprite function onSpriteOptionClick () { var sprite = new THREE.Sprite( new THREE.SpriteMaterial() ); sprite.name = 'Sprite ' + ( ++ meshCount ); editor.addObject( sprite ); editor.select( sprite ); } function onPointLightOptionClick () { var color = 0xffffff; var intensity = 1; var distance = 0; var light = new THREE.PointLight( color, intensity, distance ); light.name = 'PointLight ' + ( ++ lightCount ); editor.addObject( light ); editor.select( light ); } function onSpotLightOptionClick () { var color = 0xffffff; var intensity = 1; var distance = 0; var angle = Math.PI * 0.1; var exponent = 10; var light = new THREE.SpotLight( color, intensity, distance, angle, exponent ); //.distance // light will attenuate linearly from maximum intensity at light position down to zero at distance. // .angle // Maximum extent of the spotlight, in radians, from its direction. Should be no more than Math.PI/2. // Default — Math.PI/3. // .exponent // Rapidity of the falloff of light from its target direction. // Default — 10.0. light.name = 'SpotLight ' + ( ++ lightCount ); light.target.name = 'SpotLight ' + ( lightCount ) + ' Target'; light.position.set( 0, 1, 0 ).multiplyScalar( 200 ); editor.addObject( light ); editor.select( light ); } function onDirectionalLightOptionClick () { var color = 0xffffff; var intensity = 1; var light = new THREE.DirectionalLight( color, intensity ); light.name = 'DirectionalLight ' + ( ++ lightCount ); light.target.name = 'DirectionalLight ' + ( lightCount ) + ' Target'; light.position.set( 1, 1, 1 ).multiplyScalar( 200 ); editor.addObject( light ); editor.select( light ); } function onHemisphereLightOptionClick () { var skyColor = 0x00aaff; var groundColor = 0xffaa00; var intensity = 1; var light = new THREE.HemisphereLight( skyColor, groundColor, intensity ); light.name = 'HemisphereLight ' + ( ++ lightCount ); light.position.set( 1, 1, 1 ).multiplyScalar( 200 ); editor.addObject( light ); editor.select( light ); } function onAmbientLightOptionClick() { var color = 0x222222; var light = new THREE.AmbientLight( color ); light.name = 'AmbientLight ' + ( ++ lightCount ); editor.addObject( light ); editor.select( light ); } // configure menu contents var createOption = UI.MenubarHelper.createOption; var createDivider = UI.MenubarHelper.createDivider; var menuConfig = [ //createOption( 'Object3D', onObject3DOptionClick ), //createDivider(), createOption( 'Plane', onPlaneOptionClick ), createOption('Triangle',onTriangleOptionClick), createOption( 'Box', onBoxOptionClick ), createOption( 'Circle', onCircleOptionClick ), createOption( 'Cylinder', onCylinderOptionClick ), createOption( 'Sphere', onSphereOptionClick ), //createOption( 'Icosahedron', onIcosahedronOptionClick ), //createOption( 'Torus', onTorusOptionClick ), //createOption( 'Torus Knot', onTorusKnotOptionClick ), createDivider(), //createOption( 'Sprite', onSpriteOptionClick ), createDivider(), createOption( 'Point light', onPointLightOptionClick ), createOption( 'Spot light', onSpotLightOptionClick ), createOption( 'Directional light', onDirectionalLightOptionClick ), createOption( 'Hemisphere light', onHemisphereLightOptionClick ), createOption( 'Ambient light', onAmbientLightOptionClick ) ]; var optionsPanel = UI.MenubarHelper.createOptionsPanel( menuConfig ); return UI.MenubarHelper.createMenuContainer( 'Add', optionsPanel ); }
akshaynagpal/3d_graphics_editor
js/Menubar.Add.js
JavaScript
mit
7,787
import React, { PropTypes } from 'react'; const ProductList = (props) => { const pl = props.productList; const products = Object.keys(pl); return (<ul> {products.map(key => <li key={key}><a href={`#/product/${key}`} >{pl[key].name}</a></li>)} </ul>); }; ProductList.propTypes = { productList: PropTypes.object.isRequired }; export default ProductList;
sunitJindal/react-tutorial
redux-with-react/app/components/ProductList/presentational/ProductList.js
JavaScript
mit
368
<?php defined('PHPFOX') or exit('NO DICE!'); ?> <?php /* Cached: February 25, 2013, 5:08 am */ ?> <?php /** * [PHPFOX_HEADER] * * @copyright [PHPFOX_COPYRIGHT] * @author Raymond_Benc * @package Phpfox * @version $Id: template-footer.html.php 3244 2011-10-07 11:42:15Z Raymond_Benc $ */ ?> <?php if (! defined ( 'PHPFOX_SKIP_IM' )): ?> <?php Phpfox::getBlock('im.footer', array()); ?> <?php echo $this->_aVars['sDebugInfo']; ?> <?php endif; ?> <script type="text/javascript"> $Core.init(); </script> <?php (($sPlugin = Phpfox_Plugin::get('theme_template_body__end')) ? eval($sPlugin) : false); ?>
edbiler/BazaarCorner
file/cache_for_deletion/template/core_template_default_block_template-footer.html.php.php
PHP
mit
625
# encoding: utf-8 require 'spec_helper' describe Optimizer::Function::Binary::ConstantOperands, '#optimize' do subject { object.optimize } let(:described_class) { Class.new(Optimizer) { include Optimizer::Function::Binary } } let(:function) { Function::Numeric::Addition.new(2, 2) } let(:object) { described_class.new(function) } before do described_class.class_eval { include Optimizer::Function::Binary::ConstantOperands } expect(object).to be_optimizable end it { should be(4) } end
dkubb/axiom-optimizer
spec/unit/axiom/optimizer/function/binary/constant_operands/optimize_spec.rb
Ruby
mit
583
<?php require_once __DIR__.'/Autoloader.php'; ?> <?php spl_autoload_register('Autoloader::loader'); ?> <?php class Employee { private $employee_id; private $employee_firstname; private $employee_lastname; private $employee_username; private $employee_password; private $hash; private $employee_email; private $employee_home_address; private $employee_role; private $date_of_employment; private $still_working; private $phone_number; public function __construct($employee_firstname, $employee_lastname, $employee_username, $employee_password,$hash, $employee_email, $employee_home_address, $employee_role, $date_of_employment, $still_working,$phone_number) { global $db; $this->employee_firstname = mysqli_real_escape_string($db->connection,$employee_firstname); $this->employee_lastname = mysqli_real_escape_string($db->connection,$employee_lastname); $this->employee_username = mysqli_real_escape_string($db->connection,$employee_username); $this->employee_password = mysqli_real_escape_string($db->connection,$employee_password); $this->hash = mysqli_real_escape_string($db->connection, $hash); $this->employee_email = mysqli_real_escape_string($db->connection,$employee_email); $this->employee_home_address = mysqli_real_escape_string($db->connection,$employee_home_address); $this->employee_role = mysqli_real_escape_string($db->connection,$employee_role); $this->date_of_employment = mysqli_real_escape_string($db->connection,$date_of_employment); $this->still_working = mysqli_real_escape_string($db->connection,$still_working); $this->phone_number = mysqli_real_escape_string($db->connection,$phone_number); } // --------------------------------- GETTERS ----------------------------------------------- public function getEmployeeId() { return $this->employee_id; } public function getEmployeeFirstname() { return $this->employee_firstname; } public function getEmployeeLastname() { return $this->employee_lastname; } public function getEmployeeUsername() { return $this->employee_username; } public function getEmployeePassword() { return $this->employee_password; } public function getEmployeeHash() { return $this->hash; } public function getEmployeeEmail() { return $this->employee_email; } public function getEmployeeHomeAdress() { return $this->employee_home_address; } public function getEmployeeRole() { return $this->employee_role; } public function getEmployeeDateOfEmployment() { return $this->date_of_employment; } public function getStillWorking() { return $this->still_working; } public function getPhoneNumber() { return $this->phone_number; } // ------------------------------------------------ SETTERS ------------------------------------------------------------- public function setEmployeeFirstname($employee_firstname) { $this->employee_firstname = $employee_firstname; } public function setEmployeeLastname($employee_lastname) { $this->employee_lastname = $employee_lastname; } public function setEmployeeUsername($employee_username) { $this->employee_username = $employee_username; } public function setEmployeePassword($employee_password) { $this->employee_password = $employee_password; } public function setEmployeeEmail($employee_email) { $this->employee_email = $employee_email; } public function setEmployeeHomeAddress($employee_home_address) { $this->employee_home_address = $employee_home_address; } public function setEmployeeRole($employee_role) { $this->employee_role = $employee_role; } public function setEmployeeDateOfEmployment($date_of_employment) { $this->date_of_employment = $date_of_employment; } public function setStillWorking($still_working) { $this->still_working = $still_working; } public function setPhoneNumber($phone_number) { $this->phone_number = $phone_number; } public function cleanInput($data) { trim($data); mysqli_real_escape_string($db->connection,$data); } //$date = new DateTime(); // $emp_01 = new Employee('Nenad', 'Mirkovic', 'nena91', 'nena91', 'nena91@example.com', '11.oktobar 60', 'Web Developer', $date->setDate(2016, 8, 16), '202-555-1775'); // // $emp_01->getEmployeeId(); }
nexon91/employee-project
employee_project/classes/Employee.php
PHP
mit
4,612
ace.define("ace/snippets/sqlserver", ["require", "exports", "module"], function(require, exports, module) { "use strict"; exports.snippetText = "# ISNULL\n\ snippet isnull\n\ ISNULL(${1:check_expression}, ${2:replacement_value})\n\ # FORMAT\n\ snippet format\n\ FORMAT(${1:value}, ${2:format})\n\ # CAST\n\ snippet cast\n\ CAST(${1:expression} AS ${2:data_type})\n\ # CONVERT\n\ snippet convert\n\ CONVERT(${1:data_type}, ${2:expression})\n\ # DATEPART\n\ snippet datepart\n\ DATEPART(${1:datepart}, ${2:date})\n\ # DATEDIFF\n\ snippet datediff\n\ DATEDIFF(${1:datepart}, ${2:startdate}, ${3:enddate})\n\ # DATEADD\n\ snippet dateadd\n\ DATEADD(${1:datepart}, ${2:number}, ${3:date})\n\ # DATEFROMPARTS \n\ snippet datefromparts\n\ DATEFROMPARTS(${1:year}, ${2:month}, ${3:day})\n\ # OBJECT_DEFINITION\n\ snippet objectdef\n\ SELECT OBJECT_DEFINITION(OBJECT_ID('${1:sys.server_permissions /*object name*/}'))\n\ # STUFF XML\n\ snippet stuffxml\n\ STUFF((SELECT ', ' + ${1:ColumnName}\n\ FROM ${2:TableName}\n\ WHERE ${3:WhereClause}\n\ FOR XML PATH('')), 1, 1, '') AS ${4:Alias}\n\ ${5:/*https://msdn.microsoft.com/en-us/library/ms188043.aspx*/}\n\ # Create Procedure\n\ snippet createproc\n\ -- =============================================\n\ -- Author: ${1:Author}\n\ -- Create date: ${2:Date}\n\ -- Description: ${3:Description}\n\ -- =============================================\n\ CREATE PROCEDURE ${4:Procedure_Name}\n\ ${5:/*Add the parameters for the stored procedure here*/}\n\ AS\n\ BEGIN\n\ -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.\n\ SET NOCOUNT ON;\n\ \n\ ${6:/*Add the T-SQL statements to compute the return value here*/}\n\ \n\ END\n\ GO\n\ # Create Scalar Function\n\ snippet createfn\n\ -- =============================================\n\ -- Author: ${1:Author}\n\ -- Create date: ${2:Date}\n\ -- Description: ${3:Description}\n\ -- =============================================\n\ CREATE FUNCTION ${4:Scalar_Function_Name}\n\ -- Add the parameters for the function here\n\ RETURNS ${5:Function_Data_Type}\n\ AS\n\ BEGIN\n\ DECLARE @Result ${5:Function_Data_Type}\n\ \n\ ${6:/*Add the T-SQL statements to compute the return value here*/}\n\ \n\ END\n\ GO"; exports.scope = "sqlserver"; }); (function() { ace.require(["ace/snippets/sqlserver"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
TeamSPoon/logicmoo_workspace
packs_web/swish/web/node_modules/ace/build/src-noconflict/snippets/sqlserver.js
JavaScript
mit
2,522
#!/usr/bin/python import petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc Print = PETSc.Sys.Print # from MatrixOperations import * from dolfin import * import numpy as np import matplotlib.pylab as plt import scipy.sparse as sps import scipy.sparse.linalg as slinalg import os import scipy.io import PETScIO as IO import MatrixOperations as MO def StoreMatrix(A,name): test ="".join([name,".mat"]) scipy.io.savemat( test, {name: A},oned_as='row') parameters['num_threads'] = 10 m = 6 errL2b =np.zeros((m-1,1)) errCurlb =np.zeros((m-1,1)) errL2r =np.zeros((m-1,1)) errH1r =np.zeros((m-1,1)) l2border = np.zeros((m-1,1)) Curlborder =np.zeros((m-1,1)) # set_log_level(DEBUG) NN = np.zeros((m-1,1)) DoF = np.zeros((m-1,1)) Vdim = np.zeros((m-1,1)) Qdim = np.zeros((m-1,1)) Wdim = np.zeros((m-1,1)) iterations = np.zeros((m-1,1)) SolTime = np.zeros((m-1,1)) udiv = np.zeros((m-1,1)) MU = np.zeros((m-1,1)) nn = 2 dim = 2 Solving = 'Direct' ShowResultPlots = 'yes' ShowErrorPlots = 'no' EigenProblem = 'no' SavePrecond = 'no' CheckMu = 'no' case = 4 parameters['linear_algebra_backend'] = 'uBLAS' MU[0]= 1e0 for xx in xrange(1,m): print xx nn = 2**(xx)/2 if (CheckMu == 'yes'): if (xx != 1): MU[xx-1] = MU[xx-2]/10 else: if (xx != 1): MU[xx-1] = MU[xx-2] # Create mesh and define function space nn = int(nn) NN[xx-1] = nn parameters["form_compiler"]["quadrature_degree"] = 3 parameters["form_compiler"]["optimize"] = True parameters["form_compiler"]["representation"] = 'quadrature' # mesh = BoxMesh(-1,-1,-1,1, 1, 1, nn, nn, nn) mesh = UnitCubeMesh(nn,nn,nn) parameters['reorder_dofs_serial'] = False V = FunctionSpace(mesh, "N1curl",2) Q = FunctionSpace(mesh, "CG",2) Vdim[xx-1] = V.dim() print "\n\n\n V-dim", V.dim() def boundary(x, on_boundary): return on_boundary if case == 1: u0 = Expression(("x[1]*x[1]*(x[1]-1)","x[0]*x[0]*(x[0]-1)","0")) elif case == 2: u0 = Expression(("sin(2*pi*x[1])*cos(2*pi*x[0])","-sin(2*pi*x[0])*cos(2*pi*x[1])")) elif case == 3: u0 = Expression(("x[0]*x[0]*(x[0]-1)","x[1]*x[1]*(x[1]-1)","0")) elif case == 4: u0 = Expression(("x[0]*x[1]*x[2]*(x[0]-1)","x[0]*x[1]*x[2]*(x[1]-1)","x[0]*x[1]*x[2]*(x[2]-1)")) bcs = DirichletBC(V,u0, boundary) # (u1) = TrialFunctions(V) # (v1) = TestFunctions(V) c = .5 if case == 1: # f= Expression(("(8*pow(pi,2)-C)*sin(2*pi*x[1])*cos(2*pi*x[0])","-(8*pow(pi,2)-C)*sin(2*pi*x[0])*cos(2*pi*x[1])"),C = c) f = Expression(("-6*x[1]+2","-6*x[0]+2"))+c*u0 elif case == 2: f = 8*pow(pi,2)*u0+c*u0 elif case == 3: f = Expression(("0","0","0"),C = c) f = c*u0 elif case == 4: f = Expression(("x[2]*(2*x[1]-1)+x[1]*(2*x[2]-1)","x[0]*(2*x[2]-1)+x[2]*(2*x[0]-1)","x[1]*(2*x[0]-1)+x[0]*(2*x[1]-1)"))+c*u0 (u) = TrialFunction(V) (v) = TestFunction(V) a = dot(curl(u),curl(v))*dx+c*inner(u, v)*dx L1 = inner(v, f)*dx tic() AA, bb = assemble_system(a, L1, bcs) As = AA.sparray() StoreMatrix(As,'A') A = PETSc.Mat().createAIJ(size=As.shape,csr=(As.indptr, As.indices, As.data)) # exit # A = as_backend_type(AA).mat() print toc() b = bb.array() zeros = 0*b x = IO.arrayToVec(zeros) bb = IO.arrayToVec(b) if (Solving == 'Direct'): ksp = PETSc.KSP().create() ksp.setOperators(A) ksp.setFromOptions() ksp.setType(ksp.Type.PREONLY) ksp.pc.setType(ksp.pc.Type.LU) # print 'Solving with:', ksp.getType() # Solve! tic() ksp.solve(bb, x) SolTime[xx-1] = toc() print "time to solve: ",SolTime[xx-1] del AA if (Solving == 'Iterative' or Solving == 'Direct'): if case == 1: ue = Expression(("x[1]*x[1]*(x[1]-1)","x[0]*x[0]*(x[0]-1)")) elif case == 2: ue = Expression(("sin(2*pi*x[1])*cos(2*pi*x[0])","-sin(2*pi*x[0])*cos(2*pi*x[1])")) elif case == 3: ue=u0 elif case == 4: ue=u0 Ve = FunctionSpace(mesh, "N1curl",4) u = interpolate(ue,Ve) Nv = u.vector().array().shape X = IO.vecToArray(x) x = X[0:Nv[0]] ua = Function(V) ua.vector()[:] = x parameters["form_compiler"]["quadrature_degree"] = 4 parameters["form_compiler"]["optimize"] = True ErrorB = Function(V) ErrorB.vector()[:] = interpolate(ue,V).vector().array()-ua.vector().array() errL2b[xx-1] = sqrt(assemble(inner(ErrorB, ErrorB)*dx)) errCurlb[xx-1] = sqrt(assemble(inner(curl(ErrorB), curl(ErrorB))*dx)) if xx == 1: a = 1 else: l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) print errL2b[xx-1] print errCurlb[xx-1] import pandas as pd print "\n\n Magnetic convergence" MagneticTitles = ["Total DoF","Soln Time","B-L2","B-order","B-Curl","Curl-order"] MagneticValues = np.concatenate((Vdim,SolTime,errL2b,l2border,errCurlb,Curlborder),axis=1) MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) pd.set_option('precision',3) MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") print MagneticTable if (SavePrecond == 'yes'): scipy.io.savemat('eigenvalues/Wdim.mat', {'Wdim':Wdim-1},oned_as = 'row') if (ShowResultPlots == 'yes'): plot(ua) plot(interpolate(ue,V)) interactive()
wathen/PhD
MHD/FEniCS/ShiftCurlCurl/saddle.py
Python
mit
5,740
module.exports = { 'handles belongsTo (blog, site)': { mysql: { result: { id: 2, name: 'bookshelfjs.org' } }, postgresql: { result: { id: 2, name: 'bookshelfjs.org' } }, sqlite3: { result: { id: 2, name: 'bookshelfjs.org' } } }, 'handles hasMany (posts)': { mysql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }, postgresql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }, sqlite3: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] } }, 'handles hasOne (meta)': { mysql: { result: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } }, postgresql: { result: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } }, sqlite3: { result: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } }, 'handles belongsToMany (posts)': { mysql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] }, postgresql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] }, sqlite3: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] } }, 'eager loads "hasOne" relationships correctly (site -> meta)': { mysql: { result: { id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } }, postgresql: { result: { id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } }, sqlite3: { result: { id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } } }, 'eager loads "hasMany" relationships correctly (site -> authors, blogs)': { mysql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }], authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } } }, 'eager loads "belongsTo" relationships correctly (blog -> site)': { mysql: { result: { id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } } }, postgresql: { result: { id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } } }, sqlite3: { result: { id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } } } }, 'eager loads "belongsToMany" models correctly (post -> tags)': { mysql: { result: { id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] } }, postgresql: { result: { id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] } }, sqlite3: { result: { id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] } } }, 'Attaches an empty related model or collection if the `EagerRelation` comes back blank': { mysql: { result: { id: 3, name: 'backbonejs.org', meta: { }, blogs: [], authors: [] } }, postgresql: { result: { id: 3, name: 'backbonejs.org', meta: { }, authors: [], blogs: [] } }, sqlite3: { result: { id: 3, name: 'backbonejs.org', meta: { }, blogs: [], authors: [] } } }, 'eager loads "hasOne" models correctly (sites -> meta)': { mysql: { result: [{ id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } },{ id: 2, name: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } },{ id: 3, name: 'backbonejs.org', meta: { } }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } },{ id: 2, name: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } },{ id: 3, name: 'backbonejs.org', meta: { } }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } },{ id: 2, name: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } },{ id: 3, name: 'backbonejs.org', meta: { } }] } }, 'eager loads "belongsTo" models correctly (blogs -> site)': { mysql: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, name: 'Alternate Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } },{ id: 4, site_id: 2, name: 'Alternate Site Blog', site: { id: 2, name: 'bookshelfjs.org' } }] }, postgresql: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, name: 'Alternate Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } },{ id: 4, site_id: 2, name: 'Alternate Site Blog', site: { id: 2, name: 'bookshelfjs.org' } }] }, sqlite3: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, name: 'Alternate Site Blog', site: { id: 1, name: 'knexjs.org' } },{ id: 3, site_id: 2, name: 'Main Site Blog', site: { id: 2, name: 'bookshelfjs.org' } },{ id: 4, site_id: 2, name: 'Alternate Site Blog', site: { id: 2, name: 'bookshelfjs.org' } }] } }, 'eager loads "hasMany" models correctly (site -> blogs)': { mysql: { result: { id: 1, name: 'knexjs.org', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog' },{ id: 2, site_id: 1, name: 'Alternate Site Blog' }] } } }, 'eager loads "belongsToMany" models correctly (posts -> tags)': { mysql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.', tags: [] }] }, postgresql: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.', tags: [] }] }, sqlite3: { result: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', tags: [{ id: 1, name: 'cool', _pivot_post_id: 1, _pivot_tag_id: 1 },{ id: 2, name: 'boring', _pivot_post_id: 1, _pivot_tag_id: 2 },{ id: 3, name: 'exciting', _pivot_post_id: 1, _pivot_tag_id: 3 }] },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.', tags: [] }] } }, 'eager loads "hasMany" -> "hasMany" (site -> authors.ownPosts)': { mysql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] } } }, 'eager loads "hasMany" -> "belongsToMany" (site -> authors.posts)': { mysql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 2, _pivot_post_id: 1 },{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.', _pivot_author_id: 2, _pivot_post_id: 2 }] }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 2, _pivot_post_id: 1 },{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.', _pivot_author_id: 2, _pivot_post_id: 2 }] }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 1, _pivot_post_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', posts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.', _pivot_author_id: 2, _pivot_post_id: 2 },{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.', _pivot_author_id: 2, _pivot_post_id: 1 }] }] } } }, 'does multi deep eager loads (site -> authors.ownPosts, authors.site, blogs.posts)': { mysql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }], site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }], site: { id: 1, name: 'knexjs.org' } }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', posts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' }] }] } }, postgresql: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', site: { id: 1, name: 'knexjs.org' }, ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', site: { id: 1, name: 'knexjs.org' }, ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', posts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' }] }] } }, sqlite3: { result: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }], site: { id: 1, name: 'knexjs.org' } },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }], site: { id: 1, name: 'knexjs.org' } }], blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', posts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', posts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' }] }] } } }, 'eager loads "hasMany" -> "hasMany" (sites -> authors.ownPosts)': { mysql: { result: [{ id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] },{ id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', ownPosts: [{ id: 4, owner_id: 3, blog_id: 3, name: 'This is a new Title 4!', content: 'Lorem ipsum Anim sed eu sint aute.' }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', ownPosts: [{ id: 5, owner_id: 4, blog_id: 4, name: 'This is a new Title 5!', content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.' }] }] },{ id: 3, name: 'backbonejs.org', authors: [] }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] },{ id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', ownPosts: [{ id: 4, owner_id: 3, blog_id: 3, name: 'This is a new Title 4!', content: 'Lorem ipsum Anim sed eu sint aute.' }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', ownPosts: [{ id: 5, owner_id: 4, blog_id: 4, name: 'This is a new Title 5!', content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.' }] }] },{ id: 3, name: 'backbonejs.org', authors: [] }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', ownPosts: [{ id: 1, owner_id: 1, blog_id: 1, name: 'This is a new Title!', content: 'Lorem ipsum Labore eu sed sed Excepteur enim laboris deserunt adipisicing dolore culpa aliqua cupidatat proident ea et commodo labore est adipisicing ex amet exercitation est.' }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', ownPosts: [{ id: 2, owner_id: 2, blog_id: 2, name: 'This is a new Title 2!', content: 'Lorem ipsum Veniam ex amet occaecat dolore in pariatur minim est exercitation deserunt Excepteur enim officia occaecat in exercitation aute et ad esse ex in in dolore amet consequat quis sed mollit et id incididunt sint dolore velit officia dolor dolore laboris dolor Duis ea ex quis deserunt anim nisi qui culpa laboris nostrud Duis anim deserunt esse laboris nulla qui in dolor voluptate aute reprehenderit amet ut et non voluptate elit irure mollit dolor consectetur nisi adipisicing commodo et mollit dolore incididunt cupidatat nulla ut irure deserunt non officia laboris fugiat ut pariatur ut non aliqua eiusmod dolor et nostrud minim elit occaecat commodo consectetur cillum elit laboris mollit dolore amet id qui eiusmod nulla elit eiusmod est ad aliqua aute enim ut aliquip ex in Ut nisi sint exercitation est mollit veniam cupidatat adipisicing occaecat dolor irure in aute aliqua ullamco.' },{ id: 3, owner_id: 2, blog_id: 1, name: 'This is a new Title 3!', content: 'Lorem ipsum Reprehenderit esse esse consectetur aliquip magna.' }] }] },{ id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', ownPosts: [{ id: 4, owner_id: 3, blog_id: 3, name: 'This is a new Title 4!', content: 'Lorem ipsum Anim sed eu sint aute.' }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', ownPosts: [{ id: 5, owner_id: 4, blog_id: 4, name: 'This is a new Title 5!', content: 'Lorem ipsum Commodo consectetur eu ea amet laborum nulla eiusmod minim veniam ullamco nostrud sed mollit consectetur veniam mollit Excepteur quis cupidatat.' }] }] },{ id: 3, name: 'backbonejs.org', authors: [] }] } }, 'eager loads relations on a populated model (site -> blogs, authors.site)': { mysql: { result: { id: 1, name: 'knexjs.org' } }, postgresql: { result: { id: 1, name: 'knexjs.org' } }, sqlite3: { result: { id: 1, name: 'knexjs.org' } } }, 'eager loads attributes on a collection (sites -> blogs, authors.site)': { mysql: { result: [{ id: 1, name: 'knexjs.org' },{ id: 2, name: 'bookshelfjs.org' },{ id: 3, name: 'backbonejs.org' }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org' },{ id: 2, name: 'bookshelfjs.org' },{ id: 3, name: 'backbonejs.org' }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org' },{ id: 2, name: 'bookshelfjs.org' },{ id: 3, name: 'backbonejs.org' }] } }, 'works with many-to-many (user -> roles)': { mysql: { result: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] }, postgresql: { result: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] }, sqlite3: { result: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] } }, 'works with eager loaded many-to-many (user -> roles)': { mysql: { result: { uid: 1, username: 'root', roles: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] } }, postgresql: { result: { uid: 1, username: 'root', roles: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] } }, sqlite3: { result: { uid: 1, username: 'root', roles: [{ rid: 4, name: 'admin', _pivot_uid: 1, _pivot_rid: 4 }] } } }, 'handles morphOne (photo)': { mysql: { result: { id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors' } }, postgresql: { result: { id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors' } }, sqlite3: { result: { id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors' } } }, 'handles morphMany (photo)': { mysql: { result: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] }, postgresql: { result: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] }, sqlite3: { result: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] } }, 'handles morphTo (imageable "authors")': { mysql: { result: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } }, postgresql: { result: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } }, sqlite3: { result: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } } }, 'handles morphTo (imageable "sites")': { mysql: { result: { id: 1, name: 'knexjs.org' } }, postgresql: { result: { id: 1, name: 'knexjs.org' } }, sqlite3: { result: { id: 1, name: 'knexjs.org' } } }, 'eager loads morphMany (sites -> photos)': { mysql: { result: [{ id: 1, name: 'knexjs.org', photos: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] },{ id: 2, name: 'bookshelfjs.org', photos: [{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' }] },{ id: 3, name: 'backbonejs.org', photos: [] }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org', photos: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] },{ id: 2, name: 'bookshelfjs.org', photos: [{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' }] },{ id: 3, name: 'backbonejs.org', photos: [] }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org', photos: [{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites' }] },{ id: 2, name: 'bookshelfjs.org', photos: [{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites' }] },{ id: 3, name: 'backbonejs.org', photos: [] }] } }, 'eager loads morphTo (photos -> imageable)': { mysql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] }, postgresql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] }, sqlite3: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org' } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org' } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] } }, 'eager loads beyond the morphTo, where possible': { mysql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] }, postgresql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] }, sqlite3: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageable: { id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageable: { id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageable: { id: 1, name: 'knexjs.org', authors: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser' },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe' }] } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageable: { id: 2, name: 'bookshelfjs.org', authors: [{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown' },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy' }] } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageable: { } }] } }, 'handles hasMany `through`': { mysql: { result: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] }, postgresql: { result: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] }, sqlite3: { result: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] } }, 'eager loads hasMany `through`': { mysql: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', comments: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', comments: [] }] }, postgresql: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', comments: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', comments: [] }] }, sqlite3: { result: [{ id: 1, site_id: 1, name: 'Main Site Blog', comments: [{ id: 1, post_id: 1, name: '(blank)', email: 'test@example.com', comment: 'this is neat.', _pivot_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, name: 'Alternate Site Blog', comments: [] }] } }, 'handles hasOne `through`': { mysql: { result: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } }, postgresql: { result: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } }, sqlite3: { result: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } } }, 'eager loads hasOne `through`': { mysql: { result: [{ id: 1, name: 'knexjs.org', info: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } },{ id: 2, name: 'bookshelfjs.org', info: { id: 2, meta_id: 2, other_description: 'This is an info block for an eager hasOne -> through test', _pivot_id: 2, _pivot_site_id: 2 } }] }, postgresql: { result: [{ id: 1, name: 'knexjs.org', info: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } },{ id: 2, name: 'bookshelfjs.org', info: { id: 2, meta_id: 2, other_description: 'This is an info block for an eager hasOne -> through test', _pivot_id: 2, _pivot_site_id: 2 } }] }, sqlite3: { result: [{ id: 1, name: 'knexjs.org', info: { id: 1, meta_id: 1, other_description: 'This is an info block for hasOne -> through test', _pivot_id: 1, _pivot_site_id: 1 } },{ id: 2, name: 'bookshelfjs.org', info: { id: 2, meta_id: 2, other_description: 'This is an info block for an eager hasOne -> through test', _pivot_id: 2, _pivot_site_id: 2 } }] } }, 'eager loads belongsToMany `through`': { mysql: { result: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 1, _pivot_owner_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 3, _pivot_owner_id: 2, _pivot_blog_id: 1 },{ id: 2, site_id: 1, name: 'Alternate Site Blog', _pivot_id: 2, _pivot_owner_id: 2, _pivot_blog_id: 2 }] },{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', blogs: [{ id: 3, site_id: 2, name: 'Main Site Blog', _pivot_id: 4, _pivot_owner_id: 3, _pivot_blog_id: 3 }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', blogs: [{ id: 4, site_id: 2, name: 'Alternate Site Blog', _pivot_id: 5, _pivot_owner_id: 4, _pivot_blog_id: 4 }] }] }, postgresql: { result: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 1, _pivot_owner_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 3, _pivot_owner_id: 2, _pivot_blog_id: 1 },{ id: 2, site_id: 1, name: 'Alternate Site Blog', _pivot_id: 2, _pivot_owner_id: 2, _pivot_blog_id: 2 }] },{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', blogs: [{ id: 3, site_id: 2, name: 'Main Site Blog', _pivot_id: 4, _pivot_owner_id: 3, _pivot_blog_id: 3 }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', blogs: [{ id: 4, site_id: 2, name: 'Alternate Site Blog', _pivot_id: 5, _pivot_owner_id: 4, _pivot_blog_id: 4 }] }] }, sqlite3: { result: [{ id: 1, site_id: 1, first_name: 'Tim', last_name: 'Griesser', blogs: [{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 1, _pivot_owner_id: 1, _pivot_blog_id: 1 }] },{ id: 2, site_id: 1, first_name: 'Bazooka', last_name: 'Joe', blogs: [{ id: 2, site_id: 1, name: 'Alternate Site Blog', _pivot_id: 2, _pivot_owner_id: 2, _pivot_blog_id: 2 },{ id: 1, site_id: 1, name: 'Main Site Blog', _pivot_id: 3, _pivot_owner_id: 2, _pivot_blog_id: 1 }] },{ id: 3, site_id: 2, first_name: 'Charlie', last_name: 'Brown', blogs: [{ id: 3, site_id: 2, name: 'Main Site Blog', _pivot_id: 4, _pivot_owner_id: 3, _pivot_blog_id: 3 }] },{ id: 4, site_id: 2, first_name: 'Ron', last_name: 'Burgundy', blogs: [{ id: 4, site_id: 2, name: 'Alternate Site Blog', _pivot_id: 5, _pivot_owner_id: 4, _pivot_blog_id: 4 }] }] } }, '#65 - should eager load correctly for models': { mysql: { result: { hostname: 'google.com', instance_id: 3, route: null, instance: { id: 3, name: 'search engine' } } }, postgresql: { result: { hostname: 'google.com', instance_id: 3, route: null, instance: { id: '3', name: 'search engine' } } }, sqlite3: { result: { hostname: 'google.com', instance_id: 3, route: null, instance: { id: 3, name: 'search engine' } } } }, '#65 - should eager load correctly for collections': { mysql: { result: [{ hostname: 'google.com', instance_id: 3, route: null, instance: { id: 3, name: 'search engine' } },{ hostname: 'apple.com', instance_id: 10, route: null, instance: { id: 10, name: 'computers' } }] }, postgresql: { result: [{ hostname: 'google.com', instance_id: 3, route: null, instance: { id: '3', name: 'search engine' } },{ hostname: 'apple.com', instance_id: 10, route: null, instance: { id: '10', name: 'computers' } }] }, sqlite3: { result: [{ hostname: 'google.com', instance_id: 3, route: null, instance: { id: 3, name: 'search engine' } },{ hostname: 'apple.com', instance_id: 10, route: null, instance: { id: 10, name: 'computers' } }] } }, 'parses eager-loaded morphTo relations (model)': { mysql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageableParsed: { id_parsed: 1, site_id_parsed: 1, first_name_parsed: 'Tim', last_name_parsed: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageableParsed: { id_parsed: 2, site_id_parsed: 1, first_name_parsed: 'Bazooka', last_name_parsed: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageableParsed: { } }] }, postgresql: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageableParsed: { id_parsed: 1, site_id_parsed: 1, first_name_parsed: 'Tim', last_name_parsed: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageableParsed: { id_parsed: 2, site_id_parsed: 1, first_name_parsed: 'Bazooka', last_name_parsed: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageableParsed: { } }] }, sqlite3: { result: [{ id: 1, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'authors', imageableParsed: { id_parsed: 1, site_id_parsed: 1, first_name_parsed: 'Tim', last_name_parsed: 'Griesser' } },{ id: 2, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'authors', imageableParsed: { id_parsed: 2, site_id_parsed: 1, first_name_parsed: 'Bazooka', last_name_parsed: 'Joe' } },{ id: 3, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 4, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 1, imageable_type: 'sites', imageableParsed: { id_parsed: 1, name_parsed: 'knexjs.org', meta: { id: 1, site_id: 1, description: 'This is a description for the Knexjs Site' } } },{ id: 5, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 6, url: 'https://www.google.com/images/srpr/logo4w.png', caption: 'Lorem ipsum Quis Ut eu nostrud ea sint aute non aliqua ut ullamco cupidatat exercitation nisi nisi.', imageable_id: 2, imageable_type: 'sites', imageableParsed: { id_parsed: 2, name_parsed: 'bookshelfjs.org', meta: { id: 2, site_id: 2, description: 'This is a description for the Bookshelfjs Site' } } },{ id: 7, url: 'http://image.dev', caption: 'this is a test image', imageable_id: 10, imageable_type: 'sites', imageableParsed: { } }] } } };
viniborges/designizando
node_modules/bookshelf/test/integration/output/Relations.js
JavaScript
mit
97,438
package principal.peticiones; import java.io.Serializable; import principal.cs.*; public class PeticionRegistro implements Serializable{ private String usuario; private char[] password; private String email; public PeticionRegistro(String u, char[] p, String e) { this.usuario = u; this.password = p; this.email = e; } public String getUsuario(){ return this.usuario; } public char[] getPassword(){ return this.password; } public String getEmail(){ return this.email; } }
Crakens/jrpg
TheLordOfSouls/src/principal/peticiones/PeticionRegistro.java
Java
mit
507
/** * Module dependencies */ var Server = require('annex-ws-node').Server; var http = require('http'); var stack = require('connect-stack'); var pns = require('pack-n-stack'); module.exports = function createServer(opts) { var server = http.createServer(); server.stack = []; server.handle = stack(server.stack); server.use = function(fn) { fn.handle = fn; server.stack.push(fn); return server; }; var routes = server.routes = {}; var hasPushedRouter = false; server.register = server.fn = function(modName, fnName, cb) { var mod = routes[modName] = routes[modName] || {}; var fn = mod[fnName] = mod[fnName] || []; fn.push(cb); server.emit('register:call', modName, fnName); if (hasPushedRouter) return server; server.use(router); hasPushedRouter = true; return server; }; function router(req, res, next) { var mod = routes[req.module]; if (!mod) return next(); var fn = mod[req.method]; if (!fn) return next(); // TODO support next('route') fn[0](req, res, next); } var wss = new Server({server: server, marshal: opts.marshal}); wss.listen(function(req, res) { // TODO do a domain here server.handle(req, res, function(err) { if (!res._sent) { err ? res.error(err.message) : res.error(req.module + ':' + req.method + ' not implemented'); if (err) console.error(err.stack || err.message); } }); }); return server; }
poegroup/poe-service-node
server.js
JavaScript
mit
1,468
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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. */ package org.spongepowered.common.registry.type.block; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import net.minecraft.block.BlockDoublePlant; import org.spongepowered.api.data.type.DoublePlantType; import org.spongepowered.api.data.type.DoublePlantTypes; import org.spongepowered.common.registry.CatalogRegistryModule; import org.spongepowered.common.registry.util.RegisterCatalog; import java.util.Collection; import java.util.Map; import java.util.Optional; public final class DoublePlantTypeRegistryModule implements CatalogRegistryModule<DoublePlantType> { @RegisterCatalog(DoublePlantTypes.class) private final Map<String, DoublePlantType> doublePlantMappings = new ImmutableMap.Builder<String, DoublePlantType>() .put("sunflower", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.SUNFLOWER) .put("syringa", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.SYRINGA) .put("grass", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.GRASS) .put("fern", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.FERN) .put("rose", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.ROSE) .put("paeonia", (DoublePlantType) (Object) BlockDoublePlant.EnumPlantType.PAEONIA) .build(); @Override public Optional<DoublePlantType> getById(String id) { return Optional.ofNullable(this.doublePlantMappings.get(checkNotNull(id).toLowerCase())); } @Override public Collection<DoublePlantType> getAll() { return ImmutableList.copyOf(this.doublePlantMappings.values()); } }
kamcio96/SpongeCommon
src/main/java/org/spongepowered/common/registry/type/block/DoublePlantTypeRegistryModule.java
Java
mit
2,972
(function () { 'use strict'; /* Controllers */ var pollsControllers = angular.module('pollsControllers', []); var author = 'Patrick Nicholls'; pollsControllers.controller('PollListCtrl', ['$scope', '$http', function ($scope, $http) { var resource = "/~pjn59/365/polls/index.php/services/polls"; $scope.polls = undefined; $scope.author = author; $http.get(resource) .success(function(data){ $scope.polls = data; }) .error(function(){ console.log("Couldn't get data"); }); }]); pollsControllers.controller('PollDetailCtrl', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) { $scope.pollId = $routeParams.pollId; $scope.title = undefined; $scope.quesiton = undefined; $scope.choice = undefined; var base_url = "/~pjn59/365/polls/index.php/services/"; $http.get(base_url + "polls/" + $scope.pollId) .success(function(data){ console.log(data); var choices = []; for (var i = 0; i < data.choices.length; i++) { choices[i] = { 'choice': data.choices[i], 'votes' : parseInt(data.votes[i]) }; } $scope.choices = choices; $scope.question = data.question; $scope.title = data.title; console.log($scope.choices); }) .error(function(){ console.log("Couldn't get data"); }); $scope.vote = function() { //Increment database through PHP somehow $scope.choices[$scope.choice-1].votes += 1; $http.post(base_url + "votes/" + $scope.pollId + "/" + $scope.choice) .success(function(data){ console.log("Vote succeeded") }) .error(function(){ console.log("Vote unsuccessful"); }); }; $scope.reset = function() { for (var i = 0; i < $scope.choices.length; i++) { $scope.choices[i].votes = 0; } $http.delete(base_url + "votes/" + $scope.pollId) .success(function(data){ console.log("Reset succeeded") }) .error(function(){ console.log("Reset unsuccessful"); }); } }]); pollsControllers.controller('AboutCtrl', ['$scope', function ($scope) { $scope.author = author; }]); }())
agronauts/poll
angularjs/js/controllers.js
JavaScript
mit
2,957
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-08-01 07:59 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion import proso.django.models class Migration(migrations.Migration): initial = True dependencies = [ ('proso_user', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('proso_common', '0001_initial'), ] operations = [ migrations.CreateModel( name='Answer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.DateTimeField(default=datetime.datetime.now)), ('response_time', models.IntegerField()), ('guess', models.FloatField(default=0)), ('type', models.CharField(max_length=10)), ('lang', models.CharField(blank=True, default=None, max_length=2, null=True)), ('config', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_common.Config')), ], ), migrations.CreateModel( name='AnswerMeta', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.TextField()), ('content_hash', models.CharField(db_index=True, max_length=40, unique=True)), ], ), migrations.CreateModel( name='Audit', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('key', models.CharField(max_length=50)), ('value', models.FloatField()), ('time', models.DateTimeField(default=datetime.datetime.now)), ('answer', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.Answer')), ], ), migrations.CreateModel( name='EnvironmentInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status', models.IntegerField(choices=[(0, 'disabled'), (1, 'loading'), (2, 'enabled'), (3, 'active')], default=1)), ('revision', models.IntegerField()), ('load_progress', models.IntegerField(default=0)), ('updated', models.DateTimeField(auto_now=True)), ('created', models.DateTimeField(auto_now_add=True)), ('config', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='proso_common.Config')), ], ), migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('active', models.BooleanField(default=True)), ], bases=(models.Model, proso.django.models.ModelDiffMixin), ), migrations.CreateModel( name='ItemRelation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('visible', models.BooleanField(default=True)), ('active', models.BooleanField(default=True)), ('child', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='child_relations', to='proso_models.Item')), ('parent', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='parent_relations', to='proso_models.Item')), ], bases=(models.Model, proso.django.models.ModelDiffMixin), ), migrations.CreateModel( name='ItemType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('model', models.CharField(max_length=100)), ('table', models.CharField(max_length=100)), ('foreign_key', models.CharField(max_length=100)), ('language', models.CharField(blank=True, default=None, max_length=100, null=True)), ('valid', models.BooleanField(default=True)), ], ), migrations.CreateModel( name='PracticeContext', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.TextField()), ('content_hash', models.CharField(db_index=True, max_length=40, unique=True)), ], ), migrations.CreateModel( name='PracticeSet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('finished', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='Variable', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('permanent', models.BooleanField(default=False)), ('key', models.CharField(max_length=50)), ('value', models.FloatField()), ('audit', models.BooleanField(default=True)), ('updated', models.DateTimeField(default=datetime.datetime.now)), ('answer', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.Answer')), ('info', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.EnvironmentInfo')), ('item_primary', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='item_primary_variables', to='proso_models.Item')), ('item_secondary', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='item_secondary_variables', to='proso_models.Item')), ('user', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AlterUniqueTogether( name='itemtype', unique_together=set([('model', 'foreign_key'), ('table', 'foreign_key')]), ), migrations.AddField( model_name='item', name='children', field=models.ManyToManyField(related_name='parents', through='proso_models.ItemRelation', to='proso_models.Item'), ), migrations.AddField( model_name='item', name='item_type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.ItemType'), ), migrations.AddField( model_name='audit', name='info', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.EnvironmentInfo'), ), migrations.AddField( model_name='audit', name='item_primary', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='item_primary_audits', to='proso_models.Item'), ), migrations.AddField( model_name='audit', name='item_secondary', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='item_secondary_audits', to='proso_models.Item'), ), migrations.AddField( model_name='audit', name='user', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='answer', name='context', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.PracticeContext'), ), migrations.AddField( model_name='answer', name='item', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='item_answers', to='proso_models.Item'), ), migrations.AddField( model_name='answer', name='item_answered', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='item_answered_answers', to='proso_models.Item'), ), migrations.AddField( model_name='answer', name='item_asked', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='item_asked_answers', to='proso_models.Item'), ), migrations.AddField( model_name='answer', name='metainfo', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.AnswerMeta'), ), migrations.AddField( model_name='answer', name='practice_set', field=models.ForeignKey(blank=None, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.PracticeSet'), ), migrations.AddField( model_name='answer', name='session', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_user.Session'), ), migrations.AddField( model_name='answer', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AlterUniqueTogether( name='variable', unique_together=set([('info', 'key', 'user', 'item_primary', 'item_secondary')]), ), migrations.AlterIndexTogether( name='variable', index_together=set([('info', 'key', 'user'), ('info', 'key', 'user', 'item_primary'), ('info', 'key', 'user', 'item_primary', 'item_secondary'), ('info', 'key', 'item_primary'), ('info', 'key')]), ), migrations.AlterUniqueTogether( name='environmentinfo', unique_together=set([('config', 'revision')]), ), migrations.AlterIndexTogether( name='audit', index_together=set([('info', 'key', 'user'), ('info', 'key', 'user', 'item_primary'), ('info', 'key', 'user', 'item_primary', 'item_secondary'), ('info', 'key', 'item_primary'), ('info', 'key')]), ), migrations.AlterIndexTogether( name='answer', index_together=set([('user', 'context')]), ), ]
adaptive-learning/proso-apps
proso_models/migrations/0001_initial.py
Python
mit
11,335
require 'spec_helper' RSpec.describe 'btse integration specs' do let(:client) { Cryptoexchange::Client.new } let(:btc_usd_pair) { Cryptoexchange::Models::MarketPair.new(base: 'BTC', target: 'USD', market: 'btse') } it 'fetch pairs' do pairs = client.pairs('btse') expect(pairs).not_to be_empty pair = pairs.first expect(pair.base).to_not be nil expect(pair.target).to_not be nil expect(pair.market).to eq 'btse' end it 'give trade url' do trade_page_url = client.trade_page_url 'btse', base: btc_usd_pair.base, target: btc_usd_pair.target expect(trade_page_url).to eq "https://www.btse.com/en/trading/BTC-USD" end it 'fetch ticker' do ticker = client.ticker(btc_usd_pair) expect(ticker.base).to eq 'BTC' expect(ticker.target).to eq 'USD' expect(ticker.market).to eq 'btse' expect(ticker.last).to be_a Numeric expect(ticker.ask).to be_a Numeric expect(ticker.bid).to be_a Numeric expect(ticker.high).to be_a Numeric expect(ticker.low).to be_a Numeric expect(ticker.volume).to be_a Numeric expect(ticker.change).to be_a Numeric expect(ticker.timestamp).to be nil expect(ticker.payload).to_not be nil end it 'fetch order book' do order_book = client.order_book(btc_usd_pair) expect(order_book.base).to eq 'BTC' expect(order_book.target).to eq 'USD' expect(order_book.market).to eq 'btse' expect(order_book.asks).to_not be_empty expect(order_book.bids).to_not be_empty expect(order_book.asks.first.price).to_not be_nil expect(order_book.bids.first.amount).to_not be_nil expect(order_book.bids.first.timestamp).to be_nil expect(order_book.asks.count).to be > 0 expect(order_book.bids.count).to be > 0 expect(order_book.timestamp).to be_a Numeric expect(order_book.payload).to_not be nil end it 'fetch trade' do trades = client.trades(btc_usd_pair) trade = trades.sample expect(trades).to_not be_empty expect(trade.trade_id).to_not be_nil expect(trade.base).to eq 'BTC' expect(trade.target).to eq 'USD' expect(['buy', 'sell']).to include trade.type expect(trade.price).to_not be_nil expect(trade.amount).to_not be_nil expect(trade.timestamp).to be_a Numeric expect(trade.payload).to_not be nil expect(trade.market).to eq 'btse' end end
coingecko/cryptoexchange
spec/exchanges/btse/integration/market_spec.rb
Ruby
mit
2,357
package TerrariaClone.GameData; import TerrariaClone.BlockToolsProvider; import TerrariaClone.HorrificBlockNameProvider; import TerrariaClone.HorrificBlockToolsProvider; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class JsonBlockToolsProviderTest { @Test public void constantlyBootstrapBlockTools() { String[] blocknames = new HorrificBlockNameProvider().getBlockNames(); JsonBlockToolsProvider provider = new JsonBlockToolsProvider(); HorrificBlockToolsProvider horrible_provider = new HorrificBlockToolsProvider(); provider.createBlockToolsData(horrible_provider.getBlockToolsData()); } @Test public void getBlockTools() throws Exception { String[] blocknames = new HorrificBlockNameProvider().getBlockNames(); BlockToolsProvider provider = new JsonBlockToolsProvider(); BlockToolsProvider horrible_provider = new HorrificBlockToolsProvider(); HashMap<Integer, Short[]> newData= provider.getBlockTools(blocknames); HashMap<Integer, Short[]> originalData= provider.getBlockTools(blocknames); assertMapWithArrayEqual(newData, originalData); } public static void assertMapWithArrayEqual(Map<Integer,Short[]> lhs, Map<Integer, Short[]> rhs) { assertArrayEquals("Map keys should be the same", lhs.keySet().toArray(), rhs.keySet().toArray()); for(Integer key : lhs.keySet()) { assertArrayEquals("Inner arrays should be the same", lhs.get(key), rhs.get(key)); } } }
polytomous/TerrariaClone
src/test/java/TerrariaClone/GameData/JsonBlockToolsProviderTest.java
Java
mit
1,606
namespace Elephant.Hank.WindowsApplication { partial class frmMain { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); this.tmrSchedular = new System.Windows.Forms.Timer(this.components); this.mnuCtxRightClick = new System.Windows.Forms.ContextMenuStrip(this.components); this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.sysTray = new System.Windows.Forms.NotifyIcon(this.components); this.btnSave = new System.Windows.Forms.Button(); this.tmrHideMe = new System.Windows.Forms.Timer(this.components); this.tmrCleaner = new System.Windows.Forms.Timer(this.components); this.grpCleaner = new System.Windows.Forms.GroupBox(); this.lblCleanerHours = new System.Windows.Forms.Label(); this.txtCleanerRunAtHour = new System.Windows.Forms.TextBox(); this.lblClearReportHours = new System.Windows.Forms.Label(); this.lblClearLogHours = new System.Windows.Forms.Label(); this.txtClearReportHours = new System.Windows.Forms.TextBox(); this.txtClearLogHours = new System.Windows.Forms.TextBox(); this.grpBase = new System.Windows.Forms.GroupBox(); this.lblBaseWebUrl = new System.Windows.Forms.Label(); this.txtBaseWebUrl = new System.Windows.Forms.TextBox(); this.lblFrameworkBasePath = new System.Windows.Forms.Label(); this.txtFrameworkBasePath = new System.Windows.Forms.TextBox(); this.lblBaseApiUrl = new System.Windows.Forms.Label(); this.txtBaseApiUrl = new System.Windows.Forms.TextBox(); this.lblExecutionTimeLapseInMilli = new System.Windows.Forms.Label(); this.txtExecutionTimeLapseInMilli = new System.Windows.Forms.TextBox(); this.btnClose = new System.Windows.Forms.Button(); this.btnCompressPng = new System.Windows.Forms.Button(); this.grpRunning = new System.Windows.Forms.GroupBox(); this.dgRunning = new System.Windows.Forms.DataGridView(); this.grpInQueue = new System.Windows.Forms.GroupBox(); this.dgInQueue = new System.Windows.Forms.DataGridView(); this.btnClearHub = new System.Windows.Forms.Button(); this.btnPause = new System.Windows.Forms.Button(); this.mnuCtxRightClick.SuspendLayout(); this.grpCleaner.SuspendLayout(); this.grpBase.SuspendLayout(); this.grpRunning.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgRunning)).BeginInit(); this.grpInQueue.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgInQueue)).BeginInit(); this.SuspendLayout(); // // tmrSchedular // this.tmrSchedular.Enabled = true; this.tmrSchedular.Interval = 10000; this.tmrSchedular.Tick += new System.EventHandler(this.tmrSchedular_Tick); // // mnuCtxRightClick // this.mnuCtxRightClick.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.settingsToolStripMenuItem, this.toolStripSeparator1, this.exitToolStripMenuItem1}); this.mnuCtxRightClick.Name = "mnuCtxRightCLick"; this.mnuCtxRightClick.Size = new System.Drawing.Size(117, 54); // // settingsToolStripMenuItem // this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem"; this.settingsToolStripMenuItem.Size = new System.Drawing.Size(116, 22); this.settingsToolStripMenuItem.Text = "Settings"; this.settingsToolStripMenuItem.Click += new System.EventHandler(this.settingsToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(113, 6); // // exitToolStripMenuItem1 // this.exitToolStripMenuItem1.Name = "exitToolStripMenuItem1"; this.exitToolStripMenuItem1.Size = new System.Drawing.Size(116, 22); this.exitToolStripMenuItem1.Text = "E&xit"; this.exitToolStripMenuItem1.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // sysTray // this.sysTray.ContextMenuStrip = this.mnuCtxRightClick; this.sysTray.Icon = ((System.Drawing.Icon)(resources.GetObject("sysTray.Icon"))); this.sysTray.Text = "Protractor controller"; this.sysTray.Visible = true; this.sysTray.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.sysTray_MouseDoubleClick); // // btnSave // this.btnSave.Location = new System.Drawing.Point(519, 605); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(75, 23); this.btnSave.TabIndex = 4; this.btnSave.Text = "S&ave"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // tmrHideMe // this.tmrHideMe.Enabled = true; this.tmrHideMe.Interval = 1000; this.tmrHideMe.Tick += new System.EventHandler(this.tmrHideMe_Tick); // // tmrCleaner // this.tmrCleaner.Enabled = true; this.tmrCleaner.Interval = 10000; this.tmrCleaner.Tick += new System.EventHandler(this.tmrCleaner_Tick); // // grpCleaner // this.grpCleaner.Controls.Add(this.lblCleanerHours); this.grpCleaner.Controls.Add(this.txtCleanerRunAtHour); this.grpCleaner.Controls.Add(this.lblClearReportHours); this.grpCleaner.Controls.Add(this.lblClearLogHours); this.grpCleaner.Controls.Add(this.txtClearReportHours); this.grpCleaner.Controls.Add(this.txtClearLogHours); this.grpCleaner.Location = new System.Drawing.Point(12, 170); this.grpCleaner.Name = "grpCleaner"; this.grpCleaner.Size = new System.Drawing.Size(663, 122); this.grpCleaner.TabIndex = 22; this.grpCleaner.TabStop = false; this.grpCleaner.Text = "I/O Cleaner Setup"; // // lblCleanerHours // this.lblCleanerHours.AutoSize = true; this.lblCleanerHours.Location = new System.Drawing.Point(36, 30); this.lblCleanerHours.Name = "lblCleanerHours"; this.lblCleanerHours.Size = new System.Drawing.Size(108, 13); this.lblCleanerHours.TabIndex = 27; this.lblCleanerHours.Text = "Cleaner run at (hours)"; // // txtCleanerRunAtHour // this.txtCleanerRunAtHour.Location = new System.Drawing.Point(187, 30); this.txtCleanerRunAtHour.Name = "txtCleanerRunAtHour"; this.txtCleanerRunAtHour.Size = new System.Drawing.Size(435, 20); this.txtCleanerRunAtHour.TabIndex = 26; // // lblClearReportHours // this.lblClearReportHours.AutoSize = true; this.lblClearReportHours.Location = new System.Drawing.Point(36, 82); this.lblClearReportHours.Name = "lblClearReportHours"; this.lblClearReportHours.Size = new System.Drawing.Size(136, 13); this.lblClearReportHours.TabIndex = 25; this.lblClearReportHours.Text = "Keep report data for (hours)"; // // lblClearLogHours // this.lblClearLogHours.AutoSize = true; this.lblClearLogHours.Location = new System.Drawing.Point(36, 56); this.lblClearLogHours.Name = "lblClearLogHours"; this.lblClearLogHours.Size = new System.Drawing.Size(128, 13); this.lblClearLogHours.TabIndex = 24; this.lblClearLogHours.Text = "Keep logs data for (hours)"; // // txtClearReportHours // this.txtClearReportHours.Location = new System.Drawing.Point(187, 82); this.txtClearReportHours.Name = "txtClearReportHours"; this.txtClearReportHours.Size = new System.Drawing.Size(435, 20); this.txtClearReportHours.TabIndex = 23; // // txtClearLogHours // this.txtClearLogHours.Location = new System.Drawing.Point(187, 56); this.txtClearLogHours.Name = "txtClearLogHours"; this.txtClearLogHours.Size = new System.Drawing.Size(435, 20); this.txtClearLogHours.TabIndex = 22; // // grpBase // this.grpBase.Controls.Add(this.lblBaseWebUrl); this.grpBase.Controls.Add(this.txtBaseWebUrl); this.grpBase.Controls.Add(this.lblFrameworkBasePath); this.grpBase.Controls.Add(this.txtFrameworkBasePath); this.grpBase.Controls.Add(this.lblBaseApiUrl); this.grpBase.Controls.Add(this.txtBaseApiUrl); this.grpBase.Controls.Add(this.lblExecutionTimeLapseInMilli); this.grpBase.Controls.Add(this.txtExecutionTimeLapseInMilli); this.grpBase.Location = new System.Drawing.Point(12, 12); this.grpBase.Name = "grpBase"; this.grpBase.Size = new System.Drawing.Size(663, 152); this.grpBase.TabIndex = 23; this.grpBase.TabStop = false; this.grpBase.Text = "Base Setup"; // // lblBaseWebUrl // this.lblBaseWebUrl.AutoSize = true; this.lblBaseWebUrl.Location = new System.Drawing.Point(36, 86); this.lblBaseWebUrl.Name = "lblBaseWebUrl"; this.lblBaseWebUrl.Size = new System.Drawing.Size(71, 13); this.lblBaseWebUrl.TabIndex = 23; this.lblBaseWebUrl.Text = "Base Web url"; // // txtBaseWebUrl // this.txtBaseWebUrl.Location = new System.Drawing.Point(187, 83); this.txtBaseWebUrl.Name = "txtBaseWebUrl"; this.txtBaseWebUrl.Size = new System.Drawing.Size(435, 20); this.txtBaseWebUrl.TabIndex = 18; // // lblFrameworkBasePath // this.lblFrameworkBasePath.AutoSize = true; this.lblFrameworkBasePath.Location = new System.Drawing.Point(37, 113); this.lblFrameworkBasePath.Name = "lblFrameworkBasePath"; this.lblFrameworkBasePath.Size = new System.Drawing.Size(109, 13); this.lblFrameworkBasePath.TabIndex = 22; this.lblFrameworkBasePath.Text = "Framework base path"; // // txtFrameworkBasePath // this.txtFrameworkBasePath.Location = new System.Drawing.Point(187, 110); this.txtFrameworkBasePath.Name = "txtFrameworkBasePath"; this.txtFrameworkBasePath.Size = new System.Drawing.Size(435, 20); this.txtFrameworkBasePath.TabIndex = 20; // // lblBaseApiUrl // this.lblBaseApiUrl.AutoSize = true; this.lblBaseApiUrl.Location = new System.Drawing.Point(37, 60); this.lblBaseApiUrl.Name = "lblBaseApiUrl"; this.lblBaseApiUrl.Size = new System.Drawing.Size(65, 13); this.lblBaseApiUrl.TabIndex = 21; this.lblBaseApiUrl.Text = "Base Api Url"; // // txtBaseApiUrl // this.txtBaseApiUrl.Location = new System.Drawing.Point(187, 57); this.txtBaseApiUrl.Name = "txtBaseApiUrl"; this.txtBaseApiUrl.Size = new System.Drawing.Size(435, 20); this.txtBaseApiUrl.TabIndex = 17; // // lblExecutionTimeLapseInMilli // this.lblExecutionTimeLapseInMilli.AutoSize = true; this.lblExecutionTimeLapseInMilli.Location = new System.Drawing.Point(37, 34); this.lblExecutionTimeLapseInMilli.Name = "lblExecutionTimeLapseInMilli"; this.lblExecutionTimeLapseInMilli.Size = new System.Drawing.Size(67, 13); this.lblExecutionTimeLapseInMilli.TabIndex = 19; this.lblExecutionTimeLapseInMilli.Text = "Time interval"; // // txtExecutionTimeLapseInMilli // this.txtExecutionTimeLapseInMilli.Location = new System.Drawing.Point(187, 31); this.txtExecutionTimeLapseInMilli.Name = "txtExecutionTimeLapseInMilli"; this.txtExecutionTimeLapseInMilli.Size = new System.Drawing.Size(435, 20); this.txtExecutionTimeLapseInMilli.TabIndex = 16; // // btnClose // this.btnClose.Location = new System.Drawing.Point(600, 605); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(75, 23); this.btnClose.TabIndex = 24; this.btnClose.Text = "Cl&ose"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnCompressPng // this.btnCompressPng.Location = new System.Drawing.Point(393, 605); this.btnCompressPng.Name = "btnCompressPng"; this.btnCompressPng.Size = new System.Drawing.Size(120, 23); this.btnCompressPng.TabIndex = 25; this.btnCompressPng.Text = "Compress Png to Jpg"; this.btnCompressPng.UseVisualStyleBackColor = true; this.btnCompressPng.Click += new System.EventHandler(this.btnCompressPng_Click); // // grpRunning // this.grpRunning.Controls.Add(this.dgRunning); this.grpRunning.Location = new System.Drawing.Point(12, 298); this.grpRunning.Name = "grpRunning"; this.grpRunning.Size = new System.Drawing.Size(663, 140); this.grpRunning.TabIndex = 26; this.grpRunning.TabStop = false; this.grpRunning.Text = "Running"; // // dgRunning // this.dgRunning.AllowUserToAddRows = false; this.dgRunning.AllowUserToDeleteRows = false; dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.dgRunning.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; this.dgRunning.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dgRunning.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgRunning.Location = new System.Drawing.Point(10, 22); this.dgRunning.Name = "dgRunning"; this.dgRunning.ReadOnly = true; this.dgRunning.Size = new System.Drawing.Size(640, 112); this.dgRunning.TabIndex = 0; // // grpInQueue // this.grpInQueue.Controls.Add(this.dgInQueue); this.grpInQueue.Location = new System.Drawing.Point(12, 444); this.grpInQueue.Name = "grpInQueue"; this.grpInQueue.Size = new System.Drawing.Size(663, 140); this.grpInQueue.TabIndex = 27; this.grpInQueue.TabStop = false; this.grpInQueue.Text = "In Queue"; // // dgInQueue // this.dgInQueue.AllowUserToAddRows = false; this.dgInQueue.AllowUserToDeleteRows = false; dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.dgInQueue.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle2; this.dgInQueue.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dgInQueue.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgInQueue.Location = new System.Drawing.Point(10, 19); this.dgInQueue.Name = "dgInQueue"; this.dgInQueue.ReadOnly = true; this.dgInQueue.Size = new System.Drawing.Size(640, 115); this.dgInQueue.TabIndex = 1; // // btnClearHub // this.btnClearHub.Location = new System.Drawing.Point(267, 605); this.btnClearHub.Name = "btnClearHub"; this.btnClearHub.Size = new System.Drawing.Size(120, 23); this.btnClearHub.TabIndex = 28; this.btnClearHub.Text = "Clear Hub"; this.btnClearHub.UseVisualStyleBackColor = true; this.btnClearHub.Click += new System.EventHandler(this.btnClearHub_Click); // // btnPause // this.btnPause.Location = new System.Drawing.Point(141, 605); this.btnPause.Name = "btnPause"; this.btnPause.Size = new System.Drawing.Size(120, 23); this.btnPause.TabIndex = 29; this.btnPause.Text = "Pause"; this.btnPause.UseVisualStyleBackColor = true; this.btnPause.Click += new System.EventHandler(this.btnPause_Click); // // frmMain // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(689, 640); this.ContextMenuStrip = this.mnuCtxRightClick; this.Controls.Add(this.btnPause); this.Controls.Add(this.btnClearHub); this.Controls.Add(this.grpInQueue); this.Controls.Add(this.grpRunning); this.Controls.Add(this.btnCompressPng); this.Controls.Add(this.btnClose); this.Controls.Add(this.grpBase); this.Controls.Add(this.grpCleaner); this.Controls.Add(this.btnSave); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmMain"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Settings"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMain_FormClosing); this.Load += new System.EventHandler(this.frmMain_Load); this.Resize += new System.EventHandler(this.frmMain_Resize); this.mnuCtxRightClick.ResumeLayout(false); this.grpCleaner.ResumeLayout(false); this.grpCleaner.PerformLayout(); this.grpBase.ResumeLayout(false); this.grpBase.PerformLayout(); this.grpRunning.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgRunning)).EndInit(); this.grpInQueue.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgInQueue)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Timer tmrSchedular; private System.Windows.Forms.ContextMenuStrip mnuCtxRightClick; private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem1; private System.Windows.Forms.NotifyIcon sysTray; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.Timer tmrHideMe; private System.Windows.Forms.Timer tmrCleaner; private System.Windows.Forms.GroupBox grpCleaner; private System.Windows.Forms.Label lblClearReportHours; private System.Windows.Forms.Label lblClearLogHours; private System.Windows.Forms.TextBox txtClearReportHours; private System.Windows.Forms.TextBox txtClearLogHours; private System.Windows.Forms.GroupBox grpBase; private System.Windows.Forms.Label lblBaseWebUrl; private System.Windows.Forms.TextBox txtBaseWebUrl; private System.Windows.Forms.Label lblFrameworkBasePath; private System.Windows.Forms.TextBox txtFrameworkBasePath; private System.Windows.Forms.Label lblBaseApiUrl; private System.Windows.Forms.TextBox txtBaseApiUrl; private System.Windows.Forms.Label lblExecutionTimeLapseInMilli; private System.Windows.Forms.TextBox txtExecutionTimeLapseInMilli; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Button btnCompressPng; private System.Windows.Forms.Label lblCleanerHours; private System.Windows.Forms.TextBox txtCleanerRunAtHour; private System.Windows.Forms.GroupBox grpRunning; private System.Windows.Forms.GroupBox grpInQueue; private System.Windows.Forms.DataGridView dgRunning; private System.Windows.Forms.DataGridView dgInQueue; private System.Windows.Forms.Button btnClearHub; private System.Windows.Forms.Button btnPause; } }
elephant-insurance/hank
Elephant.Hank.WindowsApplication/src/WindowsApplication/frmMain.Designer.cs
C#
mit
23,273
declare module "*.png" declare module "*.webp"
artsy/eigen
typings/images.d.ts
TypeScript
mit
47
#!/usr/bin/env python # Usage parse_shear sequences.fna a2t.txt emb_output.b6 import sys import csv from collections import Counter, defaultdict sequences = sys.argv[1] accession2taxonomy = sys.argv[2] alignment = sys.argv[3] with open(accession2taxonomy) as inf: next(inf) csv_inf = csv.reader(inf, delimiter="\t") a2t = dict(('_'.join(row[0].split()[0].split('_')[:-1]).split('.')[0], row[-1]) for row in csv_inf) print("Loaded accession2taxonomy.") reads_counter = Counter() with open(sequences) as inf: for i, line in enumerate(inf): if i % 100000 == 0: print("Processed %d lines" % i) print(line) if line.startswith('>'): name = '_'.join(line.split()[0][1:].split('_')[:-1]).split('.')[0] if name in a2t: species = a2t[name] reads_counter.update([species]) print("Loaded read counter") counts_dict = defaultdict(Counter) with open(alignment) as inf: csv_inf = csv.reader(inf, delimiter="\t") for i, row in enumerate(csv_inf): if i % 100000 == 0: print("Processed %d records" % i) print(row) if row[-1].startswith('k'): read = row[0] read = "_".join(read.split('_')[:-1]).split('.')[0] if read in a2t: species = a2t[read] tax = row[-1] counts_dict[species].update([tax]) print("Loaded counts_dict.") with open("sheared_bayes.txt", "w") as outf: for i, species in enumerate(counts_dict.keys()): row = [0] * 10 row[-1] = reads_counter[species] row[0] = species counts = counts_dict[species] if i % 10000 == 0: print("Processed %d records" % i) print(counts) for j in counts.keys(): c = j.count(';') row[c+1] = counts[j] row = list(map(str, row)) outf.write("\t".join(row) + "\n")
knights-lab/analysis_SHOGUN
scripts/parse_shear.py
Python
mit
2,010
<?php namespace Bprs\CommandLineBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class StopWorkerCommand extends ContainerAwareCommand { private $jobservice; public function __construct($jobService) { $this->jobservice = $jobService; parent::__construct(); } /** * {@inheritdoc} */ protected function configure() { $this ->setName('bprs:commandline:stop_worker') ->addOption('force', false, InputOption::VALUE_NONE, 'force quit (kill -9)') ->setDescription('Stops all workers on this machine'); } protected function execute(InputInterface $input, OutputInterface $output) { $this->jobservice->stopWorkers($input->getOption('force')); } }
SrgSteak/BPRSCommandlineBundle
Command/StopWorkerCommand.php
PHP
mit
954
//----------------------------------------------------------------------- // <copyright file="InputArgs.cs" company="Sully"> // Copyright (c) Johnathon Sullinger. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace MudDesigner.Engine { using System; /// <summary> /// Input Arguments provided when an event is fired requiring messaging support. /// </summary> public sealed class InputArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref="InputArgs"/> class. /// </summary> /// <param name="message">The message.</param> public InputArgs(string message) { this.Message = message; } /// <summary> /// Gets the message. /// </summary> public string Message { get; } } }
MudDesigner/MudDesigner
Source/Runtime/MudDesigner.Engine/InputArgs.cs
C#
mit
902
<?php include("init.php"); # Conexão mysql_connect($bd, $user, $pass) or die('Não foi possível conectar ao banco de dados: ' . mysql_error()); # Escolhendo o banco de dados mysql_select_db($db) or die('Não foi possível selecionar o banco de dados'); ?>
leonebruno/qr-school
Servidor/Config/Conn/mysql/conn.php
PHP
mit
269
// Generated by CoffeeScript 1.7.1 (function() { var ERROR, IGNORE, WARN; ERROR = 'error'; WARN = 'warn'; IGNORE = 'ignore'; module.exports = { coffeescript_error: { level: ERROR, message: '' } }; }).call(this);
prehnRA/lintron
src/coffeelint/lib/rules.js
JavaScript
mit
249