text
stringlengths
2
1.04M
meta
dict
<?php namespace PizzaBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Route\RouteCollection; class OrderAdmin extends Admin { protected function configureRoutes(RouteCollection $collection) { $collection ->remove('create') ->remove('edit') ; } public function configureFormFields(FormMapper $formMapper) { $formMapper ->with('Order', array( 'class' => 'col-md-8', 'box_class' => 'box box-solid box-success', 'description' => 'Change your contact')) ->add('name', 'text') ->add('phone', 'integer') ->add('email', 'text') ->add('message', 'text') ->add('status', 'choice') ->end(); } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('name') ->add('phone') ->add('email') ->add('message') ->add('status') ; } protected function configureListFields(ListMapper $listMapper) { $listMapper ->add('_action', 'actions', array( 'actions' => array( 'delete' => array(), ))) ->add('name', null, array( 'editable' => true )) ->add('phone', null, array( 'editable' => true )) ->add('email', null, array( 'editable' => true )) ->add('message', null, array( 'editable' => true )) ->add('status', null, array( 'editable' => true )) ; } }
{ "content_hash": "d930d150df08847ec7075a543b905f0c", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 79, "avg_line_length": 28.60810810810811, "alnum_prop": 0.43693906471421823, "repo_name": "artro8/Symfony3---WebsitePizza", "id": "75df490c15759f0b93d63f1d92c3ca2d2ffba9dd", "size": "2117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PizzaBundle/Admin/OrderAdmin.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3605" }, { "name": "CSS", "bytes": "28715" }, { "name": "HTML", "bytes": "274757" }, { "name": "JavaScript", "bytes": "4257" }, { "name": "PHP", "bytes": "92934" } ], "symlink_target": "" }
<?php namespace Google\AdsApi\AdManager\v202202; /** * This file was generated from WSDL. DO NOT EDIT. */ class LineItemErrorReason { const ALREADY_STARTED = 'ALREADY_STARTED'; const UPDATE_RESERVATION_NOT_ALLOWED = 'UPDATE_RESERVATION_NOT_ALLOWED'; const ALL_ROADBLOCK_NOT_ALLOWED = 'ALL_ROADBLOCK_NOT_ALLOWED'; const ALL_COMPANION_DELIVERY_NOT_ALLOWED = 'ALL_COMPANION_DELIVERY_NOT_ALLOWED'; const CREATIVE_SET_ROADBLOCK_NOT_ALLOWED = 'CREATIVE_SET_ROADBLOCK_NOT_ALLOWED'; const FRACTIONAL_PERCENTAGE_NOT_ALLOWED = 'FRACTIONAL_PERCENTAGE_NOT_ALLOWED'; const DISCOUNT_NOT_ALLOWED = 'DISCOUNT_NOT_ALLOWED'; const UPDATE_CANCELED_LINE_ITEM_NOT_ALLOWED = 'UPDATE_CANCELED_LINE_ITEM_NOT_ALLOWED'; const UPDATE_PENDING_APPROVAL_LINE_ITEM_NOT_ALLOWED = 'UPDATE_PENDING_APPROVAL_LINE_ITEM_NOT_ALLOWED'; const UPDATE_ARCHIVED_LINE_ITEM_NOT_ALLOWED = 'UPDATE_ARCHIVED_LINE_ITEM_NOT_ALLOWED'; const CREATE_OR_UPDATE_LEGACY_DFP_LINE_ITEM_TYPE_NOT_ALLOWED = 'CREATE_OR_UPDATE_LEGACY_DFP_LINE_ITEM_TYPE_NOT_ALLOWED'; const COPY_LINE_ITEM_FROM_DIFFERENT_COMPANY_NOT_ALLOWED = 'COPY_LINE_ITEM_FROM_DIFFERENT_COMPANY_NOT_ALLOWED'; const INVALID_SIZE_FOR_PLATFORM = 'INVALID_SIZE_FOR_PLATFORM'; const INVALID_LINE_ITEM_TYPE_FOR_PLATFORM = 'INVALID_LINE_ITEM_TYPE_FOR_PLATFORM'; const INVALID_WEB_PROPERTY_FOR_PLATFORM = 'INVALID_WEB_PROPERTY_FOR_PLATFORM'; const INVALID_WEB_PROPERTY_FOR_ENVIRONMENT = 'INVALID_WEB_PROPERTY_FOR_ENVIRONMENT'; const AFMA_BACKFILL_NOT_ALLOWED = 'AFMA_BACKFILL_NOT_ALLOWED'; const UPDATE_ENVIRONMENT_TYPE_NOT_ALLOWED = 'UPDATE_ENVIRONMENT_TYPE_NOT_ALLOWED'; const COMPANIONS_NOT_ALLOWED = 'COMPANIONS_NOT_ALLOWED'; const ROADBLOCKS_WITH_NONROADBLOCKS_NOT_ALLOWED = 'ROADBLOCKS_WITH_NONROADBLOCKS_NOT_ALLOWED'; const CANNOT_UPDATE_TO_OR_FROM_CREATIVE_SET_ROADBLOCK = 'CANNOT_UPDATE_TO_OR_FROM_CREATIVE_SET_ROADBLOCK'; const UPDATE_FROM_BACKFILL_LINE_ITEM_TYPE_NOT_ALLOWED = 'UPDATE_FROM_BACKFILL_LINE_ITEM_TYPE_NOT_ALLOWED'; const UPDATE_TO_BACKFILL_LINE_ITEM_TYPE_NOT_ALLOWED = 'UPDATE_TO_BACKFILL_LINE_ITEM_TYPE_NOT_ALLOWED'; const UPDATE_BACKFILL_WEB_PROPERTY_NOT_ALLOWED = 'UPDATE_BACKFILL_WEB_PROPERTY_NOT_ALLOWED'; const INVALID_COMPANION_DELIVERY_OPTION_FOR_ENVIRONMENT_TYPE = 'INVALID_COMPANION_DELIVERY_OPTION_FOR_ENVIRONMENT_TYPE'; const COMPANION_BACKFILL_REQUIRES_VIDEO = 'COMPANION_BACKFILL_REQUIRES_VIDEO'; const COMPANION_DELIVERY_OPTION_REQUIRE_PREMIUM = 'COMPANION_DELIVERY_OPTION_REQUIRE_PREMIUM'; const DUPLICATE_MASTER_SIZES = 'DUPLICATE_MASTER_SIZES'; const INVALID_PRIORITY_FOR_LINE_ITEM_TYPE = 'INVALID_PRIORITY_FOR_LINE_ITEM_TYPE'; const INVALID_ENVIRONMENT_TYPE = 'INVALID_ENVIRONMENT_TYPE'; const INVALID_ENVIRONMENT_TYPE_FOR_PLATFORM = 'INVALID_ENVIRONMENT_TYPE_FOR_PLATFORM'; const INVALID_TYPE_FOR_AUTO_EXTENSION = 'INVALID_TYPE_FOR_AUTO_EXTENSION'; const VIDEO_INVALID_ROADBLOCKING = 'VIDEO_INVALID_ROADBLOCKING'; const BACKFILL_TYPE_NOT_ALLOWED = 'BACKFILL_TYPE_NOT_ALLOWED'; const INVALID_BACKFILL_LINK_TYPE = 'INVALID_BACKFILL_LINK_TYPE'; const DIFFERENT_BACKFILL_ACCOUNT = 'DIFFERENT_BACKFILL_ACCOUNT'; const COMPANION_DELIVERY_OPTIONS_NOT_ALLOWED_WITH_BACKFILL = 'COMPANION_DELIVERY_OPTIONS_NOT_ALLOWED_WITH_BACKFILL'; const INVALID_WEB_PROPERTY_FOR_ADX_BACKFILL = 'INVALID_WEB_PROPERTY_FOR_ADX_BACKFILL'; const INVALID_COST_PER_UNIT_FOR_BACKFILL = 'INVALID_COST_PER_UNIT_FOR_BACKFILL'; const INVALID_SIZE_FOR_ENVIRONMENT = 'INVALID_SIZE_FOR_ENVIRONMENT'; const TARGET_PLATOFRM_NOT_ALLOWED = 'TARGET_PLATOFRM_NOT_ALLOWED'; const INVALID_LINE_ITEM_CURRENCY = 'INVALID_LINE_ITEM_CURRENCY'; const LINE_ITEM_CANNOT_HAVE_MULTIPLE_CURRENCIES = 'LINE_ITEM_CANNOT_HAVE_MULTIPLE_CURRENCIES'; const CANNOT_CHANGE_CURRENCY = 'CANNOT_CHANGE_CURRENCY'; const INVALID_LINE_ITEM_DATE_TIME = 'INVALID_LINE_ITEM_DATE_TIME'; const INVALID_COST_PER_UNIT_FOR_CPA = 'INVALID_COST_PER_UNIT_FOR_CPA'; const UPDATE_CPA_COST_TYPE_NOT_ALLOWED = 'UPDATE_CPA_COST_TYPE_NOT_ALLOWED'; const UPDATE_VCPM_COST_TYPE_NOT_ALLOWED = 'UPDATE_VCPM_COST_TYPE_NOT_ALLOWED'; const MASTER_COMPANION_LINE_ITEM_CANNOT_HAVE_VCPM_COST_TYPE = 'MASTER_COMPANION_LINE_ITEM_CANNOT_HAVE_VCPM_COST_TYPE'; const DUPLICATED_UNIT_TYPE = 'DUPLICATED_UNIT_TYPE'; const MULTIPLE_GOAL_TYPE_NOT_ALLOWED = 'MULTIPLE_GOAL_TYPE_NOT_ALLOWED'; const INVALID_UNIT_TYPE_COMBINATION_FOR_SECONDARY_GOALS = 'INVALID_UNIT_TYPE_COMBINATION_FOR_SECONDARY_GOALS'; const INVALID_CREATIVE_TARGETING_NAME = 'INVALID_CREATIVE_TARGETING_NAME'; const INVALID_CREATIVE_CUSTOM_TARGETING_MATCH_TYPE = 'INVALID_CREATIVE_CUSTOM_TARGETING_MATCH_TYPE'; const INVALID_CREATIVE_ROTATION_TYPE_WITH_CREATIVE_TARGETING = 'INVALID_CREATIVE_ROTATION_TYPE_WITH_CREATIVE_TARGETING'; const CANNOT_OVERBOOK_WITH_CREATIVE_TARGETING = 'CANNOT_OVERBOOK_WITH_CREATIVE_TARGETING'; const PLACEHOLDERS_DO_NOT_MATCH_PROPOSAL = 'PLACEHOLDERS_DO_NOT_MATCH_PROPOSAL'; const UNSUPPORTED_LINE_ITEM_TYPE_FOR_THIS_API_VERSION = 'UNSUPPORTED_LINE_ITEM_TYPE_FOR_THIS_API_VERSION'; const NATIVE_CREATIVE_TEMPLATE_REQUIRED = 'NATIVE_CREATIVE_TEMPLATE_REQUIRED'; const CANNOT_HAVE_CREATIVE_TEMPLATE = 'CANNOT_HAVE_CREATIVE_TEMPLATE'; const CANNOT_INCLUDE_NATIVE_CREATIVE_TEMPLATE = 'CANNOT_INCLUDE_NATIVE_CREATIVE_TEMPLATE'; const CANNOT_INCLUDE_NATIVE_PLACEHOLDER_WITHOUT_TEMPLATE_ID = 'CANNOT_INCLUDE_NATIVE_PLACEHOLDER_WITHOUT_TEMPLATE_ID'; const NO_SIZE_WITH_DURATION = 'NO_SIZE_WITH_DURATION'; const INVALID_VIEWABILITY_PROVIDER_COMPANY = 'INVALID_VIEWABILITY_PROVIDER_COMPANY'; const CANNOT_ACCESS_CUSTOM_PACING_CURVE_CLOUD_STORAGE_BUCKET = 'CANNOT_ACCESS_CUSTOM_PACING_CURVE_CLOUD_STORAGE_BUCKET'; const CMS_METADATA_LINE_ITEM_ENVIRONMENT_TYPE_NOT_SUPPORTED = 'CMS_METADATA_LINE_ITEM_ENVIRONMENT_TYPE_NOT_SUPPORTED'; const SKIPPABLE_AD_TYPE_NOT_ALLOWED = 'SKIPPABLE_AD_TYPE_NOT_ALLOWED'; const CUSTOM_PACING_CURVE_START_TIME_MUST_MATCH_LINE_ITEM_START_TIME = 'CUSTOM_PACING_CURVE_START_TIME_MUST_MATCH_LINE_ITEM_START_TIME'; const CUSTOM_PACING_CURVE_START_TIME_PAST_LINE_ITEM_END_TIME = 'CUSTOM_PACING_CURVE_START_TIME_PAST_LINE_ITEM_END_TIME'; const INVALID_LINE_ITEM_TYPE_FOR_DELIVERY_FORECAST_SOURCE = 'INVALID_LINE_ITEM_TYPE_FOR_DELIVERY_FORECAST_SOURCE'; const INVALID_TOTAL_CUSTOM_PACING_GOAL_AMOUNTS = 'INVALID_TOTAL_CUSTOM_PACING_GOAL_AMOUNTS'; const COPY_LINE_ITEM_WITH_CUSTOM_PACING_CURVE_FULLY_IN_PAST_NOT_ALLOWED = 'COPY_LINE_ITEM_WITH_CUSTOM_PACING_CURVE_FULLY_IN_PAST_NOT_ALLOWED'; const LAST_CUSTOM_PACING_GOAL_AMOUNT_CANNOT_BE_ZERO = 'LAST_CUSTOM_PACING_GOAL_AMOUNT_CANNOT_BE_ZERO'; const GRP_PACED_LINE_ITEM_CANNOT_HAVE_ABSOLUTE_CUSTOM_PACING_CURVE_GOALS = 'GRP_PACED_LINE_ITEM_CANNOT_HAVE_ABSOLUTE_CUSTOM_PACING_CURVE_GOALS'; const INVALID_MAX_VIDEO_CREATIVE_DURATION = 'INVALID_MAX_VIDEO_CREATIVE_DURATION'; const INVALID_NATIVE_SIZE = 'INVALID_NATIVE_SIZE'; const INVALID_TARGETED_REQUEST_PLATFORM_FOR_WEB_PROPERTY_CODE = 'INVALID_TARGETED_REQUEST_PLATFORM_FOR_WEB_PROPERTY_CODE'; const UNKNOWN = 'UNKNOWN'; }
{ "content_hash": "3834e5e92aa9dcca422f918906cc06ee", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 148, "avg_line_length": 78.97802197802197, "alnum_prop": 0.7640183664950605, "repo_name": "googleads/googleads-php-lib", "id": "119bf02282b29608f833e68d18a25ff9d842e9a1", "size": "7187", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/Google/AdsApi/AdManager/v202202/LineItemErrorReason.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "11415914" } ], "symlink_target": "" }
# Envelop: Dependency Injection ## en·vel·op /enˈveləp/ ### Verb 1. Wrap up, cover, or surround completely. 2. Make obscure; conceal. ## What is Envelop Envelop is a simple to use Dependency Injection and Inversion of Control container. ## Examples: ### Interfaces ```c# interface ISomeInterface { } class SomeInterfaceImplementation : ISomeInterface { } class SomeInterfaceImplementation2 : ISomeInterface { } interface IAnotherInterface { ISomeInterface SomeInterface { get; } } class AnotherInterfaceImplementation : IAnotherInterface { public ISomeInterface SomeInterface { get; private set; } public AnotherInterfaceImplementation(ISomeInterface someInterface) { this.SomeInterface = someInterface; } } interface IMultiInterface { ISomeInterface[] SomeInterfaces { get; } } class MultiInterfaceImplementation : IMultiInterface { public ISomeInterface[] SomeInterfaces { get; private set; } public MultiInterfaceImplementation(ISomeInterface[] someInterfaces) { this.SomeInterfaces = someInterfaces; } } ``` ### Fluent ```c# var kernel = Kernel.Create(); // Automatic construction kernel.Bind<ISomeInterface>().To<SomeInterfaceImplementation>(); // Factory based construction kernel.Bind<ISomeInterface>().To(_ => new SomeInterfaceImplementation()); // Singletons kernel.Bind<ISomeInterface>().To(new SomeInterfaceImplementation()); kernel.Bind<ISomeInterface>().To<SomeInterfaceImplementation>().AsSingleton(); kernel.Bind<ISomeInterface>().To(req => new SomeInterfaceImplementation()).AsSingleton(); // Constraints kernel.Bind<ISomeInterface>().To<SomeInterfaceImplementation2>().When(req => typeof(IAnotherInterface).IsAssignableFrom(req.Target)); ``` ### Injection ```c# var kernel = Kernel.Create(); kernel.Bind<ISomeInterface>().To<SomeInterfaceImplementation>(); kernel.Bind<IAnotherInterface>().To<AnotherInterfaceImplementation>(); var anotherInterfaceInstance = kernel.Resolve<IAnotherInterface>(); ``` ### Multi-injection ```c# var kernel = Kernel.Create(); kernel.Bind<ISomeInterface>().To<SomeInterfaceImplementation>(); kernel.Bind<ISomeInterface>().To<SomeInterfaceImplementation2>(); kernel.Bind<IMultiInterface>().To<MultiInterfaceImplementation>(); var t1 = kernel.Resolve<IMultiInterface>(); var someInterfaces = kernel.ResolveAll<ISomeInterface>(); ```
{ "content_hash": "eeb9f2087e42dc9181569894c433029e", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 133, "avg_line_length": 22.563106796116504, "alnum_prop": 0.7680722891566265, "repo_name": "kthompson/envelop", "id": "54435d65198956beb4343a0bb84a8b0fc30ae7ab", "size": "2330", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "52" }, { "name": "C#", "bytes": "88242" } ], "symlink_target": "" }
[![Build Status](https://secure.travis-ci.org/LearnBoost/engine.io-client.png)](http://travis-ci.org/LearnBoost/engine.io-client) [![NPM version](https://badge.fury.io/js/engine.io-client.png)](http://badge.fury.io/js/engine.io-client) This is the client for [Engine.IO](http://github.com/learnboost/engine.io), the implementation of transport-based cross-browser/cross-device bi-directional communication layer for [Socket.IO](http://github.com/learnboost/socket.io). ## How to use ### Standalone You can find an `engine.io.js` file in this repository, which is a standalone build you can use as follows: ```html <script src="/path/to/engine.io.js"></script> <script> // eio = Socket var socket = eio('ws://localhost'); socket.on('open', function(){ socket.on('message', function(data){}); socket.on('close', function(){}); }); </script> ``` ### With browserify Engine.IO is a commonjs module, which means you can include it by using `require` on the browser and package using [browserify](http://browserify.org/): 1. install the client package ``` shell npm install engine.io-client ``` 1. write your app code ```js var socket = require('engine.io-client')('ws://localhost'); socket.on('open', function(){ socket.on('message', function(data){}); socket.on('close', function(){}); }); ``` 1. build your app bundle ```bash $ browserify app.js > bundle.js ``` 1. include on your page ```html <script src="/path/to/bundle.js"></script> ``` ### Sending and receiving binary ```html <script src="/path/to/engine.io.js"></script> <script> var socket = new eio.Socket('ws://localhost/'); socket.binaryType = 'blob'; socket.on('open', function () { socket.send(new Int8Array(5)); socket.on('message', function(blob){}); socket.on('close', function(){ }); }); </script> ``` ### Node.JS Add `engine.io-client` to your `package.json` and then: ```js var socket = require('engine.io-client')('ws://localhost'); socket.on('open', function(){ socket.on('message', function(data){}); socket.on('close', function(){}); }); ``` ## Features - Lightweight - Lazyloads Flash transport - Runs on browser and node.js seamlessly - Transports are independent of `Engine` - Easy to debug - Easy to unit test - Runs inside HTML5 WebWorker - Can send and receive binary data - Receives as ArrayBuffer or Blob when in browser, and Buffer or ArrayBuffer in Node - When XHR2 or WebSockets are used, binary is emitted directly. Otherwise binary is encoded into base64 strings, and decoded when binary types are supported. - With browsers that don't support ArrayBuffer, an object { base64: true, data: dataAsBase64String } is emitted on the `message` event. ## API ### Socket The client class. Mixes in [Emitter](http://github.com/component/emitter). Exposed as `eio` in the browser standalone build. #### Properties - `protocol` _(Number)_: protocol revision number - `binaryType` _(String)_ : can be set to 'arraybuffer' or 'blob' in browsers, and `buffer` or `arraybuffer` in Node. Blob is only used in browser if it's supported. #### Events - `open` - Fired upon successful connection. - `message` - Fired when data is received from the server. - **Arguments** - `String` | `ArrayBuffer`: utf-8 encoded data or ArrayBuffer containing binary data - `close` - Fired upon disconnection. In compliance with the WebSocket API spec, this event may be fired even if the `open` event does not occur (i.e. due to connection error or `close()`). - `error` - Fired when an error occurs. - `flush` - Fired upon completing a buffer flush - `drain` - Fired after `drain` event of transport if writeBuffer is empty - `upgradeError` - Fired if an error occurs with a transport we're trying to upgrade to. - `upgrade` - Fired upon upgrade success, after the new transport is set #### Methods - **constructor** - Initializes the client - **Parameters** - `String` uri - `Object`: optional, options object - **Options** - `agent` (`http.Agent`): `http.Agent` to use, defaults to `false` (NodeJS only) - `upgrade` (`Boolean`): defaults to true, whether the client should try to upgrade the transport from long-polling to something better. - `forceJSONP` (`Boolean`): forces JSONP for polling transport. - `forceBase64` (`Boolean`): forces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary. - `timestampRequests` (`Boolean`): whether to add the timestamp with each transport request. Note: this is ignored if the browser is IE or Android, in which case requests are always stamped (`false`) - `timestampParam` (`String`): timestamp parameter (`t`) - `flashPath` (`String`): path to flash client files with trailing slash - `policyPort` (`Number`): port the policy server listens on (`843`) - `path` (`String`): path to connect to, default is `/engine.io` - `transports` (`Array`): a list of transports to try (in order). Defaults to `['polling', 'websocket', 'flashsocket']`. `Engine` always attempts to connect directly with the first one, provided the feature detection test for it passes. - `rememberUpgrade` (`Boolean`): defaults to false. If true and if the previous websocket connection to the server succeeded, the connection attempt will bypass the normal upgrade process and will initially try websocket. A connection attempt following a transport error will use the normal upgrade process. It is recommended you turn this on only when using SSL/TLS connections, or if you know that your network does not block websockets. - `send` - Sends a message to the server - **Parameters** - `String` | `ArrayBuffer` | `ArrayBufferView` | `Blob`: data to send - `Function`: optional, callback upon `drain` - `close` - Disconnects the client. ### Transport The transport class. Private. _Inherits from EventEmitter_. #### Events - `poll`: emitted by polling transports upon starting a new request - `pollComplete`: emitted by polling transports upon completing a request - `drain`: emitted by polling transports upon a buffer drain ## Flash transport In order for the Flash transport to work correctly, ensure the `flashPath` property points to the location where the files `web_socket.js`, `swfobject.js` and `WebSocketMainInsecure.swf` are located. These files can be found here [https://github.com/gimite/web-socket-js.git](https://github.com/gimite/web-socket-js.git) ## Tests `engine.io-client` is used to test [engine](http://github.com/learnboost/engine.io). Running the `engine.io` test suite ensures the client works and vice-versa. Browser tests are run using [zuul](https://github.com/defunctzombie/zuul). You can run the tests locally using the following command. ``` ./node_modules/.bin/zuul --local 8080 -- test/index.js ``` Additionally, `engine.io-client` has a standalone test suite you can run with `make test` which will run node.js and browser tests. You must have zuul setup with a saucelabs account. ## Support The support channels for `engine.io-client` are the same as `socket.io`: - irc.freenode.net **#socket.io** - [Google Groups](http://groups.google.com/group/socket_io) - [Website](http://socket.io) ## Development To contribute patches, run tests or benchmarks, make sure to clone the repository: ```bash git clone git://github.com/LearnBoost/engine.io-client.git ``` Then: ```bash cd engine.io-client npm install ``` See the `Tests` section above for how to run tests before submitting any patches. ## License MIT - Copyright (c) 2014 Automattic, Inc.
{ "content_hash": "9a7ab707d395420daa16145c454bee5c", "timestamp": "", "source": "github", "line_count": 239, "max_line_length": 178, "avg_line_length": 32.55648535564853, "alnum_prop": 0.6993959645289809, "repo_name": "go-lab/smart-device", "id": "7a0704c76bd9a21461d508913ec883dc5e7ddf43", "size": "7802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RaspberryPi/robotic_arm-raspberry-pi/modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "4803" }, { "name": "C", "bytes": "33310" }, { "name": "C++", "bytes": "270335" }, { "name": "CSS", "bytes": "20043" }, { "name": "HTML", "bytes": "44506" }, { "name": "JavaScript", "bytes": "860597" }, { "name": "Makefile", "bytes": "30315" }, { "name": "Objective-C", "bytes": "4945" }, { "name": "PHP", "bytes": "1160" }, { "name": "Python", "bytes": "1440" }, { "name": "Shell", "bytes": "52" } ], "symlink_target": "" }
require 'spec_helper' describe Promisepay::Client do let(:client) { Promisepay::Client.new } describe 'initialize' do before { EnvironmentVariables.clean_up && Promisepay.setup } after { EnvironmentVariables.restore && Promisepay.setup } context 'without parameters' do it 'configures client with default values' do expect(client.api_domain).to be_a(String) expect(client.environment).to be_a(String) expect(client.username).to be_nil expect(client.token).to be_nil end end context 'with parameters' do let(:client_with_params) do Promisepay::Client.new( api_domain: 'api.domain.com', environment: 'production', username: 'myUsername', token: 'myToken' ) end it 'properly configures client' do expect(client_with_params.api_domain).to eql('api.domain.com') expect(client_with_params.environment).to eql('production') expect(client_with_params.username).to eql('myUsername') expect(client_with_params.token).to eql('myToken') end end context 'with environment variables' do before do ENV['PROMISEPAY_ENVIRONMENT'] = 'env_environment' ENV['PROMISEPAY_API_DOMAIN'] = 'env_api_domain' ENV['PROMISEPAY_USERNAME'] = 'env_username' ENV['PROMISEPAY_TOKEN'] = 'env_token' Promisepay.setup end it 'properly configures client' do expect(client.environment).to eql('env_environment') expect(client.api_domain).to eql('env_api_domain') expect(client.username).to eql('env_username') expect(client.token).to eql('env_token') end end end describe 'connection' do it 'returns a Faraday connection' do expect(client.connection).to be_a(Faraday::Connection) end end describe 'CRUD requests' do it 'are available' do expect(client).to respond_to(:get).with(2).arguments expect(client).to respond_to(:post).with(2).arguments expect(client).to respond_to(:patch).with(2).arguments expect(client).to respond_to(:delete).with(2).arguments end end describe 'self.resources' do it 'contains all available resources' do expect(Promisepay::Client.resources).to be_a(Hash) expect(Promisepay::Client.resources).to_not be_empty end end describe 'resources' do context 'when no request was previously made' do it 'is empty' do expect(client.resources).to be_empty end end context 'when requests were previously made', vcr: { cassette_name: 'users_multiple' } do before { client.users.find_all } it 'is not empty' do expect(client.resources).to_not be_empty end it 'contains previosuly used resources' do expect(client.resources).to have_key(:users) end end end end
{ "content_hash": "b1b7df936df5868bb81a3e8310cc1fb1", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 94, "avg_line_length": 30.239583333333332, "alnum_prop": 0.6469169824319669, "repo_name": "maccca/promisepay-ruby", "id": "c1a25e4019a849f2bc2fd1fa0aaa330afb2552f4", "size": "2903", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/promisepay/client_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "82253" } ], "symlink_target": "" }
package university.wur; import org.caleydo.core.internal.cmd.AOpenViewHandler; import org.caleydo.vis.lineup.model.RankTableModel; import demo.ARcpRankTableDemoView; import demo.IModelBuilder; import demo.project.model.RankTableSpec; /** * @author Samuel Gratzl * */ public class WorldUniversityRanking2012View extends ARcpRankTableDemoView { private static final String ID = "lineup.demo.university.wur2012"; @Override public IModelBuilder createModel(RankTableSpec tableSpec) { return new WorldUniversityRanking2012(tableSpec); } @Override protected String getCopyright() { return "QS World University Rankings® - 2012/2013"; } @Override public RankTableSpec createRankTableSpec() { RankTableModel t = getTable(); RankTableSpec tableSpec = t == null ? null : RankTableSpec.save(t, AWorldUniversityRanking.DATA_CREATOR); return tableSpec; } @Override public String getViewGUIID() { return ID; } public static class Handler extends AOpenViewHandler { public Handler() { super(ID); } } }
{ "content_hash": "182eb6f70f5d9fbb829ccc97408c0ab3", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 107, "avg_line_length": 22.955555555555556, "alnum_prop": 0.7666989351403679, "repo_name": "Caleydo/org.caleydo.vis.lineup.demos.data", "id": "a296be8a9ae0dfd397cfad56219c45ec932dece9", "size": "1400", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/university/wur/WorldUniversityRanking2012View.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "1580" }, { "name": "Java", "bytes": "119266" }, { "name": "JavaScript", "bytes": "6094" }, { "name": "R", "bytes": "705" } ], "symlink_target": "" }
<ion-view view-title="Exis+Ionic"> <ion-content class="padding"> <img class="exis-logo" src="img/exis-logo.png" alt="exisLogo"> <h2>Welcome to Exis+Ionic</h2> <p> This app shows how simple communication between clients and backend can be, enter text below and press <code>Send</code>. </p> <input type="text" placeholder="Hello World!" ng-model="input"> <button class="button button-block button-calm" ng-click="echo(input)">Send</button> <br /><br /> <p> Backend says: {{response}} </p> </ion-content> </ion-view>
{ "content_hash": "872add8afa6934a1bff63c83a648410b", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 125, "avg_line_length": 37.53333333333333, "alnum_prop": 0.6465364120781527, "repo_name": "exis-io/hello-ionic", "id": "9d31440bc1261b20f7bb339962bfb607c0b523fc", "size": "563", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/templates/tab-dash.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "956" }, { "name": "HTML", "bytes": "2472" }, { "name": "JavaScript", "bytes": "8484" } ], "symlink_target": "" }
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.appex.android.inquisitor.activity.AboutActivity.GoogleActivity"> <item android:id="@+id/action_settings" android:title="@string/action_settings" android:orderInCategory="100" app:showAsAction="never" /> </menu>
{ "content_hash": "1b41a77d668a101c8f84eeb03f685c48", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 87, "avg_line_length": 59.714285714285715, "alnum_prop": 0.7344497607655502, "repo_name": "anuraagbaishya/Inquisitor", "id": "d826fcf6f7bd8b46da5d5cc762e825d17edb8ee1", "size": "418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/menu/menu_google.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "577107" } ], "symlink_target": "" }
import { css } from 'glamor'; import { themeVariables, themeColors } from '@shopgate/pwa-common/helpers/config'; const sliderContainer = css({ marginLeft: 'auto', marginRight: 'auto', position: 'relative', paddingBottom: 10, }).toString(); const slider = css({ width: '100%', flex: 1, paddingTop: 16, paddingBottom: 16, }).toString(); const sliderItem = css({ width: '50%', }).toString(); const productInfo = css({ padding: 15, }).toString(); const productName = css({ fontWeight: 500, }).toString(); const priceGrid = css({ alignItems: 'flex-end', }).toString(); const priceStrikedItem = css({ flexGrow: 1, }).toString(); const priceItem = css({ flexGrow: 1, textAlign: 'right', }).toString(); const priceBase = css({ padding: '0 15px', }).toString(); const priceStriked = css({ ...priceBase, fontSize: '0.875rem', }).toString(); const price = css({ ...priceBase, color: themeColors.primary, fontSize: '1rem', }).toString(); const card = css({ background: themeColors.light, height: '100%', margin: '0px 8px', }).toString(); const headline = css({ fontSize: 18, margin: `0 0 ${themeVariables.gap.big}px`, textAlign: 'center', }).toString(); export default { card, headline, sliderContainer, slider, sliderItem, productInfo, productName, priceGrid, priceStrikedItem, priceItem, priceBase, priceStriked, price, };
{ "content_hash": "6874a3c6c42bc33fc03aadf366c06f55", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 82, "avg_line_length": 16.75, "alnum_prop": 0.650319829424307, "repo_name": "shopgate/theme-gmd", "id": "cef6dc6bbe6f838a18ee76f2f9ed42097cbc59ea", "size": "1407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "widgets/ProductSlider/style.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "683804" } ], "symlink_target": "" }
package com.cmendenhall.views; import com.cmendenhall.board.Board; import com.cmendenhall.utils.StringLoader; import com.cmendenhall.views.io.CharStreamConsole; import com.cmendenhall.views.io.IOHandler; import com.cmendenhall.views.io.SystemConsole; import java.util.HashMap; public class TerminalView implements View { private IOHandler io; public TerminalView() { setUpConsole(); } public TerminalView(IOHandler ioHandler) { io = ioHandler; } private void setUpConsole() { if (System.console() == null) { System.err.println("No system console found."); io = new CharStreamConsole(); } else { io = new SystemConsole(); } } public void displayBoard(Board board) { String boardString = board.toString(); io.print(boardString); } public void displayMessage(String message) { io.print(message); } public String getInput() { String input = io.readLine(); return input; } public void reload() { } public HashMap<String, String> getStrings() { HashMap<String, String> viewStrings = new StringLoader().getViewStrings("/viewstrings.properties"); return viewStrings; } }
{ "content_hash": "183534d4d978bb341e127048cccbbded", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 107, "avg_line_length": 24.056603773584907, "alnum_prop": 0.6423529411764706, "repo_name": "ecmendenhall/Java-TTT", "id": "b04ff84dfa27493eb894d633c5a129053ad63845", "size": "1275", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/cmendenhall/views/TerminalView.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "120284" } ], "symlink_target": "" }
package controllers import ( "github.com/revel/examples/chat/app/chatroom" "github.com/revel/revel" ) type LongPolling struct { *revel.Controller } func (c LongPolling) Room(user string) revel.Result { chatroom.Join(user) return c.Render(user) } func (c LongPolling) Say(user, message string) revel.Result { chatroom.Say(user, message) return nil } func (c LongPolling) WaitMessages(lastReceived int) revel.Result { subscription := chatroom.Subscribe() defer subscription.Cancel() // See if anything is new in the archive. var events []chatroom.Event for _, event := range subscription.Archive { if event.Timestamp > lastReceived { events = append(events, event) } } // If we found one, grand. if len(events) > 0 { return c.RenderJSON(events) } // Else, wait for something new. event := <-subscription.New return c.RenderJSON([]chatroom.Event{event}) } func (c LongPolling) Leave(user string) revel.Result { chatroom.Leave(user) return c.Redirect(Application.Index) }
{ "content_hash": "4e9e12d93a9c60b9b959157cdbb905cc", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 66, "avg_line_length": 21.425531914893618, "alnum_prop": 0.7239324726911619, "repo_name": "zhyhang/gofirst", "id": "49a238d3f1041c63a492152cdbc23955ad0a0c38", "size": "1007", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/revel/chat/app/controllers/longpolling.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2056" }, { "name": "Go", "bytes": "95000" }, { "name": "HTML", "bytes": "10530" }, { "name": "JavaScript", "bytes": "1192" } ], "symlink_target": "" }
libraryinit() function main(in type, in input, in mode, out output) { // evade compiler warning false and type and input and mode; // no conversion in this skeleton ioconv routine output = input; return true; } libraryexit()
{ "content_hash": "ef24755e1a657302ee805ba2cd8547a8", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 55, "avg_line_length": 16.785714285714285, "alnum_prop": 0.7191489361702128, "repo_name": "exodusdb/exodusdb", "id": "620a035dfc1a76ae33f4d532568a548155b25975", "size": "263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "exodus/libexodus/exodus/ioconv_custom.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "48844" }, { "name": "C++", "bytes": "2692110" }, { "name": "CMake", "bytes": "31492" }, { "name": "CSS", "bytes": "27076" }, { "name": "Classic ASP", "bytes": "51959" }, { "name": "HTML", "bytes": "502802" }, { "name": "JavaScript", "bytes": "852795" }, { "name": "Makefile", "bytes": "32" }, { "name": "PHP", "bytes": "69433" }, { "name": "Python", "bytes": "4101" }, { "name": "Shell", "bytes": "66668" } ], "symlink_target": "" }
package ru.job4j.accapplications; import java.util.Arrays; import java.util.Date; /** * Класс описывающий структуру заявки. * @author Artem Prokopov * @since 27.04.2017 * @version 1.0 */ public class Item { /** * Константа пустой заявки с id равному строке empty. */ public static final Item EMPTY_ITEM = new Item("empty"); /** * Поле id содержит уникальную идентификационную строку заявки. */ private final String id; /** * Поле name содержит имя создавшего заявку. */ private String name = ""; /** * Поле desc содержит описание заявки. */ private String desc = ""; /** * Поле created содержит врея создание заявки в мс. */ private long created = 0; /** * Поле comments содержит массив строк комментариев заявке. */ private String[] comments = new String[0]; /** * Private конструктод для создания пустой заявки. * @param str строка иницализации поля id */ private Item(String str) { this.id = str; } /** * Конструктор создающий базовую заявку. */ Item() { this.created = new Date().getTime(); this.id = Long.toString((this.created) / ((long) (Math.random() * 100) + 1L)) + "-" + (long) (Math.random() * 1000000); } /** * Геттер возвращает значение поля id{@link Item#id}. * @return возвращает значение поля id */ public String getId() { return id; } /** * Геттер возвращает значение поля name. * @return возвращает значение поля name */ public String getName() { return name; } /** * Сеттер устанавливает значени поля name. * @param name имя составителя заявки. */ public void setName(String name) { this.name = name; } /** * Геттер возвращает значение поля desc. * @return возвращает значение поля desc. */ public String getDesc() { return desc; } /** * Сеттер учтанавливает значение поля desc. * @param desc передаваямое значени. */ public void setDesc(String desc) { this.desc = desc; } /** * Геттер возвращает значение поля create. * @return возвращает значение поля create. */ public long getCreated() { return created; } /** * Сеттер устанавливает время созднания или обновления заявки. * @param created устанавливаемое время */ void setCreated(long created) { this.created = created; } /** * Сеттер устанавливает время создания или модификации заявки. * */ protected void setCreated() { this.created = new Date().getTime(); } /** * Геттер возвращает значение поля comments(массив комментариев). * @return возвращает значение поля comments. */ public String[] getComments() { return comments; } /** * Добавляет комментарий. * @param comments массив комментариев. */ protected void setComments(String[] comments) { this.comments = comments; } /** * Добавляет комментарий к заявке. * @param comment содержание комментария */ public void addComments(String comment) { if (this.comments.length == 0) { this.comments = new String[]{comment}; } else { String[] temp = new String[this.comments.length + 1]; System.arraycopy(this.comments, 0, temp, 0, this.comments.length); temp[temp.length - 1] = comment; this.comments = temp; } } /** * Удаляет комментарий из заявки. * @param delComment удаляемый комментарий. * @return возвращает true если операция зовершена успешно, иначе возвращает false. */ public boolean deletComment(String delComment) { if (this.comments.length != 0) { for (int i = 0; i < this.comments.length; i++) { if (delComment.equals(this.comments[i])) { String[] temp = new String[this.comments.length - 1]; System.arraycopy(this.comments, 0, temp, 0, i); System.arraycopy(this.comments, i + 1, temp, i, this.comments.length - i - 1); this.comments = temp; return true; } } } return false; } /** * Обновляет указанный комментарий. * @param upComment обновляемый комментарий. * @param newComment новый комментарий. * @return вовращает true если операция завершена успешно, иначе возвращает false/ */ public boolean updateComment(String upComment, String newComment) { if (this.comments.length != 0) { for (int i = 0; i < this.comments.length; i++) { if (upComment.equals(this.comments[i])) { this.comments[i] = newComment; return true; } } } return false; } /** * Метод сравнения объектов Item по полю id. * @param item объект с которым сравниваем. * @return true если поля равны. */ public boolean equalsId(Item item) { return this.id.equals(item.id); } /** * Метод сравнения объектов Item по содержанию полей кроме уникального поля id, * и даты создания. * @param item объект с которым сравниваем. * @return true если поля равны. */ public boolean equalsItem(Item item) { if (!this.name.equals(item.name)) { return false; } if (!this.desc.equals(item.desc)) { return false; } return Arrays.deepEquals(this.comments, item.comments); } /** * Метод получения копии объекта Item с сохранением уникального поля id, * и даты создания created. * @return копию объекта Item с сохранением idб и даты создания created. */ public Item getCopyItemSafeIdAndCreated() { Item item = new Item(this.id); item.setName(this.name); item.setDesc(this.desc); item.setCreated(this.created); item.setComments(this.comments); return item; } /** * Метод получения копии объекта Item с созданием уникального поля id, * и новой даты создания created. * @return копию объекта Item с сохранением id. */ public Item getCopyItemWithNewIdAndCreated() { Item item = new Item(); item.setName(this.name); item.setDesc(this.desc); item.setComments(this.comments); return item; } /** * Перегружаем метод equals класса Object. * @param o объект с которым сравниваем. * @return true если объекты равны, иначе false. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Item item = (Item) o; if (this.created != item.created) { return false; } if (!this.id.equals(item.id)) { return false; } if (!this.name.equals(item.name)) { return false; } if (!this.desc.equals(item.desc)) { return false; } return Arrays.deepEquals(this.comments, item.comments); } /** * Перегружаем метод hashCode. * @return возвращает hashCode. */ @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + name.hashCode(); result = 31 * result + desc.hashCode(); result = 31 * result + (int) (created ^ (created >>> 32)); result = 31 * result + Arrays.hashCode(comments); return result; } }
{ "content_hash": "c92dc1f7c815d3ce6adbd16cf5890702", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 98, "avg_line_length": 27.06228373702422, "alnum_prop": 0.5668073136427567, "repo_name": "artemprokopov/aprokopov", "id": "fb21a7dd9dc99975c6d0f57a81750dd7d950de9e", "size": "9418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_002/src/main/java/ru/job4j/accapplications/Item.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "529993" } ], "symlink_target": "" }
package org.eurekaj.plugins.riak.dao; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.eurekaj.api.dao.TreeMenuDao; import org.eurekaj.api.datatypes.Statistics; import org.eurekaj.api.datatypes.basic.BasicStatistics; import com.basho.riak.client.IRiakClient; import com.basho.riak.client.RiakException; import com.basho.riak.client.RiakRetryFailedException; import com.basho.riak.client.bucket.Bucket; import com.basho.riak.client.query.indexes.BucketIndex; public class RiakTreeMenuDao implements TreeMenuDao { private static final Logger logger = Logger.getLogger(RiakTreeMenuDao.class.getName()); private IRiakClient riakClient; public RiakTreeMenuDao(IRiakClient riakClient) { super(); this.riakClient = riakClient; } @Override public void persistTreeMenu(Statistics statistics) { //logger.info("Persisting tree menu: " + statistics.getGuiPath() + " for account: " + statistics.getAccountName()); Bucket myBucket = null; try { myBucket = riakClient.fetchBucket("Statistics;" + statistics.getAccountName()).execute(); myBucket.store(statistics.getGuiPath(), statistics).execute(); } catch (RiakRetryFailedException rrfe) { rrfe.printStackTrace(); } } @Override public List<Statistics> getTreeMenu(String accountName) { List<Statistics> statList = new ArrayList<Statistics>(); Bucket myBucket = null; try { myBucket = riakClient.fetchBucket("Statistics;" + accountName).execute(); for (String key : myBucket.fetchIndex(BucketIndex.index).withValue("$key").execute()) { statList.add(myBucket.fetch(key, BasicStatistics.class).execute()); } } catch (RiakRetryFailedException rrfe) { rrfe.printStackTrace(); } catch (RiakException e) { e.printStackTrace(); } return statList; } @Override public Statistics getTreeMenu(String guiPath, String accountName) { BasicStatistics statistics = null; Bucket myBucket = null; try { myBucket = riakClient.fetchBucket("Statistics;" + accountName).execute(); statistics = myBucket.fetch(guiPath, BasicStatistics.class).execute(); } catch (RiakRetryFailedException rrfe) { rrfe.printStackTrace(); } return statistics; } @Override public void deleteTreeMenu(String guiPath, String accountName) { Bucket myBucket = null; try { myBucket = riakClient.fetchBucket("Statistics;" + accountName).execute(); myBucket.delete(guiPath).execute(); } catch (RiakRetryFailedException rrfe) { rrfe.printStackTrace(); } catch (RiakException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
{ "content_hash": "b52549a9966bd70ad219fd7318504a64", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 117, "avg_line_length": 32.32954545454545, "alnum_prop": 0.6829525483304042, "repo_name": "NichenLg/Montric", "id": "e9d0874fbf352e29846bd73c8cf0d6585b36dbb1", "size": "2845", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Montric.RiakPlugin/src/main/java/org/eurekaj/plugins/riak/dao/RiakTreeMenuDao.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "48419" }, { "name": "HTML", "bytes": "60693" }, { "name": "Java", "bytes": "690582" }, { "name": "JavaScript", "bytes": "3222567" }, { "name": "Ruby", "bytes": "2395" }, { "name": "Shell", "bytes": "4267" } ], "symlink_target": "" }
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.service.protocol; import java.net.*; /** * The operation set is a very simplified version of the server stored info * operation sets, allowing protocol providers to implement a quick way of * showing user information, by simply returning a URL where the information * of a specific user is to be found. */ public interface OperationSetWebContactInfo extends OperationSet { /** * Returns the URL of a page containing information on <tt>contact</tt> * @param contact the <tt>Contact</tt> that we'd like to get information * about. * @return the URL of a page containing information on the specified * contact. */ public URL getWebContactInfo(Contact contact); /** * Returns the URL of a page containing information on the contact with the * specified <tt>contactAddress</tt>. * @param contactAddress the <tt>contactAddress</tt> that we'd like to get * information about. * @return the URL of a page containing information on the specified * contact. */ public URL getWebContactInfo(String contactAddress); }
{ "content_hash": "062ed1df24875c7c7e4a9bbc5d1a5677", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 79, "avg_line_length": 33.71052631578947, "alnum_prop": 0.7096018735362998, "repo_name": "ibauersachs/jitsi", "id": "b0dbcba2012220dc86a81552ad9938d513725fc9", "size": "1281", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "src/net/java/sip/communicator/service/protocol/OperationSetWebContactInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "423671" }, { "name": "C++", "bytes": "464408" }, { "name": "CSS", "bytes": "7555" }, { "name": "Groff", "bytes": "2384" }, { "name": "HTML", "bytes": "5051" }, { "name": "Java", "bytes": "21111446" }, { "name": "Makefile", "bytes": "12348" }, { "name": "Mathematica", "bytes": "21265" }, { "name": "Objective-C", "bytes": "171020" }, { "name": "Shell", "bytes": "13717" }, { "name": "Visual Basic", "bytes": "11032" }, { "name": "XSLT", "bytes": "1814" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; using WorldPayMvc.Models; namespace WorldPayMvc.Binders { public class WorldPayResponseModelBinder : DefaultModelBinder { private readonly static string[] WorldPayCustomVariables = new string[] { "MC_", "M_", "CM_" }; protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var type = typeof(WorldPayResponseModel); var model = Activator.CreateInstance(type) as WorldPayResponseModel; bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type); foreach (var key in controllerContext.HttpContext.Request.Form.AllKeys.Where(q => WorldPayCustomVariables.Any(v => q.StartsWith(v)))) { model.CustomProperties.Add(key, controllerContext.RequestContext.HttpContext.Request.Form.GetValues(key).First()); } return model; } } }
{ "content_hash": "ab1e97ead42de1215504cb5736537655", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 147, "avg_line_length": 42.15384615384615, "alnum_prop": 0.7153284671532847, "repo_name": "pjcunningham/WorldPayMvc", "id": "fb51fb7f60608ac9ae418cb6e9fb6ce56e3e4447", "size": "1098", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WorldPayMvc/Binders/WorldPayResponseModelBinder.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "C#", "bytes": "52472" }, { "name": "CSS", "bytes": "685" }, { "name": "JavaScript", "bytes": "10714" } ], "symlink_target": "" }
package com.docker.storage; public class DBException extends Exception{ private String debugReason; private int code; private int type; public static final int ERRORTYPE_UNKNOWN = 0; public static final int ERRORTYPE_DUPLICATEKEY = 1; public static final int ERRORTYPE_NETWORK = 2; public static final int ERRORTYPE_CURSORNOTFOUND = 3; /** * */ private static final long serialVersionUID = 2866216484067863942L; public DBException(int type, int code, String message, String debugReason){ super(message); this.debugReason = debugReason; this.code = code; this.type = type; System.out.println("[ERROR] " + this); } public DBException(int type, int code, String message){ this(type, code, message, null); } public String getDebugReason(){ return debugReason; } public String toString(){ return type + "-" + code + ": " + getMessage() + "; " + debugReason; } public void setCode(int code) { this.code = code; } public int getCode() { return code; } public void setType(int type) { this.type = type; } public int getType() { return type; } }
{ "content_hash": "b8c65f2afceb814226fd0cd4c1a62272", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 76, "avg_line_length": 20.90566037735849, "alnum_prop": 0.6931407942238267, "repo_name": "dobybros/scriptcore", "id": "119b502bb31c44a28838282371b6cb16ea03f57e", "size": "1108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SDockerCore/src/com/docker/storage/DBException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "77984" }, { "name": "HTML", "bytes": "611" }, { "name": "IDL", "bytes": "3714" }, { "name": "Java", "bytes": "901604" }, { "name": "JavaScript", "bytes": "12846" }, { "name": "Shell", "bytes": "1928" } ], "symlink_target": "" }
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("InterviewApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("InterviewApp")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("e6c23dc2-533a-4f79-96c1-69e325b1e438")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "8829e311fc8055a7060b43d4d72c37e1", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 38.77142857142857, "alnum_prop": 0.7487103905674282, "repo_name": "bfocht/interview_app", "id": "e36294dd2a7fa46e802c2a0410abb3b7b9f7ee7a", "size": "1360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "csharp/InterviewApp/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "C#", "bytes": "6487" }, { "name": "JavaScript", "bytes": "1073" }, { "name": "PowerShell", "bytes": "3137" }, { "name": "Python", "bytes": "1019" } ], "symlink_target": "" }
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2022] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::Draw::GlyphSet::simple_features; ### Standard rendering of data from simple_feature table (or similar) use strict; use parent qw(EnsEMBL::Draw::GlyphSet::Simple); sub init { my $self = shift; $self->{'my_config'}->set('bumped', 1); } sub get_data { my $self = shift; my $call = 'get_all_' . ($self->my_config('type') || 'SimpleFeatures'); my $db_type = $self->my_config('db'); my @feature_objects = map @{$self->{'container'}->$call($_, undef, $db_type)||[]}, @{$self->my_config('logic_names')||[]}; my $colours = $self->{'my_config'}->get('colours'); my $default_colour = 'red'; my $features = []; foreach my $f (@feature_objects) { my ($start, $end) = $self->ok_feature($f); next unless $start; push @$features, { 'start' => $start, 'end' => $end, 'colour' => $colours->{$f->analysis->logic_name}{'default'} || $default_colour, 'label' => $f->display_id, 'label_colour' => $colours->{$f->analysis->logic_name}{'text'} || $colours->{$f->analysis->logic_name}{'default'} || $default_colour, 'href' => $self->href($f), 'title' => $self->title($f), }; } return [{'features' => $features}]; } sub title { my ($self, $f) = @_; my ($start, $end) = $self->slice2sr($f->start, $f->end); my $score = length($f->score) ? sprintf('score: %s;', $f->score) : ''; return sprintf '%s: %s; %s bp: %s', $f->analysis->logic_name, $f->display_label, $score, "$start-$end"; } sub href { my ($self, $f) = @_; my $ext_url = $self->my_config('ext_url'); return undef unless $ext_url; my ($start, $end) = $self->slice2sr($f->start, $f->end); return $self->_url({ action => 'SimpleFeature', logic_name => $f->analysis->logic_name, display_label => $f->display_label, score => $f->score, bp => "$start-$end", ext_url => $ext_url }); } 1;
{ "content_hash": "1056b6f1e2ca25bc674c24dd4ebeb66e", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 124, "avg_line_length": 33.01136363636363, "alnum_prop": 0.5555938037865749, "repo_name": "Ensembl/ensembl-webcode", "id": "b796329ab6ae596301a2557a5b3195de811dbe13", "size": "2905", "binary": false, "copies": "1", "ref": "refs/heads/release/108", "path": "modules/EnsEMBL/Draw/GlyphSet/simple_features.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "22238" }, { "name": "CSS", "bytes": "357082" }, { "name": "Elixir", "bytes": "99" }, { "name": "HTML", "bytes": "239145" }, { "name": "JavaScript", "bytes": "1088839" }, { "name": "Perl", "bytes": "7118006" }, { "name": "Raku", "bytes": "11199" }, { "name": "Shell", "bytes": "16094" }, { "name": "XS", "bytes": "315" }, { "name": "XSLT", "bytes": "35709" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <languages> <language name="English" id="en"> <vulcan> <searchprovider> <pages> <name>Vulcan Pages</name> </pages> <blocks> <name>Vulcan Blocks</name> </blocks> <files> <name>Vulcan Files</name> </files> <products> <name>Vulcan Products</name> </products> </searchprovider> </vulcan> </language> </languages>
{ "content_hash": "54de98f1417be1ba2d8732c5f76b79c4", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 56, "avg_line_length": 23.476190476190474, "alnum_prop": 0.5152129817444219, "repo_name": "TCB-Internet-Solutions/vulcan", "id": "3dd034eada44bc20236a76c8c3398d5f56ac1a70", "size": "495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/TcbInternetSolutions.Vulcan.Core/Resources/LanguageFiles/Vulcan_en.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "279398" }, { "name": "HTML", "bytes": "11287" }, { "name": "JavaScript", "bytes": "3354" } ], "symlink_target": "" }
const UXRegExp = require('../uxregexp'); describe('UXRegExp:', () => { describe('test(...)', () => { it('should return false if no match', () => { var uxre = new UXRegExp('abc'); var result = uxre.test('xyz'); expect(result).toBe(false); }); it('should return true if match', () => { var uxre = new UXRegExp('abc'); var result = uxre.test('PREabcPOST'); expect(result).toBe(true); }); }); });
{ "content_hash": "0cbd51c8c3f5b6858a73ce10d28b0cde", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 49, "avg_line_length": 28.125, "alnum_prop": 0.5311111111111111, "repo_name": "hg42/uxregexp", "id": "495ff21e237cde5e4b2bff92ac0b2b1804da15bd", "size": "451", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/method-uxre-test-spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "40493" }, { "name": "Shell", "bytes": "366" } ], "symlink_target": "" }
package pl.java.scalatech.collection.map.simple; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.orm.jpa.EntityScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import pl.java.scalatech.config.hikari.HikariCPConfiguration; @EntityScan(basePackages = "pl.java.scalatech.domain.mapkey.entityExample") @EnableJpaRepositories(basePackages = "pl.java.scalatech.repository.map.entityExample") @Import({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, PersistenceExceptionTranslationAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,HikariCPConfiguration.class }) @Profile("mapExample") @Configuration public class JpaMapConfig { }
{ "content_hash": "87341fd062c1cc57a242c85463a90947", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 137, "avg_line_length": 52.65217391304348, "alnum_prop": 0.870355078447564, "repo_name": "przodownikR1/springJpaKata", "id": "f8425c5618099a2f5ee25b01a8f35795cce583ae", "size": "1211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/pl/java/scalatech/collection/map/simple/JpaMapConfig.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "444590" }, { "name": "PLSQL", "bytes": "4480" } ], "symlink_target": "" }
@implementation LGCard -(id) initWithNumber:(NSString *) number expiryMonth:(NSInteger) expMonth expiryYear:(NSInteger) expYear securityCode:(NSInteger) securityCode{ self = [super init]; if (self) { if ([number length] > 20) { return nil; } _number = number; if (expMonth > 12 || expMonth < 1) { return nil; } _expirationMonth = [NSString stringWithFormat:@"%02lu",(long)expMonth]; if (expYear > 2000) { // offset the expiration year if > 2000 expYear -= 2000; } if (expYear > 50) { // No support after 2050 return nil; } _expirationYear = [NSString stringWithFormat:@"%02lu", (long)expYear]; if (securityCode > 9999 || securityCode <= 99) { // Amex security may be 4 digits, no security code < 100 return nil; } _securityCode = [NSString stringWithFormat:@"%02lu", (long)securityCode]; } return self; } -(id) initWithNumber:(NSString *) number expiryMonth:(NSInteger) expMonth expiryYear:(NSInteger) expYear securityCode:(NSInteger) securityCode error:(NSError **) error{ self = [super init]; if (self) { if ([number length] > 20) { return nil; } _number = number; if (expMonth > 12 || expMonth < 1) { *error = [NSError errorWithDomain:@"com.soevolved.legato" code:LGCardErrorInvalidMonth userInfo:@{@"description" : @"Month should be between 1 and 12"}]; return nil; } _expirationMonth = [NSString stringWithFormat:@"%02lu",(long)expMonth]; if (expYear > 2000) { // offset the expiration year if > 2000 expYear -= 2000; } if (expYear > 50) { // No support after 2050 *error = [NSError errorWithDomain:@"com.soevolved.legato" code:LGCardErrorInvalidYear userInfo:nil]; return nil; } _expirationYear = [NSString stringWithFormat:@"%02lu", (long)expYear]; if (securityCode > 9999 || securityCode <= 99) { // Amex security may be 4 digits, no security code < 100 *error = [NSError errorWithDomain:@"com.soevolved.legato" code:LGCardErrorInvalidCCV userInfo:@{@"description":@"CCV sould be 3 numbers for Visa and MasterCard and 4 numbers for Amex"}]; return nil; } _securityCode = [NSString stringWithFormat:@"%02lu", (long)securityCode]; } return self; } @end
{ "content_hash": "ff56c8bc557df0bae10917799115ca1c", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 198, "avg_line_length": 37.85294117647059, "alnum_prop": 0.5765345765345765, "repo_name": "flovilmart/legato-ios", "id": "6468db82deb9268aaf1f646d9dc9eabbd0cfe19f", "size": "2729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Legato/LGCard.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "10823" } ], "symlink_target": "" }
namespace tera { namespace master { namespace test { class TableStateMachineTest : public ::testing::Test { public: TableStateMachineTest() : state_mchine_(kTableEnable) {} virtual ~TableStateMachineTest() {} virtual void SetUp() {} virtual void TearDown() {} static void SetUpTestCase() {} static void TearDownTestCase() {} private: bool TransitFromState(const TableStatus& status, const TableEvent& event) { state_mchine_.SetStatus(status); return state_mchine_.DoStateTransition(event); } TableStateMachine state_mchine_; }; TEST_F(TableStateMachineTest, LegalTransition) { EXPECT_TRUE(TransitFromState(kTableEnable, TableEvent::kDisableTable)); EXPECT_EQ(state_mchine_.GetStatus(), kTableDisable); EXPECT_TRUE(TransitFromState(kTableDisable, TableEvent::kEnableTable)); EXPECT_EQ(state_mchine_.GetStatus(), kTableEnable); EXPECT_TRUE(TransitFromState(kTableDisable, TableEvent::kDeleteTable)); EXPECT_EQ(state_mchine_.GetStatus(), kTableDeleting); EXPECT_TRUE(TransitFromState(kTableDeleting, TableEvent::kDisableTable)); EXPECT_EQ(state_mchine_.GetStatus(), kTableDisable); } TEST_F(TableStateMachineTest, IllegalTransition) { EXPECT_FALSE(TransitFromState(kTableEnable, TableEvent::kDeleteTable)); EXPECT_EQ(state_mchine_.GetStatus(), kTableEnable); EXPECT_FALSE(TransitFromState(kTableDeleting, TableEvent::kEnableTable)); EXPECT_EQ(state_mchine_.GetStatus(), kTableDeleting); std::cout << TableEvent::kEnableTable << std::endl; } } } }
{ "content_hash": "c059af9e0b66126feb8021788a97b1bc", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 77, "avg_line_length": 35.76190476190476, "alnum_prop": 0.7616511318242344, "repo_name": "BaiduPS/tera", "id": "242b2bdac3b96a56781141aec595df670d7f9fa4", "size": "1613", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/master/test/table_state_machine_test.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "80545" }, { "name": "C++", "bytes": "3656768" }, { "name": "CMake", "bytes": "1005" }, { "name": "Java", "bytes": "29791" }, { "name": "Makefile", "bytes": "16373" }, { "name": "Protocol Buffer", "bytes": "28979" }, { "name": "Python", "bytes": "121068" }, { "name": "Shell", "bytes": "36158" } ], "symlink_target": "" }
<?php /** _full_width.php * * Template Name: Full Width * * @author Konstantin Obenland * @package The Bootstrap * @since 1.3.0 - 29.04.2012 */ get_header(); ?> <section id="primary" class="span12"> <?php tha_content_before(); ?> <div id="content" role="main"> <?php tha_content_top(); the_post(); get_template_part( '/partials/content', 'page' ); comments_template( '', true ); tha_content_bottom(); ?> </div><!-- #content --> <?php tha_content_after(); ?> </section><!-- #primary --> <?php get_footer(); /* End of file _full_width.php */ /* Location: ./wp-content/themes/the-bootstrap/_full_width.php */
{ "content_hash": "21c4ba6fa304f892e54372446426a10e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 65, "avg_line_length": 19.9375, "alnum_prop": 0.603448275862069, "repo_name": "jw-psychopomp/FeedMoreForLess-webapp", "id": "b2dfd842ac3e08e7dffe8a84d908ef172407df67", "size": "638", "binary": false, "copies": "20", "ref": "refs/heads/master", "path": "wp-content/themes/the-bootstrap/templates/_full_width.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11623" }, { "name": "JavaScript", "bytes": "16230" }, { "name": "PHP", "bytes": "166805" } ], "symlink_target": "" }
package io.fabric8.jolokia.support; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.io.IOException; import java.lang.reflect.Array; /** * Factory method of JMX MBean proxies for working with Fabric */ public class JolokiaHelpers { private static ObjectMapper objectMapper = new ObjectMapper(); public static Object convertJolokiaToJavaType(Class<?> clazz, Object value) throws IOException { if (clazz.isArray()) { if (value instanceof JSONArray) { JSONArray jsonArray = (JSONArray) value; Object[] javaArray = (Object[]) Array.newInstance(clazz.getComponentType(), jsonArray.size()); int idx = 0; for (Object element : jsonArray) { Array.set(javaArray, idx++, convertJolokiaToJavaType(clazz.getComponentType(), element)); } return javaArray; } else { return null; } } else if (String.class.equals(clazz)) { return (value != null) ? value.toString() : null; } else if (clazz.equals(Byte.class) || clazz.equals(byte.class)) { Number number = asNumber(value); return number != null ? number.byteValue() : null; } else if (clazz.equals(Short.class) || clazz.equals(short.class)) { Number number = asNumber(value); return number != null ? number.shortValue() : null; } else if (clazz.equals(Integer.class) || clazz.equals(int.class)) { Number number = asNumber(value); return number != null ? number.intValue() : null; } else if (clazz.equals(Long.class) || clazz.equals(long.class)) { Number number = asNumber(value); return number != null ? number.longValue() : null; } else if (clazz.equals(Float.class) || clazz.equals(float.class)) { Number number = asNumber(value); return number != null ? number.floatValue() : null; } else if (clazz.equals(Double.class) || clazz.equals(double.class)) { Number number = asNumber(value); return number != null ? number.doubleValue() : null; } else if (value instanceof JSONObject) { JSONObject jsonObject = (JSONObject) value; if (!JSONObject.class.isAssignableFrom(clazz)) { String json = jsonObject.toJSONString(); return getObjectMapper().readerFor(clazz).readValue(json); } } return value; } public static ObjectMapper getObjectMapper() { return objectMapper; } public static void setObjectMapper(ObjectMapper objectMapper) { JolokiaHelpers.objectMapper = objectMapper; } protected static Number asNumber(Object value) { if (value instanceof Number) { return (Number) value; } else { return null; } } }
{ "content_hash": "1043b737d862074eb0dd4fc5eebf635f", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 110, "avg_line_length": 39.71052631578947, "alnum_prop": 0.6003976143141153, "repo_name": "sobkowiak/fabric8", "id": "8b4f1a31f7f48ccfd8796ec7c7938e75cc812808", "size": "3826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/jolokia-assertions/src/main/java/io/fabric8/jolokia/support/JolokiaHelpers.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2403" }, { "name": "FreeMarker", "bytes": "2319" }, { "name": "HTML", "bytes": "97599" }, { "name": "Java", "bytes": "2950853" }, { "name": "JavaScript", "bytes": "965" }, { "name": "RAML", "bytes": "6493" }, { "name": "Scala", "bytes": "5192" }, { "name": "Shell", "bytes": "39945" } ], "symlink_target": "" }
<?php /** * Include Crypt_Random */ // the class_exists() will only be called if the crypt_random_string function hasn't been defined and // will trigger a call to __autoload() if you're wanting to auto-load classes // call function_exists() a second time to stop the include_once from being called outside // of the auto loader if (!function_exists('crypt_random_string')) { include_once 'Random.php'; } /** * Include Crypt_Hash */ if (!class_exists('Crypt_Hash')) { include_once 'Hash.php'; } /**#@+ * @access public * @see self::encrypt() * @see self::decrypt() */ /** * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding} * (OAEP) for encryption / decryption. * * Uses sha1 by default. * * @see self::setHash() * @see self::setMGFHash() */ define('CRYPT_RSA_ENCRYPTION_OAEP', 1); /** * Use PKCS#1 padding. * * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards * compatibility with protocols (like SSH-1) written before OAEP's introduction. */ define('CRYPT_RSA_ENCRYPTION_PKCS1', 2); /** * Do not use any padding * * Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy * stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc. */ define('CRYPT_RSA_ENCRYPTION_NONE', 3); /**#@-*/ /**#@+ * @access public * @see self::sign() * @see self::verify() * @see self::setHash() */ /** * Use the Probabilistic Signature Scheme for signing * * Uses sha1 by default. * * @see self::setSaltLength() * @see self::setMGFHash() */ define('CRYPT_RSA_SIGNATURE_PSS', 1); /** * Use the PKCS#1 scheme by default. * * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards * compatibility with protocols (like SSH-2) written before PSS's introduction. */ define('CRYPT_RSA_SIGNATURE_PKCS1', 2); /**#@-*/ /**#@+ * @access private * @see self::createKey() */ /** * ASN1 Integer */ define('CRYPT_RSA_ASN1_INTEGER', 2); /** * ASN1 Bit String */ define('CRYPT_RSA_ASN1_BITSTRING', 3); /** * ASN1 Octet String */ define('CRYPT_RSA_ASN1_OCTETSTRING', 4); /** * ASN1 Object Identifier */ define('CRYPT_RSA_ASN1_OBJECT', 6); /** * ASN1 Sequence (with the constucted bit set) */ define('CRYPT_RSA_ASN1_SEQUENCE', 48); /**#@-*/ /**#@+ * @access private * @see self::Crypt_RSA() */ /** * To use the pure-PHP implementation */ define('CRYPT_RSA_MODE_INTERNAL', 1); /** * To use the OpenSSL library * * (if enabled; otherwise, the internal implementation will be used) */ define('CRYPT_RSA_MODE_OPENSSL', 2); /**#@-*/ /** * Default openSSL configuration file. */ define('CRYPT_RSA_OPENSSL_CONFIG', dirname(__FILE__) . '/../openssl.cnf'); /**#@+ * @access public * @see self::createKey() * @see self::setPrivateKeyFormat() */ /** * PKCS#1 formatted private key * * Used by OpenSSH */ define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0); /** * PuTTY formatted private key */ define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1); /** * XML formatted private key */ define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2); /** * PKCS#8 formatted private key */ define('CRYPT_RSA_PRIVATE_FORMAT_PKCS8', 8); /**#@-*/ /**#@+ * @access public * @see self::createKey() * @see self::setPublicKeyFormat() */ /** * Raw public key * * An array containing two Math_BigInteger objects. * * The exponent can be indexed with any of the following: * * 0, e, exponent, publicExponent * * The modulus can be indexed with any of the following: * * 1, n, modulo, modulus */ define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3); /** * PKCS#1 formatted public key (raw) * * Used by File/X509.php * * Has the following header: * * -----BEGIN RSA PUBLIC KEY----- * * Analogous to ssh-keygen's pem format (as specified by -m) */ define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 4); define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW', 4); /** * XML formatted public key */ define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5); /** * OpenSSH formatted public key * * Place in $HOME/.ssh/authorized_keys */ define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6); /** * PKCS#1 formatted public key (encapsulated) * * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set) * * Has the following header: * * -----BEGIN PUBLIC KEY----- * * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8 * is specific to private keys it's basically creating a DER-encoded wrapper * for keys. This just extends that same concept to public keys (much like ssh-keygen) */ define('CRYPT_RSA_PUBLIC_FORMAT_PKCS8', 7); /**#@-*/ /** * Pure-PHP PKCS#1 compliant implementation of RSA. * * @package Crypt_RSA * @author Jim Wigginton <terrafrost@php.net> * @access public */ class Crypt_RSA { /** * Precomputed Zero * * @var array * @access private */ var $zero; /** * Precomputed One * * @var array * @access private */ var $one; /** * Private Key Format * * @var int * @access private */ var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1; /** * Public Key Format * * @var int * @access public */ var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS8; /** * Modulus (ie. n) * * @var Math_BigInteger * @access private */ var $modulus; /** * Modulus length * * @var Math_BigInteger * @access private */ var $k; /** * Exponent (ie. e or d) * * @var Math_BigInteger * @access private */ var $exponent; /** * Primes for Chinese Remainder Theorem (ie. p and q) * * @var array * @access private */ var $primes; /** * Exponents for Chinese Remainder Theorem (ie. dP and dQ) * * @var array * @access private */ var $exponents; /** * Coefficients for Chinese Remainder Theorem (ie. qInv) * * @var array * @access private */ var $coefficients; /** * Hash name * * @var string * @access private */ var $hashName; /** * Hash function * * @var Crypt_Hash * @access private */ var $hash; /** * Length of hash function output * * @var int * @access private */ var $hLen; /** * Length of salt * * @var int * @access private */ var $sLen; /** * Hash function for the Mask Generation Function * * @var Crypt_Hash * @access private */ var $mgfHash; /** * Length of MGF hash function output * * @var int * @access private */ var $mgfHLen; /** * Encryption mode * * @var int * @access private */ var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP; /** * Signature mode * * @var int * @access private */ var $signatureMode = CRYPT_RSA_SIGNATURE_PSS; /** * Public Exponent * * @var mixed * @access private */ var $publicExponent = false; /** * Password * * @var string * @access private */ var $password = false; /** * Components * * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions - * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't. * * @see self::_start_element_handler() * @var array * @access private */ var $components = array(); /** * Current String * * For use with parsing XML formatted keys. * * @see self::_character_handler() * @see self::_stop_element_handler() * @var mixed * @access private */ var $current; /** * OpenSSL configuration file name. * * Set to null to use system configuration file. * @see self::createKey() * @var mixed * @Access public */ var $configFile; /** * Public key comment field. * * @var string * @access private */ var $comment = 'phpseclib-generated-key'; /** * The constructor * * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late. * * @return Crypt_RSA * @access public */ function Crypt_RSA() { if (!class_exists('Math_BigInteger')) { include_once 'Math/BigInteger.php'; } $this->configFile = CRYPT_RSA_OPENSSL_CONFIG; if (!defined('CRYPT_RSA_MODE')) { switch (true) { // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular, // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either. case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'): define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); break; // openssl_pkey_get_details - which is used in the only place Crypt/RSA.php uses OpenSSL - was introduced in PHP 5.2.0 case !function_exists('openssl_pkey_get_details'): define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); break; case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile): // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work ob_start(); @phpinfo(); $content = ob_get_contents(); ob_end_clean(); preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches); $versions = array(); if (!empty($matches[1])) { for ($i = 0; $i < count($matches[1]); $i++) { $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i]))); // Remove letter part in OpenSSL version if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) { $versions[$matches[1][$i]] = $fullVersion; } else { $versions[$matches[1][$i]] = $m[0]; } } } // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+ switch (true) { case !isset($versions['Header']): case !isset($versions['Library']): case $versions['Header'] == $versions['Library']: define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL); break; default: define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); define('MATH_BIGINTEGER_OPENSSL_DISABLE', true); } break; default: define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); } } $this->zero = new Math_BigInteger(); $this->one = new Math_BigInteger(1); $this->hash = new Crypt_Hash('sha1'); $this->hLen = $this->hash->getLength(); $this->hashName = 'sha1'; $this->mgfHash = new Crypt_Hash('sha1'); $this->mgfHLen = $this->mgfHash->getLength(); } /** * Create public / private key pair * * Returns an array with the following three elements: * - 'privatekey': The private key. * - 'publickey': The public key. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout). * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing. * * @access public * @param int $bits * @param int $timeout * @param Math_BigInteger $p */ function createKey($bits = 1024, $timeout = false, $partial = array()) { if (!defined('CRYPT_RSA_EXPONENT')) { // http://en.wikipedia.org/wiki/65537_%28number%29 define('CRYPT_RSA_EXPONENT', '65537'); } // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if // CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_INTERNAL. if CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_OPENSSL then // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key // generation when there's a chance neither gmp nor OpenSSL are installed) if (!defined('CRYPT_RSA_SMALLEST_PRIME')) { define('CRYPT_RSA_SMALLEST_PRIME', 4096); } // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum if (CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) { $config = array(); if (isset($this->configFile)) { $config['config'] = $this->configFile; } $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config); openssl_pkey_export($rsa, $privatekey, null, $config); $publickey = openssl_pkey_get_details($rsa); $publickey = $publickey['key']; $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1))); $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1))); // clear the buffer of error strings stemming from a minimalistic openssl.cnf while (openssl_error_string() !== false) { } return array( 'privatekey' => $privatekey, 'publickey' => $publickey, 'partialkey' => false ); } static $e; if (!isset($e)) { $e = new Math_BigInteger(CRYPT_RSA_EXPONENT); } extract($this->_generateMinMax($bits)); $absoluteMin = $min; $temp = $bits >> 1; // divide by two to see how many bits P and Q would be if ($temp > CRYPT_RSA_SMALLEST_PRIME) { $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME); $temp = CRYPT_RSA_SMALLEST_PRIME; } else { $num_primes = 2; } extract($this->_generateMinMax($temp + $bits % $temp)); $finalMax = $max; extract($this->_generateMinMax($temp)); $generator = new Math_BigInteger(); $n = $this->one->copy(); if (!empty($partial)) { extract(unserialize($partial)); } else { $exponents = $coefficients = $primes = array(); $lcm = array( 'top' => $this->one->copy(), 'bottom' => false ); } $start = time(); $i0 = count($primes) + 1; do { for ($i = $i0; $i <= $num_primes; $i++) { if ($timeout !== false) { $timeout-= time() - $start; $start = time(); if ($timeout <= 0) { return array( 'privatekey' => '', 'publickey' => '', 'partialkey' => serialize(array( 'primes' => $primes, 'coefficients' => $coefficients, 'lcm' => $lcm, 'exponents' => $exponents )) ); } } if ($i == $num_primes) { list($min, $temp) = $absoluteMin->divide($n); if (!$temp->equals($this->zero)) { $min = $min->add($this->one); // ie. ceil() } $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout); } else { $primes[$i] = $generator->randomPrime($min, $max, $timeout); } if ($primes[$i] === false) { // if we've reached the timeout if (count($primes) > 1) { $partialkey = ''; } else { array_pop($primes); $partialkey = serialize(array( 'primes' => $primes, 'coefficients' => $coefficients, 'lcm' => $lcm, 'exponents' => $exponents )); } return array( 'privatekey' => '', 'publickey' => '', 'partialkey' => $partialkey ); } // the first coefficient is calculated differently from the rest // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1]) if ($i > 2) { $coefficients[$i] = $n->modInverse($primes[$i]); } $n = $n->multiply($primes[$i]); $temp = $primes[$i]->subtract($this->one); // textbook RSA implementations use Euler's totient function instead of the least common multiple. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function $lcm['top'] = $lcm['top']->multiply($temp); $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp); $exponents[$i] = $e->modInverse($temp); } list($temp) = $lcm['top']->divide($lcm['bottom']); $gcd = $temp->gcd($e); $i0 = 1; } while (!$gcd->equals($this->one)); $d = $e->modInverse($temp); $coefficients[2] = $primes[2]->modInverse($primes[1]); // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>: // RSAPrivateKey ::= SEQUENCE { // version Version, // modulus INTEGER, -- n // publicExponent INTEGER, -- e // privateExponent INTEGER, -- d // prime1 INTEGER, -- p // prime2 INTEGER, -- q // exponent1 INTEGER, -- d mod (p-1) // exponent2 INTEGER, -- d mod (q-1) // coefficient INTEGER, -- (inverse of q) mod p // otherPrimeInfos OtherPrimeInfos OPTIONAL // } return array( 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients), 'publickey' => $this->_convertPublicKey($n, $e), 'partialkey' => false ); } /** * Convert a private key to the appropriate format. * * @access private * @see self::setPrivateKeyFormat() * @param string $RSAPrivateKey * @return string */ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients) { $signed = $this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_XML; $num_primes = count($primes); $raw = array( 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi 'modulus' => $n->toBytes($signed), 'publicExponent' => $e->toBytes($signed), 'privateExponent' => $d->toBytes($signed), 'prime1' => $primes[1]->toBytes($signed), 'prime2' => $primes[2]->toBytes($signed), 'exponent1' => $exponents[1]->toBytes($signed), 'exponent2' => $exponents[2]->toBytes($signed), 'coefficient' => $coefficients[2]->toBytes($signed) ); // if the format in question does not support multi-prime rsa and multi-prime rsa was used, // call _convertPublicKey() instead. switch ($this->privateKeyFormat) { case CRYPT_RSA_PRIVATE_FORMAT_XML: if ($num_primes != 2) { return false; } return "<RSAKeyValue>\r\n" . ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" . ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" . ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" . ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" . ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" . ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" . ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" . ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" . '</RSAKeyValue>'; break; case CRYPT_RSA_PRIVATE_FORMAT_PUTTY: if ($num_primes != 2) { return false; } $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: "; $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none'; $key.= $encryption; $key.= "\r\nComment: " . $this->comment . "\r\n"; $public = pack( 'Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus'] ); $source = pack( 'Na*Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption, strlen($this->comment), $this->comment, strlen($public), $public ); $public = base64_encode($public); $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n"; $key.= chunk_split($public, 64); $private = pack( 'Na*Na*Na*Na*', strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient'] ); if (empty($this->password) && !is_string($this->password)) { $source.= pack('Na*', strlen($private), $private); $hashkey = 'putty-private-key-file-mac-key'; } else { $private.= crypt_random_string(16 - (strlen($private) & 15)); $source.= pack('Na*', strlen($private), $private); if (!class_exists('Crypt_AES')) { include_once 'Crypt/AES.php'; } $sequence = 0; $symkey = ''; while (strlen($symkey) < 32) { $temp = pack('Na*', $sequence++, $this->password); $symkey.= pack('H*', sha1($temp)); } $symkey = substr($symkey, 0, 32); $crypto = new Crypt_AES(); $crypto->setKey($symkey); $crypto->disablePadding(); $private = $crypto->encrypt($private); $hashkey = 'putty-private-key-file-mac-key' . $this->password; } $private = base64_encode($private); $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n"; $key.= chunk_split($private, 64); if (!class_exists('Crypt_Hash')) { include_once 'Crypt/Hash.php'; } $hash = new Crypt_Hash('sha1'); $hash->setKey(pack('H*', sha1($hashkey))); $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n"; return $key; default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1 $components = array(); foreach ($raw as $name => $value) { $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value); } $RSAPrivateKey = implode('', $components); if ($num_primes > 2) { $OtherPrimeInfos = ''; for ($i = 3; $i <= $num_primes; $i++) { // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo // // OtherPrimeInfo ::= SEQUENCE { // prime INTEGER, -- ri // exponent INTEGER, -- di // coefficient INTEGER -- ti // } $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true)); $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true)); $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true)); $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo); } $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos); } $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); if ($this->privateKeyFormat == CRYPT_RSA_PRIVATE_FORMAT_PKCS8) { $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA $RSAPrivateKey = pack( 'Ca*a*Ca*a*', CRYPT_RSA_ASN1_INTEGER, "\01\00", $rsaOID, 4, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey ); $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); if (!empty($this->password) || is_string($this->password)) { $salt = crypt_random_string(8); $iterationCount = 2048; if (!class_exists('Crypt_DES')) { include_once 'Crypt/DES.php'; } $crypto = new Crypt_DES(); $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount); $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey); $parameters = pack( 'Ca*a*Ca*N', CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($salt)), $salt, CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(4), $iterationCount ); $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03"; $encryptionAlgorithm = pack( 'Ca*a*Ca*a*', CRYPT_RSA_ASN1_OBJECT, $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC, CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($parameters)), $parameters ); $RSAPrivateKey = pack( 'Ca*a*Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm, CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey ); $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END ENCRYPTED PRIVATE KEY-----'; } else { $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END PRIVATE KEY-----'; } return $RSAPrivateKey; } if (!empty($this->password) || is_string($this->password)) { $iv = crypt_random_string(8); $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8); if (!class_exists('Crypt_TripleDES')) { include_once 'Crypt/TripleDES.php'; } $des = new Crypt_TripleDES(); $des->setKey($symkey); $des->setIV($iv); $iv = strtoupper(bin2hex($iv)); $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . "Proc-Type: 4,ENCRYPTED\r\n" . "DEK-Info: DES-EDE3-CBC,$iv\r\n" . "\r\n" . chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) . '-----END RSA PRIVATE KEY-----'; } else { $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END RSA PRIVATE KEY-----'; } return $RSAPrivateKey; } } /** * Convert a public key to the appropriate format * * @access private * @see self::setPublicKeyFormat() * @param string $RSAPrivateKey * @return string */ function _convertPublicKey($n, $e) { $signed = $this->publicKeyFormat != CRYPT_RSA_PUBLIC_FORMAT_XML; $modulus = $n->toBytes($signed); $publicExponent = $e->toBytes($signed); switch ($this->publicKeyFormat) { case CRYPT_RSA_PUBLIC_FORMAT_RAW: return array('e' => $e->copy(), 'n' => $n->copy()); case CRYPT_RSA_PUBLIC_FORMAT_XML: return "<RSAKeyValue>\r\n" . ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" . ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" . '</RSAKeyValue>'; break; case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH: // from <http://tools.ietf.org/html/rfc4253#page-15>: // string "ssh-rsa" // mpint e // mpint n $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus); $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment; return $RSAPublicKey; default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1 // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>: // RSAPublicKey ::= SEQUENCE { // modulus INTEGER, -- n // publicExponent INTEGER -- e // } $components = array( 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus), 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent) ); $RSAPublicKey = pack( 'Ca*a*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])), $components['modulus'], $components['publicExponent'] ); if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW) { $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . chunk_split(base64_encode($RSAPublicKey), 64) . '-----END RSA PUBLIC KEY-----'; } else { // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA $RSAPublicKey = chr(0) . $RSAPublicKey; $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey; $RSAPublicKey = pack( 'Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey ); $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split(base64_encode($RSAPublicKey), 64) . '-----END PUBLIC KEY-----'; } return $RSAPublicKey; } } /** * Break a public or private key down into its constituant components * * @access private * @see self::_convertPublicKey() * @see self::_convertPrivateKey() * @param string $key * @param int $type * @return array */ function _parseKey($key, $type) { if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) { return false; } switch ($type) { case CRYPT_RSA_PUBLIC_FORMAT_RAW: if (!is_array($key)) { return false; } $components = array(); switch (true) { case isset($key['e']): $components['publicExponent'] = $key['e']->copy(); break; case isset($key['exponent']): $components['publicExponent'] = $key['exponent']->copy(); break; case isset($key['publicExponent']): $components['publicExponent'] = $key['publicExponent']->copy(); break; case isset($key[0]): $components['publicExponent'] = $key[0]->copy(); } switch (true) { case isset($key['n']): $components['modulus'] = $key['n']->copy(); break; case isset($key['modulo']): $components['modulus'] = $key['modulo']->copy(); break; case isset($key['modulus']): $components['modulus'] = $key['modulus']->copy(); break; case isset($key[1]): $components['modulus'] = $key[1]->copy(); } return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false; case CRYPT_RSA_PRIVATE_FORMAT_PKCS1: case CRYPT_RSA_PRIVATE_FORMAT_PKCS8: case CRYPT_RSA_PUBLIC_FORMAT_PKCS1: /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here: http://tools.ietf.org/html/rfc1421#section-4.6.1.1 http://tools.ietf.org/html/rfc1421#section-4.6.1.3 DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's own implementation. ie. the implementation *is* the standard and any bugs that may exist in that implementation are part of the standard, as well. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */ if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) { $iv = pack('H*', trim($matches[2])); $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8))); // remove the Proc-Type / DEK-Info sections as they're no longer needed $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key); $ciphertext = $this->_extractBER($key); if ($ciphertext === false) { $ciphertext = $key; } switch ($matches[1]) { case 'AES-256-CBC': if (!class_exists('Crypt_AES')) { include_once 'Crypt/AES.php'; } $crypto = new Crypt_AES(); break; case 'AES-128-CBC': if (!class_exists('Crypt_AES')) { include_once 'Crypt/AES.php'; } $symkey = substr($symkey, 0, 16); $crypto = new Crypt_AES(); break; case 'DES-EDE3-CFB': if (!class_exists('Crypt_TripleDES')) { include_once 'Crypt/TripleDES.php'; } $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB); break; case 'DES-EDE3-CBC': if (!class_exists('Crypt_TripleDES')) { include_once 'Crypt/TripleDES.php'; } $symkey = substr($symkey, 0, 24); $crypto = new Crypt_TripleDES(); break; case 'DES-CBC': if (!class_exists('Crypt_DES')) { include_once 'Crypt/DES.php'; } $crypto = new Crypt_DES(); break; default: return false; } $crypto->setKey($symkey); $crypto->setIV($iv); $decoded = $crypto->decrypt($ciphertext); } else { $decoded = $this->_extractBER($key); } if ($decoded !== false) { $key = $decoded; } $components = array(); if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($key) != strlen($key)) { return false; } $tag = ord($this->_string_shift($key)); /* intended for keys for which OpenSSL's asn1parse returns the following: 0:d=0 hl=4 l= 631 cons: SEQUENCE 4:d=1 hl=2 l= 1 prim: INTEGER :00 7:d=1 hl=2 l= 13 cons: SEQUENCE 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 20:d=2 hl=2 l= 0 prim: NULL 22:d=1 hl=4 l= 609 prim: OCTET STRING ie. PKCS8 keys*/ if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") { $this->_string_shift($key, 3); $tag = CRYPT_RSA_ASN1_SEQUENCE; } if ($tag == CRYPT_RSA_ASN1_SEQUENCE) { $temp = $this->_string_shift($key, $this->_decodeLength($key)); if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_OBJECT) { return false; } $length = $this->_decodeLength($temp); switch ($this->_string_shift($temp, $length)) { case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption break; case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC /* PBEParameter ::= SEQUENCE { salt OCTET STRING (SIZE(8)), iterationCount INTEGER } */ if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($temp) != strlen($temp)) { return false; } $this->_string_shift($temp); // assume it's an octet string $salt = $this->_string_shift($temp, $this->_decodeLength($temp)); if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_INTEGER) { return false; } $this->_decodeLength($temp); list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT)); $this->_string_shift($key); // assume it's an octet string $length = $this->_decodeLength($key); if (strlen($key) != $length) { return false; } if (!class_exists('Crypt_DES')) { include_once 'Crypt/DES.php'; } $crypto = new Crypt_DES(); $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount); $key = $crypto->decrypt($key); if ($key === false) { return false; } return $this->_parseKey($key, CRYPT_RSA_PRIVATE_FORMAT_PKCS1); default: return false; } /* intended for keys for which OpenSSL's asn1parse returns the following: 0:d=0 hl=4 l= 290 cons: SEQUENCE 4:d=1 hl=2 l= 13 cons: SEQUENCE 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 17:d=2 hl=2 l= 0 prim: NULL 19:d=1 hl=4 l= 271 prim: BIT STRING */ $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of // unused bits in the final subsequent octet. The number shall be in the range zero to seven." // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2) if ($tag == CRYPT_RSA_ASN1_BITSTRING) { $this->_string_shift($key); } if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($key) != strlen($key)) { return false; } $tag = ord($this->_string_shift($key)); } if ($tag != CRYPT_RSA_ASN1_INTEGER) { return false; } $length = $this->_decodeLength($key); $temp = $this->_string_shift($key, $length); if (strlen($temp) != 1 || ord($temp) > 2) { $components['modulus'] = new Math_BigInteger($temp, 256); $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER $length = $this->_decodeLength($key); $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256); return $components; } if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) { return false; } $length = $this->_decodeLength($key); $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256)); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256)); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), 256)); if (!empty($key)) { if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) { return false; } $this->_decodeLength($key); while (!empty($key)) { if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) { return false; } $this->_decodeLength($key); $key = substr($key, 1); $length = $this->_decodeLength($key); $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); } } return $components; case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH: $parts = explode(' ', $key, 3); $key = isset($parts[1]) ? base64_decode($parts[1]) : false; if ($key === false) { return false; } $comment = isset($parts[2]) ? $parts[2] : false; $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa"; if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256); if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256); if ($cleanup && strlen($key)) { if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $realModulus = new Math_BigInteger($this->_string_shift($key, $length), -256); return strlen($key) ? false : array( 'modulus' => $realModulus, 'publicExponent' => $modulus, 'comment' => $comment ); } else { return strlen($key) ? false : array( 'modulus' => $modulus, 'publicExponent' => $publicExponent, 'comment' => $comment ); } // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue // http://en.wikipedia.org/wiki/XML_Signature case CRYPT_RSA_PRIVATE_FORMAT_XML: case CRYPT_RSA_PUBLIC_FORMAT_XML: $this->components = array(); $xml = xml_parser_create('UTF-8'); xml_set_object($xml, $this); xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler'); xml_set_character_data_handler($xml, '_data_handler'); // add <xml></xml> to account for "dangling" tags like <BitStrength>...</BitStrength> that are sometimes added if (!xml_parse($xml, '<xml>' . $key . '</xml>')) { return false; } return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false; // from PuTTY's SSHPUBK.C case CRYPT_RSA_PRIVATE_FORMAT_PUTTY: $components = array(); $key = preg_split('#\r\n|\r|\n#', $key); $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0])); if ($type != 'ssh-rsa') { return false; } $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1])); $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2])); $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3])); $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength)))); $public = substr($public, 11); extract(unpack('Nlength', $this->_string_shift($public, 4))); $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256); extract(unpack('Nlength', $this->_string_shift($public, 4))); $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256); $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4])); $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength)))); switch ($encryption) { case 'aes256-cbc': if (!class_exists('Crypt_AES')) { include_once 'Crypt/AES.php'; } $symkey = ''; $sequence = 0; while (strlen($symkey) < 32) { $temp = pack('Na*', $sequence++, $this->password); $symkey.= pack('H*', sha1($temp)); } $symkey = substr($symkey, 0, 32); $crypto = new Crypt_AES(); } if ($encryption != 'none') { $crypto->setKey($symkey); $crypto->disablePadding(); $private = $crypto->decrypt($private); if ($private === false) { return false; } } extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256)); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256); $temp = $components['primes'][1]->subtract($this->one); $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp)); $temp = $components['primes'][2]->subtract($this->one); $components['exponents'][] = $components['publicExponent']->modInverse($temp); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256)); return $components; } } /** * Returns the key size * * More specifically, this returns the size of the modulo in bits. * * @access public * @return int */ function getSize() { return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits()); } /** * Start Element Handler * * Called by xml_set_element_handler() * * @access private * @param resource $parser * @param string $name * @param array $attribs */ function _start_element_handler($parser, $name, $attribs) { //$name = strtoupper($name); switch ($name) { case 'MODULUS': $this->current = &$this->components['modulus']; break; case 'EXPONENT': $this->current = &$this->components['publicExponent']; break; case 'P': $this->current = &$this->components['primes'][1]; break; case 'Q': $this->current = &$this->components['primes'][2]; break; case 'DP': $this->current = &$this->components['exponents'][1]; break; case 'DQ': $this->current = &$this->components['exponents'][2]; break; case 'INVERSEQ': $this->current = &$this->components['coefficients'][2]; break; case 'D': $this->current = &$this->components['privateExponent']; } $this->current = ''; } /** * Stop Element Handler * * Called by xml_set_element_handler() * * @access private * @param resource $parser * @param string $name */ function _stop_element_handler($parser, $name) { if (isset($this->current)) { $this->current = new Math_BigInteger(base64_decode($this->current), 256); unset($this->current); } } /** * Data Handler * * Called by xml_set_character_data_handler() * * @access private * @param resource $parser * @param string $data */ function _data_handler($parser, $data) { if (!isset($this->current) || is_object($this->current)) { return; } $this->current.= trim($data); } /** * Loads a public or private key * * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed) * * @access public * @param string $key * @param int $type optional */ function loadKey($key, $type = false) { if (is_object($key) && strtolower(get_class($key)) == 'crypt_rsa') { $this->privateKeyFormat = $key->privateKeyFormat; $this->publicKeyFormat = $key->publicKeyFormat; $this->k = $key->k; $this->hLen = $key->hLen; $this->sLen = $key->sLen; $this->mgfHLen = $key->mgfHLen; $this->encryptionMode = $key->encryptionMode; $this->signatureMode = $key->signatureMode; $this->password = $key->password; $this->configFile = $key->configFile; $this->comment = $key->comment; if (is_object($key->hash)) { $this->hash = new Crypt_Hash($key->hash->getHash()); } if (is_object($key->mgfHash)) { $this->mgfHash = new Crypt_Hash($key->mgfHash->getHash()); } if (is_object($key->modulus)) { $this->modulus = $key->modulus->copy(); } if (is_object($key->exponent)) { $this->exponent = $key->exponent->copy(); } if (is_object($key->publicExponent)) { $this->publicExponent = $key->publicExponent->copy(); } $this->primes = array(); $this->exponents = array(); $this->coefficients = array(); foreach ($this->primes as $prime) { $this->primes[] = $prime->copy(); } foreach ($this->exponents as $exponent) { $this->exponents[] = $exponent->copy(); } foreach ($this->coefficients as $coefficient) { $this->coefficients[] = $coefficient->copy(); } return true; } if ($type === false) { $types = array( CRYPT_RSA_PUBLIC_FORMAT_RAW, CRYPT_RSA_PRIVATE_FORMAT_PKCS1, CRYPT_RSA_PRIVATE_FORMAT_XML, CRYPT_RSA_PRIVATE_FORMAT_PUTTY, CRYPT_RSA_PUBLIC_FORMAT_OPENSSH ); foreach ($types as $type) { $components = $this->_parseKey($key, $type); if ($components !== false) { break; } } } else { $components = $this->_parseKey($key, $type); } if ($components === false) { return false; } if (isset($components['comment']) && $components['comment'] !== false) { $this->comment = $components['comment']; } $this->modulus = $components['modulus']; $this->k = strlen($this->modulus->toBytes()); $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent']; if (isset($components['primes'])) { $this->primes = $components['primes']; $this->exponents = $components['exponents']; $this->coefficients = $components['coefficients']; $this->publicExponent = $components['publicExponent']; } else { $this->primes = array(); $this->exponents = array(); $this->coefficients = array(); $this->publicExponent = false; } switch ($type) { case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH: case CRYPT_RSA_PUBLIC_FORMAT_RAW: $this->setPublicKey(); break; case CRYPT_RSA_PRIVATE_FORMAT_PKCS1: switch (true) { case strpos($key, '-BEGIN PUBLIC KEY-') !== false: case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false: $this->setPublicKey(); } } return true; } /** * Sets the password * * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false. * Or rather, pass in $password such that empty($password) && !is_string($password) is true. * * @see self::createKey() * @see self::loadKey() * @access public * @param string $password */ function setPassword($password = false) { $this->password = $password; } /** * Defines the public key * * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being * public. * * Do note that when a new key is loaded the index will be cleared. * * Returns true on success, false on failure * * @see self::getPublicKey() * @access public * @param string $key optional * @param int $type optional * @return bool */ function setPublicKey($key = false, $type = false) { // if a public key has already been loaded return false if (!empty($this->publicExponent)) { return false; } if ($key === false && !empty($this->modulus)) { $this->publicExponent = $this->exponent; return true; } if ($type === false) { $types = array( CRYPT_RSA_PUBLIC_FORMAT_RAW, CRYPT_RSA_PUBLIC_FORMAT_PKCS1, CRYPT_RSA_PUBLIC_FORMAT_XML, CRYPT_RSA_PUBLIC_FORMAT_OPENSSH ); foreach ($types as $type) { $components = $this->_parseKey($key, $type); if ($components !== false) { break; } } } else { $components = $this->_parseKey($key, $type); } if ($components === false) { return false; } if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) { $this->modulus = $components['modulus']; $this->exponent = $this->publicExponent = $components['publicExponent']; return true; } $this->publicExponent = $components['publicExponent']; return true; } /** * Defines the private key * * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force * phpseclib to treat the key as a private key. This function will do that. * * Do note that when a new key is loaded the index will be cleared. * * Returns true on success, false on failure * * @see self::getPublicKey() * @access public * @param string $key optional * @param int $type optional * @return bool */ function setPrivateKey($key = false, $type = false) { if ($key === false && !empty($this->publicExponent)) { $this->publicExponent = false; return true; } $rsa = new Crypt_RSA(); if (!$rsa->loadKey($key, $type)) { return false; } $rsa->publicExponent = false; // don't overwrite the old key if the new key is invalid $this->loadKey($rsa); return true; } /** * Returns the public key * * The public key is only returned under two circumstances - if the private key had the public key embedded within it * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this * function won't return it since this library, for the most part, doesn't distinguish between public and private keys. * * @see self::getPublicKey() * @access public * @param string $key * @param int $type optional */ function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS8) { if (empty($this->modulus) || empty($this->publicExponent)) { return false; } $oldFormat = $this->publicKeyFormat; $this->publicKeyFormat = $type; $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent); $this->publicKeyFormat = $oldFormat; return $temp; } /** * Returns the public key's fingerprint * * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is * no public key currently loaded, false is returned. * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716) * * @access public * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned * for invalid values. * @return mixed */ function getPublicKeyFingerprint($algorithm = 'md5') { if (empty($this->modulus) || empty($this->publicExponent)) { return false; } $modulus = $this->modulus->toBytes(true); $publicExponent = $this->publicExponent->toBytes(true); $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus); switch ($algorithm) { case 'sha256': $hash = new Crypt_Hash('sha256'); $base = base64_encode($hash->hash($RSAPublicKey)); return substr($base, 0, strlen($base) - 1); case 'md5': return substr(chunk_split(md5($RSAPublicKey), 2, ':'), 0, -1); default: return false; } } /** * Returns the private key * * The private key is only returned if the currently loaded key contains the constituent prime numbers. * * @see self::getPublicKey() * @access public * @param string $key * @param int $type optional * @return mixed */ function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1) { if (empty($this->primes)) { return false; } $oldFormat = $this->privateKeyFormat; $this->privateKeyFormat = $type; $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients); $this->privateKeyFormat = $oldFormat; return $temp; } /** * Returns a minimalistic private key * * Returns the private key without the prime number constituants. Structurally identical to a public key that * hasn't been set as the public key * * @see self::getPrivateKey() * @access private * @param string $key * @param int $type optional */ function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS8) { if (empty($this->modulus) || empty($this->exponent)) { return false; } $oldFormat = $this->publicKeyFormat; $this->publicKeyFormat = $mode; $temp = $this->_convertPublicKey($this->modulus, $this->exponent); $this->publicKeyFormat = $oldFormat; return $temp; } /** * __toString() magic method * * @access public * @return string */ function __toString() { $key = $this->getPrivateKey($this->privateKeyFormat); if ($key !== false) { return $key; } $key = $this->_getPrivatePublicKey($this->publicKeyFormat); return $key !== false ? $key : ''; } /** * __clone() magic method * * @access public * @return Crypt_RSA */ function __clone() { $key = new Crypt_RSA(); $key->loadKey($this); return $key; } /** * Generates the smallest and largest numbers requiring $bits bits * * @access private * @param int $bits * @return array */ function _generateMinMax($bits) { $bytes = $bits >> 3; $min = str_repeat(chr(0), $bytes); $max = str_repeat(chr(0xFF), $bytes); $msb = $bits & 7; if ($msb) { $min = chr(1 << ($msb - 1)) . $min; $max = chr((1 << $msb) - 1) . $max; } else { $min[0] = chr(0x80); } return array( 'min' => new Math_BigInteger($min, 256), 'max' => new Math_BigInteger($max, 256) ); } /** * DER-decode the length * * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private * @param string $string * @return int */ function _decodeLength(&$string) { $length = ord($this->_string_shift($string)); if ($length & 0x80) { // definite length, long form $length&= 0x7F; $temp = $this->_string_shift($string, $length); list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)); } return $length; } /** * DER-encode the length * * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private * @param int $length * @return string */ function _encodeLength($length) { if ($length <= 0x7F) { return chr($length); } $temp = ltrim(pack('N', $length), chr(0)); return pack('Ca*', 0x80 | strlen($temp), $temp); } /** * String Shift * * Inspired by array_shift * * @param string $string * @param int $index * @return string * @access private */ function _string_shift(&$string, $index = 1) { $substr = substr($string, 0, $index); $string = substr($string, $index); return $substr; } /** * Determines the private key format * * @see self::createKey() * @access public * @param int $format */ function setPrivateKeyFormat($format) { $this->privateKeyFormat = $format; } /** * Determines the public key format * * @see self::createKey() * @access public * @param int $format */ function setPublicKeyFormat($format) { $this->publicKeyFormat = $format; } /** * Determines which hashing function should be used * * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and * decryption. If $hash isn't supported, sha1 is used. * * @access public * @param string $hash */ function setHash($hash) { // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example. switch ($hash) { case 'md2': case 'md5': case 'sha1': case 'sha256': case 'sha384': case 'sha512': $this->hash = new Crypt_Hash($hash); $this->hashName = $hash; break; default: $this->hash = new Crypt_Hash('sha1'); $this->hashName = 'sha1'; } $this->hLen = $this->hash->getLength(); } /** * Determines which hashing function should be used for the mask generation function * * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's * best if Hash and MGFHash are set to the same thing this is not a requirement. * * @access public * @param string $hash */ function setMGFHash($hash) { // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example. switch ($hash) { case 'md2': case 'md5': case 'sha1': case 'sha256': case 'sha384': case 'sha512': $this->mgfHash = new Crypt_Hash($hash); break; default: $this->mgfHash = new Crypt_Hash('sha1'); } $this->mgfHLen = $this->mgfHash->getLength(); } /** * Determines the salt length * * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}: * * Typical salt lengths in octets are hLen (the length of the output * of the hash function Hash) and 0. * * @access public * @param int $format */ function setSaltLength($sLen) { $this->sLen = $sLen; } /** * Integer-to-Octet-String primitive * * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}. * * @access private * @param Math_BigInteger $x * @param int $xLen * @return string */ function _i2osp($x, $xLen) { $x = $x->toBytes(); if (strlen($x) > $xLen) { user_error('Integer too large'); return false; } return str_pad($x, $xLen, chr(0), STR_PAD_LEFT); } /** * Octet-String-to-Integer primitive * * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}. * * @access private * @param string $x * @return Math_BigInteger */ function _os2ip($x) { return new Math_BigInteger($x, 256); } /** * Exponentiate with or without Chinese Remainder Theorem * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}. * * @access private * @param Math_BigInteger $x * @return Math_BigInteger */ function _exponentiate($x) { if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) { return $x->modPow($this->exponent, $this->modulus); } $num_primes = count($this->primes); if (defined('CRYPT_RSA_DISABLE_BLINDING')) { $m_i = array( 1 => $x->modPow($this->exponents[1], $this->primes[1]), 2 => $x->modPow($this->exponents[2], $this->primes[2]) ); $h = $m_i[1]->subtract($m_i[2]); $h = $h->multiply($this->coefficients[2]); list(, $h) = $h->divide($this->primes[1]); $m = $m_i[2]->add($h->multiply($this->primes[2])); $r = $this->primes[1]; for ($i = 3; $i <= $num_primes; $i++) { $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]); $r = $r->multiply($this->primes[$i - 1]); $h = $m_i->subtract($m); $h = $h->multiply($this->coefficients[$i]); list(, $h) = $h->divide($this->primes[$i]); $m = $m->add($r->multiply($h)); } } else { $smallest = $this->primes[1]; for ($i = 2; $i <= $num_primes; $i++) { if ($smallest->compare($this->primes[$i]) > 0) { $smallest = $this->primes[$i]; } } $one = new Math_BigInteger(1); $r = $one->random($one, $smallest->subtract($one)); $m_i = array( 1 => $this->_blind($x, $r, 1), 2 => $this->_blind($x, $r, 2) ); $h = $m_i[1]->subtract($m_i[2]); $h = $h->multiply($this->coefficients[2]); list(, $h) = $h->divide($this->primes[1]); $m = $m_i[2]->add($h->multiply($this->primes[2])); $r = $this->primes[1]; for ($i = 3; $i <= $num_primes; $i++) { $m_i = $this->_blind($x, $r, $i); $r = $r->multiply($this->primes[$i - 1]); $h = $m_i->subtract($m); $h = $h->multiply($this->coefficients[$i]); list(, $h) = $h->divide($this->primes[$i]); $m = $m->add($r->multiply($h)); } } return $m; } /** * Performs RSA Blinding * * Protects against timing attacks by employing RSA Blinding. * Returns $x->modPow($this->exponents[$i], $this->primes[$i]) * * @access private * @param Math_BigInteger $x * @param Math_BigInteger $r * @param int $i * @return Math_BigInteger */ function _blind($x, $r, $i) { $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i])); $x = $x->modPow($this->exponents[$i], $this->primes[$i]); $r = $r->modInverse($this->primes[$i]); $x = $x->multiply($r); list(, $x) = $x->divide($this->primes[$i]); return $x; } /** * Performs blinded RSA equality testing * * Protects against a particular type of timing attack described. * * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)} * * Thanks for the heads up singpolyma! * * @access private * @param string $x * @param string $y * @return bool */ function _equals($x, $y) { if (strlen($x) != strlen($y)) { return false; } $result = 0; for ($i = 0; $i < strlen($x); $i++) { $result |= ord($x[$i]) ^ ord($y[$i]); } return $result == 0; } /** * RSAEP * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}. * * @access private * @param Math_BigInteger $m * @return Math_BigInteger */ function _rsaep($m) { if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) { user_error('Message representative out of range'); return false; } return $this->_exponentiate($m); } /** * RSADP * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}. * * @access private * @param Math_BigInteger $c * @return Math_BigInteger */ function _rsadp($c) { if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) { user_error('Ciphertext representative out of range'); return false; } return $this->_exponentiate($c); } /** * RSASP1 * * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}. * * @access private * @param Math_BigInteger $m * @return Math_BigInteger */ function _rsasp1($m) { if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) { user_error('Message representative out of range'); return false; } return $this->_exponentiate($m); } /** * RSAVP1 * * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}. * * @access private * @param Math_BigInteger $s * @return Math_BigInteger */ function _rsavp1($s) { if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) { user_error('Signature representative out of range'); return false; } return $this->_exponentiate($s); } /** * MGF1 * * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}. * * @access private * @param string $mgfSeed * @param int $mgfLen * @return string */ function _mgf1($mgfSeed, $maskLen) { // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output. $t = ''; $count = ceil($maskLen / $this->mgfHLen); for ($i = 0; $i < $count; $i++) { $c = pack('N', $i); $t.= $this->mgfHash->hash($mgfSeed . $c); } return substr($t, 0, $maskLen); } /** * RSAES-OAEP-ENCRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}. * * @access private * @param string $m * @param string $l * @return string */ function _rsaes_oaep_encrypt($m, $l = '') { $mLen = strlen($m); // Length checking // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. if ($mLen > $this->k - 2 * $this->hLen - 2) { user_error('Message too long'); return false; } // EME-OAEP encoding $lHash = $this->hash->hash($l); $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2); $db = $lHash . $ps . chr(1) . $m; $seed = crypt_random_string($this->hLen); $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1); $maskedDB = $db ^ $dbMask; $seedMask = $this->_mgf1($maskedDB, $this->hLen); $maskedSeed = $seed ^ $seedMask; $em = chr(0) . $maskedSeed . $maskedDB; // RSA encryption $m = $this->_os2ip($em); $c = $this->_rsaep($m); $c = $this->_i2osp($c, $this->k); // Output the ciphertext C return $c; } /** * RSAES-OAEP-DECRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2: * * Note. Care must be taken to ensure that an opponent cannot * distinguish the different error conditions in Step 3.g, whether by * error message or timing, or, more generally, learn partial * information about the encoded message EM. Otherwise an opponent may * be able to obtain useful information about the decryption of the * ciphertext C, leading to a chosen-ciphertext attack such as the one * observed by Manger [36]. * * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}: * * Both the encryption and the decryption operations of RSAES-OAEP take * the value of a label L as input. In this version of PKCS #1, L is * the empty string; other uses of the label are outside the scope of * this document. * * @access private * @param string $c * @param string $l * @return string */ function _rsaes_oaep_decrypt($c, $l = '') { // Length checking // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) { user_error('Decryption error'); return false; } // RSA decryption $c = $this->_os2ip($c); $m = $this->_rsadp($c); if ($m === false) { user_error('Decryption error'); return false; } $em = $this->_i2osp($m, $this->k); // EME-OAEP decoding $lHash = $this->hash->hash($l); $y = ord($em[0]); $maskedSeed = substr($em, 1, $this->hLen); $maskedDB = substr($em, $this->hLen + 1); $seedMask = $this->_mgf1($maskedDB, $this->hLen); $seed = $maskedSeed ^ $seedMask; $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1); $db = $maskedDB ^ $dbMask; $lHash2 = substr($db, 0, $this->hLen); $m = substr($db, $this->hLen); if ($lHash != $lHash2) { user_error('Decryption error'); return false; } $m = ltrim($m, chr(0)); if (ord($m[0]) != 1) { user_error('Decryption error'); return false; } // Output the message M return substr($m, 1); } /** * Raw Encryption / Decryption * * Doesn't use padding and is not recommended. * * @access private * @param string $m * @return string */ function _raw_encrypt($m) { $temp = $this->_os2ip($m); $temp = $this->_rsaep($temp); return $this->_i2osp($temp, $this->k); } /** * RSAES-PKCS1-V1_5-ENCRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}. * * @access private * @param string $m * @return string */ function _rsaes_pkcs1_v1_5_encrypt($m) { $mLen = strlen($m); // Length checking if ($mLen > $this->k - 11) { user_error('Message too long'); return false; } // EME-PKCS1-v1_5 encoding $psLen = $this->k - $mLen - 3; $ps = ''; while (strlen($ps) != $psLen) { $temp = crypt_random_string($psLen - strlen($ps)); $temp = str_replace("\x00", '', $temp); $ps.= $temp; } $type = 2; // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) { $type = 1; // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF" $ps = str_repeat("\xFF", $psLen); } $em = chr(0) . chr($type) . $ps . chr(0) . $m; // RSA encryption $m = $this->_os2ip($em); $c = $this->_rsaep($m); $c = $this->_i2osp($c, $this->k); // Output the ciphertext C return $c; } /** * RSAES-PKCS1-V1_5-DECRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}. * * For compatibility purposes, this function departs slightly from the description given in RFC3447. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the * second byte is 2 or less. If it is, we'll accept the decrypted string as valid. * * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but * not private key encrypted ciphertext's. * * @access private * @param string $c * @return string */ function _rsaes_pkcs1_v1_5_decrypt($c) { // Length checking if (strlen($c) != $this->k) { // or if k < 11 user_error('Decryption error'); return false; } // RSA decryption $c = $this->_os2ip($c); $m = $this->_rsadp($c); if ($m === false) { user_error('Decryption error'); return false; } $em = $this->_i2osp($m, $this->k); // EME-PKCS1-v1_5 decoding if (ord($em[0]) != 0 || ord($em[1]) > 2) { user_error('Decryption error'); return false; } $ps = substr($em, 2, strpos($em, chr(0), 2) - 2); $m = substr($em, strlen($ps) + 3); if (strlen($ps) < 8) { user_error('Decryption error'); return false; } // Output M return $m; } /** * EMSA-PSS-ENCODE * * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}. * * @access private * @param string $m * @param int $emBits */ function _emsa_pss_encode($m, $emBits) { // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8) $sLen = $this->sLen ? $this->sLen : $this->hLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { user_error('Encoding error'); return false; } $salt = crypt_random_string($sLen); $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; $h = $this->hash->hash($m2); $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2); $db = $ps . chr(1) . $salt; $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); $maskedDB = $db ^ $dbMask; $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0]; $em = $maskedDB . $h . chr(0xBC); return $em; } /** * EMSA-PSS-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}. * * @access private * @param string $m * @param string $em * @param int $emBits * @return string */ function _emsa_pss_verify($m, $em, $emBits) { // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8); $sLen = $this->sLen ? $this->sLen : $this->hLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { return false; } if ($em[strlen($em) - 1] != chr(0xBC)) { return false; } $maskedDB = substr($em, 0, -$this->hLen - 1); $h = substr($em, -$this->hLen - 1, $this->hLen); $temp = chr(0xFF << ($emBits & 7)); if ((~$maskedDB[0] & $temp) != $temp) { return false; } $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); $db = $maskedDB ^ $dbMask; $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0]; $temp = $emLen - $this->hLen - $sLen - 2; if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) { return false; } $salt = substr($db, $temp + 1); // should be $sLen long $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; $h2 = $this->hash->hash($m2); return $this->_equals($h, $h2); } /** * RSASSA-PSS-SIGN * * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}. * * @access private * @param string $m * @return string */ function _rsassa_pss_sign($m) { // EMSA-PSS encoding $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1); // RSA signature $m = $this->_os2ip($em); $s = $this->_rsasp1($m); $s = $this->_i2osp($s, $this->k); // Output the signature S return $s; } /** * RSASSA-PSS-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}. * * @access private * @param string $m * @param string $s * @return string */ function _rsassa_pss_verify($m, $s) { // Length checking if (strlen($s) != $this->k) { user_error('Invalid signature'); return false; } // RSA verification $modBits = 8 * $this->k; $s2 = $this->_os2ip($s); $m2 = $this->_rsavp1($s2); if ($m2 === false) { user_error('Invalid signature'); return false; } $em = $this->_i2osp($m2, $modBits >> 3); if ($em === false) { user_error('Invalid signature'); return false; } // EMSA-PSS verification return $this->_emsa_pss_verify($m, $em, $modBits - 1); } /** * EMSA-PKCS1-V1_5-ENCODE * * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}. * * @access private * @param string $m * @param int $emLen * @return string */ function _emsa_pkcs1_v1_5_encode($m, $emLen) { $h = $this->hash->hash($m); if ($h === false) { return false; } // see http://tools.ietf.org/html/rfc3447#page-43 switch ($this->hashName) { case 'md2': $t = pack('H*', '3020300c06082a864886f70d020205000410'); break; case 'md5': $t = pack('H*', '3020300c06082a864886f70d020505000410'); break; case 'sha1': $t = pack('H*', '3021300906052b0e03021a05000414'); break; case 'sha256': $t = pack('H*', '3031300d060960864801650304020105000420'); break; case 'sha384': $t = pack('H*', '3041300d060960864801650304020205000430'); break; case 'sha512': $t = pack('H*', '3051300d060960864801650304020305000440'); } $t.= $h; $tLen = strlen($t); if ($emLen < $tLen + 11) { user_error('Intended encoded message length too short'); return false; } $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3); $em = "\0\1$ps\0$t"; return $em; } /** * RSASSA-PKCS1-V1_5-SIGN * * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}. * * @access private * @param string $m * @return string */ function _rsassa_pkcs1_v1_5_sign($m) { // EMSA-PKCS1-v1_5 encoding $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k); if ($em === false) { user_error('RSA modulus too short'); return false; } // RSA signature $m = $this->_os2ip($em); $s = $this->_rsasp1($m); $s = $this->_i2osp($s, $this->k); // Output the signature S return $s; } /** * RSASSA-PKCS1-V1_5-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}. * * @access private * @param string $m * @return string */ function _rsassa_pkcs1_v1_5_verify($m, $s) { // Length checking if (strlen($s) != $this->k) { user_error('Invalid signature'); return false; } // RSA verification $s = $this->_os2ip($s); $m2 = $this->_rsavp1($s); if ($m2 === false) { user_error('Invalid signature'); return false; } $em = $this->_i2osp($m2, $this->k); if ($em === false) { user_error('Invalid signature'); return false; } // EMSA-PKCS1-v1_5 encoding $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k); if ($em2 === false) { user_error('RSA modulus too short'); return false; } // Compare return $this->_equals($em, $em2); } /** * Set Encryption Mode * * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1. * * @access public * @param int $mode */ function setEncryptionMode($mode) { $this->encryptionMode = $mode; } /** * Set Signature Mode * * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1 * * @access public * @param int $mode */ function setSignatureMode($mode) { $this->signatureMode = $mode; } /** * Set public key comment. * * @access public * @param string $comment */ function setComment($comment) { $this->comment = $comment; } /** * Get public key comment. * * @access public * @return string */ function getComment() { return $this->comment; } /** * Encryption * * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will * be concatenated together. * * @see self::decrypt() * @access public * @param string $plaintext * @return string */ function encrypt($plaintext) { switch ($this->encryptionMode) { case CRYPT_RSA_ENCRYPTION_NONE: $plaintext = str_split($plaintext, $this->k); $ciphertext = ''; foreach ($plaintext as $m) { $ciphertext.= $this->_raw_encrypt($m); } return $ciphertext; case CRYPT_RSA_ENCRYPTION_PKCS1: $length = $this->k - 11; if ($length <= 0) { return false; } $plaintext = str_split($plaintext, $length); $ciphertext = ''; foreach ($plaintext as $m) { $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m); } return $ciphertext; //case CRYPT_RSA_ENCRYPTION_OAEP: default: $length = $this->k - 2 * $this->hLen - 2; if ($length <= 0) { return false; } $plaintext = str_split($plaintext, $length); $ciphertext = ''; foreach ($plaintext as $m) { $ciphertext.= $this->_rsaes_oaep_encrypt($m); } return $ciphertext; } } /** * Decryption * * @see self::encrypt() * @access public * @param string $plaintext * @return string */ function decrypt($ciphertext) { if ($this->k <= 0) { return false; } $ciphertext = str_split($ciphertext, $this->k); $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT); $plaintext = ''; switch ($this->encryptionMode) { case CRYPT_RSA_ENCRYPTION_NONE: $decrypt = '_raw_encrypt'; break; case CRYPT_RSA_ENCRYPTION_PKCS1: $decrypt = '_rsaes_pkcs1_v1_5_decrypt'; break; //case CRYPT_RSA_ENCRYPTION_OAEP: default: $decrypt = '_rsaes_oaep_decrypt'; } foreach ($ciphertext as $c) { $temp = $this->$decrypt($c); if ($temp === false) { return false; } $plaintext.= $temp; } return $plaintext; } /** * Create a signature * * @see self::verify() * @access public * @param string $message * @return string */ function sign($message) { if (empty($this->modulus) || empty($this->exponent)) { return false; } switch ($this->signatureMode) { case CRYPT_RSA_SIGNATURE_PKCS1: return $this->_rsassa_pkcs1_v1_5_sign($message); //case CRYPT_RSA_SIGNATURE_PSS: default: return $this->_rsassa_pss_sign($message); } } /** * Verifies a signature * * @see self::sign() * @access public * @param string $message * @param string $signature * @return bool */ function verify($message, $signature) { if (empty($this->modulus) || empty($this->exponent)) { return false; } switch ($this->signatureMode) { case CRYPT_RSA_SIGNATURE_PKCS1: return $this->_rsassa_pkcs1_v1_5_verify($message, $signature); //case CRYPT_RSA_SIGNATURE_PSS: default: return $this->_rsassa_pss_verify($message, $signature); } } /** * Extract raw BER from Base64 encoding * * @access private * @param string $str * @return string */ function _extractBER($str) { /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them * above and beyond the ceritificate. * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line: * * Bag Attributes * localKeyID: 01 00 00 00 * subject=/O=organization/OU=org unit/CN=common name * issuer=/O=organization/CN=common name */ $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1); // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff $temp = preg_replace('#-+[^-]+-+#', '', $temp); // remove new lines $temp = str_replace(array("\r", "\n", ' '), '', $temp); $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; return $temp != false ? $temp : $str; } }
{ "content_hash": "1ec592cb1699f725fbc460a53c5e33a4", "timestamp": "", "source": "github", "line_count": 3050, "max_line_length": 178, "avg_line_length": 34.91770491803279, "alnum_prop": 0.482417675283336, "repo_name": "vihoangson/Family", "id": "b292d0a51ea92605a627035559a9bee58c88da1f", "size": "108794", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "blog/wp-content/plugins/updraftplus/includes/phpseclib/Crypt/RSA.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2520447" }, { "name": "HTML", "bytes": "673052" }, { "name": "JavaScript", "bytes": "2762556" }, { "name": "PHP", "bytes": "17225078" }, { "name": "Perl", "bytes": "408" }, { "name": "Shell", "bytes": "2577" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: main.cpp Example File (mainwindows/recentfiles/main.cpp)</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">main.cpp Example File</h1> <span class="small-subtitle">mainwindows/recentfiles/main.cpp</span> <!-- $$$mainwindows/recentfiles/main.cpp-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> <span class="comment"></span> <span class="preprocessor">#include &lt;QApplication&gt;</span> <span class="preprocessor">#include &quot;mainwindow.h&quot;</span> <span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>) { <span class="type"><a href="qapplication.html">QApplication</a></span> app(argc<span class="operator">,</span> argv); app<span class="operator">.</span>setOrganizationName(<span class="string">&quot;Trolltech&quot;</span>); app<span class="operator">.</span>setApplicationName(<span class="string">&quot;Recent Files Example&quot;</span>); MainWindow <span class="operator">*</span>mainWin <span class="operator">=</span> <span class="keyword">new</span> MainWindow; <span class="preprocessor">#if defined(Q_OS_SYMBIAN)</span> mainWin<span class="operator">-</span><span class="operator">&gt;</span>showMaximized(); <span class="preprocessor">#else</span> mainWin<span class="operator">-</span><span class="operator">&gt;</span>show(); <span class="preprocessor">#endif</span> <span class="keyword">return</span> app<span class="operator">.</span>exec(); }</pre> </div> <!-- @@@mainwindows/recentfiles/main.cpp --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
{ "content_hash": "52cf6c7c02b1187bac3fbd0349c082e0", "timestamp": "", "source": "github", "line_count": 221, "max_line_length": 231, "avg_line_length": 47.782805429864254, "alnum_prop": 0.5712121212121212, "repo_name": "stephaneAG/PengPod700", "id": "ae634a892ea67d8a7852c645071f07ab6b98c896", "size": "12611", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "QtEsrc/backup_qt/qt-everywhere-opensource-src-4.8.5/doc/html/mainwindows-recentfiles-main-cpp.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "167426" }, { "name": "Batchfile", "bytes": "25368" }, { "name": "C", "bytes": "3755463" }, { "name": "C#", "bytes": "9282" }, { "name": "C++", "bytes": "177871700" }, { "name": "CSS", "bytes": "600936" }, { "name": "GAP", "bytes": "758872" }, { "name": "GLSL", "bytes": "32226" }, { "name": "Groff", "bytes": "106542" }, { "name": "HTML", "bytes": "273585110" }, { "name": "IDL", "bytes": "1194" }, { "name": "JavaScript", "bytes": "435912" }, { "name": "Makefile", "bytes": "289373" }, { "name": "Objective-C", "bytes": "1898658" }, { "name": "Objective-C++", "bytes": "3222428" }, { "name": "PHP", "bytes": "6074" }, { "name": "Perl", "bytes": "291672" }, { "name": "Prolog", "bytes": "102468" }, { "name": "Python", "bytes": "22546" }, { "name": "QML", "bytes": "3580408" }, { "name": "QMake", "bytes": "2191574" }, { "name": "Scilab", "bytes": "2390" }, { "name": "Shell", "bytes": "116533" }, { "name": "TypeScript", "bytes": "42452" }, { "name": "Visual Basic", "bytes": "8370" }, { "name": "XQuery", "bytes": "25094" }, { "name": "XSLT", "bytes": "252382" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v6.0.0: v8::CpuProfileDeoptInfo Struct Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v6.0.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="structv8_1_1CpuProfileDeoptInfo.html">CpuProfileDeoptInfo</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-attribs">Public Attributes</a> &#124; <a href="structv8_1_1CpuProfileDeoptInfo-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">v8::CpuProfileDeoptInfo Struct Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a> Public Attributes</h2></td></tr> <tr class="memitem:a908eb3ba33b47ace8973eeb2fda96ca9"><td class="memItemLeft" align="right" valign="top">const char *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structv8_1_1CpuProfileDeoptInfo.html#a908eb3ba33b47ace8973eeb2fda96ca9">deopt_reason</a></td></tr> <tr class="separator:a908eb3ba33b47ace8973eeb2fda96ca9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9446493c0e0a00e3ada02ba8df858d42"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9446493c0e0a00e3ada02ba8df858d42"></a> std::vector&lt; <a class="el" href="structv8_1_1CpuProfileDeoptFrame.html">CpuProfileDeoptFrame</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><b>stack</b></td></tr> <tr class="separator:a9446493c0e0a00e3ada02ba8df858d42"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Member Data Documentation</h2> <a class="anchor" id="a908eb3ba33b47ace8973eeb2fda96ca9"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const char* v8::CpuProfileDeoptInfo::deopt_reason</td> </tr> </table> </div><div class="memdoc"> <p>A pointer to a static string owned by <a class="el" href="namespacev8.html">v8</a>. </p> </div> </div> <hr/>The documentation for this struct was generated from the following file:<ul> <li>deps/v8/include/<a class="el" href="v8-profiler_8h_source.html">v8-profiler.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "6b9cb3d21f2aaaa1828374e49ec6c280", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 287, "avg_line_length": 45.878787878787875, "alnum_prop": 0.6644649933949802, "repo_name": "v8-dox/v8-dox.github.io", "id": "2dd0a5a291954e59778e134856e2101cdc57dcf2", "size": "6056", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "c1729b0/html/structv8_1_1CpuProfileDeoptInfo.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace LeapMIDI.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LeapMIDI.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
{ "content_hash": "d7048dcf3c3a1eae21bae6c9ce31820f", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 174, "avg_line_length": 44.111111111111114, "alnum_prop": 0.612450521770421, "repo_name": "LeifBloomquist/LeapMotion", "id": "9cee93802e665e5c26af0e152a6b90747238e49d", "size": "2781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "C#/LeapMIDI/Properties/Resources.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "47609" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>tesseract: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">tesseract &#160;<span id="projectnumber">4.0.0-beta.1-59-g2cc4</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('a04287.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">FEATURE_DESC_STRUCT Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="a04287.html">FEATURE_DESC_STRUCT</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="a04287.html#ae276ef0b2d76b9e37c74065737c64f83">NumParams</a></td><td class="entry"><a class="el" href="a04287.html">FEATURE_DESC_STRUCT</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="a04287.html#acc46f9f5b3cded3ca8e7de3e94407c58">ParamDesc</a></td><td class="entry"><a class="el" href="a04287.html">FEATURE_DESC_STRUCT</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="a04287.html#a11853141d8e7d72bdb9bc320001fa3d0">ShortName</a></td><td class="entry"><a class="el" href="a04287.html">FEATURE_DESC_STRUCT</a></td><td class="entry"></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Wed Mar 28 2018 20:00:43 for tesseract by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
{ "content_hash": "adbc3f6c8cc1dff1578b1898a7e863a4", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 229, "avg_line_length": 42.02884615384615, "alnum_prop": 0.676504232441089, "repo_name": "stweil/tesseract-ocr.github.io", "id": "cfbf20ac88a101880a6f3a41af580aafb70746b1", "size": "4371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "4.0.0/a04284.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1481625" }, { "name": "CSS", "bytes": "136547" }, { "name": "HTML", "bytes": "489171589" }, { "name": "JavaScript", "bytes": "9187479" } ], "symlink_target": "" }
namespace base { class CommandLine; } namespace content { class BrowserContext; } namespace extensions { class ChromeComponentExtensionResourceManager; class ChromeExtensionsAPIClient; class ChromeProcessManagerDelegate; class ScopedExtensionUpdaterKeepAlive; // Implementation of BrowserClient for Chrome, which includes // knowledge of Profiles, BrowserContexts and incognito. // // NOTE: Methods that do not require knowledge of browser concepts should be // implemented in ChromeExtensionsClient even if they are only used in the // browser process (see chrome/common/extensions/chrome_extensions_client.h). class ChromeExtensionsBrowserClient : public ExtensionsBrowserClient { public: ChromeExtensionsBrowserClient(); ChromeExtensionsBrowserClient(const ChromeExtensionsBrowserClient&) = delete; ChromeExtensionsBrowserClient& operator=( const ChromeExtensionsBrowserClient&) = delete; ~ChromeExtensionsBrowserClient() override; // ExtensionsBrowserClient overrides: bool IsShuttingDown() override; bool AreExtensionsDisabled(const base::CommandLine& command_line, content::BrowserContext* context) override; bool IsValidContext(content::BrowserContext* context) override; bool IsSameContext(content::BrowserContext* first, content::BrowserContext* second) override; bool HasOffTheRecordContext(content::BrowserContext* context) override; content::BrowserContext* GetOffTheRecordContext( content::BrowserContext* context) override; content::BrowserContext* GetOriginalContext( content::BrowserContext* context) override; #if BUILDFLAG(IS_CHROMEOS_ASH) std::string GetUserIdHashFromContext( content::BrowserContext* context) override; #endif bool IsGuestSession(content::BrowserContext* context) const override; bool IsExtensionIncognitoEnabled( const std::string& extension_id, content::BrowserContext* context) const override; bool CanExtensionCrossIncognito( const Extension* extension, content::BrowserContext* context) const override; base::FilePath GetBundleResourcePath( const network::ResourceRequest& request, const base::FilePath& extension_resources_path, int* resource_id) const override; void LoadResourceFromResourceBundle( const network::ResourceRequest& request, mojo::PendingReceiver<network::mojom::URLLoader> loader, const base::FilePath& resource_relative_path, int resource_id, scoped_refptr<net::HttpResponseHeaders> headers, mojo::PendingRemote<network::mojom::URLLoaderClient> client) override; bool AllowCrossRendererResourceLoad( const network::ResourceRequest& request, network::mojom::RequestDestination destination, ui::PageTransition page_transition, int child_id, bool is_incognito, const Extension* extension, const ExtensionSet& extensions, const ProcessMap& process_map) override; PrefService* GetPrefServiceForContext( content::BrowserContext* context) override; void GetEarlyExtensionPrefsObservers( content::BrowserContext* context, std::vector<EarlyExtensionPrefsObserver*>* observers) const override; ProcessManagerDelegate* GetProcessManagerDelegate() const override; std::unique_ptr<ExtensionHostDelegate> CreateExtensionHostDelegate() override; bool DidVersionUpdate(content::BrowserContext* context) override; void PermitExternalProtocolHandler() override; bool IsInDemoMode() override; bool IsScreensaverInDemoMode(const std::string& app_id) override; bool IsRunningInForcedAppMode() override; bool IsAppModeForcedForApp(const ExtensionId& extension_id) override; bool IsLoggedInAsPublicAccount() override; ExtensionSystemProvider* GetExtensionSystemFactory() override; void RegisterBrowserInterfaceBindersForFrame( mojo::BinderMapWithContext<content::RenderFrameHost*>* binder_map, content::RenderFrameHost* render_frame_host, const Extension* extension) const override; std::unique_ptr<RuntimeAPIDelegate> CreateRuntimeAPIDelegate( content::BrowserContext* context) const override; const ComponentExtensionResourceManager* GetComponentExtensionResourceManager() override; void BroadcastEventToRenderers( events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> args, bool dispatch_to_off_the_record_profiles) override; ExtensionCache* GetExtensionCache() override; bool IsBackgroundUpdateAllowed() override; bool IsMinBrowserVersionSupported(const std::string& min_version) override; ExtensionWebContentsObserver* GetExtensionWebContentsObserver( content::WebContents* web_contents) override; void ReportError(content::BrowserContext* context, std::unique_ptr<ExtensionError> error) override; void CleanUpWebView(content::BrowserContext* browser_context, int embedder_process_id, int view_instance_id) override; void ClearBackForwardCache() override; void AttachExtensionTaskManagerTag(content::WebContents* web_contents, mojom::ViewType view_type) override; scoped_refptr<update_client::UpdateClient> CreateUpdateClient( content::BrowserContext* context) override; std::unique_ptr<ScopedExtensionUpdaterKeepAlive> CreateUpdaterKeepAlive( content::BrowserContext* context) override; bool IsActivityLoggingEnabled(content::BrowserContext* context) override; void GetTabAndWindowIdForWebContents(content::WebContents* web_contents, int* tab_id, int* window_id) override; KioskDelegate* GetKioskDelegate() override; bool IsLockScreenContext(content::BrowserContext* context) override; std::string GetApplicationLocale() override; bool IsExtensionEnabled(const std::string& extension_id, content::BrowserContext* context) const override; bool IsWebUIAllowedToMakeNetworkRequests(const url::Origin& origin) override; network::mojom::NetworkContext* GetSystemNetworkContext() override; UserScriptListener* GetUserScriptListener() override; void SignalContentScriptsLoaded(content::BrowserContext* context) override; std::string GetUserAgent() const override; bool ShouldSchemeBypassNavigationChecks( const std::string& scheme) const override; base::FilePath GetSaveFilePath(content::BrowserContext* context) override; void SetLastSaveFilePath(content::BrowserContext* context, const base::FilePath& path) override; bool HasIsolatedStorage(const std::string& extension_id, content::BrowserContext* context) override; bool IsScreenshotRestricted( content::WebContents* web_contents) const override; bool IsValidTabId(content::BrowserContext* context, int tab_id) const override; bool IsExtensionTelemetryServiceEnabled( content::BrowserContext* context) const override; bool IsExtensionTelemetryRemoteHostContactedSignalEnabled() const override; void NotifyExtensionApiTabExecuteScript( content::BrowserContext* context, const ExtensionId& extension_id, const std::string& code) const override; void NotifyExtensionRemoteHostContacted(content::BrowserContext* context, const ExtensionId& extension_id, const GURL& url) const override; static void set_did_chrome_update_for_testing(bool did_update); private: friend struct base::LazyInstanceTraitsBase<ChromeExtensionsBrowserClient>; // Support for ProcessManager. std::unique_ptr<ChromeProcessManagerDelegate> process_manager_delegate_; // Client for API implementations. std::unique_ptr<ChromeExtensionsAPIClient> api_client_; std::unique_ptr<ChromeComponentExtensionResourceManager> resource_manager_; std::unique_ptr<ExtensionCache> extension_cache_; std::unique_ptr<KioskDelegate> kiosk_delegate_; UserScriptListener user_script_listener_; }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_CHROME_EXTENSIONS_BROWSER_CLIENT_H_
{ "content_hash": "53699c88ef434137d43bc787b79b9137", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 80, "avg_line_length": 46.55367231638418, "alnum_prop": 0.7529126213592233, "repo_name": "scheib/chromium", "id": "c009aae2288c02c4d10ef0ee61fe235e48c302e2", "size": "9134", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "chrome/browser/extensions/chrome_extensions_browser_client.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
FROM balenalib/orbitty-tx2-debian:bookworm-build # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.9.7 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.2.4 ENV SETUPTOOLS_VERSION 58.0.0 RUN set -x \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \ && echo "8dbeafe80bd47a8f31d5d23cd22af78e1d7c4a9716497e8d4c6fae3de44bc209 Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install --no-cache-dir virtualenv ENV PYTHON_DBUS_VERSION 1.2.18 # install dbus-python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ libdbus-1-dev \ libdbus-glib-1-dev \ && rm -rf /var/lib/apt/lists/* \ && apt-get -y autoremove # install dbus-python RUN set -x \ && mkdir -p /usr/src/dbus-python \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \ && gpg --verify dbus-python.tar.gz.asc \ && tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \ && rm dbus-python.tar.gz* \ && cd /usr/src/dbus-python \ && PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \ && make -j$(nproc) \ && make install -j$(nproc) \ && cd / \ && rm -rf /usr/src/dbus-python # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bookworm \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.7, Pip v21.2.4, Setuptools v58.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "e833d2f5ea72a43084ba7f3b7e23a5f3", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 712, "avg_line_length": 50.90526315789474, "alnum_prop": 0.7036807278742763, "repo_name": "resin-io-library/base-images", "id": "8ffdeda49a1036d6edb3d5c1c524fbf4a6d8b081", "size": "4857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/orbitty-tx2/debian/bookworm/3.9.7/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
package com.storage.shivam.directoryfinal; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
{ "content_hash": "9be611dc5de58b5711d99c59b5f7e72a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 93, "avg_line_length": 28, "alnum_prop": 0.7554945054945055, "repo_name": "shivarajp/AndroidDirectoryChooserExample", "id": "85e51264c83099dedee439f61c618c797f333260", "size": "364", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/androidTest/java/com/storage/shivam/directoryfinal/ApplicationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1593" }, { "name": "Java", "bytes": "34922" } ], "symlink_target": "" }
package io.cattle.platform.configitem.server.model.util; import io.cattle.platform.configitem.context.ConfigItemContextFactory; import io.cattle.platform.configitem.server.model.impl.GenericConfigItemFactory; import io.cattle.platform.configitem.server.resource.AbstractCachingResourceRoot; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConfigItemResourceUtil { private static final Logger log = LoggerFactory.getLogger(ConfigItemResourceUtil.class); public static List<ConfigItemContextFactory> getFactories(List<ConfigItemContextFactory> factories, String item) { List<ConfigItemContextFactory> result = new ArrayList<ConfigItemContextFactory>(); for ( ConfigItemContextFactory factory : factories ) { for ( String check : factory.getItems() ) { if ( item.equals(check) ) { result.add(factory); } } } return result; } public static Map<String,Map<String,URL>> processUrlRoot(boolean ignoreNotFound, String root, URL[] resources) throws IOException { List<URL> baseUrls = Collections.list(GenericConfigItemFactory.class.getClassLoader().getResources(root)); if ( baseUrls.size() == 0 ) { if ( ignoreNotFound ) { return new HashMap<String, Map<String,URL>>(); } else { throw new IllegalStateException("Failed to find [" + root + "]"); } } Map<String,Map<String,URL>> config = new TreeMap<String, Map<String,URL>>(); outer: for ( URL resource : resources ) { String name = null; String path = null; for ( URL baseUrl : baseUrls ) { String base = baseUrl.toExternalForm(); String fullUrl = resource.toExternalForm(); if ( ! fullUrl.startsWith(base) ) { continue; } String part = trimLeading(fullUrl.substring(base.length())); int idx = StringUtils.indexOfAny(part, "/", "\\"); if ( idx != -1 ) { name = part.substring(0, idx); path = part.substring(idx); break; } } if ( name == null ) { log.error("Ignoring resource [{}] can not find it realtive to root [{}]", resource, root); continue; } path = trimLeading(path); if ( StringUtils.isBlank(path) || path.endsWith("/") || path.endsWith("\\") ) { continue; } for ( String part : path.split("[/\\\\]") ) { if ( AbstractCachingResourceRoot.shouldIgnore(part) ) { continue outer; } } Map<String,URL> urlMapping = config.get(name); if ( urlMapping == null ) { urlMapping = new TreeMap<String, URL>(); config.put(name, urlMapping); } urlMapping.put(path, resource); } return config; } protected static String trimLeading(String text) { if ( text.startsWith("/") || text.startsWith("\\") ) { return text.substring(1); } else { return text; } } }
{ "content_hash": "5a8ecae6c3f19f640a1b8fabccaf8a21", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 135, "avg_line_length": 35.5188679245283, "alnum_prop": 0.5442231075697211, "repo_name": "alena1108/cattle", "id": "d3d6333352a1f295ce68bed315f72956882b5c9e", "size": "3765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/iaas/config-item/server/src/main/java/io/cattle/platform/configitem/server/model/util/ConfigItemResourceUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3287143" }, { "name": "Makefile", "bytes": "6771" }, { "name": "Python", "bytes": "193716" }, { "name": "Shell", "bytes": "54068" } ], "symlink_target": "" }
[![GoDoc](https://godoc.org/github.com/urfave/negroni?status.svg)](http://godoc.org/github.com/urfave/negroni) [![Build Status](https://travis-ci.org/urfave/negroni.svg?branch=master)](https://travis-ci.org/urfave/negroni) [![codebeat](https://codebeat.co/badges/47d320b1-209e-45e8-bd99-9094bc5111e2)](https://codebeat.co/projects/github-com-urfave-negroni) [![codecov](https://codecov.io/gh/urfave/negroni/branch/master/graph/badge.svg)](https://codecov.io/gh/urfave/negroni) **Note:** Ce projet était initiallement connu comme `github.com/codegangsta/negroni` -- Github redirigera automatiquement les requêtes vers ce dépôt. Nous vous recommandons néanmoins d'utiliser la référence vers ce nouveau dépôt pour plus de clarté. Negroni approche la question de la création de *middleware* de manière pragmatique. La librairie se veut légère, non intrusive et encourage l'utilisation des *Handlers* de la librairie standard `net/http`. Si vous appréciez le projet [Martini](https://github.com/go-martini/martini) et estimez qu'une certaine magie s'en dégage, Negroni sera sans doute plus approprié. ## Démarrer avec Negroni Une fois Go installé et votre variable [GOPATH](http://golang.org/doc/code.html#GOPATH) à jour, créez votre premier fichier `.go` et nommez le `server.go`. <!-- { "interrupt": true } --> ``` go package main import ( "fmt" "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) n := negroni.Classic() // Inclue les "middlewares" par défaut. n.UseHandler(mux) http.ListenAndServe(":3000", n) } ``` Installez au préalable le paquet Negroni (**NOTE**: Une version de Go &gt;= **go 1.1** est nécessaire): ``` go get github.com/urfave/negroni ``` Démarrez le serveur: ``` go run server.go ``` Vous avez dès à présent un serveur web Go basé sur `net/http` disponible à l'adresse `localhost:3000`. ### Paquets Si vous utilisez Debian, `negroni` est aussi disponible en tant que [paquet] (https://packages.debian.org/sid/golang-github-urfave-negroni-dev). La commande `apt install golang-github-urfave-negroni-dev` vous permettra de l'installer (À ce jour, vous les trouverez dans les dépôts `sid`). ## Negroni est-il un *framework* ? Negroni **n'est pas** un *framework*. Considérez le comme une librairie centrée sur l'utilisation de *middleware* développés pour fonctionner directement avec la librairie `net/http`. ## Redirection (*Routing*) ? Negroni est *BYOR* (*Bring your own Router*, Apporter votre propre routeur). La communauté Go offre un nombre importants de routeur et Negroni met tout en oeuvre pour fonctionner avec chacun d'entre eux en assurant un support complet de la librairie `net/http`. Par exemple, une utilisation avec [Gorilla Mux] se présente sous la forme: ``` go router := mux.NewRouter() router.HandleFunc("/", HomeHandler) n := negroni.New(Middleware1, Middleware2) // on peut utiliser également la fonction Use() pour ajouter un "middleware" n.Use(Middleware3) // le routeur se trouve toujours en dernier. n.UseHandler(router) http.ListenAndServe(":3001", n) ``` ## `negroni.Classic()` L'instance `negroni.Classic()` propose par défaut trois middlewares qui seront utiles à la plupart des applications: * [`negroni.Recovery`](#recovery) - Récupère des appels à `panic`. * [`negroni.Logger`](#logger) - Journalise les requêtes et les réponses. * [`negroni.Static`](#static) - Sers les fichiers statiques présent dans le dossier "public". Elle offre un démarrage aisé sans recourir à la configuration pour utiliser quelques une des fonctions les plus utiles de Negroni. ## *Handlers* Negroni offre un flux bidirectionnel via les *middlewares* (aller-retour entre la requête et la réponse). Tout repose sur l'interface `negroni.Handler` : ``` go type Handler interface { ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) } ``` Si un *middleware* n'a pas écrit au `ResponseWriter`, il doit faire appel au prochain `http.Handlerfunc` de la chaîne pour que le prochain *middleware* soit appelé: ``` go func MyMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { // faire quelque chose avant next(rw, r) // faire quelque chose après } ``` Vous pouvez insérer votre *middleware* dans la chaîne en utilisant la fonction `Use`: ``` go n := negroni.New() n.Use(negroni.HandlerFunc(MyMiddleware)) ``` Vous pour également utiliser un `http.Handler` classique: ``` go n := negroni.New() mux := http.NewServeMux() // définissez vos routes n.UseHandler(mux) http.ListenAndServe(":3000", n) ``` ## `With()` La méthode `With()` vous permet de regrouper un ou plusieurs `Handler` au sein d'une nouvelle instance `Negroni`. Cette dernière est la combinaison des `Handlers` de l'ancienne et de la nouvelle instance. ```go // "middleware" à réutiliser. common := negroni.New() common.Use(MyMiddleware1) common.Use(MyMiddleware2) // `specific` devient une nouvelle instance avec les "handlers" provenant de `common` ainsi // que ceux passés en paramètres. specific := common.With( SpecificMiddleware1, SpecificMiddleware2 ) ``` ## `Run()` Negroni peut-être démarrer en utilisant la méthode `Run()`. Cette dernière prend en paramètre l'adresse du serveur, à l'instar de la méthode [`http.ListenAndServe`](https://godoc.org/net/http#ListenAndServe). <!-- { "interrupt": true } --> ``` go package main import ( "github.com/urfave/negroni" ) func main() { n := negroni.Classic() n.Run(":8080") } ``` Si aucune adresse n'est renseignée, la variable d'environnement `PORT` est utilisée. Si cette dernière n'est pas définie, l'adresse par défaut est utilisée. Pour une description détaillée, veuillez-vous référer à la documentation de la méthode [Run]((https://godoc.org/github.com/urfave/negroni#Negroni.Run). De manière générale, vous voudrez vous servir de la librairie `net/http` et utiliser `negroni` comme un simple `Handler` pour plus de flexibilité. Par exemple: <!-- { "interrupt": true } --> ``` go package main import ( "fmt" "log" "net/http" "time" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) n := negroni.Classic() // Inclue les "middlewares" par défaut n.UseHandler(mux) s := &http.Server{ Addr: ":8080", Handler: n, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) } ``` ## Redirection spécifique Si un ensemble de routes nécessite l'appel à des *middleware* spécifiques, vous pouvez simplement créer une nouvelle instance Negroni et l'utiliser comme `Handler` pour cet ensemble. ``` go router := mux.NewRouter() adminRoutes := mux.NewRouter() // ajout des routes relatives à l'administration // Création d'une nouvelle instance pour le "middleware" admin. router.PathPrefix("/admin").Handler(negroni.New( Middleware1, Middleware2, negroni.Wrap(adminRoutes), )) ``` Si vous utilisez [Gorilla Mux], vous pourriez utiliser un *subrouter*: ``` go router := mux.NewRouter() subRouter := mux.NewRouter().PathPrefix("/subpath").Subrouter().StrictSlash(true) subRouter.HandleFunc("/", someSubpathHandler) // "/subpath/" subRouter.HandleFunc("/:id", someSubpathHandler) // "/subpath/:id" // "/subpath" est nécessaire pour assurer la cohésion entre le `subrouter` et le routeur principal router.PathPrefix("/subpath").Handler(negroni.New( Middleware1, Middleware2, negroni.Wrap(subRouter), )) ``` La méthode `With()` peut aider à réduire la duplication des *middlewares* partagés par plusieurs routes. ``` go router := mux.NewRouter() apiRoutes := mux.NewRouter() // ajout des routes api ici webRoutes := mux.NewRouter() // ajout des routes web ici // création un "middleware" commun pour faciliter le partage common := negroni.New( Middleware1, Middleware2, ) // création d'une nouvelle instance pour le "middleware" // api en utilisant le "middleware" commun comme base. router.PathPrefix("/api").Handler(common.With( APIMiddleware1, negroni.Wrap(apiRoutes), )) // création d'une nouvelle instance pour le "middleware" // web en utilisant le "middleware" commun comme base. router.PathPrefix("/web").Handler(common.With( WebMiddleware1, negroni.Wrap(webRoutes), )) ``` ## *Middlewares* fournis ### Static Ce *middleware* va servir les fichiers présents sur le système de fichiers. Si un fichier n'existe pas, il transmet la requête au *middleware* suivant. Si vous souhaitez retourner le message `404 File Not Found` pour les fichiers non existants, vous pouvez utiliser la fonction [http.FileServer](https://golang.org/pkg/net/http/#FileServer) comme `Handler`. Exemple: <!-- { "interrupt": true } --> ``` go package main import ( "fmt" "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) // Exemple d'usage de la fonction http.FileServer pour avoir un comportement similaire à un // serveur HTTP "standard" plutôt que le comportement "middleware" // mux.Handle("/public", http.FileServer(http.Dir("/home/public"))) n := negroni.New() n.Use(negroni.NewStatic(http.Dir("/tmp"))) n.UseHandler(mux) http.ListenAndServe(":3002", n) } ``` Ce programme servira les fichiers depuis le dossier `/tmp` en premier lieu. Si le fichier n'est pas trouvé, il transmet la requête au *middleware* suivant. ### Recupération (*Recovery*) Ce *middleware* capture les appels à `panic` et renvoie une réponse `500` à la requête correspondante. Si un autre *middleware* a déjà renvoyé une réponse (vide ou non), le renvoie de la réponse `500` au client échouera, le client en ayant déjà obtenu une. Il est possible d'adjoindre au *middleware* une fonction de type `PanicHandlerFunc` pour collecter les erreurs `500` et les transmettre à un service de rapport d'erreur tels Sentry ou Airbrake. Exemple: <!-- { "interrupt": true } --> ``` go package main import ( "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("oh no") }) n := negroni.New() n.Use(negroni.NewRecovery()) n.UseHandler(mux) http.ListenAndServe(":3003", n) } ``` Ce programme renverra une erreur `500 Internal Server Error` à chaque requête reçue. Il transmettra à son *logger* associé la trace de la pile d'exécution et affichera cette même trace sur la sortie standard si la valeur `PrintStack` est mise à `true`. (valeur par défaut) Exemple avec l'utilisation d'une `PanicHandlerFunc`: ``` go package main import ( "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("oh no") }) n := negroni.New() recovery := negroni.NewRecovery() recovery.PanicHandlerFunc = reportToSentry n.Use(recovery) n.UseHandler(mux) http.ListenAndServe(":3003", n) } func reportToSentry(info *negroni.PanicInformation) { // code envoyant le rapport d'erreur à Sentry } ``` ## Journalisation (*Logger*) Ce *middleware* va *logger* toutes les requêtes et réponses. Exemple: <!-- { "interrupt": true } --> ``` go package main import ( "fmt" "net/http" "github.com/urfave/negroni" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) n := negroni.New() n.Use(negroni.NewLogger()) n.UseHandler(mux) http.ListenAndServe(":3004", n) } ``` Ce programme affichera un *log* similaire à celui-ci pour chaque requête/réponse: ``` [negroni] 2017-10-04T14:56:25+02:00 | 200 | 378µs | localhost:3004 | GET / ``` Il est possible de modifier le format par défaut en utilisant la fonction `SetFormat`. Le format est `template` dont les champs associés sont les propriétés de l'objet `LoggerEntry`. Par exemple: ```go l.SetFormat("[{{.Status}} {{.Duration}}] - {{.Request.UserAgent}}") ``` Ce format proposera un affichage similaire à: `[200 18.263µs] - Go-User-Agent/1.1 ` ## *Middlewares* tiers Vous trouverez ici une liste de *middlewares* compatibles avec Negroni. N'hésitez pas à créer une PR pour renseigner un middleware de votre cru: | Middleware | Author | Description | | -----------|--------|-------------| | [authz](https://github.com/casbin/negroni-authz) | [Yang Luo](https://github.com/hsluoyz) | Un *middleware* de gestion d'accès ACL, RBAC, ABAC basé sur [Casbin](https://github.com/casbin/casbin) | | [binding](https://github.com/mholt/binding) | [Matt Holt](https://github.com/mholt) | Associez facilement les données des requêtes HTTP vers des structures Go | | [cloudwatch](https://github.com/cvillecsteele/negroni-cloudwatch) | [Colin Steele](https://github.com/cvillecsteele) | *Middleware* pour utiliser les métriques AWS cloudwatch | | [cors](https://github.com/rs/cors) | [Olivier Poitrey](https://github.com/rs) | Support [Cross Origin Resource Sharing](http://www.w3.org/TR/cors/) (CORS) | | [csp](https://github.com/awakenetworks/csp) | [Awake Networks](https://github.com/awakenetworks) | Support [Content Security Policy](https://www.w3.org/TR/CSP2/) (CSP) | | [delay](https://github.com/jeffbmartinez/delay) | [Jeff Martinez](https://github.com/jeffbmartinez) | Ajouter des délais de réponse sur les routes. Utile pour tester les effets de la latence. | | [New Relic Go Agent](https://github.com/yadvendar/negroni-newrelic-go-agent) | [Yadvendar Champawat](https://github.com/yadvendar) | [Agent New Relic Go](https://github.com/newrelic/go-agent) officiel | | [gorelic](https://github.com/jingweno/negroni-gorelic) | [Jingwen Owen Ou](https://github.com/jingweno) | Agent New Relic agent pour le runtime Go | | [Graceful](https://github.com/tylerb/graceful) | [Tyler Bunnell](https://github.com/tylerb) | Graceful HTTP Shutdown | | [gzip](https://github.com/phyber/negroni-gzip) | [phyber](https://github.com/phyber) | Compression GZIP des réponses | | [JWT Middleware](https://github.com/auth0/go-jwt-middleware) | [Auth0](https://github.com/auth0) | Middleware vérifiant la présence d'un JWT dans le *header* `Authorization` et le décode | | [logrus](https://github.com/meatballhat/negroni-logrus) | [Dan Buch](https://github.com/meatballhat) | *Logger* basé sur Logrus | | [oauth2](https://github.com/goincremental/negroni-oauth2) | [David Bochenski](https://github.com/bochenski) | Middleware oAuth2 | | [onthefly](https://github.com/xyproto/onthefly) | [Alexander Rødseth](https://github.com/xyproto) | Générer des éléments TinySVG, HTML et CSS à la volée | | [permissions2](https://github.com/xyproto/permissions2) | [Alexander Rødseth](https://github.com/xyproto) | Cookies, utilisateurs et permissions | | [prometheus](https://github.com/zbindenren/negroni-prometheus) | [Rene Zbinden](https://github.com/zbindenren) | Créer des métriques facilement avec l'outil [prometheus](http://prometheus.io) | | [render](https://github.com/unrolled/render) | [Cory Jacobsen](https://github.com/unrolled) | Rendre des templates JSON, XML et HTML | | [RestGate](https://github.com/pjebs/restgate) | [Prasanga Siripala](https://github.com/pjebs) | Authentification sécurisée pour les APIs REST | | [secure](https://github.com/unrolled/secure) | [Cory Jacobsen](https://github.com/unrolled) | Middleware implémentant des basiques de sécurité | | [sessions](https://github.com/goincremental/negroni-sessions) | [David Bochenski](https://github.com/bochenski) | Gestions des sessions | | [stats](https://github.com/thoas/stats) | [Florent Messa](https://github.com/thoas) | Stockez des informations à propos de votre application web (temps de réponse, etc.) | | [VanGoH](https://github.com/auroratechnologies/vangoh) | [Taylor Wrobel](https://github.com/twrobel3) | *Middleware* d'authentification HMAC configurable basée sur [AWS-Style](http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html) | | [xrequestid](https://github.com/pilu/xrequestid) | [Andrea Franz](https://github.com/pilu) | Un *middleware* qui assigne un *header* `X-Request-Id` à chaque requête | | [mgo session](https://github.com/joeljames/nigroni-mgo-session) | [Joel James](https://github.com/joeljames) | Un *middleware* qui gère les sessions mgo pour chaque requête (ouverture, fermeture) | | [digits](https://github.com/bamarni/digits) | [Bilal Amarni](https://github.com/bamarni) | Un *middleware* qui gère l'authentification via [Twitter Digits](https://get.digits.com/) | | [stats](https://github.com/guptachirag/stats) | [Chirag Gupta](https://github.com/guptachirag/stats) | Middleware qui gère les statistiques qps et latence pour vos points de terminaison et les envoie de manière asynchrone à influx db | ## Exemples [Alexander Rødseth](https://github.com/xyproto) a créé [mooseware](https://github.com/xyproto/mooseware), un squelette pour écrire un *middleware* Negroni. [Prasanga Siripala](https://github.com/pjebs) a créé un squelette pour les applications web basées sur Go et Negroni: [Go-Skeleton](https://github.com/pjebs/go-skeleton) ## Rechargement automatique du code ? [gin](https://github.com/codegangsta/gin) et [fresh](https://github.com/pilu/fresh) permettent tous deux de recharger les applications Negroni suite à une modification opérée dans le code. ## Lectures pour les débutants avec Go et Negroni * [Using a Context to pass information from middleware to end handler](http://elithrar.github.io/article/map-string-interface/) * [Understanding middleware](https://mattstauffer.co/blog/laravel-5.0-middleware-filter-style) ## À propos Negroni est obsessivement développé par nulle autre personne que [Code Gangsta](https://codegangsta.io/) [Gorilla Mux]: https://github.com/gorilla/mux [`http.FileSystem`]: https://godoc.org/net/http#FileSystem
{ "content_hash": "741ba98e550269edbfcc13620a3ba99d", "timestamp": "", "source": "github", "line_count": 509, "max_line_length": 251, "avg_line_length": 35.66011787819254, "alnum_prop": 0.7264613519916258, "repo_name": "cloudfoundry-community/stackdriver-tools", "id": "5929e221bcb1f791ca53e507a1e13651daae27b5", "size": "18366", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/cf-stackdriver-example/vendor/github.com/codegangsta/negroni/translations/README_fr_FR.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1165" }, { "name": "Go", "bytes": "241405" }, { "name": "HCL", "bytes": "488" }, { "name": "HTML", "bytes": "13123" }, { "name": "Makefile", "bytes": "4359" }, { "name": "Ruby", "bytes": "7380" }, { "name": "Shell", "bytes": "35782" }, { "name": "Smarty", "bytes": "1523" } ], "symlink_target": "" }
"""Package providing an alternative to the standard |Queue| class, such that messages are not written to storage but instead immediately relayed. An |Edge| service will have to wait for a message to finish relaying before its reply can be issued. """ from __future__ import absolute_import import uuid from slimta.relay import RelayError class ProxyQueue(object): """Class implementing the same interface as |Queue|, but proxies a message to a |Relay| service instead of storing and trying/retrying delivery. :param relay: |Relay| object used to attempt message deliveries. """ def __init__(self, relay): self.relay = relay def add_policy(self, *args): msg = 'ProxyQueue objects do not support add_policy()' raise NotImplementedError(msg) def start(self): # No-op, because this class does not inherit from Greenlet. Provided # for backwards compatibility with the standard Queue class. pass def kill(self): # No-op, because this class does not inherit from Greenlet. Provided # for backwards compatibility with the standard Queue class. pass def flush(self): # No-op, because this class does not maintain an actual queue. Provided # for backwards compatibility with the standard Queue class. pass def enqueue(self, envelope): try: self.relay._attempt(envelope, 0) except RelayError as e: return [(envelope, e)] else: return [(envelope, uuid.uuid4().hex)] # vim:et:fdm=marker:sts=4:sw=4:ts=4
{ "content_hash": "6e63dfab575c85dd493f292b0e9c8542", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 79, "avg_line_length": 29.685185185185187, "alnum_prop": 0.6681222707423581, "repo_name": "slimta/python-slimta", "id": "f0428c941ebb68e854ddeba596fd22983aefaeb9", "size": "2696", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "slimta/queue/proxy.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "606434" } ], "symlink_target": "" }
\begin{figure}[H] \centering \includegraphics[width=6in]{figs/run_1/run_1_turb_visc_ettap_vs_r_meshscatter} \caption{Scatter plot of $\nu_T$ pressure relaxation term vs radius at $z/c$=5.37, $V_{free}$=15.22, station 1.} \label{fig:run_1_turb_visc_ettap_vs_r_meshscatter} \end{figure}
{ "content_hash": "672f7919f48b44393ab9d3fd9ee8a93a", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 112, "avg_line_length": 35.875, "alnum_prop": 0.7247386759581882, "repo_name": "Jwely/pivpr", "id": "2f6f6a68475202304c8add1758cc8cf28b9c9884", "size": "287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "texdocs/figs/run_1/run_1_turb_visc_ettap_vs_r_meshscatter.tex", "mode": "33188", "license": "mit", "language": [ { "name": "MATLAB", "bytes": "137127" }, { "name": "Python", "bytes": "183435" }, { "name": "TeX", "bytes": "1267545" } ], "symlink_target": "" }
<?php /** * @namespace */ namespace Zend\View\Exception; use Zend\View\Exception; /** * Runtime exception * * @uses \RuntimeException * @category Zend * @package Zend_View * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class RuntimeException extends \RuntimeException implements Exception { }
{ "content_hash": "568aaaac442efe08233859f318c0e728", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 87, "avg_line_length": 19.863636363636363, "alnum_prop": 0.6864988558352403, "repo_name": "magicobject/zf2", "id": "e182281f001dc78e12b1597a4d5e1231a97d2f80", "size": "1107", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "library/Zend/View/Exception/RuntimeException.php", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.apache.hadoop.hbase.io.util; import java.lang.management.ManagementFactory; import java.lang.management.MemoryType; import java.lang.management.MemoryUsage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.yetus.audience.InterfaceAudience; import org.apache.hadoop.hbase.regionserver.MemStoreLAB; import org.apache.hadoop.hbase.util.Pair; /** * Util class to calculate memory size for memstore, block cache(L1, L2) of RS. */ @InterfaceAudience.Private public class MemorySizeUtil { public static final String MEMSTORE_SIZE_KEY = "hbase.regionserver.global.memstore.size"; public static final String MEMSTORE_SIZE_OLD_KEY = "hbase.regionserver.global.memstore.upperLimit"; public static final String MEMSTORE_SIZE_LOWER_LIMIT_KEY = "hbase.regionserver.global.memstore.size.lower.limit"; public static final String MEMSTORE_SIZE_LOWER_LIMIT_OLD_KEY = "hbase.regionserver.global.memstore.lowerLimit"; // Max global off heap memory that can be used for all memstores // This should be an absolute value in MBs and not percent. public static final String OFFHEAP_MEMSTORE_SIZE_KEY = "hbase.regionserver.offheap.global.memstore.size"; public static final float DEFAULT_MEMSTORE_SIZE = 0.4f; // Default lower water mark limit is 95% size of memstore size. public static final float DEFAULT_MEMSTORE_SIZE_LOWER_LIMIT = 0.95f; private static final Log LOG = LogFactory.getLog(MemorySizeUtil.class); // a constant to convert a fraction to a percentage private static final int CONVERT_TO_PERCENTAGE = 100; private static final String JVM_HEAP_EXCEPTION = "Got an exception while attempting to read " + "information about the JVM heap. Please submit this log information in a bug report and " + "include your JVM settings, specifically the GC in use and any -XX options. Consider " + "restarting the service."; /** * Return JVM memory statistics while properly handling runtime exceptions from the JVM. * @return a memory usage object, null if there was a runtime exception. (n.b. you * could also get -1 values back from the JVM) * @see MemoryUsage */ public static MemoryUsage safeGetHeapMemoryUsage() { MemoryUsage usage = null; try { usage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); } catch (RuntimeException exception) { LOG.warn(JVM_HEAP_EXCEPTION, exception); } return usage; } /** * Checks whether we have enough heap memory left out after portion for Memstore and Block cache. * We need atleast 20% of heap left out for other RS functions. * @param conf */ public static void checkForClusterFreeHeapMemoryLimit(Configuration conf) { if (conf.get(MEMSTORE_SIZE_OLD_KEY) != null) { LOG.warn(MEMSTORE_SIZE_OLD_KEY + " is deprecated by " + MEMSTORE_SIZE_KEY); } float globalMemstoreSize = getGlobalMemStoreHeapPercent(conf, false); int gml = (int)(globalMemstoreSize * CONVERT_TO_PERCENTAGE); float blockCacheUpperLimit = getBlockCacheHeapPercent(conf); int bcul = (int)(blockCacheUpperLimit * CONVERT_TO_PERCENTAGE); if (CONVERT_TO_PERCENTAGE - (gml + bcul) < (int)(CONVERT_TO_PERCENTAGE * HConstants.HBASE_CLUSTER_MINIMUM_MEMORY_THRESHOLD)) { throw new RuntimeException("Current heap configuration for MemStore and BlockCache exceeds " + "the threshold required for successful cluster operation. " + "The combined value cannot exceed 0.8. Please check " + "the settings for hbase.regionserver.global.memstore.size and " + "hfile.block.cache.size in your configuration. " + "hbase.regionserver.global.memstore.size is " + globalMemstoreSize + " hfile.block.cache.size is " + blockCacheUpperLimit); } } /** * Retrieve global memstore configured size as percentage of total heap. * @param c * @param logInvalid */ public static float getGlobalMemStoreHeapPercent(final Configuration c, final boolean logInvalid) { float limit = c.getFloat(MEMSTORE_SIZE_KEY, c.getFloat(MEMSTORE_SIZE_OLD_KEY, DEFAULT_MEMSTORE_SIZE)); if (limit > 0.8f || limit <= 0.0f) { if (logInvalid) { LOG.warn("Setting global memstore limit to default of " + DEFAULT_MEMSTORE_SIZE + " because supplied value outside allowed range of (0 -> 0.8]"); } limit = DEFAULT_MEMSTORE_SIZE; } return limit; } /** * Retrieve configured size for global memstore lower water mark as fraction of global memstore * size. */ public static float getGlobalMemStoreHeapLowerMark(final Configuration conf, boolean honorOldConfig) { String lowMarkPercentStr = conf.get(MEMSTORE_SIZE_LOWER_LIMIT_KEY); if (lowMarkPercentStr != null) { float lowMarkPercent = Float.parseFloat(lowMarkPercentStr); if (lowMarkPercent > 1.0f) { LOG.error("Bad configuration value for " + MEMSTORE_SIZE_LOWER_LIMIT_KEY + ": " + lowMarkPercent + ". Using 1.0f instead."); lowMarkPercent = 1.0f; } return lowMarkPercent; } if (!honorOldConfig) return DEFAULT_MEMSTORE_SIZE_LOWER_LIMIT; String lowerWaterMarkOldValStr = conf.get(MEMSTORE_SIZE_LOWER_LIMIT_OLD_KEY); if (lowerWaterMarkOldValStr != null) { LOG.warn(MEMSTORE_SIZE_LOWER_LIMIT_OLD_KEY + " is deprecated. Instead use " + MEMSTORE_SIZE_LOWER_LIMIT_KEY); float lowerWaterMarkOldVal = Float.parseFloat(lowerWaterMarkOldValStr); float upperMarkPercent = getGlobalMemStoreHeapPercent(conf, false); if (lowerWaterMarkOldVal > upperMarkPercent) { lowerWaterMarkOldVal = upperMarkPercent; LOG.error("Value of " + MEMSTORE_SIZE_LOWER_LIMIT_OLD_KEY + " (" + lowerWaterMarkOldVal + ") is greater than global memstore limit (" + upperMarkPercent + ") set by " + MEMSTORE_SIZE_KEY + "/" + MEMSTORE_SIZE_OLD_KEY + ". Setting memstore lower limit " + "to " + upperMarkPercent); } return lowerWaterMarkOldVal / upperMarkPercent; } return DEFAULT_MEMSTORE_SIZE_LOWER_LIMIT; } /** * @return Pair of global memstore size and memory type(ie. on heap or off heap). */ public static Pair<Long, MemoryType> getGlobalMemStoreSize(Configuration conf) { long offheapMSGlobal = conf.getLong(OFFHEAP_MEMSTORE_SIZE_KEY, 0);// Size in MBs if (offheapMSGlobal > 0) { // Off heap memstore size has not relevance when MSLAB is turned OFF. We will go with making // this entire size split into Chunks and pooling them in MemstoreLABPoool. We dont want to // create so many on demand off heap chunks. In fact when this off heap size is configured, we // will go with 100% of this size as the pool size if (MemStoreLAB.isEnabled(conf)) { // We are in offheap Memstore use long globalMemStoreLimit = (long) (offheapMSGlobal * 1024 * 1024); // Size in bytes return new Pair<>(globalMemStoreLimit, MemoryType.NON_HEAP); } else { // Off heap max memstore size is configured with turning off MSLAB. It makes no sense. Do a // warn log and go with on heap memstore percentage. By default it will be 40% of Xmx LOG.warn("There is no relevance of configuring '" + OFFHEAP_MEMSTORE_SIZE_KEY + "' when '" + MemStoreLAB.USEMSLAB_KEY + "' is turned off." + " Going with on heap global memstore size ('" + MEMSTORE_SIZE_KEY + "')"); } } return new Pair<>(getOnheapGlobalMemStoreSize(conf), MemoryType.HEAP); } /** * Returns the onheap global memstore limit based on the config * 'hbase.regionserver.global.memstore.size'. * @param conf * @return the onheap global memstore limt */ public static long getOnheapGlobalMemStoreSize(Configuration conf) { long max = -1L; final MemoryUsage usage = safeGetHeapMemoryUsage(); if (usage != null) { max = usage.getMax(); } float globalMemStorePercent = getGlobalMemStoreHeapPercent(conf, true); return ((long) (max * globalMemStorePercent)); } /** * Retrieve configured size for on heap block cache as percentage of total heap. * @param conf */ public static float getBlockCacheHeapPercent(final Configuration conf) { // L1 block cache is always on heap float l1CachePercent = conf.getFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, HConstants.HFILE_BLOCK_CACHE_SIZE_DEFAULT); float l2CachePercent = getL2BlockCacheHeapPercent(conf); return l1CachePercent + l2CachePercent; } /** * @param conf * @return The on heap size for L2 block cache. */ public static float getL2BlockCacheHeapPercent(Configuration conf) { float l2CachePercent = 0.0F; String bucketCacheIOEngineName = conf.get(HConstants.BUCKET_CACHE_IOENGINE_KEY, null); // L2 block cache can be on heap when IOEngine is "heap" if (bucketCacheIOEngineName != null && bucketCacheIOEngineName.startsWith("heap")) { float bucketCachePercentage = conf.getFloat(HConstants.BUCKET_CACHE_SIZE_KEY, 0F); long max = -1L; final MemoryUsage usage = safeGetHeapMemoryUsage(); if (usage != null) { max = usage.getMax(); } l2CachePercent = bucketCachePercentage < 1 ? bucketCachePercentage : (bucketCachePercentage * 1024 * 1024) / max; } return l2CachePercent; } /** * @param conf used to read cache configs * @return the number of bytes to use for LRU, negative if disabled. * @throws IllegalArgumentException if HFILE_BLOCK_CACHE_SIZE_KEY is > 1.0 */ public static long getLruCacheSize(final Configuration conf) { float cachePercentage = conf.getFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, HConstants.HFILE_BLOCK_CACHE_SIZE_DEFAULT); if (cachePercentage <= 0.0001f) { return -1; } if (cachePercentage > 1.0) { throw new IllegalArgumentException(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY + " must be between 0.0 and 1.0, and not > 1.0"); } long max = -1L; final MemoryUsage usage = safeGetHeapMemoryUsage(); if (usage != null) { max = usage.getMax(); } // Calculate the amount of heap to give the heap. return (long) (max * cachePercentage); } /** * @param conf used to read config for bucket cache size. (< 1 is treated as % and > is treated as MiB) * @return the number of bytes to use for bucket cache, negative if disabled. */ public static long getBucketCacheSize(final Configuration conf) { final float bucketCachePercentage = conf.getFloat(HConstants.BUCKET_CACHE_SIZE_KEY, 0F); long bucketCacheSize; // Values < 1 are treated as % of heap if (bucketCachePercentage < 1) { long max = -1L; final MemoryUsage usage = safeGetHeapMemoryUsage(); if (usage != null) { max = usage.getMax(); } bucketCacheSize = (long)(max * bucketCachePercentage); // values >= 1 are treated as # of MiB } else { bucketCacheSize = (long)(bucketCachePercentage * 1024 * 1024); } return bucketCacheSize; } }
{ "content_hash": "15c8e208f4ee18bbb6ba913207b8e15e", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 105, "avg_line_length": 42.70454545454545, "alnum_prop": 0.6906155756608124, "repo_name": "JingchengDu/hbase", "id": "dbfb295eea3fbbe7f002f2200c55ce3f2f6cd894", "size": "12080", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/io/util/MemorySizeUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "351" }, { "name": "Batchfile", "bytes": "25288" }, { "name": "C", "bytes": "28534" }, { "name": "C++", "bytes": "56085" }, { "name": "CMake", "bytes": "13186" }, { "name": "CSS", "bytes": "35785" }, { "name": "Groovy", "bytes": "12548" }, { "name": "HTML", "bytes": "17275" }, { "name": "Java", "bytes": "31868492" }, { "name": "JavaScript", "bytes": "2694" }, { "name": "Makefile", "bytes": "1359" }, { "name": "PHP", "bytes": "8385" }, { "name": "Perl", "bytes": "383739" }, { "name": "Protocol Buffer", "bytes": "278993" }, { "name": "Python", "bytes": "109656" }, { "name": "Ruby", "bytes": "547382" }, { "name": "Scala", "bytes": "442815" }, { "name": "Shell", "bytes": "181569" }, { "name": "Thrift", "bytes": "41524" }, { "name": "XSLT", "bytes": "6764" } ], "symlink_target": "" }
package javax.persistence; import java.lang.annotation.Target; import java.lang.annotation.Retention; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Specifies a composite primary key class that is mapped to * multiple fields or properties of the entity. * * <p> The names of the fields or properties in the primary key * class and the primary key fields or properties of the entity * must correspond and their types must be the same. * * <pre> * * Example: * * &#064;IdClass(com.acme.EmployeePK.class) * &#064;Entity * public class Employee { * &#064;Id String empName; * &#064;Id Date birthDay; * ... * } * </pre> * * @since Java Persistence 1.0 */ @Target({TYPE}) @Retention(RUNTIME) public @interface IdClass { /** Primary key class */ Class value(); }
{ "content_hash": "37ab973e6b00365c202996862f685416", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 64, "avg_line_length": 22.82051282051282, "alnum_prop": 0.6831460674157304, "repo_name": "argv0/cloudstack", "id": "3a5eef715e2da8c53c2631eb92840cad77e5a450", "size": "2830", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "utils/src/javax/persistence/IdClass.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "52484672" }, { "name": "JavaScript", "bytes": "1913801" }, { "name": "Perl", "bytes": "824212" }, { "name": "Python", "bytes": "2076246" }, { "name": "Ruby", "bytes": "2166" }, { "name": "Shell", "bytes": "445096" } ], "symlink_target": "" }
package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.RandomAccess; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import javax.annotation.Nullable; /** * Synchronized collection views. The returned synchronized collection views are * serializable if the backing collection and the mutex are serializable. * * <p>If {@code null} is passed as the {@code mutex} parameter to any of this * class's top-level methods or inner class constructors, the created object * uses itself as the synchronization mutex. * * <p>This class should be used by other collection classes only. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) final class Synchronized { private Synchronized() {} static class SynchronizedObject implements Serializable { final Object delegate; final Object mutex; SynchronizedObject(Object delegate, @Nullable Object mutex) { this.delegate = checkNotNull(delegate); this.mutex = (mutex == null) ? this : mutex; } Object delegate() { return delegate; } // No equals and hashCode; see ForwardingObject for details. @Override public String toString() { synchronized (mutex) { return delegate.toString(); } } // Serialization invokes writeObject only when it's private. // The SynchronizedObject subclasses don't need a writeObject method since // they don't contain any non-transient member variables, while the // following writeObject() handles the SynchronizedObject members. @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { synchronized (mutex) { stream.defaultWriteObject(); } } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; } private static <E> Collection<E> collection( Collection<E> collection, @Nullable Object mutex) { return new SynchronizedCollection<E>(collection, mutex); } @VisibleForTesting static class SynchronizedCollection<E> extends SynchronizedObject implements Collection<E> { private SynchronizedCollection( Collection<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Collection<E> delegate() { return (Collection<E>) super.delegate(); } @Override public boolean add(E e) { synchronized (mutex) { return delegate().add(e); } } @Override public boolean addAll(Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(c); } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean contains(Object o) { synchronized (mutex) { return delegate().contains(o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return delegate().containsAll(c); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Iterator<E> iterator() { return delegate().iterator(); // manually synchronized } @Override public boolean remove(Object o) { synchronized (mutex) { return delegate().remove(o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return delegate().removeAll(c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return delegate().retainAll(c); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Object[] toArray() { synchronized (mutex) { return delegate().toArray(); } } @Override public <T> T[] toArray(T[] a) { synchronized (mutex) { return delegate().toArray(a); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <E> Set<E> set(Set<E> set, @Nullable Object mutex) { return new SynchronizedSet<E>(set, mutex); } static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { SynchronizedSet(Set<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Set<E> delegate() { return (Set<E>) super.delegate(); } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static <E> SortedSet<E> sortedSet( SortedSet<E> set, @Nullable Object mutex) { return new SynchronizedSortedSet<E>(set, mutex); } static class SynchronizedSortedSet<E> extends SynchronizedSet<E> implements SortedSet<E> { SynchronizedSortedSet(SortedSet<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSet<E> delegate() { return (SortedSet<E>) super.delegate(); } @Override public Comparator<? super E> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public SortedSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return sortedSet(delegate().subSet(fromElement, toElement), mutex); } } @Override public SortedSet<E> headSet(E toElement) { synchronized (mutex) { return sortedSet(delegate().headSet(toElement), mutex); } } @Override public SortedSet<E> tailSet(E fromElement) { synchronized (mutex) { return sortedSet(delegate().tailSet(fromElement), mutex); } } @Override public E first() { synchronized (mutex) { return delegate().first(); } } @Override public E last() { synchronized (mutex) { return delegate().last(); } } private static final long serialVersionUID = 0; } private static <E> List<E> list(List<E> list, @Nullable Object mutex) { return (list instanceof RandomAccess) ? new SynchronizedRandomAccessList<E>(list, mutex) : new SynchronizedList<E>(list, mutex); } private static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { SynchronizedList(List<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override List<E> delegate() { return (List<E>) super.delegate(); } @Override public void add(int index, E element) { synchronized (mutex) { delegate().add(index, element); } } @Override public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(index, c); } } @Override public E get(int index) { synchronized (mutex) { return delegate().get(index); } } @Override public int indexOf(Object o) { synchronized (mutex) { return delegate().indexOf(o); } } @Override public int lastIndexOf(Object o) { synchronized (mutex) { return delegate().lastIndexOf(o); } } @Override public ListIterator<E> listIterator() { return delegate().listIterator(); // manually synchronized } @Override public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); // manually synchronized } @Override public E remove(int index) { synchronized (mutex) { return delegate().remove(index); } } @Override public E set(int index, E element) { synchronized (mutex) { return delegate().set(index, element); } } @Override public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return list(delegate().subList(fromIndex, toIndex), mutex); } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list, @Nullable Object mutex) { super(list, mutex); } private static final long serialVersionUID = 0; } static <E> Multiset<E> multiset( Multiset<E> multiset, @Nullable Object mutex) { if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { return multiset; } return new SynchronizedMultiset<E>(multiset, mutex); } private static class SynchronizedMultiset<E> extends SynchronizedCollection<E> implements Multiset<E> { transient Set<E> elementSet; transient Set<Entry<E>> entrySet; SynchronizedMultiset(Multiset<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override Multiset<E> delegate() { return (Multiset<E>) super.delegate(); } @Override public int count(Object o) { synchronized (mutex) { return delegate().count(o); } } @Override public int add(E e, int n) { synchronized (mutex) { return delegate().add(e, n); } } @Override public int remove(Object o, int n) { synchronized (mutex) { return delegate().remove(o, n); } } @Override public int setCount(E element, int count) { synchronized (mutex) { return delegate().setCount(element, count); } } @Override public boolean setCount(E element, int oldCount, int newCount) { synchronized (mutex) { return delegate().setCount(element, oldCount, newCount); } } @Override public Set<E> elementSet() { synchronized (mutex) { if (elementSet == null) { elementSet = typePreservingSet(delegate().elementSet(), mutex); } return elementSet; } } @Override public Set<Entry<E>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = typePreservingSet(delegate().entrySet(), mutex); } return entrySet; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> Multimap<K, V> multimap( Multimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedMultimap || multimap instanceof ImmutableMultimap) { return multimap; } return new SynchronizedMultimap<K, V>(multimap, mutex); } private static class SynchronizedMultimap<K, V> extends SynchronizedObject implements Multimap<K, V> { transient Set<K> keySet; transient Collection<V> valuesCollection; transient Collection<Map.Entry<K, V>> entries; transient Map<K, Collection<V>> asMap; transient Multiset<K> keys; @SuppressWarnings("unchecked") @Override Multimap<K, V> delegate() { return (Multimap<K, V>) super.delegate(); } SynchronizedMultimap(Multimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public boolean containsKey(Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public boolean containsEntry(Object key, Object value) { synchronized (mutex) { return delegate().containsEntry(key, value); } } @Override public Collection<V> get(K key) { synchronized (mutex) { return typePreservingCollection(delegate().get(key), mutex); } } @Override public boolean put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public boolean putAll(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().putAll(key, values); } } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { synchronized (mutex) { return delegate().putAll(multimap); } } @Override public Collection<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public boolean remove(Object key, Object value) { synchronized (mutex) { return delegate().remove(key, value); } } @Override public Collection<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = typePreservingSet(delegate().keySet(), mutex); } return keySet; } } @Override public Collection<V> values() { synchronized (mutex) { if (valuesCollection == null) { valuesCollection = collection(delegate().values(), mutex); } return valuesCollection; } } @Override public Collection<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entries == null) { entries = typePreservingCollection(delegate().entries(), mutex); } return entries; } } @Override public Map<K, Collection<V>> asMap() { synchronized (mutex) { if (asMap == null) { asMap = new SynchronizedAsMap<K, V>(delegate().asMap(), mutex); } return asMap; } } @Override public Multiset<K> keys() { synchronized (mutex) { if (keys == null) { keys = multiset(delegate().keys(), mutex); } return keys; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> ListMultimap<K, V> listMultimap( ListMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedListMultimap || multimap instanceof ImmutableListMultimap) { return multimap; } return new SynchronizedListMultimap<K, V>(multimap, mutex); } private static class SynchronizedListMultimap<K, V> extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> { SynchronizedListMultimap( ListMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(K key) { synchronized (mutex) { return list(delegate().get(key), mutex); } } @Override public List<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public List<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } private static final long serialVersionUID = 0; } static <K, V> SetMultimap<K, V> setMultimap( SetMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedSetMultimap || multimap instanceof ImmutableSetMultimap) { return multimap; } return new SynchronizedSetMultimap<K, V>(multimap, mutex); } private static class SynchronizedSetMultimap<K, V> extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> { transient Set<Map.Entry<K, V>> entrySet; SynchronizedSetMultimap( SetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(K key) { synchronized (mutex) { return set(delegate().get(key), mutex); } } @Override public Set<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public Set<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Set<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entries(), mutex); } return entrySet; } } private static final long serialVersionUID = 0; } static <K, V> SortedSetMultimap<K, V> sortedSetMultimap( SortedSetMultimap<K, V> multimap, @Nullable Object mutex) { if (multimap instanceof SynchronizedSortedSetMultimap) { return multimap; } return new SynchronizedSortedSetMultimap<K, V>(multimap, mutex); } private static class SynchronizedSortedSetMultimap<K, V> extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> { SynchronizedSortedSetMultimap( SortedSetMultimap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { synchronized (mutex) { return sortedSet(delegate().get(key), mutex); } } @Override public SortedSet<V> removeAll(Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Comparator<? super V> valueComparator() { synchronized (mutex) { return delegate().valueComparator(); } } private static final long serialVersionUID = 0; } private static <E> Collection<E> typePreservingCollection( Collection<E> collection, @Nullable Object mutex) { if (collection instanceof SortedSet) { return sortedSet((SortedSet<E>) collection, mutex); } if (collection instanceof Set) { return set((Set<E>) collection, mutex); } if (collection instanceof List) { return list((List<E>) collection, mutex); } return collection(collection, mutex); } private static <E> Set<E> typePreservingSet( Set<E> set, @Nullable Object mutex) { if (set instanceof SortedSet) { return sortedSet((SortedSet<E>) set, mutex); } else { return set(set, mutex); } } private static class SynchronizedAsMapEntries<K, V> extends SynchronizedSet<Map.Entry<K, Collection<V>>> { SynchronizedAsMapEntries( Set<Map.Entry<K, Collection<V>>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Iterator<Map.Entry<K, Collection<V>>> iterator() { // Must be manually synchronized. final Iterator<Map.Entry<K, Collection<V>>> iterator = super.iterator(); return new ForwardingIterator<Map.Entry<K, Collection<V>>>() { @Override protected Iterator<Map.Entry<K, Collection<V>>> delegate() { return iterator; } @Override public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); return new ForwardingMapEntry<K, Collection<V>>() { @Override protected Map.Entry<K, Collection<V>> delegate() { return entry; } @Override public Collection<V> getValue() { return typePreservingCollection(entry.getValue(), mutex); } }; } }; } // See Collections.CheckedMap.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { synchronized (mutex) { return ObjectArrays.toArrayImpl(delegate()); } } @Override public <T> T[] toArray(T[] array) { synchronized (mutex) { return ObjectArrays.toArrayImpl(delegate(), array); } } @Override public boolean contains(Object o) { synchronized (mutex) { return Maps.containsEntryImpl(delegate(), o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return Collections2.containsAllImpl(delegate(), c); } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return Sets.equalsImpl(delegate(), o); } } @Override public boolean remove(Object o) { synchronized (mutex) { return Maps.removeEntryImpl(delegate(), o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return Iterators.removeAll(delegate().iterator(), c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return Iterators.retainAll(delegate().iterator(), c); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <K, V> Map<K, V> map(Map<K, V> map, @Nullable Object mutex) { return new SynchronizedMap<K, V>(map, mutex); } private static class SynchronizedMap<K, V> extends SynchronizedObject implements Map<K, V> { transient Set<K> keySet; transient Collection<V> values; transient Set<Map.Entry<K, V>> entrySet; SynchronizedMap(Map<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Map<K, V> delegate() { return (Map<K, V>) super.delegate(); } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean containsKey(Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public Set<Map.Entry<K, V>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entrySet(), mutex); } return entrySet; } } @Override public V get(Object key) { synchronized (mutex) { return delegate().get(key); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = set(delegate().keySet(), mutex); } return keySet; } } @Override public V put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public void putAll(Map<? extends K, ? extends V> map) { synchronized (mutex) { delegate().putAll(map); } } @Override public V remove(Object key) { synchronized (mutex) { return delegate().remove(key); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Collection<V> values() { synchronized (mutex) { if (values == null) { values = collection(delegate().values(), mutex); } return values; } } @Override public boolean equals(Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K, V> SortedMap<K, V> sortedMap( SortedMap<K, V> sortedMap, @Nullable Object mutex) { return new SynchronizedSortedMap<K, V>(sortedMap, mutex); } static class SynchronizedSortedMap<K, V> extends SynchronizedMap<K, V> implements SortedMap<K, V> { SynchronizedSortedMap(SortedMap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override SortedMap<K, V> delegate() { return (SortedMap<K, V>) super.delegate(); } @Override public Comparator<? super K> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public K firstKey() { synchronized (mutex) { return delegate().firstKey(); } } @Override public SortedMap<K, V> headMap(K toKey) { synchronized (mutex) { return sortedMap(delegate().headMap(toKey), mutex); } } @Override public K lastKey() { synchronized (mutex) { return delegate().lastKey(); } } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { synchronized (mutex) { return sortedMap(delegate().subMap(fromKey, toKey), mutex); } } @Override public SortedMap<K, V> tailMap(K fromKey) { synchronized (mutex) { return sortedMap(delegate().tailMap(fromKey), mutex); } } private static final long serialVersionUID = 0; } static <K, V> BiMap<K, V> biMap(BiMap<K, V> bimap, @Nullable Object mutex) { if (bimap instanceof SynchronizedBiMap || bimap instanceof ImmutableBiMap) { return bimap; } return new SynchronizedBiMap<K, V>(bimap, mutex, null); } @VisibleForTesting static class SynchronizedBiMap<K, V> extends SynchronizedMap<K, V> implements BiMap<K, V>, Serializable { private transient Set<V> valueSet; private transient BiMap<V, K> inverse; private SynchronizedBiMap(BiMap<K, V> delegate, @Nullable Object mutex, @Nullable BiMap<V, K> inverse) { super(delegate, mutex); this.inverse = inverse; } @Override BiMap<K, V> delegate() { return (BiMap<K, V>) super.delegate(); } @Override public Set<V> values() { synchronized (mutex) { if (valueSet == null) { valueSet = set(delegate().values(), mutex); } return valueSet; } } @Override public V forcePut(K key, V value) { synchronized (mutex) { return delegate().forcePut(key, value); } } @Override public BiMap<V, K> inverse() { synchronized (mutex) { if (inverse == null) { inverse = new SynchronizedBiMap<V, K>(delegate().inverse(), mutex, this); } return inverse; } } private static final long serialVersionUID = 0; } private static class SynchronizedAsMap<K, V> extends SynchronizedMap<K, Collection<V>> { transient Set<Map.Entry<K, Collection<V>>> asMapEntrySet; transient Collection<Collection<V>> asMapValues; SynchronizedAsMap(Map<K, Collection<V>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Collection<V> get(Object key) { synchronized (mutex) { Collection<V> collection = super.get(key); return (collection == null) ? null : typePreservingCollection(collection, mutex); } } @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { synchronized (mutex) { if (asMapEntrySet == null) { asMapEntrySet = new SynchronizedAsMapEntries<K, V>( delegate().entrySet(), mutex); } return asMapEntrySet; } } @Override public Collection<Collection<V>> values() { synchronized (mutex) { if (asMapValues == null) { asMapValues = new SynchronizedAsMapValues<V>(delegate().values(), mutex); } return asMapValues; } } @Override public boolean containsValue(Object o) { // values() and its contains() method are both synchronized. return values().contains(o); } private static final long serialVersionUID = 0; } private static class SynchronizedAsMapValues<V> extends SynchronizedCollection<Collection<V>> { SynchronizedAsMapValues( Collection<Collection<V>> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override public Iterator<Collection<V>> iterator() { // Must be manually synchronized. final Iterator<Collection<V>> iterator = super.iterator(); return new ForwardingIterator<Collection<V>>() { @Override protected Iterator<Collection<V>> delegate() { return iterator; } @Override public Collection<V> next() { return typePreservingCollection(super.next(), mutex); } }; } private static final long serialVersionUID = 0; } @GwtIncompatible("NavigableSet") @VisibleForTesting static class SynchronizedNavigableSet<E> extends SynchronizedSortedSet<E> implements NavigableSet<E> { SynchronizedNavigableSet(NavigableSet<E> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override NavigableSet<E> delegate() { return (NavigableSet<E>) super.delegate(); } @Override public E ceiling(E e) { synchronized (mutex) { return delegate().ceiling(e); } } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); // manually synchronized } transient NavigableSet<E> descendingSet; @Override public NavigableSet<E> descendingSet() { synchronized (mutex) { if (descendingSet == null) { NavigableSet<E> dS = Synchronized.navigableSet(delegate().descendingSet(), mutex); descendingSet = dS; return dS; } return descendingSet; } } @Override public E floor(E e) { synchronized (mutex) { return delegate().floor(e); } } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet( delegate().headSet(toElement, inclusive), mutex); } } @Override public E higher(E e) { synchronized (mutex) { return delegate().higher(e); } } @Override public E lower(E e) { synchronized (mutex) { return delegate().lower(e); } } @Override public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { synchronized (mutex) { return Synchronized.navigableSet(delegate().subSet( fromElement, fromInclusive, toElement, toInclusive), mutex); } } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet( delegate().tailSet(fromElement, inclusive), mutex); } } @Override public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } private static final long serialVersionUID = 0; } @GwtIncompatible("NavigableSet") static <E> NavigableSet<E> navigableSet( NavigableSet<E> navigableSet, @Nullable Object mutex) { return new SynchronizedNavigableSet<E>(navigableSet, mutex); } @GwtIncompatible("NavigableSet") static <E> NavigableSet<E> navigableSet(NavigableSet<E> navigableSet) { return navigableSet(navigableSet, null); } @GwtIncompatible("NavigableMap") static <K, V> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap) { return navigableMap(navigableMap, null); } @GwtIncompatible("NavigableMap") static <K, V> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap, @Nullable Object mutex) { return new SynchronizedNavigableMap<K, V>(navigableMap, mutex); } @GwtIncompatible("NavigableMap") @VisibleForTesting static class SynchronizedNavigableMap<K, V> extends SynchronizedSortedMap<K, V> implements NavigableMap<K, V> { SynchronizedNavigableMap( NavigableMap<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override NavigableMap<K, V> delegate() { return (NavigableMap<K, V>) super.delegate(); } @Override public Entry<K, V> ceilingEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().ceilingEntry(key), mutex); } } @Override public K ceilingKey(K key) { synchronized (mutex) { return delegate().ceilingKey(key); } } transient NavigableSet<K> descendingKeySet; @Override public NavigableSet<K> descendingKeySet() { synchronized (mutex) { if (descendingKeySet == null) { return descendingKeySet = Synchronized.navigableSet(delegate().descendingKeySet(), mutex); } return descendingKeySet; } } transient NavigableMap<K, V> descendingMap; @Override public NavigableMap<K, V> descendingMap() { synchronized (mutex) { if (descendingMap == null) { return descendingMap = navigableMap(delegate().descendingMap(), mutex); } return descendingMap; } } @Override public Entry<K, V> firstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().firstEntry(), mutex); } } @Override public Entry<K, V> floorEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().floorEntry(key), mutex); } } @Override public K floorKey(K key) { synchronized (mutex) { return delegate().floorKey(key); } } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { synchronized (mutex) { return navigableMap( delegate().headMap(toKey, inclusive), mutex); } } @Override public Entry<K, V> higherEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().higherEntry(key), mutex); } } @Override public K higherKey(K key) { synchronized (mutex) { return delegate().higherKey(key); } } @Override public Entry<K, V> lastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lastEntry(), mutex); } } @Override public Entry<K, V> lowerEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lowerEntry(key), mutex); } } @Override public K lowerKey(K key) { synchronized (mutex) { return delegate().lowerKey(key); } } @Override public Set<K> keySet() { return navigableKeySet(); } transient NavigableSet<K> navigableKeySet; @Override public NavigableSet<K> navigableKeySet() { synchronized (mutex) { if (navigableKeySet == null) { return navigableKeySet = Synchronized.navigableSet(delegate().navigableKeySet(), mutex); } return navigableKeySet; } } @Override public Entry<K, V> pollFirstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollFirstEntry(), mutex); } } @Override public Entry<K, V> pollLastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollLastEntry(), mutex); } } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { synchronized (mutex) { return navigableMap( delegate().subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { return navigableMap( delegate().tailMap(fromKey, inclusive), mutex); } } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } private static final long serialVersionUID = 0; } @GwtIncompatible("works but is needed only for NavigableMap") private static <K, V> Entry<K, V> nullableSynchronizedEntry( @Nullable Entry<K, V> entry, @Nullable Object mutex) { if (entry == null) { return null; } return new SynchronizedEntry<K, V>(entry, mutex); } @GwtIncompatible("works but is needed only for NavigableMap") private static class SynchronizedEntry<K, V> extends SynchronizedObject implements Entry<K, V> { SynchronizedEntry(Entry<K, V> delegate, @Nullable Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") // guaranteed by the constructor @Override Entry<K, V> delegate() { return (Entry<K, V>) super.delegate(); } @Override public boolean equals(Object obj) { synchronized (mutex) { return delegate().equals(obj); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } @Override public K getKey() { synchronized (mutex) { return delegate().getKey(); } } @Override public V getValue() { synchronized (mutex) { return delegate().getValue(); } } @Override public V setValue(V value) { synchronized (mutex) { return delegate().setValue(value); } } private static final long serialVersionUID = 0; } }
{ "content_hash": "a05b445ed867fa29efcb7062fc870ac1", "timestamp": "", "source": "github", "line_count": 1551, "max_line_length": 80, "avg_line_length": 26.259832366215345, "alnum_prop": 0.6135431756242481, "repo_name": "windyuuy/opera", "id": "4262b27978a477e75f35249e12619e36ba741c60", "size": "41329", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "chromium/src/third_party/guava/src/guava/src/com/google/common/collect/Synchronized.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "25707" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Assembly", "bytes": "51642" }, { "name": "Batchfile", "bytes": "35942" }, { "name": "C", "bytes": "4303018" }, { "name": "C#", "bytes": "35203" }, { "name": "C++", "bytes": "207333360" }, { "name": "CMake", "bytes": "25089" }, { "name": "CSS", "bytes": "681256" }, { "name": "Dart", "bytes": "24294" }, { "name": "Emacs Lisp", "bytes": "25534" }, { "name": "Groff", "bytes": "5283" }, { "name": "HTML", "bytes": "10400943" }, { "name": "IDL", "bytes": "836" }, { "name": "Java", "bytes": "2821184" }, { "name": "JavaScript", "bytes": "14563996" }, { "name": "Lua", "bytes": "13749" }, { "name": "Makefile", "bytes": "55521" }, { "name": "Objective-C", "bytes": "1211523" }, { "name": "Objective-C++", "bytes": "6221908" }, { "name": "PHP", "bytes": "61320" }, { "name": "Perl", "bytes": "82949" }, { "name": "Protocol Buffer", "bytes": "280464" }, { "name": "Python", "bytes": "12627773" }, { "name": "Rebol", "bytes": "262" }, { "name": "Ruby", "bytes": "937" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "894814" }, { "name": "VimL", "bytes": "4953" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "14650" } ], "symlink_target": "" }
module Formats class DottiesPostup < Zshrc end end
{ "content_hash": "5cc306354c2ba49d97e19e02e7656fb0", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 29, "avg_line_length": 13.75, "alnum_prop": 0.7636363636363637, "repo_name": "tinytacoteam/dotties-core", "id": "424d561599a0a88cc37c17f62e7e016cdedd1d97", "size": "55", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/dotties-core/formats/dotties_postup.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "12041" } ], "symlink_target": "" }
namespace axl { namespace cf { //.............................................................................. void SecScopedBookmark::close() { stopAccess(); m_filePath.clear(); m_isDirectory = false; m_dataCache.clear(); } void SecScopedBookmark::create( const sl::StringRef& filePath, bool isDirectory ) { if (m_filePath == filePath && m_isDirectory == isDirectory) return; stopAccess(); m_filePath = filePath; m_isDirectory = isDirectory; m_dataCache.clear(); } void SecScopedBookmark::copy(const SecScopedBookmark& src) { if (this == &src || m_filePath == src.m_filePath && m_isDirectory == src.m_isDirectory) return; stopAccess(); m_filePath = src.m_filePath; m_isDirectory = src.m_isDirectory; m_dataCache = src.m_dataCache; if (!src.m_accessUrl) return; bool result = ((Url*)&src.m_accessUrl)->startAccessingSecurityScopedResource(); if (result) m_accessUrl = src.m_accessUrl; else AXL_TRACE("WARNING: can't access an already-accessible resource: %s", err::getLastErrorDescription().sz()); } #if (_AXL_CPP_HAS_RVALUE_REF) void SecScopedBookmark::move(SecScopedBookmark&& src) { stopAccess(); m_filePath = std::move(src.m_filePath); m_accessUrl = std::move(src.m_accessUrl); m_dataCache = std::move(src.m_dataCache); m_isDirectory = std::move(src.m_isDirectory); } #endif bool SecScopedBookmark::load( const void* p, size_t size ) { close(); Url url; bool result = url.resolveBookmark(p, size, kCFURLBookmarkResolutionWithoutUIMask | kCFURLBookmarkResolutionWithSecurityScope); if (!result) return false; m_filePath = url.getFileSystemPath(); m_isDirectory = url.isDirectory(); stopAccess(); result = url.startAccessingSecurityScopedResource(); // may fail for already-accessible locations (not an error really) if (result) m_accessUrl = std::move(url); return true; } bool SecScopedBookmark::save(sl::Array<char>* buffer) const { if (!m_dataCache.isEmpty()) { *buffer = m_dataCache; return true; } Url url; bool result = url.create(m_filePath, kCFURLPOSIXPathStyle, m_isDirectory) && url.createBookmark(&m_dataCache, kCFURLBookmarkCreationWithSecurityScope); if (!result) return false; *buffer = m_dataCache; return true; } void SecScopedBookmark::stopAccess() { if (!m_accessUrl) return; m_accessUrl.stopAccessingSecurityScopedResource(); m_accessUrl.clear(); } //.............................................................................. } // namespace cf } // namespace axl
{ "content_hash": "eecf1cc1c1bfad3b154497fec4d9c1ef", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 127, "avg_line_length": 21.10169491525424, "alnum_prop": 0.6686746987951807, "repo_name": "vovkos/axl", "id": "ff055b77a559593302feca2b9eba425ea3971ab2", "size": "2990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/axl_cf/axl_cf_SecScopedBookmark.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "8807" }, { "name": "Batchfile", "bytes": "10532" }, { "name": "C", "bytes": "698735" }, { "name": "C++", "bytes": "1881436" }, { "name": "CMake", "bytes": "158055" }, { "name": "Perl", "bytes": "626" }, { "name": "Ragel", "bytes": "13661" }, { "name": "Shell", "bytes": "7699" } ], "symlink_target": "" }
import { expect } from 'chai'; import configureStore from 'redux-mock-store'; import { thunk } from '~/store/configureStore'; import * as actions from './actions'; import actionTypes from './actionTypes'; const middlewares = [thunk]; const mockStore = configureStore(middlewares); describe('UI actions', () => { let alert; let store; let initialState; let expectedActions; beforeEach(() => { initialState = {}; }); describe('setAlert()', () => { beforeEach(() => { initialState = {}; store = mockStore(initialState); alert = { type: 'error', message: 'some error message' }; }); context('when the alert is set', () => { beforeEach(() => { expectedActions = [{ type: actionTypes.SET_ALERT, alert }]; return store.dispatch(actions.setAlert(alert)); }); it('executes the expected actions', () => ( expect(store.getActions()).to.deep.equal(expectedActions) )); }); }); describe('closeAlert()', () => { beforeEach(() => { initialState = {}; store = mockStore(initialState); alert = { type: 'error', message: 'some error message' }; }); context('when the alert is deleted', () => { beforeEach(() => { expectedActions = [{ type: actionTypes.CLOSE_ALERT }]; return store.dispatch(actions.closeAlert(alert)); }); it('executes the expected actions', () => ( expect(store.getActions()).to.deep.equal(expectedActions) )); }); }); });
{ "content_hash": "16e6a9239f199d89964e07041344718f", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 67, "avg_line_length": 24.80952380952381, "alnum_prop": 0.5674984005118362, "repo_name": "lucaslencinas/react-node-socketio-template", "id": "25a4f45585c5d73487da9604345cddcc8b5956fa", "size": "1563", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/domains/ui/actions.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3095" }, { "name": "JavaScript", "bytes": "30296" } ], "symlink_target": "" }
import { request } from '../core/request'; class DomainCheckResource { get(q) { return request(`api/v1/check?name=${q}`); } } export const DomainCheck = new DomainCheckResource();
{ "content_hash": "ea41df1fe35e03a3d12f14f6dce94418", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 53, "avg_line_length": 20.666666666666668, "alnum_prop": 0.6881720430107527, "repo_name": "everdimension/check.ru", "id": "e003f22b47eafb425d285447ee9a31703b06b644", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/api/DomainCheck.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12651" }, { "name": "HTML", "bytes": "3066" }, { "name": "JavaScript", "bytes": "70498" }, { "name": "Shell", "bytes": "467" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "c47243214bd751e8475db3fded5c94f3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "4a598668bc53f20d4cf5083a4b1674a9483d0a4b", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Commelinales/Haemodoraceae/Anigozanthos/Anigozanthos manglesii/ Syn. Anigozanthos manglesii leptophylla/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* "$Header$ */ /* * Copyright (c) 1995-1997 Sam Leffler * Copyright (c) 1995-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * Generate a library version string for systems that * do not have a shell (by default this is done with * awk and echo from the Makefile). * * This was written by Peter Greenham for Acorn systems. * * Syntax: mkversion [-v version-file] [<outfile>] */ #include <stdio.h> #include <stdlib.h> #include <string.h> static void usage(void) { fprintf(stderr, "usage: mkversion [-v version-file]\n" " [-r releasedate-file] [outfile]\n"); exit(-1); } static FILE* openFile(char* filename) { FILE* fd = fopen(filename, "r"); if (fd == NULL) { fprintf(stderr, "mkversion: %s: Could not open for reading.\n", filename); exit(-1); } return (fd); } int main(int argc, char* argv[]) { char* versionFile = "../VERSION"; char* releaseDateFile = "../RELEASE-DATE"; char version[128]; char rawReleaseDate[128]; char tiffLibVersion[128]; FILE* fd; char* cp; argc--, argv++; while (argc > 0 && argv[0][0] == '-') { if (strcmp(argv[0], "-v") == 0) { if (argc < 1) usage(); argc--, argv++; versionFile = argv[0]; } else if (strcmp(argv[0], "-r") == 0) { if (argc < 1) usage(); argc--, argv++; releaseDateFile = argv[0]; } else usage(); argc--, argv++; } /* * Read the VERSION file. */ fd = openFile(versionFile); if (fgets(version, sizeof (version)-1, fd) == NULL) { fprintf(stderr, "mkversion: No version information in %s.\n", versionFile); exit(-1); } cp = strchr(version, '\n'); if (cp) *cp = '\0'; fclose(fd); /* * Read the RELEASE-DATE, and translate format to emit TIFFLIB_VERSION. */ fd = openFile(releaseDateFile); if (fgets(rawReleaseDate, sizeof (rawReleaseDate)-1, fd) == NULL) { fprintf(stderr, "mkversion: No release date information in %s.\n", releaseDateFile); exit(-1); } fclose(fd); sprintf( tiffLibVersion, "#define TIFFLIB_VERSION %4.4s%2.2s%2.2s", rawReleaseDate+6, rawReleaseDate+0, rawReleaseDate+3 ); /* * Emit the tiffvers.h file. */ if (argc > 0) { fd = fopen(argv[0], "w"); if (fd == NULL) { fprintf(stderr, "mkversion: %s: Could not open for writing.\n", argv[0]); exit(-1); } } else fd = stdout; fprintf(fd, "#define TIFFLIB_VERSION_STR \"LIBTIFF, Version %s\\n", version); fprintf(fd, "Copyright (c) 1988-1996 Sam Leffler\\n"); fprintf(fd, "Copyright (c) 1991-1996 Silicon Graphics, Inc.\"\n"); fprintf( fd, "/*\n" " * This define can be used in code that requires\n" " * compilation-related definitions specific to a\n" " * version or versions of the library. Runtime\n" " * version checking should be done based on the\n" " * string returned by TIFFGetVersion.\n" " */\n" ); fprintf(fd, "%s\n", tiffLibVersion ); if (fd != stdout) fclose(fd); return (0); }
{ "content_hash": "0db6ade8633dd547fd8ed0b40b7db939", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 81, "avg_line_length": 28.91216216216216, "alnum_prop": 0.6139284879644776, "repo_name": "libla/luacode", "id": "5e99f03df68c0a3734e9d055a0003e7fb7f2fcc5", "size": "4279", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "libs/wxWidgets/src/tiff/mkversion.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "140685" }, { "name": "Batchfile", "bytes": "8174" }, { "name": "C", "bytes": "8830730" }, { "name": "C++", "bytes": "20516155" }, { "name": "CSS", "bytes": "8680" }, { "name": "DIGITAL Command Language", "bytes": "4055" }, { "name": "Groff", "bytes": "216724" }, { "name": "HTML", "bytes": "306015" }, { "name": "Inno Setup", "bytes": "3873" }, { "name": "JavaScript", "bytes": "30416" }, { "name": "Lua", "bytes": "553896" }, { "name": "Makefile", "bytes": "62813" }, { "name": "Module Management System", "bytes": "38773" }, { "name": "NSIS", "bytes": "5541" }, { "name": "Objective-C", "bytes": "108425" }, { "name": "PHP", "bytes": "36038" }, { "name": "Python", "bytes": "14696" }, { "name": "Shell", "bytes": "155800" }, { "name": "Slash", "bytes": "27675" }, { "name": "SourcePawn", "bytes": "8634" } ], "symlink_target": "" }
<?php namespace Akuma\Bundle\BootswatchBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Exception\IOException; /** * InstallCommand * */ class InstallCommand extends ContainerAwareCommand { /** * {@inheritDoc} */ protected function configure() { $this->setName('akuma:bootswatch:install') ->setDescription('Installs the icon font'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $destDir = $this->getDestDir(); $finder = new Finder; $fs = new Filesystem; try { $fs->mkdir($destDir); } catch (IOException $e) { $output->writeln(sprintf('<error>Could not create directory %s.</error>', $destDir)); return; } $srcDir = $this->getSrcDir(); if (false === file_exists($srcDir)) { $output->writeln(sprintf( '<error>Fonts directory "%s" does not exist. Did you install thomaspark/bootswatch?</error>', $srcDir )); return; } $finder->files()->in($srcDir); foreach ($finder as $file) { $dest = sprintf('%s/%s', $destDir, $file->getBaseName()); try { $fs->copy($file, $dest); } catch (IOException $e) { $output->writeln(sprintf('<error>Could not copy %s</error>', $file->getBaseName())); return; } } $output->writeln(sprintf('Copied icon fonts to <comment>%s</comment>.', $destDir)); if($this->getContainer()->getParameter('akuma_bootswatch.font_awesome')){ $srcDir = $this->getFaSrcDir(); if (false === file_exists($srcDir)) { $output->writeln(sprintf( '<error>Fonts directory "%s" does not exist. Did you install thomaspark/bootswatch?</error>', $srcDir )); return; } $finder->files()->in($srcDir); foreach ($finder as $file) { $dest = sprintf('%s/%s', $destDir, $file->getBaseName()); try { $fs->copy($file, $dest); } catch (IOException $e) { $output->writeln(sprintf('<error>Could not copy %s</error>', $file->getBaseName())); return; } } $output->writeln(sprintf('Copied Font-Awesome icon fonts to <comment>%s</comment>.', $destDir)); } } protected function getFaSrcDir() { return sprintf( '%s/%s', $this->getContainer()->getParameter('akuma_bootswatch.bootswatch.path'), 'bower_components/font-awesome/fonts' ); } /** * @return string */ protected function getSrcDir() { return sprintf( '%s/%s', $this->getContainer()->getParameter('akuma_bootswatch.bootswatch.path'), ( // Sass version stores fonts in a different directory in_array($this->getContainer()->getParameter('akuma_bootswatch.less_filter'), array('sass', 'scssphp')) ? 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap' : 'bower_components/bootstrap/fonts' ) ); } /** * @return string */ protected function getDestDir() { return $this->getContainer()->getParameter('akuma_bootswatch.fonts_dir'); } }
{ "content_hash": "1ae07e89bc2b282c91541f67b4796415", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 117, "avg_line_length": 29.33587786259542, "alnum_prop": 0.5368201925578975, "repo_name": "inri13666/AkumaBootswatchBundle", "id": "eebdaf2c930e3cdf92163065ca592eff10766a27", "size": "3843", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Command/InstallCommand.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "588" }, { "name": "HTML", "bytes": "175227" }, { "name": "JavaScript", "bytes": "3713" }, { "name": "PHP", "bytes": "61638" } ], "symlink_target": "" }
.include "${.CURDIR}/../Makefile.inc" .PATH: ${SVNDIR}/libsvn_wc INTERNALLIB= yes LIB= svn_wc SRCS= adm_crawler.c adm_files.c adm_ops.c \ ambient_depth_filter_editor.c cleanup.c conflicts.c \ context.c copy.c crop.c delete.c deprecated.c diff_editor.c \ diff_local.c entries.c externals.c info.c lock.c merge.c \ node.c old-and-busted.c props.c questions.c relocate.c \ revert.c revision_status.c status.c translate.c \ tree_conflicts.c update_editor.c upgrade.c util.c \ wc_db.c wc_db_pristine.c wc_db_update_move.c wc_db_util.c \ wc_db_wcroot.c wcroot_anchor.c workqueue.c CFLAGS+= -I${SVNDIR}/include -I${SVNDIR} -I${.CURDIR}/../.. \ -I${.CURDIR}/../libapr \ -I${APR}/include/arch/unix \ -I${APR}/include \ -I${.CURDIR}/../libapr_util \ -I${APRU}/include/private \ -I${APRU}/include .include <bsd.lib.mk>
{ "content_hash": "297c9f6ecc5f5916aa1497920acda1ed", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 63, "avg_line_length": 32.42307692307692, "alnum_prop": 0.6725978647686833, "repo_name": "jhbsz/OSI-OS", "id": "ce3905a6670ef6afa4be110376f6bb80cfabca83", "size": "856", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "usr.bin/svn/lib/libsvn_wc/Makefile", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
layout: page title: "RUSS 4861: Absurd and Supernatural in Russian Literature Statistics" comments: true description: "blanks" keywords: "RUSS,4861,CU,Boulder" --- <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script> <!-- <script src="../assets/js/highcharts.js"></script> --> <style type="text/css">@font-face { font-family: "Bebas Neue"; src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype"); } h1.Bebas { font-family: "Bebas Neue", Verdana, Tahoma; } </style> </head> <body> <div id="container" style="float: right; width: 45%; height: 88%; margin-left: 2.5%; margin-right: 2.5%;"></div> <script language="JavaScript"> $(document).ready(function() { var chart = {type: 'column'}; var title = {text: 'Grade Distribution'}; var xAxis = {categories: ['A','B','C','D','F'],crosshair: true}; var yAxis = {min: 0,title: {text: 'Percentage'}}; var tooltip = {headerFormat: '<center><b><span style="font-size:20px">{point.key}</span></b></center>', pointFormat: '<td style="padding:0"><b>{point.y:.1f}%</b></td>', footerFormat: '</table>',shared: true,useHTML: true}; var plotOptions = {column: {pointPadding: 0.0,borderWidth: 0}}; var credits = {enabled: false};var series= [{name: 'Percent',data: [49.44,23.44,14.33,2.0,10.78,]}]; var json = {}; json.chart = chart; json.title = title; json.tooltip = tooltip; json.xAxis = xAxis; json.yAxis = yAxis; json.series = series; json.plotOptions = plotOptions; json.credits = credits; $('#container').highcharts(json); }); </script> </body> #### GRADE AND WORKLOAD STATISTICS **Percent withdrawn**: 1.9% **Percent incomplete**: 0.0% **Average grade** (4.0 scale): 2.92 **Standard deviation in grades** (4.0 scale): 0.1 **Average workload** (raw): 2.72 **Standard deviation in workload** (raw): 0.17 #### COURSE AND INSTRUCTOR RATINGS/INFORMATION **Average course rating** (6 point scale): 4.29 **Standard deviation in course rating** (6 point scale): 0.95 **Average instructor rating** (6 point scale): 4.39 **Standard deviation in instructor rating** (6 point scale): 1.28 **Instructors**: <a href='../../instructors/Laura_Olson_Osterman'>Laura Olson Osterman</a>, <a href='../../instructors/Meghan_Vicks'>Meghan Vicks</a> #### GENERAL CLASS INFORMATION **Years provided**: Fall 2008, Spring 2013 **Credits**: 3 **RAP/Honors class?** Neither **Number of Sections**: 2 **Department**: GSLL **College**: College of Arts and Sciences **A&S Division**: Arts and Humanities **Level**: Upper **Activity**: LEC - Lecture
{ "content_hash": "7185b26ed2885e89a3026df90d5d6282", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 149, "avg_line_length": 30.274725274725274, "alnum_prop": 0.6588021778584392, "repo_name": "nikhilrajaram/nikhilrajaram.github.io", "id": "14a024549413695e9efe87e2b064728d31ee449e", "size": "2759", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "courses/RUSS-4861.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15727" }, { "name": "HTML", "bytes": "48339721" }, { "name": "Python", "bytes": "9692" }, { "name": "Ruby", "bytes": "5940" } ], "symlink_target": "" }
(function () { "use strict"; const numCPUs = require('os').cpus().length; const child_process = require("child_process"); const uuid = require("uuid-v4"); const Q = require("q"); const _ = require("lodash"); const HEARTBEAT_TICK = 1000 * 60; //60s const HEARTBEAT_DELAY = 1000 * 1; //1s let WORKER = []; let PROVIDED = {}; let MESSAGES = {}; let CONSUMEABLES = {}; let QUEUE = {}; let HEARTBEAT_TIMEOUT; let supervisor = module.exports = { provide: provide, request: request, cluster: cluster, stats: stats, log: { info: console.log.bind(console), error: console.error.bind(console), debug: console.log.bind(console), verbose: console.log.bind(console), silly: console.log.bind(console) } }; // Clustered Worker if (process.env.WORKER === "true") { recieveHeartbeat(); supervisor.log = { info: logFactory("info"), error: logFactory("error"), debug: logFactory("debug"), verbose: logFactory("verbose"), silly: logFactory("silly") }; } process.on('exit', () => { WORKER.forEach((worker) => { worker.kill(); }); }); process.on('message', (m) => { //request from master to worker for job if (m.request) { if (typeof CONSUMEABLES[m.request] === "function") { let res = CONSUMEABLES[m.request].apply(null, m.args || []); Q.when(res) .then((res) => { process.send({ result: res, success: true, reply: true, id: m.id }); }) .catch((err) => { supervisor.log.error(err); process.send({ result: err, success: false, reply: true, id: m.id }); }); } } //master -> worker heartbeat if (m.heartbeat) { recieveHeartbeat(); } }); function recieveHeartbeat() { clearTimeout(HEARTBEAT_TIMEOUT); HEARTBEAT_TIMEOUT = setTimeout(() => { supervisor.log.info(`recieved no heartbeat after ${HEARTBEAT_TICK}ms -> suicide`); process.exit(0); }, HEARTBEAT_TICK); } function logFactory(level) { return function () { let args = Array.prototype.slice.call(arguments); process.send({ log: true, level: level, args: args }); }; } function provide(name, fn) { name = name.toLowerCase(); process.send({ provide: name }); CONSUMEABLES[name] = fn; } function request() { let args = Array.prototype.slice.call(arguments); let name = args.shift().toLowerCase(); let deferred = Q.defer(); let id = uuid(); let msg = { request: name, args: args, id: id, deferred: deferred }; MESSAGES[id] = msg; if (PROVIDED[name] && PROVIDED[name].length) { send(name, msg); } else { QUEUE[name] = QUEUE[name] || []; QUEUE[name].push(msg); } return deferred.promise; } function send(name, msg, childOverride) { let child = childOverride || PROVIDED[name][0]; if (!child) { QUEUE[name] = QUEUE[name] || []; QUEUE[name].push(msg); return; } child.threads++; msg.worker = child; child.send({ id: msg.id, request: msg.request, args: msg.args }); PROVIDED[name].sort((a, b) => { let res = a.threads - b.threads; //roundrobin if (res === 0) { res = a.threadsdone - b.threadsdone; } return res; }); } function cluster(path) { for (let i = 0; i < numCPUs; i++) { createWorker(path); } } function createWorker(path) { let env = _.clone(process.env); env.SUPERVISOR_MODE = "child"; let child = child_process.fork(path, [], { env: _.extend(env, { "WORKER": true }), execArgv: [] }); child.threads = 0; child.threadsdone = 0; child.title = `${path} ${pad(child.pid, 6)}`; child.titlemin = `[WORKER${pad(child.pid, 7)}]`; WORKER.push(child); supervisor.log.info(`${child.titlemin} spawned`); let interval = setInterval(() => { child.send({ heartbeat: true }); }, HEARTBEAT_DELAY); child.on('exit', (worker, signal) => { clearInterval(interval); setTimeout(() => { supervisor.log.error(`${child.titlemin} died - signal: ${signal}`); cleanup(child, path); }, 500); }); child.on("message", (msg) => { if (msg.log) { msg.args.unshift(child.titlemin); supervisor.log[msg.level].apply(supervisor.log, msg.args); } if (msg.provide) { if (!Array.isArray(msg.provide)) { msg.provide = [msg.provide]; } msg.provide.forEach((name) => { name = name.toLowerCase(); PROVIDED[name] = PROVIDED[name] || []; PROVIDED[name].push(child); if (QUEUE[name]) { QUEUE[name].forEach(msg => send(name, msg)); delete QUEUE[name]; } }); } if (msg.reply) { child.threads--; child.threadsdone++; //other worker finished this, might happen after relocate if (!MESSAGES[msg.id]) { return; } let deferred = MESSAGES[msg.id].deferred; if (msg.success) { deferred.resolve(msg.result); } else { deferred.reject(msg.result); } delete MESSAGES[msg.id]; } }); return child; } function cleanup(child, path) { removeChild(child); let next = createWorker(path); relocateMessages(child, next); } function removeChild(child) { let index = WORKER.indexOf(child); if (index !== -1) { WORKER.splice(index, 1); } Object.getOwnPropertyNames(PROVIDED) .forEach((name) => { let index = PROVIDED[name].indexOf(child); if (index !== -1) { PROVIDED[name].splice(index, 1); } }); } function stats() { return { workers: WORKER.map(child => { return { id: child.pid, threads: child.threads, done: child.threadsdone }; }) }; } function relocateMessages(prevChild, nextChild) { let c = 0; Object.getOwnPropertyNames(MESSAGES) .forEach((id) => { let msg = MESSAGES[id]; if (msg.worker === prevChild) { send(msg.request, msg, nextChild); c++; } }); supervisor.log.error(`${prevChild.titlemin} -> relocated ${c}/${prevChild.threads} tasks`); } function pad(value, length) { return (value.toString().length < length) ? pad(" " + value, length) : value; } })();
{ "content_hash": "a46b2f54d629a006bb212b8133dd8693", "timestamp": "", "source": "github", "line_count": 299, "max_line_length": 95, "avg_line_length": 22.732441471571907, "alnum_prop": 0.5271443283801677, "repo_name": "Bombshock/supervisor", "id": "4161f72161e2f7c8d6b0858974d70ea8188faead", "size": "6885", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "supervisor.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10833" } ], "symlink_target": "" }
<?php class xTblRefDataRaw extends Eloquent{ /** * The database table used by the model. * * @var string */ protected $table = 'tbl_ref_data_raw'; //protected $timestamps = false; }
{ "content_hash": "f9a71c3b9636e5ae911fa936ff68cdf6", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 41, "avg_line_length": 10.68421052631579, "alnum_prop": 0.625615763546798, "repo_name": "i2x/raindb", "id": "a5fcd8e2b7cd55b89331a08f59e50b1c5226c5d1", "size": "203", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/xTblRefDataRaw.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "234239" }, { "name": "Java", "bytes": "81125" }, { "name": "JavaScript", "bytes": "3579479" }, { "name": "PHP", "bytes": "945082" }, { "name": "Prolog", "bytes": "5620" }, { "name": "Python", "bytes": "7918" }, { "name": "Shell", "bytes": "14762" } ], "symlink_target": "" }
/* popModal - 1.23 [11.04.16] Author: vadimsva Github: https://github.com/vadimsva/popModal */ $(function() { /* popModal */ (function($) { $.fn.popModal = function(method) { var elem = $(this), elemObj, isFixed = '', closeBut = '', elemClass = 'popModal', overflowContentClass = '', asMenuClass, _options, animTime, effectIn = 'fadeIn', effectOut = 'fadeOut', bl = 'bottomLeft', bc = 'bottomCenter', br = 'bottomRight', lt = 'leftTop', lc = 'leftCenter', rt = 'rightTop', rc = 'rightCenter', currentID; var methods = { init : function(params) { var _defaults = { html: '', placement: bl, showCloseBut: true, onDocumentClickClose : true, onDocumentClickClosePrevent : '', overflowContent : false, inline : true, asMenu : false, beforeLoadingContent : 'Please, wait...', onOkBut: function() {return true;}, onCancelBut: function() {}, onLoad: function() {}, onClose: function() {} }; _options = $.extend(_defaults, params); if ( $('body').find('.' + elemClass).length !== 0 && $('body').find('.' + elemClass).attr('data-popmodal_id') == elem.attr('data-popmodal_id') ) { popModalClose(); } else { $('html.' + elemClass + 'Open').off('.' + elemClass + 'Event').removeClass(elemClass + 'Open'); $('.' + elemClass + '_source').replaceWith($('.' + elemClass + '_content').children()); $('.' + elemClass).remove(); if (elem.css('position') == 'fixed') { isFixed = 'position:fixed;'; } if (_options.asMenu) { asMenuClass = ' ' + elemClass + '_asMenu'; } else { asMenuClass = ''; if (_options.showCloseBut) { closeBut = $('<button type="button" class="close">&times;</button>'); } if (_options.overflowContent) { overflowContentClass = ' ' + elemClass + '_contentOverflow'; } else { overflowContentClass = ''; } } currentID = new Date().getMilliseconds(); elem.attr('data-popmodal_id', currentID); var tooltipContainer = $('<div class="' + elemClass + ' animated" style="' + isFixed + '" data-popmodal_id="' + currentID + '"></div>'); var tooltipContent = $('<div class="' + elemClass + '_content' + overflowContentClass + asMenuClass + '"></div>'); tooltipContainer.append(closeBut, tooltipContent); if ($.isFunction(_options.html)) { var beforeLoadingContent = _options.beforeLoadingContent; tooltipContent.append(beforeLoadingContent); _options.html(function(loadedContent) { tooltipContent.empty().append(loadedContent); elemObj = $('.' + elemClass); getPlacement(); }); } else { if ($.type(_options.html) == 'object') { _options.html.after($('<div class="popModal_source"></div>')); } tooltipContent.append(_options.html); } if ($(window).width() <= 500) { _options.inline = true; } if (_options.inline) { elem.after(tooltipContainer); } else { $('body').append(tooltipContainer); } elemObj = $('.' + elemClass); var elemObjFooter = elemObj.find('.' + elemClass + '_footer'); if (elemObjFooter.length != 0) { elemObj.find('.' + elemClass + '_content').css({marginBottom: elemObjFooter.outerHeight() + 15 + 'px'}); } if (!$.isFunction(_options.html)) { var htmlStr; if ($.type(_options.html) == 'string') { htmlStr = _options.html; } else { htmlStr = _options.html[0].outerHTML; } } if (_options.onLoad && $.isFunction(_options.onLoad)) { _options.onLoad(); } $(_options.html).trigger('load'); elemObj.on('destroyed', function() { if (_options.onClose && $.isFunction(_options.onClose)) { _options.onClose(); } $(_options.html).trigger('close'); }); getPlacement(); if (_options.onDocumentClickClose) { $('html').on('click.' + elemClass + 'Event', function(event) { $(this).addClass(elemClass + 'Open'); if (elemObj.is(':hidden')) { popModalClose(); } var target = $(event.target); if (!target.parents().addBack().is('.' + elemClass) && !target.parents().addBack().is(elem)) { var zIndex = parseInt(target.parents().filter(function() { return $(this).css('zIndex') !== 'auto'; }).first().css('zIndex')); if (isNaN(zIndex)) { zIndex = 0; } if (_options.onDocumentClickClosePrevent !== '' && target.is(_options.onDocumentClickClosePrevent)) { zIndex = 9999; } var target_zIndex = target.css('zIndex'); if (target_zIndex == 'auto') { target_zIndex = 0; } if (zIndex < target_zIndex) { zIndex = target_zIndex; } if (zIndex <= elemObj.css('zIndex')) { popModalClose(); } } }); } $(window).resize(function() { getPlacement(); }); elemObj.find('.close').on('click', function() { popModalClose(); $(this).off('click'); }); elemObj.find('[data-popmodal-but="close"]').on('click', function() { popModalClose(); $(this).off('click'); }); elemObj.find('[data-popmodal-but="ok"]').on('click', function(event) { var ok; if (_options.onOkBut && $.isFunction(_options.onOkBut)) { ok = _options.onOkBut(event); } if (ok !== false) { popModalClose(); } $(this).off('click'); $(_options.html).trigger('okbut'); }); elemObj.find('[data-popmodal-but="cancel"]').on('click', function() { if (_options.onCancelBut && $.isFunction(_options.onCancelBut)) { _options.onCancelBut(); } popModalClose(); $(this).off('click'); $(_options.html).trigger('cancelbut'); }); $('html').on('keydown.' + elemClass + 'Event', function(event) { if (event.keyCode == 27) { popModalClose(); } }); } return elemObj; }, hide : function() { popModalClose(); } }; function getPlacement() { if (_options.inline) { var eLeft = elem.position().left; var eTop = elem.position().top; } else { var eLeft = elem.offset().left; var eTop = elem.offset().top; } var offset = 10, eMLeft = parseInt(elem.css('marginLeft')), ePLeft = parseInt(elem.css('paddingLeft')), eMTop = parseInt(elem.css('marginTop')), eHeight = elem.outerHeight(), eWidth = elem.outerWidth(), eObjWidth = elemObj.outerWidth(), eObjHeight = elemObj.outerHeight(); var placement, eOffsetLeft = elem.offset().left, eOffsetRight = $(window).width() - elem.offset().left - eWidth, eOffsetTop = elem.offset().top, deltaL = eOffsetLeft - offset - eObjWidth, deltaBL = eWidth + eOffsetLeft - eObjWidth, deltaR = eOffsetRight - offset - eObjWidth, deltaBR = eWidth + eOffsetRight - eObjWidth, deltaCL = eWidth / 2 + eOffsetLeft - eObjWidth / 2, deltaCR = eWidth / 2 + eOffsetRight - eObjWidth / 2, deltaC = Math.min(deltaCR, deltaCL), deltaCT = eOffsetTop - eObjHeight / 2; function optimalPosition(current) { var optimal; var maxDelta = Math.max(deltaBL, deltaBR, deltaC); if (isCurrentFits(current)) { optimal = current; } else if (deltaBR > 0 && deltaBR == maxDelta) { optimal = bl; } else if (deltaBL > 0 && deltaBL == maxDelta) { optimal = br; } else if (deltaC > 0 && deltaC == maxDelta) { optimal = bc; } else { optimal = current; } return optimal; } function isCurrentFits(current) { return current == bl ? deltaBR > 0 : current == br ? deltaBL > 0 : deltaC > 0; } if ((/^bottom/).test(_options.placement)) { placement = optimalPosition(_options.placement); } else if ((/^left/).test(_options.placement)) { if (deltaL > 0) { if (_options.placement == lc && deltaCT > 0) { placement = lc; } else { placement = lt; } } else { placement = optimalPosition(bl); } } else if ((/^right/).test(_options.placement)) { if (deltaR > 0) { if (_options.placement == rc && deltaCT > 0) { placement = rc; } else { placement = rt; } } else { placement = optimalPosition(br); } } elemObj.removeAttr('class').addClass(elemClass + ' animated ' + placement); switch (placement){ case (bl): elemObj.css({ top: eTop + eMTop + eHeight + offset + 'px', left: eLeft + eMLeft + 'px' }).addClass(effectIn + 'Bottom'); break; case (br): elemObj.css({ top: eTop + eMTop + eHeight + offset + 'px', left: eLeft + eMLeft + eWidth - eObjWidth + 'px' }).addClass(effectIn + 'Bottom'); break; case (bc): elemObj.css({ top: eTop + eMTop + eHeight + offset + 'px', left: eLeft + eMLeft + (eWidth - eObjWidth) / 2 + 'px' }).addClass(effectIn + 'Bottom'); break; case (lt): elemObj.css({ top: eTop + eMTop + 'px', left: eLeft + eMLeft - eObjWidth - offset + 'px' }).addClass(effectIn + 'Left'); break; case (rt): elemObj.css({ top: eTop + eMTop + 'px', left: eLeft + eMLeft + eWidth + offset + 'px' }).addClass(effectIn + 'Right'); break; case (lc): elemObj.css({ top: eTop + eMTop + eHeight / 2 - eObjHeight / 2 + 'px', left: eLeft + eMLeft - eObjWidth - offset + 'px' }).addClass(effectIn + 'Left'); break; case (rc): elemObj.css({ top: eTop + eMTop + eHeight / 2 - eObjHeight / 2 + 'px', left: eLeft + eMLeft + eWidth + offset + 'px' }).addClass(effectIn + 'Right'); break; } } function popModalClose() { elemObj = $('.' + elemClass); if (elemObj.length) { reverseEffect(); getAnimTime(); setTimeout(function () { $('.' + elemClass + '_source').replaceWith($('.' + elemClass + '_content').children()); elemObj.remove(); $('html.' + elemClass + 'Open').off('.' + elemClass + 'Event').removeClass(elemClass + 'Open'); }, animTime); } } function getAnimTime() { if (!animTime) { animTime = elemObj.css('animationDuration'); if (animTime !== undefined) { animTime = animTime.replace('s', '') * 1000; } else { animTime = 0; } } } function reverseEffect() { var animClassOld = elemObj.attr('class'), animClassNew = animClassOld.replace(effectIn, effectOut); elemObj.removeClass(animClassOld).addClass(animClassNew); } if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } }; $('* [data-popmodal-bind]').bind('click', function() { var elemBind = $(this).attr('data-popmodal-bind'); var params = {html: $(elemBind)}; if ($(this).attr('data-placement') !== undefined) { params['placement'] = $(this).attr('data-placement'); } if ($(this).attr('data-showclose-but') !== undefined) { params['showCloseBut'] = (/^true$/i).test($(this).attr('data-showclose-but')); } if ($(this).attr('data-overflowcontent') !== undefined) { params['overflowContent'] = (/^false$/i).test($(this).attr('data-overflowcontent')); } if ($(this).attr('data-ondocumentclick-close') !== undefined) { params['onDocumentClickClose'] = (/^true$/i).test($(this).attr('data-ondocumentclick-close')); } if ($(this).attr('data-ondocumentclick-close-prevent') !== undefined) { params['onDocumentClickClosePrevent'] = $(this).attr('data-ondocumentclick-close-prevent'); } if ($(this).attr('data-inline') !== undefined) { params['inline'] = (/^true$/i).test($(this).attr('data-inline')); } if ($(this).attr('data-asmenu') !== undefined) { params['asMenu'] = (/^false$/i).test($(this).attr('data-asmenu')); } if ($(this).attr('data-beforeloading-content') !== undefined) { params['beforeLoadingContent'] = $(this).attr('data-beforeloading-content'); } $(this).popModal(params); }); $.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; })(jQuery); /* notifyModal */ (function($) { $.fn.notifyModal = function(method) { var elem = $(this), elemObj, elemClass = 'notifyModal', onTopClass = '', _options, animTime; var methods = { init : function(params) { var _defaults = { duration: 2500, placement: 'center', type: 'notify', overlay : true, onClose: function() {} }; _options = $.extend(_defaults, params); if (_options.overlay) { onTopClass = 'overlay'; } $('.' + elemClass).remove(); var notifyContainer = $('<div class="' + elemClass + ' ' + _options.placement + ' ' + onTopClass + ' ' + _options.type + '"></div>'); var notifyContent = $('<div class="' + elemClass + '_content"></div>'); var closeBut = $('<button type="button" class="close">&times;</button>'); if (elem[0] === undefined) { elem = elem['selector']; } else { elem = elem[0].innerHTML; } notifyContent.append(closeBut, elem); notifyContainer.append(notifyContent); $('body').append(notifyContainer); elemObj = $('.' + elemClass); getAnimTime(); elemObj.addClass('open'); elemObj.click(function() { notifyModalClose(); }); if (_options.duration != -1) { notifDur = setTimeout(notifyModalClose, _options.duration); } }, hide : function() { notifyModalClose(); } }; function notifyModalClose() { var elemObj = $('.' + elemClass); elemObj.removeClass('open'); setTimeout(function() { elemObj.remove(); if (_options.duration != -1) { clearTimeout(notifDur); } if (_options.onClose && $.isFunction(_options.onClose)) { _options.onClose(); } }, animTime); } function getAnimTime() { if (!animTime) { animTime = elemObj.css('transitionDuration'); if (animTime !== undefined) { animTime = animTime.replace('s', '') * 1000; } else { animTime = 0; } } } $('html').keydown(function(event) { if (event.keyCode == 27) { notifyModalClose(); } }); if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } }; $('* [data-notifymodal-bind]').bind('click', function() { var elemBind = $(this).attr('data-notifymodal-bind'); var params = {}; if ($(this).attr('data-duration') !== undefined) { params['duration'] = parseInt($(this).attr('data-duration')); } if ($(this).attr('data-placement') !== undefined) { params['placement'] = $(this).attr('data-placement'); } if ($(this).attr('data-ontop') !== undefined) { params['onTop'] = (/^true$/i).test($(this).attr('data-ontop')); } $(elemBind).notifyModal(params); }); })(jQuery); /* hintModal */ (function($) { $.fn.hintModal = function(method){ $('.hintModal').off(); var methods = { init : function() { $(this).on('mouseenter', function() { var elem = $(this).find('> .hintModal_container'); if (elem[0].textContent.length > 1) { elem.addClass('animated fadeInBottom'); getPlacement($(this), elem); } }); $(this).on('mouseleave', function() { var elem = $(this).find('> .hintModal_container'); if (elem[0].textContent.length > 1) { elem.removeClass('animated fadeInBottom'); } }); function getPlacement(elemObj, elem) { var placementDefault, classDefault = elemObj.attr('class'), eObjWidth = elemObj.outerWidth(), eWidth = elem.outerWidth(), eOffsetLeft = elemObj.offset().left, eOffsetRight = $(window).width() - elemObj.offset().left - eObjWidth, deltaBL = eObjWidth + eOffsetLeft - eWidth, deltaBR = eObjWidth + eOffsetRight - eWidth, deltaCL = eObjWidth / 2 + eOffsetLeft - eWidth / 2, deltaCR = eObjWidth / 2 + eOffsetRight - eWidth / 2, deltaC = Math.min(deltaCR, deltaCL), bl = 'bottomLeft', bc = 'bottomCenter', br = 'bottomRight'; if (elemObj.hasClass(bl)) { placementDefault = bl; } else if (elemObj.hasClass(bc)) { placementDefault = bc; } else if (elemObj.hasClass(br)) { placementDefault = br; } else { placementDefault = bl; } if (elemObj.data('placement') === undefined) { elemObj.data('placement', placementDefault); } function optimalPosition(current) { var optimal; var maxDelta = Math.max(deltaBL, deltaBR, deltaC); if (isCurrentFits(current)) { optimal = current; } else if (deltaBR > 0 && deltaBR == maxDelta) { optimal = bl; } else if (deltaBL > 0 && deltaBL == maxDelta) { optimal = br; } else if (deltaC > 0 && deltaC == maxDelta) { optimal = bc; } else { optimal = current; } return optimal; } function isCurrentFits(current) { return current == bl ? deltaBR > 0 : current == br ? deltaBL > 0 : deltaC > 0; } elemObj.removeAttr('class').addClass(classDefault + ' ' + optimalPosition(elemObj.data('placement'))); } } }; if (methods[method]) { return methods[method].apply( this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } }; $('.hintModal').hintModal(); document.addEventListener("DOMNodeInserted", function(event) { if ($(event.target).hasClass('hintModal')) { $('.hintModal').hintModal(); } }, false); })(jQuery); /* dialogModal */ (function($) { $.fn.dialogModal = function(method) { var elem = $(this), elemObj, elemClass = 'dialogModal', prevBut = 'dialogPrev', nextBut = 'dialogNext', _options, animTime; var methods = { init : function(params) { var _defaults = { topOffset: 0, top: '10%', type: '', onOkBut: function() {return true;}, onCancelBut: function() {}, onLoad: function() {}, onClose: function() {}, onChange: function() {} }; _options = $.extend(_defaults, params); $('html.' + elemClass + 'Open').off('.' + elemClass + 'Event').removeClass(elemClass + 'Open'); $('.' + elemClass + ' .' + prevBut + ', .' + elemClass + ' .' + nextBut).off('click'); $('.' + elemClass).remove(); if (_options.type == '') { _options.top = 0; } else { _options.top = 'calc(' + _options.top + ' + 60px)'; } var currentDialog = 0, maxDialog = elem.length - 1, dialogMain = $('<div class="' + elemClass + ' ' + _options.type + '" style="top:' + _options.topOffset + 'px"></div>'), dialogContainer = $('<div class="' + elemClass + '_container" style="top:' + _options.top + '"></div>'), dialogTop = $('<div class="' + elemClass + '_top animated"></div>'), dialogHeader = $('<div class="' + elemClass + '_header"></div>'), dialogBody = $('<div class="' + elemClass + '_body animated"></div>'), dialogCloseBut = $('<button type="button" class="close">&times;</button>'); dialogMain.append(dialogContainer); dialogContainer.append(dialogTop, dialogBody); dialogTop.append(dialogHeader); dialogHeader.append(dialogCloseBut); dialogBody.append(elem[currentDialog].innerHTML); if (maxDialog > 0) { dialogHeader.append($('<div class="' + nextBut + '">&rsaquo;</div><div class="' + prevBut + ' notactive">&lsaquo;</div>')); } dialogHeader.append('<span>' + elem.find('.' + elemClass + '_header')[currentDialog].innerHTML + '</span>'); $('body').append(dialogMain).addClass(elemClass + 'Open'); if (_options.type == '') { var getScrollBarWidth = dialogMain.outerWidth() - dialogMain[0].scrollWidth; dialogTop.css({right:getScrollBarWidth + 'px'}); } elemObj = $('.' + elemClass); getAnimTime(); if (_options.onLoad && $.isFunction(_options.onLoad)) { _options.onLoad(elemObj, currentDialog + 1); } elem.trigger('load', {el: elemObj, current: currentDialog + 1}); elemObj.on('destroyed', function() { if (_options.onClose && $.isFunction(_options.onClose)) { _options.onClose(); } elem.trigger('close'); }); elemObj.addClass('open'); setTimeout(function() { if (_options.type != '') { dialogContainer.css({opacity:1}); } dialogTop.addClass('fadeInTopBig'); dialogBody.addClass('fadeInTopBig'); }, animTime + 100); bindFooterButtons(); function bindFooterButtons() { elemObj.find('[data-dialogmodal-but="close"]').on('click', function() { dialogModalClose(); $(this).off('click'); }); elemObj.find('[data-dialogmodal-but="ok"]').on('click', function(event) { var ok; if (_options.onOkBut && $.isFunction(_options.onOkBut)) { ok = _options.onOkBut(event); } if (ok !== false) { dialogModalClose(); } $(this).off('click'); elem.trigger('okbut'); }); elemObj.find('[data-dialogmodal-but="cancel"]').on('click', function() { if (_options.onCancelBut && $.isFunction(_options.onCancelBut)) { _options.onCancelBut(); } dialogModalClose(); $(this).off('click'); elem.trigger('cancelbut'); }); elemObj.find('[data-dialogmodal-but="prev"]').on('click', function() { elemObj.find('.' + prevBut).click(); }); elemObj.find('[data-dialogmodal-but="next"]').on('click', function() { elemObj.find('.' + nextBut).click(); }); } elemObj.find('.' + prevBut).on('click', function() { if (currentDialog > 0) { --currentDialog; if (currentDialog < maxDialog) { elemObj.find('.' + nextBut).removeClass('notactive'); } if (currentDialog === 0) { elemObj.find('.' + prevBut).addClass('notactive'); } changeDialogContent(); } }); elemObj.find('.' + nextBut).on('click', function() { if (currentDialog < maxDialog) { ++currentDialog; if (currentDialog > 0) { elemObj.find('.' + prevBut).removeClass('notactive'); } if (currentDialog == maxDialog) { elemObj.find('.' + nextBut).addClass('notactive'); } changeDialogContent(); } }); function changeDialogContent() { dialogBody.empty().append(elem[currentDialog].innerHTML); dialogHeader.find('span').html(elem.find('.' + elemClass + '_header')[currentDialog].innerHTML); bindFooterButtons(); if (_options.onChange && $.isFunction(_options.onChange)) { _options.onChange(elemObj, currentDialog + 1); } elem.trigger('change', {el: elemObj, current: currentDialog + 1}); } elemObj.find('.close').on('click', function() { dialogModalClose(); $(this).off('click'); }); $('html').on('keydown.' + elemClass + 'Event', function(event) { if (event.keyCode == 27) { dialogModalClose(); } else if (event.keyCode == 37) { elemObj.find('.' + prevBut).click(); } else if (event.keyCode == 39) { elemObj.find('.' + nextBut).click(); } }); }, hide : function() { dialogModalClose(); } }; function dialogModalClose() { var elemObj = $('.' + elemClass); elemObj.removeClass('open'); setTimeout(function() { elemObj.remove(); $('body').removeClass(elemClass + 'Open').css({paddingRight:''}); $('html.' + elemClass + 'Open').off('.' + elemClass + 'Event').removeClass(elemClass + 'Open'); elemObj.find('.' + prevBut).off('click'); elemObj.find('.' + nextBut).off('click'); }, animTime); } function getAnimTime() { if (!animTime) { animTime = elemObj.css('transitionDuration'); if (animTime !== undefined) { animTime = animTime.replace('s', '') * 1000; } else { animTime = 0; } } } if (methods[method]) { return methods[method].apply( this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply( this, arguments ); } }; $('* [data-dialogmodal-bind]').bind('click', function() { var elemBind = $(this).attr('data-dialogmodal-bind'); var params = {}; if ($(this).attr('data-topoffset') !== undefined) { params['topOffset'] = $(this).attr('data-topoffset'); } if ($(this).attr('data-top') !== undefined) { params['top'] = $(this).attr('data-top'); } if ($(this).attr('data-topoffset') !== undefined) { params['type'] = $(this).attr('data-type'); } $(elemBind).dialogModal(params); }); $.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; })(jQuery); /* titleModal */ (function($) { $.fn.titleModal = function(method) { $('.titleModal').off(); var methods = { init : function() { var elem, elemObj, elemClass = 'titleModal', getElem = $('.' + elemClass), effectIn = 'fadeIn', effectOut = 'fadeOut'; getElem.on('mouseenter', function() { elem = $(this); var titleAttr; if (elem.attr('title') !== undefined || elem.css('textOverflow') == 'ellipsis' || elem.css('textOverflow') == 'clip') { if (elem.attr('title') !== undefined) { titleAttr = elem.attr('title'); } else { titleAttr = elem.text(); } elem.removeAttr('title'); elem.attr('data-title', titleAttr); var titleModal = $('<div class="' + elemClass + '_container animated"></div>'); elemObj = $('.' + elemClass + '_container'); var placement = elem.attr('data-placement'); if (placement === undefined) { placement = 'bottom'; } if (elemObj) { elemObj.remove(); } elem.after(titleModal.append(titleAttr)); //elem.append getPlacement(placement); } }); getElem.on('mouseleave', function() { elem = $(this); var titleAttr; if (elem.attr('data-title') !== undefined){ titleAttr = elem.attr('data-title'); elem.removeAttr('data-title'); elem.attr('title', titleAttr); reverseEffect(); elemObj.remove(); } }); function getPlacement(placement) { elemObj = $('.' + elemClass + '_container'); var eLeft = elem.position().left, eTop = elem.position().top, eMLeft = elem.css('marginLeft'), eMTop = elem.css('marginTop'), eHeight = elem.outerHeight(), eWidth = elem.outerWidth(), eObjWidth = elemObj.outerWidth(), eObjHeight = elemObj.outerHeight(); switch (placement) { case 'bottom': elemObj.css({ top: eTop + parseInt(eMTop) + eHeight - 5 + 'px', left: eLeft + parseInt(eMLeft) + (eWidth - eObjWidth) / 2 + 'px' }).addClass(effectIn + 'Bottom'); break; case 'top': elemObj.css({ top: eTop + parseInt(eMTop) - eObjHeight + 'px', left: eLeft + parseInt(eMLeft) + (eWidth - eObjWidth) / 2 + 'px' }).addClass('top ' + effectIn + 'Top'); break; case 'left': elemObj.css({ top: eTop + parseInt(eMTop) + eHeight / 2 - eObjHeight / 2 + 'px', left: eLeft + parseInt(eMLeft) - eObjWidth - 10 + 'px' }).addClass('left ' + effectIn + 'Left'); break; case 'right': elemObj.css({ top: eTop + parseInt(eMTop) + eHeight / 2 - eObjHeight / 2 + 'px', left: eLeft + parseInt(eMLeft) + eWidth + 10 + 'px' }).addClass('right ' + effectIn + 'Right'); break; } } function reverseEffect() { var animClassOld = elemObj.attr('class'), animClassNew = animClassOld.replace(effectIn, effectOut); elemObj.removeClass(animClassOld).addClass(animClassNew); } } }; if (methods[method]) { return methods[method].apply( this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply( this, arguments ); } }; $('.titleModal').titleModal(); document.addEventListener("DOMNodeInserted", function(event) { if ($(event.target).hasClass('titleModal')) { $('.titleModal').titleModal(); } }, false); })(jQuery); /* confirmModal */ (function($) { $.fn.confirmModal = function(method) { var elem = $(this), elemObj, elemClass = 'confirmModal', _options, animTime; var methods = { init : function(params) { var _defaults = { topOffset: 0, onOkBut: function() {return true;}, onCancelBut: function() {}, onLoad: function() {}, onClose: function() {} }; _options = $.extend(_defaults, params); $('html.' + elemClass + 'Open').off('.' + elemClass + 'Event').removeClass(elemClass + 'Open'); $('.' + elemClass).remove(); var dialogMain = $('<div class="' + elemClass + '" style="top:' + _options.topOffset + 'px"></div>'), dialogBody = $('<div class="' + elemClass + '_body animated"></div>'); dialogMain.append(dialogBody); dialogBody.append(elem[0].innerHTML); $('body').append(dialogMain).addClass(elemClass + 'Open'); elemObj = $('.' + elemClass); getAnimTime(); if (_options.onLoad && $.isFunction(_options.onLoad)) { _options.onLoad(); } elemObj.on('destroyed', function() { if (_options.onClose && $.isFunction(_options.onClose)) { _options.onClose(); } }); elemObj.addClass('open'); setTimeout(function() { dialogBody.addClass('fadeInTopBig'); setTimeout(function() { dialogBody.removeClass('fadeInTopBig').addClass('open'); }, animTime + 100); }, animTime + 100); bindFooterButtons(); function bindFooterButtons() { elemObj.find('[data-confirmmodal-but="close"]').on('click', function() { confirmModalClose(); $(this).off('click'); }); elemObj.find('[data-confirmmodal-but="ok"]').on('click', function(event) { var ok; if (_options.onOkBut && $.isFunction(_options.onOkBut)) { ok = _options.onOkBut(event); } if (ok !== false) { confirmModalClose(); } $(this).off('click'); }); elemObj.find('[data-confirmmodal-but="cancel"]').on('click', function() { if (_options.onCancelBut && $.isFunction(_options.onCancelBut)) { _options.onCancelBut(); } confirmModalClose(); $(this).off('click'); }); function needConfirm() { dialogBody.addClass('needConfirm'); setTimeout(function() { dialogBody.removeClass('needConfirm'); }, animTime + 100); } elemObj.on('click', function(event) { var target = $(event.target); if (!target.parents().addBack().is(dialogBody)) { needConfirm(); } }); $('html').on('keydown.' + elemClass + 'Event', function(event) { if (event.keyCode == 27) { needConfirm(); } }); } }, hide : function() { confirmModalClose(); } }; function confirmModalClose() { var elemObj = $('.' + elemClass); elemObj.removeClass('open'); setTimeout(function() { elemObj.remove(); $('body').removeClass(elemClass + 'Open').css({paddingRight:''}); $('html.' + elemClass + 'Open').off('.' + elemClass + 'Event').removeClass(elemClass + 'Open'); }, animTime); } function getAnimTime() { if (!animTime) { animTime = elemObj.css('transitionDuration'); if (animTime !== undefined) { animTime = animTime.replace('s', '') * 1000; } else { animTime = 0; } } } if (methods[method]) { return methods[method].apply( this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply( this, arguments ); } }; $('* [data-confirmmodal-bind]').bind('click', function() { var elemBind = $(this).attr('data-confirmmodal-bind'); var params = {}; if ($(this).attr('data-topoffset') !== undefined) { params['topOffset'] = $(this).attr('data-topoffset'); } $(elemBind).confirmModal(params); }); $.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; })(jQuery); });
{ "content_hash": "525922d235079b3d8994de42e714cba3", "timestamp": "", "source": "github", "line_count": 1130, "max_line_length": 150, "avg_line_length": 28.94070796460177, "alnum_prop": 0.564810567837813, "repo_name": "voltrobe/vebmate", "id": "6444e9d7c3c3e3020a1bf614591d62091b5065d5", "size": "32703", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pages/popup/popModal.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2221912" }, { "name": "HTML", "bytes": "6796596" }, { "name": "Java", "bytes": "27519" }, { "name": "JavaScript", "bytes": "7409419" }, { "name": "Makefile", "bytes": "285" }, { "name": "PHP", "bytes": "170276" }, { "name": "Ruby", "bytes": "3879" }, { "name": "Shell", "bytes": "680" } ], "symlink_target": "" }
package com.example.zhiliangmin.myweather.db; import org.litepal.crud.DataSupport; /** * Created by zhiliangmin on 2017/2/16. */ public class County extends DataSupport { private int id; private String countyName; private String weatherId; private int cityId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountyName() { return countyName; } public void setCountyName(String countyName) { this.countyName = countyName; } public String getWeatherId() { return weatherId; } public void setWeatherId(String weatherId) { this.weatherId = weatherId; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }
{ "content_hash": "4b6cd644c7f064f03a7f2d650767dad7", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 50, "avg_line_length": 18.630434782608695, "alnum_prop": 0.6219369894982497, "repo_name": "zhiliangmin/MyWeather", "id": "a4533853d09d9dab6a35e0052869c0165b594c1a", "size": "857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/example/zhiliangmin/myweather/db/County.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "33213" } ], "symlink_target": "" }
div.dt-button-info { position: fixed; top: 50%; left: 50%; width: 400px; margin-top: -100px; margin-left: -200px; background-color: white; border: 2px solid #111; box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.3); border-radius: 3px; text-align: center; z-index: 21; } div.dt-button-info h2 { padding: 0.5em; margin: 0; font-weight: normal; border-bottom: 1px solid #ddd; background-color: #f3f3f3; } div.dt-button-info > div { padding: 1em; } button.dt-button, div.dt-button, a.dt-button { position: relative; display: inline-block; box-sizing: border-box; margin-right: 0.333em; padding: 0.5em 1em; border: 1px solid #999; border-radius: 2px; cursor: pointer; font-size: 0.88em; color: black; white-space: nowrap; overflow: hidden; background-color: #e9e9e9; /* Fallback */ background-image: -webkit-linear-gradient(top, white 0%, #e9e9e9 100%); /* Chrome 10+, Saf5.1+, iOS 5+ */ /* FF3.6 */ /* IE10 */ /* Opera 11.10+ */ background-image: linear-gradient(top, white 0%, #e9e9e9 100%); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='white', EndColorStr='#e9e9e9'); -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; text-decoration: none; outline: none; } button.dt-button.disabled, div.dt-button.disabled, a.dt-button.disabled { color: #999; border: 1px solid #d0d0d0; cursor: default; background-color: #f9f9f9; /* Fallback */ background-image: -webkit-linear-gradient(top, #ffffff 0%, #f9f9f9 100%); /* Chrome 10+, Saf5.1+, iOS 5+ */ /* FF3.6 */ /* IE10 */ /* Opera 11.10+ */ background-image: linear-gradient(top, #ffffff 0%, #f9f9f9 100%); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#ffffff', EndColorStr='#f9f9f9'); } button.dt-button:active:not(.disabled), button.dt-button.active:not(.disabled), div.dt-button:active:not(.disabled), div.dt-button.active:not(.disabled), a.dt-button:active:not(.disabled), a.dt-button.active:not(.disabled) { background-color: #e2e2e2; /* Fallback */ background-image: -webkit-linear-gradient(top, #f3f3f3 0%, #e2e2e2 100%); /* Chrome 10+, Saf5.1+, iOS 5+ */ /* FF3.6 */ /* IE10 */ /* Opera 11.10+ */ background-image: linear-gradient(top, #f3f3f3 0%, #e2e2e2 100%); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#f3f3f3', EndColorStr='#e2e2e2'); box-shadow: inset 1px 1px 3px #999999; } button.dt-button:active:not(.disabled):hover:not(.disabled), button.dt-button.active:not(.disabled):hover:not(.disabled), div.dt-button:active:not(.disabled):hover:not(.disabled), div.dt-button.active:not(.disabled):hover:not(.disabled), a.dt-button:active:not(.disabled):hover:not(.disabled), a.dt-button.active:not(.disabled):hover:not(.disabled) { box-shadow: inset 1px 1px 3px #999999; background-color: #cccccc; /* Fallback */ background-image: -webkit-linear-gradient(top, #eaeaea 0%, #cccccc 100%); /* Chrome 10+, Saf5.1+, iOS 5+ */ /* FF3.6 */ /* IE10 */ /* Opera 11.10+ */ background-image: linear-gradient(top, #eaeaea 0%, #cccccc 100%); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#eaeaea', EndColorStr='#cccccc'); } button.dt-button:hover, div.dt-button:hover, a.dt-button:hover { text-decoration: none; } button.dt-button:hover:not(.disabled), div.dt-button:hover:not(.disabled), a.dt-button:hover:not(.disabled) { border: 1px solid #666; background-color: #e0e0e0; /* Fallback */ background-image: -webkit-linear-gradient(top, #f9f9f9 0%, #e0e0e0 100%); /* Chrome 10+, Saf5.1+, iOS 5+ */ /* FF3.6 */ /* IE10 */ /* Opera 11.10+ */ background-image: linear-gradient(top, #f9f9f9 0%, #e0e0e0 100%); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#f9f9f9', EndColorStr='#e0e0e0'); } button.dt-button:focus:not(.disabled), div.dt-button:focus:not(.disabled), a.dt-button:focus:not(.disabled) { border: 1px solid #426c9e; text-shadow: 0 1px 0 #c4def1; outline: none; background-color: #79ace9; /* Fallback */ background-image: -webkit-linear-gradient(top, #bddef4 0%, #79ace9 100%); /* Chrome 10+, Saf5.1+, iOS 5+ */ /* FF3.6 */ /* IE10 */ /* Opera 11.10+ */ background-image: linear-gradient(top, #bddef4 0%, #79ace9 100%); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#bddef4', EndColorStr='#79ace9'); } .dt-button embed { outline: none; } div.dt-buttons { position: relative; float: left; } div.dt-buttons.buttons-right { float: right; } div.dt-button-collection { position: absolute; top: 0; left: 0; width: 150px; margin-top: 3px; padding: 8px 8px 4px 8px; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.4); background-color: white; overflow: hidden; z-index: 2002; border-radius: 5px; box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3); z-index: 2002; -webkit-column-gap: 8px; -moz-column-gap: 8px; -ms-column-gap: 8px; -o-column-gap: 8px; column-gap: 8px; } div.dt-button-collection button.dt-button, div.dt-button-collection div.dt-button, div.dt-button-collection a.dt-button { position: relative; left: 0; right: 0; display: block; float: none; margin-bottom: 4px; margin-right: 0; } div.dt-button-collection button.dt-button:active:not(.disabled), div.dt-button-collection button.dt-button.active:not(.disabled), div.dt-button-collection div.dt-button:active:not(.disabled), div.dt-button-collection div.dt-button.active:not(.disabled), div.dt-button-collection a.dt-button:active:not(.disabled), div.dt-button-collection a.dt-button.active:not(.disabled) { background-color: #dadada; /* Fallback */ background-image: -webkit-linear-gradient(top, #f0f0f0 0%, #dadada 100%); /* Chrome 10+, Saf5.1+, iOS 5+ */ /* FF3.6 */ /* IE10 */ /* Opera 11.10+ */ background-image: linear-gradient(top, #f0f0f0 0%, #dadada 100%); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#f0f0f0', EndColorStr='#dadada'); box-shadow: inset 1px 1px 3px #666; } div.dt-button-collection.fixed { position: fixed; top: 50%; left: 50%; margin-left: -75px; border-radius: 0; } div.dt-button-collection.fixed.two-column { margin-left: -150px; } div.dt-button-collection.fixed.three-column { margin-left: -225px; } div.dt-button-collection.fixed.four-column { margin-left: -300px; } div.dt-button-collection > * { -webkit-column-break-inside: avoid; page-break-inside: avoid; break-inside: avoid; } div.dt-button-collection.two-column { width: 300px; padding-bottom: 1px; -webkit-column-count: 2; -moz-column-count: 2; -ms-column-count: 2; -o-column-count: 2; column-count: 2; } div.dt-button-collection.three-column { width: 450px; padding-bottom: 1px; -webkit-column-count: 3; -moz-column-count: 3; -ms-column-count: 3; -o-column-count: 3; column-count: 3; } div.dt-button-collection.four-column { width: 600px; padding-bottom: 1px; -webkit-column-count: 4; -moz-column-count: 4; -ms-column-count: 4; -o-column-count: 4; column-count: 4; } div.dt-button-background { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.7); /* Fallback */ /* IE10 Consumer Preview */ /* Firefox */ /* Opera */ background: -webkit-gradient(radial, center center, 0, center center, 497, color-stop(0, rgba(0, 0, 0, 0.3)), color-stop(1, rgba(0, 0, 0, 0.7))); /* Webkit (Safari/Chrome 10) */ background: -webkit-radial-gradient(center, ellipse farthest-corner, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 100%); /* Webkit (Chrome 11+) */ background: -webkit-radial-gradient(ellipse farthest-corner at center, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 100%); background: radial-gradient(ellipse farthest-corner at center, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.7) 100%); /* W3C Markup, IE10 Release Preview */ z-index: 2001; } @media screen and (max-width: 640px) { div.dt-buttons { float: none !important; text-align: center; } } /*# sourceMappingURL=admin-buttons.css.map */
{ "content_hash": "7338eb75c6f4ac509b80b3af0e8e0b00", "timestamp": "", "source": "github", "line_count": 297, "max_line_length": 147, "avg_line_length": 27.646464646464647, "alnum_prop": 0.6733649981731823, "repo_name": "MAbarri/Laravel_Costimazable_Blog", "id": "cc5697f5b2ea8641b689969f477dcdfb5b22c02c", "size": "8211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/css/admin-buttons.css", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "CSS", "bytes": "62" }, { "name": "HTML", "bytes": "53192" }, { "name": "JavaScript", "bytes": "82068" }, { "name": "PHP", "bytes": "241203" } ], "symlink_target": "" }
ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
{ "content_hash": "6e99a978baa3ed5ec7ec5d5801f03b8b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.076923076923077, "alnum_prop": 0.6779661016949152, "repo_name": "mdoering/backbone", "id": "e6bfc6c612852a8c4718537ecdbe072d3bd419b9", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Alonsoa/Alonsoa warscewiczii/Alonsoa warscewiczii warscewiczii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package example.plugins; import system.plugins.MausGroupContentInterface; import system.processor.MausPage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.*; /** * Created by Fabi on 3/4/2015. */ public class MausGroupMetaWordCloud implements MausGroupContentInterface { private String filename = "maus/result/"; private Map<String,Integer> words = new HashMap<>(); private int maxWords = 100; private int maxUpperCount = 20; public MausGroupMetaWordCloud(String seed) { if(seed != null && !seed.isEmpty()) { this.filename += seed + "/"; } this.filename += "meta-wordcloud.csv"; } @Override public synchronized void handle(MausPage page) { Map<String,Integer> value = ((MausPageContentWordCloud)(page.getContent("wordcloud-seed"))).getWords(); for(Map.Entry<String,Integer> entry : value.entrySet()) { if(this.words.containsKey(entry.getKey())) { this.words.put(entry.getKey(), this.words.get(entry.getKey()) + entry.getValue()); } else { this.words.put(entry.getKey(), entry.getValue()); } } } @Override public void save() { File f = new File(filename); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } List<String> candidates = sortedValues(this.words); int minValue = this.words.get(candidates.get(candidates.size()-1)); StringBuilder builder = new StringBuilder(); for(String s : candidates) { int toValue = this.words.get(s) / minValue; toValue = toValue > maxUpperCount ? maxUpperCount : toValue; for(int i=0;i<toValue;i++) { builder.append(s).append(" "); } builder.append("\n"); } try { BufferedWriter fout = new BufferedWriter(new FileWriter(f)); fout.write(builder.toString()); fout.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void setRootFolder() { } @Override public String getRootFolder() { return null; } @Override public String getFilePath() { return null; } private List<String> sortedValues(Map<String,Integer> input) { List<Map.Entry<String,Integer>> value = new ArrayList<>(input.entrySet()); Collections.sort(value, (a, b) -> b.getValue().compareTo(a.getValue())); List<String> result = new ArrayList<>(); int count = 0; for(Map.Entry<String,Integer> e : value) { result.add(e.getKey()); count++; if(count >= maxWords) { break; } } return result; } }
{ "content_hash": "16f9c98671c5db62e1ede82ce0a8fbc1", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 111, "avg_line_length": 27.850467289719628, "alnum_prop": 0.5526845637583893, "repo_name": "WirrWar2850/mauscrawler", "id": "6d3c506a6ac168bd16bbf80bc30a520374bb1b25", "size": "2980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/example/plugins/MausGroupMetaWordCloud.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "96012" } ], "symlink_target": "" }
package com.bradmcevoy.http; import com.bradmcevoy.http.exceptions.BadRequestException; import com.bradmcevoy.http.exceptions.ConflictException; import com.bradmcevoy.http.exceptions.NotAuthorizedException; import com.bradmcevoy.http.http11.CustomPostHandler; import com.bradmcevoy.http.http11.Http11ResponseHandler; import com.bradmcevoy.http.http11.auth.ExpiredNonceRemover; import com.bradmcevoy.http.http11.auth.Nonce; import com.bradmcevoy.http.http11.auth.NonceProvider; import com.bradmcevoy.http.http11.auth.SimpleMemoryNonceProvider; import com.bradmcevoy.http.webdav.DefaultWebDavResponseHandler; import com.bradmcevoy.http.webdav.WebDavResponseHandler; import com.bradmcevoy.property.PropertyAuthoriser; import com.bradmcevoy.property.PropertyHandler; import com.ettrema.common.Stoppable; import com.ettrema.event.EventManager; import com.ettrema.event.EventManagerImpl; import com.ettrema.event.RequestEvent; import com.ettrema.event.ResponseEvent; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Milton's main class. All the servlets and stuff is just fluff, this is where * stuff really starts to happen * * * @author brad */ public class HttpManager { private static final Logger log = LoggerFactory.getLogger(HttpManager.class); public static String decodeUrl(String s) { return Utils.decodePath(s); } private static final ThreadLocal<Request> tlRequest = new ThreadLocal<Request>(); private static final ThreadLocal<Response> tlResponse = new ThreadLocal<Response>(); public static Request request() { return tlRequest.get(); } public static Response response() { return tlResponse.get(); } private final ProtocolHandlers handlers; private Map<String, Handler> methodHandlers = new ConcurrentHashMap<String, Handler>(); List<Filter> filters = new ArrayList<Filter>(); List<EventListener> eventListeners = new ArrayList<EventListener>(); protected final ResourceFactory resourceFactory; protected final Http11ResponseHandler responseHandler; private SessionAuthenticationHandler sessionAuthenticationHandler; private PropertyAuthoriser propertyPermissionService; private EventManager eventManager = new EventManagerImpl(); private final List<Stoppable> shutdownHandlers = new CopyOnWriteArrayList<Stoppable>(); /** * Creates the manager with a DefaultResponseHandler * * @param resourceFactory */ public HttpManager(ResourceFactory resourceFactory) { if (resourceFactory == null) { throw new NullPointerException("resourceFactory cannot be null"); } this.resourceFactory = resourceFactory; Map<UUID, Nonce> nonces = new ConcurrentHashMap<UUID, Nonce>(); int nonceValiditySeconds = 60 * 60 * 24; ExpiredNonceRemover expiredNonceRemover = new ExpiredNonceRemover(nonces, nonceValiditySeconds); NonceProvider nonceProvider = new SimpleMemoryNonceProvider(nonceValiditySeconds, expiredNonceRemover, nonces); AuthenticationService authenticationService = new AuthenticationService(nonceProvider); DefaultWebDavResponseHandler webdavResponseHandler = new DefaultWebDavResponseHandler(authenticationService); this.responseHandler = webdavResponseHandler; this.handlers = new ProtocolHandlers(webdavResponseHandler, authenticationService); initHandlers(); shutdownHandlers.add(expiredNonceRemover); expiredNonceRemover.start(); } public HttpManager(ResourceFactory resourceFactory, AuthenticationService authenticationService) { if (resourceFactory == null) { throw new NullPointerException("resourceFactory cannot be null"); } this.resourceFactory = resourceFactory; DefaultWebDavResponseHandler webdavResponseHandler = new DefaultWebDavResponseHandler(authenticationService); this.responseHandler = webdavResponseHandler; this.handlers = new ProtocolHandlers(webdavResponseHandler, authenticationService); initHandlers(); } public HttpManager(ResourceFactory resourceFactory, WebDavResponseHandler responseHandler, AuthenticationService authenticationService) { if (resourceFactory == null) { throw new NullPointerException("resourceFactory cannot be null"); } this.resourceFactory = resourceFactory; this.responseHandler = responseHandler; this.handlers = new ProtocolHandlers(responseHandler, authenticationService); initHandlers(); } public HttpManager(ResourceFactory resourceFactory, WebDavResponseHandler responseHandler, ProtocolHandlers handlers) { if (resourceFactory == null) { throw new NullPointerException("resourceFactory cannot be null"); } this.resourceFactory = resourceFactory; this.responseHandler = responseHandler; this.handlers = handlers; initHandlers(); } private void initHandlers() { for (HttpExtension ext : handlers) { for (Handler h : ext.getHandlers()) { for (String m : h.getMethods()) { this.methodHandlers.put(m, h); } } } // The standard filter must always be there, its what invokes the main milton processing filters.add(createStandardFilter()); } public Handler getMethodHandler(Request.Method m) { return methodHandlers.get(m.code); } public ResourceFactory getResourceFactory() { return resourceFactory; } public SessionAuthenticationHandler getSessionAuthenticationHandler() { return sessionAuthenticationHandler; } public void setSessionAuthenticationHandler(SessionAuthenticationHandler sessionAuthenticationHandler) { this.sessionAuthenticationHandler = sessionAuthenticationHandler; } /** * @deprecated - use an AuthenticationHandler instead * * @param request * @return - if no SessionAuthenticationHandler has been set returns null. * Otherwise, calls getSessionAuthentication on it and returns the result * * */ @Deprecated public Auth getSessionAuthentication(Request request) { if (this.sessionAuthenticationHandler == null) { return null; } return this.sessionAuthenticationHandler.getSessionAuthentication(request); } public void process(Request request, Response response) { if (log.isInfoEnabled()) { log.info(request.getMethod() + " :: " + request.getAbsoluteUrl() + " - " + request.getAbsoluteUrl()); } tlRequest.set(request); tlResponse.set(response); try { fireRequestEvent(request); } catch (ConflictException ex) { responseHandler.respondConflict(null, response, request, null); } catch (BadRequestException ex) { responseHandler.respondBadRequest(null, response, request); } catch (NotAuthorizedException ex) { responseHandler.respondUnauthorised(null, response, request); } try { FilterChain chain = new FilterChain(this); chain.process(request, response); try { fireResponseEvent(request, response); } catch (ConflictException ex) { log.warn("exception thrown from event handler after response is complete", ex); } catch (BadRequestException ex) { log.warn("exception thrown from event handler after response is complete", ex); } catch (NotAuthorizedException ex) { log.warn("exception thrown from event handler after response is complete", ex); } } finally { tlRequest.remove(); tlResponse.remove(); } } protected Filter createStandardFilter() { return new StandardFilter(); } public void addFilter(int pos, Filter filter) { filters.add(pos, filter); } public void addEventListener(EventListener l) { eventListeners.add(l); } public void removeEventListener(EventListener l) { eventListeners.remove(l); } public void onProcessResourceFinish(Request request, Response response, Resource resource, long duration) { for (EventListener l : eventListeners) { l.onProcessResourceFinish(request, response, resource, duration); } } public void onProcessResourceStart(Request request, Response response, Resource resource) { for (EventListener l : eventListeners) { l.onProcessResourceStart(request, response, resource); } } public void onPost(Request request, Response response, Resource resource, Map<String, String> params, Map<String, FileItem> files) { for (EventListener l : eventListeners) { l.onPost(request, response, resource, params, files); } } public void onGet(Request request, Response response, Resource resource, Map<String, String> params) { for (EventListener l : eventListeners) { l.onGet(request, response, resource, params); } } public List<Filter> getFilters() { ArrayList<Filter> col = new ArrayList<Filter>(filters); return col; } public void setFilters(List<Filter> filters) { this.filters = filters; filters.add(createStandardFilter()); } public void setEventListeners(List<EventListener> eventListeners) { this.eventListeners = eventListeners; } public Collection<Handler> getAllHandlers() { return this.methodHandlers.values(); } public Http11ResponseHandler getResponseHandler() { return responseHandler; } public ProtocolHandlers getHandlers() { return handlers; } public PropertyAuthoriser getPropertyPermissionService() { return propertyPermissionService; } public void setPropertyPermissionService(PropertyAuthoriser propertyPermissionService) { log.trace("setPropertyPermissionService: " + propertyPermissionService.getClass().getCanonicalName()); this.propertyPermissionService = propertyPermissionService; for (Handler h : methodHandlers.values()) { if (h instanceof PropertyHandler) { PropertyHandler ph = (PropertyHandler) h; log.trace("set propertyPermissionService on: " + ph.getClass().getCanonicalName()); ph.setPermissionService(propertyPermissionService); } } } public boolean isEnableExpectContinue() { return handlers.isEnableExpectContinue(); } public void setEnableExpectContinue(boolean enableExpectContinue) { handlers.setEnableExpectContinue(enableExpectContinue); } public EventManager getEventManager() { return eventManager; } public void setEventManager(EventManager eventManager) { this.eventManager = eventManager; } private void fireRequestEvent(Request request) throws ConflictException, BadRequestException, NotAuthorizedException { if (eventManager == null) { return; } eventManager.fireEvent(new RequestEvent(request)); } private void fireResponseEvent(Request request, Response response) throws ConflictException, BadRequestException, NotAuthorizedException { if (eventManager == null) { return; } eventManager.fireEvent(new ResponseEvent(request, response)); } public List<CustomPostHandler> getCustomPostHandlers() { List<CustomPostHandler> list = new ArrayList<CustomPostHandler>(); for (HttpExtension p : this.handlers) { if (p.getCustomPostHandlers() != null) { for (CustomPostHandler h : p.getCustomPostHandlers()) { list.add(h); } } } return list; } public final void shutdown() { for (Stoppable stoppable : shutdownHandlers) { try { stoppable.stop(); } catch (Throwable e) { log.warn("Exception stopping: " + stoppable.getClass(), e); } } } }
{ "content_hash": "b643c9fade247f593005322a560f7850", "timestamp": "", "source": "github", "line_count": 336, "max_line_length": 139, "avg_line_length": 33.87797619047619, "alnum_prop": 0.7497144865149785, "repo_name": "arkxu/milton2", "id": "8b6625241eaf0bb3c3988025fcd8a8252bed9731", "size": "11383", "binary": false, "copies": "3", "ref": "refs/heads/1.7.2", "path": "milton-api/src/main/java/com/bradmcevoy/http/HttpManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2744584" }, { "name": "JavaScript", "bytes": "276443" }, { "name": "Shell", "bytes": "66" } ], "symlink_target": "" }
var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "@VERSION", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // HANDLE: $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = context.createDocumentFragment(); jQuery.clean( [ data ], context, parsed, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document);
{ "content_hash": "dbd7752ae1c846fe63e9e257aaa2465d", "timestamp": "", "source": "github", "line_count": 933, "max_line_length": 112, "avg_line_length": 24.65380493033226, "alnum_prop": 0.60420832971046, "repo_name": "Shipow/jquery", "id": "844eb159364f1e51970688884e99274af6f8c430", "size": "23002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import React, { PropTypes } from 'react'; import SwipeableViews from 'vendor/Swipeable'; import Styles from './Styles/main.scss'; import BreakPoints from 'vendor/PixelPerfect/breakpoints'; import Palette from 'components/Assets/Palette'; import BubbleArticle from 'components/Assets/Icons/BubbleArticle'; export default function Mobile(props) { const styles = { backgroundImage: 'url(https://cdn.hope.ua/media/shows/ALKU/episodes/02816/ALKU02816-cover.jpg)' }; const swipeParams = { containerWidth: 81.25, containerMargin: 4.4, resistance: true }; return ( <section className={ Styles.articleComponent }> <h1 className={ Styles.title }>Анонсы</h1> { BreakPoints.phonePortrait.name === props.mediaType ? (<SwipeableViews { ...swipeParams }> <article> <div className={ Styles.image } style={ styles }/> <div className={ Styles.info }> <div className={ Styles.date }> <BubbleArticle color={ Palette.mainColor3 }/> <p><strong>15 августа,</strong>&nbsp;14:32</p> </div> <h1>«Помолитесь за меня»: Моментальный ответ</h1> <p className={ Styles.description }>Когда тело женщины вытащили с воды, она не дышала </p> </div> </article> <article> <div className={ Styles.image } style={ styles }/> <div className={ Styles.info }> <div className={ Styles.date }> <BubbleArticle color={ Palette.mainColor3 }/> <p><strong>15 августа,</strong>&nbsp;14:32</p> </div> <h1>«Помолитесь за меня»: Моментальный ответ</h1> <p className={ Styles.description }>Когда тело женщины вытащили с воды, она не дышала </p> </div> </article> <article> <div className={ Styles.image } style={ styles }/> <div className={ Styles.info }> <div className={ Styles.date }> <BubbleArticle color={ Palette.mainColor3 }/> <p><strong>15 августа,</strong>&nbsp;14:32</p> </div> <h1>«Помолитесь за меня»: Моментальный ответ</h1> <p className={ Styles.description }>Когда тело женщины вытащили с воды, она не дышала </p> </div> </article> </SwipeableViews> ) : [ <article key={ 1 }> <div className={ Styles.image } style={ styles }/> <div className={ Styles.info }> <div className={ Styles.date }> <BubbleArticle color={ Palette.mainColor3 }/> <p><strong>15 августа,</strong>&nbsp;14:32</p> </div> <h1>«Помолитесь за меня»: Моментальный ответ</h1> <p className={ Styles.description }>Когда тело женщины вытащили с воды, она не дышала</p> </div> </article>, <article key={ 2 }> <div className={ Styles.image } style={ styles }/> <div className={ Styles.info }> <div className={ Styles.date }> <BubbleArticle color={ Palette.mainColor3 }/> <p><strong>15 августа,</strong>&nbsp;14:32</p> </div> <h1>«Помолитесь за меня»: Моментальный ответ</h1> <p className={ Styles.description }>Когда тело женщины вытащили с воды, она не дышала</p> </div> </article> ] } </section> ); } Mobile.propTypes = { mediaType: PropTypes.string.isRequired };
{ "content_hash": "ff5b0840ff611f80c4e07cd0ce43bbe1", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 117, "avg_line_length": 48.552083333333336, "alnum_prop": 0.4275906457841665, "repo_name": "HopeUA/tv.hope.ua-react", "id": "6352707c604bf8bd383dd3230e0878a0f04b5a58", "size": "5077", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/components/Home/Articles/Views/Mobile/tpl.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "377113" }, { "name": "JavaScript", "bytes": "670758" } ], "symlink_target": "" }
this.chongdashu = this.chongdashu||{}; (function() { "use strict"; /** * SequenceCheckComponent * @class Game.Component.SequenceCheckComponent * @extends Core.Component * @constructor **/ var SequenceCheckComponent = function(sequence) { // @param {Phaser.Keyboard} entity this.init(sequence); }; var p = createjs.extend(SequenceCheckComponent, chongdashu.Component); /** * The type identifier of this component. * * @property Game.SequenceCheckComponent.TYPE * @type String * @static * @final */ SequenceCheckComponent.TYPE = "component:SequenceCheckComponent"; p.sequence = null; p.sequencePointer = 0; p.init = function(sequence) { console.log("[SequenceCheckComponent], init()"); this.Component_init(SequenceCheckComponent.TYPE); this.sequence = sequence; this.sequencePointer = 0; }; // Link // ---- chongdashu.SequenceCheckComponent = createjs.promote(SequenceCheckComponent, "Component"); }());
{ "content_hash": "6d120b38589ac9a4bd02f01b8df2fddf", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 90, "avg_line_length": 22.347826086956523, "alnum_prop": 0.6605058365758755, "repo_name": "chongdashu/game-a-week-2015-1026-1101", "id": "5a21790cf5f347e522fb785cc0d89732ab996eb8", "size": "1146", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/chongdashu/Components/SequenceCheckComponent.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "36646" }, { "name": "JavaScript", "bytes": "81062" } ], "symlink_target": "" }
import socket import serial import threading class ServerEva: def __init__(self,host,port): self.host = host self.port = port self.serial_port = '/dev/ttyUSB0' self.buff_serial = 1024 self.baudrate = 38400 self.buff_sock = 1024 self.run_thread = True self.serial = None self.sock_server = None self.server_thread = None self.client = None self.connectBot() self.startServer() def connectBot(self): self.serial = serial.Serial(port=self.serial_port,baudrate=self.baudrate) print "Eva Connected" def startServer(self): self.sock_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.sock_server.bind((self.host,self.port)) self.sock_server.listen(5) self.server_thread = threading.Thread(target=self.serveForever) self.server_thread.start() def serveForever(self): (self.client, address) = self.sock_server.accept() print "Cliente Conectado" print address while self.run_thread: cmd = self.client.recv(self.buff_sock) self.processMessage(cmd) self.client.close() print "Coneccion cerrada" def processMessage(self,msg): print msg if msg == "AA": self.serial.write("$A,35,60,35,60\r\n") elif msg == "BB": self.serial.write("$A,-35,60,-35,60\r\n") elif msg == "DD": self.serial.write("$A,-20,20,20,20\r\n") elif msg == "DD2": self.serial.write("$A,-20,40,20,40\r\n") elif msg == "DIST": print "TODO" elif msg == "CC": self.serial.write("$A,20,20,-20,20\r\n") elif msg == "CC2": self.serial.write("$A,20,40,-20,40\r\n") elif msg == "EE": self.serial.write("$P,0\r\n") elif msg == "FF": self.serial.write("$P,1\r\n") elif msg == "SS": print "TODO" elif msg == "PP": self.serial.write("$A,10,10,10,10\r\n") elif msg == "CLOSE": self.run_thread = False self.client.send("connection close") def main(): server = ServerEva('192.168.1.205',8080) if __name__ == '__main__': main()
{ "content_hash": "03ed8096b1c664efd08e656dbc49c938", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 81, "avg_line_length": 30.342105263157894, "alnum_prop": 0.5424978317432784, "repo_name": "GeorgEncinas/Multi-Agents", "id": "54c469e27d9f2c15ea8c27f309ed8b9d2b4f777d", "size": "2306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "serverpi/ServerEva.py", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "3437" }, { "name": "Python", "bytes": "38025" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Fri Dec 06 06:56:42 CET 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Package eu.digitisation.io (ocrevalUAtion 1.2.4 API)</title> <meta name="date" content="2013-12-06"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package eu.digitisation.io (ocrevalUAtion 1.2.4 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?eu/digitisation/io/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package eu.digitisation.io" class="title">Uses of Package<br>eu.digitisation.io</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../eu/digitisation/io/package-summary.html">eu.digitisation.io</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#eu.digitisation.io">eu.digitisation.io</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="eu.digitisation.io"> <!-- --> </a> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../eu/digitisation/io/package-summary.html">eu.digitisation.io</a> used by <a href="../../../eu/digitisation/io/package-summary.html">eu.digitisation.io</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../eu/digitisation/io/class-use/CharFilter.html#eu.digitisation.io">CharFilter</a> <div class="block">Transform text according to a mapping between (source, target) Unicode character sequences.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../eu/digitisation/io/class-use/FileType.html#eu.digitisation.io">FileType</a> <div class="block">Supported input file types</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?eu/digitisation/io/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2009&#x2013;2013 <a href="http://www.digitisation.eu/">IMPACT Centre of Competence</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "d1bd482268de3c631c9da0a0854840a3", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 248, "avg_line_length": 35.10126582278481, "alnum_prop": 0.638838802740714, "repo_name": "impactcentre/ocrevalUAtion", "id": "ba0a277455e83038417cd82dd07b6c40ee0766dc", "size": "5546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/eu/digitisation/io/package-use.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "HTML", "bytes": "2001290" }, { "name": "Java", "bytes": "420322" }, { "name": "Makefile", "bytes": "370" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <Tokens version="1.0"> <File path="Classes/NOZCentralDirectoryRecord.html"> <Token> <TokenIdentifier>//apple_ref/occ/cl/NOZCentralDirectoryRecord</TokenIdentifier> <Abstract type="html">A central directory record is a zip entry populated with all the pertinent central directory info.</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/setName:</TokenIdentifier> <Abstract type="html">Name of entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly, nonnull) NSString *name</Declaration> <Anchor>//api/name/name</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/name</TokenIdentifier> <Abstract type="html">Name of entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly, nonnull) NSString *name</Declaration> <Anchor>//api/name/name</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instp/NOZCentralDirectoryRecord/name</TokenIdentifier> <Abstract type="html">Name of entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly, nonnull) NSString *name</Declaration> <Anchor>//api/name/name</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/setComment:</TokenIdentifier> <Abstract type="html">Optional comment for entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly, nullable) NSString *comment</Declaration> <Anchor>//api/name/comment</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/comment</TokenIdentifier> <Abstract type="html">Optional comment for entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly, nullable) NSString *comment</Declaration> <Anchor>//api/name/comment</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instp/NOZCentralDirectoryRecord/comment</TokenIdentifier> <Abstract type="html">Optional comment for entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly, nullable) NSString *comment</Declaration> <Anchor>//api/name/comment</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/setCompressionLevel:</TokenIdentifier> <Abstract type="html">Compression level for entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) NOZCompressionLevel compressionLevel</Declaration> <Anchor>//api/name/compressionLevel</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/compressionLevel</TokenIdentifier> <Abstract type="html">Compression level for entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) NOZCompressionLevel compressionLevel</Declaration> <Anchor>//api/name/compressionLevel</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instp/NOZCentralDirectoryRecord/compressionLevel</TokenIdentifier> <Abstract type="html">Compression level for entry</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) NOZCompressionLevel compressionLevel</Declaration> <Anchor>//api/name/compressionLevel</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/setCompressedSize:</TokenIdentifier> <Abstract type="html"></Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) SInt64 compressedSize</Declaration> <Anchor>//api/name/compressedSize</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/compressedSize</TokenIdentifier> <Abstract type="html"></Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) SInt64 compressedSize</Declaration> <Anchor>//api/name/compressedSize</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instp/NOZCentralDirectoryRecord/compressedSize</TokenIdentifier> <Abstract type="html"></Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) SInt64 compressedSize</Declaration> <Anchor>//api/name/compressedSize</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/setUncompressedSize:</TokenIdentifier> <Abstract type="html"></Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) SInt64 uncompressedSize</Declaration> <Anchor>//api/name/uncompressedSize</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/uncompressedSize</TokenIdentifier> <Abstract type="html"></Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) SInt64 uncompressedSize</Declaration> <Anchor>//api/name/uncompressedSize</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instp/NOZCentralDirectoryRecord/uncompressedSize</TokenIdentifier> <Abstract type="html"></Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>@property (nonatomic, readonly) SInt64 uncompressedSize</Declaration> <Anchor>//api/name/uncompressedSize</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/instm/NOZCentralDirectoryRecord/init</TokenIdentifier> <Abstract type="html">Unavailable</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>- (nullable instancetype)init</Declaration> <Anchor>//api/name/init</Anchor> <NodeRef refid="3"/> </Token> <Token> <TokenIdentifier>//apple_ref/occ/clm/NOZCentralDirectoryRecord/new</TokenIdentifier> <Abstract type="html">Unavailable</Abstract> <DeclaredIn>NOZUnzipper.h</DeclaredIn> <Declaration>+ (nullable instancetype)new</Declaration> <Anchor>//api/name/new</Anchor> <NodeRef refid="3"/> </Token> </File> </Tokens>
{ "content_hash": "9e94013556ba0c95f1600b271f8f13b7", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 134, "avg_line_length": 31.846846846846848, "alnum_prop": 0.694908062234795, "repo_name": "Ashton-W/ZipUtilities", "id": "68b9ff28ee0c5a42c9f320be8111fafd9973c5af", "size": "7070", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docset/Contents/Resources/Tokens3.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1340" }, { "name": "CSS", "bytes": "34242" }, { "name": "HTML", "bytes": "628390" }, { "name": "JavaScript", "bytes": "3032" }, { "name": "Objective-C", "bytes": "209322" } ], "symlink_target": "" }
// // LoginViewController.m // SportsContact // // Created by bobo on 14-7-9. // Copyright (c) 2014年 CAF. All rights reserved. // #import "LoginViewController.h" #import "LoginEngine.h" #import "ViewUtil.h" #import "NoticeManager.h" #import <BmobSDK/BmobUser.h> #import <BmobSDK/BmobQuery.h> #import "MainNavigationController.h" #import <ShareSDK/ShareSDK.h> //#import "WXApi.h" //#import "WeiboSDK.h" #import <TencentOpenAPI/QQApi.h> #import <TencentOpenAPI/QQApiInterface.h> #import <TencentOpenAPI/TencentOAuth.h> @interface LoginViewController () @end @implementation LoginViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // [LoginEngine loginWithUsername:@"ssss9" password:@"123456" block:^(id result, NSError *error) // { // if (error) // { // BDLog(@"Error :%@", [Util errorStringWithCode:error.code]); // }else // { // UserInfo *user = result; // BDLog(@"Login username :%@", user.username); // } // }]; // Do any additional setup after loading the view. // self.loginButton.backgroundColor=[ViewUtil hexStringToColor:@"f47900"]; // self.qqLoginButton.backgroundColor=[ViewUtil hexStringToColor:@"555c64"]; } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationController setNavigationBarHidden:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ - (IBAction)onSelectedLoginQQ:(id)sender { [ShareSDK authWithType:ShareTypeQQSpace options:nil result:^(SSAuthState state, id<ICMErrorInfo> error) { if (state == SSAuthStateSuccess) { id<ISSPlatformCredential> credential = [ShareSDK getCredentialWithType:ShareTypeQQSpace]; NSDictionary *responseDictionary = @{@"access_token":[credential token],@"uid":[credential uid],@"expirationDate":[credential expired]}; //通过授权信息注册登录 [self showLoadingView]; [BmobUser loginInBackgroundWithAuthorDictionary:responseDictionary platform:BmobSNSPlatformQQ block:^(BmobUser *user, NSError *error) { [self hideLoadingView]; [(MainNavigationController *)self.navigationController pushContentViewControllerAnimated:YES]; if ([BmobUser getCurrentUser]) { [NoticeManager updatePushProfile]; [[NoticeManager sharedManager] bindDB]; [self showMessage:@"登陆成功!"]; } }]; //授权成功之后,第一次,要提取QQ信息,注册Bmobuser // [ShareSDK getUserInfoWithType:ShareTypeQQ // authOptions:nil // result:^(BOOL result1, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) // { // // BDLog(@"************%@",[userInfo nickname]); // // if (result1) // { // // //提取QQ的信息,注册用户 // // [LoginEngine getUserinfoWithPhoenumber:[userInfo nickname] block:^(id result, NSError *error) { // // NSMutableArray *array=[[NSMutableArray alloc]init]; // array=result; // // if ([array count]==0) // { // // //提交用户注册信息 // // // // // [self showMessage:@"欢迎注册"]; // // } // else // { // // // [self showMessage:@"欢迎回来"]; // // } // // // // }]; // // // } // else // { // // } // // // // // // }]; } else if (state == SSAuthStateFail) { // BDLog(@"分享失败,错误码:%d,错误描述:%@", [error errorCode], [error errorDescription]); [self showMessage:@"登陆失败!"]; } else { } }]; // [ShareSDK getUserInfoWithType:ShareTypeQQSpace // authOptions:nil // result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) { // // BDLog(@"*********%@",[error errorDescription]); // // if (result) // { //// PFQuery *query = [PFQuery queryWithClassName:@"UserInfo"]; //// [query whereKey:@"uid" equalTo:[userInfo uid]]; //// [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { //// //// if ([objects count] == 0) //// { //// PFObject *newUser = [PFObject objectWithClassName:@"UserInfo"]; //// [newUser setObject:[userInfo uid] forKey:@"uid"]; //// [newUser setObject:[userInfo nickname] forKey:@"name"]; //// [newUser setObject:[userInfo profileImage] forKey:@"icon"]; //// [newUser saveInBackground]; //// //// UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"欢迎注册" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil]; //// [alertView show]; //// [alertView release]; //// } //// else //// { //// UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"欢迎回来" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil]; //// [alertView show]; //// [alertView release]; //// } //// }]; //// //// MainViewController *mainVC = [[[MainViewController alloc] init] autorelease]; //// [self.navigationController pushViewController:mainVC animated:YES]; // // } // // }]; } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"LoginDetail"]) { } } @end
{ "content_hash": "909e9b558a1a19c22db4d9dc0a027eda", "timestamp": "", "source": "github", "line_count": 311, "max_line_length": 194, "avg_line_length": 29.95498392282958, "alnum_prop": 0.3875053671103478, "repo_name": "bmob/BmobTiQiuBa", "id": "34f1e980780006b6e6c30daaec19553a641927a5", "size": "9498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iOS/SportsContact/UI/Login/LoginViewController.m", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "28" }, { "name": "Batchfile", "bytes": "380" }, { "name": "C", "bytes": "7069" }, { "name": "C++", "bytes": "6523" }, { "name": "CSS", "bytes": "38491" }, { "name": "HTML", "bytes": "78215" }, { "name": "Java", "bytes": "1043540" }, { "name": "JavaScript", "bytes": "39217" }, { "name": "Objective-C", "bytes": "3473681" }, { "name": "Objective-C++", "bytes": "5141" }, { "name": "PHP", "bytes": "375004" }, { "name": "Ruby", "bytes": "382" }, { "name": "Shell", "bytes": "4098" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `PROT_READ` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, PROT_READ"> <title>libc::consts::os::posix88::PROT_READ - Rust</title> <link rel="stylesheet" type="text/css" href="../../../../main.css"> <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <a href='../../../../libc/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a> <p class='location'><a href='../../../index.html'>libc</a>::<wbr><a href='../../index.html'>consts</a>::<wbr><a href='../index.html'>os</a>::<wbr><a href='index.html'>posix88</a></p><script>window.sidebarCurrent = {name: 'PROT_READ', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press 'S' to search, '?' for more options..." type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../../../index.html'>libc</a>::<wbr><a href='../../index.html'>consts</a>::<wbr><a href='../index.html'>os</a>::<wbr><a href='index.html'>posix88</a>::<wbr><a class='constant' href=''>PROT_READ</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-1788' class='srclink' href='../../../../src/libc/lib.rs.html#2911' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const PROT_READ: <a class='type' href='../../../../libc/types/os/arch/c95/type.c_int.html' title='libc::types::os::arch::c95::c_int'>c_int</a><code> = </code><code>1</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div class="shortcuts"> <h1>Keyboard shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>typedef</code> (or <code>tdef</code>). </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> <script> window.rootPath = "../../../../"; window.currentCrate = "libc"; window.playgroundUrl = "http://play.rust-lang.org/"; </script> <script src="../../../../jquery.js"></script> <script src="../../../../main.js"></script> <script src="../../../../playpen.js"></script> <script async src="../../../../search-index.js"></script> </body> </html>
{ "content_hash": "515c5974c4f52e555e8ed82bf85b7bf8", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 326, "avg_line_length": 42.37623762376238, "alnum_prop": 0.5242990654205607, "repo_name": "mcanders/bevy", "id": "28dcfb065755edb60fe4f217018afc9efc2404fe", "size": "4280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/libc/consts/os/posix88/constant.PROT_READ.html", "mode": "33188", "license": "mit", "language": [ { "name": "Rust", "bytes": "316751" } ], "symlink_target": "" }
package br.com.fametro.wine.repository.helper.usuario; import java.util.List; import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import org.hibernate.sql.JoinType; import org.springframework.transaction.annotation.Transactional; import br.com.fametro.wine.model.Usuario; public class UsuariosImpl implements UsuariosQueries { @PersistenceContext private EntityManager manager; @Override public Optional<Usuario> porEmailAtivo(String email) { return manager .createQuery("from Usuario where lower(email) = lower(:email) and ativo = true", Usuario.class) .setParameter("email", email).getResultList().stream().findFirst(); } @Override public List<String> permissoes(Usuario usuario) { return manager.createQuery( "select distinct p.nome from Usuario u inner join u.grupos g inner join g.permissoes p where u = :usuario", String.class) .setParameter("usuario", usuario) .getResultList(); } @Transactional(readOnly = true) @Override public Usuario buscarComGrupos(Long codigo) { Criteria criteria = manager.unwrap(Session.class).createCriteria(Usuario.class); criteria.createAlias("grupos", "g", JoinType.LEFT_OUTER_JOIN); criteria.add(Restrictions.eq("codigo", codigo)); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return (Usuario) criteria.uniqueResult(); } }
{ "content_hash": "edd5fa799fa51bdf6062b0eaa2bdb47f", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 125, "avg_line_length": 31.333333333333332, "alnum_prop": 0.7746010638297872, "repo_name": "EliasMG/wine", "id": "ca4c180a0f7c00397e24dce6fd50d7eafe0cadae", "size": "1504", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/br/com/fametro/wine/repository/helper/usuario/UsuariosImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5006" }, { "name": "HTML", "bytes": "52631" }, { "name": "Java", "bytes": "76278" }, { "name": "JavaScript", "bytes": "16968" } ], "symlink_target": "" }
.dashboard { /* stylelint-ignore */ display:flex; flex-basis: 100%; flex-direction: row; max-width: 100%; }
{ "content_hash": "1300212705a713c5c128353929f2f5c3", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 36, "avg_line_length": 19.333333333333332, "alnum_prop": 0.6379310344827587, "repo_name": "litdevelopers/tinder", "id": "97f9b1d0689dfa043e0c836836e105e4326393d5", "size": "116", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/containers/Dashboard/styles.css", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1526" }, { "name": "CSS", "bytes": "19246" }, { "name": "HTML", "bytes": "9023" }, { "name": "JavaScript", "bytes": "227451" } ], "symlink_target": "" }
/* global io */ 'use strict'; angular.module('biyblApp') .factory('socket', function(socketFactory) { // socket.io now auto-configures its connection when we ommit a connection url var ioSocket = io('', { // Send auth token on connection, you will need to DI the Auth service above // 'query': 'token=' + Auth.getToken() path: '/socket.io-client' }); var socket = socketFactory({ ioSocket: ioSocket }); return { socket: socket, /** * Register listeners to sync an array with updates on a model * * Takes the array we want to sync, the model name that socket updates are sent from, * and an optional callback function after new items are updated. * * @param {String} modelName * @param {Array} array * @param {Function} cb */ syncUpdates: function (modelName, array, cb) { cb = cb || angular.noop; /** * Syncs item creation/updates on 'model:save' */ socket.on(modelName + ':save', function (item) { var oldItem = _.find(array, {_id: item._id}); var index = array.indexOf(oldItem); var event = 'created'; // replace oldItem if it exists // otherwise just add item to the collection if (oldItem) { array.splice(index, 1, item); event = 'updated'; } else { array.push(item); } cb(event, item, array); }); /** * Syncs removed items on 'model:remove' */ socket.on(modelName + ':remove', function (item) { var event = 'deleted'; _.remove(array, {_id: item._id}); cb(event, item, array); }); }, /** * Removes listeners for a models updates on the socket * * @param modelName */ unsyncUpdates: function (modelName) { socket.removeAllListeners(modelName + ':save'); socket.removeAllListeners(modelName + ':remove'); } }; });
{ "content_hash": "17998c72bdb26f21a83c5b16d4e40eff", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 91, "avg_line_length": 29.094594594594593, "alnum_prop": 0.5197398978169996, "repo_name": "Cogiva/biybl", "id": "d03d1af5dd33c78a51290373cbf2cb6ab5cf4dd8", "size": "2153", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/components/socket/socket.service.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "24682" }, { "name": "CSS", "bytes": "2509" }, { "name": "HTML", "bytes": "17789" }, { "name": "JavaScript", "bytes": "79890" } ], "symlink_target": "" }
dos2unix --quiet /usr/local/bin/run-cloud-env-monitor echo "rtws.cloud.provider=EUC" > /usr/local/rtws/properties/rtws-common.properties
{ "content_hash": "75ec01dce6eb732a2a2a3ae600f7a7b9", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 82, "avg_line_length": 46, "alnum_prop": 0.782608695652174, "repo_name": "deleidos/digitaledge-platform", "id": "f053a044deb561f5b6351d292387e1a2f1f68cb2", "size": "875", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cloud-environment-monitor/target/scripts/post_install.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "16315580" }, { "name": "Batchfile", "bytes": "15678" }, { "name": "C", "bytes": "26042" }, { "name": "CSS", "bytes": "846559" }, { "name": "Groovy", "bytes": "93743" }, { "name": "HTML", "bytes": "36583222" }, { "name": "Java", "bytes": "33127586" }, { "name": "JavaScript", "bytes": "2030589" }, { "name": "Nginx", "bytes": "3934" }, { "name": "Perl", "bytes": "330290" }, { "name": "Python", "bytes": "54288" }, { "name": "Ruby", "bytes": "5133" }, { "name": "Shell", "bytes": "2482631" }, { "name": "XSLT", "bytes": "978664" } ], "symlink_target": "" }
FROM balenalib/var-som-mx6-ubuntu:xenial-run ENV NODE_VERSION 10.24.1 ENV YARN_VERSION 1.22.4 RUN buildDeps='curl libatomic1' \ && set -x \ && for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends \ && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "5b156bbd04adfaad2184b4d1e8324b21b546b40fb46e7105fa39f5ad2f34ddf3 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu xenial \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v10.24.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "7559082670978ab47c8ca0eaa7d1cc4b", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 692, "avg_line_length": 64.4, "alnum_prop": 0.704623878536922, "repo_name": "nghiant2710/base-images", "id": "fd041db742361cd09721b8aabc3b4db4714b8e33", "size": "2919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/var-som-mx6/ubuntu/xenial/10.24.1/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
enum ColorMode { MODE_COLOR, MODE_IR_16, MODE_IR_RGB, }; class MultiFrameListener : public astra::FrameListener { public: using BufferPtr = std::unique_ptr<uint8_t[]>; struct StreamView { sf::Sprite sprite_; sf::Texture texture_; BufferPtr buffer_; int width_{0}; int height_{0}; }; MultiFrameListener() { prev_ = ClockType::now(); } void init_texture(int width, int height, StreamView& view) { if (view.buffer_ == nullptr || width != view.width_ || height != view.height_) { view.width_ = width; view.height_ = height; // texture is RGBA const int byteLength = width * height * 4; view.buffer_ = BufferPtr(new uint8_t[byteLength]); clear_view(view); view.texture_.create(width, height); view.sprite_.setTexture(view.texture_); view.sprite_.setPosition(0, 0); } } void clear_view(StreamView& view) { const int byteLength = view.width_ * view.height_ * 4; std::fill(&view.buffer_[0], &view.buffer_[0] + byteLength, 0); } void check_fps() { const float frameWeight = .2f; const ClockType::time_point now = ClockType::now(); const float elapsedMillis = std::chrono::duration_cast<DurationType>(now - prev_).count(); elapsedMillis_ = elapsedMillis * frameWeight + elapsedMillis_ * (1.f - frameWeight); prev_ = now; const float fps = 1000.f / elapsedMillis; const auto precision = std::cout.precision(); std::cout << std::fixed << std::setprecision(1) << fps << " fps (" << std::setprecision(1) << elapsedMillis_ << " ms)" << std::setprecision(precision) << std::endl; } void update_depth(astra::Frame& frame) { const astra::PointFrame pointFrame = frame.get<astra::PointFrame>(); if (!pointFrame.is_valid()) { clear_view(depthView_); depthView_.texture_.update(&depthView_.buffer_[0]); return; } const int depthWidth = pointFrame.width(); const int depthHeight = pointFrame.height(); init_texture(depthWidth, depthHeight, depthView_); if (isPaused_) { return; } visualizer_.update(pointFrame); astra::RgbPixel* vizBuffer = visualizer_.get_output(); uint8_t* buffer = &depthView_.buffer_[0]; for (int i = 0; i < depthWidth * depthHeight; i++) { const int rgbaOffset = i * 4; buffer[rgbaOffset] = vizBuffer[i].r; buffer[rgbaOffset + 1] = vizBuffer[i].g; buffer[rgbaOffset + 2] = vizBuffer[i].b; buffer[rgbaOffset + 3] = 255; } depthView_.texture_.update(&depthView_.buffer_[0]); } void update_color(astra::Frame& frame) { const astra::ColorFrame colorFrame = frame.get<astra::ColorFrame>(); if (!colorFrame.is_valid()) { clear_view(colorView_); colorView_.texture_.update(&colorView_.buffer_[0]); return; } const int colorWidth = colorFrame.width(); const int colorHeight = colorFrame.height(); init_texture(colorWidth, colorHeight, colorView_); if (isPaused_) { return; } const astra::RgbPixel* color = colorFrame.data(); uint8_t* buffer = &colorView_.buffer_[0]; for(int i = 0; i < colorWidth * colorHeight; i++) { const int rgbaOffset = i * 4; buffer[rgbaOffset] = color[i].r; buffer[rgbaOffset + 1] = color[i].g; buffer[rgbaOffset + 2] = color[i].b; buffer[rgbaOffset + 3] = 255; } colorView_.texture_.update(&colorView_.buffer_[0]); } void update_ir_16(astra::Frame& frame) { const astra::InfraredFrame16 irFrame = frame.get<astra::InfraredFrame16>(); if (!irFrame.is_valid()) { clear_view(colorView_); colorView_.texture_.update(&colorView_.buffer_[0]); return; } const int irWidth = irFrame.width(); const int irHeight = irFrame.height(); init_texture(irWidth, irHeight, colorView_); if (isPaused_) { return; } const uint16_t* ir_values = irFrame.data(); uint8_t* buffer = &colorView_.buffer_[0]; for (int i = 0; i < irWidth * irHeight; i++) { const int rgbaOffset = i * 4; const uint16_t value = ir_values[i]; const uint8_t red = static_cast<uint8_t>(value >> 2); const uint8_t blue = 0x66 - red / 2; buffer[rgbaOffset] = red; buffer[rgbaOffset + 1] = 0; buffer[rgbaOffset + 2] = blue; buffer[rgbaOffset + 3] = 255; } colorView_.texture_.update(&colorView_.buffer_[0]); } void update_ir_rgb(astra::Frame& frame) { const astra::InfraredFrameRgb irFrame = frame.get<astra::InfraredFrameRgb>(); if (!irFrame.is_valid()) { clear_view(colorView_); colorView_.texture_.update(&colorView_.buffer_[0]); return; } int irWidth = irFrame.width(); int irHeight = irFrame.height(); init_texture(irWidth, irHeight, colorView_); if (isPaused_) { return; } const astra::RgbPixel* irRGB = irFrame.data(); uint8_t* buffer = &colorView_.buffer_[0]; for (int i = 0; i < irWidth * irHeight; i++) { const int rgbaOffset = i * 4; buffer[rgbaOffset] = irRGB[i].r; buffer[rgbaOffset + 1] = irRGB[i].g; buffer[rgbaOffset + 2] = irRGB[i].b; buffer[rgbaOffset + 3] = 255; } colorView_.texture_.update(&colorView_.buffer_[0]); } virtual void on_frame_ready(astra::StreamReader& reader, astra::Frame& frame) override { update_depth(frame); switch (colorMode_) { case MODE_COLOR: update_color(frame); break; case MODE_IR_16: update_ir_16(frame); break; case MODE_IR_RGB: update_ir_rgb(frame); break; } check_fps(); } void draw_to(sf::RenderWindow& window, sf::Vector2f origin, sf::Vector2f size) { const int viewSize = (int)(size.x / 2.0f); const sf::Vector2f windowSize = window.getView().getSize(); if (depthView_.buffer_ != nullptr) { const float depthScale = viewSize / (float)depthView_.width_; const int horzCenter = origin.y * windowSize.y; depthView_.sprite_.setScale(depthScale, depthScale); depthView_.sprite_.setPosition(origin.x * windowSize.x, horzCenter); window.draw(depthView_.sprite_); } if (colorView_.buffer_ != nullptr) { const float colorScale = viewSize / (float)colorView_.width_; const int horzCenter = origin.y * windowSize.y; colorView_.sprite_.setScale(colorScale, colorScale); if (overlayDepth_) { colorView_.sprite_.setPosition(origin.x * windowSize.x, horzCenter); colorView_.sprite_.setColor(sf::Color(255, 255, 255, 128)); } else { colorView_.sprite_.setPosition(origin.x * windowSize.x + viewSize, horzCenter); colorView_.sprite_.setColor(sf::Color(255, 255, 255, 255)); } window.draw(colorView_.sprite_); } } void toggle_depth_overlay() { overlayDepth_ = !overlayDepth_; } bool get_overlay_depth() const { return overlayDepth_; } void toggle_paused() { isPaused_ = !isPaused_; } bool is_paused() const { return isPaused_; } ColorMode get_mode() const { return colorMode_; } void set_mode(ColorMode mode) { colorMode_ = mode; } private: samples::common::LitDepthVisualizer visualizer_; using DurationType = std::chrono::milliseconds; using ClockType = std::chrono::high_resolution_clock; ClockType::time_point prev_; float elapsedMillis_{.0f}; StreamView depthView_; StreamView colorView_; ColorMode colorMode_; bool overlayDepth_{ false }; bool isPaused_{ false }; }; astra::DepthStream configure_depth(astra::StreamReader& reader) { auto depthStream = reader.stream<astra::DepthStream>(); //We don't have to set the mode to start the stream, but if you want to here is how: astra::ImageStreamMode depthMode; depthMode.set_width(640); depthMode.set_height(480); depthMode.set_pixel_format(astra_pixel_formats::ASTRA_PIXEL_FORMAT_DEPTH_MM); depthMode.set_fps(30); depthStream.set_mode(depthMode); return depthStream; } astra::InfraredStream configure_ir(astra::StreamReader& reader, bool useRGB) { auto irStream = reader.stream<astra::InfraredStream>(); astra::ImageStreamMode irMode; irMode.set_width(640); irMode.set_height(480); if (useRGB) { irMode.set_pixel_format(astra_pixel_formats::ASTRA_PIXEL_FORMAT_RGB888); } else { irMode.set_pixel_format(astra_pixel_formats::ASTRA_PIXEL_FORMAT_GRAY16); } irMode.set_fps(30); irStream.set_mode(irMode); return irStream; } astra::ColorStream configure_color(astra::StreamReader& reader) { auto colorStream = reader.stream<astra::ColorStream>(); astra::ImageStreamMode colorMode; colorMode.set_width(640); colorMode.set_height(480); colorMode.set_pixel_format(astra_pixel_formats::ASTRA_PIXEL_FORMAT_RGB888); colorMode.set_fps(30); colorStream.set_mode(colorMode); return colorStream; } int main(int argc, char** argv) { astra::initialize(); set_key_handler(); #ifdef _WIN32 auto fullscreenStyle = sf::Style::None; #else auto fullscreenStyle = sf::Style::Fullscreen; #endif const sf::VideoMode fullScreenMode = sf::VideoMode::getFullscreenModes()[0]; const sf::VideoMode windowedMode(1800, 675); bool isFullScreen = false; sf::RenderWindow window(windowedMode, "Stream Viewer"); astra::StreamSet streamSet; astra::StreamReader reader = streamSet.create_reader(); reader.stream<astra::PointStream>().start(); auto depthStream = configure_depth(reader); depthStream.start(); auto colorStream = configure_color(reader); colorStream.start(); auto irStream = configure_ir(reader, false); MultiFrameListener listener; listener.set_mode(MODE_COLOR); reader.add_listener(listener); while (window.isOpen()) { astra_temp_update(); sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: { switch (event.key.code) { case sf::Keyboard::Escape: window.close(); break; case sf::Keyboard::F: if (isFullScreen) { isFullScreen = false; window.create(windowedMode, "Stream Viewer", sf::Style::Default); } else { isFullScreen = true; window.create(fullScreenMode, "Stream Viewer", fullscreenStyle); } break; case sf::Keyboard::R: depthStream.enable_registration(!depthStream.registration_enabled()); break; case sf::Keyboard::M: { const bool newMirroring = !depthStream.mirroring_enabled(); depthStream.enable_mirroring(newMirroring); colorStream.enable_mirroring(newMirroring); irStream.enable_mirroring(newMirroring); } break; case sf::Keyboard::G: colorStream.stop(); configure_ir(reader, false); listener.set_mode(MODE_IR_16); irStream.start(); break; case sf::Keyboard::I: colorStream.stop(); configure_ir(reader, true); listener.set_mode(MODE_IR_RGB); irStream.start(); break; case sf::Keyboard::O: listener.toggle_depth_overlay(); if (listener.get_overlay_depth()) { depthStream.enable_registration(true); } break; case sf::Keyboard::P: listener.toggle_paused(); break; case sf::Keyboard::C: if (event.key.control) { window.close(); } else { irStream.stop(); listener.set_mode(MODE_COLOR); colorStream.start(); } break; default: break; } break; } default: break; } } // clear the window with black color window.clear(sf::Color::Black); listener.draw_to(window, sf::Vector2f(0.f, 0.f), sf::Vector2f(window.getSize().x, window.getSize().y)); window.display(); if (!shouldContinue) { window.close(); } } astra::terminate(); return 0; }
{ "content_hash": "ab8d408c578d34c3b600b374e7102d4f", "timestamp": "", "source": "github", "line_count": 497, "max_line_length": 111, "avg_line_length": 29.225352112676056, "alnum_prop": 0.5180034423407918, "repo_name": "orbbec/astra", "id": "254360edd9b165435cb13d5f680dde41afbf87df", "size": "15423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/sfml/SimpleStreamViewer-SFML/main.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1181" }, { "name": "C", "bytes": "66282" }, { "name": "C++", "bytes": "1249747" }, { "name": "CMake", "bytes": "151778" }, { "name": "Common Lisp", "bytes": "99476" }, { "name": "Java", "bytes": "16575" }, { "name": "Objective-C", "bytes": "4052" }, { "name": "Protocol Buffer", "bytes": "390" }, { "name": "Shell", "bytes": "1127" } ], "symlink_target": "" }
package org.apache.kafka.common.network; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.config.SslConfigs; import org.apache.kafka.common.config.internals.BrokerSecurityConfigs; import org.apache.kafka.common.memory.MemoryPool; import org.apache.kafka.common.security.auth.KafkaPrincipal; import org.apache.kafka.common.security.auth.KafkaPrincipalBuilder; import org.apache.kafka.common.security.auth.KafkaPrincipalSerde; import org.apache.kafka.common.security.auth.SslAuthenticationContext; import org.apache.kafka.common.security.ssl.SslFactory; import org.apache.kafka.common.security.ssl.SslPrincipalMapper; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.common.utils.Utils; import org.slf4j.Logger; import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; public class SslChannelBuilder implements ChannelBuilder, ListenerReconfigurable { private final ListenerName listenerName; private final boolean isInterBrokerListener; private SslFactory sslFactory; private Mode mode; private Map<String, ?> configs; private SslPrincipalMapper sslPrincipalMapper; private final Logger log; /** * Constructs an SSL channel builder. ListenerName is provided only * for server channel builder and will be null for client channel builder. */ public SslChannelBuilder(Mode mode, ListenerName listenerName, boolean isInterBrokerListener, LogContext logContext) { this.mode = mode; this.listenerName = listenerName; this.isInterBrokerListener = isInterBrokerListener; this.log = logContext.logger(getClass()); } public void configure(Map<String, ?> configs) throws KafkaException { try { this.configs = configs; String sslPrincipalMappingRules = (String) configs.get(BrokerSecurityConfigs.SSL_PRINCIPAL_MAPPING_RULES_CONFIG); if (sslPrincipalMappingRules != null) sslPrincipalMapper = SslPrincipalMapper.fromRules(sslPrincipalMappingRules); this.sslFactory = new SslFactory(mode, null, isInterBrokerListener); this.sslFactory.configure(this.configs); } catch (KafkaException e) { throw e; } catch (Exception e) { throw new KafkaException(e); } } @Override public Set<String> reconfigurableConfigs() { return SslConfigs.RECONFIGURABLE_CONFIGS; } @Override public void validateReconfiguration(Map<String, ?> configs) { sslFactory.validateReconfiguration(configs); } @Override public void reconfigure(Map<String, ?> configs) { sslFactory.reconfigure(configs); } @Override public ListenerName listenerName() { return listenerName; } @Override public KafkaChannel buildChannel(String id, SelectionKey key, int maxReceiveSize, MemoryPool memoryPool, ChannelMetadataRegistry metadataRegistry) throws KafkaException { try { SslTransportLayer transportLayer = buildTransportLayer(sslFactory, id, key, metadataRegistry); Supplier<Authenticator> authenticatorCreator = () -> new SslAuthenticator(configs, transportLayer, listenerName, sslPrincipalMapper); return new KafkaChannel(id, transportLayer, authenticatorCreator, maxReceiveSize, memoryPool != null ? memoryPool : MemoryPool.NONE, metadataRegistry); } catch (Exception e) { throw new KafkaException(e); } } @Override public void close() { if (sslFactory != null) sslFactory.close(); } protected SslTransportLayer buildTransportLayer(SslFactory sslFactory, String id, SelectionKey key, ChannelMetadataRegistry metadataRegistry) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); return SslTransportLayer.create(id, key, sslFactory.createSslEngine(socketChannel.socket()), metadataRegistry); } /** * Note that client SSL authentication is handled in {@link SslTransportLayer}. This class is only used * to transform the derived principal using a {@link KafkaPrincipalBuilder} configured by the user. */ private static class SslAuthenticator implements Authenticator { private final SslTransportLayer transportLayer; private final KafkaPrincipalBuilder principalBuilder; private final ListenerName listenerName; private SslAuthenticator(Map<String, ?> configs, SslTransportLayer transportLayer, ListenerName listenerName, SslPrincipalMapper sslPrincipalMapper) { this.transportLayer = transportLayer; this.principalBuilder = ChannelBuilders.createPrincipalBuilder(configs, null, sslPrincipalMapper); this.listenerName = listenerName; } /** * No-Op for plaintext authenticator */ @Override public void authenticate() {} /** * Constructs Principal using configured principalBuilder. * @return the built principal */ @Override public KafkaPrincipal principal() { InetAddress clientAddress = transportLayer.socketChannel().socket().getInetAddress(); // listenerName should only be null in Client mode where principal() should not be called if (listenerName == null) throw new IllegalStateException("Unexpected call to principal() when listenerName is null"); SslAuthenticationContext context = new SslAuthenticationContext( transportLayer.sslSession(), clientAddress, listenerName.value()); return principalBuilder.build(context); } @Override public Optional<KafkaPrincipalSerde> principalSerde() { return principalBuilder instanceof KafkaPrincipalSerde ? Optional.of((KafkaPrincipalSerde) principalBuilder) : Optional.empty(); } @Override public void close() throws IOException { if (principalBuilder instanceof Closeable) Utils.closeQuietly((Closeable) principalBuilder, "principal builder"); } /** * SslAuthenticator doesn't implement any additional authentication mechanism. * @return true */ @Override public boolean complete() { return true; } } }
{ "content_hash": "fe2c62d208204c4fdbbc307f8283b29e", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 166, "avg_line_length": 40.529761904761905, "alnum_prop": 0.6845351740343663, "repo_name": "apache/kafka", "id": "caaceb1b5199d72e6aa49c88e8c9ac4898453a64", "size": "7607", "binary": false, "copies": "3", "ref": "refs/heads/trunk", "path": "clients/src/main/java/org/apache/kafka/common/network/SslChannelBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "32930" }, { "name": "Dockerfile", "bytes": "9184" }, { "name": "HTML", "bytes": "3739" }, { "name": "Java", "bytes": "33868408" }, { "name": "Python", "bytes": "1153808" }, { "name": "Roff", "bytes": "39396" }, { "name": "Scala", "bytes": "10004229" }, { "name": "Shell", "bytes": "107622" }, { "name": "XSLT", "bytes": "7116" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ISO-8859-1"?> <LEOSimulation version="2.5.0"> <STELAVersion>2.5.1</STELAVersion> <SpaceObject> <mass unit="kg">9.0</mass> <dragArea>0.045</dragArea> <reflectingArea>0.18</reflectingArea> <reflectivityCoefficient>1.5</reflectivityCoefficient> <orbitType>LEO</orbitType> <ConstantDragCoef> <cstDragCoef>2.1</cstDragCoef> </ConstantDragCoef> <name>1W1NAJGB</name> </SpaceObject> <EphemerisManager version="2.5.0"> <initState> <bulletin version="2.5.0"> <date>2014-07-14T15:07:08.000</date> <Type2PosVel> <frame>CELESTIAL_MEAN_OF_DATE</frame> <nature>MEAN</nature> <semiMajorAxis unit="m">7000000.0</semiMajorAxis> <eccentricity>0.001</eccentricity> <inclination unit="rad">1.66678943565</inclination> <rAAN unit="rad">0.0</rAAN> <argOfPerigee unit="rad">0.0</argOfPerigee> <meanAnomaly unit="rad">0.0</meanAnomaly> </Type2PosVel> </bulletin> </initState> <finalState> <bulletin version="2.5.0"> <date>2055-03-31T15:25:52.497</date> <Type2PosVel> <frame>CELESTIAL_MEAN_OF_DATE</frame> <nature>MEAN</nature> <semiMajorAxis unit="m">6517962.434882684</semiMajorAxis> <eccentricity>3.5195355224973163E-4</eccentricity> <inclination unit="rad">1.6654274800655662</inclination> <rAAN unit="rad">2.0812279249289922</rAAN> <argOfPerigee unit="rad">1.3920972486681658</argOfPerigee> <meanAnomaly unit="rad">2.0163676470907355</meanAnomaly> </Type2PosVel> </bulletin> </finalState> </EphemerisManager> <author>CNES</author> <comment>LEO example simulation</comment> <simulationDuration unit="years">100.0</simulationDuration> <ephemerisStep unit="s">86400.0</ephemerisStep> <ttMinusUT1 unit="s">67.184</ttMinusUT1> <srpSwitch>true</srpSwitch> <sunSwitch>true</sunSwitch> <moonSwitch>true</moonSwitch> <extrapolationDuration>27247</extrapolationDuration> <warningFlag>false</warningFlag> <iterativeMode>false</iterativeMode> <GTOIntegrator> <Integrator> <effective_duration unit="years">40.71256130051081</effective_duration> <LOSCriteria1 version="2.5.0"> <status_criteria1>0</status_criteria1> <comment_criteria1>Lifetime :40.71 years</comment_criteria1> </LOSCriteria1> <LOSCriteria2 version="2.5.0"> <status_criteria2>3</status_criteria2> </LOSCriteria2> <LOSCriteria3 version="2.5.0"> <status_criteria3>3</status_criteria3> </LOSCriteria3> <LOSCriteria4 version="2.5.0"> <status_criteria4>3</status_criteria4> </LOSCriteria4> </Integrator> </GTOIntegrator> <modelType>GTO</modelType> <atmosModel>NRLMSISE-00</atmosModel> <VariableSolarActivity> <solActType>VARIABLE</solActType> </VariableSolarActivity> <integrationStep unit="s">86400.0</integrationStep> <dragSwitch>true</dragSwitch> <dragQuadPoints>33</dragQuadPoints> <atmosDragRecomputeStep>1</atmosDragRecomputeStep> <srpQuadPoints>11</srpQuadPoints> <reentryAltitude unit="m">120000.0</reentryAltitude> <iterationData> <funcValueAccuracy unit="days">10.0</funcValueAccuracy> <expDuration unit="years">24.75</expDuration> <simMinusExpDuration unit="years">75.25</simMinusExpDuration> <iterationMethod>FrozenOrbit</iterationMethod> </iterationData> <nbIntegrationStepTesseral>5.0</nbIntegrationStepTesseral> <zonalOrder>7</zonalOrder> </LEOSimulation>
{ "content_hash": "bbaebe7b7139531fb7098ff569a542dd", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 74, "avg_line_length": 35.4, "alnum_prop": 0.7270294380017841, "repo_name": "pouyana/satgen", "id": "3f9db5f64f7dfc5650135b6bbe3896a0d317f82d", "size": "3363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sim/1W1NAJGB_a_sim.xml_out_sim.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "552816" }, { "name": "Matlab", "bytes": "1015" }, { "name": "Python", "bytes": "227028" } ], "symlink_target": "" }
import unittest2 class TestClient(unittest2.TestCase): def _getTargetClass(self): from gcloud.bigquery.client import Client return Client def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test_ctor(self): from gcloud.bigquery.connection import Connection PROJECT = 'PROJECT' creds = _Credentials() http = object() client = self._makeOne(project=PROJECT, credentials=creds, http=http) self.assertTrue(isinstance(client.connection, Connection)) self.assertTrue(client.connection.credentials is creds) self.assertTrue(client.connection.http is http) def test_list_datasets_defaults(self): from gcloud.bigquery.dataset import Dataset PROJECT = 'PROJECT' DATASET_1 = 'dataset_one' DATASET_2 = 'dataset_two' PATH = 'projects/%s/datasets' % PROJECT TOKEN = 'TOKEN' DATA = { 'nextPageToken': TOKEN, 'datasets': [ {'kind': 'bigquery#dataset', 'id': '%s:%s' % (PROJECT, DATASET_1), 'datasetReference': {'datasetId': DATASET_1, 'projectId': PROJECT}, 'friendlyName': None}, {'kind': 'bigquery#dataset', 'id': '%s:%s' % (PROJECT, DATASET_2), 'datasetReference': {'datasetId': DATASET_2, 'projectId': PROJECT}, 'friendlyName': 'Two'}, ] } creds = _Credentials() client = self._makeOne(PROJECT, creds) conn = client.connection = _Connection(DATA) datasets, token = client.list_datasets() self.assertEqual(len(datasets), len(DATA['datasets'])) for found, expected in zip(datasets, DATA['datasets']): self.assertTrue(isinstance(found, Dataset)) self.assertEqual(found.dataset_id, expected['id']) self.assertEqual(found.friendly_name, expected['friendlyName']) self.assertEqual(token, TOKEN) self.assertEqual(len(conn._requested), 1) req = conn._requested[0] self.assertEqual(req['method'], 'GET') self.assertEqual(req['path'], '/%s' % PATH) def test_list_datasets_explicit(self): from gcloud.bigquery.dataset import Dataset PROJECT = 'PROJECT' DATASET_1 = 'dataset_one' DATASET_2 = 'dataset_two' PATH = 'projects/%s/datasets' % PROJECT TOKEN = 'TOKEN' DATA = { 'datasets': [ {'kind': 'bigquery#dataset', 'id': '%s:%s' % (PROJECT, DATASET_1), 'datasetReference': {'datasetId': DATASET_1, 'projectId': PROJECT}, 'friendlyName': None}, {'kind': 'bigquery#dataset', 'id': '%s:%s' % (PROJECT, DATASET_2), 'datasetReference': {'datasetId': DATASET_2, 'projectId': PROJECT}, 'friendlyName': 'Two'}, ] } creds = _Credentials() client = self._makeOne(PROJECT, creds) conn = client.connection = _Connection(DATA) datasets, token = client.list_datasets( include_all=True, max_results=3, page_token=TOKEN) self.assertEqual(len(datasets), len(DATA['datasets'])) for found, expected in zip(datasets, DATA['datasets']): self.assertTrue(isinstance(found, Dataset)) self.assertEqual(found.dataset_id, expected['id']) self.assertEqual(found.friendly_name, expected['friendlyName']) self.assertEqual(token, None) self.assertEqual(len(conn._requested), 1) req = conn._requested[0] self.assertEqual(req['method'], 'GET') self.assertEqual(req['path'], '/%s' % PATH) self.assertEqual(req['query_params'], {'all': True, 'maxResults': 3, 'pageToken': TOKEN}) def test_dataset(self): from gcloud.bigquery.dataset import Dataset PROJECT = 'PROJECT' DATASET = 'dataset_name' creds = _Credentials() http = object() client = self._makeOne(project=PROJECT, credentials=creds, http=http) dataset = client.dataset(DATASET) self.assertTrue(isinstance(dataset, Dataset)) self.assertEqual(dataset.name, DATASET) self.assertTrue(dataset._client is client) def test_load_table_from_storage(self): from gcloud.bigquery.job import LoadTableFromStorageJob PROJECT = 'PROJECT' JOB = 'job_name' DATASET = 'dataset_name' DESTINATION = 'destination_table' SOURCE_URI = 'http://example.com/source.csv' creds = _Credentials() http = object() client = self._makeOne(project=PROJECT, credentials=creds, http=http) dataset = client.dataset(DATASET) destination = dataset.table(DESTINATION) job = client.load_table_from_storage(JOB, destination, SOURCE_URI) self.assertTrue(isinstance(job, LoadTableFromStorageJob)) self.assertTrue(job._client is client) self.assertEqual(job.name, JOB) self.assertEqual(list(job.source_uris), [SOURCE_URI]) self.assertTrue(job.destination is destination) def test_copy_table(self): from gcloud.bigquery.job import CopyJob PROJECT = 'PROJECT' JOB = 'job_name' DATASET = 'dataset_name' SOURCE = 'source_table' DESTINATION = 'destination_table' creds = _Credentials() http = object() client = self._makeOne(project=PROJECT, credentials=creds, http=http) dataset = client.dataset(DATASET) source = dataset.table(SOURCE) destination = dataset.table(DESTINATION) job = client.copy_table(JOB, destination, source) self.assertTrue(isinstance(job, CopyJob)) self.assertTrue(job._client is client) self.assertEqual(job.name, JOB) self.assertEqual(list(job.sources), [source]) self.assertTrue(job.destination is destination) def test_extract_table_to_storage(self): from gcloud.bigquery.job import ExtractTableToStorageJob PROJECT = 'PROJECT' JOB = 'job_name' DATASET = 'dataset_name' SOURCE = 'source_table' DESTINATION = 'gs://bucket_name/object_name' creds = _Credentials() http = object() client = self._makeOne(project=PROJECT, credentials=creds, http=http) dataset = client.dataset(DATASET) source = dataset.table(SOURCE) job = client.extract_table_to_storage(JOB, source, DESTINATION) self.assertTrue(isinstance(job, ExtractTableToStorageJob)) self.assertTrue(job._client is client) self.assertEqual(job.name, JOB) self.assertEqual(job.source, source) self.assertEqual(list(job.destination_uris), [DESTINATION]) def test_run_async_query(self): from gcloud.bigquery.job import RunAsyncQueryJob PROJECT = 'PROJECT' JOB = 'job_name' QUERY = 'select count(*) from persons' creds = _Credentials() http = object() client = self._makeOne(project=PROJECT, credentials=creds, http=http) job = client.run_async_query(JOB, QUERY) self.assertTrue(isinstance(job, RunAsyncQueryJob)) self.assertTrue(job._client is client) self.assertEqual(job.name, JOB) self.assertEqual(job.query, QUERY) def test_run_sync_query(self): from gcloud.bigquery.job import RunSyncQueryJob PROJECT = 'PROJECT' QUERY = 'select count(*) from persons' creds = _Credentials() http = object() client = self._makeOne(project=PROJECT, credentials=creds, http=http) job = client.run_sync_query(QUERY) self.assertTrue(isinstance(job, RunSyncQueryJob)) self.assertTrue(job._client is client) self.assertEqual(job.name, None) self.assertEqual(job.query, QUERY) class _Credentials(object): _scopes = None @staticmethod def create_scoped_required(): return True def create_scoped(self, scope): self._scopes = scope return self class _Connection(object): def __init__(self, *responses): self._responses = responses self._requested = [] def api_request(self, **kw): self._requested.append(kw) response, self._responses = self._responses[0], self._responses[1:] return response
{ "content_hash": "0aee3d3042be7c55033fd56e5792a68f", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 77, "avg_line_length": 38.44, "alnum_prop": 0.5938258758237946, "repo_name": "thonkify/thonkify", "id": "0e9fa7482ca6e2f96f04d5ad96d47ad62f400e69", "size": "9246", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/lib/gcloud/bigquery/test_client.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "10460214" }, { "name": "Shell", "bytes": "1470" } ], "symlink_target": "" }
This provides an implementation of the Linked Data Registry originally developed under ukl-registry-poc. The implementation runs as a java web application. The war is self-contained and includes an example starting configuration and set of UI templates and style sheets. However, it will detect and use an external set of configuration files if available. For information on installing and operating a registry instance see the wiki: * [Build](https://github.com/UKGovLD/registry-core/wiki/Build) * [Installation](https://github.com/UKGovLD/registry-core/wiki/Installation) * [Configuration](https://github.com/UKGovLD/registry-core/wiki/Configuration) * [Operation](https://github.com/UKGovLD/registry-core/wiki/Operation) Download most recent full release: [registry-core-2.3.12.war](https://s3-eu-west-1.amazonaws.com/ukgovld/release/com/github/ukgovld/registry-core/2.3.12/registry-core-2.3.12.war) - [Release Notes 2.3.12](https://github.com/UKGovLD/registry-core/wiki/Release-2.3.12) Earlier release notes can be found at: [Release Notes](https://github.com/UKGovLD/registry-core/wiki#release-notes) ## Project governance See: * [Project governance](https://github.com/der/ukl-registry-poc/wiki/Project-Governance)
{ "content_hash": "5481288cb5e0331a1aa62a50e0bc9ba3", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 181, "avg_line_length": 59.23809523809524, "alnum_prop": 0.7797427652733119, "repo_name": "UKGovLD/registry-core", "id": "431a436977c4ffe9faf20ba917761e1c2f4e70c9", "size": "1261", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "14759" }, { "name": "HTML", "bytes": "1346" }, { "name": "Java", "bytes": "955564" }, { "name": "JavaScript", "bytes": "638319" }, { "name": "Shell", "bytes": "16348" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "fd96a3bc0c7f859d1ae869ad72d34f57", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "62e9e847013d3e54a75241ef65fd270d3757c4e8", "size": "200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Bacteria/Cyanobacteria/Chroococcales/Chroococcaceae/Aphanocapsaopsis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Web; using System.Web.Mvc; using Recaptcha; namespace PoliteCaptcha { /// <summary> /// A CAPTCHA validator that uses reCAPTCHA. /// </summary> public class ReCaptchaValidator : ICaptchaValidator { readonly RecaptchaValidator _recaptchaValidator; readonly IConfigurationSource _configSource; public ReCaptchaValidator() : this(new DefaultConfigurationSource()) { } public ReCaptchaValidator(IConfigurationSource configSource) { _configSource = configSource; _recaptchaValidator = new RecaptchaValidator(); } /// <summary> /// Validates a CAPTCHA response using reCAPTCHA. /// </summary> /// <param name="httpContext">The request's HTTP context.</param> /// <returns>The result of validation; true or false.</returns> public bool Validate(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } var configurationSource = GetConfigurationSource(); var privateApiKey = configurationSource.GetConfigurationValue(Const.ReCaptchaPrivateKeyAppSettingKey); if (privateApiKey == null) { if (!httpContext.Request.IsLocal) throw new InvalidOperationException(ErrorMessage.DefaultReCaptchApiKeysOnlyAllowedForLocalRequest); privateApiKey = Const.ReCaptchaLocalhostPrivateKey; } var challenge = httpContext.Request.Form[Const.ReCaptchaChallengeField]; if (string.IsNullOrWhiteSpace(challenge)) return false; var response = httpContext.Request.Form[Const.ReCaptchaResponseField]; if (string.IsNullOrWhiteSpace(response)) return false; _recaptchaValidator.PrivateKey = privateApiKey; _recaptchaValidator.RemoteIP = httpContext.Request.UserHostAddress; _recaptchaValidator.Challenge = challenge; _recaptchaValidator.Response = response; return _recaptchaValidator.Validate().IsValid; } private IConfigurationSource GetConfigurationSource() { if (_configSource != null) { return _configSource; } if (DependencyResolver.Current != null) { var resolvedConfigSource = DependencyResolver.Current.GetService<IConfigurationSource>(); if (resolvedConfigSource != null) { return resolvedConfigSource; } } return new DefaultConfigurationSource(); } } }
{ "content_hash": "145698140662a11e5061c2601dce3c9e", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 119, "avg_line_length": 33.654761904761905, "alnum_prop": 0.6027591085956845, "repo_name": "NuGet/PoliteCaptcha", "id": "2b768174aafe67646578e9ea345523d052b7738c", "size": "2829", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "PoliteCaptcha/ReCaptchaValidator.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "97" }, { "name": "C#", "bytes": "34115" }, { "name": "CSS", "bytes": "976" }, { "name": "PowerShell", "bytes": "203" }, { "name": "XSLT", "bytes": "10095" } ], "symlink_target": "" }
import html from 'choo/html' import style from './style' export default (state, emit, content) => { return html` <main class=${style}>${content}</main> ` }
{ "content_hash": "4703548604ed7fd8c4bb1a0e69742b9d", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 42, "avg_line_length": 16.7, "alnum_prop": 0.6347305389221557, "repo_name": "Pablo-Rodriguez/alotroladodelapagina", "id": "3f1f09cc3ed818408f5cfee03ab675e5aa89f477", "size": "168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/frontend/js/components/aolp-main/aolp-main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3722" }, { "name": "HTML", "bytes": "934" }, { "name": "JavaScript", "bytes": "668226" }, { "name": "Shell", "bytes": "318" } ], "symlink_target": "" }
package org.broadinstitute.hellbender.utils.codecs.gtf; import com.google.common.annotations.VisibleForTesting; import htsjdk.samtools.util.Locatable; import htsjdk.tribble.Feature; import htsjdk.tribble.annotation.Strand; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.broadinstitute.hellbender.exceptions.UserException; import org.broadinstitute.hellbender.utils.SimpleInterval; import org.broadinstitute.hellbender.utils.Utils; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * A {@link GencodeGtfFeature} represents data in a GENCODE GTF file. * * Features are grouped logically by related data. * While the abstract class {@link GencodeGtfFeature} represents a single line * of a GENCODE GTF File, the concrete instantiations represent at least one line, * and often more than one. * * For example, a {@link GencodeGtfGeneFeature} represents all lines in the given * data file with information on a particular gene. This includes all transcripts, * exons, coding regions, etc. in that gene. * * Similarly, a {@link GencodeGtfTranscriptFeature} represents all lines in the given * data file with information on a particular transcript. * * However, a {@link GencodeGtfSelenocysteineFeature} represents a particular line * in the given data file that contains information on a specific selenocysteine. * * The specification of a GTF file is defined here: * http://mblab.wustl.edu/GTF22.html * * Currently only supports GENCODE versions 19-26. * * Created by jonn on 7/21/17. */ public abstract class GencodeGtfFeature implements Feature, Comparable<GencodeGtfFeature> { private static final Logger logger = LogManager.getLogger(GencodeGtfFeature.class); // =========================================================================== public static final String ANNOTATION_SOURCE_ENSEMBL = "ENSEMBL"; public static final String ANNOTATION_SOURCE_HAVANA = "HAVANA"; public static final String ANNOTATION_SOURCE_ENA = "ena"; // =========================================================================== // Metadata fields: private static final String FIELD_DELIMITER = "\t"; public static final int NO_FEATURE_ORDER = -1; public static final int NO_EXON_NUMBER = -1; private static final int NUM_FIELDS = 9; private static final int CHROMOSOME_NAME_INDEX = 0; private static final int ANNOTATION_SOURCE_INDEX = 1; private static final int FEATURE_TYPE_INDEX = 2; private static final int START_LOCATION_INDEX = 3; private static final int END_LOCATION_INDEX = 4; private static final int GENOMIC_STRAND_INDEX = 6; private static final int GENOMIC_PHASE_INDEX = 7; private static final int EXTRA_FIELDS_INDEX = 8; private static final String EXTRA_FIELD_DELIMITER = ";"; private static final int EXTRA_FIELD_KEY_INDEX = 0; private static final int EXTRA_FIELD_VALUE_INDEX = 1; public static final String EXTRA_FIELD_KEY_VALUE_SPLITTER = " "; private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d\\d*"); private String ucscGenomeVersion = null; @VisibleForTesting final GencodeGtfFeatureBaseData baseData; // ================================================================================================ /** * Populate this GencodeGtfFeature with the given data. * @param gtfFields {@link String[]} containing an ordered list of fields to use to populate this {@link GencodeGtfFeature}. * @param gtfFileType A {@link String} containing the file type of the GTF data that created this {@link GencodeGtfFeature}. */ protected GencodeGtfFeature(final String[] gtfFields, final String gtfFileType) { Utils.validateArg(gtfFields.length == NUM_FIELDS, "Unexpected number of fields: " + gtfFields.length + " != " + NUM_FIELDS); baseData = new GencodeGtfFeatureBaseData(); try { baseData.genomicPosition = new SimpleInterval( gtfFields[CHROMOSOME_NAME_INDEX], Integer.valueOf(gtfFields[START_LOCATION_INDEX]), Integer.valueOf(gtfFields[END_LOCATION_INDEX]) ); } catch (final NumberFormatException ex) { throw new UserException.MalformedFile("Cannot read integer value for start/end position!"); } baseData.gtfSourceFileType = gtfFileType; baseData.annotationSource = gtfFields[ANNOTATION_SOURCE_INDEX]; baseData.featureType = GencodeGtfFeature.FeatureType.getEnum( gtfFields[FEATURE_TYPE_INDEX].toLowerCase() ); baseData.genomicStrand = convertStringToStrand( gtfFields[GENOMIC_STRAND_INDEX] ); baseData.genomicPhase = GenomicPhase.getEnum( gtfFields[GENOMIC_PHASE_INDEX] ); // Get the extra fields from the last column: final String[] extraFields = gtfFields[EXTRA_FIELDS_INDEX].split(EXTRA_FIELD_DELIMITER, -1); final StringBuilder anonymousOptionalFieldBuilder = new StringBuilder(); // Now there are "optional" fields to go through (some actually required, some actually optional), // But we need to match up the field names to the fields themselves: for ( final String extraField : extraFields ) { final String trimmedExtraField = extraField.trim(); if (trimmedExtraField.isEmpty()) { continue; } final int splitPoint = trimmedExtraField.indexOf(EXTRA_FIELD_KEY_VALUE_SPLITTER); if( splitPoint == -1 ) { throw new UserException.MalformedFile("Extraneous optional field data - not in a key/value pair: " + extraField); } final String fieldName = trimmedExtraField.substring(0, splitPoint).trim(); // The value of the field may be between two quotes. // We remove them here. final String rawFieldValue = trimmedExtraField.substring(splitPoint + 1, trimmedExtraField.length()); final String fieldValue = StringUtils.remove(rawFieldValue.trim(), '"'); if( fieldValue.contains(EXTRA_FIELD_KEY_VALUE_SPLITTER) ){ throw new UserException("Expected a key/value pair but found several values " + fieldName + "/" + fieldValue); } OptionalField<?> optionalField = null; switch (fieldName) { // Find the right field to set: case "gene_id": baseData.geneId = fieldValue; break; case "transcript_id": baseData.transcriptId = fieldValue; break; case "gene_type": baseData.geneType = fieldValue; break; // For ENSEMBL GTF files: case "gene_biotype": baseData.geneType = fieldValue; break; case "gene_status": baseData.geneStatus = GeneTranscriptStatus.valueOf(fieldValue); break; case "gene_name": baseData.geneName = fieldValue; break; case "transcript_type": baseData.transcriptType = fieldValue; break; case "transcript_biotype": baseData.transcriptType = fieldValue; break; case "transcript_status": baseData.transcriptStatus = GeneTranscriptStatus.valueOf(fieldValue); break; case "transcript_name": baseData.transcriptName = fieldValue; break; case "exon_number": try { baseData.exonNumber = Integer.valueOf(fieldValue); } catch (final NumberFormatException ex) { throw new UserException.MalformedFile("Could not convert field value into integer: " + fieldValue); } break; case "exon_id": baseData.exonId = fieldValue; break; case "level": baseData.locusLevel = LocusLevel.getEnum(fieldValue); break; case "tag": optionalField = new OptionalField<>(fieldName, FeatureTag.getEnum(fieldValue)); break; case "ccdsid": optionalField = new OptionalField<>(fieldName, fieldValue); break; case "havana_gene": optionalField = new OptionalField<>(fieldName, fieldValue); break; case "havana_transcript": optionalField = new OptionalField<>(fieldName, fieldValue); break; case "protein_id": optionalField = new OptionalField<>(fieldName, fieldValue); break; case "ont": optionalField = new OptionalField<>(fieldName, fieldValue); break; case "transcript_support_level": optionalField = new OptionalField<>(fieldName, TranscriptSupportLevel.getEnum(fieldValue)); break; case "remap_status": optionalField = new OptionalField<>(fieldName, RemapStatus.getEnum(fieldValue)); break; case "remap_original_id": optionalField = new OptionalField<>(fieldName, fieldValue); break; case "remap_original_location": try { optionalField = new OptionalField<>(fieldName, Long.valueOf(fieldValue)); } catch (final NumberFormatException nfe) { // We must have gotten a field that has a different format. // For now, just copy it over: optionalField = new OptionalField<>(fieldName, fieldValue); } break; case "remap_num_mappings": optionalField = new OptionalField<>(fieldName, Long.valueOf(fieldValue)); break; case "remap_target_status": optionalField = new OptionalField<>(fieldName, RemapTargetStatus.getEnum(fieldValue)); break; case "remap_substituted_missing_target": optionalField = new OptionalField<>(fieldName, fieldValue); break; default: anonymousOptionalFieldBuilder.append(extraField); anonymousOptionalFieldBuilder.append(EXTRA_FIELD_DELIMITER); break; } // If the optional field was good, we add it: if ( optionalField != null ) { baseData.optionalFields.add(optionalField); } } // Save our anonymous optional fields: if ( anonymousOptionalFieldBuilder.length() != 0 ) { baseData.anonymousOptionalFields = anonymousOptionalFieldBuilder.toString(); } } /** * Converts the given {@link String} into a {@link Strand}. * @param s {@link String} to convert into a {@link Strand}. * @return The {@link Strand} corresponding to {@code s}. */ private static Strand convertStringToStrand( final String s ) { if ( s.equals("+") ) { return Strand.POSITIVE; } else if ( s.equals("-") ) { return Strand.NEGATIVE; } else { throw new IllegalArgumentException("Unexpected value: " + s); } } /** * Populate this GencodeGtfFeature with the given data. */ protected GencodeGtfFeature(final GencodeGtfFeatureBaseData baseData) { this.baseData = baseData; } // ================================================================================================ /** * Create the appropriate {@link GencodeGtfFeature} object based on the given {@code baseData} * @param baseData A {@link GencodeGtfFeatureBaseData} object containing all data for a single line in a GENCODE GTF File. * @return A {@link GencodeGtfFeature} containing the data in {@code baseData} */ public static GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { Utils.nonNull(baseData); // Create our feature: return baseData.featureType.create(baseData); } /** * Create a {@link GencodeGtfFeature} based on a line from a Gencode GTF File. * @param gtfLine A line from a Gencode GTF File to convert into a {@link GencodeGtfFeature} object. * @param gtfFileType A {@link String} containing the file type of the GTF data that created this {@link GencodeGtfFeature}. * @return The {@link GencodeGtfFeature} representing the information in {@code gtfLine} */ public static GencodeGtfFeature create(final String gtfLine, final String gtfFileType) { Utils.nonNull(gtfLine); return create(gtfLine.split(FIELD_DELIMITER), gtfFileType); } /** * Create a {@link GencodeGtfFeature} based on a line from a Gencode GTF File. * @param gtfFields A line from a Gencode GTF File split on the {@link #FIELD_DELIMITER} character. * @param gtfFileType A {@link String} containing the file type of the GTF data that created this {@link GencodeGtfFeature}. * @return The {@link GencodeGtfFeature} representing the information in {@code gtfLine} */ public static GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { Utils.nonNull(gtfFields); // Ensure that the input data are superficially well-formed: if ( gtfFields.length != GencodeGtfCodec.NUM_COLUMNS ) { throw new UserException.MalformedFile("Invalid number of fields in the given GENCODE line " + " - Given: " + gtfFields.length + " Expected: " + GencodeGtfCodec.NUM_COLUMNS); } final FeatureType featureType = FeatureType.getEnum( gtfFields[FEATURE_TYPE_INDEX] ); // Return our feature: return featureType.create(gtfFields, gtfFileType); } // ================================================================================================ @Override public String getContig() { return baseData.genomicPosition.getContig(); } @Override public int getStart() { return baseData.genomicPosition.getStart(); } @Override public int getEnd() { return baseData.genomicPosition.getEnd(); } // ================================================================================================ /** * Get all the features from this {@link GencodeGtfFeature} itself. * This is useful to get any subfeatures included in this {@link GencodeGtfFeature}. * @return A {@link List} of the features represented in this {@link GencodeGtfFeature}. */ @VisibleForTesting List<GencodeGtfFeature> getAllFeatures() { final List<GencodeGtfFeature> list = new ArrayList<>(); list.add(this); return list; } /** * Serializes the base data in {@link GencodeGtfFeature} to a string. * @return a {@link String} representing this {@link GencodeGtfFeature} */ private String serializeToStringHelper() { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( baseData.genomicPosition.getContig() ); stringBuilder.append( '\t' ); stringBuilder.append( baseData.annotationSource ); stringBuilder.append( '\t' ); stringBuilder.append( baseData.featureType ); stringBuilder.append( '\t' ); stringBuilder.append( baseData.genomicPosition.getStart() ); stringBuilder.append( '\t' ); stringBuilder.append( baseData.genomicPosition.getEnd() ); stringBuilder.append( "\t.\t" ); stringBuilder.append( baseData.genomicStrand ); stringBuilder.append( '\t' ); stringBuilder.append( baseData.genomicPhase ); stringBuilder.append( '\t' ); if ( baseData.geneId != null ) { stringBuilder.append("gene_id \""); stringBuilder.append(baseData.geneId); stringBuilder.append( "\"; " ); } if ( baseData.transcriptId != null) { stringBuilder.append("transcript_id \""); stringBuilder.append(baseData.transcriptId); stringBuilder.append( "\"; " ); } if ( baseData.geneType != null ) { stringBuilder.append("gene_type \""); stringBuilder.append(baseData.geneType); stringBuilder.append( "\"; " ); } if ( baseData.geneStatus != null ) { stringBuilder.append("gene_status \""); stringBuilder.append(baseData.geneStatus); stringBuilder.append( "\"; " ); } if ( baseData.geneName != null ) { stringBuilder.append("gene_name \""); stringBuilder.append(baseData.geneName); stringBuilder.append( "\"; " ); } if ( baseData.transcriptType != null ) { stringBuilder.append("transcript_type \""); stringBuilder.append(baseData.transcriptType); stringBuilder.append( "\"; " ); } if ( baseData.transcriptStatus != null ) { stringBuilder.append("transcript_status \""); stringBuilder.append(baseData.transcriptStatus); stringBuilder.append( "\"; " ); } if ( baseData.transcriptName != null ) { stringBuilder.append("transcript_name \""); stringBuilder.append(baseData.transcriptName); stringBuilder.append( "\"; " ); } if ( baseData.exonNumber != NO_EXON_NUMBER ) { stringBuilder.append("exon_number "); stringBuilder.append(baseData.exonNumber); stringBuilder.append( "; " ); } if ( baseData.exonId != null) { stringBuilder.append("exon_id \""); stringBuilder.append(baseData.exonId); stringBuilder.append( "\"; "); } if (baseData.locusLevel != null) { stringBuilder.append("level "); stringBuilder.append(baseData.locusLevel); stringBuilder.append("; "); } // = = = = = = = = = = = = = = = = = = = = = = = // Output our optional fields: stringBuilder.append( baseData.optionalFields.stream().map(Object::toString).collect(Collectors.joining(" ")) ); if ( baseData.anonymousOptionalFields != null ) { stringBuilder.append(baseData.anonymousOptionalFields); } return stringBuilder.toString().trim(); } /** * Serializes all data in {@link GencodeGtfFeature} to a string. * This includes all subfields of child classes. * @return a {@link String} representing this {@link GencodeGtfFeature} */ public String serializeToString() { final StringBuilder stringBuilder = new StringBuilder(); final List<GencodeGtfFeature> features = getAllFeatures(); Collections.sort( features ); for ( final GencodeGtfFeature feature : features ) { stringBuilder.append( feature.serializeToStringHelper() ); stringBuilder.append("\n"); } return stringBuilder.toString().trim(); } @Override public String toString() { return serializeToString(); } // ================================================================================================ public String getGtfSourceFileType() { return baseData.gtfSourceFileType; } public String getUcscGenomeVersion() { return ucscGenomeVersion; } public void setUcscGenomeVersion(final String ucscGenomeVersion) { this.ucscGenomeVersion = ucscGenomeVersion; } public SimpleInterval getGenomicPosition() { return baseData.genomicPosition; } public int getFeatureOrderNumber() { return baseData.featureOrderNumber; } public String getChromosomeName() { return baseData.genomicPosition.getContig(); } public String getAnnotationSource() { return baseData.annotationSource; } public FeatureType getFeatureType() { return baseData.featureType; } public int getGenomicStartLocation() { return baseData.genomicPosition.getStart(); } public int getGenomicEndLocation() { return baseData.genomicPosition.getEnd(); } public Strand getGenomicStrand() { return baseData.genomicStrand; } public GenomicPhase getGenomicPhase() { return baseData.genomicPhase; } public String getGeneId() { return baseData.geneId; } public String getTranscriptId() { return baseData.transcriptId; } public String getGeneType() { return baseData.geneType; } public String getGeneName() { return baseData.geneName; } public String getTranscriptType() { return baseData.transcriptType; } public String getTranscriptName() { return baseData.transcriptName; } public GeneTranscriptStatus getGeneStatus() { return baseData.geneStatus; } public GeneTranscriptStatus getTranscriptStatus() { return baseData.transcriptStatus; } public int getExonNumber() { return baseData.exonNumber; } public String getExonId() { return baseData.exonId; } public LocusLevel getLocusLevel() { return baseData.locusLevel; } public List<OptionalField<?>> getOptionalFields() { return baseData.optionalFields; } public String getAnonymousOptionalFields() { return baseData.anonymousOptionalFields; } public OptionalField<?> getOptionalField(final String key) { for (final OptionalField<?> optionalField : baseData.optionalFields) { if ( optionalField.getName().equals(key) ) { return optionalField; } } return null; } /** * Comparable interface implementation for {@link GencodeGtfFeature}. * * Order is determined by {@link GencodeGtfFeatureBaseData#featureOrderNumber} * * @param other {@link GencodeGtfFeature} to which to compare * @return -1 if this < other; 0 if this == other; 1 if this > other */ @Override public int compareTo(final GencodeGtfFeature other) { Utils.nonNull(other); return (baseData.featureOrderNumber - other.baseData.featureOrderNumber); } @Override public boolean equals(final Object that) { if (that == null) { return false; } else if ( this == that ) { return true; } boolean isEqual = that instanceof GencodeGtfFeature; if (isEqual) { final GencodeGtfFeature thatFeature = (GencodeGtfFeature) that; isEqual = Objects.equals(baseData, thatFeature.baseData); if ( isEqual ) { isEqual = ucscGenomeVersion.equals( thatFeature.getUcscGenomeVersion() ); } } return isEqual; } @Override public int hashCode() { return baseData != null ? baseData.hashCode() : 0; } /** * Checks if {@code other} is contained within this {@link GencodeGtfFeature}. * Comparison is made using {@link SimpleInterval#contains(Locatable)} ala {@link GencodeGtfFeatureBaseData#genomicPosition} * @param other {@link Locatable} of which to check the bounds. * @return true if {@code other} is contained within the bounds of this {@link GencodeGtfFeature}, false otherwise. */ public boolean contains(final Locatable other) { return baseData.genomicPosition.contains(other); } /** * Checks if {@code other} overlaps with this {@link GencodeGtfFeature}. * Comparison is made using {@link SimpleInterval#overlaps(Locatable)} ala {@link GencodeGtfFeatureBaseData#genomicPosition} * @param other {@link Locatable}-derived class of which to check the bounds. * @return true if {@code other} overlaps the bounds of this {@link GencodeGtfFeature}, false otherwise. */ public boolean overlaps(final Locatable other) { return baseData.genomicPosition.overlaps(other); } public void setFeatureOrderNumber(final int featureOrderNumber) { this.baseData.featureOrderNumber = featureOrderNumber; } // ================================================================================================ static public class OptionalField<T> { private String name; private T value; public OptionalField(final String name, final T value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public T getValue() { return value; } public void setValue(final T value) { this.value = value; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(name); sb.append(" "); // We need to do some formatting for the numbers / non-numbers in the field: final String valueString = value.toString(); if ( NUMBER_PATTERN.matcher(valueString).matches() ) { sb.append(valueString); sb.append(";"); } else { sb.append("\""); sb.append(valueString); sb.append("\";"); } return sb.toString(); } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override public boolean equals(final Object other) { if (other == null) { return false; } else if ( this == other ) { return true; } if ( !(other instanceof OptionalField) ) { return false; } final OptionalField<?> otherOptionalField = (OptionalField<?>) other; return (name.equals(otherOptionalField.name)) && (value.equals(otherOptionalField.value)); } } // ================================================================================================ // ================================================================================================ /** * Keyword identifying the source of the feature, like a program * (e.g. Augustus or RepeatMasker) or an organization (like TAIR). * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format */ public enum AnnotationSource { ENSEMBL, HAVANA, ena // From ENSEMBLE GTFs } /** * Type of the feature represented in a single line of a GENCODE GTF File. * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format */ public enum FeatureType { GENE("gene"){ public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { return GencodeGtfGeneFeature.create(baseData); } public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { return GencodeGtfGeneFeature.create(gtfFields, gtfFileType); } }, TRANSCRIPT("transcript"){ public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { return GencodeGtfTranscriptFeature.create(baseData); } public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { return GencodeGtfTranscriptFeature.create(gtfFields, gtfFileType); } }, SELENOCYSTEINE("Selenocysteine"){ public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { return GencodeGtfSelenocysteineFeature.create(baseData); } public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { return GencodeGtfSelenocysteineFeature.create(gtfFields, gtfFileType); } }, EXON("exon"){ public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { return GencodeGtfExonFeature.create(baseData); } public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { return GencodeGtfExonFeature.create(gtfFields, gtfFileType); } }, CDS("CDS"){ public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { return GencodeGtfCDSFeature.create(baseData); } public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { return GencodeGtfCDSFeature.create(gtfFields, gtfFileType); } }, START_CODON("start_codon"){ public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { return GencodeGtfStartCodonFeature.create(baseData); } public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { return GencodeGtfStartCodonFeature.create(gtfFields, gtfFileType); } }, STOP_CODON("stop_codon"){ public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { return GencodeGtfStopCodonFeature.create(baseData); } public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { return GencodeGtfStopCodonFeature.create(gtfFields, gtfFileType); } }, UTR("UTR"){ public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) { return GencodeGtfUTRFeature.create(baseData); } public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType) { return GencodeGtfUTRFeature.create(gtfFields, gtfFileType); } }; @SuppressWarnings("unchecked") private static final Map<String, FeatureType> VALUE_MAP = Arrays.stream(values()).collect(Collectors.toMap(v -> v.serialized.toLowerCase(), v -> v)); private final String serialized; FeatureType(final String serializedValue) { serialized = serializedValue; } @Override public String toString() { return serialized; } public static FeatureType getEnum(final String s) { final String lowerS = s.toLowerCase(); if ( VALUE_MAP.containsKey(lowerS) ){ return VALUE_MAP.get(lowerS); } throw new IllegalArgumentException("Unexpected value: " + s); } /** * Create a {@link GencodeGtfFeature} of this type given {@code baseData} * @param baseData The data to use to create a {@link GencodeGtfFeature} * @return The {@link GencodeGtfFeature} represented by the given {@code baseData} */ abstract public GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData); /** * Create a {@link GencodeGtfFeature} of this type given {@code gtfFields} * @param gtfFields The data to use to create a {@link GencodeGtfFeature} * @param gtfFileType A {@link String} containing the file type of the GTF data that created this {@link GencodeGtfFeature}. * @return The {@link GencodeGtfFeature} represented by the given {@code gtfFields} */ abstract public GencodeGtfFeature create(final String[] gtfFields, final String gtfFileType); } /** * Whether the first base of the CDS segment is the first (frame 0), second (frame 1) or third (frame 2) \ * in the codon of the ORF. * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format */ public enum GenomicPhase { ZERO("0"), ONE ("1"), TWO ("2"), DOT ("."); @SuppressWarnings("unchecked") private static final Map<String, GenomicPhase> VALUE_MAP = Arrays.stream(values()).collect(Collectors.toMap(v -> v.serialized.toLowerCase(), v -> v)); private final String serialized; GenomicPhase(final String serializedValue) { serialized = serializedValue; } @Override public String toString() { return serialized; } public static GenomicPhase getEnum(final String s) { final String lowerS = s.toLowerCase(); if ( VALUE_MAP.containsKey(lowerS) ){ return VALUE_MAP.get(lowerS); } throw new IllegalArgumentException("Unexpected value: " + s); } } /** * Biotype / transcript type for the transcript or gene represented in a feature. * This is a tag of some biological function associated with a feature. * * The values here are not exhaustive, but should be used as a reference for already used / known types. * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format */ public enum KnownGeneBiotype { // Immunoglobulin (Ig) variable chain and T-cell receptor (TcR) genes imported or annotated according to the IMGT (http://www.imgt.org/) IG_C_GENE("IG_C_gene"), IG_D_GENE("IG_D_gene"), IG_J_GENE("IG_J_gene"), IG_LV_GENE("IG_LV_gene"), IG_V_GENE("IG_V_gene"), TR_C_GENE("TR_C_gene"), TR_J_GENE("TR_J_gene"), TR_V_GENE("TR_V_gene"), TR_D_GENE("TR_D_gene"), // Inactivated immunoglobulin gene. IG_PSEUDOGENE("IG_pseudogene"), IG_C_PSEUDOGENE("IG_C_pseudogene"), IG_J_PSEUDOGENE("IG_J_pseudogene"), IG_V_PSEUDOGENE("IG_V_pseudogene"), TR_V_PSEUDOGENE("TR_V_pseudogene"), TR_J_PSEUDOGENE("TR_J_pseudogene"), // Non-coding RNA predicted using sequences from Rfam (http://rfam.xfam.org/) and miRBase (http://www.mirbase.org/) MT_RRNA("Mt_rRNA"), MT_TRNA("Mt_tRNA"), MIRNA("miRNA"), MISC_RNA("misc_RNA"), RRNA("rRNA"), SCRNA("scRNA"), SNRNA("snRNA"), SNORNA("snoRNA"), RIBOZYME("ribozyme"), SRNA("sRNA"), SCARNA("scaRNA"), // ENSEMBL-Specific values: TRNA("tRNA"), TMRNA("tmRNA"), // Non-coding RNA predicted to be pseudogene by the Ensembl pipeline MT_TRNA_PSEUDOGENE("Mt_tRNA_pseudogene"), TRNA_PSEUDOGENE("tRNA_pseudogene"), SNORNA_PSEUDOGENE("snoRNA_pseudogene"), SNRNA_PSEUDOGENE("snRNA_pseudogene"), SCRNA_PSEUDOGENE("scRNA_pseudogene"), RRNA_PSEUDOGENE("rRNA_pseudogene"), MISC_RNA_PSEUDOGENE("misc_RNA_pseudogene"), MIRNA_PSEUDOGENE("miRNA_pseudogene"), // To be Experimentally Confirmed. This is used for non-spliced EST clusters that have polyA features. This category has been specifically created for the ENCODE project to highlight regions that could indicate the presence of protein coding genes that require experimental validation, either by 5' RACE or RT-PCR to extend the transcripts, or by confirming expression of the putatively-encoded peptide with specific antibodies. TEC("TEC"), // If the coding sequence (following the appropriate reference) of a transcript finishes >50bp from a downstream splice site then it is tagged as NMD. If the variant does not cover the full reference coding sequence then it is annotated as NMD if NMD is unavoidable i.e. no matter what the exon structure of the missing portion is the transcript will be subject to NMD. NONSENSE_MEDIATED_DECAY("nonsense_mediated_decay"), // Transcript that has polyA features (including signal) without a prior stop codon in the CDS, i.e. a non-genomic polyA tail attached directly to the CDS without 3' UTR. These transcripts are subject to degradation. NON_STOP_DECAY("non_stop_decay"), // Alternatively spliced transcript believed to contain intronic sequence relative to other, coding, variants. RETAINED_INTRON("retained_intron"), // Contains an open reading frame (ORF). PROTEIN_CODING("protein_coding"), // Doesn't contain an ORF. PROCESSED_TRANSCRIPT("processed_transcript"), // Transcript which is known from the literature to not be protein coding. NON_CODING("non_coding"), // Transcript believed to be protein coding, but with more than one possible open reading frame. AMBIGUOUS_ORF("ambiguous_orf"), // Long non-coding transcript in introns of a coding gene that does not overlap any exons. SENSE_INTRONIC("sense_intronic"), // Long non-coding transcript that contains a coding gene in its intron on the same strand. SENSE_OVERLAPPING("sense_overlapping"), // Has transcripts that overlap the genomic span (i.e. exon or introns) of a protein-coding locus on the opposite strand. ANTISENSE("antisense"), ANTISENSE_RNA("antisense_RNA"), KNOWN_NCRNA("known_ncrna"), // Have homology to proteins but generally suffer from a disrupted coding sequence and an active homologous gene can be found at another locus. Sometimes these entries have an intact coding sequence or an open but truncated ORF, in which case there is other evidence used (for example genomic polyA stretches at the 3' end) to classify them as a pseudogene. Can be further classified as one of the following. PSEUDOGENE("pseudogene"), // Pseudogene that lack introns and is thought to arise from reverse transcription of mRNA followed by reinsertion of DNA into the genome. PROCESSED_PSEUDOGENE("processed_pseudogene"), // Pseudogene owing to a SNP/DIP but in other individuals/haplotypes/strains the gene is translated. POLYMORPHIC_PSEUDOGENE("polymorphic_pseudogene"), // Pseudogene owing to a reverse transcribed and re-inserted sequence. RETROTRANSPOSED("retrotransposed"), // Pseudogene where protein homology or genomic structure indicates a pseudogene, but the presence of locus-specific transcripts indicates expression. TRANSCRIBED_PROCESSED_PSEUDOGENE("transcribed_processed_pseudogene"), TRANSCRIBED_UNPROCESSED_PSEUDOGENE("transcribed_unprocessed_pseudogene"), TRANSCRIBED_UNITARY_PSEUDOGENE("transcribed_unitary_pseudogene"), // Pseudogene that has mass spec data suggesting that it is also translated. TRANSLATED_PROCESSED_PSEUDOGENE("translated_processed_pseudogene"), TRANSLATED_UNPROCESSED_PSEUDOGENE("translated_unprocessed_pseudogene"), // A species specific unprocessed pseudogene without a parent gene, as it has an active orthologue in another species. UNITARY_PSEUDOGENE("unitary_pseudogene"), // Pseudogene that can contain introns since produced by gene duplication. UNPROCESSED_PSEUDOGENE("unprocessed_pseudogene"), // Used to tag mistakes in the public databases (Ensembl/SwissProt/Trembl) ARTIFACT("artifact"), // Long, intervening noncoding (linc) RNA that can be found in evolutionarily conserved, intergenic regions. LINCRNA("lincRNA"), LNCRNA("lncRNA"), // Unspliced lncRNA that is several kb in size. MACRO_LNCRNA("macro_lncRNA"), // Transcript where ditag and/or published experimental data strongly supports the existence of short non-coding transcripts transcribed from the 3'UTR. THREE_PRIME_OVERLAPPING_NCRNA("3prime_overlapping_ncRNA"), // Otherwise viable coding region omitted from this alternatively spliced transcript because the splice variation affects a region coding for a protein domain. DISRUPTED_DOMAIN("disrupted_domain"), // Short non coding RNA gene that forms part of the vault ribonucleoprotein complex. VAULTRNA("vaultRNA"), // A non-coding locus that originates from within the promoter region of a protein-coding gene, with transcription proceeding in the opposite direction on the other strand. BIDIRECTIONAL_PROMOTER_LNCRNA("bidirectional_promoter_lncRNA"); @SuppressWarnings("unchecked") private static final Map<String, KnownGeneBiotype> VALUE_MAP = Arrays.stream(values()).collect(Collectors.toMap(v -> v.serialized.toLowerCase(), v -> v)); private final String serialized; KnownGeneBiotype(final String serializedValue) { serialized = serializedValue; } @Override public String toString() { return serialized; } private static final Map<String, String> SPECIAL_CASE_STRING_VALUE_MAP = createSpecialCaseMap(); public static KnownGeneBiotype getEnum(final String s) { String lowerS = s.toLowerCase(); // Handle special cases: lowerS = SPECIAL_CASE_STRING_VALUE_MAP.getOrDefault(lowerS, lowerS); if ( VALUE_MAP.containsKey(lowerS) ){ return VALUE_MAP.get(lowerS); } throw new IllegalArgumentException("Unexpected value: " + s); } /** * Create a special case map for alternate field names for known {@link KnownGeneBiotype}s. */ private static Map<String, String> createSpecialCaseMap() { final Map<String, String> map = new HashMap<>(); // From ENSEMBLE GTF files: map.put("ncrna", "non_coding"); return map; } } /** * Indication of whether a feature is new, tenatative, or already known. * * This attribute was removed after release 25. * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format */ public enum GeneTranscriptStatus { KNOWN, NOVEL, PUTATIVE } /** * Status of how a position was annotated / verified: * * 1 - verified locus * 2 - manually annotated locus * 3 - automatically annotated locus * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format */ public enum LocusLevel { /** Verified locus */ VERIFIED("1"), /** Manually annotated locus */ MANUALLY_ANNOTATED("2"), /** Automatically annotated locus */ AUTOMATICALLY_ANNOTATED("3"); @SuppressWarnings("unchecked") private static final Map<String, LocusLevel> VALUE_MAP = Arrays.stream(values()).collect(Collectors.toMap(v -> v.serialized.toLowerCase(), v -> v)); private final String serialized; LocusLevel(final String serializedValue) { serialized = serializedValue; } @Override public String toString() { return serialized; } public static LocusLevel getEnum(final String s) { final String lowerS = s.toLowerCase(); if ( VALUE_MAP.containsKey(lowerS) ){ return VALUE_MAP.get(lowerS); } throw new IllegalArgumentException("Unexpected value: " + s); } } /** * Additional relevant information appended to a feature. * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format * https://www.gencodegenes.org/pages/tags.html */ public enum FeatureTag { /** 3' end extended based on RNA-seq data. */ THREE_PRIME_NESTED_SUPPORTED_EXTENSION("3_nested_supported_extension"), /** 3' end extended based on RNA-seq data. */ THREE_PRIME_STANDARD_SUPPORTED_EXTENSION("3_standard_supported_extension"), /** annotated based on RNA-seq data. */ FOURFIVEFOUR_RNA_SEQ_SUPPORTED("454_RNA_Seq_supported"), /** 5' end extended based on RNA-seq data. */ FIVE_PRIME_NESTED_SUPPORTED_EXTENSION("5_nested_supported_extension"), /** 5' end extended based on RNA-seq data. */ FIVE_PRIME_STANDARD_SUPPORTED_EXTENSION("5_standard_supported_extension"), /** shares an identical CDS but has alternative 5' UTR with respect to a reference variant. */ ALTERNATIVE_3_UTR("alternative_3_UTR"), /** shares an identical CDS but has alternative 3' UTR with respect to a reference variant. */ ALTERNATIVE_5_UTR("alternative_5_UTR"), // -------------------------------------------------------------------------------------------------------- // Please note that the ordering of the APPRIS_* tags is also used in sorting here. Do not re-order! // -------------------------------------------------------------------------------------------------------- /** Transcript expected to code for the main functional isoform based on a range of protein features (APPRIS pipeline). */ APPRIS_PRINCIPAL("appris_principal"), /** (This flag corresponds to the older flag "appris_principal") Where the transcript expected to code for the main */ APPRIS_PRINCIPAL_1("appris_principal_1"), /** (This flag corresponds to the older flag "appris_candidate_ccds") Where the APPRIS core modules are unable to choose a */ APPRIS_PRINCIPAL_2("appris_principal_2"), /** Where the APPRIS core modules are unable to choose a clear principal variant and there more than one of the variants */ APPRIS_PRINCIPAL_3("appris_principal_3"), /** (This flag corresponds to the Ensembl 78 flag "appris_candidate_longest_ccds") Where the APPRIS core modules are unable */ APPRIS_PRINCIPAL_4("appris_principal_4"), /** (This flag corresponds to the Ensembl 78 flag "appris_candidate_longest_seq") Where the APPRIS core modules are unable */ APPRIS_PRINCIPAL_5("appris_principal_5"), /** Candidate transcript(s) models that are conserved in at least three tested non-primate species. */ APPRIS_ALTERNATIVE_1("appris_alternative_1"), /** Candidate transcript(s) models that appear to be conserved in fewer than three tested non-primate species. */ APPRIS_ALTERNATIVE_2("appris_alternative_2"), /** where there is no 'appris_principal' variant, the candidate with highest APPRIS score is selected as the primary */ APPRIS_CANDIDATE_HIGHEST_SCORE("appris_candidate_highest_score"), /** the "appris_candidate" transcripts where there are several CCDS, in this case APPRIS labels the longest CCDS. */ APPRIS_CANDIDATE_LONGEST_CCDS("appris_candidate_longest_ccds"), /** the "appris_candidate" transcript that has an unique CCDS. */ APPRIS_CANDIDATE_CCDS("appris_candidate_ccds"), /** where there is no "appris_candidate_ccds" or "appris_candidate_longest_ccds" variant, the longest protein of the */ APPRIS_CANDIDATE_LONGEST_SEQ("appris_candidate_longest_seq"), /** where there is no 'appris_principal' variant, the longest of the 'appris_candidate' variants is selected as the primary */ APPRIS_CANDIDATE_LONGEST("appris_candidate_longest"), /** where there is no single 'appris_principal' variant the main functional isoform will be translated from one of the */ APPRIS_CANDIDATE("appris_candidate"), /** identifies a subset of representative transcripts for each gene; prioritises full-length protein coding transcripts */ BASIC("basic"), /** Transcript contains two confidently annotated CDSs. Support may come from eg proteomic data, cross-species conservation */ BICISTRONIC("bicistronic"), /** Transcript 5' end overlaps ENCODE or Fantom CAGE cluster. */ CAGE_SUPPORTED_TSS("CAGE_supported_TSS"), /** member of the consensus CDS gene set, confirming coding regions between ENSEMBL, UCSC, NCBI and HAVANA. */ CCDS("CCDS"), /** The coding region end could not be confirmed. */ CDS_END_NF("cds_end_NF"), /** The coding region start could not be confirmed. */ CDS_START_NF("cds_start_NF"), /** Transcript QC checked using dotplot to identify features eg splice junctions, end of homology. */ DOTTER_CONFIRMED("dotter_confirmed"), /** an upstream ATG is used where a downstream ATG seems more evolutionary conserved. */ DOWNSTREAM_ATG("downstream_ATG"), /** Transcript was tested and confirmed experimentally. */ EXP_CONF("exp_conf"), /** locus consists of non-overlapping transcript fragments either because of genome assembly issues (i.e., gaps or */ FRAGMENTED_LOCUS("fragmented_locus"), /** Transcript model contains all possible in-frame exons supported by homology, experimental evidence or conservation, but */ INFERRED_EXON_COMBINATION("inferred_exon_combination"), /** Transcript model is not supported by a single piece of transcript evidence. May be supported by multiple fragments of */ INFERRED_TRANSCRIPT_MODEL("inferred_transcript_model"), /** Transcript supported by transcript evidence that, while ampping best-in-genome, shows regions of poor sequence quality. */ LOW_SEQUENCE_QUALITY("low_sequence_quality"), /** the mRNA end could not be confirmed. */ MRNA_END_NF("mRNA_end_NF"), /** the mRNA start could not be confirmed. */ MRNA_START_NF("mRNA_start_NF"), /** the transcript belongs to the MANE Select data set. The Matched Annotation from NCBI and EMBL-EBI project (MANE) is a collaboration between Ensembl-GENCODE and RefSeq to select a default transcript per human protein coding locus that is representative of biology, well-supported, expressed and conserved. This transcript set matches GRCh38 and is 100% identical between RefSeq and Ensembl-GENCODE for 5' UTR, CDS, splicing and 3' UTR. */ MANE_SELECT("MANE_Select"), /** in-frame type of variation where, at the acceptor site, some variants splice after the first AG and others after the */ NAGNAG_SPLICE_SITE("NAGNAG_splice_site"), /** the locus is a host for small non-coding RNAs. */ NCRNA_HOST("ncRNA_host"), /** annotated based on RNA-seq data. */ NESTED_454_RNA_SEQ_SUPPORTED("nested_454_RNA_Seq_supported"), /** the transcript looks like it is subject to NMD but publications, experiments or conservation support the translation of */ NMD_EXCEPTION("NMD_exception"), /** codon if the transcript were longer but cannot currently be annotated as NMD as does not fulfil all criteria - most */ NMD_LIKELY_IF_EXTENDED("NMD_likely_if_extended"), /** the CDS has a non-ATG start and its validity is supported by publication or conservation. */ NON_ATG_START("non_ATG_start"), /** the transcript has a non-canonical splice site conserved in other species. */ NON_CANONICAL_CONSERVED("non_canonical_conserved"), /** the transcript has a non-canonical splice site explained by a genomic sequencing error. */ NON_CANONICAL_GENOME_SEQUENCE_ERROR("non_canonical_genome_sequence_error"), /** the transcript has a non-canonical splice site explained by other reasons. */ NON_CANONICAL_OTHER("non_canonical_other"), /** the transcript has a non-canonical splice site explained by a SNP. */ NON_CANONICAL_POLYMORPHISM("non_canonical_polymorphism"), /** the transcript has a non-canonical splice site that needs experimental confirmation. */ NON_CANONICAL_TEC("non_canonical_TEC"), /** the transcript has a non-canonical splice site explained by a U12 intron (i.e. AT-AC splice site). */ NON_CANONICAL_U12("non_canonical_U12"), /** a splice variant for which supporting evidence has not been submitted to databases, i.e. the model is based on */ NON_SUBMITTED_EVIDENCE("non_submitted_evidence"), /** a transcript is supported by evidence from same species paralogous loci. */ NOT_BEST_IN_GENOME_EVIDENCE("not_best_in_genome_evidence"), /** evidence from other species was used to build model. */ NOT_ORGANISM_SUPPORTED("not_organism_supported"), /** protein-coding locus with no paralogues or orthologs. */ ORPHAN("orphan"), /** exon(s) of the locus overlap exon(s) of a readthrough transcript or a transcript belonging to another locus. */ OVERLAPPING_LOCUS("overlapping_locus"), /** a low confidence upstream ATG existing in other coding variant would lead to NMD in this trancript, that uses the high */ OVERLAPPING_UORF("overlapping_uORF"), /** annotation in the pseudo-autosomal region, which is duplicated between chromosomes X and Y. */ PAR("PAR"), /** member of the pseudogene set predicted by YALE, UCSC and HAVANA. */ PSEUDO_CONSENS("pseudo_consens"), /** a transcript that overlaps two or more independent loci but is considered to belong to a third, separate locus. */ READTHROUGH_TRANSCRIPT("readthrough_transcript"), /** locus overlaps a sequence error or an assembly error in the reference genome that affects its annotation (e.g., 1 or */ REFERENCE_GENOME_ERROR("reference_genome_error"), /** internal intron of CDS portion of transcript is retained. */ RETAINED_INTRON_CDS("retained_intron_CDS"), /** final intron of CDS portion of transcript is retained. */ RETAINED_INTRON_FINAL("retained_intron_final"), /** first intron of CDS portion of transcript is retained. */ RETAINED_INTRON_FIRST("retained_intron_first"), /** protein-coding locus created via retrotransposition. */ RETROGENE("retrogene"), /** Transcript supported by RNAseq data and not supported by mRNA or EST evidence. */ RNA_SEQ_SUPPORTED_ONLY("RNA_Seq_supported_only"), /** Transcript annotated based on mixture of RNA-seq data and EST/mRNA/protein evidence. */ RNA_SEQ_SUPPORTED_PARTIAL("RNA_Seq_supported_partial"), /** Transcript that contains a CDS that has a translation initiation site supported by Ribosomal Profiling data. */ RP_SUPPORTED_TIS("RP_supported_TIS"), /** contains a selenocysteine. */ SELENO("seleno"), /** a processed pseudogene with one or more introns still present. These are likely formed through the retrotransposition */ SEMI_PROCESSED("semi_processed"), /** Transcript contains at least 1 non-canonical splice junction that is associated with a known or novel genome sequence */ SEQUENCE_ERROR("sequence_error"), /** Transcript whose coding sequence contains an internal stop codon that does not cause the translation termination. */ STOP_CODON_READTHROUGH("stop_codon_readthrough"), /** Transcript created or extended using assembled RNA-seq long reads. */ TAGENE("TAGENE"), /** an upstream ATG exists when a downstream ATG is better supported. */ UPSTREAM_ATG("upstream_ATG"), /** a low confidence upstream ATG existing in other coding variant would lead to NMD in this trancript, that uses the high */ UPSTREAM_UORF("upstream_uORF"); @SuppressWarnings("unchecked") private static final Map<String, FeatureTag> VALUE_MAP = Arrays.stream(values()).collect(Collectors.toMap(v -> v.serialized.toLowerCase(), v -> v)); private final String serialized; FeatureTag(final String serializedValue) { serialized = serializedValue; } @Override public String toString() { return serialized; } public static FeatureTag getEnum(final String s) { final String lowerS = s.toLowerCase(); if ( VALUE_MAP.containsKey(lowerS) ){ return VALUE_MAP.get(lowerS); } throw new IllegalArgumentException("Unexpected value: " + s); } } /** * Transcript score according to how well mRNA and EST alignments match over its full length. * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format */ public enum TranscriptSupportLevel { /** all splice junctions of the transcript are supported by at least one non-suspect mRNA */ ALL_MRNA_VERIFIED("1"), /** the best supporting mRNA is flagged as suspect or the support is from multiple ESTs */ BEST_MRNA_SUSPECT("2"), /** the only support is from a single EST */ SINGLE_EST_SUPPORT("3"), /** the best supporting EST is flagged as suspect */ BEST_EST_SUSPECT("4"), /** no single transcript supports the model structure */ NO_SINGLE_TRANSCRIPT_SUPPORT("5"), /** the transcript was not analyzed */ NA("NA"); @SuppressWarnings("unchecked") private static final Map<String, TranscriptSupportLevel> VALUE_MAP = Arrays.stream(values()).collect(Collectors.toMap(v -> v.serialized.toLowerCase(), v -> v)); private final String serialized; TranscriptSupportLevel(final String serializedValue) { serialized = serializedValue; } @Override public String toString() { return serialized; } public static TranscriptSupportLevel getEnum(final String s) { final String lowerS = s.toLowerCase(); if ( VALUE_MAP.containsKey(lowerS) ){ return VALUE_MAP.get(lowerS); } throw new IllegalArgumentException("Unexpected value: " + s); } } /** * Attribute that indicates the status of the mapping. * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format * http://www.gencodegenes.org/releases/grch37_mapped_releases.html#attrib */ public enum RemapStatus { /** * Gene or transcript completely mapped to the target genome with all features intact. */ FULL_CONTIG("full_contig"), /** * Gene or transcript completely mapped to the target genome with insertions in some features. These are usually small insertions. */ FULL_FRAGMENT("full_fragment"), /** * Gene or transcript partially mapped to the target genome. */ PARTIAL("partial"), /** * Gene or transcript did not map to the target genome. */ DELETED("deleted"), /** * The source sequence is not in the assembly alignments. This will occur with alt loci genes if the alignments only contain the primary assembly. */ NO_SEQ_MAP("no_seq_map"), /** * Transcripts in the gene mapped to multiple locations. */ GENE_CONFLICT("gene_conflict"), /** * Transcripts caused gene length to change by more than 50%. This is to detect mapping to processed pseudogenes and mapping across tandem gene duplications. */ GENE_SIZE_CHANGE("gene_size_change"), /** * Gene is from a small, automatic (ENSEMBL source) non-coding RNA. Taken from the target annotation. */ AUTOMATIC_SMALL_NCRNA_GENE("automatic_small_ncrna_gene"), /** * Gene is from an automatic process (ENSEMBL source). Taken from the target annotation. */ AUTOMATIC_GENE("automatic_gene"), /** * Pseudogene annotations (excluding polymorphic). */ PSEUDOGENE("pseudogene"); @SuppressWarnings("unchecked") private static final Map<String, RemapStatus> VALUE_MAP = Arrays.stream(values()).collect(Collectors.toMap(v -> v.serialized.toLowerCase(), v -> v)); private final String serialized; RemapStatus(final String serializedValue) { serialized = serializedValue; } @Override public String toString() { return serialized; } public static RemapStatus getEnum(final String s) { final String lowerS = s.toLowerCase(); if ( VALUE_MAP.containsKey(lowerS) ){ return VALUE_MAP.get(lowerS); } throw new IllegalArgumentException("Unexpected value: " + s); } } /** * Attribute that compares the mapping to the existing target annotations. * * For more information, see: * https://www.gencodegenes.org/data_format.html * https://en.wikipedia.org/wiki/General_feature_format * http://www.gencodegenes.org/releases/grch37_mapped_releases.html#attrib */ public enum RemapTargetStatus { /** * Gene or transcript was not in target annotations. */ NEW("new"), /** * Gene or transcript exists in source and target genome, however source was not mapped. */ LOST("lost"), /** * Gene or transcript overlaps previous version of annotation on target genome. */ OVERLAP("overlap"), /** * Gene or transcript exists in target, however source mapping is to a different location. This is often mappings to a gene family members or pseudogenes. */ NONOVERLAP("nonOverlap"); @SuppressWarnings("unchecked") private static final Map<String, RemapTargetStatus> VALUE_MAP = Arrays.stream(values()).collect(Collectors.toMap(v -> v.serialized.toLowerCase(), v -> v)); private final String serialized; RemapTargetStatus(final String serializedValue) { serialized = serializedValue; } @Override public String toString() { return serialized; } public static RemapTargetStatus getEnum(final String s) { final String lowerS = s.toLowerCase(); if ( VALUE_MAP.containsKey(lowerS) ){ return VALUE_MAP.get(lowerS); } throw new IllegalArgumentException("Unexpected value: " + s); } } }
{ "content_hash": "4b3d2248d20265de2e1c7903a44462e6", "timestamp": "", "source": "github", "line_count": 1579, "max_line_length": 449, "avg_line_length": 40.74414186193793, "alnum_prop": 0.6142379731095049, "repo_name": "broadinstitute/hellbender", "id": "c9711d247abc93f99e8d4b1d7fa33af0e2b4bff5", "size": "64335", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/broadinstitute/hellbender/utils/codecs/gtf/GencodeGtfFeature.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1878" }, { "name": "C++", "bytes": "60687" }, { "name": "Java", "bytes": "7458782" }, { "name": "Python", "bytes": "10963" }, { "name": "R", "bytes": "27481" }, { "name": "Shell", "bytes": "11688" } ], "symlink_target": "" }
A small rails app for serving up information from [The Big Lebowski](http://en.wikipedia.org/wiki/The_Big_Lebowski) ## Routes ``` /api/script /api/quotes/random /api/quotes/search?term=that+poor+woman /api/quotes/:id /api/lines/search?term=mountain /api/lines/random /api/lines/:id /api/search?term=mountain # alias for /api/quotes/search ``` ## Text format Append `.txt` to several routes to receive a text format ``` /api/quotes/random.txt /api/quotes/search.txt?term=that+poor+woman /api/quotes/:id.txt /api/lines/search.txt?term=mountain /api/lines/random.txt /api/lines/:id.txt /api/search.txt?term=mountain # alias for /api/quotes/search ``` ## Random quotes and searching by character name ``` /api/quotes/random.txt?character=Bunny /api/quotes/random.txt?character=The+Dude /api/lines/random.txt?character=The+Dude /api/lines/search.txt?term=objects&character=The+Dude ``` ## Using cURL ```bash $ curl -L http://lebowski.me ``` ## CLI client [lebowski](https://github.com/aackerman/lebowski) ```bash $ npm i -g lebowski ``` ## Author | [![twitter/_aaronackerman_](http://gravatar.com/avatar/c73ff9c7e654647b2b339d9e08b52143?s=70)](http://twitter.com/_aaronackerman_ "Follow @_aaronackerman_ on Twitter") | |---| | [Aaron Ackerman](https://twitter.com/_aaronackerman_) |
{ "content_hash": "3a05ca2ae7ac31ee1d8b7fd2b404e3d0", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 171, "avg_line_length": 22.666666666666668, "alnum_prop": 0.7291021671826625, "repo_name": "aackerman/lebowski-api", "id": "0c6aeea6e6e84ac875e66b58d8703520c62a96f5", "size": "1589", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "198" }, { "name": "Ruby", "bytes": "33844" }, { "name": "Shell", "bytes": "1080" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"> <android.support.design.widget.AppBarLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <TextView android:id="@+id/txt_welcome" android:layout_marginTop="50dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello" android:textSize="22sp"/> <TextView android:id="@+id/txt_temperature_value" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="60sp" android:paddingTop="75dp" android:layout_gravity="center" android:paddingBottom="25dp"/> <TextView android:id="@+id/txt_temperature_name" android:text="@string/title_temperature" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:layout_gravity="center" android:paddingBottom="25dp"/> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" /> </android.support.design.widget.CoordinatorLayout>
{ "content_hash": "c2f2f5de88a5b6ff73a99bba616057f0", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 100, "avg_line_length": 42.26, "alnum_prop": 0.689540937056318, "repo_name": "relayr/blog", "id": "5f7c521603d848acab6b21ab71378e3d4dc03c47", "size": "2113", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidApp/Myfirstandroid/app/src/main/res/layout/activity_main.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "21461" }, { "name": "C++", "bytes": "13026" }, { "name": "CSS", "bytes": "20382" }, { "name": "HTML", "bytes": "60321" }, { "name": "Java", "bytes": "12736" }, { "name": "JavaScript", "bytes": "474339" } ], "symlink_target": "" }
require_relative "../lib/fx_rates" require 'minitest/autorun' require 'minitest/unit' require 'minitest/pride'
{ "content_hash": "f99ad304b8e0ef1839a34667644fe582", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 34, "avg_line_length": 27.75, "alnum_prop": 0.7747747747747747, "repo_name": "overture8/fx_rates", "id": "1ec8407cedb702edeaf21896ef1d8ffd71420d91", "size": "111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "11744" } ], "symlink_target": "" }
using UnityEngine; using UnityEngine.Networking; using System.Collections; public class GameSceneMultiplayer { /* public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) { Debug.Log ("Player Connected: " + conn.address); //var player = (GameObject)GameObject.Instantiate(null, Vector3.zero, Quaternion.identity); //NetworkServer.AddPlayerForConnection(conn, player, playerControllerId); } */ }
{ "content_hash": "f1ed62ad637c264290d55bedce67c60a", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 93, "avg_line_length": 29.4, "alnum_prop": 0.780045351473923, "repo_name": "GameWorthy/G1", "id": "c4fa0c27ea954d98a04846c32966d4c9daf9b4c7", "size": "443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/Multiplayer/GameSceneMultiplayer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "89159" }, { "name": "C++", "bytes": "2798" }, { "name": "GLSL", "bytes": "886" }, { "name": "Java", "bytes": "759" }, { "name": "Objective-C", "bytes": "27754" } ], "symlink_target": "" }
{% extends 'home.base.html' %} {% load staticfiles %} {% load i18n %} {% block head %} <link href="{% static 'css/home.css' %}" rel="stylesheet"> {% endblock head %} {% block title %}LOUDERdEV | Web Dev{% endblock %} {% block body %} <!-- Main --> <div id="main" class="wrapper style1"> <div class="container"> <header class="major"> <h2>Web Development</h2> <p>Web Development in Python Django, ASP.NET, or Wordpress CMS</p> </header> <!-- Content --> <section id="content"> <a class="image fit"><img src="{% static 'img/code.png' %}" alt="" /></a> <h3 class="centerElement">San Juan Health District</h3> <p>San Juan Health Service District is a small hospital and two clinics that were in need of a new website to help show a more professional presence to locals and visitors of southeastern Utah.</p> <p>I implemented a new website, leveraging WordPress and front-end web languages to transform a 30+ page site to what it is today, including online job form and other online form submissions from the previous paper or fax alternatives.</p> <p class="centerElement"> <a href="https://sjhsd.org/" class="button">View San Juan Health District</a> </p> <br> <h3 class="centerElement">BYU AIS</h3> <p>The BYU AIS club previously had a Python Django implementation but because the site didn’t need to have any business logic, I decided to simplify the site to a Wordpress implementation. Through using the CMS and basic HTML, CSS, and JS, I was able to make the site more simple to manage, especially for quick edits, as the owner of the site is constantly changing.</p> <p class="centerElement"> <a href="http://ais.byu.edu/" class="button">View BYU AIS</a> </p> <br> </section> </div> </div> {% endblock body %}
{ "content_hash": "4bcb77ba25c0b44e161f6ad1b60c8452", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 387, "avg_line_length": 42.87755102040816, "alnum_prop": 0.581151832460733, "repo_name": "drakeloud/louderdev", "id": "a2f86ab7ae8ffb53a9738d72c495a68a68604560", "size": "2103", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "louderdev/home/templates/home/web-development.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "156059" }, { "name": "HTML", "bytes": "176563" }, { "name": "JavaScript", "bytes": "120049" }, { "name": "Python", "bytes": "168254" }, { "name": "Shell", "bytes": "4206" } ], "symlink_target": "" }
import os from airflow import models from airflow.providers.google.cloud.transfers.sheets_to_gcs import GoogleSheetsToGCSOperator from airflow.providers.google.suite.transfers.gcs_to_sheets import GCSToGoogleSheetsOperator from airflow.utils.dates import days_ago BUCKET = os.environ.get("GCP_GCS_BUCKET", "example-test-bucket3") SPREADSHEET_ID = os.environ.get("SPREADSHEET_ID", "example-spreadsheetID") NEW_SPREADSHEET_ID = os.environ.get("NEW_SPREADSHEET_ID", "1234567890qwerty") with models.DAG( "example_gcs_to_sheets", start_date=days_ago(1), schedule_interval='@once', # Override to match your needs tags=["example"], ) as dag: upload_sheet_to_gcs = GoogleSheetsToGCSOperator( task_id="upload_sheet_to_gcs", destination_bucket=BUCKET, spreadsheet_id=SPREADSHEET_ID, ) # [START upload_gcs_to_sheets] upload_gcs_to_sheet = GCSToGoogleSheetsOperator( task_id="upload_gcs_to_sheet", bucket_name=BUCKET, object_name="{{ task_instance.xcom_pull('upload_sheet_to_gcs')[0] }}", spreadsheet_id=NEW_SPREADSHEET_ID, ) # [END upload_gcs_to_sheets] upload_sheet_to_gcs >> upload_gcs_to_sheet
{ "content_hash": "63d2d4b63dc3f2d7af05be7869bbdb48", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 92, "avg_line_length": 35.088235294117645, "alnum_prop": 0.7074601844090528, "repo_name": "apache/incubator-airflow", "id": "d83e3b59db223e0aabd9635c0d4dd69829e2e874", "size": "1981", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "airflow/providers/google/suite/example_dags/example_gcs_to_sheets.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "69070" }, { "name": "Dockerfile", "bytes": "2001" }, { "name": "HTML", "bytes": "283783" }, { "name": "JavaScript", "bytes": "1387552" }, { "name": "Mako", "bytes": "1284" }, { "name": "Python", "bytes": "5482822" }, { "name": "Shell", "bytes": "40957" } ], "symlink_target": "" }
package com.vaadin.tests.server; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.net.URISyntaxException; import org.easymock.EasyMock; import org.junit.Test; import com.vaadin.server.DownloadStream; import com.vaadin.server.StreamResource; import com.vaadin.server.StreamResource.StreamSource; /** * * @author Vaadin Ltd */ public class StreamResourceTest { @Test public void testEqualsWithNullFields() { StreamResource resource1 = new StreamResource(null, null); StreamResource resource2 = new StreamResource(null, null); assertEquals(resource1, resource2); } @Test public void testNotEqualsWithNullFields() { StreamResource resource1 = new StreamResource(null, null); StreamResource resource2 = new StreamResource( EasyMock.createMock(StreamSource.class), ""); assertNotEquals(resource1, resource2); } @Test public void testHashCodeForNullFields() { StreamResource resource = new StreamResource(null, null); // No NPE resource.hashCode(); } @Test public void cacheTime() throws URISyntaxException { StreamResource resource = new StreamResource( EasyMock.createMock(StreamSource.class), "") { @Override public long getCacheTime() { return 5; } }; resource.setBufferSize(100); resource.setCacheTime(200); DownloadStream downloadStream = resource.getStream(); assertEquals( "DownloadStream buffer size must be same as resource buffer size", resource.getBufferSize(), downloadStream.getBufferSize()); assertEquals( "DownloadStream cache time must be same as resource cache time", resource.getCacheTime(), downloadStream.getCacheTime()); } }
{ "content_hash": "82aac6179f84962b6f712bce610b82dc", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 82, "avg_line_length": 29.333333333333332, "alnum_prop": 0.6627066115702479, "repo_name": "Darsstar/framework", "id": "b2d14802b0b7117c99f2eb3861d47421bc7d2d8a", "size": "2531", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "server/src/test/java/com/vaadin/tests/server/StreamResourceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "751129" }, { "name": "HTML", "bytes": "104675" }, { "name": "Java", "bytes": "24247164" }, { "name": "JavaScript", "bytes": "131503" }, { "name": "Python", "bytes": "33975" }, { "name": "Shell", "bytes": "14720" }, { "name": "Smarty", "bytes": "175" } ], "symlink_target": "" }
@protocol WPYExpiryAccessoryViewDelegate <NSObject> - (void)doneButtonTapped; @end @interface WPYExpiryAccessoryView : UIView @property(nonatomic, weak) id <WPYExpiryAccessoryViewDelegate> delegate; @end
{ "content_hash": "c34df32cc873a5df736298211eb1ab54", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 72, "avg_line_length": 29.285714285714285, "alnum_prop": 0.8292682926829268, "repo_name": "webpay/webpay-token-ios", "id": "a0dac21e0bf75ada1c0bfbfd13c35d210a690d10", "size": "373", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Webpay/CardForm/Field/ExpiryPicker/WPYExpiryAccessoryView.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "214044" }, { "name": "Ruby", "bytes": "1015" } ], "symlink_target": "" }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; using UnitsNet; using UnitsNet.Units; namespace FDA.Extensions { public static class UnitsExtensions { public static string DefaultUnit() { return ""; } public static bool HasIndex(this Array source, int index) { return source.Length > index; } public static double GForces(this Acceleration source) { return source.MeterPerSecondSquared * 9.81; } public static double Value(this Acceleration source) { return source.MeterPerSecondSquared; } public static double Value(this Angle source) { return source.Degrees; } public static void BlockCopy<T>(this byte[] source, int offset, int size, params T[] value) where T: struct { Buffer.BlockCopy (value, 0, source, offset, value.Length * size); } public static byte GetHexByte(this char value) { switch (value) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return (byte)(value - 48); case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return (byte)(value - 55); case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': return (byte)(value - 87); default: throw new ArgumentOutOfRangeException (); } } public static IEnumerable<T> GetHexBytes<T>(this string value) where T: struct { if (value.Equals ("-")) { yield break; } char[] chrs = value.ToCharArray (); int i = chrs [1] == 'x' || chrs [1] == 'X' ? 2 : 0; for (; i < chrs.Length; i++) { var a = chrs [i].GetHexByte (); var b = chrs.Length - i - 1; var c = a * (int)Math.Pow (16, b); var d = (T)Convert.ChangeType (c, typeof(T)); yield return d; } yield break; } public static IEnumerable<int> GetHexBytes(this string value) { if (value.Equals ("-")) { yield break; } char[] chrs = value.ToCharArray (); int i = chrs [1] == 'x' || chrs [1] == 'X' ? 2 : 0; for (; i < chrs.Length; i++) { var a = chrs [i].GetHexByte (); var b = chrs.Length - i - 1; yield return a * (int)Math.Pow(16, b); } yield break; } public static int GetInt32(this IEnumerable<byte> data, int index = 0) { return BitConverter.ToInt32(data.ToArray(), index); } public static long GetInt64(this IEnumerable<byte> data, int index = 0) { return BitConverter.ToInt64(data.ToArray(), index); } /*public static bool TryParse(this string value, out byte num){ } public static bool TryParse(this string value, out sbyte num){ }*/ public static bool TryParseHex(this string value, out byte num){ num = 0; //var b = value.GetHexBytes ().ToArray (); return true; } public static bool TryParse(this string value, out short num){ num = 0; int result; if (TryParse (value, out result)) { num = (short)result; return true; } return false; } public static bool TryParse(this string value, out int num) { num = 0; bool negate = value.ToCharArray()[0].Equals('-'); if (negate) { value = value.Substring(1); } if (value.Length == 0) { return false; } var b = Encoding.ASCII.GetBytes(value); foreach (var n in b) { if (n < '0' || n > '9') { return false; } num *= 10; num += (n - 48); } if (negate) { num *= -1; } return true; } public static bool TryParse(this string value, out ushort num) { num = 0; int _num = 0; if (TryParse (value, out num) && _num < ushort.MaxValue) { num = (ushort)_num; return true; } return false; } public static bool TryParse(this string value, out uint num){ num = 0; var b = Encoding.ASCII.GetBytes (value); foreach (var n in b) { if (n < '0' || n > '9') { return false; } num *= 10; num += (uint)(n - 48); } return true; } public static bool TryParse(this string value, out ulong num){ num = 0L; return false; } public static bool TryParse(this string value, out float num) { num = 0.0f; double v = double.NaN; return TryParse (value, out v); } public static bool TryParse(this string value, out double num){ num = 0.0; bool negate = value.ToCharArray()[0].Equals('-'); bool leftSide = true; int offset = 0; if (negate) { value = value.Substring (1); if (value.Length == 0) { return false; } } var b = Encoding.ASCII.GetBytes (value); foreach (var n in b) { if (n < '0' || n > '9') { if (leftSide && n == '.') { leftSide = false; continue; } return false; } num *= 10; num += (n - 48); if (!leftSide) { offset++; } } num /= (int)Math.Pow (10, offset); if (negate) { num *= -1; } return true; } public static dynamic As<T>(this string value) { return As (value, typeof(T)); } public static dynamic As(this string value, Type type) { var t = type.Name; switch (t) { case "Boolean": return value.AsBoolean(false); case "Byte": return value.AsByte(); case "Int16": return value.AsShort(); case "Int32": return value.AsInt(); case "Single": return value.AsFloat(); case "Double": return value.AsDouble(); case "DateTime": return value.AsDateTime(); case "TimeSpan": return value.AsTimeSpan(); case "String": return value; default: throw new Exception(); } } public static DateTime AsDateTime(this string value){ var dt = new DateTime ( value.Substring (0, 4).AsInt (), value.Substring (4, 2).AsInt (), value.Substring (6, 2).AsInt () ); return dt; } public static DateTime AsDateTime(this string value, string span) { return AsDateTime(value, span.AsTimeSpan()); } public static DateTime AsDateTime(this string value, TimeSpan ts) { return AsDateTime(value).Add(ts); } public static TimeSpan AsTimeSpan(this string value){ var ts = new TimeSpan ( value.Substring (0, 2).AsInt (), value.Substring (3, 2).AsInt (), value.Substring (6, 2).AsInt () ); return ts; } public static bool AsBoolean(this string value, bool? defaultValue = null) { int num = 0; if (TryParse(value, out num) && num == 0 || num == 1) { return num == 1; } if (defaultValue.HasValue) { return defaultValue.Value; } else { throw new ArgumentOutOfRangeException(); } } public static byte AsByte(this string value, byte defaultValue = byte.MinValue){ byte result = defaultValue; //return value.TryParse( return result; } public static ushort AsUShort(this string value, ushort defaultValue = ushort.MinValue){ ushort result; return value.TryParse (out result) ? result : defaultValue; } public static short AsShort(this string value, short falseValue = short.MinValue){ short result; return value.TryParse(out result) ? result : falseValue; } public static int AsInt(this string value, int falseValue = int.MinValue) { int result; return value.TryParse (out result) ? result : falseValue; } public static float AsFloat(this string value, float defaultValue = float.NaN) { float result; return value.TryParse(out result) ? result : defaultValue; } public static double AsDouble(this string value, double defaultValue = double.NaN){ double result; return value.TryParse (out result) ? result : defaultValue; } public static bool IsNaN(this double d) { return double.IsNaN(d); } public static double AsDouble(this char a) { // Only valid chars are digits switch (a) { case '0': return 0.0; case '1': return 1.0; case '2': return 2.0; case '3': return 3.0; case '4': return 4.0; case '5': return 5.0; case '6': return 6.0; case '7': return 7.0; case '8': return 8.0; case '9': return 9.0; default: return double.NaN; } } public static double AsDouble(char a, char b, bool allowNegative = true) { // First char could be '-' or digit // Second char must be digit double c = a.AsDouble(); double d = b.AsDouble(); if (!double.IsNaN(c) && !double.IsNaN(d)) { return 10.0 * c + d; } else if (allowNegative && c == '-' && !double.IsNaN(d)) { return -1.0 * d; } else { return double.NaN; } } public static double AsDouble(char a, char b, char c, bool allowNegative = true) { // First char could be - or digit // Second char could be '.' if first is digit // Third char must be digit double d = a.AsDouble(); double e = b.AsDouble(); double f = c.AsDouble(); if (!d.IsNaN() && !e.IsNaN() && !f.IsNaN()) { return 100.0 * d + 10.0 * e + f; } else if (!d.IsNaN() && e == '.' && !f.IsNaN()) { return d + f / 10.0; } else if (d == '-' && !e.IsNaN() && !f.IsNaN()) { return -1 * (e * 10.0 + f); } else { return double.NaN; } } public static double AsDouble(char a, char b, char c, char d, bool allowNegative = true) { throw new NotImplementedException(); } } }
{ "content_hash": "a47c416114212f039683f701dbefaca2", "timestamp": "", "source": "github", "line_count": 497, "max_line_length": 96, "avg_line_length": 22.718309859154928, "alnum_prop": 0.4900363121069879, "repo_name": "DefectiveCube/FlightDataAnalyzer", "id": "0c2657a48825f2b2c8e5aa04bd91d0ac736ded5a", "size": "11293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AnalysisLib/Extensions/Extensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "319672" }, { "name": "FLUX", "bytes": "399" }, { "name": "HTML", "bytes": "16092" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package framework.interpreter; import framework.game.Game; import framework.io.input.Input; import framework.io.printer.Printer; /** * * @author Marcos */ public class InterpreterFactory { //Interpreters não serão diretamente instanciados pelo código. /** @TODO Faz sentido o Factory ser estático?*/ /** * @param idioma * @return * @TODO Exception joga string na exceção.*/ public static Interpreter getInterpreter(String idioma, Game g) { if (idioma.toLowerCase().startsWith("pt") || idioma.toLowerCase().startsWith("br")) { return new InterpreterPT(g); } if (idioma.toLowerCase().startsWith("en")) { return new InterpreterEN(g); } throw new ExceptionInInitializerError("Problem with specified factory. Please check."); } }
{ "content_hash": "02dc202b7c287ccbe1b69e3d4062a5d2", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 95, "avg_line_length": 33.645161290322584, "alnum_prop": 0.6567593480345159, "repo_name": "marcossilva/IFAdventure", "id": "94c6bddc17899917ff6e22b8f3dbfe7686a8ba59", "size": "1049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EnsaioRetentivo/src/framework/interpreter/InterpreterFactory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "302646" } ], "symlink_target": "" }
layout: post title: The Eagle tags: random --- ![The Eagle Poster](https://resizing.flixster.com/dLd6oRr6xNQ-HerZcQSkfs-Iy9c=/180x267/v1.bTsxMTE1NDMwMztqOzE3MDIyOzIwNDg7NDA1MDs2MDAw "The Eagle Poster") 3/25/16: The first thing you should know about this movie is that it has zero named female characters. The second thing you should know is that no women even speak. Otherwise pretty boring. I guess Channing Tatum is pretty attractive. 2/10
{ "content_hash": "dc29bf9d9b807d48e1597c6b0a060ad3", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 239, "avg_line_length": 55.5, "alnum_prop": 0.7972972972972973, "repo_name": "GregoryBL/GregoryBL.github.io", "id": "bd0ff2552e63dff1c6d21a284ad96e2ef5235e1b", "size": "448", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2016-3-25-the-eagle.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "62995" }, { "name": "HTML", "bytes": "6276" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.genmod.families.family.Binomial.links &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.genmod.families.family.Binomial.safe_links" href="statsmodels.genmod.families.family.Binomial.safe_links.html" /> <link rel="prev" title="statsmodels.genmod.families.family.Binomial.link" href="statsmodels.genmod.families.family.Binomial.link.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.genmod.families.family.Binomial.links" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.1</span> <span class="md-header-nav__topic"> statsmodels.genmod.families.family.Binomial.links </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../glm.html" class="md-tabs__link">Generalized Linear Models</a></li> <li class="md-tabs__item"><a href="statsmodels.genmod.families.family.Binomial.html" class="md-tabs__link">statsmodels.genmod.families.family.Binomial</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.1</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.genmod.families.family.Binomial.links.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-genmod-families-family-binomial-links--page-root">statsmodels.genmod.families.family.Binomial.links<a class="headerlink" href="#generated-statsmodels-genmod-families-family-binomial-links--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py attribute"> <dt id="statsmodels.genmod.families.family.Binomial.links"> <code class="sig-prename descclassname">Binomial.</code><code class="sig-name descname">links</code><em class="property"> = [&lt;class 'statsmodels.genmod.families.links.logit'&gt;, &lt;class 'statsmodels.genmod.families.links.probit'&gt;, &lt;class 'statsmodels.genmod.families.links.cauchy'&gt;, &lt;class 'statsmodels.genmod.families.links.log'&gt;, &lt;class 'statsmodels.genmod.families.links.cloglog'&gt;, &lt;class 'statsmodels.genmod.families.links.identity'&gt;]</em><a class="headerlink" href="#statsmodels.genmod.families.family.Binomial.links" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.genmod.families.family.Binomial.link.html" title="statsmodels.genmod.families.family.Binomial.link" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.genmod.families.family.Binomial.link </span> </div> </a> <a href="statsmodels.genmod.families.family.Binomial.safe_links.html" title="statsmodels.genmod.families.family.Binomial.safe_links" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.genmod.families.family.Binomial.safe_links </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Oct 29, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "167e0cbceb6826248f03f982fa45e368", "timestamp": "", "source": "github", "line_count": 490, "max_line_length": 999, "avg_line_length": 37.704081632653065, "alnum_prop": 0.5952909336941813, "repo_name": "statsmodels/statsmodels.github.io", "id": "94b644a046a3b55ff33bd131452dce3cc9eb35dc", "size": "18479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.12.1/generated/statsmodels.genmod.families.family.Binomial.links.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!doctype html> <html class="default no-js"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>ISharedNodePointer | hifi</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../assets/css/main.css"> <script src="../assets/js/modernizr.js"></script> </head> <body> <header> <div class="tsd-page-toolbar"> <div class="container"> <div class="table-wrap"> <div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base=".."> <div class="field"> <label for="tsd-search-field" class="tsd-widget search no-caption">Search</label> <input id="tsd-search-field" type="text" /> </div> <ul class="results"> <li class="state loading">Preparing search index...</li> <li class="state failure">The search index is not available</li> </ul> <a href="../index.html" class="title">hifi</a> </div> <div class="table-cell" id="tsd-widgets"> <div id="tsd-filter"> <a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a> <div class="tsd-filter-group"> <input type="checkbox" id="tsd-filter-inherited" checked /> <label class="tsd-widget" for="tsd-filter-inherited">Inherited</label> <input type="checkbox" id="tsd-filter-private" checked /> <label class="tsd-widget" for="tsd-filter-private">Private</label> <input type="checkbox" id="tsd-filter-externals" checked /> <label class="tsd-widget" for="tsd-filter-externals">Externals</label> <input type="checkbox" id="tsd-filter-only-exported" /> <label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label> </div> </div> <a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a> </div> </div> </div> </div> <div class="tsd-page-title"> <div class="container"> <ul class="tsd-breadcrumb"> <li> <a href="../globals.html">Globals</a> </li> <li> <a href="../modules/hifi.html">hifi</a> </li> <li> <a href="hifi.isharednodepointer.html">ISharedNodePointer</a> </li> </ul> <h1>Interface ISharedNodePointer</h1> </div> </div> </header> <div class="container container-main"> <div class="row"> <div class="col-8 col-content"> <section class="tsd-panel-group tsd-index-group"> <h2>Index</h2> <section class="tsd-panel tsd-index-panel"> <div class="tsd-index-content"> </div> </section> </section> </div> <div class="col-4 col-menu menu-sticky-wrap menu-highlight"> <nav class="tsd-navigation primary"> <ul> <li class="globals "> <a href="../globals.html"><em>Globals</em></a> </li> <li class="current tsd-kind-container"> <a href="../modules/hifi.html">hifi</a> </li> </ul> </nav> <nav class="tsd-navigation secondary menu-sticky"> <ul class="before-current"> </ul> <ul class="current"> <li class="current tsd-kind-interface tsd-parent-kind-container"> <a href="hifi.isharednodepointer.html" class="tsd-kind-icon">IShared<wbr>Node<wbr>Pointer</a> </li> </ul> <ul class="after-current"> </ul> </nav> </div> </div> </div> <footer class="with-border-bottom"> <div class="container"> <h2>Legend</h2> <div class="tsd-legend-group"> <ul class="tsd-legend"> <li class="tsd-kind-container"><span class="tsd-kind-icon">Container, dynamic module</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li> <li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li> <li class="tsd-kind-construct-signature"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property"><span class="tsd-kind-icon">Variable</span></li> <li class="tsd-kind-call-signature"><span class="tsd-kind-icon">Function, call signature, accessor</span></li> <li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li> <li class="tsd-kind-construct-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Member, accessor</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li> <li class="tsd-kind-construct-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Member, accessor</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li>&nbsp;</li> <li class="tsd-kind-construct-signature tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited member</span></li> </ul> <ul class="tsd-legend"> <li>&nbsp;</li> <li class="tsd-kind-construct-signature tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private member</span></li> </ul> <ul class="tsd-legend"> <li>&nbsp;</li> <li>&nbsp;</li> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static member</span></li> </ul> </div> </div> </footer> <div class="container tsd-generator"> <p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p> </div> <div class="overlay"></div> <script src="../assets/js/main.js"></script> <script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script> </body> </html>
{ "content_hash": "7e02d81b42c57e00d007e19face04712", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 145, "avg_line_length": 44.34375, "alnum_prop": 0.6535588442565187, "repo_name": "JeroMiya/hifi-typescript", "id": "9c8084461d63c9b9a31fb1a60b17b13cf1b12c82", "size": "7097", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HiFi/docs/interfaces/hifi.isharednodepointer.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "46500" }, { "name": "JavaScript", "bytes": "793569" }, { "name": "TypeScript", "bytes": "57695" } ], "symlink_target": "" }
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.CollapsingToolbar" parent="AppTheme"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.CollapsingToolbar.MainList" parent="AppTheme.CollapsingToolbar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> </resources>
{ "content_hash": "fe71310216982f44d05cfefa059c60f4", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 90, "avg_line_length": 36.166666666666664, "alnum_prop": 0.6700460829493088, "repo_name": "dilipkumar4813/Capstone-Project", "id": "fd1846e64034b13cb5bab545d2b29bda5aa4de9a", "size": "1085", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/styles.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "172953" } ], "symlink_target": "" }
package com.zimbra.common.calendar; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import com.zimbra.common.localconfig.LC; import com.zimbra.common.service.ServiceException; import com.zimbra.common.util.ZimbraLog; import com.zimbra.common.mime.MimeConstants; import net.fortuna.ical4j.data.CalendarParser; import net.fortuna.ical4j.data.CalendarParserImpl; import net.fortuna.ical4j.data.ContentHandler; import net.fortuna.ical4j.data.ParserException; public class ZCalendar { public static final String sZimbraProdID = "Zimbra-Calendar-Provider"; public static final String sIcalVersion = "2.0"; public static final String sObsoleteVcalVersion = "1.0"; public static enum ICalTok { ACTION, ALTREP, ATTACH, ATTENDEE, BINARY, BOOLEAN, CAL_ADDRESS, CALSCALE, CATEGORIES, CLASS, CN, COMMENT, COMPLETED, CONTACT, CREATED, CUTYPE, DATE, DATE_TIME, DELEGATED_FROM, DELEGATED_TO, DESCRIPTION, DIR, DTEND, DTSTAMP, DTSTART, DUE, DURATION, ENCODING, EXDATE, EXRULE, FBTYPE, FLOAT, FMTTYPE, FREEBUSY, GEO, INTEGER, LANGUAGE, LAST_MODIFIED, LOCATION, MEMBER, METHOD, ORGANIZER, PARTSTAT, PERCENT_COMPLETE, PERIOD, PRIORITY, PRODID, RDATE, RECUR, RECURRENCE_ID, RELATED, RELATED_TO, RELTYPE, REPEAT, RESOURCES, ROLE, RRULE, RSVP, SENT_BY, SEQUENCE, STATUS, SUMMARY, TEXT, TIME, TRANSP, TRIGGER, TZID, TZNAME, TZOFFSETFROM, TZOFFSETTO, TZURL, UID, URI, URL, UTC_OFFSET, VALARM, VALUE, VERSION, VEVENT, VFREEBUSY, VJOURNAL, VTIMEZONE, VTODO, // METHOD PUBLISH, REQUEST, REPLY, ADD, CANCEL, REFRESH, COUNTER, DECLINECOUNTER, // CLASS PUBLIC, PRIVATE, CONFIDENTIAL, // ROLE CHAIR, REQ_PARTICIPANT, OPT_PARTICIPANT, NON_PARTICIPANT, // CUTYPE INDIVIDUAL, GROUP, RESOURCE, ROOM, UNKNOWN, // STATUS TENTATIVE, CONFIRMED, /*CANCELLED,*/ NEEDS_ACTION, /*COMPLETED,*/ IN_PROCESS, CANCELLED, DRAFT, FINAL, // PARTSTAT ACCEPTED, /*COMPLETED,*/ DECLINED, DELEGATED, /*IN_PROCESS,*/ /*NEEDS_ACTION,*/ /*TENTATIVE,*/ // TRANSPARENCY TRANSPARENT, OPAQUE, // VTIMEZONE STANDARD, DAYLIGHT, // RECURRENCE-ID RANGE, THISANDFUTURE, THISANDPRIOR, // alternate DESCRIPTION (HTML; used by Outlook 2007) X_ALT_DESC, X_MICROSOFT_CDO_ALLDAYEVENT, X_MICROSOFT_CDO_INTENDEDSTATUS, X_MICROSOFT_DISALLOW_COUNTER, // ZCO Custom values X_ZIMBRA_STATUS, X_ZIMBRA_STATUS_WAITING, X_ZIMBRA_STATUS_DEFERRED, X_ZIMBRA_PARTSTAT_WAITING, X_ZIMBRA_PARTSTAT_DEFERRED, // whether VEVENT/VTODO for an exception is a local-only change not shared with other attendees X_ZIMBRA_LOCAL_ONLY, // set to TRUE in series update to tell attendee to discard all exceptions while applying new series // This is a ZCO special. X_ZIMBRA_DISCARD_EXCEPTIONS, // tracks important data that changed in a modify operation // comma-separated list of "time", "location", etc. (See InviteChanges class for more info.) X_ZIMBRA_CHANGES; public static ICalTok lookup(String str) { try { str = str.replace('-', '_'); return ICalTok.valueOf(str); } catch (IllegalArgumentException e) { return null; } } public String toString() { return super.toString().replace('_', '-'); } } private static final String LINE_BREAK = "\r\n"; /** * @author tim * * Calendar has * Components * Properties */ public static class ZVCalendar { List<ZComponent> mComponents = new ArrayList<ZComponent>(); List<ZProperty> mProperties = new ArrayList<ZProperty>(); public ZVCalendar() { } public void addVersionAndProdId() { addProperty(new ZProperty(ICalTok.PRODID, sZimbraProdID)); addProperty(new ZProperty(ICalTok.VERSION, sIcalVersion)); } public void addProperty(ZProperty prop) { mProperties.add(prop); } public void addComponent(ZComponent comp) { mComponents.add(comp); } public ZComponent getComponent(ICalTok tok) { return findComponent(mComponents, tok); } public Iterator<ZComponent> getComponentIterator() { return mComponents.iterator(); } public ZProperty getProperty(ICalTok tok) { return findProp(mProperties, tok); } public String getPropVal(ICalTok tok, String defaultValue) { ZProperty prop = getProperty(tok); if (prop != null) return prop.mValue; return defaultValue; } public long getPropLongVal(ICalTok tok, long defaultValue) { ZProperty prop = getProperty(tok); if (prop != null) return Long.parseLong(prop.mValue); return defaultValue; } public String toString() { StringBuffer toRet = new StringBuffer("BEGIN:VCALENDAR"); toRet.append(LINE_BREAK); String INDENT = "\t"; for (ZProperty prop : mProperties) { toRet.append(prop.toString(INDENT)); } for (ZComponent comp : mComponents) { toRet.append(comp.toString(INDENT)); } toRet.append("END:VCALENDAR"); return toRet.toString(); } public void toICalendar(Writer w) throws IOException { toICalendar(w, false); } public void toICalendar(Writer w, boolean needAppleICalHacks) throws IOException { w.write("BEGIN:VCALENDAR"); w.write(LINE_BREAK); for (ZProperty prop : mProperties) prop.toICalendar(w, needAppleICalHacks); for (ZComponent comp : mComponents) comp.toICalendar(w, needAppleICalHacks); w.write("END:VCALENDAR"); } public void addDescription(String desc, String descHtml) { ZProperty descProp = new ZProperty(ICalTok.DESCRIPTION, desc); ZProperty altDescProp = new ZProperty(ICalTok.X_ALT_DESC, descHtml); altDescProp.addParameter(new ZParameter(ICalTok.FMTTYPE, MimeConstants.CT_TEXT_HTML)); for (ZComponent comp : mComponents) { ICalTok name = comp.getTok(); if (ICalTok.VEVENT.equals(name) || ICalTok.VTODO.equals(name) || ICalTok.VJOURNAL.equals(name)) { if (desc != null && desc.length() > 0) { // Add DESCRIPTION property to components that take that property, // if the property is not set. ZProperty prop = comp.getProperty(ICalTok.DESCRIPTION); if (prop == null) { comp.addProperty(descProp); } else { String val = prop.getValue(); if (val == null || val.length() < 1) prop.setValue(desc); } } if (descHtml != null && descHtml.length() > 0) { // Just add the X-ALT-DESC value. Don't worry about replacing existing value. comp.addProperty(altDescProp); } } } } public ICalTok getMethod() { ICalTok ret = null; ZProperty method = getProperty(ICalTok.METHOD); if (method != null) { String methodStr = method.getValue(); if (methodStr != null) { try { ret = ICalTok.valueOf(methodStr); } catch (IllegalArgumentException e) {} } } return ret; } } /** * @author tim * * Component has * Name * Properties * Components */ public static class ZComponent { public ZComponent(String name) { mName = name.toUpperCase(); mTok = ICalTok.lookup(mName); } public ZComponent(ICalTok tok) { mTok = tok; mName = tok.toString(); } private String mName; ICalTok mTok; public String getName() { return mName; } public ICalTok getTok() { return mTok; } List<ZProperty> mProperties = new ArrayList<ZProperty>(); List<ZComponent> mComponents = new ArrayList<ZComponent>(); public void addProperty(ZProperty prop) { mProperties.add(prop); } public void addComponent(ZComponent comp) { mComponents.add(comp); } public ZComponent getComponent(ICalTok tok) { return findComponent(mComponents, tok); } public Iterator<ZComponent> getComponentIterator() { return mComponents.iterator(); } public Iterator<ZProperty> getPropertyIterator() { return mProperties.iterator(); } public ZProperty getProperty(ICalTok tok) { return findProp(mProperties, tok); } public String getPropVal(ICalTok tok, String defaultValue) { ZProperty prop = getProperty(tok); if (prop != null) return prop.mValue; return defaultValue; } long getPropLongVal(ICalTok tok, long defaultValue) { ZProperty prop = getProperty(tok); if (prop != null) return Long.parseLong(prop.mValue); return defaultValue; } public String toString() { return toString(""); } public String toString(String INDENT) { StringBuffer toRet = new StringBuffer(INDENT).append("COMPONENT:").append(mName).append('(').append(mTok).append(')').append('\n'); String NEW_INDENT = INDENT+'\t'; for (ZProperty prop : mProperties) { toRet.append(prop.toString(NEW_INDENT)); } for (ZComponent comp : mComponents) { toRet.append(comp.toString(NEW_INDENT)); } toRet.append(INDENT).append("END:").append(mName).append('\n'); return toRet.toString(); } public void toICalendar(Writer w) throws IOException { toICalendar(w, false); } public void toICalendar(Writer w, boolean needAppleICalHacks) throws IOException { toICalendar(w, needAppleICalHacks, false); } public void toICalendar(Writer w, boolean needAppleICalHacks, boolean escapeHtmlTags) throws IOException { w.write("BEGIN:"); w.write(mName); w.write(LINE_BREAK); for (ZProperty prop : mProperties) { // If we're dealing with Apple iCal, don't generate the X-ALT-DESC property. // iCal can't handle it when the value is too long. (Exact threshold is unknown, // but we've seen the failure with a 19KB sample.) iCal doesn't support x-props anyway, // so there is no loss of functionality. // Also, don't generate the X-MICROSOFT-CDO-INTENDEDSTATUS property as iCal can't handle this // property and becomes stale when the event transparency is modified in iCal5. if (needAppleICalHacks && (ICalTok.X_ALT_DESC.equals(prop.getToken()) || ICalTok.X_MICROSOFT_CDO_INTENDEDSTATUS.equals(prop.getToken()))) continue; prop.toICalendar(w, needAppleICalHacks, escapeHtmlTags); } for (ZComponent comp : mComponents) comp.toICalendar(w, needAppleICalHacks); w.write("END:"); w.write(mName); w.write(LINE_BREAK); } public String getDescriptionHtml() { for (ZProperty prop : mProperties) { if (ICalTok.X_ALT_DESC.equals(prop.getToken())) { ZParameter fmttype = prop.getParameter(ICalTok.FMTTYPE); if (fmttype != null && MimeConstants.CT_TEXT_HTML.equalsIgnoreCase(fmttype.getValue())) return prop.getValue(); } } return null; } } // these are the characters that MUST be escaped: , ; " \n and \ -- note that \ // becomes \\\\ here because it is double-unescaped during the compile process! private static final Pattern MUST_ESCAPE = Pattern.compile("[,;\n\\\\]"); private static final Pattern SIMPLE_ESCAPE = Pattern.compile("([,;\\\\])"); private static final Pattern NEWLINE_CRLF_ESCAPE = Pattern.compile("\r\n"); private static final Pattern NEWLINE_BARE_CR_OR_LF_ESCAPE = Pattern.compile("[\r\n]"); /** * ,;"\ and \n must all be escaped. */ public static String escape(String str) { if (str!= null && MUST_ESCAPE.matcher(str).find()) { // escape ([,;"])'s String toRet = SIMPLE_ESCAPE.matcher(str).replaceAll("\\\\$1"); // escape toRet = NEWLINE_CRLF_ESCAPE.matcher(toRet).replaceAll("\\\\n"); toRet = NEWLINE_BARE_CR_OR_LF_ESCAPE.matcher(toRet).replaceAll("\\\\n"); return toRet; } return str; } private static final Pattern SIMPLE_ESCAPED = Pattern.compile("\\\\([,;\\\\])"); private static final Pattern NEWLINE_ESCAPED = Pattern.compile("\\\\[nN]"); public static String unescape(String str) { if (str != null && str.indexOf('\\') >= 0) { String toRet = SIMPLE_ESCAPED.matcher(str).replaceAll("$1"); return NEWLINE_ESCAPED.matcher(toRet).replaceAll("\r\n"); } return str; } public static String toCommaSepText(List<String> vals) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String val : vals) { if (first) first = false; else sb.append(","); sb.append(escape(val)); } return sb.toString(); } public static List<String> parseCommaSepText(String encoded) { List<String> list = new ArrayList<String>(); int len; if (encoded != null && (len = encoded.length()) > 0) { int start = 0; char prev = encoded.charAt(0); for (int i = 0; i < len; i++) { char curr = encoded.charAt(i); if (curr == ',' && prev != '\\') { String val = encoded.substring(start, i); list.add(unescape(val)); start = i + 1; } prev = curr; } String val = encoded.substring(start); list.add(unescape(val)); } return list; } /** * @author tim * * Property has * Name * Parameters * Value */ public static class ZProperty { public ZProperty(String name) { setName(name); mTok = ICalTok.lookup(mName); } public ZProperty(ICalTok tok) { mTok = tok; mName = tok.toString(); } public ZProperty(ICalTok tok, String value) { mTok = tok; mName = tok.toString(); setValue(value); } public ZProperty(ICalTok tok, boolean value) { mTok = tok; mName = tok.toString(); mValue = value ? "TRUE" : "FALSE"; } public ZProperty(ICalTok tok, long value) { mTok = tok; mName = tok.toString(); mValue = Long.toString(value); } public ZProperty(ICalTok tok, int value) { mTok = tok; mName = tok.toString(); mValue = Integer.toString(value); } public void setName(String name) { mName = name.toUpperCase(); } public void setValue(String value) { mValue = value; } public void setValueList(List<String> valueList) { mValueList = valueList; } List<ZParameter> mParameters = new ArrayList<ZParameter>(); public void addParameter(ZParameter param) { mParameters.add(param); } public ZParameter getParameter(ICalTok tok) { return findParameter(mParameters, tok); } public Iterator<ZParameter> parameterIterator() { return mParameters.iterator(); } public int getNumParameters() { return mParameters.size(); } public String getParameterVal(ICalTok tok, String defaultValue) { ZParameter param = findParameter(mParameters, tok); if (param != null) return param.getValue(); else return defaultValue; } public String paramVal(ICalTok tok, String defaultValue) { ZParameter param = getParameter(tok); if (param != null) { return param.getValue(); } return defaultValue; } public String toString() { return toString(""); } public String toString(String INDENT) { StringBuffer toRet = new StringBuffer(INDENT).append("PROPERTY:").append(mName).append('(').append(mTok).append(')').append('\n'); String NEW_INDENT = INDENT+'\t'; for (ZParameter param: mParameters) { toRet.append(param.toString(NEW_INDENT)); } toRet.append(NEW_INDENT).append("VALUE=\"").append(mValue).append("\"\n"); toRet.append(INDENT).append("END:").append(mName).append('\n'); return toRet.toString(); } private static final Pattern CONTROL_CHARS = Pattern.compile("[\\x00-\\x08\\x0A-\\x1F\\x7F]"); private String sanitize(String str) { // Sanitize control characters if (str != null) { return CONTROL_CHARS.matcher(str).replaceAll("?"); } return str; } private static final int CHARS_PER_FOLDED_LINE = 76; public void toICalendar(Writer w) throws IOException { toICalendar(w, false); } public void toICalendar(Writer w, boolean needAppleICalHacks) throws IOException { toICalendar(w, needAppleICalHacks, false); } public void toICalendar(Writer w, boolean needAppleICalHacks, boolean escapeHtmlTags) throws IOException { StringWriter sw = new StringWriter(); Pattern htmlPattern = Pattern.compile("<([^>]+)>"); sw.write(mName); for (ZParameter param: mParameters) param.toICalendar(sw, needAppleICalHacks); sw.write(':'); if (ICalTok.CATEGORIES.equals(mTok) || ICalTok.RESOURCES.equals(mTok)) { if (mValueList != null) sw.write(toCommaSepText(mValueList)); } else if (mValue != null) { String value = mValue; boolean noEscape = false; if (mTok != null) { switch (mTok) { case RRULE: case EXRULE: case RDATE: case EXDATE: case GEO: noEscape = true; break; } if (needAppleICalHacks && mTok.equals(ICalTok.TZID)) { // bug 15549: Apple iCal refuses to work with anything other than Olson TZIDs. value = TZIDMapper.canonicalize(value); } } if (noEscape) sw.write(value); else sw.write(escape(value)); } // Write with folding. String rawval = sanitize(sw.toString()); if (escapeHtmlTags) { // Use only escapeHtmlTags when the file isn't supposed to be downloaded (ie. it's supposed to be shown in the browser) w.write(htmlPattern.matcher(rawval).replaceAll("&lt;$1&gt;")); } else { int len = rawval.length(); for (int i = 0; i < len; i += CHARS_PER_FOLDED_LINE) { int upto = Math.min(i + CHARS_PER_FOLDED_LINE, len); String segment = rawval.substring(i, upto); if (i > 0) { w.write(LINE_BREAK); w.write(' '); } w.write(segment); } } w.write(LINE_BREAK); } public ICalTok getToken() { return mTok; } // may be null public String getName() { return mName; } public String getValue() { return mValue; } public List<String> getValueList() { return mValueList; } public long getLongValue() { return Long.parseLong(mValue); }; public int getIntValue() { return Integer.parseInt(mValue); }; public boolean getBoolValue() { return mValue.equalsIgnoreCase("TRUE"); } private ICalTok mTok; private String mName; private String mValue; private List<String> mValueList; // used only for CATEGORIES and RESOURCES properties } /** * @author tim * * Name:Value pair */ public static class ZParameter { public ZParameter(String name, String value) { setName(name); setValue(value); mTok = ICalTok.lookup(mName); } public ZParameter(ICalTok tok, String value) { mTok = tok; mName = tok.toString(); setValue(value); } public ZParameter(ICalTok tok, boolean value) { mTok = tok; mName = tok.toString(); maValue = value ? "TRUE" : "FALSE"; } public void setName(String name) { mName = name.toUpperCase(); } public void setValue(String value) { maValue = unquote(value); } public String toString() { return toString(""); } public String toString(String INDENT) { StringBuffer toRet = new StringBuffer(INDENT).append("PARAM:").append(mName).append('(').append(mTok).append(')').append(':').append(maValue).append('\n'); return toRet.toString(); } public void toICalendar(Writer w) throws IOException { toICalendar(w, false); } public void toICalendar(Writer w, boolean needAppleICalHacks) throws IOException { w.write(';'); w.write(mName); w.write('='); if (maValue == null || maValue.length()==0) { w.write("\"\""); // bug 4941: cannot put a completely blank parameter value, will confuse parsers } else if (ICalTok.TZID.equals(mTok)) { String value = maValue; if (needAppleICalHacks) { // bug 15549: Apple iCal refuses to work with anything other than Olson TZIDs. value = TZIDMapper.canonicalize(value); } // Microsoft Entourage 2004 (Outlook-like program for Mac) // insists on quoting TZID parameter value (but not TZID // property value). It's an Entourage bug, but we have to // keep it happy with a hacky quoting policy. boolean entourageCompat = LC.calendar_entourage_compatible_timezones.booleanValue(); w.write(quote(value, entourageCompat)); } else { w.write(quote(maValue, false)); } } public ICalTok getToken() { return mTok; } // may be null public String getName() { return mName; } public String getValue() { return maValue; } long getLongValue() { return Long.parseLong(maValue); }; int getIntValue() { return Integer.parseInt(maValue); }; private ICalTok mTok; private String mName; private String maValue; /** * Sanitize a string to make it a valid param-value. DQUOTE * is changed to a single quote and CTL chars are changed to question * marks ('?'). String is quoted if str is already quoted or if it * contains ',', ':' or ';'. * * To workaround a bug in Outlook's MIME parser (see bug 12008), string * is quoted if any non-US-ASCII chars are present, e.g. non-English * names. (These characters don't require quoting according to * RFC2445.) * * Empty string is returned if str is null or is an empty string. * * @param str * @return */ private static String quote(String str, boolean force) { if (str == null) return ""; int len = str.length(); if (len == 0) return ""; boolean needToQuote; int start, end; // index of first and last char to examine // end is last char + 1 if (len >= 2 && str.charAt(0) == '"' && str.charAt(len - 1) == '"') { needToQuote = true; start = 1; end = len - 1; } else { needToQuote = false; start = 0; end = len; } StringBuilder sb = new StringBuilder(len + 2); sb.append('"'); // always start with quote for (int i = start; i < end; i++) { // Some chars require quoting, others require changing to a // valid char. No char requires both. char ch = str.charAt(i); if ((ch >= 0x3C && ch <= 0x7E) // "<=>?@ABC ..." (English letters) || ch == 0x20 // space || (ch >= 0x2D && ch <= 0x39) // "-./0123456789" || (ch >= 0x23 && ch <= 0x2B) // "#$%&'()*+" || ch == 0x09 // horizontal tab || ch == 0x21) { // '!' // Char is okay. } else if (ch >= 0x80 // NON-US-ASCII and higher || ch == 0x2C // ',' || ch == 0x3A // ':' || ch == 0x3B) { // ';' // Chars 0x80 and above don't need to be quoted in RFC2445, // but Outlook thinks differently. (bug 12008) needToQuote = true; } else if (ch == 0x22) { // '"' // DQUOTE is not allowed. Change to single quote. ch = '\''; } else { // ch is a CTL: // 0x00 <= ch <= 0x08 or // 0x0A <= ch <= 0x1F or // ch == 0x7F // CTL is invalid in a param-value, so change to a '?'. ch = '?'; } sb.append(ch); } sb.append('"'); // matches initial quote if (needToQuote || force) return sb.toString(); else return sb.substring(1, sb.length() - 1); } public static String unquote(String str) { if (str != null && str.length() >= 2) { if ((str.charAt(0) == '\"') && (str.charAt(str.length() - 1) == '\"')) return str.substring(1, str.length() - 1); } return str; } } static ZProperty findProp(List <ZProperty> list, ICalTok tok) { for (ZProperty prop : list) { if (prop.mTok == tok) { return prop; } } return null; } static ZParameter findParameter(List <ZParameter> list, ICalTok tok) { for (ZParameter param: list) { if (param.mTok == tok) { return param; } } return null; } static ZComponent findComponent(List <ZComponent> list, ICalTok tok) { for (ZComponent comp: list) { if (comp.mTok == tok) { return comp; } } return null; } public interface ZICalendarParseHandler extends ContentHandler { public boolean inZCalendar(); public int getNumCals(); } public static class DefaultContentHandler implements ZICalendarParseHandler { List<ZVCalendar> mCals = new ArrayList<ZVCalendar>(1); ZVCalendar mCurCal = null; List<ZComponent> mComponents = new ArrayList<ZComponent>(); ZProperty mCurProperty = null; private int mNumCals; private boolean mInZCalendar; public List<ZVCalendar> getCals() { return mCals; } public void startCalendar() { mInZCalendar = true; mCurCal = new ZVCalendar(); mCals.add(mCurCal); } public void endCalendar() { mCurCal = null; mInZCalendar = false; mNumCals++; } public boolean inZCalendar() { return mInZCalendar; } public int getNumCals() { return mNumCals; } public void startComponent(String name) { ZComponent newComponent = new ZComponent(name); if (mComponents.size() > 0) { mComponents.get(mComponents.size()-1).mComponents.add(newComponent); } else { mCurCal.mComponents.add(newComponent); } mComponents.add(newComponent); } public void endComponent(String name) { mComponents.remove(mComponents.size()-1); } public void startProperty(String name) { mCurProperty = new ZProperty(name); if (mComponents.size() > 0) { mComponents.get(mComponents.size()-1).mProperties.add(mCurProperty); } else { mCurCal.mProperties.add(mCurProperty); } } public void propertyValue(String value) throws ParserException { ICalTok token = mCurProperty.getToken(); if (ICalTok.CATEGORIES.equals(token) || ICalTok.RESOURCES.equals(token) || ICalTok.FREEBUSY.equals(token)) mCurProperty.setValueList(parseCommaSepText(value)); else mCurProperty.setValue(unescape(value)); if (mComponents.size() == 0) { if (ICalTok.VERSION.equals(mCurProperty.getToken())) { if (sObsoleteVcalVersion.equals(value)) throw new ParserException("vCalendar 1.0 format not supported; use iCalendar instead"); if (!sIcalVersion.equals(value)) throw new ParserException("Unknow iCalendar version " + value); } } } public void endProperty(String name) { mCurProperty = null; } public void parameter(String name, String value) { ZParameter param = new ZParameter(name, value); if (mCurProperty != null) { mCurProperty.mParameters.add(param); } else { ZimbraLog.calendar.debug("ERROR: got parameter " + name + "," + value + " outside of Property"); } } } public static class ZCalendarBuilder { public static ZVCalendar build(String icalStr) throws ServiceException { ByteArrayInputStream bais = null; try { bais = new ByteArrayInputStream(icalStr.getBytes(MimeConstants.P_CHARSET_UTF8)); } catch (UnsupportedEncodingException e) { throw ServiceException.FAILURE("Can't get input stream from string", e); } try { return build(bais, MimeConstants.P_CHARSET_UTF8); } finally { try { bais.close(); } catch (IOException e) {} } } public static ZVCalendar build(InputStream is, String charset) throws ServiceException { List<ZVCalendar> list = buildMulti(is, charset); int len = list.size(); if (len == 1) { return list.get(0); } else if (len > 1) { ZimbraLog.calendar.warn( "Returning only the first ZCALENDAR after parsing " + len); return list.get(0); } else { throw ServiceException.PARSE_ERROR("No ZCALENDAR found", null); } } public static List<ZVCalendar> buildMulti(InputStream is, String charset) throws ServiceException { DefaultContentHandler handler = new DefaultContentHandler(); parse(is, charset, handler); return handler.getCals(); } private static final byte[] BOM_UTF8 = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; public static void parse(InputStream is, String charset, ZICalendarParseHandler handler) throws ServiceException { BufferedInputStream bis = new BufferedInputStream(is); // Skip UTF-8 Byte Order Mark. (EF BB BF) if (MimeConstants.P_CHARSET_UTF8.equalsIgnoreCase(charset)) { byte[] buf = new byte[3]; try { boolean bomFound = false; bis.mark(4); if (bis.read(buf) == 3) bomFound = buf[0] == BOM_UTF8[0] && buf[1] == BOM_UTF8[1] && buf[2] == BOM_UTF8[2]; if (!bomFound) bis.reset(); } catch (IOException e) { throw ServiceException.FAILURE("Caught IOException during UTF-8 BOM check", e); } } bis.mark(32 * 1024); CalendarParser parser = new CalendarParserImpl(); try { parser.parse(bis, charset, handler); } catch (IOException e) { throw ServiceException.FAILURE("Caught IOException parsing calendar: " + e, e); } catch (ParserException e) { StringBuilder s = new StringBuilder("Caught ParseException parsing calendar: " + e); try { bis.reset(); byte[] ics = new byte[32 * 1024]; int bytesRead = bis.read(ics, 0, ics.length); if (bytesRead > 0) { String icsStr = new String(ics, 0, bytesRead, charset); s.append(icsStr).append("\n"); if (bytesRead == ics.length) { s.append("...\n"); } } } catch (IOException ioe) { ioe.printStackTrace(); } ServiceException se = ServiceException.PARSE_ERROR(s.toString(), e); if (handler.inZCalendar() || handler.getNumCals() < 1) { // Got parse error inside ZCALENDAR block. Can't recover. throw se; } else { // Found garbage after END:ZCALENDAR. Log warning and move on. if (ZimbraLog.calendar.isDebugEnabled()) ZimbraLog.calendar.warn("Ignoring bad data at the end of text/calendar part: " + s.toString() , e); else ZimbraLog.calendar.warn("Ignoring bad data at the end of text/calendar part: " + e.getMessage()); } } } } }
{ "content_hash": "26aa2f4891368d035817963b648d25e3", "timestamp": "", "source": "github", "line_count": 959, "max_line_length": 167, "avg_line_length": 38.40875912408759, "alnum_prop": 0.5258999837107021, "repo_name": "nico01f/z-pec", "id": "341997e7dc047d5e98bfe5147fd04175c8caab3e", "size": "37397", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ZimbraCommon/src/java/com/zimbra/common/calendar/ZCalendar.java", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "18110" }, { "name": "C", "bytes": "61139" }, { "name": "C#", "bytes": "1461640" }, { "name": "C++", "bytes": "723279" }, { "name": "CSS", "bytes": "2648118" }, { "name": "Groff", "bytes": "15389" }, { "name": "HTML", "bytes": "83875860" }, { "name": "Java", "bytes": "49998455" }, { "name": "JavaScript", "bytes": "39307223" }, { "name": "Makefile", "bytes": "13060" }, { "name": "PHP", "bytes": "4263" }, { "name": "PLSQL", "bytes": "17047" }, { "name": "Perl", "bytes": "2030870" }, { "name": "PowerShell", "bytes": "1485" }, { "name": "Python", "bytes": "129210" }, { "name": "Shell", "bytes": "575209" }, { "name": "XSLT", "bytes": "20635" } ], "symlink_target": "" }
(function() { 'use strict'; angular.module('Core') .service('commonService', commonService); commonService.$inject = ['$stateParams', '$state', 'sessionService', '$http', '$q', '$timeout', '$window']; function commonService($stateParams, $state, sessionService, $http, $q, $timeout, $window) { var service = this; service.isEmpty = isEmpty; service.resetForm = resetForm; service.http = http; service.goToPage = goToPage; service.getCurrentState = getCurrentState; /* ======================================== Var ==================================================== */ service.baseUrl = ''; service.$q = $q; service.$timeout = $timeout; service.$window = $window; var apiObj = { /* Example: name: { methodType: 'POST' / 'GET' / 'PUT' / 'DELETE', url: '....', nextUrlPart: 'get_paired_vehicles' <== This is: http://url/id/nextUrlPart } */ } /* ======================================== Services =============================================== */ var sessionSvc = sessionService; /* ======================================== Public Methods ========================================= */ function getCurrentState() { return $state.current; } function goToPage(stateName, hasRoot, toReload) { if((stateName === undefined || stateName === null)&&(hasRoot === undefined || hasRoot === null)) { if (toReload) { $state.reload(); } } else { if (hasRoot) { $state.go('root.' + stateName); } else { $state.go(stateName); } } } function http(apiObjKey, headerObj, dataObj, authToken, idOnUrl) { var deferred = service.$q.defer(); var headerObject = (headerObj === undefined || headerObj === null) ? {} : headerObj; var dataObject = (dataObj === undefined || dataObj === null) ? {} : dataObj; if (authToken === true) { // headerObject['Authorization'] = 'Token token='+sessionSvc.userData.access_token } if (idOnUrl === undefined || idOnUrl === null) { idOnUrl = ''; } else { idOnUrl = '/' + idOnUrl; } var nextUrl = ''; if (!(apiObj[apiObjKey].nextUrlPart === undefined || apiObj[apiObjKey].nextUrlPart === null)) { nextUrl = '/' + apiObj[apiObjKey].nextUrlPart; } if (!isEmpty(dataObj) && (!(dataObj.image_url === undefined || dataObj.image_url === null))) { dataObj.image_url = dataObj.image_url.$ngfDataUrl.substring(dataObj.image_url.$ngfDataUrl.indexOf(',') + 1); } // If HTTP GET request, API params to be set to "params" key in $http request object // If HTTP POST/PUT request, API params to be set to "data" key in $http request object if (apiObj[apiObjKey].methodType.toLowerCase() == 'get') { $http({ method: apiObj[apiObjKey].methodType, url: service.baseUrl + apiObj[apiObjKey].url + idOnUrl + nextUrl, headers: headerObject, params: dataObject }).then(function(rs) { if (rs.data.status === undefined || rs.data.status === null) { deferred.reject(rs.data); } else { if (rs.data.status.toLowerCase() === 'ok') { deferred.resolve(rs.data); } else { deferred.reject(rs.data); } } }, function(err) { // Non 200 response }); } else { $http({ method: apiObj[apiObjKey].methodType, url: service.baseUrl + apiObj[apiObjKey].url + idOnUrl + nextUrl, headers: headerObject, data: dataObject }).then(function(rs) { if (rs.data.status === undefined || rs.data.status === null) { deferred.reject(rs.data); } else { if (rs.data.status.toLowerCase() === 'ok') { deferred.resolve(rs.data); } else { deferred.reject(rs.data); } } }, function(err) { // Non 200 response }); } return deferred.promise; } function resetForm(formName, formObj) { formName.$setPristine(); angular.copy({}, formObj); } function isEmpty(obj) { if (obj === void(0)) { return true; } for (var prop in obj) { if (obj[prop] === void(0)) { delete obj[prop]; } if (obj.hasOwnProperty(prop)) { return false; } } return true; } /* ======================================== Private Methods ======================================== */ function init() { } init(); } })();
{ "content_hash": "5667f7bed8f9a84a357e4f0468cd3545", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 124, "avg_line_length": 36.23076923076923, "alnum_prop": 0.41259731068648264, "repo_name": "tlkiong/stadium-booking", "id": "2fc08440fc19306829bb797cb10a372ee8785655", "size": "5652", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/modules/core/components/common.service.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3360" }, { "name": "HTML", "bytes": "8760" }, { "name": "JavaScript", "bytes": "69402" } ], "symlink_target": "" }
package com.example.test; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * 利用数据库来记录下载信息 * * @author acer */ public class DownLoadHelper extends SQLiteOpenHelper { private static final String SQL_NAME = "download.db"; private static final int DOWNLOAD_VERSION = 1; public DownLoadHelper(Context context) { super(context, SQL_NAME, null, DOWNLOAD_VERSION); } /** * 在download.db数据库下创建一个download_info表存储下载信息 * 开始位置start_pos,结束位置end_pos,完成的大小compelete_size */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, " + "start_pos integer, end_pos integer, compelete_size integer,url char)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
{ "content_hash": "f2f31fc34d4d853d5c1831f958d0bd81", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 100, "avg_line_length": 25.88888888888889, "alnum_prop": 0.7242489270386266, "repo_name": "zhumingwei/filedownload-multithreaddownload", "id": "38dde4aae8e408d7bf3a83d2fdf174e1bdd3e0a1", "size": "1014", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/example/test/DownLoadHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18219" } ], "symlink_target": "" }
(function() { 'use strict'; angular .module('uiRouterApp') .directive('acmeNavbar', acmeNavbar); /** @ngInject */ function acmeNavbar() { var directive = { restrict: 'E', templateUrl: 'app/components/navbar/navbar.html', scope: { creationDate: '=' }, controller: NavbarController, controllerAs: 'vm', bindToController: true }; return directive; /** @ngInject */ function NavbarController(moment) { var vm = this; // "vm.creationDate" is available by directive option "bindToController: true" vm.relativeDate = moment(vm.creationDate).fromNow(); } } })();
{ "content_hash": "65aa37d9d6aeff70a202cbf9216764d8", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 84, "avg_line_length": 21.03125, "alnum_prop": 0.5928677563150074, "repo_name": "Toilal/showcase-ng-routers", "id": "74e408d61a55fb53a006fe1e0c2566d0f148a923", "size": "673", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui-router-app/src/app/components/navbar/navbar.directive.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2743" }, { "name": "HTML", "bytes": "10248" }, { "name": "JavaScript", "bytes": "73303" } ], "symlink_target": "" }
/* * Tester.PCL * * This file was automatically generated for Stamplay by APIMATIC v2.0 ( https://apimatic.io ) on 06/12/2016 */ using System; using System.Collections; using System.Reflection; using Newtonsoft.Json; namespace Tester.PCL.Models { /// <summary> /// Converts a stirng valued enum to and from its name string value. /// </summary> public class StringValuedEnumConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The json writer</param> /// <param name="value">The value to write</param> /// <param name="serializer">The calling serializer</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); return; } //handle string valued enums in dictionaries if (value is IDictionary) { writer.WriteStartObject(); foreach (object keyValuePair in (value as IDictionary)) { var entry = (DictionaryEntry) keyValuePair; writer.WritePropertyName(entry.Key.ToString()); writeStringValue(writer, entry.Value); } writer.WriteEndObject(); } //handle string valued enums in lists else if (value is IEnumerable) { writer.WriteStartArray(); foreach (var item in (value as IEnumerable)) { writeStringValue(writer, item); } writer.WriteEndArray(); } //handle string valued enums else { writeStringValue(writer, value); } } /// <summary> /// Loads and writes the string value against a given enum element /// </summary> /// <param name="value">The string valued enum element value</param> private void writeStringValue(JsonWriter writer, object value) { Type enumHelperType = loadEnumHelperType(value.GetType()); MethodInfo enumHelperMethod = enumHelperType.GetMethod("ToValue", new[] { value.GetType() }); object stringValue = enumHelperMethod.Invoke(null, new object[] { value }); if (stringValue != null) writer.WriteValue(stringValue); else writer.WriteNull(); } /// <summary> /// Load the enum helper class against a given enum type /// </summary> /// <param name="enumType">The enum type to locate the helper</param> /// <returns>Type of the helper class for the given enum type</returns> private static Type loadEnumHelperType(Type enumType) { string enumHelperClassName = string.Format("{0}Helper",enumType.FullName); Assembly assembly = typeof(StringValuedEnumConverter).Assembly; Type enumHelperType = assembly.GetType(enumHelperClassName); if (enumHelperType == null) throw new InvalidCastException("Unable to load enum helper for casting value"); return enumHelperType; } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The json reader</param> /// <param name="objectType">Type of the object to be read</param> /// <param name="existingValue">The existing value of object being read</param> /// <param name="serializer">The calling serializer</param> /// <returns>The object value as enum element</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; try { if (reader.TokenType == JsonToken.String) { string enumStringValue = reader.Value.ToString(); Type enumHelperType = loadEnumHelperType(objectType); MethodInfo enumHelperMethod = enumHelperType.GetMethod("ParseString", new[] { typeof(string) }); object parsed = enumHelperMethod.Invoke(null, new object[] { enumStringValue }); return parsed; } } catch { throw new InvalidCastException(string.Format("Unable to cast value {0} to enum type {1}", reader.Value, objectType.Name)); } throw new InvalidCastException(string.Format("Unexpected token {0} when parsing enum.", reader.TokenType)); } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { Type toCheck = objectType; Type[] genericArgs = objectType.GetGenericArguments(); if ((genericArgs != null) && (genericArgs.Length > 0)) toCheck = genericArgs[genericArgs.Length - 1]; var attributes = toCheck.GetCustomAttributes(typeof(JsonConverterAttribute), false); if ((attributes == null)) return false; foreach (var converterAttrib in attributes) { if (attributes == null) continue; foreach (var attribute in attributes) { var converterrType = (attribute as JsonConverterAttribute).ConverterType; if (converterrType.FullName.Equals(this.GetType().FullName)) return true; } } return false; } } }
{ "content_hash": "c25da75dd24c02bc30f1c179babacc03", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 138, "avg_line_length": 39.04968944099379, "alnum_prop": 0.5554318434865596, "repo_name": "zeeshanejaz/TesterAPI-PCL", "id": "fee65e58f33aead8a5a407d4a1c3ee8f6619edea", "size": "6287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tester.PCL/Models/StringValuedEnumConverter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "335391" } ], "symlink_target": "" }