repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
rcapel/FRED-API-Toolkit
Version 2.0/FREDApi/FREDApi/Core/Requests/Request.cs
5358
using FRED.Api.Core.Arguments; using Newtonsoft.Json; using System; using System.IO; using System.Net; using System.Threading.Tasks; using System.Xml; namespace FRED.Api.Core.Requests { /// <summary> /// Provides behavior for communicating with FRED service endpoints. /// </summary> public class Request : IRequest { #region properties /// <summary> /// Indicates whether this instance expects JSON as the format for data returned from a fetch. /// False indicates that this instance expects XML as the format. /// </summary> public bool Json { get; set; } /// <summary> /// The URL used in a FRED API fetch. /// </summary> public string Url { get; protected set; } /// <summary> /// Any message returned by the FRED API. /// </summary> public string FetchMessage { get; private set; } /// <summary> /// Any exception not reflected in the <see cref="FetchMessage"/> property, or null when no exception occurs. /// </summary> public Exception Exception { get; private set; } #endregion #region public methods /// <summary> /// Fetches data from a FRED service endpoint. /// </summary> /// <param name="arguments">The arguments used in the FRED API call.</param> /// <returns>A string containing fetch results, or null when any argument is invalid.</returns> public string Fetch(ArgumentsBase arguments) { string result = null; Url = BuildUrl(arguments); if (Url == null) return null; try { result = InvokeService(); } catch (WebException exception) { HandleException(exception, Json); } return result; } /// <summary> /// Fetches data asynchronously from a FRED service endpoint. /// </summary> /// <param name="arguments">The arguments used in the FRED API call.</param> /// <returns>A string containing fetch results.</returns> public async Task<string> FetchAsync(ArgumentsBase arguments) { string result = null; Url = BuildUrl(arguments); if (Url == null) return result; try { result = await InvokeServiceAsync(); } catch (WebException exception) { HandleException(exception, Json); } return result; } #endregion #region protected methods /// <summary> /// Invoke the actual FRED API endpoint. Subclasses can override this template method to provide specialized behavior. /// </summary> /// <returns>A string containing fetch results.</returns> protected virtual string InvokeService() { WebRequest request = WebRequest.Create(Url); request.Credentials = CredentialCache.DefaultCredentials; using (WebResponse response = request.GetResponse()) { return BuildResult(response); } } /// <summary> /// Invoke the actual FRED API endpoint asynchronously. Subclasses can override this template method to provide specialized behavior. /// </summary> /// <returns>A string containing fetch results.</returns> protected virtual async Task<string> InvokeServiceAsync() { WebRequest request = WebRequest.Create(Url); request.Credentials = CredentialCache.DefaultCredentials; using (WebResponse response = await request.GetResponseAsync()) { return BuildResult(response); } } #endregion #region private methods private string BuildUrl(ArgumentsBase arguments) { string stringifiedArguments = arguments.Stringify(); if (stringifiedArguments == null) return null; string fileType = Json ? "&file_type=json" : null; string url = string.Format("https://api.stlouisfed.org/fred/{0}?{1}{2}", arguments.UrlExtension, stringifiedArguments, fileType); return url; } private string BuildResult(WebResponse response) { string responseString = null; using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream); responseString = reader.ReadToEnd(); } responseString = Json ? responseString : responseString.Replace("\n", null); return responseString; } /// <summary> /// Handles exceptions from FRED API service calls. /// </summary> /// <param name="exception">The exception.</param> /// <param name="isJson">Indicates whether the exception is in JSON format. False indicates XML format.</param> private void HandleException(WebException exception, bool isJson) { try { Stream stream = exception.Response.GetResponseStream(); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); string text = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length); string errorMessage = null; if (isJson) { Error error = JsonConvert.DeserializeObject<Error>(text); errorMessage = error.error_message; } else { XmlDocument document = new XmlDocument(); document.LoadXml(text); XmlNode node = document.SelectSingleNode("//error/@message"); errorMessage = node == null ? null : node.InnerText; } FetchMessage = errorMessage; } catch { Exception = exception; } } #endregion #region embedded types /// <summary> /// Provides a container for JSON error messages from the FRED API. /// </summary> private class Error { public string error_code { get; set; } public string error_message { get; set; } } #endregion } }
mit
ajlopez/AjRools
Src/AjRools.Expert/AjRools.Expert.Tests/Rules/RuleTests.cs
1697
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using AjRools.Expert.Rules; using AjRools.Expert.Facts; namespace AjRools.Expert.Tests.Rules { [TestClass] public class RuleTests { [TestMethod] public void RuleNotFireInEmptyWorld() { Rule rule = new Rule(new Fact[] { new IsFact("Temperature", 40), new IsFact("Age", 50) }, null); World world = new World(); Assert.IsFalse(rule.FireIfReady(world)); } [TestMethod] public void RuleFire() { Rule rule = new Rule(new Fact[] { new IsFact("Temperature", 40), new IsFact("Age", 50) }, new Fact[] { new IsFact("HasFever", true) }); World world = new World(); world.AssertFact(new IsFact("Age", 50)); world.AssertFact(new IsFact("Temperature", 40)); Assert.IsTrue(rule.FireIfReady(world)); Assert.IsTrue(world.IsAFact(new IsFact("HasFever", true))); } [TestMethod] public void RuleNotFire() { Rule rule = new Rule(new Fact[] { new IsFact("Temperature", 40), new IsFact("Age", 50) }, null); World world = new World(); world.AssertFact(new IsFact("Age", 60)); world.AssertFact(new IsFact("Temperature", 40)); Assert.IsFalse(rule.FireIfReady(world)); } } }
mit
668Jerry/Official-Tutorial-My-First-App
app/src/main/java/me/leisureapp/omyfirstapp/DisplayMessageActivity.java
1631
package me.leisureapp.omyfirstapp; import android.content.Intent; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class DisplayMessageActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_display_message); Intent intent = getIntent(); String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE); TextView textView = new TextView(this); textView.setTextSize(40); textView.setText(message); setContentView(textView); } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.menu_display_message, menu); // return true; // } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
mit
dotnetsoutheast/dotnetsoutheast-website
_site/webpack.config.js
2862
const env = process.env.NODE_ENV; const webpack = require('webpack'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const SvgSpritePlugin = require('webpack-svg-sprite-plugin'); const { path, resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const WebpackCritical = require('webpack-critical'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const WebpackShellPlugin = require('webpack-shell-plugin'); const wwwdir = resolve(__dirname, 'www/'); module.exports = { devtool: '#source-map', entry: { app: './assets/scripts/main.js', }, output: { publicPath: '/', path: wwwdir, filename: 'assets/js/main.js', }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', }, }, { test: /\.svg$/, loaders: ['file-loader'], }, { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', query: { sourceMap: true, }, }, { loader: 'postcss-loader', query: { sourceMap: true, }, }, 'resolve-url-loader', { loader: 'sass-loader', query: { sourceMap: true, }, }, ], }), }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: 'assets/fonts/[name].[ext]', }, }, { test: /\.html$/, loader: 'html-loader', options: { minimize: false, removeComments: false, collapseWhitespace: true, }, }, ], }, plugins: [ // new ExtractTextPlugin('assets/css/main.[hash:7].css'), new ExtractTextPlugin('assets/css/main.css'), new UglifyJSPlugin({ sourceMap: true, }), new HtmlWebpackPlugin({ template: resolve(__dirname, 'www/index.html'), filename: resolve(__dirname, 'www/index.html'), }), // new WebpackCritical({ // context: wwwdir, // stylesheet: '/assets/css/main.css', // }), new SvgSpritePlugin({ filename: '../../_includes/sprite.symbol.svg' }), new webpack.WatchIgnorePlugin([ resolve(__dirname, './www/'), resolve(__dirname, './_layouts/**/*.html'), ]), // new WebpackShellPlugin({ // onBuildStart: ['jekyll b --watch --config config.yml'], // onBuildEnd: 'inline-critical --html www/index.html --css www/assets/css/styles.css', // }), ], watchOptions: { aggregateTimeout: 1000, }, };
mit
sonitgregorio/nbc
application/config/routes.php
5857
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | http://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'main'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE; $route['login'] = 'main/verifylogin'; $route['faculty_registration'] = 'main/fac_reg'; $route['add_school'] = 'main/add_school'; $route['user_registration'] = 'main/user_reg'; $route['add_criteria'] = 'main/add_criteria'; $route['logout'] = 'main/logout'; //Faculty Data Management Routes $route['insert_faculty'] = 'common/insert_faculty'; $route['delete_faculty/(:any)'] = 'common/delete_faculty/$1'; $route['edit_faculty/(:any)'] = 'common/edit_faculty/$1'; $route['add_fac_user/(:any)'] = 'common/add_fac_user/$1'; //School Data Management Routes $route['save_school'] = 'common/save_school'; $route['edit/(:any)'] = 'common/edit_school/$1'; $route['delete/(:any)'] = 'common/delete_school/$1'; //User Registration $route['user_reg'] = 'common/user_reg'; $route['edit_users/(:any)'] = 'common/edit_users/$1'; $route['delete_users/(:any)'] = 'common/delete_users/$1'; //Add Criteria $route['insert_criteria'] = 'common/insert_criteria'; $route['delete_cce/(:any)'] = 'common/delete_cce/$1'; $route['edit_cce/(:any)'] = 'common/edit_cce/$1'; //CCE $route['qce'] = 'qce/criteria'; $route['evaluate'] = 'student/evaluate'; $route['instructor_eval/(:num)/(:num)/(:num)'] = 'student/ins_eval/$1/$2/$3'; $route['print_qce/(:num)/(:num)/(:num)'] = 'student/print_qce/$1/$2/$3'; $route['list_evaluate'] = 'common/list_evaluate'; $route['add_evaluators/(:num)'] = 'common/add_evaluators/$1'; $route['submit_evaluate'] = 'evaluate/evaluation'; $route['cce'] = 'cce/show_instruc'; //Reports $route['reports_all'] = 'reports/view_all_rep'; $route['rep_instruct'] = 'reports/rep_instruct'; #insert cce routes $route['insert_this_cced'] = 'cce/insert_this_cce'; $route['set_cycle'] = 'cce/set_cycle'; $route['insert_cycle'] = 'cce/insert_cycle'; //Subject Route $route['add_subject'] = 'subject/add_subject'; $route['insert_subject'] = 'subject/insert_subject'; $route['delete_subject/(:num)'] = 'subject/delete_subject/$1'; $route['edit_subject/(:num)'] = 'subject/edit_subject/$1'; $route['cancel_subject'] = 'subject/cancel_subject'; //Faculty Management and adding evaluator. $route['faculty_list'] = 'faculty/faculty_list'; $route['add_faculty_evaluator/(:num)'] = 'faculty/add_faculty_evaluator/$1'; $route['insert_faculty_evaluator'] = 'faculty/insert_faculty_evaluator'; $route['delete_evaluators/(:num)/(:num)'] = 'faculty/delete_evaluators/$1/$2'; $route['view_summary/(:num)'] = 'faculty/view_summary/$1'; //Add Class $route['add_class'] = 'addClassed/add_class'; $route['insert_class'] = 'addClassed/insert_class'; $route['add_stud/(:num)'] = 'addClassed/add_stud/$1'; $route['insert_student'] = 'addClassed/insert_student'; $route['set_sy'] = 'addClassed/set_sy'; $route['insert_sy'] = 'addClassed/insert_sy'; $route['set_active/(:num)'] = 'addClassed/set_active/$1'; //Generate Evaluators $route['generate_eval/(:any)'] = 'addClassed/generate_eval/$1'; $route['insert_this_cce'] = 'addClassed/insert_this_cces'; //QCE Result Per Subject $route['qce_subject'] = 'qce/qce_subject'; $route['view_summary_subject/(:any)/(:any)']= 'qce/view_summary_subject/$1/$2'; $route['generate_evaluators_input'] = 'addClassed/generate_evaluators_input'; $route['delete_class/(:any)'] = 'addClassed/delete_class/$1'; $route['logs'] = 'addClassed/logs'; $route['about'] = 'addClassed/about'; $route['help'] = 'addClassed/help'; $route['print_s'] = 'addClassed/prints';
mit
ycabon/presentations
2018-user-conference/arcgis-js-api-road-ahead/demos/gamepad/api-snapshot/esri/layers/support/StreamPurger.js
5895
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.8/esri/copyright.txt for details. //>>built define("../../core/declare ../../core/promiseUtils ../../core/Accessor ../../core/Promise dojo/_base/lang dojo/Deferred".split(" "),function(l,m,n,p,q,k){return l([n,p],{declaredClass:"esri.layers.support.StreamPurger",constructor:function(){this._featuresByTime={};this._lastEndTimeCheck=null;this._trackIds={};this._affectedTrackIds=[];this._doTrackPurge=this._doTimePurge=!1;this._watchHandlers=[];this._processQueue=[];this._flushQueueTimer=null},normalizeCtorArgs:function(a){a=a||{};a.controller|| (a={controller:a});return a},getDefaults:function(){return q.mixin(this.inherited(arguments),{idField:"uid",parentField:"parent"})},initialize:function(){var a;if(this.controller&&this.controller.layer)try{this.graphics=this.controller.graphics;this.layer=this.controller.layer;if(a=this.get("layer.trackIdField"))this.trackIdField=a,this._doTrackPurge=!0;this.maximumTrackPoints=this.get("layer.maximumTrackPoints");this._watchHandlers.push(this.layer.watch("maximumTrackPoints",function(a){this.set("maximumTrackPoints", a)}.bind(this)));this.get("layer.purgeOptions.age")&&this.set("maxFeatureAge",this.layer.purgeOptions.age);if(this.get("layer.timeInfo.endTimeField")||this.maxFeatureAge)this._doTimePurge=!0,this._lastEndTimeCheck=1E3*Math.ceil(Date.now()/1E3);this.displayCount=this.get("layer.purgeOptions.displayCount");this._watchHandlers.push(this.layer.watch("purgeOptions",function(a){a.hasOwnProperty("displayCount")&&this.set("displayCount",a.displayCount);a.hasOwnProperty("age")&&this.set("maxFeatureAge",a.age)}.bind(this)))}catch(b){a= new k,this.addResolvingPromise(a.promise),a.reject(b)}else a=new k,this.addResolvingPromise(a.promise),a.reject(Error("A controller with a layer is required for StreamPurger constructor"))},destroy:function(){this._flushQueueTimer&&(clearTimeout(this._flushQueueTimer),this._flushQueueTimer=null);this._affectedTrackIds=this._processQueue=null;for(var a=0,b=this._watchHandlers.length;a<b;a++)this._watchHandlers[a].remove()},properties:{graphics:null,controller:null,idField:null,layer:null,trackIdField:null, maximumTrackPoints:{set:function(a){var b=this.maximumTrackPoints;b!==a&&(this._set("maximumTrackPoints",a),this._doTrackPurge&&(0===b||0!==a&&a<b)&&this._purgeByTracks())}},parentField:null,displayCount:{set:function(a){var b=this.displayCount;b!==a&&(this._set("displayCount",a),a<b&&this._purgeByDisplayCount())}},maxFeatureAge:{value:0,set:function(a){this.maxFeatureAge!==a&&(this._set("maxFeatureAge",Math.ceil(6E4*a)),this.maxFeatureAge?(this._doTimePurge=!0,this._lastEndTimeCheck=1E3*Math.ceil(Date.now()/ 1E3)):this._doTimePurge=!1)}}},addMany:function(a){var b,c,d,f,e,g,h=this._featuresByTime;b=0;for(c=a.length;b<c;b++)e=null,d=a[b],this._doTrackPurge&&(e=d.attributes[this.trackIdField],d[this.parentField]=e,this._trackIds.hasOwnProperty(e)?this._trackIds[e]+=1:this._trackIds[e]=1,-1===this._affectedTrackIds.indexOf(e)&&this._affectedTrackIds.push(e)),this._doTimePurge&&(g=this._getExpireTimeOfItem(d))&&(f={id:d[this.idField]},null!==e&&(f.trackId=e),g=1E3*Math.ceil(g/1E3),h[g]?h[g].push(f):h[g]= [f]),this._processQueue.push(d);this._flushQueueTimer||(this._flushQueueTimer=setTimeout(this._flushProcessQueue.bind(this),200))},purge:function(a){this._doTimePurge&&this._purgeByTime();this._doTrackPurge&&this._purgeByTracks(a);this._purgeByDisplayCount()},_flushProcessQueue:function(){clearTimeout(this._flushQueueTimer);this._flushQueueTimer=null;return m.resolve(this._processQueue.splice(0)).then(function(a){this.graphics.addMany(a);a=this._affectedTrackIds.splice(0);return this.purge(a)}.bind(this))}, _getExpireTimeOfItem:function(a){var b=this.layer.timeInfo||{},c;c=b.endTimeField&&a.attributes[b.endTimeField];!c&&this.maxFeatureAge&&(c=b.startTimeField&&a.attributes[b.startTimeField]?a.attributes[b.startTimeField]+this.maxFeatureAge:Date.now()+this.maxFeatureAge);return c},_getIndexOfItem:function(a){var b,c=this.idField;b="object"===typeof a?a[c]:a;return this.graphics.findIndex(function(a){return a[c]===b},this)},_getItemsByParent:function(a){return this.graphics.filter(function(b){return b[this.parentField]=== a},this)},_processRemovedTrackFeatures:function(a){if(this._doTrackPurge&&a&&a.length)for(var b,c=0,d=a.length;c<d;c++)b=a[c],--this._trackIds[b],0===this._trackIds[b]&&delete this._trackIds[b]},_purgeByDisplayCount:function(){var a,b,c=[];a=this.graphics.length-this.displayCount;if(0<a){for(var d=0;d<a;d++)this._doTrackPurge&&(b=this.graphics.getItemAt(0)[this.parentField],c.push(b)),this.graphics.removeAt(0);this._processRemovedTrackFeatures(c)}},_purgeByTime:function(){if(this._featuresByTime&& 0!==Object.getOwnPropertyNames(this._featuresByTime).length){var a,b,c,d=[],f=[];if((this.layer.timeInfo||{}).endTimeField||this.maxFeatureAge)if(a=1E3*Math.floor(this._lastEndTimeCheck/1E3),this._lastEndTimeCheck=b=1E3*Math.ceil(Date.now()/1E3),a&&a!==b){for(c=this._featuresByTime;a<=b;a+=1E3)c[a]&&(d=d.concat(c[a]),delete c[a]);b=0;for(c=d.length;b<c;b++){a=d[b];var e=this._getIndexOfItem(a.id);-1!==e&&(this.graphics.removeAt(e),(a.trackId||0===a.trackId)&&f.push(a.trackId))}this._processRemovedTrackFeatures(f)}}}, _purgeByTracks:function(a){function b(a){var b,c;b=this._getItemsByParent(a);c=b.length-d;if(0<c){for(var e=0;e<c;e++)this._removeItemFromCollection(b.getItemAt(e));this._trackIds[a]=d}}a=a||[];if(this.maximumTrackPoints){var c,d=this.maximumTrackPoints;if(a.length)for(var f=0,e=a.length;f<e;f++)c=a[f],this._trackIds[c]>d&&b.call(this,c);else for(c in a=this._trackIds,a)a[c]>d&&b.call(this,c)}},_removeItemFromCollection:function(a){var b=a[this.idField],c;if(void 0!==b)return c=this._getIndexOfItem(a), -1!==c&&this.graphics.removeAt(c),{index:c,id:b,parent:a[this.parentField]}}})});
mit
daisybill/daisybill_api
spec/daisybill_api/models/referring_provider_spec.rb
734
require "spec_helper" describe DaisybillApi::Models::ReferringProvider do it_behaves_like DaisybillApi::Ext::Attributes, :id, :first_name, :last_name, :middle_initial, :suffix, :npi, :state_license_number, :active, :billing_provider_id, :created_at, :updated_at it_behaves_like DaisybillApi::Ext::Attributes::SendAs, :first_name, :last_name, :npi, :state_license_number, :middle_initial, :suffix, :active, :billing_provider_id it_behaves_like DaisybillApi::Ext::CRUD, :all, :find, :create, :update, "/referring_providers", billing_provider_id: "/billing_providers" it_behaves_like DaisybillApi::Ext::Associations it_behaves_like DaisybillApi::Ext::Links, billing_provider: DaisybillApi::Models::BillingProvider end
mit
Taig/lokal
modules/tests/jvm/src/test/scala/net/slozzer/babel/HoconLoaderTest.scala
201
package net.slozzer.babel import _root_.cats.effect.{IO, Resource} final class HoconLoaderTest extends LoaderTest { override val loader: Resource[IO, Loader[IO]] = Resource.pure(HoconLoader[IO]) }
mit
EddieVanHalen98/vision
vision-main/src/com/evh98/vision/ui/Window.java
1533
package com.evh98.vision.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.evh98.vision.Vision; import com.evh98.vision.util.Graphics; public class Window { protected final Color color; protected final Color borderColor; protected boolean isActive; public Window(Color color, Color borderColor) { this.color = color; this.borderColor = borderColor; this.isActive = false; } public void render(SpriteBatch sprite_batch, ShapeRenderer shape_renderer) { GL20 gl = Gdx.graphics.getGL20(); gl.glEnable(GL20.GL_BLEND); gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); shape_renderer.begin(ShapeType.Filled); shape_renderer.setColor(color); Graphics.drawRect(shape_renderer, -1600, -900, 3200, 1800); shape_renderer.end(); gl.glDisable(GL20.GL_BLEND); gl.glLineWidth(6 * Vision.SCALE); shape_renderer.begin(ShapeType.Line); shape_renderer.setColor(borderColor); Graphics.drawRect(shape_renderer, -1600, -900, 3200, 1800); shape_renderer.end(); draw(sprite_batch); } public void draw(SpriteBatch sprite_batch) { } public void update() { } public boolean isActive() { return isActive; } public void setActive() { this.isActive = true; } public void setInactive() { this.isActive = false; } }
mit
ChrisRowtcliff/JudoPayDotNet4
JudoPayDotNetDotNet/Logging/DotNetLoggerFactory.cs
583
using System; using log4net; using ILog = JudoPayDotNet.Logging.ILog; namespace JudoPayDotNetDotNet.Logging { /// <summary> /// Creates a log4net instance wrapper in the judopay sdk ILog logger interface. /// </summary> public static class DotNetLoggerFactory { /// <summary> /// Create an instance of ILog /// </summary> /// <param name="askingType">the type requesting the logger</param> /// <returns></returns> public static ILog Create(Type askingType) { return new Logger(LogManager.GetLogger(askingType)); } } }
mit
aleksandra992/TelerikAcademy
CSharp Part 1/Intro-Programming-Homework/AgeAfter10Years/Properties/AssemblyInfo.cs
1406
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("AgeAfter10Years")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AgeAfter10Years")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e755ed87-e643-4a21-9c33-b21942a6961e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
AlexandreOuellet/halite-bot
nn/CattleV2.py
7971
import os import sys class RedirectStdStreams(object): def __init__(self, stdout=None, stderr=None): self._stdout = stdout or sys.stdout self._stderr = stderr or sys.stderr def __enter__(self): self.old_stdout, self.old_stderr = sys.stdout, sys.stderr self.old_stdout.flush(); self.old_stderr.flush() sys.stdout, sys.stderr = self._stdout, self._stderr def __exit__(self, exc_type, exc_value, traceback): self._stdout.flush(); self._stderr.flush() sys.stdout = self.old_stdout sys.stderr = self.old_stderr devnull = open(os.devnull, 'w') # with RedirectStdStreams(stdout=devnull, stderr=devnull): import random import numpy as np np.set_printoptions(threshold=np.nan) from collections import deque # import tensorflow as tf # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import keras from keras.models import Sequential, Model from keras.layers import Dense, Input, Embedding, Conv2D, Flatten, Activation, MaxPooling2D, Dropout from keras.optimizers import Adam from keras.utils import to_categorical, plot_model from nn import starterBot import nnutils import pickle import os.path import time import logging from keras.callbacks import Callback EPISODES = 1000 DROPOUT_RATE = 0.2 class Cattle: def __init__(self, input_shape, output_size, name): self.name = name self.input_shape = input_shape self.output_size = output_size self.memory = deque() self.gamma = 0.99 # discount rate self.epsilon = 1.0 # exploration rate self.epsilon_min = 0.01 self.epsilon_decay = 0.995 self.learning_rate = 0.0001 self.model = self._build_model() self.old_state_by_id = {} def _build_model(self): # Neural Net for Deep-Q learning Model input = Input(shape=(self.input_shape), name='guylaine_input') guylaine = Dense(512, name='dense1', activation='relu')(input) guylaine = Dropout(DROPOUT_RATE)(guylaine) guylaine = Dense(512, name='dense2', activation='relu')(guylaine) guylaine = Dropout(DROPOUT_RATE)(guylaine) guylaine = Dense(512, name='dense3', activation='relu')(guylaine) guylaine = Dropout(DROPOUT_RATE)(guylaine) output = Dense(self.output_size, activation='relu', name='output')(guylaine) model = Model(inputs=input, outputs=output) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model def rememberNextState(self, id, state, action_taken, reward): if id not in self.old_state_by_id: self.old_state_by_id[id] = (state, action_taken) else: old_state, old_action_taken= self.old_state_by_id[id] self.memory.append((id, old_state, old_action_taken, reward, state)) self.old_state_by_id[id] = (state, action_taken) def forcePredict(self,state): state = state.reshape(1, state.shape[0]) act_values = self.model.predict(state) return act_values def predict(self, state, ship, game_map): if np.random.rand() <= self.epsilon: # starter bot # starter_action = starterBot.predictStarterBot(ship, game_map) # logging.debug("starter_action: %s", starter_action) # index = nnutils.parseCommandToActionIndex(starter_action) # logging.debug("index: %s", index) # actions = np.random.rand(self.output_size) # if index == None: # actions[3] = 1 # else: # actions[index] = 1 # random action actions = np.random.rand(self.output_size) # # Force docking # for planet in game_map.all_planets(): # if ship.can_dock(planet) and planet.num_docking_spots > (planet.current_production / 6): # actions[0] = 1 # force dock if possible # logging.debug("Forced dock") action_index = np.argmax(actions) for i in range(0, len(actions)): actions[i] = 0 actions[action_index] = 1 # actions = to_categorical(actions, num_classes=self.output_size) # action_index = np.argmax(actions) logging.debug("Random action : %s", actions) logging.debug("Random action index : %d", action_index) return actions actions = self.forcePredict(state) action_index = np.argmax(actions) logging.debug("Predicted action : %s", actions) logging.debug("Predicted action index : %d", action_index) return actions def replay(self, batch_size, epoch, run_name, train_with_epsilon): from keras.callbacks import TensorBoard print("Training") # training per ships nbDataPoint = 0 training_per_ship = {} for shipId, state, action, reward, next_state in self.memory: if shipId not in training_per_ship: training_per_ship[shipId] = deque() training_per_ship[shipId].append((state, action, reward, next_state)) nbDataPoint += 1 state_batch = [] targets = np.zeros((nbDataPoint, self.output_size)) nbDataPoint = 0 for k in training_per_ship: for state, action_taken, reward, next_state in training_per_ship[k]: state_batch.append(state) targets[nbDataPoint] = self.forcePredict(state) predicted_next_actions = self.forcePredict(next_state) predicted_next_best_reward = np.amax(predicted_next_actions) target = reward + self.gamma * predicted_next_best_reward targets[nbDataPoint][action_taken] = target nbDataPoint += 1 print("Done gathering data for batch. Datapoints: %d", nbDataPoint) print("Fitting the model") # callbacks = [EarlyStop(monitor='loss', value=0.0021, verbose=1), TensorBoard(write_images=True, log_dir='./logs/'+strategy+'/'+filename] tensor_log_file = './logs/{}'.format(run_name) callback = TensorBoard(write_images=True, log_dir=tensor_log_file) history = self.model.fit(np.array(state_batch), np.array(targets), batch_size=batch_size, verbose=1, epochs=epoch, callbacks=[callback]) print("Done fitting the model, printing history") print(history) print(history.history) if train_with_epsilon and self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay print("Training done. epsilon: %s", self.epsilon) return history.history['loss'] def load(self, forceZeroEpsilon=True): dir = './{}/data/'.format(self.name) if os.path.exists(dir) == False: os.makedirs(dir) if os.path.isfile(dir+'model'): self.model.load_weights(dir+'model') if os.path.isfile(dir+'epsilon'): self.epsilon = pickle.load(open(dir+'epsilon', 'rb')) if (forceZeroEpsilon): self.epsilon = self.epsilon_min def save(self): dir = './{}/data/'.format(self.name) if os.path.exists(dir) == False: os.makedirs(dir) self.model.save_weights(dir+'model') pickle.dump(self.epsilon, open(dir+'epsilon', 'wb')) def loadMemory(self, fileName): dir = './{}/memory/'.format(self.name) if os.path.exists(dir) == False: os.makedirs(dir) if os.path.isfile(dir+fileName): self.memory = pickle.load(open(dir+fileName, 'rb')) def saveMemory(self, fileName): dir = './{}/memory/'.format(self.name) if os.path.exists(dir) == False: os.makedirs(dir) logging.debug("Saving Memory of length %s in file %s", len(self.memory), dir ) pickle.dump(self.memory, open(dir + fileName, 'wb'))
mit
RizwanMehmood/platters
application/views/CaptainFood/includes/footer-menu.php
379
<div class="footer padd" style="background-color:#000;"> <div class="container"> <div class="footer-copyright"> <p style="float:left;font-family: 'Droid Serif', serif;">&copy; Copyright 2016 CAPTAINfood&nbsp;&nbsp; <a href="#">Facebook</a>&nbsp;&nbsp;<a href="#">Linkedin</a>&nbsp;&nbsp;<a href="#">Support</a>&nbsp;&nbsp; </p> </div> </div> </div>
mit
WiiPlayer2/MessageNetwork
MessageNetwork/Messages/NodeLeftMessage.cs
439
using System; namespace MessageNetwork.Messages { [Serializable] internal class NodeLeftMessage : SystemMessage { public override SystemMessageType Type { get { return SystemMessageType.NodeLeft; } protected set { base.Type = value; } } public PublicKey PublicKey { get; set; } } }
mit
magenta-aps/OpenDESK-UI
app/tests/e2e/documents/searchDocumentPage.po.js
1180
var globalHeaderMenu = require('../common/globalHeader.po.js'); var constants = require('../common/constants'); var date = new Date(); var searchedDocument = constants.file_1.name; var breadcrumb = ""; var SearchDocumentPage = function () { var public = {}; public.getBreadcrumb = function() { //last element in breadcrumb must represent the searched/selected document return breadcrumb; } public.getSearchedDocument = function() { return searchedDocument; } public.searchDocument = function() { return browser.get("http://localhost:8000/#/projekter/" + constants.PROJECT_NAME_1).then (function(response) { var searchDocumentInput = element(by.model('$mdAutocompleteCtrl.scope.searchText')); var selectedDocument = element.all(by.css('[ng-click="vm.gotoPath(r.nodeRef);"]')).first(); searchDocumentInput.sendKeys(constants.file_1.name); selectedDocument.click(); return element.all(by.repeater('path in bcPath')).then (function (response) { var last_element = response[response.length -1]; return last_element.getText(); }); }); }; return public; }; module.exports = SearchDocumentPage();
mit
sejen/abssh
web/static/js/ckeditor/lang/tt.js
28800
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.lang['tt'] = { "editor": "Форматлаулы текст өлкәсе", "editorPanel": "Rich Text Editor panel", "common": { "editorHelp": "Ярдәм өчен ALT 0 басыгыз", "browseServer": "Сервер карап чыгу", "url": "Сылталама", "protocol": "Протокол", "upload": "Йөкләү", "uploadSubmit": "Серверга җибәрү", "image": "Рәсем", "flash": "Флеш", "form": "Форма", "checkbox": "Чекбокс", "radio": "Радио төймә", "textField": "Текст кыры", "textarea": "Текст мәйданы", "hiddenField": "Яшерен кыр", "button": "Төймə", "select": "Сайлау кыры", "imageButton": "Рәсемле төймə", "notSet": "<билгеләнмәгән>", "id": "Id", "name": "Исем", "langDir": "Язылыш юнəлеше", "langDirLtr": "Сулдан уңга язылыш (LTR)", "langDirRtl": "Уңнан сулга язылыш (RTL)", "langCode": "Тел коды", "longDescr": "Җентекле тасвирламага сылталама", "cssClass": "Стильләр класслары", "advisoryTitle": "Киңәш исем", "cssStyle": "Стиль", "ok": "Тәмам", "cancel": "Баш тарту", "close": "Чыгу", "preview": "Карап алу", "resize": "Зурлыкны үзгәртү", "generalTab": "Төп", "advancedTab": "Киңәйтелгән көйләүләр", "validateNumberFailed": "Әлеге кыйммәт сан түгел.", "confirmNewPage": "Any unsaved changes to this content will be lost. Are you sure you want to load new page?", "confirmCancel": "You have changed some options. Are you sure you want to close the dialog window?", "options": "Үзлекләр", "target": "Максат", "targetNew": "Яңа тәрәзә (_blank)", "targetTop": "Өске тәрәзә (_top)", "targetSelf": "Шул үк тәрәзә (_self)", "targetParent": "Ана тәрәзә (_parent)", "langDirLTR": "Сулдан уңга язылыш (LTR)", "langDirRTL": "Уңнан сулга язылыш (RTL)", "styles": "Стиль", "cssClasses": "Стильләр класслары", "width": "Киңлек", "height": "Биеклек", "align": "Тигезләү", "alignLeft": "Сул якка", "alignRight": "Уң якка", "alignCenter": "Үзәккә", "alignJustify": "Киңлеккә карап тигезләү", "alignTop": "Өскә", "alignMiddle": "Уртага", "alignBottom": "Аска", "alignNone": "Һичбер", "invalidValue": "Дөрес булмаган кыйммәт.", "invalidHeight": "Биеклек сан булырга тиеш.", "invalidWidth": "Киңлек сан булырга тиеш.", "invalidCssLength": "Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).", "invalidHtmlLength": "Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).", "invalidInlineStyle": "Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.", "cssLengthTooltip": "Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).", "unavailable": "%1<span class=\"cke_accessibility\">, unavailable</span>" }, "about": { "copy": "Copyright &copy; $1. Бар хокуклар сакланган", "dlgTitle": "CKEditor турында", "help": "Ярдәм өчен $1 тикшереп карагыз.", "moreInfo": "For licensing information please visit our web site:", "title": "CKEditor турында", "userGuide": "CKEditor кулланмасы" }, "basicstyles": { "bold": "Калын", "italic": "Курсив", "strike": "Сызылган", "subscript": "Аскы индекс", "superscript": "Өске индекс", "underline": "Астына сызылган" }, "bidi": {"ltr": "Сулдан уңга язылыш", "rtl": "Уңнан сулга язылыш"}, "blockquote": {"toolbar": "Өземтә блогы"}, "clipboard": { "copy": "Күчермәләү", "copyError": "Браузерыгызның иминлек үзлекләре автоматик рәвештә күчермәләү үтәүне тыя. Тиз төймәләрне (Ctrl/Cmd+C) кулланыгыз.", "cut": "Кисеп алу", "cutError": "Браузерыгызның иминлек үзлекләре автоматик рәвештә күчермәләү үтәүне тыя. Тиз төймәләрне (Ctrl/Cmd+C) кулланыгыз.", "paste": "Өстәү", "pasteArea": "Өстәү мәйданы", "pasteMsg": "Please paste inside the following box using the keyboard (<strong>Ctrl/Cmd+V</strong>) and hit OK", "securityMsg": "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", "title": "Өстәү" }, "button": {"selectedLabel": "%1 (Сайланган)"}, "colorbutton": { "auto": "Автоматик", "bgColorTitle": "Фон төсе", "colors": { "000": "Кара", "800000": "Бордо", "8B4513": "Дарчин", "2F4F4F": "Аспид соры", "008080": "Күкле-яшелле", "000080": "Куе күк", "4B0082": "Индиго", "696969": "Куе соры", "B22222": "Кармин", "A52A2A": "Чия кызыл", "DAA520": "Алтын каен", "006400": "Үлән", "40E0D0": "Фирәзә", "0000CD": "Фарсы күк", "800080": "Шәмәхә", "808080": "Соры", "F00": "Кызыл", "FF8C00": "Кабак", "FFD700": "Алтын", "008000": "Яшел", "0FF": "Ачык зәңгәр", "00F": "Зәңгәр", "EE82EE": "Миләүшә", "A9A9A9": "Ачык соры", "FFA07A": "Кызгылт сары алсу", "FFA500": "Кызгылт сары", "FFFF00": "Сары", "00FF00": "Лайм", "AFEEEE": "Тонык күк", "ADD8E6": "Тонык күкбаш", "DDA0DD": "Аксыл шәмәхә", "D3D3D3": "Ачык соры", "FFF0F5": "Ал ала миләүшә", "FAEBD7": "Җитен", "FFFFE0": "Ачык сары", "F0FFF0": "Аксыл көрән", "F0FFFF": "Ап-ак", "F0F8FF": "Аксыл зәңгәр диңгез", "E6E6FA": "Ала миләүшә", "FFF": "Ак" }, "more": "Башка төсләр...", "panelTitle": "Төсләр", "textColorTitle": "Текст төсе" }, "colordialog": { "clear": "Бушату", "highlight": "Билгеләү", "options": "Төс көйләүләре", "selected": "Сайланган төсләр", "title": "Төс сайлау" }, "templates": { "button": "Шаблоннар", "emptyListMsg": "(Шаблоннар билгеләнмәгән)", "insertOption": "Әлеге эчтәлекне алмаштыру", "options": "Шаблон үзлекләре", "selectPromptMsg": "Please select the template to open in the editor", "title": "Эчтәлек шаблоннары" }, "contextmenu": {"options": "Контекст меню үзлекләре"}, "div": { "IdInputLabel": "Идентификатор", "advisoryTitleInputLabel": "Киңәш исем", "cssClassInputLabel": "Стильләр класслары", "edit": "Edit Div", "inlineStyleInputLabel": "Эчке стиль", "langDirLTRLabel": "Сулдан уңга язылыш (LTR)", "langDirLabel": "Язылыш юнəлеше", "langDirRTLLabel": "Уңнан сулга язылыш (RTL)", "languageCodeInputLabel": "Тел коды", "remove": "Remove Div", "styleSelectLabel": "Стиль", "title": "Create Div Container", "toolbar": "Create Div Container" }, "toolbar": { "toolbarCollapse": "Collapse Toolbar", "toolbarExpand": "Expand Toolbar", "toolbarGroups": { "document": "Документ", "clipboard": "Алмашу буферы/Кайтару", "editing": "Төзәтү", "forms": "Формалар", "basicstyles": "Төп стильләр", "paragraph": "Параграф", "links": "Сылталамалар", "insert": "Өстәү", "styles": "Стильләр", "colors": "Төсләр", "tools": "Кораллар" }, "toolbars": "Editor toolbars" }, "elementspath": {"eleLabel": "Elements path", "eleTitle": "%1 элемент"}, "find": { "find": "Эзләү", "findOptions": "Эзләү көйләүләре", "findWhat": "Нәрсә эзләргә:", "matchCase": "Баш һәм юл хәрефләрен исәпкә алу", "matchCyclic": "Кабатлап эзләргә", "matchWord": "Сүзләрне тулысынча гына эзләү", "notFoundMsg": "Эзләнгән текст табылмады.", "replace": "Алмаштыру", "replaceAll": "Барысын да алмаштыру", "replaceSuccessMsg": "%1 урында(ларда) алмаштырылган.", "replaceWith": "Нәрсәгә алмаштыру:", "title": "Эзләп табу һәм алмаштыру" }, "fakeobjects": { "anchor": "Якорь", "flash": "Флеш анимациясы", "hiddenfield": "Яшерен кыр", "iframe": "IFrame", "unknown": "Танылмаган объект" }, "flash": { "access": "Script Access", "accessAlways": "Һəрвакыт", "accessNever": "Беркайчан да", "accessSameDomain": "Same domain", "alignAbsBottom": "Иң аска", "alignAbsMiddle": "Төгәл уртада", "alignBaseline": "Таяныч сызыгы", "alignTextTop": "Текст өсте", "bgcolor": "Фон төсе", "chkFull": "Allow Fullscreen", "chkLoop": "Әйләнеш", "chkMenu": "Enable Flash Menu", "chkPlay": "Auto Play", "flashvars": "Variables for Flash", "hSpace": "Горизонталь ара", "properties": "Флеш үзлекләре", "propertiesTab": "Үзлекләр", "quality": "Сыйфат", "qualityAutoHigh": "Авто югары сыйфат", "qualityAutoLow": "Авто түбән сыйфат", "qualityBest": "Иң югары сыйфат", "qualityHigh": "Югары", "qualityLow": "Түбəн", "qualityMedium": "Уртача", "scale": "Зурлык", "scaleAll": "Барысын күрсәтү", "scaleFit": "Exact Fit", "scaleNoBorder": "Чиксез", "title": "Флеш үзлекләре", "vSpace": "Вертикаль ара", "validateHSpace": "Горизонталь ара сан булырга тиеш.", "validateSrc": "URL буш булмаска тиеш.", "validateVSpace": "Вертикаль ара сан булырга тиеш.", "windowMode": "Тəрəзə тәртибе", "windowModeOpaque": "Үтә күренмәле", "windowModeTransparent": "Үтə күренмəле", "windowModeWindow": "Тəрəзə" }, "font": { "fontSize": {"label": "Зурлык", "voiceLabel": "Шрифт зурлыклары", "panelTitle": "Шрифт зурлыклары"}, "label": "Шрифт", "panelTitle": "Шрифт исеме", "voiceLabel": "Шрифт" }, "forms": { "button": { "title": "Төймә үзлекләре", "text": "Текст (күләм)", "type": "Төр", "typeBtn": "Төймә", "typeSbm": "Җибәрү", "typeRst": "Кире кайтару" }, "checkboxAndRadio": { "checkboxTitle": "Checkbox Properties", "radioTitle": "Радио төймə үзлекләре", "value": "Күләм", "selected": "Сайланган", "required": "Required" }, "form": { "title": "Форма үзлекләре", "menu": "Форма үзлекләре", "action": "Гамәл", "method": "Ысул", "encoding": "Кодировка" }, "hidden": {"title": "Яшерен кыр үзлекләре", "name": "Исем", "value": "Күләм"}, "select": { "title": "Selection Field Properties", "selectInfo": "Select Info", "opAvail": "Мөмкин булган көйләүләр", "value": "Күләм", "size": "Зурлык", "lines": "юллар", "chkMulti": "Allow multiple selections", "required": "Required", "opText": "Текст", "opValue": "Күләм", "btnAdd": "Кушу", "btnModify": "Үзгәртү", "btnUp": "Өскә", "btnDown": "Аска", "btnSetValue": "Сайланган күләм булып билгеләргә", "btnDelete": "Бетерү" }, "textarea": {"title": "Текст мәйданы үзлекләре", "cols": "Баганалар", "rows": "Юллар"}, "textfield": { "title": "Текст кыры үзлекләре", "name": "Исем", "value": "Күләм", "charWidth": "Символлар киңлеге", "maxChars": "Maximum Characters", "required": "Required", "type": "Төр", "typeText": "Текст", "typePass": "Сер сүз", "typeEmail": "Эл. почта", "typeSearch": "Эзләү", "typeTel": "Телефон номеры", "typeUrl": "Сылталама" } }, "format": { "label": "Форматлау", "panelTitle": "Параграф форматлавы", "tag_address": "Адрес", "tag_div": "Гади (DIV)", "tag_h1": "Башлам 1", "tag_h2": "Башлам 2", "tag_h3": "Башлам 3", "tag_h4": "Башлам 4", "tag_h5": "Башлам 5", "tag_h6": "Башлам 6", "tag_p": "Гади", "tag_pre": "Форматлаулы" }, "horizontalrule": {"toolbar": "Ятма сызык өстәү"}, "iframe": { "border": "Frame чикләрен күрсәтү", "noUrl": "Please type the iframe URL", "scrolling": "Enable scrollbars", "title": "IFrame үзлекләре", "toolbar": "IFrame" }, "image": { "alt": "Альтернатив текст", "border": "Чик", "btnUpload": "Серверга җибәрү", "button2Img": "Do you want to transform the selected image button on a simple image?", "hSpace": "Горизонталь ара", "img2Button": "Do you want to transform the selected image on a image button?", "infoTab": "Рәсем тасвирламасы", "linkTab": "Сылталама", "lockRatio": "Lock Ratio", "menu": "Рәсем үзлекләре", "resetSize": "Баштагы зурлык", "title": "Рәсем үзлекләре", "titleButton": "Рәсемле төймə үзлекләре", "upload": "Йөкләү", "urlMissing": "Image source URL is missing.", "vSpace": "Вертикаль ара", "validateBorder": "Чик киңлеге сан булырга тиеш.", "validateHSpace": "Горизонталь ара бөтен сан булырга тиеш.", "validateVSpace": "Вертикаль ара бөтен сан булырга тиеш." }, "indent": {"indent": "Отступны арттыру", "outdent": "Отступны кечерәйтү"}, "smiley": {"options": "Смайл көйләүләре", "title": "Смайл өстәү", "toolbar": "Смайл"}, "justify": { "block": "Киңлеккә карап тигезләү", "center": "Үзәккә тигезләү", "left": "Сул як кырыйдан тигезләү", "right": "Уң як кырыйдан тигезләү" }, "language": {"button": "Тел сайлау", "remove": "Телне бетерү"}, "link": { "acccessKey": "Access Key", "advanced": "Киңәйтелгән көйләүләр", "advisoryContentType": "Advisory Content Type", "advisoryTitle": "Киңәш исем", "anchor": { "toolbar": "Якорь", "menu": "Якорьне үзгәртү", "title": "Якорь үзлекләре", "name": "Якорь исеме", "errorName": "Якорьнең исемен языгыз", "remove": "Якорьне бетерү" }, "anchorId": "Элемент идентификаторы буенча", "anchorName": "Якорь исеме буенча", "charset": "Linked Resource Charset", "cssClasses": "Стильләр класслары", "emailAddress": "Электрон почта адресы", "emailBody": "Хат эчтәлеге", "emailSubject": "Хат темасы", "id": "Идентификатор", "info": "Сылталама тасвирламасы", "langCode": "Тел коды", "langDir": "Язылыш юнəлеше", "langDirLTR": "Сулдан уңга язылыш (LTR)", "langDirRTL": "Уңнан сулга язылыш (RTL)", "menu": "Сылталамаyны үзгәртү", "name": "Исем", "noAnchors": "(Әлеге документта якорьләр табылмады)", "noEmail": "Электрон почта адресын языгыз", "noUrl": "Сылталаманы языгыз", "other": "<бүтән>", "popupDependent": "Бәйле (Netscape)", "popupFeatures": "Popup Window Features", "popupFullScreen": "Тулы экран (IE)", "popupLeft": "Left Position", "popupLocationBar": "Location Bar", "popupMenuBar": "Menu Bar", "popupResizable": "Resizable", "popupScrollBars": "Scroll Bars", "popupStatusBar": "Status Bar", "popupToolbar": "Toolbar", "popupTop": "Top Position", "rel": "Бәйләнеш", "selectAnchor": "Якорьне сайлау", "styles": "Стиль", "tabIndex": "Tab Index", "target": "Максат", "targetFrame": "<frame>", "targetFrameName": "Target Frame Name", "targetPopup": "<popup window>", "targetPopupName": "Попап тәрәзәсе исеме", "title": "Сылталама", "toAnchor": "Якорьне текст белән бәйләү", "toEmail": "Электрон почта", "toUrl": "Сылталама", "toolbar": "Сылталама", "type": "Сылталама төре", "unlink": "Сылталаманы бетерү", "upload": "Йөкләү" }, "list": {"bulletedlist": "Маркерлы тезмә өстәү/бетерү", "numberedlist": " Номерланган тезмә өстәү/бетерү"}, "liststyle": { "armenian": "Әрмән номерлавы", "bulletedTitle": "Маркерлы тезмә үзлекләре", "circle": "Түгәрәк", "decimal": "Унарлы (1, 2, 3, ...)", "decimalLeadingZero": "Ноль белән башланган унарлы (01, 02, 03, ...)", "disc": "Диск", "georgian": "Georgian numbering (an, ban, gan, etc.)", "lowerAlpha": "Lower Alpha (a, b, c, d, e, etc.)", "lowerGreek": "Lower Greek (alpha, beta, gamma, etc.)", "lowerRoman": "Lower Roman (i, ii, iii, iv, v, etc.)", "none": "Һичбер", "notset": "<билгеләнмәгән>", "numberedTitle": "Номерлы тезмә үзлекләре", "square": "Шакмак", "start": "Башлау", "type": "Төр", "upperAlpha": "Upper Alpha (A, B, C, D, E, etc.)", "upperRoman": "Upper Roman (I, II, III, IV, V, etc.)", "validateStartNumber": "List start number must be a whole number." }, "magicline": {"title": "Бирегә параграф өстәү"}, "maximize": {"maximize": "Зурайту", "minimize": "Кечерәйтү"}, "newpage": {"toolbar": "Яңа бит"}, "pagebreak": {"alt": "Бит бүлгече", "toolbar": "Бастыру өчен бит бүлгечен өстәү"}, "pastetext": {"button": "Форматлаусыз текст өстәү", "title": "Форматлаусыз текст өстәү"}, "pastefromword": { "confirmCleanup": "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?", "error": "It was not possible to clean up the pasted data due to an internal error", "title": "Word'тан өстәү", "toolbar": "Word'тан өстәү" }, "preview": {"preview": "Карап алу"}, "print": {"toolbar": "Бастыру"}, "removeformat": {"toolbar": "Форматлауны бетерү"}, "save": {"toolbar": "Саклау"}, "selectall": {"toolbar": "Барысын сайлау"}, "showblocks": {"toolbar": "Блокларны күрсәтү"}, "sourcearea": {"toolbar": "Чыганак"}, "specialchar": { "options": "Махсус символ үзлекләре", "title": "Махсус символ сайлау", "toolbar": "Махсус символ өстәү" }, "scayt": { "btn_about": "About SCAYT", "btn_dictionaries": "Dictionaries", "btn_disable": "Disable SCAYT", "btn_enable": "Enable SCAYT", "btn_langs": "Languages", "btn_options": "Options", "text_title": "Spell Check As You Type" }, "stylescombo": { "label": "Стильләр", "panelTitle": "Форматлау стильләре", "panelTitle1": "Блоклар стильләре", "panelTitle2": "Эчке стильләр", "panelTitle3": "Объектлар стильләре" }, "table": { "border": "Чик калынлыгы", "caption": "Исем", "cell": { "menu": "Күзәнәк", "insertBefore": "Алдына күзәнәк өстәү", "insertAfter": "Артына күзәнәк өстәү", "deleteCell": "Күзәнәкләрне бетерү", "merge": "Күзәнәкләрне берләштерү", "mergeRight": "Уң яктагы белән берләштерү", "mergeDown": "Астагы белән берләштерү", "splitHorizontal": "Күзәнәкне юлларга бүлү", "splitVertical": "Күзәнәкне баганаларга бүлү", "title": "Күзәнәк үзлекләре", "cellType": "Күзәнәк төре", "rowSpan": "Юлларны берләштерү", "colSpan": "Баганаларны берләштерү", "wordWrap": "Текстны күчерү", "hAlign": "Ятма тигезләү", "vAlign": "Асма тигезләү", "alignBaseline": "Таяныч сызыгы", "bgColor": "Фон төсе", "borderColor": "Чик төсе", "data": "Мәгълүмат", "header": "Башлык", "yes": "Әйе", "no": "Юк", "invalidWidth": "Cell width must be a number.", "invalidHeight": "Cell height must be a number.", "invalidRowSpan": "Rows span must be a whole number.", "invalidColSpan": "Columns span must be a whole number.", "chooseColor": "Сайлау" }, "cellPad": "Cell padding", "cellSpace": "Cell spacing", "column": { "menu": "Багана", "insertBefore": "Сулдан баганалар өстәү", "insertAfter": "Уңнан баганалар өстәү", "deleteColumn": "Баганаларны бетерү" }, "columns": "Баганалар", "deleteTable": "Таблицаны бетерү", "headers": "Башлыклар", "headersBoth": "Икесе дә", "headersColumn": "Беренче багана", "headersNone": "Һичбер", "headersRow": "Беренче юл", "invalidBorder": "Чик киңлеге сан булырга тиеш.", "invalidCellPadding": "Cell padding must be a positive number.", "invalidCellSpacing": "Күзәнәкләр аралары уңай сан булырга тиеш.", "invalidCols": "Number of columns must be a number greater than 0.", "invalidHeight": "Таблица биеклеге сан булырга тиеш.", "invalidRows": "Number of rows must be a number greater than 0.", "invalidWidth": "Таблица киңлеге сан булырга тиеш", "menu": "Таблица үзлекләре", "row": { "menu": "Юл", "insertBefore": "Өстән юллар өстәү", "insertAfter": "Астан юллар өстәү", "deleteRow": "Юлларны бетерү" }, "rows": "Юллар", "summary": "Йомгаклау", "title": "Таблица үзлекләре", "toolbar": "Таблица", "widthPc": "процент", "widthPx": "Нокталар", "widthUnit": "киңлек берәмлеге" }, "undo": {"redo": "Кабатлау", "undo": "Кайтару"}, "wsc": { "btnIgnore": "Ignore", "btnIgnoreAll": "Ignore All", "btnReplace": "Replace", "btnReplaceAll": "Replace All", "btnUndo": "Undo", "changeTo": "Change to", "errorLoading": "Error loading application service host: %s.", "ieSpellDownload": "Spell checker not installed. Do you want to download it now?", "manyChanges": "Spell check complete: %1 words changed", "noChanges": "Spell check complete: No words changed", "noMispell": "Spell check complete: No misspellings found", "noSuggestions": "- No suggestions -", "notAvailable": "Sorry, but service is unavailable now.", "notInDic": "Not in dictionary", "oneChange": "Spell check complete: One word changed", "progress": "Spell check in progress...", "title": "Spell Checker", "toolbar": "Check Spelling" } };
mit
ustream/daemon
src/Ustream/Daemon/PreconfiguredTaskDelegator.php
2208
<?php /** * @author pepov <pepov@ustream.tv> */ /** * Ustream_Daemon_PreconfiguredTaskDelegator */ class Ustream_Daemon_PreconfiguredTaskDelegator extends Ustream_Daemon_Daemon implements Ustream_Daemon_Starter { /** * @var Ustream_Daemon_Task */ private $task; /** * @var string */ private $id; /** * @var Ustream_Daemon_Config */ private $config; /** * @param string $id * @param Ustream_Daemon_Config $config */ public function __construct($id, Ustream_Daemon_Config $config) { if ($config->customDaemonUtilLogFile !== null) { $this->daemonUtilLogFile = $config->customDaemonUtilLogFile; } parent::__construct(); $this->id = $id; $this->useMultipleInstances = $config->multipleInstances; $this->config = $config; $this->forceDirectory = $this->config->logDir; $context = $config->context; $this->setPidFileLocation('%s/%s-%s.pid', $config->runDir, $this->id, $context); $this->setLogFile(sprintf('%s/%s', $config->logDir, $this->id), $context); $this->sleepBetweenRuns = $config->sleepBetweenRuns; $this->minimumSleep = $config->minimumSleep; $this->memoryThreshold = $config->memoryThreshold; $eventListeners = $config->listeners; $this->addListeners($eventListeners); } /** * Name column for the daemon monitor * * @return string daemon id. */ public function getName() { return $this->id; } /** * @return \Ustream_Daemon_Task */ public function getTask() { return $this->task; } /** * @return string */ public function getPidFilePath() { return $this->pidFileLocation; } /** * @return string */ public function getLogFilePath() { return $this->getLogFileName(); } /** * @param Ustream_Daemon_Task $task * @return void */ public function setTask(Ustream_Daemon_Task $task) { $this->task = $task; } /** * Do task * * @return void */ protected function doTask() { try { $this->task->doTask(); } catch (Ustream_Daemon_StopException $e) { $this->stop(); } } /** * @return void */ protected function setInstanceNumber() { $this->instanceNumber = $this->config->instanceNumber; } }
mit
mrtrizer/babel
packages/babylon/src/parser/statement.js
30315
import { types as tt } from "../tokenizer/types"; import Parser from "./index"; import { lineBreak } from "../util/whitespace"; const pp = Parser.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp.parseTopLevel = function (file, program) { program.sourceType = this.options.sourceType; this.parseBlockBody(program, true, true, tt.eof); file.program = this.finishNode(program, "Program"); file.comments = this.state.comments; file.tokens = this.state.tokens; return this.finishNode(file, "File"); }; const loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; // TODO pp.stmtToDirective = function (stmt) { let expr = stmt.expression; let directiveLiteral = this.startNodeAt(expr.start, expr.loc.start); let directive = this.startNodeAt(stmt.start, stmt.loc.start); let raw = this.input.slice(expr.start, expr.end); let val = directiveLiteral.value = raw.slice(1, -1); // remove quotes this.addExtra(directiveLiteral, "raw", raw); this.addExtra(directiveLiteral, "rawValue", val); directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end); return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end); }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp.parseStatement = function (declaration, topLevel) { if (this.match(tt.at)) { this.parseDecorators(true); } let starttype = this.state.type, node = this.startNode(); // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword); case tt._debugger: return this.parseDebuggerStatement(node); case tt._do: return this.parseDoStatement(node); case tt._for: return this.parseForStatement(node); case tt._function: if (!declaration) this.unexpected(); return this.parseFunctionStatement(node); case tt._class: if (!declaration) this.unexpected(); this.takeDecorators(node); return this.parseClass(node, true); case tt._if: return this.parseIfStatement(node); case tt._return: return this.parseReturnStatement(node); case tt._switch: return this.parseSwitchStatement(node); case tt._throw: return this.parseThrowStatement(node); case tt._try: return this.parseTryStatement(node); case tt._let: case tt._const: if (!declaration) this.unexpected(); // NOTE: falls through to _var case tt._var: return this.parseVarStatement(node, starttype); case tt._while: return this.parseWhileStatement(node); case tt._with: return this.parseWithStatement(node); case tt.braceL: return this.parseBlock(); case tt.semi: return this.parseEmptyStatement(node); case tt._export: case tt._import: if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.state.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.state.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === tt._import ? this.parseImport(node) : this.parseExport(node); case tt.name: if (this.hasPlugin("asyncFunctions") && this.state.value === "async") { // peek ahead and see if next token is a function let state = this.state.clone(); this.next(); if (this.match(tt._function) && !this.canInsertSemicolon()) { this.expect(tt._function); return this.parseFunction(node, true, false, true); } else { this.state = state; } } } // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. let maybeName = this.state.value; let expr = this.parseExpression(); if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) { return this.parseLabeledStatement(node, maybeName, expr); } else { return this.parseExpressionStatement(node, expr); } }; pp.takeDecorators = function (node) { if (this.state.decorators.length) { node.decorators = this.state.decorators; this.state.decorators = []; } }; pp.parseDecorators = function (allowExport) { while (this.match(tt.at)) { this.state.decorators.push(this.parseDecorator()); } if (allowExport && this.match(tt._export)) { return; } if (!this.match(tt._class)) { this.raise(this.state.start, "Leading decorators must be attached to a class declaration"); } }; pp.parseDecorator = function () { if (!this.hasPlugin("decorators")) { this.unexpected(); } let node = this.startNode(); this.next(); node.expression = this.parseMaybeAssign(); return this.finishNode(node, "Decorator"); }; pp.parseBreakContinueStatement = function (node, keyword) { let isBreak = keyword === "break"; this.next(); if (this.isLineTerminator()) { node.label = null; } else if (!this.match(tt.name)) { this.unexpected(); } else { node.label = this.parseIdentifier(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. let i; for (i = 0; i < this.state.labels.length; ++i) { let lab = this.state.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break; if (node.label && isBreak) break; } } if (i === this.state.labels.length) this.raise(node.start, "Unsyntactic " + keyword); return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); }; pp.parseDebuggerStatement = function (node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement"); }; pp.parseDoStatement = function (node) { this.next(); this.state.labels.push(loopLabel); node.body = this.parseStatement(false); this.state.labels.pop(); this.expect(tt._while); node.test = this.parseParenExpression(); this.eat(tt.semi); return this.finishNode(node, "DoWhileStatement"); }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp.parseForStatement = function (node) { this.next(); this.state.labels.push(loopLabel); this.expect(tt.parenL); if (this.match(tt.semi)) { return this.parseFor(node, null); } if (this.match(tt._var) || this.match(tt._let) || this.match(tt._const)) { let init = this.startNode(), varKind = this.state.type; this.next(); this.parseVar(init, true, varKind); this.finishNode(init, "VariableDeclaration"); if (this.match(tt._in) || this.isContextual("of")) { if (init.declarations.length === 1 && !init.declarations[0].init) { return this.parseForIn(node, init); } } return this.parseFor(node, init); } let refShorthandDefaultPos = {start: 0}; let init = this.parseExpression(true, refShorthandDefaultPos); if (this.match(tt._in) || this.isContextual("of")) { this.toAssignable(init); this.checkLVal(init); return this.parseForIn(node, init); } else if (refShorthandDefaultPos.start) { this.unexpected(refShorthandDefaultPos.start); } return this.parseFor(node, init); }; pp.parseFunctionStatement = function (node) { this.next(); return this.parseFunction(node, true); }; pp.parseIfStatement = function (node) { this.next(); node.test = this.parseParenExpression(); node.consequent = this.parseStatement(false); node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null; return this.finishNode(node, "IfStatement"); }; pp.parseReturnStatement = function (node) { if (!this.state.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.state.start, "'return' outside of function"); } this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.isLineTerminator()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement"); }; pp.parseSwitchStatement = function (node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(tt.braceL); this.state.labels.push(switchLabel); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. let cur; for (let sawDefault; !this.match(tt.braceR); ) { if (this.match(tt._case) || this.match(tt._default)) { let isCase = this.match(tt._case); if (cur) this.finishNode(cur, "SwitchCase"); node.cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) this.raise(this.state.lastTokStart, "Multiple default clauses"); sawDefault = true; cur.test = null; } this.expect(tt.colon); } else { if (cur) { cur.consequent.push(this.parseStatement(true)); } else { this.unexpected(); } } } if (cur) this.finishNode(cur, "SwitchCase"); this.next(); // Closing brace this.state.labels.pop(); return this.finishNode(node, "SwitchStatement"); }; pp.parseThrowStatement = function (node) { this.next(); if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) this.raise(this.state.lastTokEnd, "Illegal newline after throw"); node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement"); }; // Reused empty array added for node fields that are always empty. let empty = []; pp.parseTryStatement = function (node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.match(tt._catch)) { let clause = this.startNode(); this.next(); this.expect(tt.parenL); clause.param = this.parseBindingAtom(); this.checkLVal(clause.param, true, Object.create(null)); this.expect(tt.parenR); clause.body = this.parseBlock(); node.handler = this.finishNode(clause, "CatchClause"); } node.guardedHandlers = empty; node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement"); }; pp.parseVarStatement = function (node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration"); }; pp.parseWhileStatement = function (node) { this.next(); node.test = this.parseParenExpression(); this.state.labels.push(loopLabel); node.body = this.parseStatement(false); this.state.labels.pop(); return this.finishNode(node, "WhileStatement"); }; pp.parseWithStatement = function (node) { if (this.state.strict) this.raise(this.state.start, "'with' in strict mode"); this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement(false); return this.finishNode(node, "WithStatement"); }; pp.parseEmptyStatement = function (node) { this.next(); return this.finishNode(node, "EmptyStatement"); }; pp.parseLabeledStatement = function (node, maybeName, expr) { for (let label of (this.state.labels: Array<Object>)){ if (label.name === maybeName) { this.raise(expr.start, `Label '${maybeName}' is already declared`); } } let kind = this.state.type.isLoop ? "loop" : this.match(tt._switch) ? "switch" : null; for (let i = this.state.labels.length - 1; i >= 0; i--) { let label = this.state.labels[i]; if (label.statementStart === node.start) { label.statementStart = this.state.start; label.kind = kind; } else { break; } } this.state.labels.push({name: maybeName, kind: kind, statementStart: this.state.start}); node.body = this.parseStatement(true); this.state.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement"); }; pp.parseExpressionStatement = function (node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement"); }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp.parseBlock = function (allowDirectives?) { let node = this.startNode(); this.expect(tt.braceL); this.parseBlockBody(node, allowDirectives, false, tt.braceR); return this.finishNode(node, "BlockStatement"); }; // TODO pp.parseBlockBody = function (node, allowDirectives, topLevel, end) { node.body = []; node.directives = []; let parsedNonDirective = false; let oldStrict; let octalPosition; while (!this.eat(end)) { if (!parsedNonDirective && this.state.containsOctal && !octalPosition) { octalPosition = this.state.octalPosition; } let stmt = this.parseStatement(true, topLevel); if (allowDirectives && !parsedNonDirective && stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral") { let directive = this.stmtToDirective(stmt); node.directives.push(directive); if (oldStrict === undefined && directive.value.value === "use strict") { oldStrict = this.state.strict; this.setStrict(true); if (octalPosition) { this.raise(octalPosition, "Octal literal in strict mode"); } } continue; } parsedNonDirective = true; node.body.push(stmt); } if (oldStrict === false) { this.setStrict(false); } }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp.parseFor = function (node, init) { node.init = init; this.expect(tt.semi); node.test = this.match(tt.semi) ? null : this.parseExpression(); this.expect(tt.semi); node.update = this.match(tt.parenR) ? null : this.parseExpression(); this.expect(tt.parenR); node.body = this.parseStatement(false); this.state.labels.pop(); return this.finishNode(node, "ForStatement"); }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp.parseForIn = function (node, init) { let type = this.match(tt._in) ? "ForInStatement" : "ForOfStatement"; this.next(); node.left = init; node.right = this.parseExpression(); this.expect(tt.parenR); node.body = this.parseStatement(false); this.state.labels.pop(); return this.finishNode(node, type); }; // Parse a list of variable declarations. pp.parseVar = function (node, isFor, kind) { node.declarations = []; node.kind = kind.keyword; for (;;) { let decl = this.startNode(); this.parseVarHead(decl); if (this.eat(tt.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (kind === tt._const && !(this.match(tt._in) || this.isContextual("of"))) { this.unexpected(); } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(tt._in) || this.isContextual("of")))) { this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(tt.comma)) break; } return node; }; pp.parseVarHead = function (decl) { decl.id = this.parseBindingAtom(); this.checkLVal(decl.id, true); }; // Parse a function declaration or literal (depending on the // `isStatement` parameter). pp.parseFunction = function (node, isStatement, allowExpressionBody, isAsync, optionalId) { let oldInMethod = this.state.inMethod; this.state.inMethod = false; this.initFunction(node, isAsync); if (this.match(tt.star)) { if (node.async && !this.hasPlugin("asyncGenerators")) { this.unexpected(); } else { node.generator = true; this.next(); } } if (isStatement && !optionalId && !this.match(tt.name) && !this.match(tt._yield)) { this.unexpected(); } if (this.match(tt.name) || this.match(tt._yield)) { node.id = this.parseBindingIdentifier(); } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody); this.state.inMethod = oldInMethod; return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); }; pp.parseFunctionParams = function (node) { this.expect(tt.parenL); node.params = this.parseBindingList(tt.parenR, false, this.hasPlugin("trailingFunctionCommas")); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp.parseClass = function (node, isStatement, optionalId) { this.next(); this.parseClassId(node, isStatement, optionalId); this.parseClassSuper(node); this.parseClassBody(node); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); }; pp.isClassProperty = function () { return this.match(tt.eq) || this.isLineTerminator(); }; pp.parseClassBody = function (node) { // class bodies are implicitly strict let oldStrict = this.state.strict; this.state.strict = true; let hadConstructorCall = false; let hadConstructor = false; let decorators = []; let classBody = this.startNode(); classBody.body = []; this.expect(tt.braceL); while (!this.eat(tt.braceR)) { if (this.eat(tt.semi)) { continue; } if (this.match(tt.at)) { decorators.push(this.parseDecorator()); continue; } let method = this.startNode(); // steal the decorators if there are any if (decorators.length) { method.decorators = decorators; decorators = []; } let isConstructorCall = false; let isMaybeStatic = this.match(tt.name) && this.state.value === "static"; let isGenerator = this.eat(tt.star); let isGetSet = false; let isAsync = false; this.parsePropertyName(method); method.static = isMaybeStatic && !this.match(tt.parenL); if (method.static) { if (isGenerator) this.unexpected(); isGenerator = this.eat(tt.star); this.parsePropertyName(method); } if (!isGenerator && method.key.type === "Identifier" && !method.computed) { if (this.isClassProperty()) { classBody.body.push(this.parseClassProperty(method)); continue; } if (this.hasPlugin("classConstructorCall") && method.key.name === "call" && this.match(tt.name) && this.state.value === "constructor") { isConstructorCall = true; this.parsePropertyName(method); } } let isAsyncMethod = this.hasPlugin("asyncFunctions") && !this.match(tt.parenL) && !method.computed && method.key.type === "Identifier" && method.key.name === "async"; if (isAsyncMethod) { if (this.hasPlugin("asyncGenerators") && this.eat(tt.star)) isGenerator = true; isAsync = true; this.parsePropertyName(method); } method.kind = "method"; if (!method.computed) { let { key } = method; // handle get/set methods // eg. class Foo { get bar() {} set bar() {} } if (!isAsync && !isGenerator && key.type === "Identifier" && !this.match(tt.parenL) && (key.name === "get" || key.name === "set")) { isGetSet = true; method.kind = key.name; key = this.parsePropertyName(method); } // disallow invalid constructors let isConstructor = !isConstructorCall && !method.static && ( (key.type === "Identifier" && key.name === "constructor") || (key.type === "StringLiteral" && key.value === "constructor") ); if (isConstructor) { if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class"); if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier"); if (isGenerator) this.raise(key.start, "Constructor can't be a generator"); if (isAsync) this.raise(key.start, "Constructor can't be an async function"); method.kind = "constructor"; hadConstructor = true; } // disallow static prototype method let isStaticPrototype = method.static && ( (key.type === "Identifier" && key.name === "prototype") || (key.type === "StringLiteral" && key.value === "prototype") ); if (isStaticPrototype) { this.raise(key.start, "Classes may not have static property named prototype"); } } // convert constructor to a constructor call if (isConstructorCall) { if (hadConstructorCall) this.raise(method.start, "Duplicate constructor call in the same class"); method.kind = "constructorCall"; hadConstructorCall = true; } // disallow decorators on class constructors if ((method.kind === "constructor" || method.kind === "constructorCall") && method.decorators) { this.raise(method.start, "You can't attach decorators to a class constructor"); } this.parseClassMethod(classBody, method, isGenerator, isAsync); // get methods aren't allowed to have any parameters // set methods must have exactly 1 parameter if (isGetSet) { let paramCount = method.kind === "get" ? 0 : 1; if (method.params.length !== paramCount) { let start = method.start; if (method.kind === "get") { this.raise(start, "getter should have no params"); } else { this.raise(start, "setter should have exactly one param"); } } } } if (decorators.length) { this.raise(this.state.start, "You have trailing decorators with no method"); } node.body = this.finishNode(classBody, "ClassBody"); this.state.strict = oldStrict; }; pp.parseClassProperty = function (node) { if (this.match(tt.eq)) { if (!this.hasPlugin("classProperties")) this.unexpected(); this.next(); node.value = this.parseMaybeAssign(); } else { node.value = null; } this.semicolon(); return this.finishNode(node, "ClassProperty"); }; pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) { this.parseMethod(method, isGenerator, isAsync); classBody.body.push(this.finishNode(method, "ClassMethod")); }; pp.parseClassId = function (node, isStatement, optionalId) { if (this.match(tt.name)) { node.id = this.parseIdentifier(); } else { if (optionalId || !isStatement) { node.id = null; } else { this.unexpected(); } } }; pp.parseClassSuper = function (node) { node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null; }; // Parses module export declaration. pp.parseExport = function (node) { this.next(); // export * from '...' if (this.match(tt.star)) { let specifier = this.startNode(); this.next(); if (this.hasPlugin("exportExtensions") && this.eatContextual("as")) { specifier.exported = this.parseIdentifier(); node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")]; this.parseExportSpecifiersMaybe(node); this.parseExportFrom(node, true); } else { this.parseExportFrom(node, true); return this.finishNode(node, "ExportAllDeclaration"); } } else if (this.hasPlugin("exportExtensions") && this.isExportDefaultSpecifier()) { let specifier = this.startNode(); specifier.exported = this.parseIdentifier(true); node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; if (this.match(tt.comma) && this.lookahead().type === tt.star) { this.expect(tt.comma); let specifier = this.startNode(); this.expect(tt.star); this.expectContextual("as"); specifier.exported = this.parseIdentifier(); node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); } else { this.parseExportSpecifiersMaybe(node); } this.parseExportFrom(node, true); } else if (this.eat(tt._default)) { // export default ... let expr = this.startNode(); let needsSemi = false; if (this.eat(tt._function)) { expr = this.parseFunction(expr, true, false, false, true); } else if (this.match(tt._class)) { expr = this.parseClass(expr, true, true); } else { needsSemi = true; expr = this.parseMaybeAssign(); } node.declaration = expr; if (needsSemi) this.semicolon(); this.checkExport(node); return this.finishNode(node, "ExportDefaultDeclaration"); } else if (this.state.type.keyword || this.shouldParseExportDeclaration()) { node.specifiers = []; node.source = null; node.declaration = this.parseExportDeclaration(node); } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(); this.parseExportFrom(node); } this.checkExport(node); return this.finishNode(node, "ExportNamedDeclaration"); }; pp.parseExportDeclaration = function () { return this.parseStatement(true); }; pp.isExportDefaultSpecifier = function () { if (this.match(tt.name)) { return this.state.value !== "type" && this.state.value !== "async"; } if (!this.match(tt._default)) { return false; } let lookahead = this.lookahead(); return lookahead.type === tt.comma || (lookahead.type === tt.name && lookahead.value === "from"); }; pp.parseExportSpecifiersMaybe = function (node) { if (this.eat(tt.comma)) { node.specifiers = node.specifiers.concat(this.parseExportSpecifiers()); } }; pp.parseExportFrom = function (node, expect?) { if (this.eatContextual("from")) { node.source = this.match(tt.string) ? this.parseExprAtom() : this.unexpected(); this.checkExport(node); } else { if (expect) { this.unexpected(); } else { node.source = null; } } this.semicolon(); }; pp.shouldParseExportDeclaration = function () { return this.hasPlugin("asyncFunctions") && this.isContextual("async"); }; pp.checkExport = function (node) { if (this.state.decorators.length) { let isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression"); if (!node.declaration || !isClass) { this.raise(node.start, "You can only use decorators on an export when exporting a class"); } this.takeDecorators(node.declaration); } }; // Parses a comma-separated list of module exports. pp.parseExportSpecifiers = function () { let nodes = []; let first = true; let needsFrom; // export { x, y as z } [from '...'] this.expect(tt.braceL); while (!this.eat(tt.braceR)) { if (first) { first = false; } else { this.expect(tt.comma); if (this.eat(tt.braceR)) break; } let isDefault = this.match(tt._default); if (isDefault && !needsFrom) needsFrom = true; let node = this.startNode(); node.local = this.parseIdentifier(isDefault); node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone(); nodes.push(this.finishNode(node, "ExportSpecifier")); } // https://github.com/ember-cli/ember-cli/pull/3739 if (needsFrom && !this.isContextual("from")) { this.unexpected(); } return nodes; }; // Parses import declaration. pp.parseImport = function (node) { this.next(); // import '...' if (this.match(tt.string)) { node.specifiers = []; node.source = this.parseExprAtom(); } else { node.specifiers = []; this.parseImportSpecifiers(node); this.expectContextual("from"); node.source = this.match(tt.string) ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration"); }; // Parses a comma-separated list of module imports. pp.parseImportSpecifiers = function (node) { let first = true; if (this.match(tt.name)) { // import defaultObj, { x, y as z } from '...' let startPos = this.state.start, startLoc = this.state.startLoc; node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(), startPos, startLoc)); if (!this.eat(tt.comma)) return; } if (this.match(tt.star)) { let specifier = this.startNode(); this.next(); this.expectContextual("as"); specifier.local = this.parseIdentifier(); this.checkLVal(specifier.local, true); node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier")); return; } this.expect(tt.braceL); while (!this.eat(tt.braceR)) { if (first) { first = false; } else { this.expect(tt.comma); if (this.eat(tt.braceR)) break; } let specifier = this.startNode(); specifier.imported = this.parseIdentifier(true); specifier.local = this.eatContextual("as") ? this.parseIdentifier() : specifier.imported.__clone(); this.checkLVal(specifier.local, true); node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); } }; pp.parseImportSpecifierDefault = function (id, startPos, startLoc) { let node = this.startNodeAt(startPos, startLoc); node.local = id; this.checkLVal(node.local, true); return this.finishNode(node, "ImportDefaultSpecifier"); };
mit
serg-kovalev/open_flash_chart
lib/open_flash_chart.rb
2006
module OpenFlashChart end begin require 'rails' rescue LoadError #do nothing end $stderr.puts <<-EOC if !defined?(Rails) warning: no framework detected. Your Gemfile might not be configured properly. ---- e.g. ---- Rails: gem 'open_flash_chart' EOC require 'open_flash_chart/base' require 'open_flash_chart/bar_base' require 'open_flash_chart/bar' require 'open_flash_chart/bar_3d' require 'open_flash_chart/bar_glass' require 'open_flash_chart/bar_sketch' require 'open_flash_chart/bar_filled' require 'open_flash_chart/bar_stack' require 'open_flash_chart/candle' require 'open_flash_chart/chart' require 'open_flash_chart/h_bar' require 'open_flash_chart/line_base' require 'open_flash_chart/line' require 'open_flash_chart/line_dot' require 'open_flash_chart/line_hollow' require 'open_flash_chart/pie' require 'open_flash_chart/scatter' require 'open_flash_chart/scatter_line' require 'open_flash_chart/radar_axis_labels' require 'open_flash_chart/radar_axis' require 'open_flash_chart/radar_spoke_labels' require 'open_flash_chart/title' require 'open_flash_chart/x_axis_label' require 'open_flash_chart/x_axis_labels' require 'open_flash_chart/x_axis' require 'open_flash_chart/x_legend' require 'open_flash_chart/y_axis_base' require 'open_flash_chart/y_axis' require 'open_flash_chart/y_axis_right' require 'open_flash_chart/y_legend' require 'open_flash_chart/y_legend_right' require 'open_flash_chart/legend' require 'open_flash_chart/tooltip' require 'open_flash_chart/area_base' require 'open_flash_chart/area_hollow' require 'open_flash_chart/area_line' require 'open_flash_chart/shape' require 'open_flash_chart/upload_image' require 'open_flash_chart/scatter_line' require 'open_flash_chart/radar_axis_labels' require 'open_flash_chart/radar_axis' require 'open_flash_chart/radar_spoke_labels' require 'open_flash_chart/linear_regression' require 'open_flash_chart/ofc_ajax' require 'open_flash_chart/open_flash_chart_object' require 'open_flash_chart/railtie' if defined? Rails
mit
luoshao23/ML_algorithm
Naive_Bayes/docclass.py
6690
import re import math from pysqlite2 import dbapi2 as sql def sampletrain(cl): cl.train('Nobody owns the water.', 'good') cl.train('the quick rabbit jumps fences', 'good') cl.train('buy pharmaceuticals now', 'bad') cl.train('make quick money at the online casino', 'bad') cl.train('the quick brown fox jumps', 'good') def getwords(doc): splitter = re.compile('\\W*') words = [s.lower() for s in splitter.split(doc) if len(s) > 2 and len(s) < 20] return dict([(w, 1) for w in words]) def getwordscount(doc): splitter = re.compile('\\W*') words = [s.lower() for s in splitter.split(doc) if len(s) > 2 and len(s) < 20] wordcount = {} for word in words: wordcount.setdefault(word, 0) wordcount[word] += 1 return wordcount class classifier(object): """docstring for classifier""" def __init__(self, getfeatures, filename=None): self.fc = {} self.cc = {} self.getfeatures = getfeatures self.filename = filename # print "classifier" def setdb(self, dbfile): self.con = sql.connect(dbfile) self.con.execute( 'create table if not exists fc(feature, category, count)') self.con.execute('create table if not exists cc(category, count)') def incf(self, f, cat): # self.fc.setdefault(f,{}) # self.fc[f].setdefault(cat, 0) # self.fc[f][cat] += 1 count = self.fcount(f, cat) if count == 0: self.con.execute("insert into fc values ('%s','%s',1)" % (f, cat)) else: self.con.execute("update fc set count=%d where feature='%s' and category='%s'" % (count + 1, f, cat)) def incc(self, cat): # self.cc.setdefault(cat, 0) # self.cc[cat] += 1 count = self.catcount(cat) if count == 0: self.con.execute("insert into cc values ('%s',1)" % (cat)) else: self.con.execute( "update cc set count=%d where category='%s'" % (count + 1, cat)) def fcount(self, f, cat): # if f in self.fc and cat in self.fc[f]: # return float(self.fc[f][cat]) # return 0 res = self.con.execute("select count from fc where feature='%s' and category='%s'" % (f, cat)).fetchone() if res == None: return 0 else: return float(res[0]) def catcount(self, cat): # if cat in self.cc: # return float(self.cc[cat]) # return 0 res = self.con.execute( "select count from cc where category='%s'" % (cat)).fetchone() if res == None: return 0 else: return float(res[0]) def totalcount(self): # return sum(self.cc.values()) res = self.con.execute("select sum(count) from cc").fetchone() if res == None: return 0 return res[0] def categories(self): # return self.cc.keys() cur = self.con.execute("select category from cc") return [d[0] for d in cur] def train(self, item, cat): features = self.getfeatures(item) for f in features: self.incf(f, cat) self.incc(cat) self.con.commit() def fprob(self, f, cat): """ cal prob = P(f, cat)/P() """ if self.catcount(cat) == 0: return 0 return self.fcount(f, cat) / self.catcount(cat) def weightedprob(self, f, cat, prf, weight=1.0, ap=0.5): basicprob = prf(f, cat) totals = sum([self.fcount(f, c) for c in self.categories()]) bp = ((weight * ap) + (totals * basicprob)) / (weight + totals) return bp def itemclassify(self, item, cat): wordcount = getwordscount(item) prob = 0.0 for word, count in wordcount.items(): prob += self.weightedprob(word, cat, self.fprob) * count prob = float(prob) / sum(wordcount.values()) return prob class naivebayes(classifier): """docstring for naivebayes""" def __init__(self, getfeatures): super(naivebayes, self).__init__(getfeatures) self.thresholds = {} def setthreshold(self, cat, t): self.thresholds[cat] = t def getthreshold(self, cat): if cat not in self.thresholds: return 0 return self.thresholds[cat] def docprob(self, item, cat): features = self.getfeatures(item) p = 1 for f in features: p *= self.weightedprob(f, cat, self.fprob) return p def prob(self, item, cat): catprob = self.catcount(cat) / self.totalcount() docprob = self.docprob(item, cat) return docprob * catprob def classify(self, item, default=None): probs = {} maxit = 0.0 for cat in self.categories(): probs[cat] = self.prob(item, cat) if probs[cat] > maxit: maxit = probs[cat] best = cat for cat in probs: if cat == best: continue if probs[cat] * self.getthreshold(best) > probs[best]: return default return best class fisherclassifier(classifier): """docstring for fisherclassifier""" def __init__(self, getfeatures): super(fisherclassifier, self).__init__(getfeatures) self.minimums = {} def setminimum(self, cat, minit): self.minimums[cat] = minit def getminimum(self, cat): if cat not in self.minimums: return 0 return self.minimums[cat] def cprob(self, f, cat): clf = self.fprob(f, cat) if clf == 0: return 0 freqsum = sum([self.fprob(f, c) for c in self.categories()]) p = clf / freqsum return p def fisherprob(self, item, cat): p = 1 features = self.getfeatures(item) for f in features: p *= self.weightedprob(f, cat, self.cprob) fscore = -2 * math.log(p) return self.invchi2(fscore, len(features) * 2) def invchi2(self, chi, df): m = chi / 2.0 sumit = term = math.exp(-m) for i in xrange(1, df // 2): term *= m / i sumit += term return min(sumit, 1.0) def classify(self, item, default=None): best = default maxit = 0.0 for c in self.categories(): p = self.fisherprob(item, c) if p > self.getminimum(c) and p > maxit: best = c maxit = p return best
mit
sphereio/commercetools-php-symfony
src/CtpBundle/Tests/TestKernel.php
2749
<?php namespace Commercetools\Symfony\CtpBundle\Tests; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Kernel as BaseKernel; use Symfony\Component\Routing\RouteCollectionBuilder; class TestKernel extends BaseKernel { use MicroKernelTrait; const CONFIG_EXTS = '.{php,xml,yaml,yml}'; private $containerConfigurator; public function __construct(\Closure $containerConfigurator, $environment = 'test', $debug = false) { $this->containerConfigurator = $containerConfigurator; parent::__construct($environment, $debug); } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(function (ContainerBuilder $container) use ($loader) { $container->loadFromExtension('framework', array( 'router' => array( 'resource' => 'kernel::loadRoutes', 'type' => 'service', ), )); if ($this instanceof EventSubscriberInterface) { $container->register('kernel', static::class) ->setSynthetic(true) ->setPublic(true) ->addTag('kernel.event_subscriber') ; } $this->configureContainer($container, $loader); $container->addObjectResource($this); }); $loader->load($this->containerConfigurator); } /** * Override the parent method to force recompiling the container. * For performance reasons the container is also not dumped to disk. */ protected function initializeContainer() { $this->container = $this->buildContainer(); $this->container->compile(); $this->container->set('kernel', $this); } public function getCacheDir() { return $this->getProjectDir().'/var/cache/'.$this->environment; } public function getLogDir() { return $this->getProjectDir().'/var/log'; } public function registerBundles() { yield new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(); } protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader) { $container->setParameter('container.autowiring.strict_mode', true); $container->setParameter('container.dumper.inline_class_loader', true); $container->setParameter('kernel.secret', '123456'); } protected function configureRoutes(RouteCollectionBuilder $routes) { } }
mit
phpDocumentor/phpDocumentor2
src/phpDocumentor/Descriptor/TraitDescriptor.php
5475
<?php declare(strict_types=1); /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @link https://phpdoc.org */ namespace phpDocumentor\Descriptor; use InvalidArgumentException; use phpDocumentor\Descriptor\Tag\ReturnDescriptor; use phpDocumentor\Descriptor\Validation\Error; use function ltrim; use function sprintf; /** * Descriptor representing a Trait. * * @api * @package phpDocumentor\AST */ class TraitDescriptor extends DescriptorAbstract implements Interfaces\TraitInterface { /** @var Collection<PropertyDescriptor> $properties */ protected $properties; /** @var Collection<MethodDescriptor> $methods */ protected $methods; /** @var Collection<TraitDescriptor|string> $usedTraits */ protected $usedTraits; /** * Initializes the all properties representing a collection with a new Collection object. */ public function __construct() { parent::__construct(); $this->setProperties(new Collection()); $this->setMethods(new Collection()); $this->setUsedTraits(new Collection()); } public function setMethods(Collection $methods) : void { $this->methods = $methods; } public function getMethods() : Collection { return $this->methods; } public function getInheritedMethods() : Collection { return new Collection(); } /** * @return Collection<MethodDescriptor> */ public function getMagicMethods() : Collection { /** @var Collection<Tag\MethodDescriptor> $methodTags */ $methodTags = $this->getTags()->fetch('method', new Collection()); $methods = Collection::fromClassString(MethodDescriptor::class); /** @var Tag\MethodDescriptor $methodTag */ foreach ($methodTags as $methodTag) { $method = new MethodDescriptor(); $method->setName($methodTag->getMethodName()); $method->setDescription($methodTag->getDescription()); $method->setStatic($methodTag->isStatic()); $method->setParent($this); /** @var Collection<ReturnDescriptor> $returnTags */ $returnTags = $method->getTags()->fetch('return', new Collection()); $returnTags->add($methodTag->getResponse()); foreach ($methodTag->getArguments() as $name => $argument) { $method->addArgument($name, $argument); } $methods->add($method); } return $methods; } public function setProperties(Collection $properties) : void { $this->properties = $properties; } public function getProperties() : Collection { return $this->properties; } public function getInheritedProperties() : Collection { return new Collection(); } /** * @return Collection<PropertyDescriptor> */ public function getMagicProperties() : Collection { $tags = $this->getTags(); /** @var Collection<Tag\PropertyDescriptor> $propertyTags */ $propertyTags = $tags->fetch('property', new Collection())->filter(Tag\PropertyDescriptor::class) ->merge($tags->fetch('property-read', new Collection())->filter(Tag\PropertyDescriptor::class)) ->merge($tags->fetch('property-write', new Collection())->filter(Tag\PropertyDescriptor::class)); $properties = Collection::fromClassString(PropertyDescriptor::class); /** @var Tag\PropertyDescriptor $propertyTag */ foreach ($propertyTags as $propertyTag) { $property = new PropertyDescriptor(); $property->setName(ltrim($propertyTag->getVariableName(), '$')); $property->setDescription($propertyTag->getDescription()); $property->setType($propertyTag->getType()); try { $property->setParent($this); } catch (InvalidArgumentException $e) { $property->getErrors()->add( new Error( 'ERROR', sprintf( 'Property name is invalid %s', $e->getMessage() ), null ) ); } $properties->add($property); } return $properties; } /** * @param PackageDescriptor|string $package */ public function setPackage($package) : void { parent::setPackage($package); foreach ($this->getProperties() as $property) { $property->setPackage($package); } foreach ($this->getMethods() as $method) { $method->setPackage($package); } } /** * Sets a collection of all traits used by this class. * * @param Collection<TraitDescriptor|string> $usedTraits */ public function setUsedTraits(Collection $usedTraits) : void { $this->usedTraits = $usedTraits; } /** * Returns the traits used by this class. * * Returned values may either be a string (when the Trait is not in this project) or a TraitDescriptor. * * @return Collection<TraitDescriptor|string> */ public function getUsedTraits() : Collection { return $this->usedTraits; } }
mit
argob/cofra
src/Framework/GeneralBundle/Form/DireccionIndustrialType.php
934
<?php namespace Framework\GeneralBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilder; use Framework\GeneralBundle\Form\Type\ComboPartidoType; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class DireccionIndustrialType extends AbstractType { public function buildForm(FormBuilder $builder, array $options) { $builder ->add('ruta',null,array( 'required' => false)) ->add('km',null,array( 'required' => false)) //->add('calleinterna') ->add('parcela',null,array( 'required' => false)) ->add('lote',null,array( 'required' => false)) ; } public function getName() { return 'dirIndustrial'; } public function setDefaultOptions(OptionsResolverInterface $options) { return array( 'data_class' => 'Framework\GeneralBundle\Entity\Direccion\DireccionIndustrial', ); } } ?>
mit
sdl/Testy
src/test/unit/java/com/sdl/selenium/extjs3/form/RadioGroupTest.java
1213
package com.sdl.selenium.extjs3.form; import com.sdl.selenium.extjs3.ExtJsComponent; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; public class RadioGroupTest { public static ExtJsComponent container = new ExtJsComponent("container"); @DataProvider public static Object[][] testConstructorPathDataProvider() { return new Object[][]{ {new RadioGroup(), "//*[contains(concat(' ', @class, ' '), ' x-form-radio-group ')]"}, {new RadioGroup(container), "//*[contains(concat(' ', @class, ' '), ' container ')]//*[contains(concat(' ', @class, ' '), ' x-form-radio-group ')]"}, {new RadioGroup(container, "Name"), "//*[contains(concat(' ', @class, ' '), ' container ')]//*[contains(concat(' ', @class, ' '), ' x-form-radio-group ')]"}, }; } @Test(dataProvider = "testConstructorPathDataProvider") public void getPathSelectorCorrectlyFromConstructors(RadioGroup radioGroup, String expectedXpath) { assertThat(radioGroup.getXPath(), equalTo(expectedXpath)); } }
mit
czim/laravel-cms-models
src/ModelInformation/Data/ModelMetaData.php
3224
<?php namespace Czim\CmsModels\ModelInformation\Data; use Czim\CmsModels\Contracts\ModelInformation\Data\ModelMetaDataInterface; /** * Class ModelMetaData * * Meta-information about a model in the context of the CMS. * * @property string $controller * @property string $default_controller_method * @property string $controller_api * @property string $repository_strategy * @property array $repository_strategy_parameters * @property string|bool $disable_global_scopes * @property string[] $form_requests * @property string[] $views * @property string $transformer */ class ModelMetaData extends AbstractModelInformationDataObject implements ModelMetaDataInterface { protected $attributes = [ // FQN for the controller class to handle the model's web & API presence 'controller' => null, // Default controller action to link to for the basic model's menu presence ('index', 'create', for instance) 'default_controller_method' => 'index', // FQN for the controller class to handle the model's API presence 'controller_api' => null, // The strategy to apply to the base repository query for listings & accessibility of models. 'repository_strategy' => null, // Optional parameters to pass along to the repository strategy instance. 'repository_strategy_parameters' => [], // Whether to disable all global scopes (boolean true) or a string with comma-separated global scopes to disable 'disable_global_scopes' => null, // List of FQNs for form requests, keyed by the relevant POST controller method name ('update', 'create') 'form_requests' => [], // List of (default) views to use, keyed by the controller action method name. 'views' => [], // API serialization transformer class to use. Any class that implements the models module transformer interface. 'transformer' => null, ]; protected $known = [ 'controller', 'controller_api', 'default_controller_method', 'repository_strategy', 'repository_strategy_parameters', 'disable_global_scopes', 'form_requests', 'views', 'transformer', ]; /** * @param ModelMetaDataInterface|ModelMetaData $with */ public function merge(ModelMetaDataInterface $with) { $mergeAttributes = [ 'controller', 'controller_api', 'default_controller_method', 'transformer', 'repository_strategy', 'disable_global_scopes', ]; foreach ($mergeAttributes as $attribute) { $this->mergeAttribute($attribute, $with->{$attribute}); } if ( ! empty($with->repository_strategy_parameters)) { $this->repository_strategy_parameters = $with->repository_strategy_parameters; } if ( ! empty($with->form_requests)) { $this->form_requests = array_merge($this->form_requests, $with->form_requests); } if ( ! empty($with->views)) { $this->views = array_merge($this->views, $with->views); } } }
mit
frederickfg/APP3
FeuilleAST.java
462
package APP3; /** @author Ahmed Khoumsi */ /** * Classe representant une feuille d'AST */ public class FeuilleAST extends ElemAST { // Attribut(s) /** * Constructeur pour l'initialisation d'attribut(s) */ public FeuilleAST() { // avec arguments // } /** * Evaluation de feuille d'AST */ public int EvalAST() { // } /** * Lecture de chaine de caracteres correspondant a la feuille d'AST */ public String LectAST() { // } }
mit
RossCasey/SecureDrop
src/server/Persistence/Connectors/Sqlite.js
1068
const sqlite = require('sqlite'); function getDropApi(sqlite) { return { create(id, cipherText) { return sqlite.run('INSERT INTO drops(id, cipherText) VALUES(:id, :cipherText)', {':id':id, ':cipherText':cipherText}); }, get(id) { return sqlite.get('SELECT * FROM drops WHERE claimed = 0 AND created > (strftime(\'%s\', \'now\') - 86400) AND id = ? LIMIT 1', id); }, claim(id) { return sqlite.run('UPDATE drops SET claimed = 1 WHERE id = ?', id); }, raw(query, data) { return sqlite.run(query, data); } } } function getApi(sqlite) { return { drop: getDropApi(sqlite) } } module.exports = () => { const path = process.env.DB_DATABASE || './database.sqlite'; const migrate = process.env.DB_MIGRATE || false; const force = process.env.DB_MIGRATE_FORCE || false; return sqlite.open(path, { Promise }).then(() => { if(migrate) return sqlite.migrate({ force: force }); return Promise.resolve(); }).then(() => { return getApi(sqlite); }).catch((err) => { throw err; }); };
mit
famoser/OfflineMedia
Famoser.OfflineMedia.View/ViewModels/BaseViewModelLocator.cs
3606
/* In App.xaml: <Application.Resources> <vm:ViewModelLocator xmlns:vm="clr-namespace:OfflineMediaV3" x:Key="Locator" /> </Application.Resources> In the View: DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}" You can also use Blend to do all this with the tool's support. See http://www.galasoft.ch/mvvm */ using CommonServiceLocator; using Famoser.OfflineMedia.Business.Repositories; using Famoser.OfflineMedia.Business.Repositories.Interfaces; using Famoser.OfflineMedia.Business.Repositories.Mocks; using Famoser.OfflineMedia.Business.Services; using Famoser.OfflineMedia.Business.Services.Interfaces; using Famoser.OfflineMedia.View.Services; using Famoser.SqliteWrapper.Services; using Famoser.SqliteWrapper.Services.Interfaces; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Ioc; namespace Famoser.OfflineMedia.View.ViewModels { /// <summary> /// This class contains static references to all the view models in the /// application and provides an entry point for the bindings. /// </summary> public class BaseViewModelLocator { /// <summary> /// Initializes a new instance of the ViewModelLocator class. /// </summary> static BaseViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register<IArticleRepository, ArticleRepositoryMock>(); SimpleIoc.Default.Register<ISettingsRepository, SettingsRepositoryMock>(); SimpleIoc.Default.Register<IThemeRepository, ThemeRepositoryMock>(); SimpleIoc.Default.Register<IWeatherRepository, WeatherRepositoryMock>(); } else { SimpleIoc.Default.Register<IArticleRepository, ArticleRepository>(); SimpleIoc.Default.Register<ISettingsRepository, SettingsRepository>(); SimpleIoc.Default.Register<IThemeRepository, ThemeRepository>(); SimpleIoc.Default.Register<IWeatherRepository, WeatherRepository>(); } SimpleIoc.Default.Register<ISqliteService, SqliteService>(); SimpleIoc.Default.Register<IProgressService, ProgressService>(); SimpleIoc.Default.Register<IImageDownloadService, ImageDownloadService>(); SimpleIoc.Default.Register<MainPageViewModel>(); SimpleIoc.Default.Register<FeedPageViewModel>(); SimpleIoc.Default.Register<ArticlePageViewModel>(); SimpleIoc.Default.Register<SettingsPageViewModel>(); SimpleIoc.Default.Register<MyDayViewModel>(); SimpleIoc.Default.Register<ProgressViewModel>(true); } public MainPageViewModel MainPageViewModel => ServiceLocator.Current.GetInstance<MainPageViewModel>(); public FeedPageViewModel FeedPageViewModel => ServiceLocator.Current.GetInstance<FeedPageViewModel>(); public ArticlePageViewModel ArticlePageViewModel => ServiceLocator.Current.GetInstance<ArticlePageViewModel>(); public SettingsPageViewModel SettingsPageViewModel => ServiceLocator.Current.GetInstance<SettingsPageViewModel>(); public MyDayViewModel MyDayViewModel => ServiceLocator.Current.GetInstance<MyDayViewModel>(); public ProgressViewModel ProgressViewModel => ServiceLocator.Current.GetInstance<ProgressViewModel>(); public static void Cleanup() { // TODO Clear the ViewModels } } }
mit
bstauff/orleans
test/TesterAzureUtils/Streaming/AQStreamFilteringTests.cs
2997
using System; using System.Threading.Tasks; using Orleans.Providers.Streams.AzureQueue; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using Tester.StreamingTests; using TestExtensions; using UnitTests.StreamingTests; using Xunit; namespace Tester.AzureUtils.Streaming { [TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public class StreamFilteringTests_AQ : StreamFilteringTestsBase, IClassFixture<StreamFilteringTests_AQ.Fixture>, IDisposable { private readonly string deploymentId; public class Fixture : BaseAzureTestClusterFixture { public const string StreamProvider = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME; protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(2); options.ClusterConfiguration.AddMemoryStorageProvider("MemoryStore"); options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore"); options.ClusterConfiguration.AddAzureQueueStreamProvider(StreamProvider); return new TestCluster(options); } public override void Dispose() { var deploymentId = this.HostedCluster?.DeploymentId; base.Dispose(); AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(StreamProvider, deploymentId, TestDefaultConfiguration.DataConnectionString) .Wait(); } } public StreamFilteringTests_AQ(Fixture fixture) : base(fixture) { fixture.EnsurePreconditionsMet(); this.deploymentId = fixture.HostedCluster.DeploymentId; streamProviderName = Fixture.StreamProvider; } public virtual void Dispose() { AzureQueueStreamProviderUtils.ClearAllUsedAzureQueues( streamProviderName, this.deploymentId, TestDefaultConfiguration.DataConnectionString).Wait(); } [SkippableFact, TestCategory("Functional")] public async Task AQ_Filter_Basic() { await Test_Filter_EvenOdd(true); } [SkippableFact, TestCategory("Functional")] public async Task AQ_Filter_EvenOdd() { await Test_Filter_EvenOdd(); } [SkippableFact, TestCategory("Functional")] public async Task AQ_Filter_BadFunc() { await Assert.ThrowsAsync<ArgumentException>(() => Test_Filter_BadFunc()); } [SkippableFact, TestCategory("Functional")] public async Task AQ_Filter_TwoObsv_Different() { await Test_Filter_TwoObsv_Different(); } [SkippableFact, TestCategory("Functional")] public async Task AQ_Filter_TwoObsv_Same() { await Test_Filter_TwoObsv_Same(); } } }
mit
gesh123/MyLibrary
src/client/app/poker/connection/protocol/core/serializers/PokerCommandSerializer.ts
3938
import {IPokerCommandSerializer} from "./IPokerCommandSerializer"; import {IPokerCommand} from "../commands/IPokerCommand"; import {ICommandSerializersMap} from "../maps/ICommandSerializersMap"; import {ICommandsMap} from "../maps/ICommandMap"; import {PokerCommandHeader} from "../data/PokerCommandHeader"; import {PokerCommandHeaderSerializer} from "./PokerCommandHeaderSerializer"; import {UnknownCommandSerializer} from "./UnknownCommandSerializer"; import {ArrayBufferBuilder} from "../../../../utils/ArrayBufferBuilder"; import {UnknownCommand} from "../commands/UnknownCommand"; import {PokerGeneratedCommandSerializersMap} from "../../generated/Maps/CommandSerializersMap"; import {PokerGeneratedCommandsMap} from "../../generated/Maps/CommandsMap"; import {PokerFailedCommand} from "../commands/FailedCommand"; import {AbstractPokerCommand} from "../commands/AbstractPokerCommand"; /** * Created by hivaga on 7/14/2016. */ export class PokerCommandsSerializer implements IPokerCommandSerializer { // ----------------------------------------- // PUBLIC PROPERTIES // ----------------------------------------- // ----------------------------------------- // PROTECTED PROPERTIES // ----------------------------------------- protected static SERIALIZERS_MAP:ICommandSerializersMap = new PokerGeneratedCommandSerializersMap(); protected static COMMANDS_MAP:ICommandsMap = new PokerGeneratedCommandsMap(); // ----------------------------------------- // PRIVATE PROPERTIES // ----------------------------------------- private header:PokerCommandHeader; private headerSerializer:PokerCommandHeaderSerializer; // ----------------------------------------- // CONSTRUCTOR // ----------------------------------------- constructor() { this.header = new PokerCommandHeader(); this.headerSerializer = new PokerCommandHeaderSerializer(); } // ----------------------------------------- // PUBLIC METHODS // ----------------------------------------- /** * Writes(serializes) a Command into ArrayBufferBuilder. * * @param {ArrayBufferBuilder} buffer the stream/buffer/byte array where the serialized command will be written * @param {Command} command the command which have to be written */ public serialize( buffer:ArrayBufferBuilder, command:IPokerCommand ):void { let serializer:IPokerCommandSerializer = this.getCommandSerializer( command ); serializer.serialize( buffer, command ); } /** * Reads(deserializes) a Poker Command from ArrayBufferBuilder * * @param {ArrayBufferBuilder} buffer the stream/buffer/byte array from which the command will be read/extracted and deserialized */ public deserialize( buffer:ArrayBufferBuilder ):IPokerCommand { let header:PokerCommandHeader = new PokerCommandHeader(); PokerCommandHeaderSerializer.deserialize( buffer, header ); buffer.pointer -= PokerCommandHeader.HEADER_SIZE_BYTES; let commandClass:{new():IPokerCommand} = PokerCommandsSerializer.COMMANDS_MAP.getCommand( header.pid, header.cid ) || UnknownCommand; let command:IPokerCommand = new commandClass(); let serializer:IPokerCommandSerializer = this.getCommandSerializer( command ); try { serializer.deserialize( buffer, command ); } catch (err) { command = new PokerFailedCommand( command as AbstractPokerCommand ); } return command; } // ----------------------------------------- // PROTECTED METHODS // ----------------------------------------- protected getCommandSerializer( commnad:IPokerCommand ):IPokerCommandSerializer { if (commnad instanceof UnknownCommand) { return <IPokerCommandSerializer>UnknownCommandSerializer; } let serializer:IPokerCommandSerializer = PokerCommandsSerializer.SERIALIZERS_MAP.getCommand( commnad.pid, commnad.cid ); return serializer || UnknownCommandSerializer; } // ----------------------------------------- // PRIVATE METHODS // ----------------------------------------- }
mit
tsnorri/gonia
project/src/test/java/fi/iki/tsnorri/gonia/logic/HexPointTest.java
7776
/* * Copyright (c) 2012, 2015 Tuukka Norri, tsnorri@iki.fi. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. */ package fi.iki.tsnorri.gonia.logic; import java.util.Arrays; import org.junit.*; import static org.junit.Assert.*; /** * * @author tsnorri */ public class HexPointTest { public HexPointTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testCreation1() { HexPoint c = new HexPoint(-1, 0, 1); } @Test public void testCreation2() { HexPoint c = new HexPoint(1, 1, -2); } @Test public void testCreation3() { HexPoint c = new HexPoint(0, 0, 0); } @Test public void testCreationByOffsets1() { HexPoint c = HexPoint.createWithOffsets(0, 0); assertEquals (0, c.getHorizontalOffset()); assertEquals (0, c.getY()); } @Test public void testCreationByOffsets2() { HexPoint c = HexPoint.createWithOffsets(5, 4); assertEquals(5, c.getHorizontalOffset()); assertEquals(4, c.getY()); } @Test public void testInvalidCoordinates() { Exception exc = null; try { HexPoint c = new HexPoint(1, 1, -1); } catch (IllegalArgumentException e) { exc = e; } assertNotNull(exc); assertEquals(IllegalArgumentException.class, exc.getClass()); assertEquals("The sum of coordinates must be zero.", exc.getMessage()); } @Test public void testEquals1() { HexPoint c1 = new HexPoint(1, -1, 0); HexPoint c2 = new HexPoint(1, -1, 0); assertEquals(c1, c2); } @Test public void testEquals2() { HexPoint c1 = new HexPoint(1, -1, 0); HexPoint c2 = new HexPoint(1, 0, -1); assertFalse(c1.equals (c2)); } @Test public void testEquals3() { HexPoint c = new HexPoint(1, -1, 0); String s = "s"; assertFalse(c.equals (s)); } @Test public void testSort() { HexPoint p1 = HexPoint.createWithOffsets(0, 0); HexPoint p2 = HexPoint.createWithOffsets(0, 1); HexPoint p3 = HexPoint.createWithOffsets(3, 1); HexPoint p4 = HexPoint.createWithOffsets(2, 3); HexPoint[] initial = {p2, p4, p3, p1}; HexPoint[] expected = {p1, p2, p3, p4}; Arrays.sort (initial, new HexPoint.Comparator()); assertArrayEquals(expected, initial); } @Test public void testHash() { // Smoke test only. HexPoint p = new HexPoint(1, 2, -3); assertNotSame (0, p.hashCode ()); } @Test public void testInvalidTransformation1() { int[][] matrix = { {1, 0}, {0, 1} }; HexPoint p = new HexPoint(0, 1, -1); try { p.transformedCopy(matrix); } catch (IllegalArgumentException exc) { assertEquals("Transformation matrix must be 4×4.", exc.getMessage()); } } @Test public void testInvalidTransformationMutable1() { int[][] matrix = { {1, 0}, {0, 1} }; MutableHexPoint p = new MutableHexPoint(0, 1, -1); try { p.transform(matrix); } catch (IllegalArgumentException exc) { assertEquals("Transformation matrix must be 4×4.", exc.getMessage()); } } @Test public void testInvalidTransformation2() { int[][] matrix = { {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {1, 2, 3, 1} }; HexPoint p = new HexPoint(0, 1, -1); try { p.transformedCopy(matrix); } catch (IllegalArgumentException exc) { assertEquals("The sum of translations must be zero.", exc.getMessage()); } } @Test public void testInvalidTransformationMutable2() { int[][] matrix = { {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {1, 2, 3, 1} }; MutableHexPoint p = new MutableHexPoint(0, 1, -1); try { p.transformedCopy(matrix); } catch (IllegalArgumentException exc) { assertEquals("The sum of translations must be zero.", exc.getMessage()); } } @Test public void testTransformedCopy1() { int[][] matrix = { { 0, 0, -1, 0}, {-1, 0, 0, 0}, { 0, -1, 0, 0}, { 0, 0, 0, 1} }; HexPoint c1 = new HexPoint(0, 1, -1); HexPoint c2 = c1.transformedCopy(matrix); HexPoint expected = new HexPoint(-1, 1, 0); assertEquals(expected, c2); } @Test public void testTransformedCopy2() { int[][] matrix = { { 0, -1, 0, 0}, { 0, 0, -1, 0}, {-1, 0, 0, 0}, { 0, 0, 0, 1} }; HexPoint c1 = new HexPoint(0, 1, -1); HexPoint c2 = c1.transformedCopy(matrix); HexPoint expected = new HexPoint(1, 0, -1); assertEquals(expected, c2); } @Test public void testTransformedCopy3() { HexPoint c1 = HexPoint.createWithOffsets(0, 0); int[][] matrix = HexPoint.translationTransformation(2, 0, true); HexPoint c2 = c1.transformedCopy(matrix); assertEquals(0, c1.getHorizontalOffset()); assertEquals(0, c1.getY()); assertEquals(2, c2.getHorizontalOffset()); assertEquals(0, c2.getY()); } @Test public void testTransformedCopy4() { HexPoint c1 = HexPoint.createWithOffsets (3, 1); int[][] matrix = HexPoint.translationTransformation(1, 0, false); HexPoint c2 = c1.transformedCopy(matrix); assertEquals(3, c1.getHorizontalOffset()); assertEquals(1, c1.getY()); assertEquals(4, c2.getHorizontalOffset()); assertEquals(1, c2.getY()); } @Test public void testTransformMultiple1() { HexPoint c1 = HexPoint.createWithOffsets(1, 0); HexPoint c2 = HexPoint.createWithOffsets(1, 1); HexPoint[] transformed = HexPoint.copyWithOrthogonalTranslation(new HexPoint[] {c1, c2}, 0, 1); assertEquals (2, transformed.length); HexPoint tc1 = transformed[0]; HexPoint tc2 = transformed[1]; assertEquals(1, tc1.getHorizontalOffset()); assertEquals(2, tc2.getHorizontalOffset()); assertEquals(1, tc1.getY()); assertEquals(2, tc2.getY()); } @Test public void testTransformMultiple2() { HexPoint c1 = HexPoint.createWithOffsets(1, 0); HexPoint c2 = HexPoint.createWithOffsets(1, 1); HexPoint[] transformed = HexPoint.copyWithOrthogonalTranslation(new HexPoint[] {c1, c2}, 0, -1); assertEquals(2, transformed.length); HexPoint tc1 = transformed[0]; HexPoint tc2 = transformed[1]; assertEquals(1, tc1.getHorizontalOffset()); assertEquals(2, tc2.getHorizontalOffset()); assertEquals(-1, tc1.getY()); assertEquals(0, tc2.getY()); } @Test public void testTransformMultipleMutable1() { MutableHexPoint c1 = MutableHexPoint.createWithOffsets(1, 0); MutableHexPoint c2 = MutableHexPoint.createWithOffsets(1, 1); HexPoint.applyOrthogonalTranslation(new MutableHexPoint[] {c1, c2}, 0, 1); assertEquals(1, c1.getHorizontalOffset()); assertEquals(2, c2.getHorizontalOffset()); assertEquals(1, c1.getY()); assertEquals(2, c2.getY()); } @Test public void testTransformMultipleMutable2() { MutableHexPoint c1 = MutableHexPoint.createWithOffsets(1, 0); MutableHexPoint c2 = MutableHexPoint.createWithOffsets(1, 1); HexPoint.applyOrthogonalTranslation(new MutableHexPoint[] {c1, c2}, 0, -1); assertEquals(1, c1.getHorizontalOffset()); assertEquals(2, c2.getHorizontalOffset()); assertEquals(-1, c1.getY()); assertEquals(0, c2.getY()); } @Test public void testCopyFrom() { HexPoint p1 = new HexPoint(1, 2, -3); MutableHexPoint p2 = new MutableHexPoint(0, 0, 0); assertNotSame(p2, p1); p2.copyFrom(p1); assertEquals(p2, p1); } @Test public void testAssignOffsets() { final int h = 2; final int v = 3; HexPoint p1 = HexPoint.createWithOffsets(h, v); MutableHexPoint p2 = MutableHexPoint.createWithOffsets(0, 0); assertNotSame(p2, p1); p2.assignOffsets(h, v); assertEquals(p2, p1); } }
mit
grnhse/greenhouse-tools-php
src/Services/Exceptions/GreenhouseApplicationException.php
204
<?php namespace Greenhouse\GreenhouseToolsPhp\Services\Exceptions; use Greenhouse\GreenhouseToolsPhp\Exceptions\GreenhouseException; class GreenhouseApplicationException extends GreenhouseException {}
mit
Need4Speed402/tessellator
src/renderers/FullScreenTextureRenderer.js
3979
/** * Copyright (c) 2015, Alexander Orzechowski. * * 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. */ /** * Currently in beta stage. Changes can and will be made to the core mechanic * making this not backwards compatible. * * Github: https://github.com/Need4Speed402/tessellator */ Tessellator.FullScreenTextureRenderer = function (shader, uv){ if (uv && uv.constructor === Array){ if (arguments.length > 2){ this.textures = Array.prototype.slice.call(arguments, 2, arguments.length); if (shader.constructor === Tessellator.ShaderPreset){ shader = shader.create(this.textures[0].tessellator); }; }; if (shader.constructor === Tessellator){ shader = tessellator.createPixelShader(Tessellator.PIXEL_SHADER_PASS); }; this.super(shader); this.setUV(uv); }else if (arguments.length > 1){ this.textures = Array.prototype.slice.call(arguments, 1, arguments.length); if (shader.constructor === Tessellator.ShaderPreset){ shader = tessellator.createPixelShader(shader.create(this.textures[0].tessellator)); }else if (shader.constructor === Tessellator){ shader = tessellator.createPixelShader(Tessellator.PIXEL_SHADER_PASS); }; this.super(shader); }else{ if (shader.constructor === Tessellator){ shader = tessellator.createPixelShader(Tessellator.PIXEL_SHADER_PASS); }; this.super(shader); } }; Tessellator.copyProto(Tessellator.FullScreenTextureRenderer, Tessellator.FullScreenRenderer); Tessellator.FullScreenTextureRenderer.prototype.setUV = function (uv){ this.object.setAttribute("uv", Tessellator.VEC2, new Tessellator.Array(uv)); this.object.upload(); }; Tessellator.FullScreenTextureRenderer.prototype.setTextures = function (textures){ this.textures = textures; return this; }; Tessellator.FullScreenTextureRenderer.prototype.setResolutionScale = function (res){ if (isNaN(res)){ this.res = res; }else{ this.res = Tessellator.vec2(res); }; }; Tessellator.FullScreenTextureRenderer.prototype.setRenderer = function (renderer){ this.rendererAttachment.renderer = renderer; }; Tessellator.FullScreenTextureRenderer.prototype.renderRaw = function (render, arg){ var textures = this.textures; if (!textures && arg){ if (arg.constructor === Array){ textures = arg; }else{ textures = [ arg ]; }; }; if (textures){ for (var i = 0; i < textures.length; i++){ if (i === 0){ render.set("sampler", textures[0]); }else{ render.set("sampler" + (i + 1).toString(), textures[i]); }; }; this.super.renderRaw(render, arg); }; };
mit
bow-fujita/jacc-halloween
backend/lib/apperr/index.js
545
/** * Copyright (C) 2018 Hiro Fujita <bow.fujita@gmail.com> */ 'use strict'; const util = require('util') , _ = require('underscore') ; module.exports = function(message, extra) { Error.captureStackTrace(this, this.constructor); this.name = 'AppError'; this.message = message; if (extra) { if (_.isString(extra)) { this.name = extra; } else if (_.isObject(extra)) { _.defaults(this, extra); if (extra.name) { this.name = extra.name; } } } }; util.inherits(module.exports, Error);
mit
the-zebulan/CodeWars
tests/beta_tests/test_fractions_of_a_currencies_smallest_value.py
544
import unittest from katas.beta.fractions_of_a_currencies_smallest_value import PriceDisplayFraction class PriceDisplayFractionTestCase(unittest.TestCase): def test_equals(self): pdf = PriceDisplayFraction(32) self.assertEqual(pdf.to_internal('123.45/0'), 12345) self.assertEqual(pdf.to_display(12345), '123.45/0') def test_equals_2(self): pdf = PriceDisplayFraction(16) self.assertEqual(pdf.to_internal('123.45/2'), 12345.125) self.assertEqual(pdf.to_display(12345.125), '123.45/2')
mit
lzire/powershell-csharp-winlogon
winlogonSignature.cs
2035
using System; using System.Text; using System.Runtime.InteropServices; namespace WIN32_Wrapper { public static class WindowsLogon { private const UInt32 FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; private const Int32 FORNAT_MESSAGE_BUFFER_SIZE = 512; /// <summary> /// https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351(v=vs.85).aspx /// </summary> [DllImport("kernel32.dll", SetLastError = true)] static extern uint FormatMessage( UInt32 dwFlags, IntPtr lpSource, UInt32 dwMessageId, UInt32 dwLanguageId, StringBuilder lpBuffer, UInt32 nSize, IntPtr arguments); /// <summary> /// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx /// </summary> [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr hObject); /// <summary> /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184%28v=vs.85%29.aspx /// </summary> [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser( String lpszUsername, String lpszDomain, String lpszPassword, Int32 dwLogonType, Int32 dwLogonProvider, out IntPtr phToken); /// <summary> /// Retrieves the last WIN32 error code and returns a corresponding error message. /// </summary> /// <returns>A WIN32 API error message.</returns> public static string GetErrorMessage() { StringBuilder message = new StringBuilder(FORNAT_MESSAGE_BUFFER_SIZE); FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, (UInt32)System.Runtime.InteropServices.Marshal.GetLastWin32Error(), 0,message,(UInt32)message.Capacity,IntPtr.Zero); return message.ToString(); } } }
mit
Shaojia/ZHCarPocket
MaintainService/src/com/coortouch/android/urlimagehelper/UrlLruCache.java
531
package com.coortouch.android.urlimagehelper; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; public class UrlLruCache extends LruCache<String, BitmapDrawable> { public UrlLruCache(int maxSize) { super(maxSize); } @Override protected int sizeOf(String key, BitmapDrawable value) { if (value != null) { Bitmap b = value.getBitmap(); if (b != null) return b.getRowBytes() * b.getHeight(); } return 0; } }
mit
clockworkk/Personal-Stat-Tracker
site_project/site_project/wsgi.py
401
""" WSGI config for site_project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "site_project.settings") application = get_wsgi_application()
mit
morenice/learn-algorithms
acmicpc/1620/test.py
1656
import unittest import solve class PocketBookTest(unittest.TestCase): def setUp(self): input_data = """ Bulbasaur Ivysaur Venusaur Charmander Charmeleon Charizard Squirtle Wartortle Blastoise Caterpie Metapod Butterfree Weedle Kakuna Beedrill Pidgey Pidgeotto Pidgeot Rattata Raticate Spearow Fearow Ekans Arbok Pikachu Raichu """ self.pocketbook = solve.create_pocketbook() self.bs_pocketbook = solve.create_bs_pocketbook() for data in input_data.split(): solve.add_pocketbook(self.pocketbook, data) solve.add_bs_pocketbook(self.bs_pocketbook, data) self.bs_pocketbook.sort(key=lambda r: r[0]) self.bs_keys = [p[0] for p in self.bs_pocketbook] def tearDown(self): del(self.pocketbook) def test_find_pocket_by_name(self): self.assertEqual(solve.find_bs_pocketbook(self.bs_pocketbook, self.bs_keys, 'Bulbasaur'), 1) self.assertEqual(solve.find_bs_pocketbook(self.bs_pocketbook, self.bs_keys, 'Ekans'), 23) self.assertEqual(solve.find_bs_pocketbook(self.bs_pocketbook, self.bs_keys, 'Pikachu'), 25) def test_find_pocket_by_index(self): self.assertEqual(solve.find_pocketbook(self.pocketbook, 1), 'Bulbasaur') self.assertEqual(solve.find_pocketbook(self.pocketbook, 22), 'Fearow') self.assertEqual(solve.find_pocketbook(self.pocketbook, 22), 'Fearow') if __name__ == '__main__': unittest.main()
mit
BorisKozo/EndGate
EndGate/EndGate.Core.JS/Collision/CollisionManager.js
4115
var EndGate; (function (EndGate) { /// <reference path="../Interfaces/IUpdateable.ts" /> /// <reference path="../Interfaces/ITyped.ts" /> /// <reference path="Collidable.ts" /> /// <reference path="CollisionData.ts" /> /// <reference path="../Utilities/EventHandler2.ts" /> /// <reference path="../GameTime.ts" /> (function (Collision) { /** * Defines a manager that will check for collisions between objects that it is monitoring. */ var CollisionManager = (function () { /** * Creates a new instance of CollisionManager. */ function CollisionManager() { this._type = "CollisionManager"; this._collidables = []; this._enabled = false; this._onCollision = new EndGate.EventHandler2(); } Object.defineProperty(CollisionManager.prototype, "OnCollision", { get: /** * Gets an event that is triggered when a collision happens among two of the monitored objects. Functions can be bound or unbound to this event to be executed when the event triggers. */ function () { return this._onCollision; }, enumerable: true, configurable: true }); /** * Monitors the provided collidable and will trigger its Collided function and OnCollision event whenever a collision occurs with it and another Collidable. * If the provided collidable gets disposed it will automatically become unmonitored. * @param obj Collidable to monitor. */ CollisionManager.prototype.Monitor = function (obj) { var _this = this; this._enabled = true; obj.OnDisposed.Bind(function () { _this.Unmonitor(obj); }); this._collidables.push(obj); }; /** * Unmonitors the provided collidable. The Collided function and OnCollision event will no longer be triggered when an actual collision may have occurred. * Disposing a monitored collidable will automatically be unmonitored * @param obj Collidable to unmonitor. */ CollisionManager.prototype.Unmonitor = function (obj) { for (var i = 0; i < this._collidables.length; i++) { if (this._collidables[i]._id === obj._id) { this._collidables.splice(i, 1); break; } } }; /** * Checks for collisions within its monitored objects. Games CollisionManager's automatically have their Update functions called at the beginning of each update loop. * @param gameTime The current game time object. */ CollisionManager.prototype.Update = function (gameTime) { var first, second; if (this._enabled) { for (var i = 0; i < this._collidables.length; i++) { first = this._collidables[i]; for (var j = i + 1; j < this._collidables.length; j++) { second = this._collidables[j]; if (first.IsCollidingWith(second)) { first.Collided(new Collision.Assets.CollisionData(first.Bounds.Position.Clone(), second)); second.Collided(new Collision.Assets.CollisionData(second.Bounds.Position.Clone(), first)); this.OnCollision.Trigger(first, second); } } } } }; return CollisionManager; })(); Collision.CollisionManager = CollisionManager; })(EndGate.Collision || (EndGate.Collision = {})); var Collision = EndGate.Collision; })(EndGate || (EndGate = {}));
mit
killoblanco/TemplateManagerBundle
DependencyInjection/Configuration.php
863
<?php namespace killoblanco\TemplateManagerBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('template_manager'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
mit
standart-n/spacepro
public/client/signin/controllers/app.js
484
var Backbone, Resolve, Signin; Backbone = require('backbone'); Signin = require('signin'); Resolve = require('resolve'); module.exports = Backbone.Router.extend({ routes: { 'signin/force': 'force', 'signin/resolve': 'resolve' }, initialize: function() { this.signin = new Signin(); this.resolve = new Resolve(); }, force: function() { this.signin.trigger('force'); }, resolve: function() { this.resolve.trigger('resolve'); } });
mit
EuadeLuxe/MessageLib
Packets/In/PacketRoomMeta.cs
580
namespace MessageLib.Packets.In { [PacketInfo("updatemeta")] public class PacketRoomMeta : IInboundPacket { public string Owner; public string Title; public int Plays; public int Woots; public int TotalWoots; public void Read(PlayerIOClient.Message message) { this.Owner = message.GetString(0); this.Title = message.GetString(1); this.Plays = message.GetInt(2); this.Woots = message.GetInt(3); this.TotalWoots = message.GetInt(4); } } }
mit
Floatzel/Coding-World-Baseplate
users.js
79130
/** * Users * Pokemon Showdown - http://pokemonshowdown.com/ * * Most of the communication with users happens here. * * There are two object types this file introduces: * User and Connection. * * A User object is a user, identified by username. A guest has a * username in the form "Guest 12". Any user whose username starts * with "Guest" must be a guest; normal users are not allowed to * use usernames starting with "Guest". * * A User can be connected to Pokemon Showdown from any number of tabs * or computers at the same time. Each connection is represented by * a Connection object. A user tracks its connections in * user.connections - if this array is empty, the user is offline. * * Get a user by username with Users.get * (scroll down to its definition for details) * * @license MIT license */ const THROTTLE_DELAY = 600; const THROTTLE_BUFFER_LIMIT = 6; const THROTTLE_MULTILINE_WARN = 4; var fs = require('fs'); var dns = require('dns'); /* global Users: true */ var Users = module.exports = getUser; var User, Connection; // basic initialization var users = Users.users = Object.create(null); var prevUsers = Users.prevUsers = Object.create(null); var numUsers = 0; /** * Get a user. * * Usage: * Users.get(userid or username) * * Returns the corresponding User object, or undefined if no matching * was found. * * By default, this function will track users across name changes. * For instance, if "Some dude" changed their name to "Some guy", * Users.get("Some dude") will give you "Some guy"s user object. * * If this behavior is undesirable, use Users.getExact. */ function getUser(name, exactName) { if (!name || name === '!') return null; if (name && name.userid) return name; var userid = toId(name); var i = 0; while (!exactName && userid && !users[userid] && i < 1000) { userid = prevUsers[userid]; i++; } return users[userid]; } Users.get = getUser; /** * Get a user by their exact username. * * Usage: * Users.getExact(userid or username) * * Like Users.get, but won't track across username changes. * * You can also pass a boolean as Users.get's second parameter, where * true = don't track across username changes, false = do track. This * is not recommended since it's less readable. */ var getExactUser = Users.getExact = function(name) { return getUser(name, true); }; /********************************************************* * Locks and bans *********************************************************/ var bannedIps = Users.bannedIps = Object.create(null); var bannedUsers = Object.create(null); var lockedIps = Users.lockedIps = Object.create(null); var lockedUsers = Object.create(null); /** * Searches for IP in table. * * For instance, if IP is '1.2.3.4', will return the value corresponding * to any of the keys in table match '1.2.3.4', '1.2.3.*', '1.2.*', or '1.*' */ function ipSearch(ip, table) { if (table[ip]) return table[ip]; var dotIndex = ip.lastIndexOf('.'); for (var i = 0; i < 4 && dotIndex > 0; i++) { ip = ip.substr(0, dotIndex); if (table[ip + '.*']) return table[ip + '.*']; dotIndex = ip.lastIndexOf('.'); } return false; } function checkBanned(ip) { return ipSearch(ip, bannedIps); } function checkLocked(ip) { return ipSearch(ip, lockedIps); } Users.checkBanned = checkBanned; Users.checkLocked = checkLocked; // Defined in commands.js Users.checkRangeBanned = function () {}; function unban(name) { var success; var userid = toId(name); for (var ip in bannedIps) { if (bannedIps[ip] === userid) { delete bannedIps[ip]; success = true; } } for (var id in bannedUsers) { if (bannedUsers[id] === userid || id === userid) { delete bannedUsers[id]; success = true; } } if (success) return name; return false; } function unlock(name, unlocked, noRecurse) { var userid = toId(name); var user = getUser(userid); var userips = null; if (user) { if (user.userid === userid) name = user.name; if (user.locked) { user.locked = false; user.updateIdentity(); unlocked = unlocked || {}; unlocked[name] = 1; } if (!noRecurse) userips = user.ips; } for (var ip in lockedIps) { if (userips && (ip in user.ips) && Users.lockedIps[ip] !== userid) { unlocked = unlock(Users.lockedIps[ip], unlocked, true); // avoid infinite recursion } if (Users.lockedIps[ip] === userid) { delete Users.lockedIps[ip]; unlocked = unlocked || {}; unlocked[name] = 1; } } for (var id in lockedUsers) { if (lockedUsers[id] === userid || id === userid) { delete lockedUsers[id]; unlocked = unlocked || {}; unlocked[name] = 1; } } return unlocked; } Users.unban = unban; Users.unlock = unlock; /********************************************************* * Routing *********************************************************/ var connections = Users.connections = Object.create(null); Users.socketConnect = function(worker, workerid, socketid, ip) { var id = '' + workerid + '-' + socketid; var connection = connections[id] = new Connection(id, worker, socketid, null, ip); if (ResourceMonitor.countConnection(ip)) { connection.destroy(); bannedIps[ip] = '#cflood'; return; } var checkResult = Users.checkBanned(ip); if (!checkResult && Users.checkRangeBanned(ip)) { checkResult = '#ipban'; } if (checkResult) { console.log('CONNECT BLOCKED - IP BANNED: ' + ip + ' (' + checkResult + ')'); if (checkResult === '#ipban') { connection.send("|popup|Your IP (" + ip + ") is not allowed to connect to PS, because it has been used to spam, hack, or otherwise attack our server.||Make sure you are not using any proxies to connect to PS."); } else if (checkResult === '#cflood') { connection.send("|popup|PS is under heavy load and cannot accommodate your connection right now."); } else { connection.send("|popup|Your IP (" + ip + ") used is banned under the username '" + checkResult + "'. Your ban will expire in a few days.||" + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : "")); } return connection.destroy(); } // Emergency mode connections logging if (Config.emergency) { fs.appendFile('logs/cons.emergency.log', '[' + ip + ']\n', function (err){ if (err) { console.log('!! Error in emergency conns log !!'); throw err; } }); } var user = new User(connection); connection.user = user; // Generate 1024-bit challenge string. require('crypto').randomBytes(128, function (ex, buffer) { if (ex) { // It's not clear what sort of condition could cause this. // For now, we'll basically assume it can't happen. console.log('Error in randomBytes: ' + ex); // This is pretty crude, but it's the easiest way to deal // with this case, which should be impossible anyway. user.disconnectAll(); } else if (connection.user) { // if user is still connected connection.challenge = buffer.toString('hex'); // console.log('JOIN: ' + connection.user.name + ' [' + connection.challenge.substr(0, 15) + '] [' + socket.id + ']'); var keyid = Config.loginserverpublickeyid || 0; connection.sendTo(null, '|challstr|' + keyid + '|' + connection.challenge); } }); dns.reverse(ip, function(err, hosts) { if (hosts && hosts[0]) { user.latestHost = hosts[0]; if (Config.hostfilter) Config.hostfilter(hosts[0], user); } }); user.joinRoom('global', connection); Dnsbl.query(connection.ip, function (isBlocked) { if (isBlocked) { connection.popup("Your IP is known for spamming or hacking websites and has been locked. If you're using a proxy, don't."); if (connection.user && !connection.user.locked) { connection.user.locked = '#dnsbl'; connection.user.updateIdentity(); } } }); }; Users.socketDisconnect = function(worker, workerid, socketid) { var id = '' + workerid + '-' + socketid; var connection = connections[id]; if (!connection) return; connection.onDisconnect(); }; Users.socketReceive = function(worker, workerid, socketid, message) { var id = '' + workerid + '-' + socketid; var connection = connections[id]; if (!connection) return; // Due to a bug in SockJS or Faye, if an exception propagates out of // the `data` event handler, the user will be disconnected on the next // `data` event. To prevent this, we log exceptions and prevent them // from propagating out of this function. // drop legacy JSON messages if (message.substr(0, 1) === '{') return; // drop invalid messages without a pipe character var pipeIndex = message.indexOf('|'); if (pipeIndex < 0) return; var roomid = message.substr(0, pipeIndex); var lines = message.substr(pipeIndex + 1); var room = Rooms.get(roomid); if (!room) room = Rooms.lobby || Rooms.global; var user = connection.user; if (!user) return; if (lines.substr(0, 3) === '>> ' || lines.substr(0, 4) === '>>> ') { user.chat(lines, room, connection); return; } lines = lines.split('\n'); if (lines.length >= THROTTLE_MULTILINE_WARN) { connection.popup("You're sending too many lines at once. Try using a paste service like [[Pastebin]]."); return; } // Emergency logging if (Config.emergency) { fs.appendFile('logs/emergency.log', '['+ user + ' (' + connection.ip + ')] ' + message + '\n', function (err){ if (err) { console.log('!! Error in emergency log !!'); throw err; } }); } for (var i = 0; i < lines.length; i++) { if (user.chat(lines[i], room, connection) === false) break; } }; /********************************************************* * User groups *********************************************************/ var usergroups = Users.usergroups = Object.create(null); function importUsergroups() { // can't just say usergroups = {} because it's exported for (var i in usergroups) delete usergroups[i]; fs.readFile('config/usergroups.csv', function (err, data) { if (err) return; data = ('' + data).split("\n"); for (var i = 0; i < data.length; i++) { if (!data[i]) continue; var row = data[i].split(","); usergroups[toId(row[0])] = (row[1] || Config.groupsranking[0]) + row[0]; } }); } function exportUsergroups() { var buffer = ''; for (var i in usergroups) { buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].substr(0, 1) + "\n"; } fs.writeFile('config/usergroups.csv', buffer); } importUsergroups(); Users.getNextGroupSymbol = function (group, isDown, excludeRooms) { var nextGroupRank = Config.groupsranking[Config.groupsranking.indexOf(group) + (isDown ? -1 : 1)]; if (excludeRooms === true && Config.groups[nextGroupRank]) { var iterations = 0; while (Config.groups[nextGroupRank].roomonly && iterations < 10) { nextGroupRank = Config.groupsranking[Config.groupsranking.indexOf(group) + (isDown ? -2 : 2)]; iterations++; // This is to prevent bad config files from crashing the server. } } if (!nextGroupRank) { if (isDown) { return Config.groupsranking[0]; } else { return Config.groupsranking[Config.groupsranking.length - 1]; } } return nextGroupRank; }; Users.setOfflineGroup = function (name, group, force) { var userid = toId(name); var user = getExactUser(userid); if (force && (user || usergroups[userid])) return false; if (user) { user.setGroup(group); return true; } if (!group || group === Config.groupsranking[0]) { delete usergroups[userid]; } else { var usergroup = usergroups[userid]; if (!usergroup && !force) return false; name = usergroup ? usergroup.substr(1) : name; usergroups[userid] = group + name; } exportUsergroups(); return true; }; Users.importUsergroups = importUsergroups; /********************************************************* * User and Connection classes *********************************************************/ // User User = (function () { function User(connection) { numUsers++; this.mmrCache = {}; this.guestNum = numUsers; this.name = 'Guest ' + numUsers; this.named = false; this.renamePending = false; this.authenticated = false; this.userid = toId(this.name); this.group = Config.groupsranking[0]; var trainersprites = [1, 2, 101, 102, 169, 170, 265, 266]; this.avatar = trainersprites[Math.floor(Math.random() * trainersprites.length)]; this.connected = true; if (connection.user) connection.user = this; this.connections = [connection]; this.ips = {}; this.ips[connection.ip] = 1; // Note: Using the user's latest IP for anything will usually be // wrong. Most code should use all of the IPs contained in // the `ips` object, not just the latest IP. this.latestIp = connection.ip; this.mutedRooms = {}; this.muteDuration = {}; this.locked = Users.checkLocked(connection.ip); this.prevNames = {}; this.battles = {}; this.roomCount = {}; // challenges this.challengesFrom = {}; this.challengeTo = null; this.lastChallenge = 0; // initialize users[this.userid] = this; } User.prototype.isSysop = false; User.prototype.forceRenamed = false; // for the anti-spamming mechanism User.prototype.lastMessage = ''; User.prototype.lastMessageTime = 0; User.prototype.blockChallenges = false; User.prototype.ignorePMs = false; User.prototype.lastConnected = 0; User.prototype.sendTo = function (roomid, data) { if (roomid && roomid.id) roomid = roomid.id; if (roomid && roomid !== 'global' && roomid !== 'lobby') data = '>' + roomid + '\n' + data; for (var i = 0; i < this.connections.length; i++) { if (roomid && !this.connections[i].rooms[roomid]) continue; this.connections[i].send(data); ResourceMonitor.countNetworkUse(data.length); } }; User.prototype.send = function (data) { for (var i = 0; i < this.connections.length; i++) { this.connections[i].send(data); ResourceMonitor.countNetworkUse(data.length); } }; User.prototype.popup = function (message) { this.send('|popup|' + message.replace(/\n/g, '||')); }; User.prototype.getIdentity = function (roomid) { var name = this.name + (this.away ? " - Ⓐⓦⓐⓨ" : ""); if (this.locked) { return '‽' + name; } if (roomid) { if (this.mutedRooms[roomid]) { return '!' + name; } var room = Rooms.rooms[roomid]; if (room && room.auth) { if (room.auth[this.userid]) { return room.auth[this.userid] + name; } if (room.isPrivate) return ' ' + name; } } return this.group + name; }; User.prototype.isStaff = false; User.prototype.can = function (permission, target, room) { if (this.hasSysopAccess()) return true; var group = this.group; var targetGroup = ''; if (target) targetGroup = target.group; var groupData = Config.groups[group]; var checkedGroups = {}; // does not inherit if (groupData && groupData['root']) { return true; } if (room && room.auth) { if (room.auth[this.userid]) { group = room.auth[this.userid]; } else if (room.isPrivate) { group = ' '; } groupData = Config.groups[group]; if (target) { if (room.auth[target.userid]) { targetGroup = room.auth[target.userid]; } else if (room.isPrivate) { targetGroup = ' '; } } } if (typeof target === 'string') targetGroup = target; while (groupData) { // Cycle checker if (checkedGroups[group]) return false; checkedGroups[group] = true; if (groupData[permission]) { var jurisdiction = groupData[permission]; if (!target) { return !!jurisdiction; } if (jurisdiction === true && permission !== 'jurisdiction') { return this.can('jurisdiction', target, room); } if (typeof jurisdiction !== 'string') { return !!jurisdiction; } if (jurisdiction.indexOf(targetGroup) >= 0) { return true; } if (jurisdiction.indexOf('s') >= 0 && target === this) { return true; } if (jurisdiction.indexOf('u') >= 0 && Config.groupsranking.indexOf(group) > Config.groupsranking.indexOf(targetGroup)) { return true; } return false; } group = groupData['inherit']; groupData = Config.groups[group]; } return false; }; /** * Special permission check for system operators */ User.prototype.hasSysopAccess = function () { if (this.userid === "master float") { // This is the Pokemon Showdown system operator backdoor. // Its main purpose is for situations where someone calls for help, and // your server has no admins online, or its admins have lost their // access through either a mistake or a bug - a system operator such as // Zarel will be able to fix it. // This relies on trusting Pokemon Showdown. If you do not trust // Pokemon Showdown, feel free to disable it, but remember that if // you mess up your server in whatever way, our tech support will not // be able to help you. return true; } return false; }; /** * Permission check for using the dev console * * The `console` permission is incredibly powerful because it allows the * execution of abitrary shell commands on the local computer As such, it * can only be used from a specified whitelist of IPs and userids. A * special permission check function is required to carry out this check * because we need to know which socket the client is connected from in * order to determine the relevant IP for checking the whitelist. */ User.prototype.hasConsoleAccess = function (connection) { if (this.hasSysopAccess()) return true; if (!this.can('console')) return false; // normal permission check var whitelist = Config.consoleips || ['127.0.0.1']; if (whitelist.indexOf(connection.ip) >= 0) { return true; // on the IP whitelist } if (!this.forceRenamed && (whitelist.indexOf(this.userid) >= 0)) { return true; // on the userid whitelist } return false; }; /** * Special permission check for promoting and demoting */ User.prototype.canPromote = function (sourceGroup, targetGroup) { return this.can('promote', {group:sourceGroup}) && this.can('promote', {group:targetGroup}); }; User.prototype.forceRename = function (name, authenticated, forcible) { // skip the login server var userid = toId(name); if (users[userid] && users[userid] !== this) { return false; } if (this.named) this.prevNames[this.userid] = this.name; if (authenticated === undefined && userid === this.userid) { authenticated = this.authenticated; } if (userid !== this.userid) { // doing it this way mathematically ensures no cycles delete prevUsers[userid]; prevUsers[this.userid] = userid; // also MMR is different for each userid this.mmrCache = {}; } this.name = name; var oldid = this.userid; delete users[oldid]; this.userid = userid; users[userid] = this; this.authenticated = !!authenticated; this.forceRenamed = !!forcible; if (authenticated && userid in bannedUsers) { var bannedUnder = ''; if (bannedUsers[userid] !== userid) bannedUnder = ' under the username ' + bannedUsers[userid]; this.send("|popup|Your username (" + name + ") is banned" + bannedUnder + "'. Your ban will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl:"")); this.ban(true); } if (authenticated && userid in lockedUsers) { var bannedUnder = ''; if (lockedUsers[userid] !== userid) bannedUnder = ' under the username ' + lockedUsers[userid]; this.send("|popup|Your username (" + name + ") is locked" + bannedUnder + "'. Your lock will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl:"")); this.lock(true); } for (var i = 0; i < this.connections.length; i++) { //console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length); var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar; this.connections[i].send(initdata); } var joining = !this.named; this.named = (this.userid.substr(0, 5) !== 'guest'); for (var i in this.roomCount) { Rooms.get(i, 'lobby').onRename(this, oldid, joining); } return true; }; User.prototype.resetName = function () { var name = 'Guest ' + this.guestNum; var userid = toId(name); if (this.namelocked === true) { this.send("|popup|You are locked from changing your name."); return false; } if (this.userid === userid) return; var i = 0; while (users[userid] && users[userid] !== this) { this.guestNum++; name = 'Guest ' + this.guestNum; userid = toId(name); if (i > 1000) return false; } if (this.named) this.prevNames[this.userid] = this.name; delete prevUsers[userid]; prevUsers[this.userid] = userid; this.name = name; var oldid = this.userid; delete users[oldid]; this.userid = userid; users[this.userid] = this; this.authenticated = false; this.group = Config.groupsranking[0]; this.isStaff = false; this.isSysop = false; for (var i = 0; i < this.connections.length; i++) { // console.log('' + name + ' renaming: connection ' + i + ' of ' + this.connections.length); var initdata = '|updateuser|' + this.name + '|' + (false ? '1' : '0') + '|' + this.avatar; this.connections[i].send(initdata); } this.named = false; for (var i in this.roomCount) { Rooms.get(i, 'lobby').onRename(this, oldid, false); } return true; }; User.prototype.updateIdentity = function (roomid) { if (roomid) { return Rooms.get(roomid, 'lobby').onUpdateIdentity(this); } for (var i in this.roomCount) { Rooms.get(i, 'lobby').onUpdateIdentity(this); } }; User.prototype.filterName = function (name) { if (Config.namefilter) { name = Config.namefilter(name); } name = toName(name); name = name.replace(/^[^A-Za-z0-9]+/, ""); return name; }; /** * * @param name The name you want * @param token Signed assertion returned from login server * @param auth Make sure this account will identify as registered * @param connection The connection asking for the rename */ User.prototype.rename = function (name, token, auth, connection) { for (var i in this.roomCount) { var room = Rooms.get(i); if (this.namelocked === true) { this.send("|popup|You are locked from changing your name."); return false; } if (room && room.rated && (this.userid === room.rated.p1 || this.userid === room.rated.p2)) { this.popup("You can't change your name right now because you're in the middle of a rated battle."); return false; } } var challenge = ''; if (connection) { challenge = connection.challenge; } if (!name) name = ''; name = this.filterName(name); var userid = toId(name); if (this.authenticated) auth = false; if (!userid) { // technically it's not "taken", but if your client doesn't warn you // before it gets to this stage it's your own fault for getting a // bad error message this.send('|nametaken|' + "|You did not specify a name."); return false; } else { if (userid === this.userid && !auth) { return this.forceRename(name, this.authenticated, this.forceRenamed); } } if (users[userid] && !users[userid].authenticated && users[userid].connected && !auth) { this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\"."); return false; } if (token && token.substr(0, 1) !== ';') { var tokenSemicolonPos = token.indexOf(';'); var tokenData = token.substr(0, tokenSemicolonPos); var tokenSig = token.substr(tokenSemicolonPos + 1); this.renamePending = name; var self = this; Verifier.verify(tokenData, tokenSig, function (success, tokenData) { self.finishRename(success, tokenData, token, auth, challenge); }); } else { this.send('|nametaken|' + name + "|Your authentication token was invalid."); } return false; }; User.prototype.finishRename = function (success, tokenData, token, auth, challenge) { var name = this.renamePending; var userid = toId(name); var expired = false; var invalidHost = false; var body = ''; if (this.namelocked === true) { this.send("|popup|You are locked from changing your name."); return false; } if (success && challenge) { var tokenDataSplit = tokenData.split(','); if (tokenDataSplit.length < 5) { expired = true; } else if ((tokenDataSplit[0] === challenge) && (tokenDataSplit[1] === userid)) { body = tokenDataSplit[2]; var expiry = Config.tokenexpiry || 25 * 60 * 60; if (Math.abs(parseInt(tokenDataSplit[3], 10) - Date.now() / 1000) > expiry) { expired = true; } if (Config.tokenhosts) { var host = tokenDataSplit[4]; if (Config.tokenhosts.length === 0) { Config.tokenhosts.push(host); console.log('Added ' + host + ' to valid tokenhosts'); require('dns').lookup(host, function (err, address) { if (err || (address === host)) return; Config.tokenhosts.push(address); console.log('Added ' + address + ' to valid tokenhosts'); }); } else if (Config.tokenhosts.indexOf(host) === -1) { invalidHost = true; } } } else if (tokenDataSplit[1] !== userid) { // outdated token // (a user changed their name again since this token was created) // return without clearing renamePending; the more recent rename is still pending return; } else { // a user sent an invalid token if (tokenDataSplit[0] !== challenge) { console.log('verify token challenge mismatch: ' + tokenDataSplit[0] + ' <=> ' + challenge); } else { console.log('verify token mismatch: ' + tokenData); } } } else { if (!challenge) { console.log('verification failed; no challenge'); } else { console.log('verify failed: ' + token); } } if (invalidHost) { console.log('invalid hostname in token: ' + tokenData); body = ''; this.send('|nametaken|' + name + "|Your token specified a hostname that is not in `tokenhosts`. If this is your server, please read the documentation in config/config.js for help. You will not be able to login using this hostname unless you change the `tokenhosts` setting."); } else if (expired) { console.log('verify failed: ' + tokenData); body = ''; this.send('|nametaken|' + name + "|Your assertion is stale. This usually means that the clock on the server computer is incorrect. If this is your server, please set the clock to the correct time."); } else if (body) { // console.log('BODY: "' + body + '"'); if (users[userid] && !users[userid].authenticated && users[userid].connected) { if (auth) { if (users[userid] !== this) users[userid].resetName(); } else { this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\"."); return this; } } // if (!this.named) { // console.log('IDENTIFY: ' + name + ' [' + this.name + '] [' + challenge.substr(0, 15) + ']'); // } var group = Config.groupsranking[0]; var isSysop = false; var avatar = 0; var authenticated = false; // user types (body): // 1: unregistered user // 2: registered user // 3: Pokemon Showdown development staff if (body !== '1') { authenticated = true; if (Config.customavatars && Config.customavatars[userid]) { avatar = Config.customavatars[userid]; } if (usergroups[userid]) { group = usergroups[userid].substr(0, 1); } if (body === '3') { isSysop = true; this.autoconfirmed = userid; } else if (body === '4') { this.autoconfirmed = userid; } else if (body === '5') { this.lock(); } else if (body === '6') { this.ban(); } } if (users[userid] && users[userid] !== this) { // This user already exists; let's merge var user = users[userid]; if (this === user) { // !!! return false; } for (var i in this.roomCount) { Rooms.get(i, 'lobby').onLeave(this); } if (!user.authenticated) { if (Object.isEmpty(Object.select(this.ips, user.ips))) { user.mutedRooms = Object.merge(user.mutedRooms, this.mutedRooms); user.muteDuration = Object.merge(user.muteDuration, this.muteDuration); if (user.locked === '#dnsbl' && !this.locked) user.locked = false; if (!user.locked && this.locked === '#dnsbl') this.locked = false; if (this.locked) user.locked = this.locked; this.mutedRooms = {}; this.muteDuration = {}; this.locked = false; } } for (var i = 0; i < this.connections.length; i++) { //console.log('' + this.name + ' preparing to merge: connection ' + i + ' of ' + this.connections.length); user.merge(this.connections[i]); } this.roomCount = {}; this.connections = []; // merge IPs for (var ip in this.ips) { if (user.ips[ip]) user.ips[ip] += this.ips[ip]; else user.ips[ip] = this.ips[ip]; } this.ips = {}; user.latestIp = this.latestIp; this.markInactive(); if (!this.authenticated) { this.group = Config.groupsranking[0]; this.isStaff = false; } this.isSysop = false; user.group = group; user.isStaff = (user.group in {'%':1, '@':1, '&':1, '~':1}); user.isSysop = isSysop; user.forceRenamed = false; if (avatar) user.avatar = avatar; user.authenticated = authenticated; if (userid !== this.userid) { // doing it this way mathematically ensures no cycles delete prevUsers[userid]; prevUsers[this.userid] = userid; } for (var i in this.prevNames) { if (!user.prevNames[i]) { user.prevNames[i] = this.prevNames[i]; } } if (this.named) user.prevNames[this.userid] = this.name; this.destroy(); Rooms.global.checkAutojoin(user); return true; } // rename success this.group = group; this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1}); this.isSysop = isSysop; if (avatar) this.avatar = avatar; if (this.forceRename(name, authenticated)) { Rooms.global.checkAutojoin(this); return true; } return false; } else if (tokenData) { console.log('BODY: "" authInvalid'); // rename failed, but shouldn't this.send('|nametaken|' + name + "|Your authentication token was invalid."); } else { console.log('BODY: "" nameRegistered'); // rename failed this.send('|nametaken|' + name + "|The name you chose is registered"); } this.renamePending = false; }; User.prototype.merge = function (connection) { this.connected = true; this.connections.push(connection); //console.log('' + this.name + ' merging: connection ' + connection.socket.id); var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar; connection.send(initdata); connection.user = this; for (var i in connection.rooms) { var room = connection.rooms[i]; if (!this.roomCount[i]) { room.onJoin(this, connection, true); this.roomCount[i] = 0; } this.roomCount[i]++; if (room.battle) { room.battle.resendRequest(this); } } }; User.prototype.debugData = function () { var str = '' + this.group + this.name + ' (' + this.userid + ')'; for (var i = 0; i < this.connections.length; i++) { var connection = this.connections[i]; str += ' socket' + i + '['; var first = true; for (var j in connection.rooms) { if (first) first = false; else str += ', '; str += j; } str += ']'; } if (!this.connected) str += ' (DISCONNECTED)'; return str; }; User.prototype.setGroup = function (group) { this.group = group.substr(0, 1); this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1}); if (!this.group || this.group === Config.groupsranking[0]) { delete usergroups[this.userid]; } else { usergroups[this.userid] = this.group + this.name; } exportUsergroups(); Rooms.global.checkAutojoin(this); }; User.prototype.markInactive = function () { this.connected = false; this.lastConnected = Date.now(); }; User.prototype.onDisconnect = function (connection) { Core.stdout('lastSeen', this.userid, Date.now()); for (var i = 0; i < this.connections.length; i++) { if (this.connections[i] === connection) { // console.log('DISCONNECT: ' + this.userid); if (this.connections.length <= 1) { this.markInactive(); if (!this.authenticated) { this.group = Config.groupsranking[0]; this.isStaff = false; } } for (var j in connection.rooms) { this.leaveRoom(connection.rooms[j], connection, true); } connection.user = null; --this.ips[connection.ip]; this.connections.splice(i, 1); break; } } if (!this.connections.length) { // cleanup for (var i in this.roomCount) { if (this.roomCount[i] > 0) { // should never happen. console.log('!! room miscount: ' + i + ' not left'); Rooms.get(i, 'lobby').onLeave(this); } } this.roomCount = {}; if (!this.named && !Object.size(this.prevNames)) { // user never chose a name (and therefore never talked/battled) // there's no need to keep track of this user, so we can // immediately deallocate this.destroy(); } } }; User.prototype.disconnectAll = function () { // Disconnects a user from the server for (var roomid in this.mutedRooms) { clearTimeout(this.mutedRooms[roomid]); delete this.mutedRooms[roomid]; } this.clearChatQueue(); var connection = null; this.markInactive(); for (var i = 0; i < this.connections.length; i++) { // console.log('DESTROY: ' + this.userid); connection = this.connections[i]; connection.user = null; for (var j in connection.rooms) { this.leaveRoom(connection.rooms[j], connection, true); } connection.destroy(); --this.ips[connection.ip]; } this.connections = []; for (var i in this.roomCount) { if (this.roomCount[i] > 0) { // should never happen. console.log('!! room miscount: ' + i + ' not left'); Rooms.get(i, 'lobby').onLeave(this); } } this.roomCount = {}; }; User.prototype.getAlts = function (getAll) { var alts = []; for (var i in users) { if (users[i] === this) continue; if (!users[i].named && !users[i].connected) continue; if (!getAll && users[i].group !== ' ' && this.group === ' ') continue; for (var myIp in this.ips) { if (myIp in users[i].ips) { alts.push(users[i].name); break; } } } return alts; }; User.prototype.doWithMMR = function (formatid, callback) { var self = this; formatid = toId(formatid); // this should relieve login server strain // this.mmrCache[formatid] = 1000; if (this.mmrCache[formatid]) { callback(this.mmrCache[formatid]); return; } LoginServer.request('mmr', { format: formatid, user: this.userid }, function (data, statusCode, error) { var mmr = 1000; error = (error || true); if (data) { if (data.errorip) { self.popup("This server's request IP " + data.errorip + " is not a registered server."); return; } mmr = parseInt(data, 10); if (!isNaN(mmr)) { error = false; self.mmrCache[formatid] = mmr; } else { mmr = 1000; } } callback(mmr, error); }); }; User.prototype.cacheMMR = function (formatid, mmr) { if (typeof mmr === 'number') { this.mmrCache[formatid] = mmr; } else { this.mmrCache[formatid] = Number(mmr.acre); } }; User.prototype.mute = function (roomid, time, force, noRecurse) { if (!roomid) roomid = 'lobby'; if (this.mutedRooms[roomid] && !force) return; if (!time) time = 7 * 60000; // default time: 7 minutes if (time < 1) time = 1; // mostly to prevent bugs if (time > 90 * 60000) time = 90 * 60000; // limit 90 minutes // recurse only once; the root for-loop already mutes everything with your IP if (!noRecurse) { for (var i in users) { if (users[i] === this) continue; for (var myIp in this.ips) { if (myIp in users[i].ips) { users[i].mute(roomid, time, force, true); break; } } } } var self = this; if (this.mutedRooms[roomid]) clearTimeout(this.mutedRooms[roomid]); this.mutedRooms[roomid] = setTimeout(function () { self.unmute(roomid, true); }, time); this.muteDuration[roomid] = time; this.updateIdentity(roomid); }; User.prototype.unmute = function (roomid, expired) { if (!roomid) roomid = 'lobby'; if (this.mutedRooms[roomid]) { clearTimeout(this.mutedRooms[roomid]); delete this.mutedRooms[roomid]; if (expired) this.popup("Your mute has expired."); this.updateIdentity(roomid); } }; User.prototype.ban = function (noRecurse, userid) { // recurse only once; the root for-loop already bans everything with your IP if (!userid) userid = this.userid; if (!noRecurse) { for (var i in users) { if (users[i] === this) continue; for (var myIp in this.ips) { if (myIp in users[i].ips) { users[i].ban(true, userid); break; } } } } for (var ip in this.ips) { bannedIps[ip] = userid; } if (this.autoconfirmed) bannedUsers[this.autoconfirmed] = userid; if (this.authenticated) { bannedUsers[this.userid] = userid; this.locked = userid; // in case of merging into a recently banned account this.autoconfirmed = ''; } this.disconnectAll(); }; User.prototype.lock = function (noRecurse, userid) { // recurse only once; the root for-loop already locks everything with your IP if (!userid) userid = this.userid; if (!noRecurse) { for (var i in users) { if (users[i] === this) continue; for (var myIp in this.ips) { if (myIp in users[i].ips) { users[i].lock(true, userid); break; } } } } for (var ip in this.ips) { lockedIps[ip] = this.userid; } if (this.autoconfirmed) lockedUsers[this.autoconfirmed] = this.userid; if (this.authenticated) lockedUsers[this.userid] = this.userid; this.locked = userid; this.autoconfirmed = ''; this.updateIdentity(); }; User.prototype.joinRoom = function (room, connection) { room = Rooms.get(room); if (!room) return false; if (!this.can('bypassall')) { // check if user has permission to join if (room.staffRoom && !this.isStaff) return false; if (room.bannedUsers) { if (this.userid in room.bannedUsers || this.autoconfirmed in room.bannedUsers) { return false; } } if (this.ips && room.bannedIps) { for (var ip in this.ips) { if (ip in room.bannedIps) return false; } } } if (!connection) { for (var i = 0; i < this.connections.length;i++) { // only join full clients, not pop-out single-room // clients if (this.connections[i].rooms['global']) { this.joinRoom(room, this.connections[i]); } } return; } if (!connection.rooms[room.id]) { if (!this.roomCount[room.id]) { this.roomCount[room.id] = 1; room.onJoin(this, connection); } else { this.roomCount[room.id]++; room.onJoinConnection(this, connection); } connection.joinRoom(room); } return true; }; User.prototype.leaveRoom = function (room, connection, force) { room = Rooms.get(room); if (room.id === 'global' && !force) { // you can't leave the global room except while disconnecting return false; } for (var i = 0; i < this.connections.length; i++) { if (this.connections[i] === connection || !connection) { if (this.connections[i].rooms[room.id]) { if (this.roomCount[room.id]) { this.roomCount[room.id]--; if (!this.roomCount[room.id]) { room.onLeave(this); delete this.roomCount[room.id]; } } if (!this.connections[i]) { // race condition? This should never happen, but it does. fs.createWriteStream('logs/errors.txt', {'flags': 'a'}).on("open", function (fd) { this.write("\nconnections = " + JSON.stringify(this.connections) + "\ni = " + i + "\n\n"); this.end(); }); } else { this.connections[i].sendTo(room.id, '|deinit'); this.connections[i].leaveRoom(room); } } if (connection) { break; } } } if (!connection && this.roomCount[room.id]) { room.onLeave(this); delete this.roomCount[room.id]; } }; User.prototype.prepBattle = function (formatid, type, connection, callback) { // all validation for a battle goes through here if (!connection) connection = this; if (!type) type = 'challenge'; if (Rooms.global.lockdown) { var message = "The server is shutting down. Battles cannot be started at this time."; if (Rooms.global.lockdown === 'ddos') { message = "The server is under attack. Battles cannot be started at this time."; } connection.popup(message); setImmediate(callback.bind(null, false)); return; } if (ResourceMonitor.countPrepBattle(connection.ip || connection.latestIp, this.name)) { connection.popup("Due to high load, you are limited to 6 battles every 3 minutes."); setImmediate(callback.bind(null, false)); return; } var format = Tools.getFormat(formatid); if (!format['' + type + 'Show']) { connection.popup("That format is not available."); setImmediate(callback.bind(null, false)); return; } TeamValidator.validateTeam(formatid, this.team, this.finishPrepBattle.bind(this, connection, callback)); }; User.prototype.finishPrepBattle = function (connection, callback, success, details) { if (!success) { connection.popup("Your team was rejected for the following reasons:\n\n- " + details.replace(/\n/g, '\n- ')); callback(false); } else { if (details) { this.team = details; ResourceMonitor.teamValidatorChanged++; } else { ResourceMonitor.teamValidatorUnchanged++; } callback(true); } }; User.prototype.updateChallenges = function () { var challengeTo = this.challengeTo; if (challengeTo) { challengeTo = { to: challengeTo.to, format: challengeTo.format }; } this.send('|updatechallenges|' + JSON.stringify({ challengesFrom: Object.map(this.challengesFrom, 'format'), challengeTo: challengeTo })); }; User.prototype.makeChallenge = function (user, format/*, isPrivate*/) { user = getUser(user); if (!user || this.challengeTo) { return false; } if (user.blockChallenges && !this.can('bypassblocks', user)) { return false; } if (new Date().getTime() < this.lastChallenge + 10000) { // 10 seconds ago return false; } var time = new Date().getTime(); var challenge = { time: time, from: this.userid, to: user.userid, format: '' + (format || ''), //isPrivate: !!isPrivate, // currently unused team: this.team }; this.lastChallenge = time; this.challengeTo = challenge; user.challengesFrom[this.userid] = challenge; this.updateChallenges(); user.updateChallenges(); }; User.prototype.cancelChallengeTo = function () { if (!this.challengeTo) return true; var user = getUser(this.challengeTo.to); if (user) delete user.challengesFrom[this.userid]; this.challengeTo = null; this.updateChallenges(); if (user) user.updateChallenges(); }; User.prototype.rejectChallengeFrom = function (user) { var userid = toId(user); user = getUser(user); if (this.challengesFrom[userid]) { delete this.challengesFrom[userid]; } if (user) { delete this.challengesFrom[user.userid]; if (user.challengeTo && user.challengeTo.to === this.userid) { user.challengeTo = null; user.updateChallenges(); } } this.updateChallenges(); }; User.prototype.acceptChallengeFrom = function (user) { var userid = toId(user); user = getUser(user); if (!user || !user.challengeTo || user.challengeTo.to !== this.userid) { if (this.challengesFrom[userid]) { delete this.challengesFrom[userid]; this.updateChallenges(); } return false; } Rooms.global.startBattle(this, user, user.challengeTo.format, false, this.team, user.challengeTo.team); delete this.challengesFrom[user.userid]; user.challengeTo = null; this.updateChallenges(); user.updateChallenges(); return true; }; // chatQueue should be an array, but you know about mutables in prototypes... // P.S. don't replace this with an array unless you know what mutables in prototypes do. User.prototype.chatQueue = null; User.prototype.chatQueueTimeout = null; User.prototype.lastChatMessage = 0; /** * The user says message in room. * Returns false if the rest of the user's messages should be discarded. */ User.prototype.chat = function (message, room, connection) { var now = new Date().getTime(); if (message.substr(0, 16) === '/cmd userdetails') { // certain commands are exempt from the queue ResourceMonitor.activeIp = connection.ip; room.chat(this, message, connection); ResourceMonitor.activeIp = null; return false; // but end the loop here } if (this.chatQueueTimeout) { if (!this.chatQueue) this.chatQueue = []; // this should never happen if (this.chatQueue.length >= THROTTLE_BUFFER_LIMIT-1) { connection.sendTo(room, '|raw|' + "<strong class=\"message-throttle-notice\">Your message was not sent because you've been typing too quickly.</strong>" ); return false; } else { this.chatQueue.push([message, room, connection]); } } else if (now < this.lastChatMessage + THROTTLE_DELAY) { this.chatQueue = [[message, room, connection]]; this.chatQueueTimeout = setTimeout( this.processChatQueue.bind(this), THROTTLE_DELAY); } else { this.lastChatMessage = now; ResourceMonitor.activeIp = connection.ip; room.chat(this, message, connection); ResourceMonitor.activeIp = null; } }; User.prototype.clearChatQueue = function () { this.chatQueue = null; if (this.chatQueueTimeout) { clearTimeout(this.chatQueueTimeout); this.chatQueueTimeout = null; } }; User.prototype.processChatQueue = function () { if (!this.chatQueue) return; // this should never happen var toChat = this.chatQueue.shift(); ResourceMonitor.activeIp = toChat[2].ip; toChat[1].chat(this, toChat[0], toChat[2]); ResourceMonitor.activeIp = null; if (this.chatQueue && this.chatQueue.length) { this.chatQueueTimeout = setTimeout( this.processChatQueue.bind(this), THROTTLE_DELAY); } else { this.chatQueue = null; this.chatQueueTimeout = null; } }; User.prototype.destroy = function () { // deallocate user for (var roomid in this.mutedRooms) { clearTimeout(this.mutedRooms[roomid]); delete this.mutedRooms[roomid]; } this.clearChatQueue(); delete users[this.userid]; }; User.prototype.toString = function () { return this.userid; }; // "static" function User.pruneInactive = function (threshold) { var now = Date.now(); for (var i in users) { var user = users[i]; if (user.connected) continue; if ((now - user.lastConnected) > threshold) { users[i].destroy(); } } }; return User; })(); Connection = (function () { function Connection(id, worker, socketid, user, ip) { this.id = id; this.socketid = socketid; this.worker = worker; this.rooms = {}; this.user = user; this.ip = ip || ''; } Connection.prototype.sendTo = function (roomid, data) { if (roomid && roomid.id) roomid = roomid.id; if (roomid && roomid !== 'lobby') data = '>' + roomid + '\n' + data; Sockets.socketSend(this.worker, this.socketid, data); ResourceMonitor.countNetworkUse(data.length); }; Connection.prototype.send = function (data) { Sockets.socketSend(this.worker, this.socketid, data); ResourceMonitor.countNetworkUse(data.length); }; Connection.prototype.destroy = function () { Sockets.socketDisconnect(this.worker, this.socketid); this.onDisconnect(); }; Connection.prototype.onDisconnect = function () { delete connections[this.id]; if (this.user) this.user.onDisconnect(this); }; Connection.prototype.popup = function (message) { this.send('|popup|' + message.replace(/\n/g, '||')); }; Connection.prototype.joinRoom = function (room) { if (room.id in this.rooms) return; this.rooms[room.id] = room; Sockets.channelAdd(this.worker, room.id, this.socketid); }; Connection.prototype.leaveRoom = function (room) { if (room.id in this.rooms) { delete this.rooms[room.id]; Sockets.channelRemove(this.worker, room.id, this.socketid); } }; return Connection; })(); Users.User = User; Users.Connection = Connection; /********************************************************* * Inactive user pruning *********************************************************/ Users.pruneInactive = User.pruneInactive; Users.pruneInactiveTimer = setInterval( User.pruneInactive, 1000 * 60 * 30, Config.inactiveuserthreshold || 1000 * 60 * 60 );
mit
JaySon-Huang/WebModel
WebModel/database/databasehelper.py
4676
# -*- coding: utf-8 -*- import sqlite3 VERBOSE = 0 CTABLE_DOMAIN = ''' CREATE TABLE IF NOT EXISTS Domains( did INTEGER PRIMARY KEY AUTOINCREMENT, domain VARCHAR(64) UNIQUE, indegree INTEGER, outdegree INTEGER )''' CTABLE_WEBSITE = ''' CREATE TABLE IF NOT EXISTS Websites( wid INTEGER PRIMARY KEY AUTOINCREMENT, did INTEGER, url VARCHAR(256) NOT NULL UNIQUE, title VARCHAR(100), visited bit, FOREIGN KEY (did) REFERENCES Domains(did) )''' CTABLE_RULESETS = ''' CREATE TABLE IF NOT EXISTS Rulesets( rid INTEGER PRIMARY KEY AUTOINCREMENT, did INTEGER, rules VARCHAR(512), FOREIGN KEY (did) REFERENCES Domains(did) )''' class DatabaseHelper(object): def __init__(self): '''创建表''' self.conn = sqlite3.connect("./items.db") if VERBOSE: print 'Database connection OPEN.' # Domain 表 self.conn.execute(CTABLE_DOMAIN) # Website 表 self.conn.execute(CTABLE_WEBSITE) # Rule 表 self.conn.execute(CTABLE_RULESETS) self.conn.commit() if VERBOSE: cur = self.conn.cursor() print 'Tables:',cur.execute("SELECT name FROM sqlite_master WHERE type = 'table'").fetchall() def close(self): '''关闭与数据库的连接''' if VERBOSE: print 'Database connection CLOSE.' self.conn.close() def insertDomain(self, domain, indegree=0, outdegree=0): '''增加一个域名''' cur = self.conn.cursor() cur.execute("INSERT INTO Domains VALUES (NULL,?,?,?)", (domain, indegree, outdegree)) # 写入到文件中 self.conn.commit() def insertRuleset(self, ruleset, domain): '''增加一个robots.txt规则集''' cur = self.conn.cursor() cur.execute("SELECT did FROM Domains WHERE domain=?", (domain,)) did = cur.fetchone()[0] cur.execute("INSERT INTO Rulesets VALUES (NULL,?,?)",(did, ruleset)) # 写入到文件 self.conn.commit() def insertWebsite(self, url, domain): '''增加一个网页,标记为未访问,并对相应的domain增加其入度''' cur = self.conn.cursor() cur.execute("SELECT 1 FROM Domains WHERE domain=?", (domain,)) result = cur.fetchone() if not result: # 未有对应domain记录, 先创建domain, 把入度设为1 if VERBOSE: print 'Spot Domain:',domain self.insertDomain(domain, indegree=1) cur.execute("SELECT did FROM Domains WHERE domain=?", (domain,)) did = cur.fetchone()[0] else: did = result[0] # 对应的domain记录已经存在, 对其入度+1 cur.execute("UPDATE Domains SET outdegree=outdegree+1 WHERE domain=?", (domain,)) cur.execute("INSERT INTO Websites VALUES (NULL,?,?,NULL,0)", (did, url,)) # 写入到文件 self.conn.commit() def updateInfo(self, item, newlinks, oldlinks): '''爬虫爬完之后对数据库内容进行更新''' cur = self.conn.cursor() cur.execute("SELECT wid,did FROM Websites WHERE url=?", (item['url'],)) wid, did = cur.fetchone() # website记录更新 cur.execute("UPDATE Websites SET title=?,visited=1 WHERE wid=?", (item['title'], wid,)) # 对应的domain记录中出度也需要更新 cur.execute("UPDATE Domains SET outdegree=outdegree+? WHERE did=?", (len(item['links']), did,)) # 对该网页中所有链接涉及的记录进行更新 # 外部判断未出现过的链接 for link,domain in newlinks: self.insertWebsite(link, domain) # 外部判断出现过的链接 for link,domain in oldlinks: # 对对应的domain记录入度增加 cur.execute("UPDATE Domains SET outdegree=outdegree+1 WHERE domain=?", (domain,)) # 写入到文件 self.conn.commit() def robotsrulesetOfDomain(self, domain): '''检查domain是否在数据库中, 否 --> (False, None) 是 --> (True, 数据库中存储的robots.txt内容) ''' exist = False cur = self.conn.cursor() # 是否存在 cur.execute("SELECT 1 FROM Domains WHERE domain=?", (domain,)) if cur.fetchone() : exist = True # 存在的话,结果是什么 cur.execute("SELECT rules FROM Domains,Rulesets " "WHERE domain=? AND Domains.did=Rulesets.did" ,(domain,) ) ruleset = cur.fetchone() return (exist, ruleset) def rollback(self): self.conn.rollback() def showAll(self): self.conn.commit() cur = self.conn.cursor() cur.execute("SELECT * FROM Domains") print cur.fetchall() cur.execute("SELECT * FROM Websites") print cur.fetchall() _dbcli = None def getCliInstance(): global _dbcli if not _dbcli: _dbcli = DatabaseHelper() return _dbcli def test(): dbcli = getCliInstance() # dbcli.insertDomain('jaysonhwang.com') # dbcli.insertRuleset('test','jaysonhwang.com') print dbcli.robotsrulesetOfDomain('www.zol.com') print dbcli.robotsrulesetOfDomain('jayson.com') dbcli.showAll() dbcli.close() if __name__ == '__main__': test()
mit
destos/dotfiles
link/.hammerspoon/init.lua
3739
-- Load Extensions local application = hs.application local window = hs.window local hotkey = hs.hotkey local fnutils = hs.fnutils local alert = hs.alert local grid = hs.grid -- Music controls local spotify = hs.spotify require "slowq" -- Avoid accidental cmd-Q function reloadConfig(files) doReload = false for _,file in pairs(files) do if file:sub(-4) == ".lua" then doReload = true end end if doReload then hs.reload() end end hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start() alert.show("Config loaded") --- The margin between each window vertically and horizontally. grid.setMargins('10,10') --- The number of cells high the grid is. grid.GRIDHEIGHT = 6 --- The number of cells wide the grid is. grid.GRIDWIDTH = 8 local animationDuration = 0.1 hs.window.animationDuration = animationDuration -- Set up hotkey combinations local mash = {"cmd", "alt", "ctrl"} local mashshift = {"cmd", "alt", "shift"} -- local function opendictionary() -- alert.show("Lexicon, at your service.", 0.75) -- application.launchorfocus("Dictionary") -- end -- hotkey.bind(mash, 'D', opendictionary) hotkey.bind(mash, ';', function() grid.snap(window.focusedWindow()) end) hotkey.bind(mash, "'", function() fnutils.map(window.visibleWindows(), grid.snap) end) hotkey.bind(mash, '=', function() grid.adjustNumberOfColumns( 1) end) hotkey.bind(mash, '-', function() grid.adjustNumberOfColumns(-1) end) hotkey.bind(mashshift, 'h', function() window.focusedWindow():focusWindowWest() end) hotkey.bind(mashshift, 'l', function() window.focusedWindow():focusWindowEast() end) hotkey.bind(mashshift, 'k', function() window.focusedWindow():focusWindowNorth() end) hotkey.bind(mashshift, 'j', function() window.focusedWindow():focusWindowSouth() end) hotkey.bind(mash, 'M', grid.maximizeWindow) hotkey.bind(mash, 'N', grid.pushWindowNextScreen) hotkey.bind(mash, 'P', grid.pushWindowPrevScreen) hotkey.bind(mash, 'J', grid.pushWindowDown) hotkey.bind(mash, 'K', grid.pushWindowUp) hotkey.bind(mash, 'H', grid.pushWindowLeft) hotkey.bind(mash, 'L', grid.pushWindowRight) hotkey.bind(mash, 'U', grid.resizeWindowTaller) hotkey.bind(mash, 'O', grid.resizeWindowWider) hotkey.bind(mash, 'I', grid.resizeWindowThinner) hotkey.bind(mash, 'Y', grid.resizeWindowShorter) hotkey.bind(mash, '.', function() local windows = hs.window.visibleWindows() for i in pairs(windows) do local window = windows[i] grid.snap(window) end end) -- -- Show and hide a stripe of Desktop {{{3 -- hotkey.bind(mash, ',', function() -- local windows = hs.window.visibleWindows() -- local finished = false -- for i in pairs(windows) do -- local window = windows[i] -- local frame = window:frame() -- local desktop = hs.window.desktop():frame() -- if frame.x + frame.w > desktop.w - 120 and frame ~= desktop then -- frame.w = desktop.w - frame.x - 120 -- alert.show(frame.w) -- window:setFrame(frame) -- finished = true -- end -- end -- if finished then return end -- for i in pairs(windows) do -- local window = windows[i] -- local frame = window:frame() -- local desktop = hs.window.desktop():frame() -- if frame.x + frame.w == desktop.w - 120 then -- frame.w = frame.w + 100 -- window:setFrame(frame) -- end -- end -- end) -- Spotify hotkey.bind(mashshift, 'space', spotify.displayCurrentTrack) hotkey.bind(mashshift, 'p', spotify.playpause) hotkey.bind(mashshift, 'n', spotify.next) hotkey.bind(mashshift, 'i', spotify.previous) alert.show("hammerspoon, at your service.")
mit
ramunasd/platform
src/Oro/Bundle/ApiBundle/Request/EntityClassTransformerInterface.php
574
<?php namespace Oro\Bundle\ApiBundle\Request; interface EntityClassTransformerInterface { /** * Transforms the FQCN of an entity to the type of an entity. * * @param string $entityClass The FQCN of an entity * * @return string The type of an entity */ public function transform($entityClass); /** * Transforms an entity type to the FQCN of an entity. * * @param string $entityType The type of an entity * * @return mixed The FQCN of an entity */ public function reverseTransform($entityType); }
mit
MetaMemoryT/hot-table
test/spec/settings-parser-spec.js
24541
describe('SettingsParser', function() { it('should be defined', function() { expect(HotTableUtils.SettingsParser).toBeDefined(); }); it('should return object with defined public methods and properties', function() { var parser = new HotTableUtils.SettingsParser(), publish = parser.getPublishMethodsAndProps(); expect(publish.addHook).isFunction(); expect(publish.addHookOnce).isFunction(); expect(publish.afterCellMetaReset).toBeDefined(); expect(publish.afterCellMetaResetChanged).isFunction(); expect(publish.afterChange).toBeDefined(); expect(publish.afterChangeChanged).isFunction(); expect(publish.afterChangesObserved).toBeDefined(); expect(publish.afterChangesObservedChanged).isFunction(); expect(publish.afterColumnMove).toBeDefined(); expect(publish.afterColumnMoveChanged).isFunction(); expect(publish.afterColumnResize).toBeDefined(); expect(publish.afterColumnResizeChanged).isFunction(); expect(publish.afterColumnSort).toBeDefined(); expect(publish.afterColumnSortChanged).isFunction(); expect(publish.afterContextMenuDefaultOptions).toBeDefined(); expect(publish.afterContextMenuDefaultOptionsChanged).isFunction(); expect(publish.afterCopyLimit).toBeDefined(); expect(publish.afterCopyLimitChanged).isFunction(); expect(publish.afterCreateCol).toBeDefined(); expect(publish.afterCreateColChanged).isFunction(); expect(publish.afterCreateRow).toBeDefined(); expect(publish.afterCreateRowChanged).isFunction(); expect(publish.afterDeselect).toBeDefined(); expect(publish.afterDeselectChanged).isFunction(); expect(publish.afterDestroy).toBeDefined(); expect(publish.afterDestroyChanged).isFunction(); expect(publish.afterDocumentKeyDown).toBeDefined(); expect(publish.afterDocumentKeyDownChanged).isFunction(); expect(publish.afterGetCellMeta).toBeDefined(); expect(publish.afterGetCellMetaChanged).isFunction(); expect(publish.afterGetColHeader).toBeDefined(); expect(publish.afterGetColHeaderChanged).isFunction(); expect(publish.afterGetRowHeader).toBeDefined(); expect(publish.afterGetRowHeaderChanged).isFunction(); expect(publish.afterInit).toBeDefined(); expect(publish.afterInitChanged).isFunction(); expect(publish.afterIsMultipleSelectionCheck).toBeDefined(); expect(publish.afterIsMultipleSelectionCheckChanged).isFunction(); expect(publish.afterLoadData).toBeDefined(); expect(publish.afterLoadDataChanged).isFunction(); expect(publish.afterMomentumScroll).toBeDefined(); expect(publish.afterMomentumScrollChanged).isFunction(); expect(publish.afterOnCellCornerMouseDown).toBeDefined(); expect(publish.afterOnCellCornerMouseDownChanged).isFunction(); expect(publish.afterOnCellMouseDown).toBeDefined(); expect(publish.afterOnCellMouseDownChanged).isFunction(); expect(publish.afterOnCellMouseOver).toBeDefined(); expect(publish.afterOnCellMouseOverChanged).isFunction(); expect(publish.afterRemoveCol).toBeDefined(); expect(publish.afterRemoveColChanged).isFunction(); expect(publish.afterRemoveRow).toBeDefined(); expect(publish.afterRemoveRowChanged).isFunction(); expect(publish.afterRender).toBeDefined(); expect(publish.afterRenderChanged).isFunction(); expect(publish.afterRenderer).toBeDefined(); expect(publish.afterRendererChanged).isFunction(); expect(publish.afterRowMove).toBeDefined(); expect(publish.afterRowMoveChanged).isFunction(); expect(publish.afterRowResize).toBeDefined(); expect(publish.afterRowResizeChanged).isFunction(); expect(publish.afterScrollHorizontally).toBeDefined(); expect(publish.afterScrollHorizontallyChanged).isFunction(); expect(publish.afterScrollVertically).toBeDefined(); expect(publish.afterScrollVerticallyChanged).isFunction(); expect(publish.afterSelection).toBeDefined(); expect(publish.afterSelectionChanged).isFunction(); expect(publish.afterSelectionByProp).toBeDefined(); expect(publish.afterSelectionByPropChanged).isFunction(); expect(publish.afterSelectionEnd).toBeDefined(); expect(publish.afterSelectionEndChanged).isFunction(); expect(publish.afterSelectionEndByProp).toBeDefined(); expect(publish.afterSelectionEndByPropChanged).isFunction(); expect(publish.afterSetCellMeta).toBeDefined(); expect(publish.afterSetCellMetaChanged).isFunction(); expect(publish.afterUpdateSettings).toBeDefined(); expect(publish.afterUpdateSettingsChanged).isFunction(); expect(publish.afterValidate).toBeDefined(); expect(publish.afterValidateChanged).isFunction(); expect(publish.allowInsertColumn).toBeDefined(); expect(publish.allowInsertColumnChanged).isFunction(); expect(publish.allowInsertRow).toBeDefined(); expect(publish.allowInsertRowChanged).isFunction(); expect(publish.allowInvalid).toBeDefined(); expect(publish.allowInvalidChanged).isFunction(); expect(publish.allowRemoveColumn).toBeDefined(); expect(publish.allowRemoveColumnChanged).isFunction(); expect(publish.allowRemoveRow).toBeDefined(); expect(publish.allowRemoveRowChanged).isFunction(); expect(publish.alter).isFunction(); expect(publish.autoComplete).toBeDefined(); expect(publish.autoCompleteChanged).isFunction(); expect(publish.autoWrapCol).toBeDefined(); expect(publish.autoWrapColChanged).isFunction(); expect(publish.autoWrapRow).toBeDefined(); expect(publish.autoWrapRowChanged).isFunction(); expect(publish.beforeAutofill).toBeDefined(); expect(publish.beforeAutofillChanged).isFunction(); expect(publish.beforeCellAlignment).toBeDefined(); expect(publish.beforeCellAlignmentChanged).isFunction(); expect(publish.beforeChange).toBeDefined(); expect(publish.beforeChangeChanged).isFunction(); expect(publish.beforeChangeRender).toBeDefined(); expect(publish.beforeChangeRenderChanged).isFunction(); expect(publish.beforeColumnSort).toBeDefined(); expect(publish.beforeColumnSortChanged).isFunction(); expect(publish.beforeDrawBorders).toBeDefined(); expect(publish.beforeDrawBordersChanged).isFunction(); expect(publish.beforeGetCellMeta).toBeDefined(); expect(publish.beforeGetCellMetaChanged).isFunction(); expect(publish.beforeInit).toBeDefined(); expect(publish.beforeInitChanged).isFunction(); expect(publish.beforeInitWalkontable).toBeDefined(); expect(publish.beforeInitWalkontableChanged).isFunction(); expect(publish.beforeKeyDown).toBeDefined(); expect(publish.beforeKeyDownChanged).isFunction(); expect(publish.beforeOnCellMouseDown).toBeDefined(); expect(publish.beforeOnCellMouseDownChanged).isFunction(); expect(publish.beforeRemoveCol).toBeDefined(); expect(publish.beforeRemoveColChanged).isFunction(); expect(publish.beforeRemoveRow).toBeDefined(); expect(publish.beforeRemoveRowChanged).isFunction(); expect(publish.beforeRender).toBeDefined(); expect(publish.beforeRenderChanged).isFunction(); expect(publish.beforeSetRangeEnd).toBeDefined(); expect(publish.beforeSetRangeEndChanged).isFunction(); expect(publish.beforeTouchScroll).toBeDefined(); expect(publish.beforeTouchScrollChanged).isFunction(); expect(publish.beforeValidate).toBeDefined(); expect(publish.beforeValidateChanged).isFunction(); expect(publish.cell).toBeDefined(); expect(publish.cellChanged).isFunction(); expect(publish.cells).toBeDefined(); expect(publish.cellsChanged).isFunction(); expect(publish.checkedTemplate).toBeDefined(); expect(publish.checkedTemplateChanged).isFunction(); expect(publish.className).toBeDefined(); expect(publish.classNameChanged).isFunction(); expect(publish.clear).toBeDefined(); expect(publish.clearUndo).toBeDefined(); expect(publish.colHeaders).toBeDefined(); expect(publish.colHeadersChanged).isFunction(); expect(publish.colOffset).toBeDefined(); expect(publish.colToProp).toBeDefined(); expect(publish.colWidths).toBeDefined(); expect(publish.colWidthsChanged).isFunction(); expect(publish.columnSorting).toBeDefined(); expect(publish.columnSortingChanged).isFunction(); expect(publish.columns).toBeDefined(); expect(publish.columnsChanged).isFunction(); expect(publish.commentedCellClassName).toBeDefined(); expect(publish.commentedCellClassNameChanged).isFunction(); expect(publish.comments).toBeDefined(); expect(publish.commentsChanged).isFunction(); expect(publish.contextMenu).toBeDefined(); expect(publish.contextMenuChanged).isFunction(); expect(publish.copyColsLimit).toBeDefined(); expect(publish.copyColsLimitChanged).isFunction(); expect(publish.copyRowsLimit).toBeDefined(); expect(publish.copyRowsLimitChanged).isFunction(); expect(publish.copyable).toBeDefined(); expect(publish.copyableChanged).isFunction(); expect(publish.countCols).toBeDefined(); expect(publish.countEmptyCols).toBeDefined(); expect(publish.countEmptyRows).toBeDefined(); expect(publish.countRenderedCols).toBeDefined(); expect(publish.countRenderedRows).toBeDefined(); expect(publish.countRows).toBeDefined(); expect(publish.countVisibleCols).toBeDefined(); expect(publish.countVisibleRows).toBeDefined(); expect(publish.currentColClassName).toBeDefined(); expect(publish.currentColClassNameChanged).isFunction(); expect(publish.currentRowClassName).toBeDefined(); expect(publish.currentRowClassNameChanged).isFunction(); expect(publish.customBorders).toBeDefined(); expect(publish.customBordersChanged).isFunction(); expect(publish.dataSchema).toBeDefined(); expect(publish.dataSchemaChanged).isFunction(); expect(publish.datarows).toBeDefined(); expect(publish.datarowsChanged).isFunction(); expect(publish.debug).toBeDefined(); expect(publish.debugChanged).isFunction(); expect(publish.deselectCell).toBeDefined(); expect(publish.destroy).toBeDefined(); expect(publish.destroyEditor).toBeDefined(); expect(publish.determineColumnWidth).toBeDefined(); expect(publish.disableVisualSelection).toBeDefined(); expect(publish.disableVisualSelectionChanged).isFunction(); expect(publish.editor).toBeDefined(); expect(publish.editorChanged).isFunction(); expect(publish.enterBeginsEditing).toBeDefined(); expect(publish.enterBeginsEditingChanged).isFunction(); expect(publish.enterMoves).toBeDefined(); expect(publish.enterMovesChanged).isFunction(); expect(publish.fillHandle).toBeDefined(); expect(publish.fillHandleChanged).isFunction(); expect(publish.fixedColumnsLeft).toBeDefined(); expect(publish.fixedColumnsLeftChanged).isFunction(); expect(publish.format).toBeDefined(); expect(publish.formatChanged).isFunction(); expect(publish.fragmentSelection).toBeDefined(); expect(publish.fragmentSelectionChanged).isFunction(); expect(publish.getCell).isFunction(); expect(publish.getCellEditor).isFunction(); expect(publish.getCellMeta).isFunction(); expect(publish.getCellRenderer).isFunction(); expect(publish.getCellValidator).isFunction(); expect(publish.getColHeader).isFunction(); expect(publish.getColWidth).isFunction(); expect(publish.getCopyableData).isFunction(); expect(publish.getData).isFunction(); expect(publish.getDataAtCell).isFunction(); expect(publish.getDataAtCol).isFunction(); expect(publish.getDataAtProp).isFunction(); expect(publish.getDataAtRow).isFunction(); expect(publish.getDataAtRowProp).isFunction(); expect(publish.getInstance).isFunction(); expect(publish.getRowHeader).isFunction(); expect(publish.getRowHeight).isFunction(); expect(publish.getSchema).isFunction(); expect(publish.getSelected).isFunction(); expect(publish.getSelectedRange).isFunction(); expect(publish.getSettings).isFunction(); expect(publish.getSourceDataAtCol).isFunction(); expect(publish.getSourceDataAtRow).isFunction(); expect(publish.getValue).isFunction(); expect(publish.groups).toBeDefined(); expect(publish.groupsChanged).isFunction(); expect(publish.hasColHeaders).isFunction(); expect(publish.hasRowHeaders).isFunction(); expect(publish.header).toBeDefined(); expect(publish.headerChanged).isFunction(); expect(publish.height).toBeDefined(); expect(publish.heightChanged).isFunction(); expect(publish.highlightedColumn).toBe(-1); expect(publish.highlightedRow).toBe(-1); expect(publish.init).isFunction(); expect(publish.invalidCellClassName).toBeDefined(); expect(publish.invalidCellClassNameChanged).isFunction(); expect(publish.isEmptyCol).isFunction(); expect(publish.isEmptyColChanged).isFunction(); expect(publish.isEmptyRow).isFunction(); expect(publish.isEmptyRowChanged).isFunction(); expect(publish.isListening).isFunction(); expect(publish.isRedoAvailable).isFunction(); expect(publish.isUndoAvailable).isFunction(); expect(publish.listen).isFunction(); expect(publish.loadData).isFunction(); expect(publish.manualColumnFreeze).toBeDefined(); expect(publish.manualColumnFreezeChanged).isFunction(); expect(publish.manualColumnMove).toBeDefined(); expect(publish.manualColumnMoveChanged).isFunction(); expect(publish.manualColumnResize).toBeDefined(); expect(publish.manualColumnResizeChanged).isFunction(); expect(publish.manualRowMove).toBeDefined(); expect(publish.manualRowMoveChanged).isFunction(); expect(publish.manualRowResize).toBeDefined(); expect(publish.manualRowResizeChanged).isFunction(); expect(publish.maxCols).toBeDefined(); expect(publish.maxColsChanged).isFunction(); expect(publish.maxRows).toBeDefined(); expect(publish.maxRowsChanged).isFunction(); expect(publish.mergeCells).toBeDefined(); expect(publish.mergeCellsChanged).isFunction(); expect(publish.minCols).toBeDefined(); expect(publish.minColsChanged).isFunction(); expect(publish.minRows).toBeDefined(); expect(publish.minRowsChanged).isFunction(); expect(publish.minSpareCols).toBeDefined(); expect(publish.minSpareColsChanged).isFunction(); expect(publish.minSpareRows).toBeDefined(); expect(publish.minSpareRowsChanged).isFunction(); expect(publish.modifyCol).toBeDefined(); expect(publish.modifyColChanged).isFunction(); expect(publish.modifyColWidth).toBeDefined(); expect(publish.modifyColWidthChanged).isFunction(); expect(publish.modifyRow).toBeDefined(); expect(publish.modifyRowChanged).isFunction(); expect(publish.modifyRowHeight).toBeDefined(); expect(publish.modifyRowHeightChanged).isFunction(); expect(publish.multiSelect).toBeDefined(); expect(publish.multiSelectChanged).isFunction(); expect(publish.noWordWrapClassName).toBeDefined(); expect(publish.noWordWrapClassNameChanged).isFunction(); expect(publish.observeDOMVisibility).toBeDefined(); expect(publish.observeDOMVisibilityChanged).isFunction(); expect(publish.outsideClickDeselects).toBeDefined(); expect(publish.outsideClickDeselectsChanged).isFunction(); expect(publish.pasteMode).toBeDefined(); expect(publish.pasteModeChanged).isFunction(); expect(publish.persistentState).toBeDefined(); expect(publish.persistentStateChanged).isFunction(); expect(publish.persistentStateLoad).toBeDefined(); expect(publish.persistentStateLoadChanged).isFunction(); expect(publish.persistentStateReset).toBeDefined(); expect(publish.persistentStateResetChanged).isFunction(); expect(publish.persistentStateSave).toBeDefined(); expect(publish.persistentStateSaveChanged).isFunction(); expect(publish.placeholder).toBeDefined(); expect(publish.placeholderChanged).isFunction(); expect(publish.placeholderCellClassName).toBeDefined(); expect(publish.placeholderCellClassNameChanged).isFunction(); expect(publish.populateFromArray).isFunction(); expect(publish.propToCol).isFunction(); expect(publish.readOnly).toBeDefined(); expect(publish.readOnlyChanged).isFunction(); expect(publish.readOnlyCellClassName).toBeDefined(); expect(publish.readOnlyCellClassNameChanged).isFunction(); expect(publish.redo).isFunction(); expect(publish.removeCellMeta).isFunction(); expect(publish.removeHook).isFunction(); expect(publish.render).isFunction(); expect(publish.renderer).toBeDefined(); expect(publish.rendererChanged).isFunction(); expect(publish.rowHeaders).toBeDefined(); expect(publish.rowHeadersChanged).isFunction(); expect(publish.rowOffset).isFunction(); expect(publish.runHooks).isFunction(); expect(publish.search).toBeDefined(); expect(publish.searchChanged).isFunction(); expect(publish.selectCell).isFunction(); expect(publish.selectCellByProp).isFunction(); expect(publish.setCellMeta).isFunction(); expect(publish.setCellMetaObject).isFunction(); expect(publish.setDataAtCell).isFunction(); expect(publish.setDataAtRowProp).isFunction(); expect(publish.settings).toBeDefined(); expect(publish.settingsChanged).isFunction(); expect(publish.spliceCol).isFunction(); expect(publish.spliceRow).isFunction(); expect(publish.spliceRow).isFunction(); expect(publish.startCols).toBeDefined(); expect(publish.startColsChanged).isFunction(); expect(publish.startRows).toBeDefined(); expect(publish.startRowsChanged).isFunction(); expect(publish.stretchH).toBeDefined(); expect(publish.stretchHChanged).isFunction(); expect(publish.tabMoves).toBeDefined(); expect(publish.tabMovesChanged).isFunction(); expect(publish.trimWhitespace).toBeDefined(); expect(publish.trimWhitespaceChanged).isFunction(); expect(publish.type).toBeDefined(); expect(publish.typeChanged).isFunction(); expect(publish.uncheckedTemplate).toBeDefined(); expect(publish.uncheckedTemplateChanged).isFunction(); expect(publish.undo).isFunction(); expect(publish.unlisten).isFunction(); expect(publish.updateSettings).isFunction(); expect(publish.validateCell).isFunction(); expect(publish.validateCells).isFunction(); expect(publish.validator).toBeDefined(); expect(publish.validatorChanged).isFunction(); expect(publish.viewportColumnRenderingOffset).toBeDefined(); expect(publish.viewportColumnRenderingOffsetChanged).isFunction(); expect(publish.viewportRowRenderingOffset).toBeDefined(); expect(publish.viewportRowRenderingOffsetChanged).isFunction(); expect(publish.width).toBeDefined(); expect(publish.widthChanged).isFunction(); expect(publish.wordWrap).toBeDefined(); expect(publish.wordWrapChanged).isFunction(); }); it('should parse <hot-table> attributes himself', function() { var parser = new HotTableUtils.SettingsParser(), hot, settings; hot = document.createElement('hot-table'); hot.setAttribute('allowRemoveRow', 'false'); hot.enterMoves = {row: 1, col: 1}; hot.datarows = [{id: 1, name: 'foo'}]; hot.setAttribute('copyable', 'false'); hot.setAttribute('editor', 'false'); hot.setAttribute('minCols', '10'); hot.setAttribute('width', '100'); settings = parser.parse(hot); expect(settings.allowRemoveRow).toBe(false); expect(settings.enterMoves).toBe(hot.enterMoves); expect(settings.copyable).toBe(false); expect(settings.data).toBe(hot.datarows); expect(settings.editor).toBe(false); expect(settings.minCols).toBe(10); expect(settings.width).toBe('100'); }); it('should parse <hot-table> columns attributes', function() { var parser = new HotTableUtils.SettingsParser(), hot, hotColumn, columns; hot = document.createElement('hot-table'); columns = parser.parseColumns(hot); expect(columns.length).toBe(0); hotColumn = document.createElement('hot-column'); hotColumn.classList.add('custom-class'); hotColumn.classList.add('second-class'); hotColumn.setAttribute('editor', 'false'); hotColumn.setAttribute('readOnly', 'true'); hotColumn.setAttribute('readOnlyCellClassName', 'read-only'); hot.appendChild(hotColumn); columns = parser.parseColumns(hot); expect(columns.length).toBe(1); expect(columns[0].className).toBe('custom-class second-class'); expect(columns[0].editor).toBe(false); expect(columns[0].readOnly).toBe(true); expect(columns[0].readOnlyCellClassName).toBe('read-only'); }); it('should parse <hot-table> single column attributes', function() { var parser = new HotTableUtils.SettingsParser(), hot, hotColumn, columns; hot = document.createElement('hot-table'); columns = parser.parseColumns(hot); expect(columns.length).toBe(0); hotColumn = document.createElement('hot-column'); hotColumn.classList.add('custom-class'); hotColumn.classList.add('second-class'); hotColumn.setAttribute('editor', 'false'); hotColumn.setAttribute('readOnly', 'true'); hotColumn.setAttribute('readOnlyCellClassName', 'read-only'); hot.appendChild(hotColumn); columns = parser.parseColumn(hot, hotColumn); expect(columns.className).toBe('custom-class second-class'); expect(columns.editor).toBe(false); expect(columns.readOnly).toBe(true); expect(columns.readOnlyCellClassName).toBe('read-only'); }); it('should read table options in correct way', function() { var parser = new HotTableUtils.SettingsParser(), hot; hot = document.createElement('hot-table'); spyOn(parser, 'getModelPath'); spyOn(parser, 'readBool').and.callThrough(); expect(parser.readOption(hot, 'className', '')).toBe(''); expect(parser.readOption(hot, 'className', 'true')).toBe('true'); expect(parser.readOption(hot, 'someProperty', '')).toBe(true); expect(parser.readOption(hot, 'someProperty', 'true')).toBe(true); expect(parser.readOption(hot, 'someProperty', 'false')).toBe(false); expect(parser.readOption(hot, 'someProperty', undefined)).toBe(false); expect(parser.getModelPath.calls.count()).toEqual(0); expect(parser.readBool.calls.count()).toEqual(4); parser.readOption(hot, 'renderer', 1); parser.readOption(hot, 'datarows', 2); parser.readOption(hot, 'source', 3); parser.readOption(hot, 'dataSchema', 4); expect(parser.getModelPath.calls.count()).toBe(4); expect(parser.getModelPath.calls.mostRecent().args[0]).toBe(hot); expect(parser.getModelPath.calls.mostRecent().args[1]).toBe(4); }); it('should try to read as boolean if not it returns untouched value', function() { var parser = new HotTableUtils.SettingsParser(); expect(parser.readBool('')).toBe(true); expect(parser.readBool('true')).toBe(true); expect(parser.readBool('foo')).toBe('foo'); expect(parser.readBool('false')).toBe(false); expect(parser.readBool(null)).toBe(null); expect(parser.readBool(undefined)).toBe(false); expect(parser.readBool(12345)).toBe(12345); }); it('should filter object from null values', function() { var parser = new HotTableUtils.SettingsParser(), obj, result; obj = {a: 1, b: 'foo', c: function(){}, d: {}, e: [], f: null, h: undefined}; result = parser.filterNonNull(obj); delete obj.f; expect(result).toEqual(obj); }); it('should get template model from element if it exists', function() { var parser = new HotTableUtils.SettingsParser(), fakeHot, model; model = {a: 1}; fakeHot = { templateInstance: {model: model} }; expect(parser.getModel(fakeHot)).toBe(model); expect(parser.getModel({})).toBe(window); }); it('should get model value based on path (e.g.: {{ obj.a.b }})', function() { var parser = new HotTableUtils.SettingsParser(), fakeHot, model; model = {a: {b: {c: 1}}}; fakeHot = { templateInstance: {model: model} }; expect(parser.getModelPath(fakeHot, 'a.b.c')).toBe(model.a.b.c); expect(parser.getModelPath(fakeHot, 'a.b')).toBe(model.a.b); expect(parser.getModelPath(fakeHot, 'a')).toBe(model.a); expect(parser.getModelPath(fakeHot, '')).toBe(undefined); }); });
mit
florent-pallaver/temple
diet/WebContent/app/features/diary/diary.controller.js
6759
(function() { const FOOD_RS_URL = BASE_URL + 'food/'; const module = angular.module('diary', [ 'user', 'meal' ]); module.controller('DiaryController', [ '$http', '$routeParams', 'UserService', DiaryController ]); function DiaryController($http, $routeParams, UserService) { const self = this; const baseUrl = BASE_URL + 'diary'; self.units = { 'GRAM': 'g', 'MILLILITER': 'ml', 'UNIT': '' }; self.resultClasses = { 'FAILURE': 'bg-danger', 'CHEAT_DAY': 'bg-warning', 'PASSABLE': 'bg-info', 'SUCCESS': 'bg-success' }; self.days = []; self.dates = []; self.foods = {}; self.foodList = []; self.foodFilters = { 'BREAKFAST': {}, 'MORNING_SNACK': {}, 'LUNCH': {}, 'AFTERNOON_SNACK': {}, 'DINNER': {}, 'EVENING_SNACK': {}, 'WORK_OUT': {} }; self.newDay = new Date(); self.day = null; self.init = function() { $http.get(baseUrl).then(function(response) { self.dates = []; self.days = response.data; if (self.days && self.days.length) { self.dates = self.days.map(day => day.dayDate); // TODO checker si c'est today self.day = self.days[0]; self.setViewingDay(); } else { self.addDay(); } }, onError); }; self.previousDay = function() { changeDay(1); }; self.nextDay = function() { changeDay(-1); }; function changeDay(i) { var newDayIndex = (self.dates.length + self.dates.indexOf(self.day.dayDate) + i) % self.dates.length; self.day = self.days[newDayIndex]; self.setViewingDay(); } let DEFAULT_INPUT = { 'GRAM': {max: 2500, step: 5}, 'MILLILITER': {max: 2500, step: 5}, 'UNIT': {max: 50, step: 1} }; self.initFood = function() { return $http.get(FOOD_RS_URL).then(function(response) { self.foods = {}; self.foodList = response.data; self.foodList.forEach(food => self.foods[food.id] = food); self.foodList.forEach(food => food.input = angular.copy(DEFAULT_INPUT[food.counting])); }, onError); } self.addDay = function() { var data = { day : self.newDay.getDate(), month : self.newDay.getMonth() + 1, year : self.newDay.getFullYear() }; $http.post(baseUrl, data).then(self.init, onError); } self.setViewingDay = function() { self.day.intake = new Intake(); self.day.targetIntake = new Intake(); self.day.intakeDiff = new Intake(); refreshMeals(); }; var refreshMeals = function() { self.day.meals = []; $http.get(baseUrl + '/' + self.day.id + '/meals').then(function(response) { self.day.meals = response.data; self.day.meals.forEach(initMeal); self.day.meals.forEach(meal => self.day.intake.add(meal.intake)); computeTargetIntake(); }, onError); }; var initMeal = function(meal) { meal.items = {}; meal.itemIntakes = {}; meal.editing = false; meal.showContent = false; meal.content.forEach(entry => { meal.items[entry.key] = entry.value; meal.itemIntakes[entry.key] = new Intake(self.foods[entry.key], entry.value); }); }; function Intake(food, quantity) { var self = this; self.add = function(intake, factor) { var factor = factor || 1; self.fat += intake.fat * factor; self.carb += intake.carb * factor; self.fiber += intake.fiber * factor; self.protein += intake.protein * factor; self.theoricKcal = self.fat * 9 + 4 * (self.carb + self.protein); self.kcal = self.theoricKcal; self.igLevel = intake.igLevel; self.ig = intake.ig; }; self.reset = function() { self.fat = 0; self.carb = 0; self.fiber = 0; self.protein = 0; self.kcal = 0; self.theoricKcal = 0; }; self.reset(); if(food && quantity) { self.add(food.intake, food.counting === 'UNIT' ? quantity : (quantity / 100)); } } var computeTargetIntake = function() { var d = self.day; var t = d.targetIntake; if(d.metabolicRate && d.activityFactor && d.fatFactor && d.proteinFactor && d.weight) { var kcalDelta = 0; switch(d.growthMode) { case 'INCREASE': kcalDelta = +300; // entre 200 et 300 ? break; case 'DECREASE': kcalDelta = -300; break; } t.kcal = kcalDelta + (d.metabolicRate * d.activityFactor / 100); t.fat = d.weight * d.fatFactor / 100; t.protein = d.weight * d.proteinFactor / 100; t.carb = (t.kcal - (9 * t.fat)) / 4 - t.protein; t.fiber = 35; } d.intakeDiff.reset(); d.intakeDiff.add(d.intake, 1); d.intakeDiff.add(t, -1); }; self.setDayData = function() { var data = { dayDate: self.day.dayDate, weight: self.day.weight, metabolicRate: self.day.metabolicRate, activityFactor: self.day.activityFactor, growthMode: self.day.growthMode, fatFactor: self.day.fatFactor, proteinFactor: self.day.proteinFactor, sleepDuration: self.day.sleepDuration, fasting: self.day.fasting, result: self.day.result, comments: self.day.comments || '', }; $http.put(baseUrl + '/' + self.day.id, data).then(computeTargetIntake, onError); }; self.toggleMealEditing = function(meal) { meal.editing = !meal.editing; if(!meal.editing) { _saveMeal(meal); } }; function _saveMeal(meal) { return $http.put(baseUrl + '/' + self.day.id + '/meals/' + meal.time, meal.items).then(function(response) { self.day.intake.add(meal.intake, -1); meal.intake = response.data.intake; meal.content = response.data.content; initMeal(meal); self.day.intake.add(meal.intake, +1); computeTargetIntake(); meal.showContent = true; }, onError); } self.foodUpdated = function(meal, foodId) { if(meal.items[foodId] !== null) { meal.itemIntakes[foodId] = new Intake(self.foods[foodId], meal.items[foodId]); return $http.put(baseUrl + '/' + self.day.id + '/meals/' + meal.time, meal.items).then(function(response) { self.day.intake.add(meal.intake, -1); meal.intake = response.data.intake; meal.content = response.data.content; self.day.intake.add(meal.intake, +1); computeTargetIntake(); meal.showContent = true; }, onError) } }; self.addFood = function(meal, food) { meal.items[food.id] = 0; }; self.removeFood = function(meal, foodId) { delete meal.items[foodId]; _saveMeal(meal); }; self.increase = function(meal, foodId, factor) { meal.items[foodId] += factor * self.foods[foodId].input.step; var input = self.foods[foodId].input; if(input.max < meal.items[foodId]) { input.max = meal.items[foodId]; } return self.foodUpdated(meal, foodId); } self.foodComparator = function(foodId1, foodId2) { }; self.initFood() .then(self.init); } })();
mit
wissamdagher/Temenos-T24-COB-Monitor
vendor/stack/builder/src/Stack/Builder.php
1238
<?php namespace Stack; use Symfony\Component\HttpKernel\HttpKernelInterface; class Builder { private $specs; public function __construct() { $this->specs = new \SplStack(); } public function unshift(/*$kernelClass, $args...*/) { if (func_num_args() === 0) { throw new \InvalidArgumentException("Missing argument(s) when calling unshift"); } $spec = func_get_args(); $this->specs->unshift($spec); return $this; } public function push(/*$kernelClass, $args...*/) { if (func_num_args() === 0) { throw new \InvalidArgumentException("Missing argument(s) when calling push"); } $spec = func_get_args(); $this->specs->push($spec); return $this; } public function resolve(HttpKernelInterface $app) { $middlewares = array($app); foreach ($this->specs as $spec) { $args = $spec; $firstArg = array_shift($args); if (is_callable($firstArg)) { $app = $firstArg($app); } else { $kernelClass = $firstArg; array_unshift($args, $app); $reflection = new \ReflectionClass($kernelClass); $app = $reflection->newInstanceArgs($args); } array_unshift($middlewares, $app); } return new StackedHttpKernel($app, $middlewares); } }
mit
steffen25/golang.zone
controllers/upload.go
2326
package controllers import ( "bytes" "io" "io/ioutil" "net/http" "strings" "time" "github.com/steffen25/golang.zone/util" ) const ( MB = 1 << 20 ) type UploadController struct{} type UploadImageResponse struct { ImageURL string `json:"imageUrl"` } func NewUploadController() *UploadController { return &UploadController{} } func (uc *UploadController) UploadImage(w http.ResponseWriter, r *http.Request) { contentType := r.Header.Get("Content-type") if !strings.Contains(contentType, "multipart/form-data") { NewAPIError(&APIError{false, "Invalid request body. Request body must be of type multipart/form-data", http.StatusBadRequest}, w) return } // Limit upload size r.Body = http.MaxBytesReader(w, r.Body, 2*MB) if err := r.ParseMultipartForm(2 * MB); err != nil { NewAPIError(&APIError{false, "The file you are uploading is too big. Maximum file size is 2MB", http.StatusBadRequest}, w) return } var Buf bytes.Buffer file, _, err := r.FormFile("image") if err != nil { if err == http.ErrMissingFile { NewAPIError(&APIError{false, "Image is required", http.StatusBadRequest}, w) return } NewAPIError(&APIError{false, "Error processing multipart data", http.StatusBadRequest}, w) return } defer file.Close() // Copy the file data to my buffer io.Copy(&Buf, file) fileExtension := http.DetectContentType(Buf.Bytes()) validFileExtensions := map[string]string{ "image/jpeg": ".jpg", "image/png": ".png", "image/gif": ".gif", } if _, ok := validFileExtensions[fileExtension]; !ok { NewAPIError(&APIError{false, "Invalid mime type, file must be of image/jpeg, image/png or image/gif", http.StatusBadRequest}, w) return } ext := validFileExtensions[fileExtension] now := time.Now() fileName := now.Format("2006-01-02_15-04-05") + "_" + util.GetMD5Hash(now.String()) err = ioutil.WriteFile("./public/images/"+fileName+ext, Buf.Bytes(), 0644) if err != nil { NewAPIError(&APIError{false, "Could not write file to disk", http.StatusInternalServerError}, w) return } Buf.Reset() // TODO: Remove hardcoded url imageSrc := util.GetRequestScheme(r) + r.Host + "/assets/" + fileName + ext data := UploadImageResponse{imageSrc} NewAPIResponse(&APIResponse{Success: true, Message: "Image uploaded successfully", Data: data}, w, http.StatusOK) }
mit
AlexandraMercier/StrategyIA
ai/STA/Strategy/WeirdmovementStrategy.py
2053
# Under MIT License, see LICENSE.txt from ai.Algorithm.Node import Node from ai.STA.Strategy.Strategy import Strategy from ai.STA.Tactic.GoToPositionNoPathfinder import GoToPositionNoPathfinder from ai.STA.Tactic.Stop import Stop from RULEngine.Util.Pose import Position, Pose from ai.STA.Tactic.tactic_constants import Flags class WeirdmovementStrategy(Strategy): def __init__(self, p_game_state): super().__init__(p_game_state) self.add_tactic(0, Stop(self.game_state, 0)) self.add_tactic(0, GoToPositionNoPathfinder(self.game_state, 0, Pose(Position(-500, -500)))) self.add_tactic(0, GoToPositionNoPathfinder(self.game_state, 0, Pose(Position(-1500, -1500)))) self.add_condition(0, 0, 1, self.condition2) self.add_condition(0, 1, 2, self.condition) self.add_condition(0, 2, 0, self.condition) self.add_tactic(1, GoToPositionNoPathfinder(self.game_state, 1, Pose(Position(0, 0)))) self.add_tactic(1, GoToPositionNoPathfinder(self.game_state, 1, Pose(Position(1000, 0)))) self.add_tactic(1, GoToPositionNoPathfinder(self.game_state, 1, Pose(Position(1000, 1000)))) self.add_tactic(1, GoToPositionNoPathfinder(self.game_state, 1, Pose(Position(0, 1000)))) self.add_condition(1, 0, 1, self.condition1) self.add_condition(1, 1, 2, self.condition1) self.add_condition(1, 2, 3, self.condition1) self.add_condition(1, 3, 0, self.condition1) for i in range(2, 6): self.add_tactic(i, Stop(self.game_state, i)) def condition(self): return self.graphs[0].get_current_tactic().status_flag == Flags.SUCCESS def condition1(self): """ Condition pour passer du noeud présent au noeud suivant. :return: Un booléen indiquant si la condition pour effectuer la transition est remplie. """ return self.graphs[1].get_current_tactic().status_flag == Flags.SUCCESS def condition2(self): self.graphs[1].nodes[3].tactic.status_flag == Flags.SUCCESS
mit
deciob/nightcharts
run.js
3106
(function(curl) { var config = { // baseUrl: '', paths: { 'get_siblings': "app/utils/get_siblings", 'get_node_config': "app/utils/get_node_config" }, packages: [ // Define application-level packages { name: 'welcome', location: 'app/welcome' }, { name: 'language_selector', location: 'app/language_selector' }, { name: 'collection', location: 'app/collection' }, // Define a theme package, and configure it to always use the css module loader // No need to use AMD 'css!' plugin to load things in this package, it will happen // automatigally. // WARNING: The moduleLoader config syntax will be changing in an upcoming version // of curl. { name: 'theme', location: 'theme', config: { moduleLoader: 'curl/plugin/css' } }, // Add third-party packages here { name: 'curl', location: 'lib/curl/src/curl' }, { name: 'wire', location: 'lib/wire', main: 'wire' }, { name: 'cola', location: 'lib/cola', main: 'cola' }, { name: 'rest', location: 'lib/rest', main: 'rest' }, { name: 'msgs', location: 'lib/msgs', main: 'msgs' }, { name: 'when', location: 'lib/when', main: 'when' }, { name: 'meld', location: 'lib/meld', main: 'meld' }, { name: 'poly', location: 'lib/poly' }, { name: "lodash", location: "lib/lodash/dist", main: "lodash"} ], // Turn off i18n locale sniffing. Change or remove this line if you want // to test specific locales or try automatic locale-sniffing. locale: false, // Polyfill everything ES5-ish //preloads: ['poly/all'] // Or, select individual polyfills if you prefer //preloads: ['poly/array', 'poly/function', 'poly/json', 'poly/object', 'poly/string', 'poly/xhr'] }; curl(config, ['wire!app/main']).then(success, fail); // Success! curl.js indicates that your app loaded successfully! function success () { var msg; // When using wire, the success callback is typically not needed since // wire will compose and initialize the app from the main spec. // However, this callback can be useful for executing startup tasks // you don't want inside of a wire spec, such as this: msg = 'Looking good!'; console.log(msg); } // Oops. curl.js indicates that your app failed to load correctly. function fail (ex) { var el, msg; // There are many ways to handle errors. This is just a simple example. // Note: you cannot rely on any specific library or shim to be // loaded at this point. Therefore, you must use standard DOM // manipulation and legacy IE equivalents. console.log('an error happened during loading :\'('); console.log(ex.message); if (ex.stack) console.log(ex.stack); el = document.getElementById('errout'); msg = 'An error occurred while loading: ' + ex.message + '. See the console for more information.'; if (el) { // inject the error message if ('textContent' in el) el.textContent = msg; else el.innerText = msg; // clear styling that may be hiding the error message el.style.display = ''; document.documentElement.className = ''; } else { throw msg; } } })(curl);
mit
activewarehouse/activewarehouse-etl
lib/etl/parser/csv_parser.rb
3248
module ETL #:nodoc: module Parser #:nodoc: # Parses CSV files class CsvParser < ETL::Parser::Parser # Initialize the parser # * <tt>source</tt>: The Source object # * <tt>options</tt>: Hash of options for the parser, defaults to an empty hash def initialize(source, options={}) super configure end attr_reader :validate_rows def get_fields_names(file) File.open(file) do |input| fields = CSV.parse(input.readline, options).first new_fields = [] fields.each_with_index do |field,index| # compute the index of occurrence of this specific occurrence of the field (usually, will be 1) occurrence_index = fields[0..index].find_all { |e| e == field }.size number_of_occurrences = fields.find_all { |e| e == field }.size new_field = field + (number_of_occurrences > 1 ? "_#{occurrence_index}" : "") new_fields << Field.new(new_field.to_sym) end return new_fields end end # Returns each row. def each Dir.glob(file).each do |file| ETL::Engine.logger.debug "parsing #{file}" if fields.length == 0 ETL::Engine.logger.debug "no columns specified so reading names from first line of #{file}" @fields = get_fields_names(file) end line = 0 lines_skipped = 0 CSV.foreach(file, options) do |raw_row| if lines_skipped < source.skip_lines ETL::Engine.logger.debug "skipping line" lines_skipped += 1 next end line += 1 row = {} validate_row(raw_row, line, file) if self.validate_rows raw_row.each_with_index do |value, index| f = fields[index] row[f.name] = value end yield row end end end # Get an array of defined fields def fields @fields ||= [] end private def validate_row(row, line, file) ETL::Engine.logger.debug "validating line #{line} in file #{file}" if row.length != fields.length raise_with_info( MismatchError, "The number of columns from the source (#{row.length}) does not match the number of columns in the definition (#{fields.length})", line, file ) end end def configure @validate_rows = if source.configuration.has_key?(:validate_rows) source.configuration[:validate_rows] else true end source.definition.each do |options| case options when Symbol fields << Field.new(options) when Hash fields << Field.new(options[:name]) else raise DefinitionError, "Each field definition must either be a symbol or a hash" end end end class Field #:nodoc: attr_reader :name def initialize(name) @name = name end end end end end
mit
MelnikVasya/exactonline-api-ruby-client
lib/elmas/response.rb
1313
require File.expand_path("../parser", __FILE__) require File.expand_path("../utils", __FILE__) module Elmas class Response attr_accessor :status_code, :body, :response def initialize(response) @response = response raise_and_log_error if fail? end def success? @response.success? || SUCCESS_CODES.include?(status) end def body @response.body end def parsed response.env.method == :put ? Parser.new('{}') : Parser.new(body) end def result Elmas::ResultSet.new(parsed) end def results Elmas::ResultSet.new(parsed) end def status @response.status end def fail? ERROR_CODES.include? status end def error_message parsed.error_message end def log_error message = "An error occured, the response had status #{status}. The content of the error was: #{error_message}" Elmas.error(message) end SUCCESS_CODES = [ 201, 202, 203, 204, 301, 302, 303, 304 ].freeze ERROR_CODES = [ 400, 401, 402, 403, 404, 500, 501, 502, 503 ].freeze UNAUTHORIZED_CODES = [ 400, 401, 402, 403 ].freeze private def raise_and_log_error log_error fail BadRequestException.new(@response, parsed) end end end
mit
Ataide/ckize-full
components/register/registerController.js
803
(function(){ 'use strict'; angular .module('app') .controller('RegisterController', RegisterController); RegisterController.$inject = ['$http','$state','$auth']; function RegisterController($http,$state,$auth){ var vm = this; $('body').removeClass('page-signin'); $('body').addClass('page-signup'); vm.register = function(){ var credentials = { displayName: vm.user_name, email: vm.user_email, password: vm.user_password }; $auth.signup(credentials).then(function(response){ $state.go('login', {}); alert('Registro Realizado com sucesso. Você poderá se logar agora.'); }).catch(function(error){ alert(error.data.error); }); }; } })();
mit
DanielAndreasen/SWEETer-Cat
sweetercat/config.py
6607
# Sample Gunicorn configuration file. # # Server socket # # bind - The socket to bind. # # A string of the form: 'HOST', 'HOST:PORT', 'unix:PATH'. # An IP is a valid HOST. # # backlog - The number of pending connections. This refers # to the number of clients that can be waiting to be # served. Exceeding this number results in the client # getting an error when attempting to connect. It should # only affect servers under significant load. # # Must be a positive integer. Generally set in the 64-2048 # range. # import os port = int(os.environ.get('PORT', 5000)) bind = '0.0.0.0:{}'.format(port) backlog = 2048 reload = True # # Worker processes # # workers - The number of worker processes that this server # should keep alive for handling requests. # # A positive integer generally in the 2-4 x $(NUM_CORES) # range. You'll want to vary this a bit to find the best # for your particular application's work load. # # worker_class - The type of workers to use. The default # sync class should handle most 'normal' types of work # loads. You'll want to read # http://docs.gunicorn.org/en/latest/design.html#choosing-a-worker-type # for information on when you might want to choose one # of the other worker classes. # # A string referring to a Python path to a subclass of # gunicorn.workers.base.Worker. The default provided values # can be seen at # http://docs.gunicorn.org/en/latest/settings.html#worker-class # # worker_connections - For the eventlet and gevent worker classes # this limits the maximum number of simultaneous clients that # a single process can handle. # # A positive integer generally set to around 1000. # # timeout - If a worker does not notify the master process in this # number of seconds it is killed and a new worker is spawned # to replace it. # # Generally set to thirty seconds. Only set this noticeably # higher if you're sure of the repercussions for sync workers. # For the non sync workers it just means that the worker # process is still communicating and is not tied to the length # of time required to handle a single request. # # keepalive - The number of seconds to wait for the next request # on a Keep-Alive HTTP connection. # # A positive integer. Generally set in the 1-5 seconds range. # workers = 4 worker_class = 'sync' worker_connections = 1000 timeout = 100 keepalive = 2 # # spew - Install a trace function that spews every line of Python # that is executed when running the server. This is the # nuclear option. # # True or False # spew = False # # Server mechanics # # daemon - Detach the main Gunicorn process from the controlling # terminal with a standard fork/fork sequence. # # True or False # # pidfile - The path to a pid file to write # # A path string or None to not write a pid file. # # user - Switch worker processes to run as this user. # # A valid user id (as an integer) or the name of a user that # can be retrieved with a call to pwd.getpwnam(value) or None # to not change the worker process user. # # group - Switch worker process to run as this group. # # A valid group id (as an integer) or the name of a user that # can be retrieved with a call to pwd.getgrnam(value) or None # to change the worker processes group. # # umask - A mask for file permissions written by Gunicorn. Note that # this affects unix socket permissions. # # A valid value for the os.umask(mode) call or a string # compatible with int(value, 0) (0 means Python guesses # the base, so values like "0", "0xFF", "0022" are valid # for decimal, hex, and octal representations) # # tmp_upload_dir - A directory to store temporary request data when # requests are read. This will most likely be disappearing soon. # # A path to a directory where the process owner can write. Or # None to signal that Python should choose one on its own. # daemon = False pidfile = None umask = 0 user = None group = None tmp_upload_dir = None # # Logging # # logfile - The path to a log file to write to. # # A path string. "-" means log to stdout. # # loglevel - The granularity of log output # # A string of "debug", "info", "warning", "error", "critical" # errorlog = '-' loglevel = 'info' accesslog = '-' access_log_format = '%(t)s "%(r)s" %(s)s Time: %(L)ss' # # Process naming # # proc_name - A base to use with setproctitle to change the way # that Gunicorn processes are reported in the system process # table. This affects things like 'ps' and 'top'. If you're # going to be running more than one instance of Gunicorn you'll # probably want to set a name to tell them apart. This requires # that you install the setproctitle module. # # A string or None to choose a default of something like 'gunicorn'. # proc_name = None # # Server hooks # # post_fork - Called just after a worker has been forked. # # A callable that takes a server and worker instance # as arguments. # # pre_fork - Called just prior to forking the worker subprocess. # # A callable that accepts the same arguments as after_fork # # pre_exec - Called just prior to forking off a secondary # master process during things like config reloading. # # A callable that takes a server instance as the sole argument. # def post_fork(server, worker): server.log.info("Worker spawned (pid: %s)", worker.pid) def pre_fork(server, worker): pass def pre_exec(server): server.log.info("Forked child, re-executing.") def when_ready(server): server.log.info("Server is ready. Spawning workers") def worker_int(worker): worker.log.info("worker received INT or QUIT signal") ## get traceback info import threading, sys, traceback id2name = dict([(th.ident, th.name) for th in threading.enumerate()]) code = [] for threadId, stack in sys._current_frames().items(): code.append("\n# Thread: %s(%d)" % (id2name.get(threadId,""), threadId)) for filename, lineno, name, line in traceback.extract_stack(stack): code.append('File: "%s", line %d, in %s' % (filename, lineno, name)) if line: code.append(" %s" % (line.strip())) worker.log.debug("\n".join(code)) def worker_abort(worker): worker.log.info("worker received SIGABRT signal")
mit
gvaduha/homebrew
csharp/wtf/MainForm.cs
3386
using System; using System.Collections; using System.Collections.Generic; using System.Windows.Forms; namespace wtf { public partial class MainForm : Form { private Dictionary<string, string> _templateFiles; private Dictionary<string, Variable> _variables; private bool _caseSensitiveRegex; public MainForm() { InitializeComponent(); } private void InitializeControls() { variableListbox.Items.AddRange(new ArrayList(_variables.Keys).ToArray()); templateListbox.Items.AddRange(new ArrayList(_templateFiles.Keys).ToArray()); if (variableListbox.Items.Count > 0) variableListbox.SelectedIndex = 0; if (templateListbox.Items.Count > 0) templateListbox.SelectedIndex = 0; RefreshValueControls(); } internal void Configure(Configuration config) { _templateFiles = new Dictionary<string,string>(); foreach (var item in config.TemplateFiles) _templateFiles.Add(System.IO.Path.GetFileName(item), item); _variables = config.Variables; _caseSensitiveRegex = config.IsCaseSensitiveRegex; InitializeControls(); } #region "Form event processing private void OpenSrcButtonClick(object sender, EventArgs e) { var dlg = new OpenFileDialog { Filter = @"Word documents (*.doc;*.docx;*.rtf;*.txt;*.html)|*.doc*;*.rtf;*.txt;*.htm*|All files (*.*)|*.*" }; var result = dlg.ShowDialog(); if (result == DialogResult.OK) { Cursor.Current = Cursors.WaitCursor; srcFileTextbox.Text = dlg.FileName; ClearVariables(); var text = Logic.GetAllDocumentText(srcFileTextbox.Text); text = text.Replace("\r", "\r\n").Replace("\n\n", "\n"); //Dirty hack Logic.AssignVariables(text, ref _variables, _caseSensitiveRegex); RefreshValueControls(); Cursor.Current = Cursors.Default; } } private void ProcessButtonClick(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; _variables[variableListbox.SelectedItem.ToString()].Value = variableTextBox.Text; Logic.CreateDocumentFromTemplate(_templateFiles[templateListbox.SelectedItem.ToString()], _variables); Cursor.Current = Cursors.Default; } private void VariableListboxSelectionChangeCommitted(object sender, EventArgs e) { variableTextBox.Text = _variables[variableListbox.SelectedItem.ToString()].Value; } private void SetVarButtonClick(object sender, EventArgs e) { _variables[variableListbox.SelectedItem.ToString()].Value = variableTextBox.Text; } private void InsertClipboardButtonClick(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; srcFileTextbox.Text = ""; ClearVariables(); Logic.AssignVariables(Clipboard.GetText(), ref _variables, _caseSensitiveRegex); RefreshValueControls(); Cursor.Current = Cursors.Default; } #endregion private void ClearVariables() { foreach (var item in _variables.Values) item.Value = ""; } private void RefreshValueControls() { if (variableListbox.Items.Count > 0) variableListbox.SelectedIndex = 0; VariableListboxSelectionChangeCommitted(this, null); } } }
mit
VProfirov/Telerik-Academy
Telerik-Academy/Module 1/[02] CSharp Advanced and CSS/[performance improvement versions] C# Advanced/C# Advanced v0.1/Arrays/Combinatorics/Permutation.cs
1318
 namespace Combinatorics { using System.Collections.Generic; using System.Text; public class Permutation { private int length; private int range; StringBuilder permutations; public Permutation(int length) { this.length = length; this.range = length; this.permutations = new StringBuilder(); } public string GetAllPermutations() { int[] temp = new int[this.length]; bool[] used = new bool[this.length]; Permute(temp, used, 0); return this.permutations.ToString(); } private void Permute(int[] array, bool[] used, int currentIndex) { if (currentIndex == array.Length) { this.permutations.AppendLine(string.Format("{0}{1}{2}", "{", string.Join(", ", array), "}")); return; } for (int number = 1; number <= range; number++) { if (!used[number - 1]) { used[number - 1] = true; array[currentIndex] = number; Permute(array, used, currentIndex + 1); used[number - 1] = false; } } } } }
mit
quantumpayments/media
lib/handlers/random.js
3185
module.exports = handler var debug = require('debug')('qpm_media:random') var fs = require('fs') var qpm_media = require('qpm_media') var Negotiator = require('negotiator') var wc = require('webcredits') var wc_db = require('wc_db') var qpm_ui = require('qpm_ui'); function handler(req, res) { var origin = req.headers.origin; if (origin) { res.setHeader('Access-Control-Allow-Origin', origin); } var defaultCurrency = res.locals.config.currency || 'https://w3id.org/cc#bit'; var source = req.body.source; var destination = req.body.destination; var currency = req.body.currency || defaultCurrency; var amount = req.body.amount; var timestamp = null; var description = req.body.description; var context = req.body.context; if (!req.session.userId) { res.send('must be authenticated') return } var source = req.session.userId if (!req.session.userId) { res.send('must be authenticated') return } var config = res.locals.config var cost = 25 var faucetURI = 'https://w3id.org/cc#faucet' var sequelize = wc_db.getConnection(config.db); wc.getBalance(source, sequelize, config, function(err, ret){ if (err) { console.error(err); } else { console.log(ret); var balance = ret if (balance > cost) { var credit = {}; credit["https://w3id.org/cc#source"] = req.session.userId credit["https://w3id.org/cc#amount"] = cost credit["https://w3id.org/cc#currency"] = 'https://w3id.org/cc#bit' credit["https://w3id.org/cc#destination"] = faucetURI balance -= cost wc.insert(credit, res.locals.sequelize, res.locals.config, function(err, ret) { if (err) { res.write(err); } else { qpm_media.getRandomImage(function(err, ret){ if (err) { console.error(err) } else { console.log(ret) var availableMediaTypes = ['text/html', 'text/plain', 'application/json'] var negotiator = new Negotiator(req) var mediaType = negotiator.mediaType(availableMediaTypes) console.log(mediaType) if (ret === null) { ret = 0 } var image = ret[0][0].uri res.status(200) res.header('Content-Type', mediaType) if (mediaType === 'text/html') { config.ui.image = image config.ui.balance = balance res.render('pages/random_rate', { ui : config.ui }) } else if ( mediaType === 'application/json' ) { res.write('{ "image" : "'+image+'"}') res.end() } else if ( mediaType === 'text/plain' ) { res.write(image) res.end() } } sequelize.close() }) } }); } else { res.statusCode = 402; res.send('HTTP 402! This resource has paid access control!') } } sequelize.close(); }); }
mit
ata/latumentent
protected/migrations/m110117_102801_user_add_fullname_column.php
238
<?php class m110117_102801_user_add_fullname_column extends CDbMigration { public function up() { $this->addColumn('user','fullname','string NOT NULL'); } public function down() { $this->dropColumn('user','fullname'); } }
mit
TrollCoin2/TrollCoin-2.0
src/qt/locale/bitcoin_fa.ts
122484
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fa" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About TrollCoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;TrollCoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The TrollCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:eay@cryptsoft.com&quot;&gt;eay@cryptsoft.com&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>برای ویرایش نشانی یا برچسب دوبار کلیک کنید</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>ایجاد نشانی جدید</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>نشانی انتخاب شده را در حافظهٔ سیستم کپی کن!</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-43"/> <source>These are your TrollCoin 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 line="+53"/> <source>&amp;Copy Address</source> <translation>&amp;کپی نشانی</translation> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a TrollCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation>حذف نشانی انتخاب‌شده از لیست</translation> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified TrollCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>&amp;حذف</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+66"/> <source>Copy &amp;Label</source> <translation>کپی و برچسب‌&amp;گذاری</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;ویرایش</translation> </message> <message> <location line="+248"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>پروندهٔ نوع CSV جداشونده با کاما (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation>برچسب</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>نشانی</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(بدون برچسب)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>پنجرهٔ گذرواژه</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>گذرواژه را وارد کنید</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>گذرواژهٔ جدید</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>تکرار گذرواژهٔ جدید</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation>رمزنگاری کیف پول</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>انجام این عملیات نیازمند گذرواژهٔ کیف پول شما برای باز کردن قفل آن است.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>باز کردن قفل کیف پول</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>انجام این عملیات نیازمند گذرواژهٔ کیف پول شما برای رمزگشایی کردن آن است.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>رمزگشایی کیف پول</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>تغییر گذرواژه</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>گذرواژهٔ قدیمی و جدید کیف پول را وارد کنید.</translation> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation>تأیید رمزنگاری کیف پول</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 COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>آیا مطمئن هستید که می‌خواهید کیف پول خود را رمزنگاری کنید؟</translation> </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>مهم: هر نسخهٔ پشتیبانی که تا کنون از کیف پول خود تهیه کرده‌اید، باید با کیف پول رمزنگاری شدهٔ جدید جایگزین شود. به دلایل امنیتی، پروندهٔ قدیمی کیف پول بدون رمزنگاری، تا زمانی که از کیف پول رمزنگاری‌شدهٔ جدید استفاده نکنید، غیرقابل استفاده خواهد بود.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>هشدار: کلید Caps Lock روشن است!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>کیف پول رمزنگاری شد</translation> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>TrollCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>رمزنگاری کیف پول با خطا مواجه شد</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>رمزنگاری کیف پول بنا به یک خطای داخلی با شکست مواجه شد. کیف پول شما رمزنگاری نشد.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>گذرواژه‌های داده شده با هم تطابق ندارند.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>بازگشایی قفل کیف‌پول با شکست مواجه شد</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>گذرواژهٔ وارد شده برای رمزگشایی کیف پول نادرست بود.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>رمزگشایی ناموفق کیف پول</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>گذرواژهٔ کیف پول با موفقیت عوض شد.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation>&amp;امضای پیام...</translation> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation>نمایش بررسی اجمالی کیف پول</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;تراکنش‌ها</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>مرور تاریخچهٔ تراکنش‌ها</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation>&amp;خروج</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>خروج از برنامه</translation> </message> <message> <location line="+4"/> <source>Show information about TrollCoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>دربارهٔ &amp;کیوت</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>نمایش اطلاعات دربارهٔ کیوت</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;تنظیمات...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;رمزنگاری کیف پول...</translation> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation>&amp;پیشتیبان‌گیری از کیف پول...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;تغییر گذرواژه...</translation> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-55"/> <source>Send coins to a TrollCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Modify configuration options for TrollCoin</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation>تهیهٔ پشتیبان از کیف پول در یک مکان دیگر</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>تغییر گذرواژهٔ مورد استفاده در رمزنگاری کیف پول</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>پنجرهٔ ا&amp;شکال‌زدایی</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>باز کردن کنسول خطایابی و اشکال‌زدایی</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>با&amp;زبینی پیام...</translation> </message> <message> <location line="-214"/> <location line="+555"/> <source>TrollCoin</source> <translation type="unfinished"/> </message> <message> <location line="-555"/> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <location line="+193"/> <source>&amp;About TrollCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;نمایش/ عدم نمایش</translation> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>&amp;File</source> <translation>&amp;پرونده</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;تنظیمات</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;کمک‌رسانی</translation> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation>نوارابزار برگه‌ها</translation> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation>[شبکهٔ آزمایش]</translation> </message> <message> <location line="+0"/> <location line="+58"/> <source>TrollCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to TrollCoin network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message> <location line="-812"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+277"/> <source>Up to date</source> <translation>وضعیت به‌روز</translation> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation>به‌روز رسانی...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>تراکنش ارسال شد</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>تراکنش دریافت شد</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>تاریخ: %1 مبلغ: %2 نوع: %3 نشانی: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid TrollCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>کیف پول &lt;b&gt;رمزنگاری شده&lt;/b&gt; است و هم‌اکنون &lt;b&gt;باز&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>کیف پول &lt;b&gt;رمزنگاری شده&lt;/b&gt; است و هم‌اکنون &lt;b&gt;قفل&lt;/b&gt; است</translation> </message> <message> <location line="+24"/> <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 numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation><numerusform>%n ساعت</numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation><numerusform>%n روز</numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <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="+23"/> <source>Error</source> <translation type="unfinished"/> </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="+69"/> <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="+324"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. TrollCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+110"/> <source>Network Alert</source> <translation>پیام شبکه</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>مبلغ:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+537"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>نشانی</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>تأیید شده</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-500"/> <source>Copy address</source> <translation>کپی نشانی</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>کپی برچسب</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>کپی مقدار</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>کپی شناسهٔ تراکنش</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <location line="+66"/> <source>(no label)</source> <translation>(بدون برچسب)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>ویرایش نشانی</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;برچسب</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;نشانی</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>نشانی دریافتی جدید</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>نشانی ارسالی جدید</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>ویرایش نشانی دریافتی</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>ویرایش نشانی ارسالی</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>نشانی وارد شده «%1» در حال حاضر در دفترچه وجود دارد.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid TrollCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>نمی‌توان کیف پول را رمزگشایی کرد.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>ایجاد کلید جدید با شکست مواجه شد.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>TrollCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </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>گزینه‌ها</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;عمومی</translation> </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. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>پرداخت &amp;کارمزد تراکنش</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start TrollCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start TrollCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;شبکه</translation> </message> <message> <location line="+6"/> <source>Automatically open the TrollCoin 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>نگاشت درگاه شبکه با استفاده از پروتکل &amp;UPnP</translation> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation>آ&amp;ی‌پی پراکسی:</translation> </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>&amp;درگاه:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>درگاه پراکسی (مثال 9050)</translation> </message> <message> <location line="-57"/> <source>Connect to the TrollCoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS5 proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+90"/> <source>&amp;Window</source> <translation>&amp;پنجره</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>تنها بعد از کوچک کردن پنجره، tray icon را نشان بده.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;کوچک کردن به سینی به‌جای نوار وظیفه</translation> </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>مخفی کردن در نوار کناری به‌جای خروج هنگام بستن پنجره. زمانی که این گزینه فعال است، برنامه فقط با استفاده از گزینهٔ خروج در منو قابل بسته شدن است.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>کوچک کردن &amp;در زمان بسته شدن</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;نمایش</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>زبان &amp;رابط کاربری:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting TrollCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;واحد نمایش مبالغ:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>انتخاب واحد پول مورد استفاده برای نمایش در پنجره‌ها و برای ارسال سکه.</translation> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to select the coin outputs randomly or with minimal coin age.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Minimize weight consumption (experimental)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;تأیید</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;لغو</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+47"/> <source>default</source> <translation>پیش‌فرض</translation> </message> <message> <location line="+148"/> <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 TrollCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>آدرس پراکسی داده شده صحیح نیست.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>فرم</translation> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the TrollCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-173"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-113"/> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>تراز علی‌الحساب شما</translation> </message> <message> <location line="+80"/> <source>Immature:</source> <translation>نارسیده:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>تراز استخراج شده از معدن که هنوز بالغ نشده است</translation> </message> <message> <location line="+23"/> <source>Total:</source> <translation>جمع کل:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>تراز کل فعلی شما</translation> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;تراکنش‌های اخیر&lt;/b&gt;</translation> </message> <message> <location line="-118"/> <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 line="-32"/> <source>Total of coins that was staked, 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>ناهمگام</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start trollcoin: 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 type="unfinished"/> </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>نام کلاینت</translation> </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"/> <source>N/A</source> <translation>ناموجود</translation> </message> <message> <location line="-194"/> <source>Client version</source> <translation>نسخهٔ کلاینت</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;اطلاعات</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>نسخهٔ OpenSSL استفاده شده</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>زمان آغاز به کار</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>شبکه</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>تعداد ارتباطات</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>زنجیرهٔ بلوک‌ها</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>تعداد فعلی بلوک‌ها</translation> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-383"/> <source>Last block time</source> <translation>زمان آخرین بلوک</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>با&amp;ز کردن</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the TrollCoin-Qt help message to get a list with possible TrollCoin 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>&amp;کنسول</translation> </message> <message> <location line="-237"/> <source>Build date</source> <translation>ساخت تاریخ</translation> </message> <message> <location line="-104"/> <source>TrollCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>TrollCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation>فایلِ لاگِ اشکال زدایی</translation> </message> <message> <location line="+7"/> <source>Open the TrollCoin 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>پاکسازی کنسول</translation> </message> <message> <location filename="../rpcconsole.cpp" line="+325"/> <source>Welcome to the TrollCoin 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>دکمه‌های بالا و پایین برای پیمایش تاریخچه و &lt;b&gt;Ctrl-L&lt;/b&gt; برای پاک کردن صفحه.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>برای نمایش یک مرور کلی از دستورات ممکن، عبارت &lt;b&gt;help&lt;/b&gt; را بنویسید.</translation> </message> <message> <location line="+127"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>ارسال سکه</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>مبلغ:</translation> </message> <message> <location line="+35"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>ارسال به چند دریافت‌کنندهٔ به‌طور همزمان</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;دریافت‌کنندهٔ جدید</translation> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>پاکسازی &amp;همه</translation> </message> <message> <location line="+24"/> <source>Balance:</source> <translation>تزار:</translation> </message> <message> <location line="+47"/> <source>Confirm the send action</source> <translation>عملیات ارسال را تأیید کنید</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;ارسال</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-174"/> <source>Enter a TrollCoin address (e.g. TiWpJ6o9Y3XX16bRNirG5TRqP4tcECEdbK)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>کپی مقدار</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+87"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>ارسال سکه را تأیید کنید</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>نشانی گیرنده معتبر نیست؛ لطفا دوباره بررسی کنید.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>مبلغ پرداخت باید بیشتر از ۰ باشد.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>میزان پرداخت از تراز شما بیشتر است.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>با احتساب هزینهٔ %1 برای هر تراکنش، مجموع میزان پرداختی از مبلغ تراز شما بیشتر می‌شود.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>یک نشانی تکراری پیدا شد. در هر عملیات ارسال، به هر نشانی فقط مبلغ می‌توان ارسال کرد.</translation> </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> <message> <location line="+247"/> <source>WARNING: Invalid TrollCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(بدون برچسب)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</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>A&amp;مبلغ :</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>پرداخ&amp;ت به:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. TiWpJ6o9Y3XX16bRNirG5TRqP4tcECEdbK)</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>برای این نشانی یک برچسب وارد کنید تا در دفترچهٔ آدرس ذخیره شود</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;برچسب:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </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>چسباندن نشانی از حافظهٔ سیستم</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 type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a TrollCoin address (e.g. TiWpJ6o9Y3XX16bRNirG5TRqP4tcECEdbK)</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>امضاها - امضا / تأیید یک پیام</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>ا&amp;مضای پیام</translation> </message> <message> <location line="-118"/> <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>برای احراز اینکه پیام‌ها از جانب شما هستند، می‌توانید آن‌ها را با نشانی خودتان امضا کنید. مراقب باشید چیزی که بدان اطمینان ندارید را امضا نکنید زیرا حملات فیشینگ ممکن است بخواهند از.پیامی با امضای شما سوءاستفاده کنند. تنها مواردی را که حاوی اطلاعات دقیق و قابل قبول برای شما هستند امضا کنید.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. TiWpJ6o9Y3XX16bRNirG5TRqP4tcECEdbK)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>چسباندن نشانی از حافظهٔ سیستم</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>پیامی را که می‌خواهید امضا کنید در اینجا وارد کنید</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>امضای فعلی را به حافظهٔ سیستم کپی کن</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this TrollCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>بازنشانی تمام فیلدهای پیام</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>پاک &amp;کردن همه</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;شناسایی پیام</translation> </message> <message> <location line="-64"/> <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>برای شناسایی پیام، نشانیِ امضا کننده و متن پیام را وارد کنید. (مطمئن شوید که فاصله‌ها، تب‌ها و خطوط را عیناً کپی می‌کنید.) مراقب باشید در امضا چیزی بیشتر از آنچه در پیام می‌بینید وجود نداشته باشد تا فریب دزدان اینترنتی و حملات از نوع MITM را نخورید.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. TiWpJ6o9Y3XX16bRNirG5TRqP4tcECEdbK)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified TrollCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>بازنشانی تمام فیلدهای پیام</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a TrollCoin address (e.g. TiWpJ6o9Y3XX16bRNirG5TRqP4tcECEdbK)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>برای ایجاد یک امضای جدید روی «امضای پیام» کلیک کنید</translation> </message> <message> <location line="+3"/> <source>Enter TrollCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+85"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>نشانی وارد شده نامعتبر است.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>لطفاً نشانی را بررسی کنید و دوباره تلاش کنید.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>نشانی وارد شده به هیچ کلیدی اشاره نمی‌کند.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>عملیات باز کرن قفل کیف پول لغو شد.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>کلید خصوصی برای نشانی وارد شده در دسترس نیست.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>امضای پیام با شکست مواجه شد.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>پیام امضا شد.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>امضا نمی‌تواند کدگشایی شود.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>لطفاً امضا را بررسی نموده و دوباره تلاش کنید.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>امضا با خلاصهٔ پیام مطابقت ندارد.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>شناسایی پیام با شکست مواجه شد.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>پیام شناسایی شد.</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation>باز تا %1</translation> </message> <message> <location line="+6"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/آفلاین</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/تأیید نشده</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 تأییدیه</translation> </message> <message> <location line="+17"/> <source>Status</source> <translation>وضعیت</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>، پخش از طریق %n گره</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>منبع</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>تولید شده</translation> </message> <message> <location line="+5"/> <location line="+13"/> <source>From</source> <translation>فرستنده</translation> </message> <message> <location line="+1"/> <location line="+19"/> <location line="+58"/> <source>To</source> <translation>گیرنده</translation> </message> <message> <location line="-74"/> <location line="+2"/> <source>own address</source> <translation>آدرس شما</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>برچسب</translation> </message> <message> <location line="+34"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>بدهی</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>بلوغ در %n بلوک دیگر</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>پذیرفته نشد</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>اعتبار</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>هزینهٔ تراکنش</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>مبلغ خالص</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>پیام</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>نظر</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>شناسهٔ تراکنش</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 77 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>اطلاعات اشکال‌زدایی</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>تراکنش</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>ورودی‌ها</translation> </message> <message> <location line="+21"/> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>درست</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>نادرست</translation> </message> <message> <location line="-202"/> <source>, has not been successfully broadcast yet</source> <translation>، هنوز با موفقیت ارسال نشده</translation> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+67"/> <source>unknown</source> <translation>ناشناس</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>جزئیات تراکنش</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>این پانل شامل توصیف کاملی از جزئیات تراکنش است</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>نوع</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>نشانی</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation>باز شده تا %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>تأیید شده (%1 تأییدیه)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>باز برای %n بلوک دیگر</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>این بلوک از هیچ همتای دیگری دریافت نشده است و احتمال می‌رود پذیرفته نشود!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>تولید شده ولی قبول نشده</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>دریافت‌شده با</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>دریافت‌شده از</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>ارسال‌شده به</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>پر داخت به خودتان</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>استخراج‌شده</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(ناموجود)</translation> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>وضعیت تراکنش. نشانگر را روی این فیلد نگه دارید تا تعداد تأییدیه‌ها نشان داده شود.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>تاریخ و ساعت دریافت تراکنش.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>نوع تراکنش.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>نشانی مقصد تراکنش.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>مبلغ کسر شده و یا اضافه شده به تراز.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation>همه</translation> </message> <message> <location line="-16"/> <source>Today</source> <translation>امروز</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>این هفته</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>این ماه</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>ماه گذشته</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>امسال</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>محدوده...</translation> </message> <message> <location line="+12"/> <source>Received with</source> <translation>دریافت‌شده با </translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>ارسال به</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>به خودتان</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>استخراج‌شده</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>دیگر</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>برای جست‌‌وجو نشانی یا برچسب را وارد کنید</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>مبلغ حداقل</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>کپی نشانی</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>کپی برچسب</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>کپی مقدار</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>کپی شناسهٔ تراکنش</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>ویرایش برچسب</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>نمایش جزئیات تراکنش</translation> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>پروندهٔ نوع CSV جداشونده با کاما (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>تأیید شده</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>نوع</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>برچسب</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>نشانی</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>مبلغ</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>شناسه</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>محدوده:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>به</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+212"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+171"/> <source>TrollCoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>استفاده:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or trollcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>نمایش لیست فرمان‌ها</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>راهنمایی در مورد یک دستور</translation> </message> <message> <location line="-145"/> <source>Options:</source> <translation>گزینه‌ها:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: trollcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: trollcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>مشخص کردن دایرکتوری داده‌ها</translation> </message> <message> <location line="-25"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=trollcoinrpc 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;TrollCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>تنظیم اندازهٔ کَش پایگاه‌داده برحسب مگابایت (پیش‌فرض: ۲۵)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Listen for connections on &lt;port&gt; (default: 15000 or testnet: 25000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>حداکثر &lt;n&gt; اتصال با همتایان برقرار شود (پیش‌فرض: ۱۲۵)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>اتصال به یک گره برای دریافت آدرس‌های همتا و قطع اتصال پس از اتمام عملیات</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>آدرس عمومی خود را مشخص کنید</translation> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>حد آستانه برای قطع ارتباط با همتایان بدرفتار (پیش‌فرض: ۱۰۰)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>مدت زمان جلوگیری از اتصال مجدد همتایان بدرفتار، به ثانیه (پیش‌فرض: ۸۴۶۰۰)</translation> </message> <message> <location line="-35"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>هنگام تنظیم پورت RPC %u برای گوش دادن روی IPv4 خطایی رخ داده است: %s</translation> </message> <message> <location line="+62"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 17000 or testnet: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Accept command line and JSON-RPC commands</source> <translation>پذیرش دستورات خط فرمان و دستورات JSON-RPC</translation> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation>اجرا در پشت زمینه به‌صورت یک سرویس و پذیرش دستورات</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>استفاده از شبکهٔ آزمایش</translation> </message> <message> <location line="-23"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>پذیرش اتصالات از بیرون (پیش فرض:1 بدون پراکسی یا اتصال)</translation> </message> <message> <location line="-28"/> <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="+93"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>هشدار: مبلغ paytxfee بسیار بالایی تنظیم شده است! این مبلغ هزینه‌ای است که شما برای تراکنش‌ها پرداخت می‌کنید.</translation> </message> <message> <location line="-103"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong TrollCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <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="-16"/> <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="-34"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation>بستن گزینه ایجاد</translation> </message> <message> <location line="-67"/> <source>Connect only to the specified node(s)</source> <translation>تنها در گره (های) مشخص شده متصل شوید</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>آدرس آی.پی. خود را شناسایی کنید (پیش فرض:1 در زمان when listening وno -externalip)</translation> </message> <message> <location line="+101"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>شنیدن هر گونه درگاه انجام پذیر نیست. ازlisten=0 برای اینکار استفاده کیند.</translation> </message> <message> <location line="-2"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-89"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>حداکثر بافر دریافت شده بر اساس اتصال &lt;n&gt;* 1000 بایت (پیش فرض:5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>حداکثر بافر دریافت شده بر اساس اتصال &lt;n&gt;* 1000 بایت (پیش فرض:1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>تنها =به گره ها در شبکه متصا شوید &lt;net&gt; (IPv4, IPv6 or Tor)</translation> </message> <message> <location line="+30"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>گزینه ssl (به ویکیbitcoin برای راهنمای راه اندازی ssl مراجعه شود)</translation> </message> <message> <location line="-38"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>اطلاعات ردگیری/اشکال‌زدایی را به جای فایل لاگ اشکال‌زدایی به کنسول بفرستید</translation> </message> <message> <location line="+34"/> <source>Set maximum block size in bytes (default: 7000000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>حداقل سایز بلاک بر اساس بایت تنظیم شود (پیش فرض: 0)</translation> </message> <message> <location line="-34"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>فایل debug.log را در startup مشتری کوچک کن (پیش فرض:1 اگر اشکال زدایی روی نداد)</translation> </message> <message> <location line="-41"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>(میلی ثانیه )فاصله ارتباط خاص</translation> </message> <message> <location line="+28"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>از UPnP برای شناسایی درگاه شنیداری استفاده کنید (پیش فرض:0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>از UPnP برای شناسایی درگاه شنیداری استفاده کنید (پیش فرض:1 در زمان شنیدن)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC شناسه برای ارتباطات</translation> </message> <message> <location line="+54"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <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>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <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="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>هشدار: این نسخه قدیمی است، روزآمدسازی مورد نیاز است</translation> </message> <message> <location line="-52"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-59"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC عبارت عبور برای ارتباطات</translation> </message> <message> <location line="-47"/> <source>Connect through SOCKS5 proxy</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>از آدرس آی پی خاص JSON-RPC قبول ارتباطات</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>(127.0.0.1پیش فرض: ) &amp;lt;ip&amp;gt; دادن فرمانها برای استفاده گره ها روی</translation> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>زمانی که بهترین بلاک تغییر کرد، دستور را اجرا کن (%s در cmd با block hash جایگزین شده است)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>هنگامی که یک تراکنش در کیف پولی رخ می دهد، دستور را اجرا کن(%s در دستورات بوسیله ی TxID جایگزین می شود)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <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>Upgrade wallet to latest format</source> <translation>wallet را به جدیدترین فرمت روزآمد کنید</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation> (100پیش فرض:)&amp;lt;n&amp;gt; گذاشتن اندازه کلید روی </translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>اسکان مجدد زنجیر بلوکها برای گم والت معامله</translation> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Keep at most &lt;n&gt; MiB of unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>JSON-RPCبرای ارتباطات استفاده کنید OpenSSL (https)</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation> (server.certپیش فرض: )گواهی نامه سرور</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>(server.pemپیش فرض: ) کلید خصوصی سرور</translation> </message> <message> <location line="+5"/> <source>Error: Unsupported argument -socks found. Setting SOCKS version isn&apos;t possible anymore, only SOCKS5 proxies are supported.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Initialization sanity check failed. TrollCoin is shutting down.</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <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="-168"/> <source>This help message</source> <translation>پیام کمکی</translation> </message> <message> <location line="+104"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>امکان اتصال به %s از این رایانه وجود ندارد ( bind returned error %d, %s)</translation> </message> <message> <location line="-129"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>به DNS اجازه بده تا برای addnode ، seednode و اتصال جستجو کند</translation> </message> <message> <location line="+125"/> <source>Loading addresses...</source> <translation>بار گیری آدرس ها</translation> </message> <message> <location line="-10"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>خطا در بارگیری wallet.dat: کیف پول خراب شده است</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of TrollCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart TrollCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>خطا در بارگیری wallet.dat</translation> </message> <message> <location line="-15"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>آدرس پراکسی اشتباه %s</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>شبکه مشخص شده غیرقابل شناسایی در onlynet: &apos;%s&apos;</translation> </message> <message> <location line="+3"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>آدرس قابل اتصال- شناسایی نیست %s</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>آدرس خارجی قابل اتصال- شناسایی نیست %s</translation> </message> <message> <location line="-22"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>میزان وجه اشتباه برای paytxfee=&lt;میزان وجه&gt;: %s</translation> </message> <message> <location line="+58"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>میزان وجه اشتباه</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>بود جه نا کافی </translation> </message> <message> <location line="-40"/> <source>Loading block index...</source> <translation>بار گیری شاخص بلوک</translation> </message> <message> <location line="-109"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>به اتصال یک گره اضافه کنید و اتصال را باز نگاه دارید</translation> </message> <message> <location line="+124"/> <source>Unable to bind to %s on this computer. TrollCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Minimize weight consumption (experimental) (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. TrollCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Loading wallet...</source> <translation>بار گیری والت</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>امکان تنزل نسخه در wallet وجود ندارد</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>آدرس پیش فرض قابل ذخیره نیست</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>اسکان مجدد</translation> </message> <message> <location line="+2"/> <source>Done loading</source> <translation>بار گیری انجام شده است</translation> </message> <message> <location line="-159"/> <source>To use the %s option</source> <translation>برای استفاده از %s از انتخابات</translation> </message> <message> <location line="+186"/> <source>Error</source> <translation>خطا</translation> </message> <message> <location line="-18"/> <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>%s، شما باید یک rpcpassword را در فایل پیکربندی تنظیم کنید :⏎%s⏎ اگر فایل ایجاد نشد، یک فایل فقط متنی ایجاد کنید. </translation> </message> </context> </TS>
mit
juunas11/mean_store
lib/tests/unit/server/authSpec.js
1613
/* jshint expr: true */ var chai = require('chai'), should = chai.should(), sinonChai = require('sinon-chai'), sinon = require('sinon'), auth = require('../../../config/auth'); chai.use(sinonChai); describe("Auth methods: ", function(){ describe("isAuthenticated", function(){ it("calls next if authenticated", function(){ var isAuthenticated = sinon.stub(); isAuthenticated.returns(true); var req = { isAuthenticated : isAuthenticated }; var res = {}; var next = sinon.spy(); auth.isAuthenticated(req, res, next); next.should.have.been.calledOnce; }); it("sends 401 if not authenticated", function(){ var req = { isAuthenticated : sinon.stub().returns(false) }; var res = { sendStatus : sinon.spy() }; var next = sinon.spy(); auth.isAuthenticated(req, res, next); next.should.not.have.been.called; res.sendStatus.should.have.been.calledWith(401); }); }); describe("isAdmin", function(){ it("allows admins access", function(){ var req = { isAuthenticated : sinon.stub().returns(true), user : { role : 'admin' } }; var res = {}; var next = sinon.spy(); auth.isAdmin(req, res, next); next.should.have.been.calledOnce; }); it("denies non-admins access", function(){ var req = { isAuthenticated : sinon.stub().returns(true), user : { role : 'customer' } }; var res = { sendStatus : sinon.spy() }; var next = sinon.spy(); auth.isAdmin(req, res, next); next.should.not.have.been.called; res.sendStatus.should.have.been.calledWith(401); }); }); });
mit
hadicodes/NYT-React-Search
server.js
1301
// Include Server Dependencies var express = require("express"); var bodyParser = require("body-parser"); var logger = require("morgan"); var mongoose = require("mongoose"); // Create Instance of Express var app = express(); // Sets an initial port. We'll use this later in our listener var PORT = process.env.PORT || 3000; // Run Morgan for Logging app.use(logger("dev")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.text()); app.use(bodyParser.json({ type: "application/vnd.api+json" })); //use public folder to serve static files. app.use(express.static("./public")); // Require the routes from articlescontroller.js require("./controllers/articlesController.js")(app); // ------------------------------------------------- // MongoDB Configuration (Change this URL to your own DB) mongoose.connect("mongodb://heroku_r9j0591l:2kre4ch7t2bf7vtqp11ep0qupf@ds129090.mlab.com:29090/heroku_r9j0591l"); var db = mongoose.connection; db.on("error", function(err) { console.log("Mongoose Error: ", err); }); db.once("open", function() { console.log("Mongoose connection successful."); }); // ------------------------------------------------- // Listener app.listen(PORT, function() { console.log("App listening on PORT: " + PORT); });
mit
kiyoaki/bitflyer-api-dotnet-client
BitFlyer.Apis/ResponseData/CryptoCurrencyAddress.cs
584
using System.Runtime.Serialization; using System.Text; using Utf8Json; namespace BitFlyer.Apis { public class CryptoCurrencyAddress { [DataMember(Name = "type")] public AddresseType Type { get; set; } [DataMember(Name = "currency_code")] public CurrencyCode CurrencyCode { get; set; } [DataMember(Name = "address")] public string Address { get; set; } public override string ToString() { return Encoding.UTF8.GetString(JsonSerializer.Serialize(this)); } } }
mit
wootaw/domain-flow
spec/support/contract_flow.rb
880
class ContractFlow include DomainFlow::Map def initialize initial :drafting status :drafting do to :drafted, event: :draft, who: [Department.new(:business)] end status :drafted do to :submitted, event: :pre, who: [Department.new(:manage)] to :drafting, event: :pre_turn, who: [Department.new(:manage)] end status :submitted do to :signing, event: :last, who: [Role.new(:boss)] to :drafting, event: :last_turn, who: [Role.new(:boss)] end status :signing do to :c_signed, event: :c_sign, who: [Department.new(:business)] to :b_signed, event: :b_sign, who: [Role.new(:boss)] end status :c_signed do to :signed, event: :b_sign, who: [Role.new(:boss)] end status :b_signed do to :signed, event: :c_sign, who: [Department.new(:business)] end end end
mit
minimumcut/UnnamedEngine
UnnamedEngine/Sources/Engine/Base/Types/Component.cpp
141
#include "Component.h" ComponentFlag ComponentStatics::SingletonGroupCounter = 0; ComponentFlag ComponentStatics::StaticGroupCounter = 0;
mit
aa6my/GRR
fuel/modules/fuel/assets/js/editors/ckeditor/plugins/fuellink/plugin.js
4318
/** * Basic sample plugin inserting abbreviation elements into CKEditor editing area. * * Created out of the CKEditor Plugin SDK: * http://docs.ckeditor.com/#!/guide/plugin_sdk_sample_1 */ // Register the plugin within the editor. CKEDITOR.plugins.add( 'fuellink', { // Register the icons. icons: 'anchor', // The plugin initialization logic goes inside this method. init: function( editor ) { editor.on( 'doubleclick', function( evt ) { var element = evt.data.element; if ( element.is( 'a' ) && !element.getAttribute( '_cke_realelement' )){ editor.execCommand('fuellink'); } }, null,null,100); // Define an editor command that opens our dialog. editor.addCommand( 'fuellink', { exec: function( editor ) { var selection = editor.getSelection(); element = selection.getStartElement(); var input, target, title, className, linkPdfs; if ( element ) { element = element.getAscendant( 'a', true ); if (element){ var href = element.getAttribute('href'); input = href.replace(/^\{site_url\('(.*)'\)\}/g, function(match, contents, offset, s) { return contents; } ); target = element.getAttribute('target'); title = element.getAttribute('title'); className = element.getAttribute('class'); } } linkPdfs = editor.element.getAttribute('data-link_pdfs'); var selected = selection.getSelectedText(); var selectedElem = selection.getSelectedElement(); if (selectedElem){ selected = selectedElem.getOuterHtml(); } myMarkItUpSettings.displayLinkEditWindow(selected, {input: input, title: title, target: target, className: className, linkPdfs:linkPdfs}, function(replace){ editor.insertHtml(replace); }) } }); // Register selection change handler for the unlink button. editor.on( 'selectionChange', function( evt ) { /* * Despite our initial hope, document.queryCommandEnabled() does not work * for this in Firefox. So we must detect the state by element paths. */ var command = editor.getCommand( 'fuelunlink' ), element = evt.data.path.lastElement.getAscendant( 'a', true ); if ( element && element.getName() == 'a' && element.getAttribute( 'href' ) ) command.setState( CKEDITOR.TRISTATE_OFF ); else command.setState( CKEDITOR.TRISTATE_DISABLED ); } ); // Define an editor command that opens our dialog. editor.addCommand( 'fuelunlink', { exec: function( editor ) { /* * execCommand( 'unlink', ... ) in Firefox leaves behind <span> tags at where * the <a> was, so again we have to remove the link ourselves. (See #430) * * TODO: Use the style system when it's complete. Let's use execCommand() * as a stopgap solution for now. */ var selection = editor.getSelection(), bookmarks = selection.createBookmarks(), ranges = selection.getRanges(), rangeRoot, element; for ( var i = 0 ; i < ranges.length ; i++ ) { rangeRoot = ranges[i].getCommonAncestor( true ); element = rangeRoot.getAscendant( 'a', true ); if ( !element ) continue; ranges[i].selectNodeContents( element ); } selection.selectRanges( ranges ); editor.document.$.execCommand( 'unlink', false, null ); selection.selectBookmarks( bookmarks ); } }); // // Create a toolbar button that executes the above command. editor.ui.addButton( 'FUELLink', { // // The text part of the button (if available) and tooptip. label: 'Insert Link', // // The command to execute on click. command: 'fuellink', // // The button placement in the toolbar (toolbar group name). toolbar: 'insert' }); // // Create a toolbar button that executes the above command. editor.ui.addButton( 'FUELUnlink', { // // The text part of the button (if available) and tooptip. label: 'Remove Link', // // The command to execute on click. command: 'fuelunlink', // // The button placement in the toolbar (toolbar group name). toolbar: 'insert' }); } });
mit
namics/eslint-config-namics
test/es5-disable-styles/rules/style/linebreak-style.js
132
// DESCRIPTION = disallow mixed 'LF' and 'CRLF' as linebreaks // STATUS = 0 // <!START // END!> document.window.append("", null);
mit
CarrKnight/MacroIIDiscrete
src/main/java/model/utilities/scheduler/TrueRandomScheduler.java
12048
/* * Copyright (c) 2014 by Ernesto Carrella * Licensed under MIT license. Basically do what you want with it but cite me and don't sue me. Which is just politeness, really. * See the file "LICENSE" for more information */ package model.utilities.scheduler; import com.google.common.base.Preconditions; import ec.util.MersenneTwisterFast; import model.MacroII; import model.utilities.ActionOrder; import sim.engine.SimState; import sim.engine.Steppable; import java.util.ArrayList; import java.util.EnumMap; import java.util.LinkedList; import java.util.List; /** * <h4>Description</h4> * <p/> This is the re-implementation of the random scheduler using arraylists. It is more random than the random queue * because each steppable is chosen uniformly at random every time (while the random queue gives each steppable a random "ordering" * which might let one chain of events happen very late. * <p/> * <p/> * <h4>Notes</h4> * Created with IntelliJ * <p/> * <p/> * <h4>References</h4> * * @author carrknight * @version 2013-02-15 * @see */ public class TrueRandomScheduler implements Steppable, PhaseScheduler { /** * where we store every possible action! * Each action order has an array list for every possible priority value */ private EnumMap<ActionOrder,List<Steppable>[]> steppablesByPhase; private EnumMap<ActionOrder,Long> timePerPhase; /** * The randomizer */ private final MersenneTwisterFast randomizer; /** * the maximum number of simulation days */ private int simulationDays; /** * which phase are we in? */ private ActionOrder currentPhase = ActionOrder.DAWN; final private ArrayList<PrioritySteppablePair> tomorrowSamePhase; final private ArrayList<FutureAction> futureActions; public TrueRandomScheduler(int simulationDays, MersenneTwisterFast randomizer) { this.randomizer = randomizer; this.simulationDays = simulationDays; timePerPhase = new EnumMap<>(ActionOrder.class); for(ActionOrder o : ActionOrder.values()) timePerPhase.put(o,0l); //initialize the enums resetMap(); //initialize tomorrow schedule tomorrowSamePhase = new ArrayList<>(); futureActions = new ArrayList<>(); } private void resetMap() { steppablesByPhase = new EnumMap<>(ActionOrder.class); for(ActionOrder order :ActionOrder.values()) { //put the array List<Steppable>[] array = order.isToRandomize() ? new LinkedList[Priority.values().length] : new ArrayList[Priority.values().length]; steppablesByPhase.put(order,array); //populate the array for(Priority p : Priority.values()) array[p.ordinal()]= order.isToRandomize()? new LinkedList<>() : new ArrayList<Steppable>(); } } /** * Go through a "day" in the model. It self schedules to do it again tomorrow */ @Override public void step(SimState simState) { assert simState instanceof MacroII; MersenneTwisterFast random = simState.random; //grab the random from the simstate assert tomorrowSamePhase.isEmpty() : "things shouldn't be scheduled here"; //for each phase for(ActionOrder phase : ActionOrder.values()) { long timeAtStart = System.currentTimeMillis(); currentPhase = phase; //currentPhase! int highestPriority = getHighestPriority(phase); while(highestPriority != -1) //as long as there are still things to do at any priority { //get the highest priority steppables List<Steppable> steppables = steppablesByPhase.get(phase)[highestPriority]; assert steppables != null; assert !steppables.isEmpty(); //take a random highest priority action and do it. //but don't bother randomizing for gui and clean up data final int index = currentPhase.isToRandomize() ? 0 :randomizer.nextInt(steppables.size()); Steppable steppable = steppables.remove(index); assert steppable != null; //act nau!!! steppable.step(simState); //update priority (low priority can still schedule stuff to happen at high priority so we need to keep checking) highestPriority = getHighestPriority(phase); } //add all the steppables that reserved a spot for tomorrow, same phase allocateTomorrowSamePhaseActions(phase); long duration = System.currentTimeMillis() - timeAtStart; timePerPhase.put(phase, timePerPhase.get(phase) + duration); //go to the next phase! } //prepare for tomorrow prepareForTomorrow(); //see you tomorrow if(((MacroII)simState).getMainScheduleTime() <= simulationDays) simState.schedule.scheduleOnceIn(1,this); } private void allocateTomorrowSamePhaseActions(ActionOrder phase) { List<Steppable>[] current= steppablesByPhase.get(phase); for(PrioritySteppablePair pair : tomorrowSamePhase) { current[pair.getPriority().ordinal()].add(pair.getSteppable()); } tomorrowSamePhase.clear(); //here we kept all steppables that are called to act the same phase tomorrow! } /** * gets the index of the steppable with the highest priority in a given action order * @param phase the action phase * @return the highest priority or -1 if there are none. */ public int getHighestPriority(ActionOrder phase) { List<Steppable> steppablesByPriority[] = steppablesByPhase.get(phase); for(int i=0; i<steppablesByPriority.length;i++) { assert steppablesByPriority[i] !=null; //because they are created once and never destroyed, all the arraylists should not be null if(!steppablesByPriority[i].isEmpty()) return i; } return -1; } private void prepareForTomorrow() { assert tomorrowSamePhase.isEmpty() : "things shouldn't be scheduled here"; //set phase to dawn currentPhase = ActionOrder.DAWN; //check for delayed actions LinkedList<FutureAction> toRemove = new LinkedList<>(); for(FutureAction futureAction : futureActions) { boolean ready = futureAction.spendOneDay(); if(ready) { scheduleSoon(futureAction.getPhase(),futureAction.getAction(),futureAction.getPriority()); toRemove.add(futureAction); } } futureActions.removeAll(toRemove); } /** * schedule the event to happen when the next specific phase comes up! * @param phase which phase the action should be performed? * @param action the action taken! */ @Override public void scheduleSoon( ActionOrder phase, Steppable action){ scheduleSoon(phase, action,Priority.STANDARD); } /** * Schedule as soon as this phase occurs * * @param phase the phase i want the action to occur in * @param action the steppable that should be called * @param priority the action priority */ @Override public void scheduleSoon( ActionOrder phase, Steppable action, Priority priority) { steppablesByPhase.get(phase)[priority.ordinal()].add(action); } /** * force the schedule to record this action to happen tomorrow. * This is allowed only if you are at a phase (say PRODUCTION) and you want the action to occur tomorrow at the same phase (PRODUCTION) * @param phase which phase the action should be performed? * @param action the action taken! */ @Override public void scheduleTomorrow(ActionOrder phase, Steppable action){ this.scheduleTomorrow(phase, action,Priority.STANDARD); } /** * Schedule tomorrow assuming the phase passed is EXACTLY the current phase * This is allowed only if you are at a phase (say PRODUCTION) and you want the action to occur tomorrow at the same phase (PRODUCTION) * @param phase the phase i want the action to occur in * @param action the steppable that should be called * @param priority the action priority */ @Override public void scheduleTomorrow(ActionOrder phase, Steppable action, Priority priority) { assert phase.equals(currentPhase); //put it among the steppables of that phase tomorrowSamePhase.add(new PrioritySteppablePair(action,priority)); } /** * * @param phase The action order at which this action should be scheduled * @param action the action to schedule * @param daysAway how many days from now should it be scheduled */ @Override public void scheduleAnotherDay( ActionOrder phase, Steppable action, int daysAway) { scheduleAnotherDay(phase, action, daysAway,Priority.STANDARD); } /** * Schedule in as many days as passed (at priority standard) * * @param phase the phase i want the action to occur in * @param action the steppable that should be called * @param daysAway how many days into the future should this happen * @param priority the action priority */ @Override public void scheduleAnotherDay( ActionOrder phase, Steppable action, int daysAway, Priority priority) { Preconditions.checkArgument(daysAway > 0, "Days away must be positive"); futureActions.add(new FutureAction(phase,action,priority,daysAway)); } /** * This is similar to scheduleAnotherDay except that rather than passing a fixed number of days we pass the probability * of the event being scheduled each day after the first (days away is always at least one!) * @param phase The action order at which this action should be scheduled * @param action the action to schedule * @param probability the daily probability of this action happening. So if you pass 15% then each day has a probability of 15% of triggering this action */ @Override public void scheduleAnotherDayWithFixedProbability( ActionOrder phase, Steppable action, float probability) { scheduleAnotherDayWithFixedProbability(phase, action, probability,Priority.STANDARD); } /** * @param probability each day we check against this fixed probability to know if we will step on this action today * @param phase the phase i want the action to occur in * @param action the steppable that should be called * @param */ @Override public void scheduleAnotherDayWithFixedProbability( ActionOrder phase, Steppable action, float probability, Priority priority) { Preconditions.checkArgument(probability > 0f && probability <=1f, "probability has to be in (0,1]"); int daysAway = 0; do{ daysAway++; } while (!randomizer.nextBoolean(probability)); scheduleAnotherDay(phase,action,daysAway,priority); } @Override public ActionOrder getCurrentPhase() { return currentPhase; } public void clear() { steppablesByPhase.clear(); resetMap(); tomorrowSamePhase.clear(); futureActions.clear(); currentPhase = ActionOrder.DAWN; } public void setSimulationDays(int simulationDays) { this.simulationDays = simulationDays; } public EnumMap<ActionOrder, List<Steppable>[]> getSteppablesByPhase() { return steppablesByPhase; } public EnumMap<ActionOrder, Long> getTimePerPhase() { return timePerPhase; } }
mit
aingc/EPMS
js/library/HealthBar.standalone.js
4340
/** Copyright (c) 2015 Belahcen Marwane (b.marwane@gmail.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. */ var HealthBar = function(game, providedConfig) { this.game = game; this.setupConfiguration(providedConfig); this.setPosition(this.config.x, this.config.y); this.drawBackground(); this.drawHealthBar(); this.setFixedToCamera(this.config.isFixedToCamera); }; HealthBar.prototype.constructor = HealthBar; HealthBar.prototype.setupConfiguration = function (providedConfig) { this.config = this.mergeWithDefaultConfiguration(providedConfig); this.flipped = this.config.flipped; }; HealthBar.prototype.mergeWithDefaultConfiguration = function(newConfig) { var defaultConfig= { width: 250, height: 40, x: 0, y: 0, bg: { color: '#651828' }, bar: { color: '#FEFF03' }, animationDuration: 200, flipped: false, isFixedToCamera: false }; return mergeObjetcs(defaultConfig, newConfig); }; function mergeObjetcs(targetObj, newObj) { for (var p in newObj) { try { targetObj[p] = newObj[p].constructor==Object ? mergeObjetcs(targetObj[p], newObj[p]) : newObj[p]; } catch(e) { targetObj[p] = newObj[p]; } } return targetObj; } HealthBar.prototype.drawBackground = function() { var bmd = this.game.add.bitmapData(this.config.width, this.config.height); bmd.ctx.fillStyle = this.config.bg.color; bmd.ctx.beginPath(); bmd.ctx.rect(0, 0, this.config.width, this.config.height); bmd.ctx.fill(); this.bgSprite = this.game.add.sprite(this.x, this.y, bmd); this.bgSprite.anchor.set(0.5); if(this.flipped){ this.bgSprite.scale.x = -1; } }; HealthBar.prototype.drawHealthBar = function() { var bmd = this.game.add.bitmapData(this.config.width, this.config.height); bmd.ctx.fillStyle = this.config.bar.color; bmd.ctx.beginPath(); bmd.ctx.rect(0, 0, this.config.width, this.config.height); bmd.ctx.fill(); this.barSprite = this.game.add.sprite(this.x - this.bgSprite.width/2, this.y, bmd); this.barSprite.anchor.y = 0.5; if(this.flipped){ this.barSprite.scale.x = -1; } }; HealthBar.prototype.setPosition = function (x, y) { this.x = x; this.y = y; if(this.bgSprite !== undefined && this.barSprite !== undefined){ this.bgSprite.position.x = x; this.bgSprite.position.y = y; this.barSprite.position.x = x - this.config.width/2; this.barSprite.position.y = y; } }; HealthBar.prototype.setPercent = function(newValue){ if(newValue < 0) newValue = 0; if(newValue > 100) newValue = 100; var newWidth = (newValue * this.config.width) / 100; this.setWidth(newWidth); }; HealthBar.prototype.setWidth = function(newWidth){ if(this.flipped) { newWidth = -1 * newWidth; } this.game.add.tween(this.barSprite).to( { width: newWidth }, this.config.animationDuration, Phaser.Easing.Linear.None, true); }; HealthBar.prototype.setFixedToCamera = function(fixedToCamera) { this.bgSprite.fixedToCamera = fixedToCamera; this.barSprite.fixedToCamera = fixedToCamera; }; HealthBar.prototype.kill = function() { this.bgSprite.kill(); this.barSprite.kill(); };
mit
ramcn/demo3
venv/lib/python3.4/site-packages/oauth2_provider/compat.py
1052
""" The `compat` module provides support for backwards compatibility with older versions of django and python.. """ from __future__ import unicode_literals import django from django.conf import settings # urlparse in python3 has been renamed to urllib.parse try: from urlparse import urlparse, parse_qs, parse_qsl, urlunparse except ImportError: from urllib.parse import urlparse, parse_qs, parse_qsl, urlunparse try: from urllib import urlencode, unquote_plus except ImportError: from urllib.parse import urlencode, unquote_plus # Django 1.5 add support for custom auth user model if django.VERSION >= (1, 5): AUTH_USER_MODEL = settings.AUTH_USER_MODEL else: AUTH_USER_MODEL = 'auth.User' try: from django.contrib.auth import get_user_model except ImportError: from django.contrib.auth.models import User get_user_model = lambda: User # Django's new application loading system try: from django.apps import apps get_model = apps.get_model except ImportError: from django.db.models import get_model
mit
jeffjen/machine
lib/machine/recipe.go
4230
package machine const SWARM_MASTER = `version: "2" services: swarm_manager: image: swarm:latest command: manage -H tcp://0.0.0.0:2376 --tlsverify --tlscacert /conf/ca.pem --tlscert /conf/server-cert.pem -tlskey /conf/server-key.pem nodes://{{ range $index, $element := .Nodes }}{{ if $index }}{{ print "," $element }}{{ else }}{{ $element }}{{ end }}{{ end }} network_mode: host ports: - "2376:2376" volumes: - {{ .Certpath }}/ca.pem:/conf/ca.pem - {{ .Certpath }}/server-cert.pem:/conf/server-cert.pem - {{ .Certpath }}/server-key.pem:/conf/server-key.pem - {{ .Certpath }}/.swarm:/.swarm ` const COMPOSE = `--- provision: - name: Install utility package action: - script: 00-install-pkg sudo: true - name: Install Docker Engine action: - script: 01-install-docker-engine sudo: true - name: Configure system setting action: - script: 02-config-system sudo: true - name: Configure Docker Volume action: - cmd: 'pvcreate /dev/xvdb && vgcreate data /dev/xvdb && lvcreate -l 100%FREE -n docker data' shell: true sudo: true - cmd: 'mkfs.ext4 /dev/data/docker' sudo: true - cmd: 'echo "/dev/mapper/data-docker /data ext4 rw 0 0" >>/etc/fstab' shell: true sudo: true - name: Configure Docker Engine archive: - src: docker.daemon.json dst: /etc/docker/daemon.json sudo: true action: - cmd: 'service docker stop' sudo: true - cmd: 'rm -f /etc/docker/key.json' sudo: true - cmd: 'rm -rf /var/lib/docker' sudo: true --- provision: - name: Configure swap action: - cmd: 'fallocate -l 8G /swapfile && chmod 600 /swapfile && mkswap /swapfile' shell: true sudo: true - cmd: 'echo "/swapfile none swap sw 0 0" >>/etc/fstab' shell: true sudo: true --- provision: - name: Clean up and Shutdown action: - cmd: shutdown -h now sudo: true ` const INSTALL_PKG = `#!/bin/bash # install common utility packages apt-get update && apt-get upgrade -y && apt-get install -y \ curl \ htop \ lvm2 \ ntp \ jq ` const INSTALL_DOCKER_ENGINE = `#!/bin/bash apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D apt-get update && apt-get install -y apt-transport-https linux-image-extra-$(uname -r) echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" | tee /etc/apt/sources.list.d/docker.list apt-get update && apt-get install -y docker-engine ` const CONFIGURE_SYSTEM = `#!/bin/bash truncate -s0 /etc/sysctl.conf echo "vm.overcommit_memory = 1" >>/etc/sysctl.conf cat <<\EOF >/etc/init.d/disable-transparent-hugepages #!/bin/sh ### BEGIN INIT INFO # Provides: disable-transparent-hugepages # Required-Start: $local_fs # Required-Stop: # X-Start-Before: docker # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Disable Linux transparent huge pages # Description: Disable Linux transparent huge pages, to improve # database performance. ### END INIT INFO case $1 in start) if [ -d /sys/kernel/mm/transparent_hugepage ]; then thp_path=/sys/kernel/mm/transparent_hugepage elif [ -d /sys/kernel/mm/redhat_transparent_hugepage ]; then thp_path=/sys/kernel/mm/redhat_transparent_hugepage else return 0 fi echo 'never' > ${thp_path}/enabled echo 'never' > ${thp_path}/defrag unset thp_path ;; esac EOF chmod 755 /etc/init.d/disable-transparent-hugepages update-rc.d disable-transparent-hugepages defaults # Adjust server network limit echo "net.ipv4.ip_local_port_range = 1024 65535" >>/etc/sysctl.conf echo "net.ipv4.tcp_rmem = 4096 4096 16777216" >>/etc/sysctl.conf echo "net.ipv4.tcp_wmem = 4096 4096 16777216" >>/etc/sysctl.conf echo "net.ipv4.tcp_max_syn_backlog = 4096" >>/etc/sysctl.conf echo "net.ipv4.tcp_syncookies = 1" >>/etc/sysctl.conf echo "net.core.somaxconn = 1024" >>/etc/sysctl.conf echo "fs.file-max = 100000" >>/etc/sysctl.conf echo "* - nofile 100000" >>/etc/security/limits.conf ` const DOCKER_DAEMON_CONFIG = `{ "hosts": [ "unix:///var/run/docker.sock" ], "graph": "/data" } `
mit
NataliaDymnikova/akka.scheduler
cluster-scheduler-akka/src/main/java/natalia/dymnikova/cluster/scheduler/impl/FlowHelper.java
3108
// Copyright (c) 2016 Natalia Dymnikova // Available via the MIT license // // 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 natalia.dymnikova.cluster.scheduler.impl; import natalia.dymnikova.cluster.scheduler.akka.Flow.SetFlow; import natalia.dymnikova.cluster.scheduler.akka.Flow.Stage; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static java.lang.Integer.compare; import static java.util.stream.Collectors.toList; /** * */ public class FlowHelper { public static Stage getStage(final SetFlow flow, final int id) { return getStageList(flow.getStage()).stream().filter(stage -> stage.getId() == id).findFirst().get(); } public static int getNextStageNumber(final SetFlow flow, final int id) { final Stage stage = getStage(flow, id); return getNumberOfStage(flow, nextStage(stage, flow.getStage())); } public static List<Integer> getPreviousStageNumbers(final SetFlow flow, final int id) { return getPreviousStages(flow, id).stream().map(stage -> getNumberOfStage(flow, stage)).collect(toList()); } public static int getNumberOfStage(final SetFlow flow, final Stage stage) { return stage.getId(); } public static List<Stage> getPreviousStages(final SetFlow flow, final int id) { return getStage(flow, id).getStagesList(); } public static List<Stage> getStageList(final Stage stage) { final List<Stage> stages = new ArrayList<>(); stages.addAll(stage.getStagesList().stream().flatMap(st -> getStageList(st).stream()).collect(toList())); stages.add(0, stage); return stages; } private static Stage nextStage(final Stage toFind, final Stage currStage) { if (currStage.getStagesList().contains(toFind)) { return currStage; } else { return currStage.getStagesList().stream() .map(st -> nextStage(toFind, st)) .filter(st -> st != null) .findAny() .orElse(null); } } }
mit
FelipeOliver/StockManager
src/main/java/com/stockmanager/repositories/VendaRepository.java
276
package com.stockmanager.repositories; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.stockmanager.entities.Venda; @Repository public interface VendaRepository extends CrudRepository<Venda, Long>{ }
mit
fredefl/The-Haiku-Poem-Machine
application/views/tags_view.php
4048
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><?php echo $this->lang->line("info_app_title");?> - <?php echo $this->lang->line("pages_home");?></title> <link rel="stylesheet" href="<?php echo $base_url.$css_url; ?>style.css"> <link rel="stylesheet" href="<?php echo $base_url.$css_url; ?>styles.css"> <link rel="stylesheet" href="<?php echo $base_url.$css_url; ?>chosen.css" /> <link rel="stylesheet" href="<?php echo $jquery_ui_css_url;?>jquery-ui.css"/> <script type="text/javascript"> var translations = { "alert" : "<?= $this->lang->line("errors_alert"); ?>", "missing_fields" : "<?= $this->lang->line("errors_fields_missing"); ?>", "no_sentences_match" : "<?= $this->lang->line("errors_no_sentences_matching"); ?>", "an_error_occured" : "<?= $this->lang->line("errors_an_error_occured"); ?>", "no_results_found" : "<?= $this->lang->line("home_chosen_no_result"); ?>", "unlimited" : "<?= $this->lang->line("home_unlimited"); ?>" } var userLanguage = "<?php echo $this->ui_helper->language; ?>"; var base_url = "<?= $base_url; ?>"; </script> <!--[if lt IE 9]> <script src="<?php echo $base_url.$html5_shiv_url; ?>"></script> <![endif]--> <style type="text/css"> @font-face { font-family: "Bonzai"; src: url(<?php echo $base_url; ?><?php echo $fonts_url;?>bonzai.ttf); } .text{ font-family: "Bonzai"; font-size: 250%; } body { width: 100%; height: auto; } </style> <!--[if lte IE 8]> <style type="text/css"> @font-face { font-family: bonzai; src:url(<?php echo $base_url; ?><?php echo $fonts_url;?>bonzai.eot); } .text{ font-family:bonzai; font-size: 250%; } </style> <![endif]--> </head> <body> <?php if (isset($poems)) { ?> <div id="view"> <?php foreach ($poems as $poem): ?> <div class="box" style="width:480px;"> <p style="font-size:22px;" class="center-text"><strong><?= $poem["title"]; ?></strong></p> <div class="text" style="margin-left:40px;"> <?php foreach ($poem["sentences"] as $sentence): ?> <?= $sentence["sentence"]; ?><br> <?php endforeach; ?> </div> <p><i> - <?= $poem["creator"]; ?> : <?= date($this->lang->line("home_date_time_format"),$poem["time_created"]); ?></i></p> </div> <?php endforeach; ?> </div> <?php } ?> <?php if (!isset($poems)) { ?> <div style="width:813px; margin-left:auto; margin-right:auto;"> <div class="ui-state-error ui-corner-all error" id="error" style="padding: 0 .7em; max-width:300px; margin-left:auto; margin-right:auto;"> <p> <span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span> <strong><?php echo $this->lang->line("errors_alert"); ?>:</strong> <?php switch ($error) { case 'no_poems': echo $this->lang->line("errors_no_poems_found_for_tag"); break; case 'tag_not_found': echo str_replace("{tag}", $tag, $this->lang->line("errors_tag_not_found")); break; } ?> </p> </div> </div> <?php } ?> <script src="<?php echo $jquery_url; ?>"></script> <script src="<?php echo $jquery_ui_js_url; ?>"></script> <script type="text/javascript"> $("button").button(); $('button[href]').live("click",function () { window.location = $(this).attr("href"); }); </script> </body> </html>
mit
airslie/renalware-core
spec/presenters/renalware/admissions/consult_presenter_spec.rb
910
# frozen_string_literal: true require "rails_helper" module Renalware module Admissions describe ConsultPresenter do describe ".location" do it "joins site ward and other location when all present" do site = ConsultSite.new(name: "Site") ward = Hospitals::Ward.new(name: "Ward") consult = Consult.new( consult_site: site, hospital_ward: ward, other_site_or_ward: "Other" ) expect(described_class.new(consult).location).to eq("Site, Ward, Other") end it "returns just #other_site_or_ward when consult site and ward missing" do consult = Consult.new( consult_site: nil, hospital_ward: nil, other_site_or_ward: "Other" ) expect(described_class.new(consult).location).to eq("Other") end end end end end
mit
se-panfilov/betsson_test
e2e/app.po.ts
201
import { browser, by, element } from 'protractor' export class AppPage { navigateTo() { return browser.get('/') } getParagraphText() { return element(by.css('root h1')).getText() } }
mit
vsilent/smarty-bot
core/utils/sys/cpu.py
1807
# vim:syntax=python:sw=4:ts=4:expandtab import re from core.config.settings import logger from core.utils.utils import parse_file def interval(): return 2 SYSINFO = '/sys/class/thermal/' FILE_TEMP = SYSINFO + 'thermal_zone0/temp' RE_CPU = re.compile(r'^cpu MHz\s*:\s*(?P<mhz>\d+).*$') RE_STATS = re.compile(r'^cpu (?P<user>\d+) (?P<system>\d+) (?P<nice>\d+) (?P<idle>\d+).*$') OLD_STATS = dict(user=0, system=0, nice=0, idle=0) def info(): #cpu_vals = parse_file('/proc/cpuinfo', RE_CPU) stat_vals = parse_file('/proc/stat', RE_STATS) temp_vals = '' status = '' try: tf = open(FILE_TEMP) temp_vals = int(tf.read()) / 1000 except Exception, e: logger.exception(e) tf.close() #cpu = '--' #try: #cpu = '/'.join(cpu_vals['mhz']) #except Exception as e: #logger.exception(e) load = '--' try: # convert values to int's stat_vals = dict([(k, int(v[0])) for k, v in stat_vals.items()]) dtotal = stat_vals['user'] - OLD_STATS['user'] + \ stat_vals['system'] - OLD_STATS['system'] + \ stat_vals['nice'] - OLD_STATS['nice'] + \ stat_vals['idle'] - OLD_STATS['idle'] if dtotal > 0: load = 100 - ((stat_vals['idle'] - OLD_STATS['idle']) * 100 / dtotal) loadstr = '%02d' % (load) if load > 50: status = 'critical' elif 20 < load < 50: status = 'medium' else: status = 'normal' OLD_STATS.update(stat_vals) except Exception as e: logger.exception(e) tempr = '--' try: tempr = temp_vals except Exception as e: logger.exception(e) return 'CPU: %s%% temperature [%s] %s' % (loadstr, tempr, status)
mit
chypriote/france-v2
tests/AppBundle/Controller/Player/PlayersMembersControllerTest.php
1855
<?php namespace Tests\AppBundle\Controller\Player; use Symfony\Component\HttpFoundation\Request; use Tests\WebTestCase; class PlayersMembersControllerTest extends WebTestCase { const BASE_URL = '/players'; const PLAYER_TAMOZ_UUID = '5cef176d-1ded-40a7-97a4-a397f9aac16e'; const PLAYER_HYORAI_UUID = '1d18c0fc-9680-41a8-8322-cae311a356aa'; /** * @group smoke * @dataProvider getPlayerMembersPreviousProvider */ public function testGetPlayerMembersPrevious(string $uuid, int $expectedStatusCode) { $this->client->request(Request::METHOD_GET, self::BASE_URL."/{$uuid}/members/previous"); self::assertEquals($expectedStatusCode, $this->client->getResponse()->getStatusCode()); if (200 !== $expectedStatusCode) { return; } } public function getPlayerMembersPreviousProvider(): array { return [ 'Get for existing player' => [self::PLAYER_TAMOZ_UUID, 200], 'Get for non existing player' => ['00000000-0000-0000-0000-000000000000', 404], ]; } /** * @group smoke * @dataProvider getPlayersMembersProvider */ public function testGetPlayersMembers(string $uuid, int $expectedStatusCode) { $this->client->request(Request::METHOD_GET, self::BASE_URL."/{$uuid}/members/previous"); self::assertEquals($expectedStatusCode, $this->client->getResponse()->getStatusCode()); if (200 !== $expectedStatusCode) { return; } dump($this->client->getResponse()->getContent()); } public function getPlayersMembersProvider(): array { return [ 'Get for existing player with memberships' => [self::PLAYER_TAMOZ_UUID, 200, []], 'Get for existing player without memberships' => [self::PLAYER_HYORAI_UUID, 200], 'Get for non existing player' => ['00000000-0000-0000-0000-000000000000', 404], ]; } }
mit
PHP-Geek/aviation-job-portal
application/views/page/list_our_services.php
5983
<style type="text/css"> .table-responsive { width: 100%; margin-bottom: 15px; overflow-y: hidden; -ms-overflow-style: -ms-autohiding-scrollbar; border: 1px solid #ddd; } .table-responsive > .table { margin-bottom: 0; } .table-responsive > .table > thead > tr > th, .table-responsive > .table > tbody > tr > th, .table-responsive > .table > tfoot > tr > th, .table-responsive > .table > thead > tr > td, .table-responsive > .table > tbody > tr > td, .table-responsive > .table > tfoot > tr > td { white-space: nowrap; } .table-responsive > .table-bordered { border: 0; } .table-responsive > .table-bordered > thead > tr > th:first-child, .table-responsive > .table-bordered > tbody > tr > th:first-child, .table-responsive > .table-bordered > tfoot > tr > th:first-child, .table-responsive > .table-bordered > thead > tr > td:first-child, .table-responsive > .table-bordered > tbody > tr > td:first-child, .table-responsive > .table-bordered > tfoot > tr > td:first-child { border-left: 0; } .table-responsive > .table-bordered > thead > tr > th:last-child, .table-responsive > .table-bordered > tbody > tr > th:last-child, .table-responsive > .table-bordered > tfoot > tr > th:last-child, .table-responsive > .table-bordered > thead > tr > td:last-child, .table-responsive > .table-bordered > tbody > tr > td:last-child, .table-responsive > .table-bordered > tfoot > tr > td:last-child { border-right: 0; } .table-responsive > .table-bordered > tbody > tr:last-child > th, .table-responsive > .table-bordered > tfoot > tr:last-child > th, .table-responsive > .table-bordered > tbody > tr:last-child > td, .table-responsive > .table-bordered > tfoot > tr:last-child > td { border-bottom: 0; } .hidden_table_col{ display:none; } .table-drag{ opacity: 0.6; color:white; background-color:blue; } </style> <div class="content-wrapper"> <section class="content-header"> <h1 style="display:inline-block">Increw Services</h1> <ol class="breadcrumb"> <li><a href="<?php echo base_url(); ?>dashboard"><i class="fa fa-dashboard"></i> Dashboard</a></li> <li class="active">Increw Services</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-body table-responsive"> <div> <h4 class="text-info"><i class="fa fa-info-circle"></i> Page items are shown in the following order. To change the order please drag and drop row.</h4></div> <form id="increw_service_form" method="post"> <table id="increw_services_datatable" class="table table-bordered"> <thead> <tr> <th>Title</th> <th>Content</th> <th>Image</th> <th>Status</th> <th>Action</th> <th class="hidden_table_col">ID</th> </tr> </thead> <tbody> <?php foreach ($increw_services_array as $service) { ?> <tr id="our_service_<?php echo $service['increw_service_id']; ?>"> <td><?php echo $service['increw_service_title']; ?></td> <td><a class="popover_link" href="javascript:;" data-container="body" data-toggle="popover" data-placement="right" data-content="<?php echo $service['increw_service_content'] ?>" data-trigger="hover"><?php echo substr($service['increw_service_content'], 0, 80); ?></a></td> <td><a href="<?php echo base_url() . 'uploads/pages/increw_services/' . date('Y/m/d/H/i/s/', strtotime($service['increw_service_created'])) . $service['increw_service_image']; ?>" target="_blank"><img src="<?php echo base_url() . 'uploads/pages/increw_services/' . date('Y/m/d/H/i/s/', strtotime($service['increw_service_created'])) . $service['increw_service_image']; ?>" style="width:50%;"/></a></td> <td><?php echo $service['increw_service_status'] == '1' ? '<input type="checkbox" id="id_' . $service['increw_service_id'] . '" checked="true" onchange="increw_service_status(' . $service['increw_service_id'] . ')"/>' : '<input type="checkbox" id="id_' . $service['increw_service_id'] . '" onchange="increw_service_status(' . $service['increw_service_id'] . ')"/>'; ?></td> <td><a href="<?php echo base_url(); ?>page/edit_our_service/<?php echo $service['increw_service_id']; ?>"><i class="fa fa-pencil-square-o"></i> Edit</a></td> <td class="hidden_table_col"><input type="hidden" name="increw_service_id[]" id="increw_service_id" value="<?php echo $service['increw_service_id']; ?>"/></td> </tr> <?php } ?> </tbody> </table> </form> </div> </div> </section> </div> <script src="<?php echo base_url(); ?>assets/js/jquery.tablednd.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.66.0-2013.10.09/jquery.blockUI.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#increw_services_datatable").tableDnD({ onDragClass: "table-drag", onDrop: function (table, row) { $("#increw_service_form").block(); $.post(base_url + 'page/update_our_service_order', $("#increw_service_form").serialize(), function (data) { if (data === '1') { console.log('done'); } else { console.log('Error'); } $("#increw_service_form").unblock(); }); } }); }); $(".popover_link").popover({html: true, placement: 'auto right'}); function increw_service_status(increw_service_id) { $.post(base_url + 'page/change_increw_service_status', {increw_service_id: increw_service_id, increw_service_status: $("#id_" + increw_service_id).is(':checked')}, function (data) { if (data === '1') { bootbox.alert('Status Changed Successfully.'); } else if (data === '0') { bootbox.alert('Error changing status'); } else { bootbox.alert(data); } }); } </script>
mit
unoegohh/dandm
src/Unoegohh/MarkupBundle/DependencyInjection/Configuration.php
885
<?php namespace Unoegohh\MarkupBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('unoegohh_markup'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
mit
saedar/fate_character_manager
test/helpers/attribution_helper_test.rb
78
require 'test_helper' class AttributionHelperTest < ActionView::TestCase end
mit
askheaves/Its.Cqrs
Domain.Sql/CommandScheduler/CommandSchedulerDbContext.cs
4479
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Diagnostics; using System.Linq; namespace Microsoft.Its.Domain.Sql.CommandScheduler { [DebuggerStepThrough] public class CommandSchedulerDbContext : DbContext { private static string nameOrConnectionString; static CommandSchedulerDbContext() { Database.SetInitializer(new CommandSchedulerDatabaseInitializer()); } /// <summary> /// Initializes a new instance of the <see cref="CommandSchedulerDbContext"/> class. /// </summary> public CommandSchedulerDbContext() : this(NameOrConnectionString) { } /// <summary> /// Initializes a new instance of the <see cref="CommandSchedulerDbContext"/> class. /// </summary> /// <param name="nameOrConnectionString">Either the database name or a connection string.</param> public CommandSchedulerDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } public virtual DbSet<Clock> Clocks { get; set; } public virtual DbSet<ClockMapping> ClockMappings { get; set; } public virtual DbSet<ScheduledCommand> ScheduledCommands { get; set; } public virtual DbSet<CommandExecutionError> Errors { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new ClockEntityTypeConfiguration()); modelBuilder.Configurations.Add(new ClockMappingsEntityTypeConfiguration()); modelBuilder.Configurations.Add(new CommandExecutionErrorEntityTypeConfiguration()); modelBuilder.Configurations.Add(new ScheduledCommandEntityTypeConfiguration()); // add infrastructure for catchup tracking modelBuilder.Configurations.Add(new ReadModelInfoEntityModelConfiguration.ReadModelInfoEntityTypeConfiguration()); modelBuilder.Configurations.Add(new EventHandlingErrorEntityModelConfiguration.EventHandlingErrorEntityTypeConfiguration()); } public static string NameOrConnectionString { get { return nameOrConnectionString; } set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("The value cannot be null, empty or contain only whitespace."); } nameOrConnectionString = value; } } private class ScheduledCommandEntityTypeConfiguration : EntityTypeConfiguration<ScheduledCommand> { public ScheduledCommandEntityTypeConfiguration() { ToTable("ScheduledCommand", "Scheduler"); HasKey(c => new { c.AggregateId, c.SequenceNumber }); HasRequired(c => c.Clock); Property(c => c.SerializedCommand) .IsRequired(); Ignore(c => c.Result); Ignore(c => c.NonDurable); } } private class ClockEntityTypeConfiguration : EntityTypeConfiguration<Clock> { public ClockEntityTypeConfiguration() { ToTable("Clock", "Scheduler"); Property(c => c.Name) .IsRequired() .HasMaxLength(128); } } private class ClockMappingsEntityTypeConfiguration : EntityTypeConfiguration<ClockMapping> { public ClockMappingsEntityTypeConfiguration() { ToTable("ClockMapping", "Scheduler"); HasRequired(m => m.Clock); Property(c => c.Value) .HasMaxLength(128) .IsRequired(); } } private class CommandExecutionErrorEntityTypeConfiguration : EntityTypeConfiguration<CommandExecutionError> { public CommandExecutionErrorEntityTypeConfiguration() { ToTable("Error", "Scheduler"); HasRequired(e => e.ScheduledCommand); Property(e => e.Error) .IsRequired(); } } } }
mit
alar-saat/XRDv4WSDLConverter
src/main/java/ee/rmit/xrd/AbstractConfiguration.java
4274
package ee.rmit.xrd; import ee.rmit.xrd.wsdl.Wsdl; import ee.rmit.xrd.wsdl.WsdlTemplate; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static ee.rmit.xrd.utils.DomUtils.getDocumentBuilderFactoryClassName; import static ee.rmit.xrd.utils.DomUtils.parseDocument; import static ee.rmit.xrd.utils.LoggerUtils.logInfo; import static ee.rmit.xrd.utils.StringUtils.isBlank; public abstract class AbstractConfiguration { /* for input/output wsdl files, if not set -> 'java.io.tmpdir' */ protected Path wsdlDir; /* JAXP debugging on/off */ protected boolean debug = false; /* producer name used for target namespace in wsdl document -> http://${producer}.x-road.eu */ protected String producerName; /* template wsdl file location -> classpath://, http(s)://, or filesystem */ protected String templateLocation; /* input wsdl file location (extractor, converter) -> classpath://, http(s)://, or filesystem */ protected String wsdlFileLocation; /* constructed template object from 'producerName' and 'templateLocation' */ protected WsdlTemplate template; public void setWsdlDir(Path wsdlDir) { this.wsdlDir = wsdlDir; } public void setJaxpDebuggingOn() { if (!debug) { System.setProperty("jaxp.debug", "1"); } debug = true; } public void setJaxpDebuggingOff() { if (debug) { System.setProperty("jaxp.debug", "0"); } debug = false; } public void setProducerName(String producerName) { this.producerName = producerName; } public void setTemplateLocation(String templateLocation) { this.templateLocation = templateLocation; } protected void setUpWsdlTemplate() { template = new WsdlTemplate(templateLocation, producerName); } protected void logConfig() throws ParserConfigurationException { logInfo("DOM document builder factory class: " + getDocumentBuilderFactoryClassName()); logInfo("JAXP debug: " + (debug ? "on" : "off")); } protected Wsdl createWsdl(String wsdlFile) { if (isBlank(wsdlFile)) { throw new IllegalStateException("WSDL file location undefined"); } wsdlFileLocation = wsdlFile; try { URL url = null; if (wsdlFile.startsWith("classpath://")) { String resourceName = wsdlFile.substring(12); logInfo(String.format("Using custom '%s' as classpath resource", resourceName)); url = Thread.currentThread().getContextClassLoader().getResource(resourceName); if (url == null) { throw new IllegalStateException(String.format("Classpath resource '%s' not found", resourceName)); } } else if (wsdlFile.startsWith("http://") || wsdlFile.startsWith("https://")) { logInfo(String.format("Using HTTP resource '%s'", wsdlFile)); url = new URL(wsdlFile); } else { logInfo(String.format("Using file '%s'", wsdlFile)); Path templateFile = Paths.get(wsdlFile); if (!Files.isRegularFile(templateFile)) { throw new IllegalStateException(String.format("Not a reqular file '%s'", wsdlFile)); } url = templateFile.toUri().toURL(); } return new Wsdl(parseDocument(url)); } catch (IOException | ParserConfigurationException | SAXException e) { throw new IllegalStateException("Cannot create WSDL document", e); } } protected void createWsdlDirIfNotSet() { if (wsdlDir == null) { wsdlDir = Paths.get(System.getProperty("java.io.tmpdir")); } if (!Files.isDirectory(wsdlDir)) { try { Files.createDirectories(wsdlDir); } catch (IOException e) { throw new IllegalStateException("Cannot create directory for WSDL files", e); } } logInfo("WSDLs directory: " + wsdlDir); } }
mit
lovemybamboo/lovemybamboo.github.io
Data Management System/js/js_accuracy_calculation/accuracy_calculation.js
507
/** * Created with JetBrains WebStorm. * User: Luo Bo * Date: 14-9-1 * Time: 下午9:45 * To change this template use File | Settings | File Templates. */ $(document).ready(function () { initTable(); }); function initTable(){ $('#dataTables-data-result').dataTable(); $(".form_datetime").datetimepicker({ language:"zh-CN", format: "yyyy-mm-dd hh:ii", autoclose: true, todayBtn: true, startDate: "2013-02-14 10:00", minuteStep: 10 }); }
mit
calincru/Warlight-AI-Challenge-2-Bot
src/strategies/basicroundstrategy.cpp
1676
// This program is free software licenced under MIT Licence. You can // find a copy of this licence in LICENCE.txt in the top directory of // source code. // // Self #include "basicroundstrategy.hpp" // Project #include "world.hpp" #include "region.hpp" #include "common/basicscore.hpp" // C++ #include <limits> namespace warlightAi { BasicRoundStrategy::BasicRoundStrategy(const World &world, int availableArmies) : RoundStrategy(world, availableArmies) { using common::BasicScore; std::vector<std::pair<RegionPtr, RegionPtr>> myRegOtherRegPairs; // Finds all the adjacent super regions and keep all the (src, dest) pairs // for possible attacks for (auto &myReg : m_world.getRegionsOwnedBy(Player::ME)) for (auto &otherReg : myReg->getNeighbors()) if (otherReg->getOwner() != Player::ME) myRegOtherRegPairs.emplace_back(myReg, otherReg); std::pair<RegionPtr, RegionPtr> maxPair; auto maxScore = std::numeric_limits<int>::lowest(); for (auto &p : myRegOtherRegPairs) { auto score = BasicScore::simulationScore(p.second->getSuperRegion(), availableArmies); if (score > maxScore) { maxScore = score; maxPair = p; } } m_deployments.emplace_back(maxPair.first, availableArmies); m_attacks.emplace_back(maxPair.first, maxPair.second, maxPair.first->getArmies() - 1); } RegIntList BasicRoundStrategy::getDeployments() const { return m_deployments; } RegRegIntList BasicRoundStrategy::getAttacks() const { return m_attacks; } } // namespace warlightAi
mit
iogav/Partner-Center-Java-SDK
PartnerSdk/src/main/java/com/microsoft/store/partnercenter/network/PartnerServiceProxy.java
25278
// ----------------------------------------------------------------------- // <copyright file="PartnerServiceProxy.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter.network; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Locale; import java.util.UUID; import org.apache.http.HttpHost; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.joda.JodaModule; import com.microsoft.store.partnercenter.BasePartnerComponentString; import com.microsoft.store.partnercenter.IPartner; import com.microsoft.store.partnercenter.PartnerService; import com.microsoft.store.partnercenter.errorhandling.DefaultPartnerServiceErrorHandler; import com.microsoft.store.partnercenter.errorhandling.IFailedPartnerServiceResponseHandler; import com.microsoft.store.partnercenter.exception.PartnerErrorCategory; import com.microsoft.store.partnercenter.exception.PartnerException; import com.microsoft.store.partnercenter.exception.PartnerResponseParseException; import com.microsoft.store.partnercenter.logging.PartnerLog; import com.microsoft.store.partnercenter.models.invoices.InvoiceLineItem; import com.microsoft.store.partnercenter.models.utils.KeyValuePair; import com.microsoft.store.partnercenter.requestcontext.IRequestContext; import com.microsoft.store.partnercenter.requestcontext.RequestContext; import com.microsoft.store.partnercenter.requestcontext.RequestContextFactory; import com.microsoft.store.partnercenter.utils.InvoiceLineItemDeserializer; import com.microsoft.store.partnercenter.utils.UriDeserializer; import com.microsoft.store.partnercenter.utils.StringHelper; /** * An implementation of the partner service proxy which automatically serializes request content into JSON payload and * deserializes the response from JSON into the given response type. The type of content that will be passed to the * partner service API.The type of response produced from the partner service API. */ public class PartnerServiceProxy<TRequest, TResponse> extends BasePartnerComponentString implements IPartnerServiceProxy<TRequest, TResponse> { /** * The request context the proxy will use in executing the network calls. */ private IRequestContext requestContext = new RequestContext(); /** * Initializes a new instance of the {@link #PartnerServiceProxy{TRequest, TResponse}} class. * * @param rootPartnerOperations The root partner operations instance. * @param resourcePath The resource path which will be appended to the root URL. * @param errorHandler An optional handler for failed responses. The default will be used if not provided. * @param jsonConverter An optional JSON response converter. The default will be used if not provided. */ public PartnerServiceProxy( TypeReference<TResponse> responseClass, IPartner rootPartnerOperations, String resourcePath ) { this( rootPartnerOperations, resourcePath, null, null ); this.responseClass = responseClass; } /** * Initializes a new instance of the {@link #PartnerServiceProxy{TRequest, TResponse}} class. * * @param rootPartnerOperations The root partner operations instance. * @param resourcePath The resource path which will be appended to the root URL. * @param errorHandler An optional handler for failed responses. The default will be used if not provided. * @param jsonConverter An optional JSON response converter. The default will be used if not provided. */ public PartnerServiceProxy( IPartner rootPartnerOperations, String resourcePath, IFailedPartnerServiceResponseHandler errorHandler, ObjectMapper jsonConverter ) { super( rootPartnerOperations ); if ( this.getPartner().getRequestContext().getRequestId().equals( new UUID( 0, 0 ) ) ) { // there is not request id assigned, generate one and stick to it (consider retries) this.requestContext = RequestContextFactory.getInstance().create( this.getPartner().getRequestContext().getCorrelationId(), UUID.randomUUID(), this.getPartner().getRequestContext().getLocale() ); } else { this.requestContext = this.getPartner().getRequestContext(); } this.setAccept( "application/json" ); this.setContentType( "application/json" ); this.setUriParameters( new ArrayList<KeyValuePair<String, String>>() ); this.setResourcePath( resourcePath ); this.setAdditionalRequestHeaders( new ArrayList<KeyValuePair<String, String>>() ); this.setErrorHandler( errorHandler != null ? errorHandler : new DefaultPartnerServiceErrorHandler() ); this.setJsonConverter(jsonConverter); this.setIsUrlPathAlreadyBuilt( false ); } /** * Gets or sets the assigned Microsoft Id. */ @Override public UUID getRequestId() { return this.requestContext.getRequestId(); } @Override public void setRequestId( UUID value ) { this.requestContext = RequestContextFactory.getInstance().create( this.requestContext.getCorrelationId(), value == new UUID( 0, 0 ) ? UUID.randomUUID() : value ); } /** * Gets or sets the assigned Microsoft correlation Id. */ @Override public UUID getCorrelationId() { return this.requestContext.getCorrelationId(); } @Override public void setCorrelationId( UUID value ) { this.requestContext = RequestContextFactory.getInstance().create( value, this.requestContext.getRequestId() ); } /** * Gets or sets the locale. */ @Override public String getLocale() { return this.requestContext.getLocale(); } @Override public void setLocale( String value ) { this.requestContext = RequestContextFactory.getInstance().create( this.requestContext.getCorrelationId(), this.requestContext.getRequestId(), value ); } /** * Gets or sets the e-tag used for concurrency control. */ private String __IfMatch = new String(); @Override public String getIfMatch() { return __IfMatch; } @Override public void setIfMatch( String value ) { __IfMatch = value; } /** * Gets or sets the request content type. */ private String __ContentType = new String(); @Override public String getContentType() { return __ContentType; } @Override public void setContentType( String value ) { __ContentType = value; } /** * Gets or sets the accepted response type. */ private String __Accept = new String(); @Override public String getAccept() { return __Accept; } @Override public void setAccept( String value ) { __Accept = value; } /** * Gets or sets whether the proxy should build the URL or the URL has already been built. */ private boolean __IsUrlPathAlreadyBuilt; public boolean getIsUrlPathAlreadyBuilt() { return __IsUrlPathAlreadyBuilt; } public void setIsUrlPathAlreadyBuilt( boolean value ) { __IsUrlPathAlreadyBuilt = value; } /** * Gets the additional request headers. */ private Collection<KeyValuePair<String, String>> __AdditionalRequestHeaders = new ArrayList<KeyValuePair<String, String>>(); @Override public Collection<KeyValuePair<String, String>> getAdditionalRequestHeaders() { return __AdditionalRequestHeaders; } public void setAdditionalRequestHeaders( Collection<KeyValuePair<String, String>> value ) { __AdditionalRequestHeaders = value; } /** * Gets a collection of Uri parameters which will be added to the request query string. You can add your own uri * parameters to this collection. */ private Collection<KeyValuePair<String, String>> __UriParameters = new ArrayList<KeyValuePair<String, String>>(); @Override public Collection<KeyValuePair<String, String>> getUriParameters() { return __UriParameters; } public void setUriParameters( Collection<KeyValuePair<String, String>> value ) { __UriParameters = value; } /** * Gets or sets the resource path which will be appended to the root URL. */ private String __ResourcePath = new String(); @Override public String getResourcePath() { // The paths on the configuration json file have slashes on the beginning, // but the next link from the response doesn't. This function removes that // first slash. if (__ResourcePath.startsWith( "/" )) { return __ResourcePath.substring( 1 ); } return __ResourcePath; } @Override public void setResourcePath( String value ) { __ResourcePath = value; } /** * Gets an optional JSON converter to use. */ private ObjectMapper __JsonConverter; public ObjectMapper getJsonConverter() { if ( __JsonConverter == null ) { __JsonConverter = new ObjectMapper(); __JsonConverter.registerModule( new JodaModule() ); __JsonConverter.setDateFormat( new SimpleDateFormat( "yyyy-MM-dd" ) ); __JsonConverter.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS ); __JsonConverter.setSerializationInclusion( Include.NON_NULL ); __JsonConverter.registerModule( new SimpleModule().addDeserializer( InvoiceLineItem.class, new InvoiceLineItemDeserializer() ) ); __JsonConverter.registerModule( new SimpleModule().addDeserializer( URI.class, new UriDeserializer() ) ); __JsonConverter.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } return __JsonConverter; } public void setJsonConverter( ObjectMapper value ) { __JsonConverter = value; } private TypeReference<TResponse> responseClass; /** * Gets or sets the error handler for non successful responses. */ private IFailedPartnerServiceResponseHandler __ErrorHandler; protected IFailedPartnerServiceResponseHandler getErrorHandler() { return __ErrorHandler; } protected void setErrorHandler( IFailedPartnerServiceResponseHandler value ) { __ErrorHandler = value; } /** * Executes a GET request against the partner service. * * @return The GET response. * @throws PartnerException */ @Override public TResponse get() { RequestBuilder request = RequestBuilder.get( this.buildPartnerServiceApiUri() ); return this.send( request ); } /*** * Executes a file content request against the partner service. * * @return: The file content stream. */ public InputStream getFileContent() { try { // ensure the credentials are not expired this.validateCredentials(); RetryableHttpCall retryableHttpCall = new RetryableHttpCall(); CloseableHttpClient httpClient = buildHttpClient(); CloseableHttpResponse response; try { RequestBuilder request = RequestBuilder.get( this.buildPartnerServiceApiUri() ); response = retryableHttpCall.execute( httpClient, request.build() ); } catch ( IOException e ) { throw new PartnerException( e.getMessage(), this.requestContext, PartnerErrorCategory.NOT_SPECIFIED, e ); } if ( response.getStatusLine().getStatusCode() < 400 ) { return response.getEntity().getContent() == null ? null : response.getEntity().getContent(); } else { // handle the failure according to the configured policy throw this.getErrorHandler().handleFailedResponse( response, this.requestContext ); } } catch ( Exception error ) { throw new PartnerException( error.getMessage(), error ); } } /** * Executes a POST request against the partner service. * * @param content The request body content. * @return The POST response. */ @Override public TResponse post( TRequest content ) { RequestBuilder request = RequestBuilder.post( this.buildPartnerServiceApiUri() ); try { request.setEntity( new StringEntity( getJsonConverter().writeValueAsString( content ) ) ); } catch ( UnsupportedEncodingException e ) { throw new PartnerException( "", this.requestContext, PartnerErrorCategory.REQUEST_PARSING ); } catch ( JsonProcessingException e ) { throw new PartnerException( "", this.requestContext, PartnerErrorCategory.REQUEST_PARSING ); } return this.send( request ); } /** * Executes a PATCH request against the partner service. * * @param content The request body content. * @return The PATCH response. */ @Override public TResponse patch( TRequest content ) { RequestBuilder request = RequestBuilder.patch( this.buildPartnerServiceApiUri() ); try { request.setEntity( new StringEntity( getJsonConverter().writeValueAsString( content ) ) ); } catch ( UnsupportedEncodingException e ) { throw new PartnerException( "", this.requestContext, PartnerErrorCategory.REQUEST_PARSING ); } catch ( JsonProcessingException e ) { throw new PartnerException( "", this.requestContext, PartnerErrorCategory.REQUEST_PARSING ); } return this.send( request ); } /** * Executes a PUT request against the partner service. * * @param content The request body content. * @return The PUT response. */ @Override public TResponse put( TRequest content ) { RequestBuilder request = RequestBuilder.put( this.buildPartnerServiceApiUri() ); try { request.setEntity( new StringEntity( getJsonConverter().writeValueAsString( content ) ) ); } catch ( UnsupportedEncodingException e ) { throw new PartnerException( "", this.requestContext, PartnerErrorCategory.REQUEST_PARSING ); } catch ( JsonProcessingException e ) { throw new PartnerException( "", this.requestContext, PartnerErrorCategory.REQUEST_PARSING ); } return this.send( request ); } /** * Executes a DELETE request against the partner service. * * @throws PartnerException */ @Override public void delete() { RequestBuilder request = RequestBuilder.delete( this.buildPartnerServiceApiUri() ); this.send( request ); } /** * Executes a HEAD request against the partner service. * * @throws PartnerException */ @Override public void head() { RequestBuilder request = RequestBuilder.head( this.buildPartnerServiceApiUri() ); this.send( request ); } /** * Builds the HTTP client needed to perform network calls. This method aids in mocking the HttpClient in unit tests * and hence was implemented as protected in order not to expose it to other SDK classes. * * @return A configured HTTP client. */ protected CloseableHttpClient buildHttpClient() { HttpClientBuilder builder = HttpClients.custom().disableContentCompression(); String proxyName = PartnerService.getInstance().getProxyHostName(); Integer proxyPort = PartnerService.getInstance().getProxyPort(); if ( proxyName != null && proxyPort != null ) { builder = builder.setProxy( new HttpHost( proxyName, proxyPort ) ); } return builder.build(); } /** * Sends an HTTP request to the partner service after checking that the credentials are not expired. It will also * handle the response. * * @param httpOperation The HTTP operation to execute. * @return A deserialized HTTP response. */ private TResponse send( RequestBuilder request ) { validateCredentials(); RetryableHttpCall retryableHttpCall = new RetryableHttpCall(); CloseableHttpClient httpClient = buildHttpClient(); addHttpHeaders( request ); CloseableHttpResponse response; try { response = retryableHttpCall.execute( httpClient, request.build() ); } catch ( IOException e ) { throw new PartnerException( e.getMessage(), this.requestContext, PartnerErrorCategory.TIMEOUT, e ); } return this.handleResponse( response ); } private void addHttpHeaders( RequestBuilder request ) { request.setHeader( "MS-Contract-Version", PartnerService.getInstance().getPartnerServiceApiVersion() ); request.setHeader( "MS-RequestId", this.getRequestId().toString() ); request.setHeader( "MS-CorrelationId", this.getCorrelationId().toString() ); request.setHeader( "X-Locale", getLocale() ); if( PartnerService.getInstance().getPartnerServiceApiVersion() != null && PartnerService.getInstance().getPartnerServiceApiVersion().trim().isEmpty() != true ) { request.setHeader( "MS-PartnerCenter-Application", PartnerService.getInstance().getApplicationName() ); } request.setHeader( "MS-PartnerCenter-Client", "Partner Center JAVA SDK" ); request.setHeader( "Authorization", "Bearer " + this.getPartner().getCredentials().getPartnerServiceToken() ); request.setHeader( "Accept", this.getAccept() ); if ( request.getEntity() != null ) { request.setHeader( "Content-Type", this.getContentType() ); } if ( this.getAdditionalRequestHeaders() != null ) { for ( KeyValuePair<String, String> header : this.getAdditionalRequestHeaders() ) { request.setHeader( header.getKey(), header.getValue() ); } } } /** * Ensures that the partner credentials are up to date. * * @return A task that is complete when the verification is done. */ private void validateCredentials() { if ( this.getPartner().getCredentials().isExpired() ) { if ( PartnerService.getInstance().getRefreshCredentialsHandler() != null ) { try { PartnerService.getInstance().getRefreshCredentialsHandler().onCredentialsRefreshNeeded( this.getPartner().getCredentials(), this.requestContext ); } catch ( Exception refreshProblem ) { PartnerLog.getInstance().logError( MessageFormat.format( "Refreshing the credentials has failed: {0}", refreshProblem, Locale.US ) ); throw new PartnerException( "Refreshing the credentials has failed.", this.requestContext, PartnerErrorCategory.UNAUTHORIZED, refreshProblem ); } if ( this.getPartner().getCredentials().isExpired() ) { PartnerLog.getInstance().logError( "The credential refresh mechanism provided expired credentials." ); throw new PartnerException( "The credential refresh mechanism provided expired credentials.", this.requestContext, PartnerErrorCategory.UNAUTHORIZED ); } } else { // we can't refresh the credentials silently, fail with unauthorized PartnerLog.getInstance().logError( "The partner credentials have expired." ); throw new PartnerException( "The partner credentials have expired. Please provide updated credentials.", this.requestContext, PartnerErrorCategory.UNAUTHORIZED ); } } } /** * Handles partner service responses. * * @param response The partner service response. * @return The configured response result. * @throws PartnerException */ private TResponse handleResponse( CloseableHttpResponse response ) { if ( response.getStatusLine().getStatusCode() < 400 ) { String responseBody = null; try { // That string trimming is due to the byte order mark coming on // the beginning of the Json response, after it was changed to UTF-8 TResponse responseObj = null; if ( response.getStatusLine().getStatusCode() != 204 && response.getEntity() != null ){ responseBody = StringHelper.fromInputStream( response.getEntity().getContent(), "UTF-8" ).substring( 1 ); responseObj = getJsonConverter().readValue( responseBody, responseClass ); } response.close(); return responseObj; } catch ( IOException deserializationProblem ) { throw new PartnerResponseParseException( responseBody, this.requestContext, "Could not deserialize response. Detailed message: " + deserializationProblem.getMessage(), deserializationProblem ); } } else { throw __ErrorHandler.handleFailedResponse( response, requestContext ); } } /** * Builds the partner service API Uri based on the configured properties. * * @return The complete partner service API Uri needed to invoke the current operation. */ private URI buildPartnerServiceApiUri() { StringBuilder baseUri = new StringBuilder(PartnerService.getInstance().getApiRootUrl() + "/" + PartnerService.getInstance().getPartnerServiceApiVersion() + "/" + this.getResourcePath()); if (!this.getIsUrlPathAlreadyBuilt()) { baseUri.append( this.buildQueryString() ); } try { return new URI( baseUri.toString() ); } catch ( URISyntaxException e ) { throw new IllegalArgumentException( "Error when trying to form the request URI" ); } } /** * Builds the query string part of the REST API URL. * * @return The query string. */ private String buildQueryString() { StringBuilder queryStringBuilder = new StringBuilder(); if ( !this.getUriParameters().isEmpty() ) { queryStringBuilder.append( "?" ); } for ( KeyValuePair<String, String> queryParameter : this.getUriParameters() ) { if ( queryStringBuilder.length() > 1 ) { // this is not the first query parameter queryStringBuilder.append( "&" ); } queryStringBuilder.append( MessageFormat.format( "{0}={1}", queryParameter.getKey(), queryParameter.getValue(), Locale.US ) ); } return queryStringBuilder.toString(); } }
mit
kssujithcj/TestMobileCenter
node_modules/recursive-fs/index.js
356
exports.readdirr = require('./lib/readdirr').readdirr; exports.rmdirr = require('./lib/rmdirr').rmdirr; exports.rmdirs = require('./lib/rmdirr').rmdirs; exports.rmfiles = require('./lib/rmdirr').rmfiles; exports.cpdirr = require('./lib/cpdirr').cpdirr; exports.cpdirs = require('./lib/cpdirr').cpdirs; exports.cpfiles = require('./lib/cpdirr').cpfiles;
mit
qjloong/AssetHelper
www/AssetsHelper.js
738
var exec = require('cordova/exec'); var AssetsHelper = { getAllPhotos:function(successCallback, errorCallback) { exec(successCallback, errorCallback, "AssetsHelper", "getAllPhotos", []); }, getThumbnails:function(urlList, successCallback, errorCallback) { exec(successCallback, errorCallback, "AssetsHelper", "getThumbnails", [urlList]); }, exportAsset:function(assetInfo, successCallback, errorCallback) { exec(successCallback, errorCallback, "AssetsHelper", "exportAsset", [assetInfo]); }, savePhoto:function(filePath, successCallback, errorCallback) { exec(successCallback, errorCallback, "AssetsHelper", "savePhoto", [filePath]); } } module.exports = AssetsHelper;
mit
Soaring-Outliers/news_graph
manage.py
253
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "news_graph.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
mit
akonoupakis/jsnbt
src/app/tmpl/bundle.js
8848
var md5 = require('md5'); var path = require('path'); var fs = require('fs'); var _ = require('underscore'); _.str = require('underscore.string'); var getScriptRaw = function (app, data) { var result = []; var addBundleInfo = function (groupsNames) { var combine = true; if (groupsNames.length > 0) { var groups = _.filter(_.map(groupsNames, function (x) { return _.find(app.config.scripts, function (y) { return x === y.name }); }), function (z) { return z !== undefined; }); if (_.any(groups, function (x) { return x.process === false; })) { combine = false; } if (combine) { var groupsScripts = []; _.each(groups, function (g) { if (g.items && _.isArray(g.items)) { _.each(g.items, function (gi) { groupsScripts.push(gi); }); } }); if (groupsScripts.length > 0) { var hashKey = groupsScripts.join(';'); var hashedKey = md5(hashKey); var hashedScript = '/tmp/scripts/' + hashedKey + '.js'; result.push({ items: groupsScripts, target: hashedScript }); } } } }; _.each(data, function (tmplScript) { if (_.isString(tmplScript)) { addBundleInfo([tmplScript]); } if (_.isArray(tmplScript)) { addBundleInfo(tmplScript); } }); return result; }; var getScriptBundle = function (app, data) { var scripts = []; appendScript = function (file) { var filePath = app.root.mapPath(path.join('www/public', file)); if (fs.existsSync(filePath)) { var stats = fs.statSync(filePath); scripts.push(file + '?r=' + stats.mtime.getTime()); } else { scripts.push(file); } } var addGroupScripts = function (group) { if (app.config.scripts[group] && _.isArray(app.config.scripts[group].items)) { _.each(app.config.scripts[group].items, function (groupItem) { appendScript(groupItem); }); } } var addCombinedScripts = function (groupsNames) { var combine = true; if (groupsNames.length > 0) { var groups = _.filter(_.map(groupsNames, function (x) { return _.find(app.config.scripts, function (y) { return x === y.name }); }), function (z) { return z !== undefined; }); if (_.any(groups, function (x) { return x.process === false; })) { combine = false; } var groupsScripts = []; _.each(groups, function (g) { if (g.items && _.isArray(g.items)) { _.each(g.items, function (gi) { groupsScripts.push(gi); }); } }); if (groupsScripts.length > 0) { if (combine) { var hashKey = groupsScripts.join(';'); var hashedKey = md5(hashKey); var hashedScript = '/tmp/scripts/' + hashedKey + '.js'; appendScript(hashedScript); } else { _.each(groupsScripts, function (gi) { appendScript(gi); }); } } } }; if (app.environment === 'dev') { _.each(data, function (tmplScript) { if (_.isString(tmplScript)) { addGroupScripts(tmplScript); } if (_.isArray(tmplScript)) { _.each(tmplScript, function (tmplScriptItem) { addGroupScripts(tmplScriptItem); }); } }); } else { _.each(data, function (tmplScript) { if (_.isString(tmplScript)) { addCombinedScripts([tmplScript]); } if (_.isArray(tmplScript)) { addCombinedScripts(tmplScript); } }); } return scripts; }; var getStyleRaw = function (app, data) { var result = []; var addBundleInfo = function (groupsNames) { var combine = true; if (groupsNames.length > 0) { var groups = _.filter(_.map(groupsNames, function (x) { return _.find(app.config.styles, function (y) { return x === y.name }); }), function (z) { return z !== undefined; }); if (groups.length > 1) { if (_.filter(groups, function (x) { return x.process === false; }).length > 1) { combine = false; } } if (combine) { var groupsStyles = []; _.each(groups, function (g) { if (g.items && _.isArray(g.items)) { _.each(g.items, function (gi) { groupsStyles.push(gi); }); } }); if (groupsStyles.length > 0) { var hashKey = groupsStyles.join(';'); var hashedKey = md5(hashKey); var hashedStyle = '/tmp/styles/' + hashedKey + '.css'; result.push({ items: groupsStyles, target: hashedStyle }); } } } }; _.each(data, function (tmplStyle) { if (_.isString(tmplStyle)) { addBundleInfo([tmplStyle]); } if (_.isArray(tmplStyle)) { addBundleInfo(tmplStyle); } }); return result; }; var getStyleBundle = function (app, data) { var styles = []; appendStyle = function (file) { var filePath = app.root.mapPath(path.join('www/public', file)); if (fs.existsSync(filePath)) { var stats = fs.statSync(filePath); styles.push(file + '?r=' + stats.mtime.getTime()); } else { styles.push(file); } } var addGroupStyles = function (group) { if (app.config.styles[group] && _.isArray(app.config.styles[group].items)) { _.each(app.config.styles[group].items, function (groupItem) { appendStyle(groupItem); }); } } var addCombinedStyles = function (groupsNames) { var combine = true; if (groupsNames.length > 0) { var groups = _.filter(_.map(groupsNames, function (x) { return _.find(app.config.styles, function (y) { return x === y.name }); }), function (z) { return z !== undefined; }); if (groups.length > 1) { if (_.filter(groups, function (x) { return x.process === false; }).length > 1) { combine = false; } } var groupsStyles = []; _.each(groups, function (g) { if (g.items && _.isArray(g.items)) { _.each(g.items, function (gi) { groupsStyles.push(gi); }); } }); if (groupsStyles.length > 0) { if (combine) { var hashKey = groupsStyles.join(';'); var hashedKey = md5(hashKey); var hashedStyle = '/tmp/styles/' + hashedKey + '.css'; appendStyle(hashedStyle); } else { _.each(groupsStyles, function (gi) { appendStyle(gi); }); } } } }; _.each(data, function (tmplStyle) { if (_.isString(tmplStyle)) { addCombinedStyles([tmplStyle]); } if (_.isArray(tmplStyle)) { addCombinedStyles(tmplStyle); } }); return styles; }; var Bundle = function (app) { this.app = app; }; Bundle.prototype.getScriptBundle = function (data) { return { raw: getScriptRaw(this.app, data), items: getScriptBundle(this.app, data) }; }; Bundle.prototype.getStyleBundle = function (data) { return { raw: getStyleRaw(this.app, data), items: getStyleBundle(this.app, data) }; }; module.exports = function (app) { return new Bundle(app); };
mit
ICTrekProjects/ICTrekReminderBot
bot.php
4881
<?php require_once("telegram.php"); require_once("functions.php"); $telegram = new Telegram(file_get_contents('token')); $text = $telegram->Text(); $command = explode(" ", str_replace("@ICTrekReminderBot", "", $text)); $chat_id = $telegram->ChatID(); $user_id = $telegram->UserID(); $message_id = $telegram->MessageID(); if ($text == "") { foreach (get_reminders($pdo) as $reminder => $data) { if(time() > $data['time']) { $telegram->sendMessage(array( 'chat_id' => $data['chat_id'], 'reply_to_message_id' => $data['message_id'], 'text' => 'I\'m reminding you now!' )); del_reminder($pdo, $data['id']); } } } else if ($command[0] == "/start") { send_message( "Welcome to the reminder bot made by ICTrek. I can help you with remembering stuff. To set a reminder, all you have to do is:" . PHP_EOL . "<code>/reminder [time] [message]</code>" . PHP_EOL . PHP_EOL . "<code>[time]</code> could be:" . PHP_EOL . "- 9 minutes" . PHP_EOL . "- 1 hour" . PHP_EOL . "- 5 days" . PHP_EOL . "- 2 weeks" . PHP_EOL . "- 7 months" . PHP_EOL . "- 3 years" . PHP_EOL . PHP_EOL . "Or use a date like this:" . PHP_EOL . "<code>/reminder 25-12-2018 Christmas!</code>" . PHP_EOL . "ISO8601 timestamps are supported as well." . PHP_EOL . PHP_EOL . "If you have a question or need help, just contact @Maartenwut.", $telegram, $chat_id, false, true); } else if ($command[0] == "/reminder") { // a command should look like this: /reminder 1 day Bake a pie for my nephew's birthday. $amount = $command[1]; $unit = $command[2]; $reminder = str_replace(array("/reminder ", "{$amount} ", "{$unit} "), "", $text); if ($unit && $amount && $reminder && $amount > 0 && is_numeric($amount)) { if ($unit == "minute" || $unit == "minutes") { $multiplier = 60; } else if ($unit == "hour" || $unit == "hours") { $multiplier = 3600; } else if ($unit == "day" || $unit == "days") { $multiplier = 86400; } else if ($unit == "week" || $unit == "weeks") { $multiplier = 604800; } else if ($unit == "month" || $unit == "months") { $multiplier = 2592000; } else if ($unit == "year" || $unit == "years") { $multiplier = 31557600; } else { send_message("That's not a time format I can understand.", $telegram, $chat_id, false, true); die(); } $time = time() + $multiplier * $amount; add_reminder($pdo, $chat_id, $message_id, $time, $reminder, $user_id); send_message("I'll remind you in {$amount} {$unit}.", $telegram, $chat_id, false, true); } else if (validateDate(convertDate($command[1]))) { // if the argument is a date like 1-1-2018 (YY-MM-YYY) $date = convertDate($command[1]); $unix = unixDate($date); $readable = readableTime($unix - time()); if ($unix > time()){ add_reminder($pdo, $chat_id, $message_id, $unix, $reminder, $user_id); send_message("I'll remind you in {$readable}.", $telegram, $chat_id, false, true); } else { send_message("You can't set a reminder in the past.", $telegram, $chat_id, false, true); } } else if (validISO($command[1])) { // if the argument is an ISO timestamp $unix = date("U",strtotime($command[1])); $readable = readableTime($unix - time()); if ($unix > time()){ add_reminder($pdo, $chat_id, $message_id, $unix, $reminder, $user_id); send_message("I'll remind you in {$readable}.", $telegram, $chat_id, false, true); } else { send_message("You can't set a reminder in the past.", $telegram, $chat_id, false, true); } } else { if (!$unit || !$amount) { $message = "I'm missing some info here."; } else if (!is_numeric($amount)) { $message = "{$amount} is not a number!"; } else if ($amount < 0) { $message = "You can't set a reminder in the past."; } else { $message = "An unknown error occurred."; } send_message($message, $telegram, $chat_id, false, true); } } else if ($command[0] == "/list") { $reminders = get_user_reminders($pdo, $user_id); if ($reminders) { foreach ($reminders as $reminder => $data) { $timeleft = $data['time'] - time(); $output .= "<code>(" . $reminder . ")</code> " . readableTime($timeleft) . " - " . $data['reminder'] . PHP_EOL; } send_message("These are your reminders:" . PHP_EOL . $output, $telegram, $chat_id, false, true); } else { send_message("You haven't set a reminder.", $telegram, $chat_id, false, true); } } else if ($command[0] == "/remove") { $reminders = get_user_reminders($pdo, $user_id); $reminder = $reminders[$command[1]]; $date = date('c', $reminder['time']); if ($reminder) { send_message("Your reminder \"{$reminder['reminder']}\" set for <code>{$date}</code> has been removed.", $telegram, $chat_id, false, true); del_reminder($pdo, $reminder['id']); } else { send_message("That reminder doesn't exist. Be sure to use the number of the reminder which you can find with /list.", $telegram, $chat_id, false, true); } }
mit
justinryder/PandAngular
src/js/controlsController.js
5174
app.controller('controlsController', ['$scope', '$http', function($scope, $http) { $scope.types = ['line', 'spline', 'step', 'area', 'area-spline', 'area-step']; $scope.type = 'area-spline'; $scope.$watch(function(scope){ return scope.type; }, function(newValue){ for (var i in $scope.data.types) { $scope.data.types[i] = newValue; } refreshChartData(); }); $scope.data = { x: 'x', columns: [ ['x'] ], types: {} }; var dates, nuclear, solar, wind, windSolar, btuTotal, mwTotal; $scope.events = { Solar: [], Wind: [] }; $scope.proposedEvent = { location: '', type: '', btuDelta: 0, year: new Date().getFullYear() }; $scope.minYear = new Date().getFullYear(); $scope.maxYear = 2050; $scope.saveProject = function(type) { var btu = 0; if(type === 'Wind') { btu = 6; } else if(type === 'Solar') { btu = 1; } addEvent(type, btu, $scope.proposedEvent.year, $scope.proposedEvent.location, true); }; $scope.addProject = function(powerType, btuDelta, date, location, name) { addEvent(powerType, btuDelta, date, location, name, true); }; $http.get('json/productionData.json').success(function(data){ dates = ['x'].concat(_.pluck(data, 'year')); nuclear = ['Nuclear'].concat(_.pluck(data, 'nuclear')); solar = ['Solar'].concat(_.pluck(data, 'solar')); wind = ['Wind'].concat(_.pluck(data, 'wind')); windSolar = ['Wind & Solar'].concat(_.pluck(data, 'wind solar')); btuTotal = ['Trillion BTU Total'].concat(_.pluck(data, 'trillionBtuTotal')); mwTotal = ['MegaWatt Total'].concat(_.pluck(data, 'MWTotal')); addPlannedEvents(); }); function addPlannedEvents() { addEvent('Solar', 1, 2023, 'Richmond', 'Super Solar', 'some description', false); addEvent('Wind', 6, 2020, 'Middlebury', 'Epic Winds'); } function addEvent(powerType, btuDelta, date, location, name, description, shouldRefresh){ var e = { name: name, description: description, type: powerType, btuDelta: btuDelta, date: date, location: location }; $scope.events[powerType].push(e); if (typeof shouldRefresh === 'undefined' || shouldRefresh){ applyEventsToChartData(); } } function applyEventsToChartData(){ $scope.data.columns = []; $scope.data.columns[0] = dates; var _solar = solar.concat([]), _wind = wind.concat([]); _.each($scope.events.Solar, function(e){ applyEventToDataSet(_solar, e); }); _.each($scope.events.Wind, function(e){ applyEventToDataSet(_wind, e); }); addDataSet('Nuclear', nuclear); addDataSet('Solar', _solar); addDataSet('Wind', _wind); //addDataSet('Wind & Solar', windSolar); //addDataSet('Total', btuTotal); //addDataSet('MegaWatt Total', mwTotal); } function applyEventToDataSet(dataSet, e){ for (var i = 0; i < dataSet.length; i++){ if (dates[i] >= e.date){ dataSet[i] = dataSet[i] + e.btuDelta; } } } $scope.removeEvent = function(e){ for (var i in $scope.events){ var index = $scope.events[i].indexOf(e); if (index > -1){ $scope.events[i].splice(index, 1); applyEventsToChartData(); } } }; var customers = ['detailed-service-client1', 'detailed-service-client2', 'detailed-service-client3', 'detailed-service-client4']; // init w/ the detailed 4 customer data // for (var i in customers){ // loadRawData(customers[i]); // } function loadRawData(source){ $http.get('/api/collections/raw?take=100&query=' + JSON.stringify({ Source: source })).success(function(data){ addDetailedClientDataSet(source, data); }); } function addDetailedClientDataSet(name, dataSet){ var kwh_c = [], kwh_g = [], dates = []; for (var i in dataSet){ kwh_c.push(dataSet[i].kwh_c); kwh_g.push(dataSet[i].kwh_g); var date = new Date(Date.parse(dataSet[i].dt)); dates.push(date); } dates.unshift('x'); $scope.data.columns[0] = dates; var name_kwh_c = name + '_kwh_c', name_kwh_g = name + '_kwh_g'; kwh_c.unshift(name_kwh_c); kwh_g.unshift(name_kwh_g); addDataSet(name_kwh_c, kwh_c); addDataSet(name_kwh_g, kwh_g); } function addDataSet(name, dataSet){ $scope.data.columns.push(dataSet); $scope.data.types[name] = $scope.type; refreshChartData(); } $scope.changeType = function(dataName, type){ $scope.data.types[dataName] = type; refreshChartData(); }; function refreshChartData(){ if ($scope.chart){ $scope.chart.load($scope.data); var gridLines = [ { value: 1972, text: 'VT Yankee Begins Operation' }, { value: new Date().getFullYear(), text: 'Today' } ], events = $scope.events.Solar.concat($scope.events.Wind); for (var i in events){ var e = events[i]; gridLines.push({ value: e.date, text: e.type + ' Project @ ' + e.location }); } $scope.chart.xgrids(gridLines); } } function btuToMw(btu){ return btu * 0.3; } }]);
mit
lixaviers/lixavier-console
lixavier-console-dal/src/main/java/com/lixavier/console/model/AddressExample.java
15492
package com.lixavier.console.model; import java.util.ArrayList; import java.util.List; public class AddressExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public AddressExample() { oredCriteria = new ArrayList<Criteria>(); } public String getOrderByClause() { return orderByClause; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public boolean isDistinct() { return distinct; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andParentIdIsNull() { addCriterion("parent_id is null"); return (Criteria) this; } public Criteria andParentIdIsNotNull() { addCriterion("parent_id is not null"); return (Criteria) this; } public Criteria andParentIdEqualTo(Integer value) { addCriterion("parent_id =", value, "parentId"); return (Criteria) this; } public Criteria andParentIdNotEqualTo(Integer value) { addCriterion("parent_id <>", value, "parentId"); return (Criteria) this; } public Criteria andParentIdGreaterThan(Integer value) { addCriterion("parent_id >", value, "parentId"); return (Criteria) this; } public Criteria andParentIdGreaterThanOrEqualTo(Integer value) { addCriterion("parent_id >=", value, "parentId"); return (Criteria) this; } public Criteria andParentIdLessThan(Integer value) { addCriterion("parent_id <", value, "parentId"); return (Criteria) this; } public Criteria andParentIdLessThanOrEqualTo(Integer value) { addCriterion("parent_id <=", value, "parentId"); return (Criteria) this; } public Criteria andParentIdIn(List<Integer> values) { addCriterion("parent_id in", values, "parentId"); return (Criteria) this; } public Criteria andParentIdNotIn(List<Integer> values) { addCriterion("parent_id not in", values, "parentId"); return (Criteria) this; } public Criteria andParentIdBetween(Integer value1, Integer value2) { addCriterion("parent_id between", value1, value2, "parentId"); return (Criteria) this; } public Criteria andParentIdNotBetween(Integer value1, Integer value2) { addCriterion("parent_id not between", value1, value2, "parentId"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andNumOrderIsNull() { addCriterion("num_order is null"); return (Criteria) this; } public Criteria andNumOrderIsNotNull() { addCriterion("num_order is not null"); return (Criteria) this; } public Criteria andNumOrderEqualTo(Integer value) { addCriterion("num_order =", value, "numOrder"); return (Criteria) this; } public Criteria andNumOrderNotEqualTo(Integer value) { addCriterion("num_order <>", value, "numOrder"); return (Criteria) this; } public Criteria andNumOrderGreaterThan(Integer value) { addCriterion("num_order >", value, "numOrder"); return (Criteria) this; } public Criteria andNumOrderGreaterThanOrEqualTo(Integer value) { addCriterion("num_order >=", value, "numOrder"); return (Criteria) this; } public Criteria andNumOrderLessThan(Integer value) { addCriterion("num_order <", value, "numOrder"); return (Criteria) this; } public Criteria andNumOrderLessThanOrEqualTo(Integer value) { addCriterion("num_order <=", value, "numOrder"); return (Criteria) this; } public Criteria andNumOrderIn(List<Integer> values) { addCriterion("num_order in", values, "numOrder"); return (Criteria) this; } public Criteria andNumOrderNotIn(List<Integer> values) { addCriterion("num_order not in", values, "numOrder"); return (Criteria) this; } public Criteria andNumOrderBetween(Integer value1, Integer value2) { addCriterion("num_order between", value1, value2, "numOrder"); return (Criteria) this; } public Criteria andNumOrderNotBetween(Integer value1, Integer value2) { addCriterion("num_order not between", value1, value2, "numOrder"); return (Criteria) this; } public Criteria andPyIsNull() { addCriterion("py is null"); return (Criteria) this; } public Criteria andPyIsNotNull() { addCriterion("py is not null"); return (Criteria) this; } public Criteria andPyEqualTo(String value) { addCriterion("py =", value, "py"); return (Criteria) this; } public Criteria andPyNotEqualTo(String value) { addCriterion("py <>", value, "py"); return (Criteria) this; } public Criteria andPyGreaterThan(String value) { addCriterion("py >", value, "py"); return (Criteria) this; } public Criteria andPyGreaterThanOrEqualTo(String value) { addCriterion("py >=", value, "py"); return (Criteria) this; } public Criteria andPyLessThan(String value) { addCriterion("py <", value, "py"); return (Criteria) this; } public Criteria andPyLessThanOrEqualTo(String value) { addCriterion("py <=", value, "py"); return (Criteria) this; } public Criteria andPyLike(String value) { addCriterion("py like", value, "py"); return (Criteria) this; } public Criteria andPyNotLike(String value) { addCriterion("py not like", value, "py"); return (Criteria) this; } public Criteria andPyIn(List<String> values) { addCriterion("py in", values, "py"); return (Criteria) this; } public Criteria andPyNotIn(List<String> values) { addCriterion("py not in", values, "py"); return (Criteria) this; } public Criteria andPyBetween(String value1, String value2) { addCriterion("py between", value1, value2, "py"); return (Criteria) this; } public Criteria andPyNotBetween(String value1, String value2) { addCriterion("py not between", value1, value2, "py"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } } }
mit
basmoura/hello
app/lib/hello/user.rb
600
Hello.config.user do # controller scope set :success do # @user respond_to do |format| format.html { redirect_to hello.user_path, notice: 'Your profile was successfully updated.' } format.json { # render json: @credential, status: :created, location: hello.password_sign_in_welcome_path } end end set :error do # @user respond_to do |format| format.html { render :edit } format.json { # render json: @user.errors, status: :unprocessable_entity } end end end
mit
cypreess/PyrateDice
game_server/game_server/board/tests.py
775
from django.test import TestCase # Create your tests here. from board.tasks import GameError, check_move class CheckMoveTestCase(TestCase): def test_check_move_1(self): self.assertRaises(GameError, check_move, 0, 0, [], 3) def test_check_move_2(self): self.assertRaises(GameError, check_move, 10, 0, [(1, 'player', 3, 4)], 13) def test_check_move_2a(self): try: check_move( 10, 1, [(1, 'player', 3, 4)], 13) except GameError: self.fail("Should not raise GameError") def test_check_move_2c(self): self.assertRaises(GameError, check_move, 10, 1, [(1, 'player', 3, 4)], 9) def test_check_move_3(self): self.assertRaises(GameError, check_move, 0, 10, [(1, 'player', 3, 4)], 3)
mit
balderdashy/backbone-to-sails
sails.io.backbone.js
7185
/*! * Backbone SDK for Sails and Socket.io * (override for Backbone.sync and Backbone.Collection) * * c. 2013 @mikermcneil * MIT Licensed * * * Inspired by: * backbone.iobind - Backbone.sync replacement * Copyright(c) 2011 Jake Luer <jake@alogicalparadox.com> * MIT Licensed */ (function () { // The active `socket` var socket; // Also keep track of where it came from var socketSrc; // Used to simplify app-level connection logic-- i.e. so you don't // have to wait for the socket to be connected to start trying to // synchronize data. var requestQueue = []; // A `setTimeout` that, if necessary, is used to check if the socket // is ready yet (polls). var socketTimer; /** * _acquireSocket() * * Grab hold of our active socket object, set it on `socket` closure variable above. * (if your connected socket exists on a non-standard variable, change here) * * @api private */ var _acquireSocket = function ( ) { if (socket) return; if (Backbone.socket) { socket = Backbone.socket; socketSrc = '`Backbone.socket`'; } else if (window.socket) { socket = window.socket; socketSrc = '`window.socket`'; } // The first time a socket is acquired, bind comet listener if (socket) _bindCometListener(); }; /** * Checks if the socket is ready- if so, runs the request queue. * If not, sets the timer again. */ var _keepTryingToRunRequestQueue = function ( ) { clearTimeout(socketTimer); // Check if socket is connected (synchronous) var socketIsConnected = socket.socket && socket.socket.connected; if (socketIsConnected) { // Run the request queue _.each(requestQueue, function (request) { Backbone.sync(request.method, request.model, request.options); }); } else { // Reset the timer socketTimer = setTimeout(_keepTryingToRunRequestQueue, 250); // TODO: // After a configurable period of time, if the socket has still not connected, // throw an error, since the `socket` might be improperly configured. // throw new Error( // '\n' + // 'Backbone is trying to communicate with the Sails server using '+ socketSrc +',\n'+ // 'but its `connected` property is still set to false.\n' + // 'But maybe Socket.io just hasn\'t finished connecting yet?\n' + // '\n' + // 'You might check to be sure you\'re waiting for `socket.on(\'connect\')`\n' + // 'before using sync methods on your Backbone models and collections.' // ); } }; // Set up `async.until`-esque mechanism which will attempt to acquire a socket. var attempts = 0, maxAttempts = 3, interval = 1500, initialInterval = 250; var _attemptToAcquireSocket = function () { if ( socket ) return; attempts++; _acquireSocket(); if (attempts >= maxAttempts) return; setTimeout(_attemptToAcquireSocket, interval); }; // Attempt to acquire the socket more quickly the first time, // in case the user is on a fast connection and it's available. setTimeout(_attemptToAcquireSocket, initialInterval); /** * Backbone.on('comet', ...) * * Since Backbone is already a listener (extends Backbone.Events) * all we have to do is trigger the event on the Backbone global when * we receive a new message from the server. * * I realize this doesn't do a whole lot right now-- that's ok. * Let's start light and layer on additional functionality carefully. */ var _bindCometListener = function socketAcquiredForFirstTime () { socket.on('message', function cometMessageReceived (message) { Backbone.trigger('comet', message); }); }; /** * # Backbone.sync * * Replaces default Backbone.sync function with socket.io transport * * @param {String} method * @param {Backbone.Model|Backbone.Collection} model * @param {Object} options * * @name sync */ Backbone.sync = function (method, model, options) { // Clone options to avoid smashing anything unexpected options = _.extend({}, options); // If socket is not defined yet, try to grab it again. _acquireSocket(); // Handle missing socket if (!socket) { throw new Error( '\n' + 'Backbone cannot find a suitable `socket` object.\n' + 'This SDK expects the active socket to be located at `window.socket`, '+ '`Backbone.socket` or the `socket` property\n' + 'of the Backbone model or collection attempting to communicate w/ the server.\n' ); } // Ensures the socket is connected and able to communicate w/ the server. // var socketIsConnected = socket.socket && socket.socket.connected; if ( !socketIsConnected ) { // If the socket is not connected, the request is queued // (so it can be replayed when the socket comes online.) requestQueue.push({ method: method, model: model, options: options }); // If we haven't already, start polling the socket to see if it's ready _keepTryingToRunRequestQueue(); return; } // Get the actual URL (call `.url()` if it's a function) var url; if (options.url) { url = _.result(options, 'url'); } else if (model.url) { url = _.result(model, 'url'); } // Throw an error when a URL is needed, and none is supplied. // Copied from backbone.js#1558 else throw new Error('A "url" property or function must be specified'); // Build parameters to send to the server var params = {}; if ( !options.data && model ) { params = options.attrs || model.toJSON(options) || {}; } if (options.patch === true && _.isObject(options.data) && options.data.id === null && model) { params.id = model.id; } if (_.isObject(options.data)) { _(params).extend(options.data); } // Map Backbone's concept of CRUD methods to HTTP verbs var verb; switch (method) { case 'create': verb = 'post'; break; case 'read': verb = 'get'; break; case 'update': verb = 'put'; break; default: verb = method; } // Send a simulated HTTP request to Sails via Socket.io var simulatedXHR = socket.request(url, params, function serverResponded ( response ) { if (options.success) options.success(response); }, verb); // Trigget the `request` event on the Backbone model model.trigger('request', model, simulatedXHR, options); return simulatedXHR; }; /** * TODO: * Replace sails.io.js with `jQuery-to-sails.js`, which can be a prerequisite of * this SDK. * * Will allow for better client-side error handling, proper simulation of $.ajax, * easier client-side support of headers, and overall a better experience. */ /* var simulatedXHR = $.Deferred(); // Send a simulated HTTP request to Sails via Socket.io io.emit(verb, params, function serverResponded (err, response) { if (err) { if (options.error) options.error(err); simulatedXHR.reject(); return; } if (options.success) options.success(response); simulatedXHR.resolve(); }); var promise = simulatedXHR.promise(); // Trigger the model's `request` event model.trigger('request', model, promise, options); // Return a promise to allow chaining of sync methods. return promise; */ })();
mit
jakejosol/warp-project
references/classes/Slang.php
169
<?php /* * Slang class * @author Jake Josol * @description Class that is responsible for the string languages */ class Slang extends Warp\Localization\Slang {} ?>
mit
onlabsorg/olowc
jspm_packages/npm/lodash@4.17.4/_mapCacheDelete.js
217
/* */ var getMapData = require('./_getMapData'); function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } module.exports = mapCacheDelete;
mit