code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
line_mean
float64
0.5
100
line_max
int64
1
1k
alpha_frac
float64
0.25
1
autogenerated
bool
1 class
## Rails 5.0.4 (June 19, 2017) ## * Fix regression in numericality validator when comparing Decimal and Float input values with more scale than the schema. *Bradley Priest* ## Rails 5.0.3 (May 12, 2017) ## * The original string assigned to a model attribute is no longer incorrectly frozen. Fixes #24185, #28718. *Matthew Draper* * Avoid converting integer as a string into float. *namusyaka* ## Rails 5.0.2 (March 01, 2017) ## * No changes. ## Rails 5.0.1 (December 21, 2016) ## * No changes. ## Rails 5.0.1.rc2 (December 10, 2016) ## * No changes. ## Rails 5.0.1.rc1 (December 01, 2016) ## * Fix `Type::Date#serialize` to cast a value to a date object properly. This casting fixes queries for finding records by date column. Fixes #25354. *Ryuta Kamizono* ## Rails 5.0.0 (June 30, 2016) ## * `Dirty`'s `*_changed?` methods now return an actual singleton, never `nil`, as in 4.2. Fixes #24220. *Sen-Zhang* * Ensure that instances of `ActiveModel::Errors` can be marshalled. Fixes #25165. *Sean Griffin* * Allow passing record being validated to the message proc to generate customized error messages for that object using I18n helper. *Prathamesh Sonpatki* * Validate multiple contexts on `valid?` and `invalid?` at once. Example: class Person include ActiveModel::Validations attr_reader :name, :title validates_presence_of :name, on: :create validates_presence_of :title, on: :update end person = Person.new person.valid?([:create, :update]) # => false person.errors.messages # => {:name=>["can't be blank"], :title=>["can't be blank"]} *Dmitry Polushkin* * Add case_sensitive option for confirmation validator in models. *Akshat Sharma* * Ensure `method_missing` is called for methods passed to `ActiveModel::Serialization#serializable_hash` that don't exist. *Jay Elaraj* * Remove `ActiveModel::Serializers::Xml` from core. *Zachary Scott* * Add `ActiveModel::Dirty#[attr_name]_previously_changed?` and `ActiveModel::Dirty#[attr_name]_previous_change` to improve access to recorded changes after the model has been saved. It makes the dirty-attributes query methods consistent before and after saving. *Fernando Tapia Rico* * Deprecate the `:tokenizer` option for `validates_length_of`, in favor of plain Ruby. *Sean Griffin* * Deprecate `ActiveModel::Errors#add_on_empty` and `ActiveModel::Errors#add_on_blank` with no replacement. *Wojciech Wnętrzak* * Deprecate `ActiveModel::Errors#get`, `ActiveModel::Errors#set` and `ActiveModel::Errors#[]=` methods that have inconsistent behavior. *Wojciech Wnętrzak* * Allow symbol as values for `tokenize` of `LengthValidator`. *Kensuke Naito* * Assigning an unknown attribute key to an `ActiveModel` instance during initialization will now raise `ActiveModel::AttributeAssignment::UnknownAttributeError` instead of `NoMethodError`. Example: User.new(foo: 'some value') # => ActiveModel::AttributeAssignment::UnknownAttributeError: unknown attribute 'foo' for User. *Eugene Gilburg* * Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment` allowing to use it for any object as an includable module. Example: class Cat include ActiveModel::AttributeAssignment attr_accessor :name, :status end cat = Cat.new cat.assign_attributes(name: "Gorby", status: "yawning") cat.name # => 'Gorby' cat.status # => 'yawning' cat.assign_attributes(status: "sleeping") cat.name # => 'Gorby' cat.status # => 'sleeping' *Bogdan Gusiev* * Add `ActiveModel::Errors#details` To be able to return type of used validator, one can now call `details` on errors instance. Example: class User < ActiveRecord::Base validates :name, presence: true end user = User.new; user.valid?; user.errors.details => {name: [{error: :blank}]} *Wojciech Wnętrzak* * Change `validates_acceptance_of` to accept `true` by default besides `'1'`. The default for `validates_acceptance_of` is now `'1'` and `true`. In the past, only `"1"` was the default and you were required to pass `accept: true` separately. *mokhan* * Remove deprecated `ActiveModel::Dirty#reset_#{attribute}` and `ActiveModel::Dirty#reset_changes`. *Rafael Mendonça França* * Change the way in which callback chains can be halted. The preferred method to halt a callback chain from now on is to explicitly `throw(:abort)`. In the past, returning `false` in an Active Model `before_` callback had the side effect of halting the callback chain. This is not recommended anymore and, depending on the value of the `ActiveSupport.halt_callback_chains_on_return_false` option, will either not work at all or display a deprecation warning. *claudiob* Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activemodel/CHANGELOG.md) for previous changes.
best-summer/project-dystopia
api-server/vendor/bundle/gems/activemodel-5.0.4/CHANGELOG.md
Markdown
mit
5,282
25.923469
120
0.666856
false
--- title: Color Palette layout: page description: taCss color palette same as the Material Design Lite color palette. utilities: true --- <div class="row p-3"> <h6>color setup</h6> <div class="code col-12 info p-3 m-b-3"> {% highlight scss %} /* colors setups in "core/_variables.scss" */ /* enable/disable the default colors for components */ $enable-colors: true !default; /* don't forget include minimum the primary and the accent color */ /* the palette variables can be found in the "core/_colorpalette.scss" */ $primary-palette: $teal-palette !default; $accent-palette: $deep-orange-palette !default; $enable--red-palette: true !default; $enable--pink-palette: true !default; $enable--purple-palette: true !default; $enable--deep-purple-palette: true !default; $enable--indigo-palette: true !default; $enable--blue-palette: true !default; $enable--light-blue-palette: true !default; $enable--cyan-palette: true !default; $enable--teal-palette: true !default; $enable--green-palette: true !default; $enable--light-green-palette: true !default; $enable--lime-palette: true !default; $enable--yellow-palette: true !default; $enable--amber-palette: true !default; $enable--orange-palette: true !default; $enable--deep-orange-palette: true !default; $enable--brown-palette: true !default; $enable--grey-palette: true !default; $enable--blue-grey-palette: true !default; $enable--black-palette: true !default; $enable--white-palette: true !default; /* basic palette contains black, white and the midle colors for the rest even if the color-palette not enabled. no accent color. */ $enable--basic-palette: true !default; {% endhighlight %} </div> <h6>background</h6> <p> Use the <span class="code-class">bg-</span> prefix with your <i>color</i> of choice. </p> <p class="col-6 col-t-8 "> <button class='btn bg-red'> red </button> <button class='btn bg-pink'> pink </button> <button class='btn bg-purple'> purple </button> <button class='btn bg-deep-purple'> deep-purple </button> <button class='btn bg-indigo'> indigo </button> <button class='btn bg-blue'> blue </button> <button class='btn bg-light-blue'> light-blue </button> <button class='btn bg-lime'> lime </button> <button class='btn bg-yellow'> yellow </button> <button class='btn bg-amber'> amber </button> <button class='btn bg-orange'> orange </button> <button class='btn bg-deep-orange'> deep-orange </button> <button class='btn bg-brown'> brown </button> <button class='btn bg-grey'> grey </button> <button class='btn bg-blue-grey'> blue-grey </button> <button class='btn bg-black'> black </button> <button class='btn bg-white'> white </button> </p> <div class="code info code-large col-6 col-t-8"> {% highlight html %} <button class='btn bg-red'> red </button> <button class='btn bg-pink'> pink </button> <button class='btn bg-purple'> purple </button> <button class='btn bg-deep-purple'> deep-purple </button> <button class='btn bg-indigo'> indigo </button> <button class='btn bg-blue'> blue </button> <button class='btn bg-light-blue'> light-blue </button> <button class='btn bg-lime'> lime </button> <button class='btn bg-yellow'> yellow </button> <button class='btn bg-amber'> amber </button> <button class='btn bg-orange'> orange </button> <button class='btn bg-deep-orange'> deep-orange </button> <button class='btn bg-brown'> brown </button> <button class='btn bg-grey'> grey </button> <button class='btn bg-blue-grey'> blue-grey </button> <button class='btn bg-black'> black </button> <button class='btn bg-white'> white </button> {% endhighlight %} </div> <h6>auto textcolor</h6> <p> To choose readable font color automatic to the choosen background use the <span class="code-class">colored</span> class. </p> <p class="col-6 col-t-8 "> <button class='colored btn bg-red'> red </button> <button class='colored btn bg-pink'> pink </button> <button class='colored btn bg-purple'> purple </button> <button class='colored btn bg-deep-purple'> deep-purple </button> <button class='colored btn bg-indigo'> indigo </button> <button class='colored btn bg-blue'> blue </button> <button class='colored btn bg-light-blue'> light-blue </button> <button class='colored btn bg-lime'> lime </button> <button class='colored btn bg-yellow'> yellow </button> <button class='colored btn bg-amber'> amber </button> <button class='colored btn bg-orange'> orange </button> <button class='colored btn bg-deep-orange'> deep-orange </button> <button class='colored btn bg-brown'> brown </button> <button class='colored btn bg-grey'> grey </button> <button class='colored btn bg-blue-grey'> blue-grey </button> <button class='colored btn bg-black'> black </button> <button class='colored btn bg-white'> white </button> </p> <div class="code info code-large col-6 col-t-8"> {% highlight html %} <button class='colored btn bg-red'> red </button> <button class='colored btn bg-pink'> pink </button> <button class='colored btn bg-purple'> purple </button> <button class='colored btn bg-deep-purple'> deep-purple </button> <button class='colored btn bg-indigo'> indigo </button> <button class='colored btn bg-blue'> blue </button> <button class='colored btn bg-light-blue'> light-blue </button> <button class='colored btn bg-lime'> lime </button> <button class='colored btn bg-yellow'> yellow </button> <button class='colored btn bg-amber'> amber </button> <button class='colored btn bg-orange'> orange </button> <button class='colored btn bg-deep-orange'> deep-orange </button> <button class='colored btn bg-brown'> brown </button> <button class='colored btn bg-grey'> grey </button> <button class='colored btn bg-blue-grey'> blue-grey </button> <button class='colored btn bg-black'> black </button> <button class='colored btn bg-white'> white </button> {% endhighlight %} </div> <h6>outline (border and text color)</h6> <p> Use the <span class="code-class">outline-</span> prefix with your <i>color</i> of choice to get colored border and text. </p> <p class="col-6 col-t-9"> <button class='btn outline-red'> red </button> <button class='btn outline-pink'> pink </button> <button class='btn outline-purple'> purple </button> <button class='btn outline-deep-purple'> deep-purple </button> <button class='btn outline-indigo'> indigo </button> <button class='btn outline-blue'> blue </button> <button class='btn outline-light-blue'> light-blue </button> <button class='btn outline-lime'> lime </button> <button class='btn outline-yellow'> yellow </button> <button class='btn outline-amber'> amber </button> <button class='btn outline-orange'> orange </button> <button class='btn outline-deep-orange'> deep-orange </button> <button class='btn outline-brown'> brown </button> <button class='btn outline-grey'> grey </button> <button class='btn outline-blue-grey'> blue-grey </button> <button class='btn outline-black'> black </button> <button class='btn outline-white'> white </button> </p> <div class="code info code-large col-6 col-t-8"> {% highlight html %} <button class='btn outline-red'> red </button> <button class='btn outline-pink'> pink </button> <button class='btn outline-purple'> purple </button> <button class='btn outline-deep-purple'> deep-purple </button> <button class='btn outline-indigo'> indigo </button> <button class='btn outline-blue'> blue </button> <button class='btn outline-light-blue'> light-blue </button> <button class='btn outline-lime'> lime </button> <button class='btn outline-yellow'> yellow </button> <button class='btn outline-amber'> amber </button> <button class='btn outline-orange'> orange </button> <button class='btn outline-deep-orange'> deep-orange </button> <button class='btn outline-brown'> brown </button> <button class='btn outline-grey'> grey </button> <button class='btn outline-blue-grey'> blue-grey </button> <button class='btn outline-black'> black </button> <button class='btn outline-white'> white </button> {% endhighlight %} </div> <h6>text color</h6> <p> Use the <span class="code-class">text-</span> prefix with your <i>color</i> of choice to get colored text. </p> <p class="col-6 col-t-8"> <button class='btn text-red'> red </button> <button class='btn text-pink'> pink </button> <button class='btn text-purple'> purple </button> <button class='btn text-deep-purple'> deep-purple </button> <button class='btn text-indigo'> indigo </button> <button class='btn text-blue'> blue </button> <button class='btn text-light-blue'> light-blue </button> <button class='btn text-lime'> lime </button> <button class='btn text-yellow'> yellow </button> <button class='btn text-amber'> amber </button> <button class='btn text-orange'> orange </button> <button class='btn text-deep-orange'> deep-orange </button> <button class='btn text-brown'> brown </button> <button class='btn text-grey'> grey </button> <button class='btn text-blue-grey'> blue-grey </button> <button class='btn text-black'> black </button> <button class='btn text-white'> white </button> </p> <div class="code info code-large col-6 col-t-8"> {% highlight html %} <button class='btn text-red'> red </button> <button class='btn text-pink'> pink </button> <button class='btn text-purple'> purple </button> <button class='btn text-deep-purple'> deep-purple </button> <button class='btn text-indigo'> indigo </button> <button class='btn text-blue'> blue </button> <button class='btn text-light-blue'> light-blue </button> <button class='btn text-lime'> lime </button> <button class='btn text-yellow'> yellow </button> <button class='btn text-amber'> amber </button> <button class='btn text-orange'> orange </button> <button class='btn text-deep-orange'> deep-orange </button> <button class='btn text-brown'> brown </button> <button class='btn text-grey'> grey </button> <button class='btn text-blue-grey'> blue-grey </button> <button class='btn text-black'> black </button> <button class='btn text-white'> white </button> {% endhighlight %} </div> <h6>the full color palette</h6> <div class="row" id="colorPalettesBlock"> </div> <div class="row" id=textColorPalettesBlock> </div> <script type="text/javascript"> var basicPalette = [ "red", "pink", "purple", "deep-purple", "indigo", "blue", "light-blue", "lime", "yellow", "amber", "orange", "deep-orange", "brown", "grey", "blue-grey", "black", "white", ]; var redPalette = ['red-0','red-1','red-2','red-3','red-4','red','red-6','red-7','red-8','red-9','red-a1','red-a2','red-a3','red-a4']; var pinkPalette = ['pink-0','pink-1','pink-2','pink-3','pink-4','pink','pink-6','pink-7','pink-8','pink-9','pink-a1','pink-a2','pink-a3','pink-a4']; var purplePalette = ['purple-0','purple-1','purple-2','purple-3','purple-4','purple','purple-6','purple-7','purple-8','purple-9','purple-a1','purple-a2','purple-a3','purple-a4']; var deepPurplePalette = ['deep-purple-0','deep-purple-1','deep-purple-2','deep-purple-3','deep-purple-4','deep-purple','deep-purple-6','deep-purple-7','deep-purple-8','deep-purple-9','deep-purple-a1','deep-purple-a2','deep-purple-a3','deep-purple-a3']; var indigoPalette = ['indigo-0','indigo-1','indigo-2','indigo-3','indigo-4','indigo','indigo-6','indigo-7','indigo-8','indigo-9','indigo-a1','indigo-a2','indigo-a3','indigo-a4']; var bluePalette = ['blue-0','blue-1','blue-2','blue-3','blue-4','blue','blue-6','blue-7','blue-8','blue-9','blue-a1','blue-a2','blue-a3','blue-a4']; var lightBluePalette = ['light-blue-0','light-blue-1','light-blue-2','light-blue-3','light-blue-4','light-blue','light-blue-6','light-blue-7','light-blue-8','light-blue-9','light-blue-a1','light-blue-a2','light-blue-a3','light-blue-a4']; var cyanPalette = ['cyan-0','cyan-1','cyan-2','cyan-3','cyan-4','cyan','cyan-6','cyan-7','cyan-8','cyan-9','cyan-a1','cyan-a2','cyan-a3','cyan-a4']; var tealPalette = ['teal-0','teal-1','teal-2','teal-3','teal-4','teal','teal-6','teal-7','teal-8','teal-9','teal-a1','teal-a2','teal-a3','teal-a4']; var greenPalette = ['green-0','green-1','green-2','green-3','green-4','green','green-6','green-7','green-8','green-9','green-a1','green-a2','green-a3','green-a4']; var lightGreenPalette = ['light-green-0','light-green-1','light-green-2','light-green-3','light-green-4','light-green','light-green-6','light-green-7','light-green-8','light-green-9','light-green-a1','light-green-a2','light-green-a3','light-green-a4']; var limePalette = ['lime-0','lime-1','lime-2','lime-3','lime-4','lime','lime-6','lime-7','lime-8','lime-9','lime-a1','lime-a2','lime-a3','lime-a4']; var yellowPalette = ['yellow-0','yellow-1','yellow-2','yellow-3','yellow-4','yellow','yellow-6','yellow-7','yellow-8','yellow-9','yellow-a1','yellow-a2','yellow-a3','yellow-a4']; var amberPalette = ['amber-0','amber-1','amber-2','amber-3','amber-4','amber','amber-6','amber-7','amber-8','amber-9','amber-a1','amber-a2','amber-a3','amber-a4']; var orangePalette = ['orange-0','orange-1','orange-2','orange-3','orange-4','orange','orange-6','orange-7','orange-8','orange-9','orange-a1','orange-a2','orange-a3','orange-a4']; var deepOrangePalette = ['deep-orange-0','deep-orange-1','deep-orange-2','deep-orange-3','deep-orange-4','deep-orange','deep-orange-6','deep-orange-7','deep-orange-8','deep-orange-9','deep-orange-a1','deep-orange-a2','deep-orange-a3','deep-orange-a4']; var brownPalette = ['brown-0','brown-1','brown-2','brown-3','brown-4','brown','brown-6','brown-7','brown-8','brown-9']; var greyPalette = ['grey-0','grey-1','grey-2','grey-3','grey-4','grey','grey-6','grey-7','grey-8','grey-9']; var blueGreyPalette = ['blue-grey-0','blue-grey-1','blue-grey-2','blue-grey-3','blue-grey-4','blue-grey','blue-grey-6','blue-grey-7','blue-grey-8','blue-grey-9']; var blackPalette = ['black']; var whitePalette = ['white']; var colorPalettes = ['redPalette','pinkPalette','purplePalette','deepPurplePalette','indigoPalette','bluePalette','lightBluePalette','cyanPalette','tealPalette','greenPalette','lightGreenPalette','limePalette','yellowPalette','amberPalette','orangePalette','deepOrangePalette','brownPalette','greyPalette','blueGreyPalette']; //+'blackPalette','whitePalette' str = ''; str = "<div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-black p-1 w-100 t-center colored'>black</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-white p-1 w-100 t-center colored'>white</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-white p-1 w-100 t-center colored'>black</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-black p-1 w-100 t-center colored'>white</div></div>"; for (var i = 0; i < colorPalettes.length; i++) { str += "<div class='no-gutter col col-2 bg-" + window[colorPalettes[i]][9] + "'>"; for (var j = 0; j < window[colorPalettes[i]].length; j++) { str += "<div class='bg-" + window[colorPalettes[i]][j] + " p-1 w-100 t-center colored'> " + window[colorPalettes[i]][j] + " </div>"; } str += "</div>"; } for (var i = 0; i < colorPalettes.length; i++) { str += "<div class='bg-black no-gutter col col-2'>"; for (var j = 0; j < window[colorPalettes[i]].length; j++) { str += "<div class='text-" + window[colorPalettes[i]][j] + " p-1 w-100 t-center colored'> " + window[colorPalettes[i]][j] + " </div>"; } str += "</div>"; } document.getElementById("colorPalettesBlock").innerHTML = str; </script> </div>
ostux/tacss
utilities/colors.html
HTML
mit
16,433
57.27305
481
0.635185
false
--- layout: post title: "Clean Code: Chapter 5 - Formatting" date: 2016-03-13 --- Formatting, while not consequential to how the code actually works, does make a huge difference in how future user of the code will be able to navigate and understand what is going on. In formatting, particularly, the broken window theory applies. The broken window theory is a social science concept that looks at how a single, small act of neglect can lead to snowballing negative effects. The theory gets its name from the idea that a single neglected broken window in an abandoned building would eventually invite more acts of crime and vandalism. This applies to programming because a consistently and cleanly formatted application reinforces the importance of setting positive norms for future results. Lazy formatting, on the other hand, will set a precedent for those who will add to and edit the code down the line. There are several aspects that go into a well formatted application. Vertical and horizontal formatting are a couple of considerations to make when considering how your code and files should be organized. ### Vertical Formatting >Smaller files are usually easier to understand than large files are. Vertical formatting points to a file’s overall size with regards to lines of code per file. As a general rule, you don’t want to have files over 500 lines of code, but even smaller files are easier to sort through. Beyond just lines of code, however, are vertical context guidelines. Code should be organized in a file in a meaningful way, with larger concepts towards the top, and smaller and smaller details as one descends down the file. Functions that call other functions should appear above the functions which they call. Variables that are used throughout the file should remain at the top of the file, and local variables should appear at the top of the function that is using them. With the code organized, you can make other considerations with regards to spacing. It is appropriate to use empty lines to separate concepts, such as functions. Within a grouped concept, however, using empty lines can draw out methods, making them more difficult to follow. ### Horizontal Formatting Horizontal formatting, on the other hand, deals with the smaller context of single lines. The guideline for how long your lines should be should take into consideration a reader and the required movement it would take to read from left to right. You don’t want the reader to have to scroll to read a full line, nor would you want to have to shrink the font to a tiny size to get a single line effect. Typically 100-120 characters per line are appropriate. > We use horizontal white space to associate things that are strongly related and dissassociate things that are more weakly related. Spacing can have a positive effect on the readability of the code. Consider the following: ```function area(length,width){ return (length*width)/2 }``` Sure, the code runs and does what it is supposed to, but a user friendly refactor could be as follows: ```function area(length, width) { return (length * width) / 2 }``` Just adding a couple of spaces saves time in allowing yourself to separate the different actions happening in the code. As another consideration, it is generally not wise to separate things into a column format, as the eye tends to follow the vertical line of the column, rather than the horizontal line as intended. Indentation is another important horizontal formatting concept. Consider the file as an outline and indent as such. The larger concepts such as class or module declaration would appear farthest left, with smaller details within functions and loops being indented the most. This helps readers know where concepts begin and end. Paying attention to vertical and horizontal formatting concepts will go a long way in presenting a clean code base that others will want to work with. Keep in mind a goal that you want people to look at your code and think *”wow, this person really cares”*.
NicoleCarpenter/nicolecarpenter.github.io
_posts/2016-03-13-clean-code-chapter-5-formatting.md
Markdown
mit
4,058
78.392157
476
0.794713
false
# testtesttest-yo [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][daviddm-image]][daviddm-url] [![Code Coverage][coverage-image]][coverage-url] [![Code Climate][climate-image]][climate-url] [![License][license-image]][license-url] [![Code Style][code-style-image]][code-style-url] ## Table of Contents 1. [Features](#features) 1. [Requirements](#requirements) 1. [Getting Started](#getting-started) 1. [Application Structure](#application-structure) 1. [Development](#development) 1. [Routing](#routing) 1. [Testing](#testing) 1. [Configuration](#configuration) 1. [Production](#production) 1. [Deployment](#deployment) ## Requirements * node `^5.0.0` (`6.11.0` suggested) * yarn `^0.23.0` or npm `^3.0.0` ## Getting Started 1. Install dependencies: `yarn` or `npm install` 2. Start Development server: `yarn start` or `npm start` While developing, you will probably rely mostly on `npm start`; however, there are additional scripts at your disposal: |`npm run <script>` |Description| |-------------------|-----------| |`start` |Serves your app at `localhost:3000` and displays [Webpack Dashboard](https://github.com/FormidableLabs/webpack-dashboard)| |`start:simple` |Serves your app at `localhost:3000` without [Webpack Dashboard](https://github.com/FormidableLabs/webpack-dashboard)| |`build` |Builds the application to ./dist| |`test` |Runs unit tests with Karma. See [testing](#testing)| |`test:watch` |Runs `test` in watch mode to re-run tests when changed| |`lint` |[Lints](http://stackoverflow.com/questions/8503559/what-is-linting) the project for potential errors| |`lint:fix` |Lints the project and [fixes all correctable errors](http://eslint.org/docs/user-guide/command-line-interface.html#fix)| [Husky](https://github.com/typicode/husky) is used to enable `prepush` hook capability. The `prepush` script currently runs `eslint`, which will keep you from pushing if there is any lint within your code. If you would like to disable this, remove the `prepush` script from the `package.json`. ## Application Structure The application structure presented in this boilerplate is **fractal**, where functionality is grouped primarily by feature rather than file type. Please note, however, that this structure is only meant to serve as a guide, it is by no means prescriptive. That said, it aims to represent generally accepted guidelines and patterns for building scalable applications. If you wish to read more about this pattern, please check out this [awesome writeup](https://github.com/davezuko/react-redux-starter-kit/wiki/Fractal-Project-Structure) by [Justin Greenberg](https://github.com/justingreenberg). ``` . ├── build # All build-related configuration │ └── create-config # Script for building config.js in ci environments │ └── karma.config.js # Test configuration for Karma │ └── webpack.config.js # Environment-specific configuration files for webpack ├── server # Express application that provides webpack middleware │ └── main.js # Server application entry point ├── src # Application source code │ ├── index.html # Main HTML page container for app │ ├── main.js # Application bootstrap and rendering │ ├── normalize.js # Browser normalization and polyfills │ ├── components # Global Reusable Presentational Components │ ├── containers # Global Reusable Container Components │ ├── layouts # Components that dictate major page structure │ │ └── CoreLayout # Global application layout in which to render routes │ ├── routes # Main route definitions and async split points │ │ ├── index.js # Bootstrap main application routes with store │ │ └── Home # Fractal route │ │ ├── index.js # Route definitions and async split points │ │ ├── assets # Assets required to render components │ │ ├── components # Presentational React Components │ │ ├── container # Connect components to actions and store │ │ ├── modules # Collections of reducers/constants/actions │ │ └── routes ** # Fractal sub-routes (** optional) │ ├── static # Static assets │ ├── store # Redux-specific pieces │ │ ├── createStore.js # Create and instrument redux store │ │ └── reducers.js # Reducer registry and injection │ └── styles # Application-wide styles (generally settings) ├── project.config.js # Project configuration settings (includes ci settings) └── tests # Unit tests ``` ### Routing We use `react-router` [route definitions](https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#plainroute) (`<route>/index.js`) to define units of logic within our application. See the [application structure](#application-structure) section for more information. ## Testing To add a unit test, create a `.spec.js` file anywhere inside of `./tests`. Karma and webpack will automatically find these files, and Mocha and Chai will be available within your test without the need to import them. ## Production Build code before deployment by running `npm run build`. There are multiple options below for types of deployment, if you are unsure, checkout the Firebase section. ### Deployment 1. Login to [Firebase](firebase.google.com) (or Signup if you don't have an account) and create a new project 2. Install cli: `npm i -g firebase-tools` #### CI Deploy (recommended) **Note**: Config for this is located within `travis.yml` `firebase-ci` has been added to simplify the CI deployment process. All that is required is providing authentication with Firebase: 1. Login: `firebase login:ci` to generate an authentication token (will be used to give Travis-CI rights to deploy on your behalf) 1. Set `FIREBASE_TOKEN` environment variable within Travis-CI environment 1. Run a build on Travis-CI If you would like to deploy to different Firebase instances for different branches (i.e. `prod`), change `ci` settings within `.firebaserc`. For more options on CI settings checkout the [firebase-ci docs](https://github.com/prescottprue/firebase-ci) #### Manual deploy 1. Run `firebase:login` 1. Initialize project with `firebase init` then answer: * What file should be used for Database Rules? -> `database.rules.json` * What do you want to use as your public directory? -> `build` * Configure as a single-page app (rewrite all urls to /index.html)? -> `Yes` * What Firebase project do you want to associate as default? -> **your Firebase project name** 1. Build Project: `npm run build` 1. Confirm Firebase config by running locally: `firebase serve` 1. Deploy to firebase: `firebase deploy` **NOTE:** You can use `firebase serve` to test how your application will work when deployed to Firebase, but make sure you run `npm run build` first. [npm-image]: https://img.shields.io/npm/v/testtesttest-yo.svg?style=flat-square [npm-url]: https://npmjs.org/package/testtesttest-yo [travis-image]: https://img.shields.io/travis/taforyou@hotmail.com/testtesttest-yo/master.svg?style=flat-square [travis-url]: https://travis-ci.org/taforyou@hotmail.com/testtesttest-yo [daviddm-image]: https://img.shields.io/david/taforyou@hotmail.com/testtesttest-yo.svg?style=flat-square [daviddm-url]: https://david-dm.org/taforyou@hotmail.com/testtesttest-yo [climate-image]: https://img.shields.io/codeclimate/github/taforyou@hotmail.com/testtesttest-yo.svg?style=flat-square [climate-url]: https://codeclimate.com/github/taforyou@hotmail.com/testtesttest-yo [coverage-image]: https://img.shields.io/codeclimate/coverage/github/taforyou@hotmail.com/testtesttest-yo.svg?style=flat-square [coverage-url]: https://codeclimate.com/github/taforyou@hotmail.com/testtesttest-yo [license-image]: https://img.shields.io/npm/l/testtesttest-yo.svg?style=flat-square [license-url]: https://github.com/taforyou@hotmail.com/testtesttest-yo/blob/master/LICENSE [code-style-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square [code-style-url]: http://standardjs.com/
taforyou/testtesttest-yo
README.md
Markdown
mit
8,556
58.741007
594
0.708935
false
package com.board.gd.domain.stock; import lombok.Data; import java.util.List; import java.util.stream.Collectors; /** * Created by gd.godong9 on 2017. 5. 19. */ @Data public class StockResult { private Long id; private String name; private String code; public static StockResult getStockResult(Stock stock) { StockResult stockResult = new StockResult(); stockResult.setId(stock.getId()); stockResult.setName(stock.getName()); stockResult.setCode(stock.getCode()); return stockResult; } public static List<StockResult> getStockResultList(List<Stock> stockList) { return stockList.stream() .map(stock -> getStockResult(stock)) .collect(Collectors.toList()); } }
godong9/spring-board
board/src/main/java/com/board/gd/domain/stock/StockResult.java
Java
mit
777
23.28125
79
0.658945
false
<?php /** * General purpose and commonly used PHP interface definitions * * @author Михаил Красильников <m.krasilnikov@yandex.ru> * @license http://opensource.org/licenses/MIT MIT */ namespace Mekras\Interfaces\Http\Message; use Psr\Http\Message\RequestInterface; /** * HTTP request factory * * Object can create empty instances of {@link \Psr\Http\Message\RequestInterface}. * This can be used to abstract from concrete PSR-7 implementation. * * @deprecated use https://packagist.org/packages/php-http/httplug * * @since 3.4 deprecated * @since 3.02 */ interface RequestFactory { /** * Create empty HTTP request * * @return RequestInterface * * @since 3.02 */ public function createEmptyRequest(); }
mekras/interfaces
lib/Http/Message/RequestFactory.php
PHP
mit
775
21.939394
83
0.694848
false
<!-- Unsafe sample input : get the UserData field of $_SESSION Uses a number_float_filter via filter_var function File : unsafe, use of untrusted data in CSS --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <style> <?php $tainted = $_SESSION['UserData']; $sanitized = filter_var($tainted, FILTER_SANITIZE_NUMBER_FLOAT); if (filter_var($sanitized, FILTER_VALIDATE_FLOAT)) $tainted = $sanitized ; else $tainted = "" ; //flaw echo $tainted ; ?> </style> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/unsafe/CWE_79__SESSION__func_FILTER-CLEANING-number_float_filter__Unsafe_use_untrusted_data-style.php
PHP
mit
1,407
21.349206
75
0.754797
false
var today = new Date(); console.log(today);
johnvoon/launch_school
210/lesson5/date_ex1.js
JavaScript
mit
43
21
23
0.697674
false
var RocketBoots = { isInitialized : false, readyFunctions : [], components : {}, loadedScripts: [], version: {full: "0.7.0", major: 0, minor: 7, patch: 0, codeName: "sun-master"}, _autoLoadRequirements: true, _initTimer : null, _MAX_ATTEMPTS : 300, _BOOTING_ELEMENT_ID : "booting-up-rocket-boots", _: null, // Lodash $: null, // jQuery //==== Classes Component : function(c){ this.fileName = c; this.name = null; this.isLoaded = false; this.isInstalled = false; }, //==== General Functions log : console.log, loadScript : function(url, callback){ //console.log("Loading script", url); // http://stackoverflow.com/a/7719185/1766230 var o = this; var s = document.createElement('script'); var r = false; var t; s.type = 'text/javascript'; s.src = "scripts/" + url + ".js"; s.className = "rocketboots-script"; s.onload = s.onreadystatechange = function() { //console.log( this.readyState ); //uncomment this line to see which ready states are called. if ( !r && (!this.readyState || this.readyState == 'complete') ) { r = true; o.loadedScripts.push(url); if (typeof callback == "function") callback(); } }; t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s, t); return this; }, //==== Component Functions hasComponent: function (componentClass) { if (typeof RocketBoots[componentClass] == "function") { return true; } else { return false; } }, installComponent : function (options, callback, attempt) { // options = { fileName, classNames, requirements, description, credits } var o = this; var mainClassName = (typeof options.classNames === 'object' && options.classNames.length > 0) ? options.classNames[0] : (options.classNames || options.className); var componentClass = options[mainClassName]; var requirements = options.requirements; var fileName = options.fileName; var callbacks = []; var i; // Setup array of callbacks if (typeof callback === 'function') { callbacks.push(callback); } if (typeof options.callback === 'function') { callbacks.push(options.callback); } if (typeof options.callbacks === 'object') { callbacks.concat(options.callbacks); } // Check for possible errors if (typeof mainClassName !== 'string') { console.error("Error installing component: mainClassName is not a string", mainClassName, options); console.log("options", options); return; } else if (typeof componentClass !== 'function') { console.error("Error installing component: class name", mainClassName, "not found on options:", options); console.log("options", options); return; } //console.log("Installing", fileName, " ...Are required components", requirements, " loaded?", o.areComponentsLoaded(requirements)); if (!o.areComponentsLoaded(requirements)) { var tryAgainDelay, compTimer; if (typeof attempt === "undefined") { attempt = 1; } else if (attempt > o._MAX_ATTEMPTS) { console.error("Could not initialize RocketBoots: too many attempts"); return false; } else { attempt++; } if (o._autoLoadRequirements) { console.log(fileName, "requires component(s)", requirements, " which aren't loaded. Autoloading..."); o.loadComponents(requirements); tryAgainDelay = 100 * attempt; } else { console.warn(fileName, "requires component(s)", requirements, " which aren't loaded."); tryAgainDelay = 5000; } compTimer = window.setTimeout(function(){ o.installComponent(options, callback, attempt); }, tryAgainDelay); } else { if (typeof o.components[fileName] == "undefined") { o.components[fileName] = new o.Component(fileName); } /* for (i = 0; i < callbacks.length; i++) { if (typeof callbacks[i] === "function") { callbacks[i](); } } */ o.components[fileName].name = mainClassName; o.components[fileName].isInstalled = true; o.components[fileName].callbacks = callbacks; // TODO: Add description and credits //o.components[fileName].description = ""; //o.components[fileName].credits = ""; o[mainClassName] = componentClass; } return this; }, getComponentByName: function (componentName) { var o = this; for (var cKey in o.components) { if (o.components[cKey].name == componentName) { return o.components[cKey]; } }; return; }, areComponentsLoaded: function (componentNameArr) { var o = this, areLoaded = true; if (typeof componentNameArr !== 'object') { return areLoaded; } for (var i = 0; i < componentNameArr.length; i++) { if (!o.isComponentInstalled(componentNameArr[i])) { areLoaded = false; } }; return areLoaded; }, isComponentInstalled: function (componentName) { var comp = this.getComponentByName(componentName); return (comp && comp.isInstalled); }, loadComponents : function(arr, path){ var o = this; var componentName; path = (typeof path === 'undefined') ? "rocketboots/" : path; for (var i = 0, al = arr.length; i < al; i++){ componentName = arr[i]; if (typeof o.components[componentName] == "undefined") { o.components[componentName] = new o.Component(componentName); o.loadScript(path + arr[i], function(){ o.components[componentName].isLoaded = true; }); } else { //console.warn("Trying to load", componentName, "component that already exists."); } } return this; }, loadCustomComponents : function (arr, path) { path = (typeof path === 'undefined') ? "" : path; return this.loadComponents(arr, path); }, areAllComponentsLoaded : function(){ var o = this; var componentCount = 0, componentsInstalledCount = 0; for (var c in o.components) { // if (o.components.hasOwnProperty(c)) { do stuff } componentCount++; if (o.components[c].isInstalled) componentsInstalledCount++; } console.log("RB Components Installed: " + componentsInstalledCount + "/" + componentCount); return (componentsInstalledCount >= componentCount); }, //==== Ready and Init Functions ready : function(callback){ if (typeof callback == "function") { if (this.isInitialized) { callback(this); } else { this.readyFunctions.push(callback); } } else { console.error("Ready argument (callback) not a function"); } return this; }, runReadyFunctions : function(){ var o = this; // Loop over readyFunctions and run each one var f, fn; for (var i = 0; o.readyFunctions.length > 0; i++){ f = o.readyFunctions.splice(i,1); fn = f[0]; fn(o); } return this; }, init : function(attempt){ var o = this; // TODO: allow dependecies to be injected rather than forcing them to be on the window scope var isJQueryUndefined = (typeof $ === "undefined"); var isLodashUndefined = (typeof _ === "undefined"); var areRequiredScriptsMissing = isJQueryUndefined || isLodashUndefined; if (typeof attempt === "undefined") { attempt = 1; } else if (attempt > o._MAX_ATTEMPTS) { console.error("Could not initialize RocketBoots: too many attempts"); return false; } else { attempt++; } //console.log("RB Init", attempt, (areRequiredScriptsMissing ? "Waiting on required objects from external scripts" : "")); if (!isJQueryUndefined) { o.$ = $; o.$('#' + o._BOOTING_ELEMENT_ID).show(); } if (!isLodashUndefined) { o._ = _; o.each = o.forEach = _.each; } function tryAgain () { // Clear previous to stop multiple inits from happening window.clearTimeout(o._initTimer); o._initTimer = window.setTimeout(function(){ o.init(attempt); }, (attempt * 10)); } // On first time through, do some things if (attempt === 1) { // Create "rb" alias if (typeof window.rb !== "undefined") { o._rb = window.rb; } window.rb = o; // Aliases o.window = window; o.document = window.document; // Load default components // TODO: make this configurable this.loadComponents(["Game"]); // Load required scripts if (isJQueryUndefined) { o.loadScript("libs/jquery-2.2.4.min", function(){ //o.init(1); }); } if (isLodashUndefined) { o.loadScript("libs/lodash.min", function(){ }); } } if (o.areAllComponentsLoaded() && !areRequiredScriptsMissing) { console.log("RB Init - All scripts and components are loaded.", o.loadedScripts, "\nRunning component callbacks..."); // TODO: These don't necessarily run in the correct order for requirements o.each(o.components, function(component){ o.each(component.callbacks, function(callback){ console.log("Callback for", component.name); callback(); // TODO: Make this run in the right context? }); }); console.log("RB Init - Running Ready functions.\n"); o.$('#' + o._BOOTING_ELEMENT_ID).hide(); o.runReadyFunctions(); o.isInitialized = true; return true; } tryAgain(); return false; } }; RocketBoots.init();
Lukenickerson/rocketboots
scripts/rocketboots/core.js
JavaScript
mit
8,886
29.122034
164
0.652937
false
<?php namespace ErenMustafaOzdal\LaravelModulesBase; use Illuminate\Database\Eloquent\Model; class Neighborhood extends Model { /** * The database table used by the model. * * @var string */ protected $table = 'neighborhoods'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['neighborhood']; public $timestamps = false; /* |-------------------------------------------------------------------------- | Model Relations |-------------------------------------------------------------------------- */ /** * Get the postal code of the district. * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function postalCode() { return $this->hasOne('App\PostalCode'); } /* |-------------------------------------------------------------------------- | Model Set and Get Attributes |-------------------------------------------------------------------------- */ /** * get the neighborhood uc first * * @return string */ public function getNeighborhoodUcFirstAttribute() { return ucfirst_tr($this->neighborhood); } }
erenmustafaozdal/laravel-modules-base
src/Neighborhood.php
PHP
mit
1,262
19.031746
79
0.434231
false
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; // Key used by getwork/getblocktemplate miners. // Allocated in StartRPCThreads, free'd in StopRPCThreads CReserveKey* pMiningKey = NULL; static std::string strRPCUserColonPass; // These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 5745 : 13000; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 12000000) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "Stop Netbits server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "Netbits server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name actor (function) okSafeMode threadSafe // ------------------------ ----------------------- ---------- ---------- { "help", &help, true, true }, { "stop", &stop, true, true }, { "getblockcount", &getblockcount, true, false }, { "getconnectioncount", &getconnectioncount, true, false }, { "getpeerinfo", &getpeerinfo, true, false }, { "addnode", &addnode, true, true }, { "getaddednodeinfo", &getaddednodeinfo, true, true }, { "getdifficulty", &getdifficulty, true, false }, { "getgenerate", &getgenerate, true, false }, { "setgenerate", &setgenerate, true, false }, { "gethashespersec", &gethashespersec, true, false }, { "getinfo", &getinfo, true, false }, { "getmininginfo", &getmininginfo, true, false }, { "getnewaddress", &getnewaddress, true, false }, { "getaccountaddress", &getaccountaddress, true, false }, { "setaccount", &setaccount, true, false }, { "getaccount", &getaccount, false, false }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false }, { "sendtoaddress", &sendtoaddress, false, false }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false }, { "backupwallet", &backupwallet, true, false }, { "keypoolrefill", &keypoolrefill, true, false }, { "walletpassphrase", &walletpassphrase, true, false }, { "walletpassphrasechange", &walletpassphrasechange, false, false }, { "walletlock", &walletlock, true, false }, { "encryptwallet", &encryptwallet, false, false }, { "validateaddress", &validateaddress, true, false }, { "getbalance", &getbalance, false, false }, { "move", &movecmd, false, false }, { "sendfrom", &sendfrom, false, false }, { "sendmany", &sendmany, false, false }, { "addmultisigaddress", &addmultisigaddress, false, false }, { "createmultisig", &createmultisig, true, true }, { "getrawmempool", &getrawmempool, true, false }, { "getblock", &getblock, false, false }, { "getblockhash", &getblockhash, false, false }, { "gettransaction", &gettransaction, false, false }, { "listtransactions", &listtransactions, false, false }, { "listaddressgroupings", &listaddressgroupings, false, false }, { "signmessage", &signmessage, false, false }, { "verifymessage", &verifymessage, false, false }, { "getwork", &getwork, true, false }, { "listaccounts", &listaccounts, false, false }, { "settxfee", &settxfee, false, false }, { "getblocktemplate", &getblocktemplate, true, false }, { "submitblock", &submitblock, false, false }, { "listsinceblock", &listsinceblock, false, false }, { "dumpprivkey", &dumpprivkey, true, false }, { "importprivkey", &importprivkey, false, false }, { "listunspent", &listunspent, false, false }, { "getrawtransaction", &getrawtransaction, false, false }, { "createrawtransaction", &createrawtransaction, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false }, { "signrawtransaction", &signrawtransaction, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false }, { "gettxoutsetinfo", &gettxoutsetinfo, true, false }, { "gettxout", &gettxout, true, false }, { "lockunspent", &lockunspent, false, false }, { "listlockunspent", &listlockunspent, false, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: netbits-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: netbits-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: netbits-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; loop { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection *conn); // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } else { ServiceConnection(conn); conn->close(); delete conn; } } void StartRPCThreads() { // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use netbitsd"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=netbitsrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Netbits Alert\" admin@foo.com\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl"); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); } void StopRPCThreads() { delete pMiningKey; pMiningKey = NULL; if (rpc_io_service == NULL) return; rpc_io_service->stop(); rpc_worker_group->join_all(); delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } void ServiceConnection(AcceptedConnection *conn) { bool fRun = true; while (fRun) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; break; } // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
net-bits/Netbits
src/bitcoinrpc.cpp
C++
mit
46,782
35.125097
159
0.582831
false
#!/usr/bin/env python3 # Copyright (c) 2015-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Utilities for manipulating blocks and transactions.""" import struct import time import unittest from .address import ( key_to_p2sh_p2wpkh, key_to_p2wpkh, script_to_p2sh_p2wsh, script_to_p2wsh, ) from .messages import ( CBlock, COIN, COutPoint, CTransaction, CTxIn, CTxInWitness, CTxOut, hash256, ser_uint256, tx_from_hex, uint256_from_str, ) from .script import ( CScript, CScriptNum, CScriptOp, OP_1, OP_CHECKMULTISIG, OP_CHECKSIG, OP_RETURN, OP_TRUE, ) from .script_util import ( key_to_p2wpkh_script, script_to_p2wsh_script, ) from .util import assert_equal WITNESS_SCALE_FACTOR = 4 MAX_BLOCK_SIGOPS = 20000 MAX_BLOCK_SIGOPS_WEIGHT = MAX_BLOCK_SIGOPS * WITNESS_SCALE_FACTOR # Genesis block time (regtest) TIME_GENESIS_BLOCK = 1296688602 # Coinbase transaction outputs can only be spent after this number of new blocks (network rule) COINBASE_MATURITY = 100 # Soft-fork activation heights DERSIG_HEIGHT = 102 # BIP 66 CLTV_HEIGHT = 111 # BIP 65 CSV_ACTIVATION_HEIGHT = 432 # From BIP141 WITNESS_COMMITMENT_HEADER = b"\xaa\x21\xa9\xed" NORMAL_GBT_REQUEST_PARAMS = {"rules": ["segwit"]} VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4 def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl=None, txlist=None): """Create a block (with regtest difficulty).""" block = CBlock() if tmpl is None: tmpl = {} block.nVersion = version or tmpl.get('version') or VERSIONBITS_LAST_OLD_BLOCK_VERSION block.nTime = ntime or tmpl.get('curtime') or int(time.time() + 600) block.hashPrevBlock = hashprev or int(tmpl['previousblockhash'], 0x10) if tmpl and not tmpl.get('bits') is None: block.nBits = struct.unpack('>I', bytes.fromhex(tmpl['bits']))[0] else: block.nBits = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams if coinbase is None: coinbase = create_coinbase(height=tmpl['height']) block.vtx.append(coinbase) if txlist: for tx in txlist: if not hasattr(tx, 'calc_sha256'): tx = tx_from_hex(tx) block.vtx.append(tx) block.hashMerkleRoot = block.calc_merkle_root() block.calc_sha256() return block def get_witness_script(witness_root, witness_nonce): witness_commitment = uint256_from_str(hash256(ser_uint256(witness_root) + ser_uint256(witness_nonce))) output_data = WITNESS_COMMITMENT_HEADER + ser_uint256(witness_commitment) return CScript([OP_RETURN, output_data]) def add_witness_commitment(block, nonce=0): """Add a witness commitment to the block's coinbase transaction. According to BIP141, blocks with witness rules active must commit to the hash of all in-block transactions including witness.""" # First calculate the merkle root of the block's # transactions, with witnesses. witness_nonce = nonce witness_root = block.calc_witness_merkle_root() # witness_nonce should go to coinbase witness. block.vtx[0].wit.vtxinwit = [CTxInWitness()] block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(witness_nonce)] # witness commitment is the last OP_RETURN output in coinbase block.vtx[0].vout.append(CTxOut(0, get_witness_script(witness_root, witness_nonce))) block.vtx[0].rehash() block.hashMerkleRoot = block.calc_merkle_root() block.rehash() def script_BIP34_coinbase_height(height): if height <= 16: res = CScriptOp.encode_op_n(height) # Append dummy to increase scriptSig size above 2 (see bad-cb-length consensus rule) return CScript([res, OP_1]) return CScript([CScriptNum(height)]) def create_coinbase(height, pubkey=None, extra_output_script=None, fees=0, nValue=50): """Create a coinbase transaction. If pubkey is passed in, the coinbase output will be a P2PK output; otherwise an anyone-can-spend output. If extra_output_script is given, make a 0-value output to that script. This is useful to pad block weight/sigops as needed. """ coinbase = CTransaction() coinbase.vin.append(CTxIn(COutPoint(0, 0xffffffff), script_BIP34_coinbase_height(height), 0xffffffff)) coinbaseoutput = CTxOut() coinbaseoutput.nValue = nValue * COIN if nValue == 50: halvings = int(height / 150) # regtest coinbaseoutput.nValue >>= halvings coinbaseoutput.nValue += fees if pubkey is not None: coinbaseoutput.scriptPubKey = CScript([pubkey, OP_CHECKSIG]) else: coinbaseoutput.scriptPubKey = CScript([OP_TRUE]) coinbase.vout = [coinbaseoutput] if extra_output_script is not None: coinbaseoutput2 = CTxOut() coinbaseoutput2.nValue = 0 coinbaseoutput2.scriptPubKey = extra_output_script coinbase.vout.append(coinbaseoutput2) coinbase.calc_sha256() return coinbase def create_tx_with_script(prevtx, n, script_sig=b"", *, amount, script_pub_key=CScript()): """Return one-input, one-output transaction object spending the prevtx's n-th output with the given amount. Can optionally pass scriptPubKey and scriptSig, default is anyone-can-spend output. """ tx = CTransaction() assert n < len(prevtx.vout) tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, 0xffffffff)) tx.vout.append(CTxOut(amount, script_pub_key)) tx.calc_sha256() return tx def create_transaction(node, txid, to_address, *, amount): """ Return signed transaction spending the first output of the input txid. Note that the node must have a wallet that can sign for the output that is being spent. """ raw_tx = create_raw_transaction(node, txid, to_address, amount=amount) tx = tx_from_hex(raw_tx) return tx def create_raw_transaction(node, txid, to_address, *, amount): """ Return raw signed transaction spending the first output of the input txid. Note that the node must have a wallet that can sign for the output that is being spent. """ psbt = node.createpsbt(inputs=[{"txid": txid, "vout": 0}], outputs={to_address: amount}) for _ in range(2): for w in node.listwallets(): wrpc = node.get_wallet_rpc(w) signed_psbt = wrpc.walletprocesspsbt(psbt) psbt = signed_psbt['psbt'] final_psbt = node.finalizepsbt(psbt) assert_equal(final_psbt["complete"], True) return final_psbt['hex'] def get_legacy_sigopcount_block(block, accurate=True): count = 0 for tx in block.vtx: count += get_legacy_sigopcount_tx(tx, accurate) return count def get_legacy_sigopcount_tx(tx, accurate=True): count = 0 for i in tx.vout: count += i.scriptPubKey.GetSigOpCount(accurate) for j in tx.vin: # scriptSig might be of type bytes, so convert to CScript for the moment count += CScript(j.scriptSig).GetSigOpCount(accurate) return count def witness_script(use_p2wsh, pubkey): """Create a scriptPubKey for a pay-to-witness TxOut. This is either a P2WPKH output for the given pubkey, or a P2WSH output of a 1-of-1 multisig for the given pubkey. Returns the hex encoding of the scriptPubKey.""" if not use_p2wsh: # P2WPKH instead pkscript = key_to_p2wpkh_script(pubkey) else: # 1-of-1 multisig witness_script = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG]) pkscript = script_to_p2wsh_script(witness_script) return pkscript.hex() def create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount): """Return a transaction (in hex) that spends the given utxo to a segwit output. Optionally wrap the segwit output using P2SH.""" if use_p2wsh: program = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG]) addr = script_to_p2sh_p2wsh(program) if encode_p2sh else script_to_p2wsh(program) else: addr = key_to_p2sh_p2wpkh(pubkey) if encode_p2sh else key_to_p2wpkh(pubkey) if not encode_p2sh: assert_equal(node.getaddressinfo(addr)['scriptPubKey'], witness_script(use_p2wsh, pubkey)) return node.createrawtransaction([utxo], {addr: amount}) def send_to_witness(use_p2wsh, node, utxo, pubkey, encode_p2sh, amount, sign=True, insert_redeem_script=""): """Create a transaction spending a given utxo to a segwit output. The output corresponds to the given pubkey: use_p2wsh determines whether to use P2WPKH or P2WSH; encode_p2sh determines whether to wrap in P2SH. sign=True will have the given node sign the transaction. insert_redeem_script will be added to the scriptSig, if given.""" tx_to_witness = create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount) if (sign): signed = node.signrawtransactionwithwallet(tx_to_witness) assert "errors" not in signed or len(["errors"]) == 0 return node.sendrawtransaction(signed["hex"]) else: if (insert_redeem_script): tx = tx_from_hex(tx_to_witness) tx.vin[0].scriptSig += CScript([bytes.fromhex(insert_redeem_script)]) tx_to_witness = tx.serialize().hex() return node.sendrawtransaction(tx_to_witness) class TestFrameworkBlockTools(unittest.TestCase): def test_create_coinbase(self): height = 20 coinbase_tx = create_coinbase(height=height) assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), height)
yenliangl/bitcoin
test/functional/test_framework/blocktools.py
Python
mit
9,688
36.550388
108
0.684558
false
#include "StdAfx.h" #include "Distance Joint Description.h" #include "Spring Description.h" #include "Distance Joint.h" #include <NxDistanceJointDesc.h> using namespace StillDesign::PhysX; DistanceJointDescription::DistanceJointDescription() : JointDescription( new NxDistanceJointDesc() ) { } DistanceJointDescription::DistanceJointDescription( NxDistanceJointDesc* desc ) : JointDescription( desc ) { } float DistanceJointDescription::MinimumDistance::get() { return this->UnmanagedPointer->minDistance; } void DistanceJointDescription::MinimumDistance::set( float value ) { this->UnmanagedPointer->minDistance = value; } float DistanceJointDescription::MaximumDistance::get() { return this->UnmanagedPointer->maxDistance; } void DistanceJointDescription::MaximumDistance::set( float value ) { this->UnmanagedPointer->maxDistance = value; } SpringDescription DistanceJointDescription::Spring::get() { return (SpringDescription)this->UnmanagedPointer->spring; } void DistanceJointDescription::Spring::set( SpringDescription value ) { this->UnmanagedPointer->spring = (NxSpringDesc)value; } DistanceJointFlag DistanceJointDescription::Flags::get() { return (DistanceJointFlag)this->UnmanagedPointer->flags; } void DistanceJointDescription::Flags::set( DistanceJointFlag value ) { this->UnmanagedPointer->flags = (NxDistanceJointFlag)value; } NxDistanceJointDesc* DistanceJointDescription::UnmanagedPointer::get() { return (NxDistanceJointDesc*)JointDescription::UnmanagedPointer; }
danteinforno/PhysX.Net
PhysX.Net/PhysX.Net/Source/Distance Joint Description.cpp
C++
mit
1,564
24.1
106
0.768542
false
using UnityEngine; using UnityEditor; using System.Collections; using UForms.Attributes; namespace UForms.Controls.Fields { /// <summary> /// /// </summary> [ExposeControl( "Object Field", "Fields" )] public class ObjectField : AbstractField< Object > { /// <summary> /// /// </summary> protected override Vector2 DefaultSize { get { return new Vector2( 200.0f, 16.0f ); } } /// <summary> /// /// </summary> protected override bool UseBackingFieldChangeDetection { get { return true; } } /// <summary> /// /// </summary> public System.Type Type { get; set; } /// <summary> /// /// </summary> public bool AllowSceneObjects { get; set; } public ObjectField() : base () { } /// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="allowSceneObjects"></param> /// <param name="value"></param> /// <param name="label"></param> public ObjectField( System.Type type, bool allowSceneObjects = false, Object value = null, string label = "" ) : base( value, label ) { Type = type; AllowSceneObjects = allowSceneObjects; } /// <summary> /// /// </summary> /// <param name="position"></param> /// <param name="size"></param> /// <param name="type"></param> /// <param name="allowSceneObjects"></param> /// <param name="value"></param> /// <param name="label"></param> public ObjectField( Vector2 position, Vector2 size, System.Type type, bool allowSceneObjects = false, Object value = null, string label = "" ) : base( position, size, value, label ) { Type = type; AllowSceneObjects = allowSceneObjects; } /// <summary> /// /// </summary> /// <returns></returns> protected override Object DrawAndUpdateValue() { return EditorGUI.ObjectField( ScreenRect, Label, m_cachedValue, Type, AllowSceneObjects ); } /// <summary> /// /// </summary> /// <param name="oldval"></param> /// <param name="newval"></param> /// <returns></returns> protected override bool TestValueEquality( Object oldval, Object newval ) { if ( oldval == null || newval == null ) { if ( oldval == null && newval == null ) { return true; } return false; } return oldval.Equals( newval ); } } }
kilguril/UForms
Assets/UForms/Runtime/Editor/Controls/Fields/ObjectField.cs
C#
mit
2,890
26.254717
189
0.475069
false
using Microsoft.AspNetCore.Http; using System.Linq; using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Primitives; using System.Globalization; namespace TCPServer.ServerImplemetation { class TCPRequest : HttpRequest { private TCPRequest() { } public static async Task<TCPRequest> Parse(TCPStream input, bool includeHeaders) { var r = new TCPRequest(); await r.ParseCore(input, includeHeaders).ConfigureAwait(false); return r; } private async Task ParseCore(TCPStream stream, bool includeHeaders) { Method = await stream.ReadStringAync().ConfigureAwait(false); var requestUri = await stream.ReadStringAync().ConfigureAwait(false); var uri = new Uri(requestUri); Scheme = uri.Scheme; IsHttps = false; Host = new HostString(uri.Host, uri.Port); PathBase = new PathString(uri.AbsolutePath); Path = new PathString(uri.AbsolutePath); QueryString = new QueryString(uri.Query); Query = new QueryCollection(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query)); Protocol = "http"; if(includeHeaders) { var headers = new List<Tuple<string, string>>(); var headersCount = await stream.ReadVarIntAsync().ConfigureAwait(false); for(int i = 0; i < (int)headersCount; i++) { var key = await stream.ReadStringAync().ConfigureAwait(false); var value = await stream.ReadStringAync().ConfigureAwait(false); headers.Add(Tuple.Create(key, value)); } foreach(var h in headers.GroupBy(g => g.Item1, g => g.Item2)) { Headers.Add(h.Key, new StringValues(h.ToArray())); } } var hasContent = (await stream.ReadVarIntAsync().ConfigureAwait(false)) == 1; if(hasContent) { var buffer = await stream.ReadBytesAync(TCPStream.ReadType.ManagedPool).ConfigureAwait(false); Body = new MemoryStream(buffer.Array); Body.SetLength(buffer.Count); ContentLength = buffer.Count; } } HttpContext _HttpContext; public void SetHttpContext(HttpContext context) { if(context == null) throw new ArgumentNullException(nameof(context)); _HttpContext = context; } public override HttpContext HttpContext => _HttpContext; public override string Method { get; set; } public override string Scheme { get; set; } public override bool IsHttps { get; set; } public override HostString Host { get; set; } public override PathString PathBase { get; set; } public override PathString Path { get; set; } public override QueryString QueryString { get; set; } public override IQueryCollection Query { get; set; } public override string Protocol { get; set; } IHeaderDictionary _Headers = new HeaderDictionary(); public override IHeaderDictionary Headers => _Headers; public override IRequestCookieCollection Cookies { get; set; } = new RequestCookieCollection(); public override long? ContentLength { get { StringValues value; if(!Headers.TryGetValue("Content-Length", out value)) return null; return long.Parse(value.FirstOrDefault(), CultureInfo.InvariantCulture); } set { Headers.Remove("Content-Length"); if(value != null) Headers.Add("Content-Length", value.Value.ToString(CultureInfo.InvariantCulture)); } } public override string ContentType { get { StringValues value; if(!Headers.TryGetValue("Content-Type", out value)) return null; return value.FirstOrDefault(); } set { Headers.Remove("Content-Type"); if(value != null) Headers.Add("Content-Type", new StringValues(value)); } } public override Stream Body { get; set; } public override bool HasFormContentType => false; public override IFormCollection Form { get; set; } FormCollection _ReadFormAsync = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>()); public override Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult<IFormCollection>(_ReadFormAsync); } } }
stratisproject/TCPServer
TCPServer/ServerImplemetation/TCPRequest.cs
C#
mit
4,306
22.264865
125
0.696561
false
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("UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c5d231db-9fb7-42cc-843f-72f9ca4ef087")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
sdanna/TeamcityTestSite
src/UnitTests/Properties/AssemblyInfo.cs
C#
mit
1,394
37.638889
84
0.744069
false
<?php namespace VirtualPersistAPI\VirtualPersistBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class VirtualPersistExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
paul-m/VirtualPersistAPI
src/VirtualPersistAPI/VirtualPersistBundle/DependencyInjection/VirtualPersistExtension.php
PHP
mit
903
31.25
104
0.734219
false
import { Selector } from 'testcafe' import { ROOT_URL, login } from '../e2e/utils' // eslint-disable-next-line fixture`imported data check`.beforeEach(async (t /*: TestController */) => { await t.setNativeDialogHandler(() => true) await t.navigateTo(`${ROOT_URL}/login`) await login(t) }) test('wait entry', async (t /*: TestController */) => { await t .expect(Selector('a').withText('Ask HN: single comment').exists) .ok({ timeout: 20000 }) })
reimagined/resolve
examples/ts/hacker-news/test/e2e-post-import/check-import.ts
TypeScript
mit
463
29.866667
76
0.652268
false
<!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/html; charset=utf-8" /> <title>vergerpc.config — Utilities for reading verge configuration files &mdash; verge-python 0.1.3 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.1.3', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="top" title="verge-python 0.1.3 documentation" href="index.html" /> <link rel="up" title="API reference" href="apireference.html" /> <link rel="prev" title="vergerpc.data — VERGE RPC service, data objects" href="vergerpc.data.html" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="vergerpc.data.html" title="vergerpc.data — VERGE RPC service, data objects" accesskey="P">previous</a> |</li> <li><a href="index.html">verge-python 0.1.3 documentation</a> &raquo;</li> <li><a href="apireference.html" accesskey="U">API reference</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="module-vergerpc.config"> <span id="vergerpc-config-utilities-for-reading-verge-configuration-files"></span><h1><a class="reference internal" href="#module-vergerpc.config" title="vergerpc.config"><tt class="xref py py-mod docutils literal"><span class="pre">vergerpc.config</span></tt></a> &#8212; Utilities for reading verge configuration files<a class="headerlink" href="#module-vergerpc.config" title="Permalink to this headline">¶</a></h1> <p>Utilities for reading verge configuration files.</p> <dl class="function"> <dt id="vergerpc.config.read_config_file"> <tt class="descclassname">vergerpc.config.</tt><tt class="descname">read_config_file</tt><big>(</big><em>filename</em><big>)</big><a class="headerlink" href="#vergerpc.config.read_config_file" title="Permalink to this definition">¶</a></dt> <dd><p>Read a simple <tt class="docutils literal"><span class="pre">'='</span></tt>-delimited config file. Raises <tt class="xref py py-const docutils literal"><span class="pre">IOError</span></tt> if unable to open file, or <tt class="xref py py-const docutils literal"><span class="pre">ValueError</span></tt> if an parse error occurs.</p> </dd></dl> <dl class="function"> <dt id="vergerpc.config.read_default_config"> <tt class="descclassname">vergerpc.config.</tt><tt class="descname">read_default_config</tt><big>(</big><em>filename=None</em><big>)</big><a class="headerlink" href="#vergerpc.config.read_default_config" title="Permalink to this definition">¶</a></dt> <dd><p>Read verge default configuration from the current user&#8217;s home directory.</p> <p>Arguments:</p> <ul class="simple"> <li><cite>filename</cite>: Path to a configuration file in a non-standard location (optional)</li> </ul> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="vergerpc.data.html" title="previous chapter"><tt class="docutils literal"><span class="pre">vergerpc.data</span></tt> &#8212; VERGE RPC service, data objects</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/vergerpc.config.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="vergerpc.data.html" title="vergerpc.data — VERGE RPC service, data objects" >previous</a> |</li> <li><a href="index.html">verge-python 0.1.3 documentation</a> &raquo;</li> <li><a href="apireference.html" >API reference</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2016, verge-python developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.1. </div> </body> </html>
vergecurrency/verge-python
doc/vergerpc.config.html
HTML
mit
5,858
44.6875
418
0.624594
false
<div itemprop="description" class="col-12"> <div [innerHTML]="description | sanitizeHtml"></div> </div>
aviabird/angularspree
src/app/product/components/product-detail-page/product-description/product-description.component.html
HTML
mit
106
34.333333
54
0.688679
false
# This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; only version 2 of the License is applicable. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # This plugin is to monitor queue lengths in Redis. Based on redis_info.py by # Garret Heaton <powdahound at gmail.com>, hence the GPL at the top. import collectd from contextlib import closing, contextmanager import socket # Host to connect to. Override in config by specifying 'Host'. REDIS_HOST = 'localhost' # Port to connect on. Override in config by specifying 'Port'. REDIS_PORT = 6379 # Verbose logging on/off. Override in config by specifying 'Verbose'. VERBOSE_LOGGING = False # Queue names to monitor. Override in config by specifying 'Queues'. QUEUE_NAMES = [] def fetch_queue_lengths(queue_names): """Connect to Redis server and request queue lengths. Return a dictionary from queue names to integers. """ try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((REDIS_HOST, REDIS_PORT)) log_verbose('Connected to Redis at %s:%s' % (REDIS_HOST, REDIS_PORT)) except socket.error, e: collectd.error('redis_queues plugin: Error connecting to %s:%d - %r' % (REDIS_HOST, REDIS_PORT, e)) return None queue_lengths = {} with closing(s) as redis_socket: for queue_name in queue_names: log_verbose('Requesting length of queue %s' % queue_name) redis_socket.sendall('llen %s\r\n' % queue_name) with closing(redis_socket.makefile('r')) as response_file: response = response_file.readline() if response.startswith(':'): try: queue_lengths[queue_name] = int(response[1:-1]) except ValueError: log_verbose('Invalid response: %r' % response) else: log_verbose('Invalid response: %r' % response) return queue_lengths def configure_callback(conf): """Receive configuration block""" global REDIS_HOST, REDIS_PORT, VERBOSE_LOGGING, QUEUE_NAMES for node in conf.children: if node.key == 'Host': REDIS_HOST = node.values[0] elif node.key == 'Port': REDIS_PORT = int(node.values[0]) elif node.key == 'Verbose': VERBOSE_LOGGING = bool(node.values[0]) elif node.key == 'Queues': QUEUE_NAMES = list(node.values) else: collectd.warning('redis_queues plugin: Unknown config key: %s.' % node.key) log_verbose('Configured with host=%s, port=%s' % (REDIS_HOST, REDIS_PORT)) for queue in QUEUE_NAMES: log_verbose('Watching queue %s' % queue) if not QUEUE_NAMES: log_verbose('Not watching any queues') def read_callback(): log_verbose('Read callback called') queue_lengths = fetch_queue_lengths(QUEUE_NAMES) if queue_lengths is None: # An earlier error, reported to collectd by fetch_queue_lengths return for queue_name, queue_length in queue_lengths.items(): log_verbose('Sending value: %s=%s' % (queue_name, queue_length)) val = collectd.Values(plugin='redis_queues') val.type = 'gauge' val.type_instance = queue_name val.values = [queue_length] val.dispatch() def log_verbose(msg): if not VERBOSE_LOGGING: return collectd.info('redis plugin [verbose]: %s' % msg) # register callbacks collectd.register_config(configure_callback) collectd.register_read(read_callback)
alphagov/govuk-puppet
modules/collectd/files/usr/lib/collectd/python/redis_queues.py
Python
mit
4,100
34.042735
78
0.647073
false
from .DiscreteFactor import State, DiscreteFactor from .CPD import TabularCPD from .JointProbabilityDistribution import JointProbabilityDistribution __all__ = ['TabularCPD', 'DiscreteFactor', 'State' ]
khalibartan/pgmpy
pgmpy/factors/discrete/__init__.py
Python
mit
236
28.5
70
0.694915
false
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dev to DevOps</title> <meta name="description" content="A framework for easily creating beautiful presentations using HTML"> <meta name="author" content="Hakim El Hattab"> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="stylesheet" href="css/reveal.min.css"> <link rel="stylesheet" href="css/theme/sky.css" id="theme"> <link rel="stylesheet" href="css/dev2devops.css"> <!-- For syntax highlighting --> <link rel="stylesheet" href="lib/css/zenburn.css"> <!-- If the query includes 'print-pdf', use the PDF print sheet --> <script> document.write( '<link rel="stylesheet" href="css/print/' + ( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) + '.css" type="text/css" media="print">' ); </script> <!--[if lt IE 9]> <script src="lib/js/html5shiv.js"></script> <![endif]--> </head> <body> <div class='screen-logo'> <div style='position: absolute; left: 20px; bottom: 20px; opacity: 0.5;'> <img src='img/constant-contact-logo.png' width='250'> </div> </div> <div class="reveal"> <!-- Any section element inside of this container is displayed as a slide --> <div class="slides"> <section> <h3>Intro to DevOps</h3> <p>Hi, my name is Dinshaw.</p> </section> <section> <h2>Computers</h2> <p>The cause of &ndash; and the solution to &ndash; all of life's problems.</p> </section> <section> <h2>A Brief History of Computing</h2> </section> <section> <img src="img/colosus.jpg"> <h3>Mainframe</h3> </section> <section> <img src="img/punch-cards.jpg"> <h3>Punch Cards</h3> </section> <section> <img src="img/computer.jpg"> <h3>Personal Computers</h3> </section> <section class='the-wall-goes-up'> <h3><span>Users . . .</span> The Wall <span>. . . Operations</span></h3> </section> <section> <img src="img/patrick.jpg"> <h3>Patrick Dubois</h3> <p>The 'Godfather' of DevOps</p> </section> <section> <h3>10+ Deploys Per Day:</h3> <h3>Dev and Ops Cooperation at Flickr</h3> <p>John Allspaw and Paul Hammond</p> <p>@ Velocity Conference 2009, San Jose</p> </section> <section> <img src="img/spock-scotty.jpg"> </section> <section> <h1>#devops</h1> </section> <section> <img src='img/culture.jpg'> <h3>Culture</h3> </section> <section> <img src='img/computer.jpg'> <h3>Tools</h3> </section> <section> <h3>... habits [tools &amp; culture] that allow us to survive in <em><strong>The Danger Zone</strong></em>.</h3> </section> <section> <h3>TurboTax</h3> <p>165 new-feature experiments in the 3 month tax season</p> <p><a href="http://network.intuit.com/2011/04/20/leadership-in-the-agile-age/">Economist conference 2011</a></p> </section> <section> <h3>Puppet: State of DevOps Report</h3> <p>'DevOps' up 50% on Linkedin keyword searches</p> </section> <section> <h3>Puppet: What is a DevOps Engineer?</h3> <ul> <li class='fragment'>Coding/Scripting</li> <li class='fragment'>Strong grasp of automation tools</li> <li class='fragment'>Process re-engineering</li> <li class='fragment'>A focus on business outcomes</li> <li class='fragment'>Communication &amp; Collaboration</li> </ul> </section> <section> <h2>Questions?</h2> </section> <section> <h2>Puppet &amp; Chef</h2> <ul> <li>Configuration Management</li> <li>Portable</li> <li>Repeatable</li> </ul> </section> <section> <h2>Puppet</h2> <ul> <li>http://puppetlabs.com/</li> <li>Ruby-like</li> <li>Modules @ Puppet Forge</li> </ul> <pre> <code> package { "gtypist": ensure => installed, provider => homebrew, } package { "redis": ensure => installed, provider => homebrew, } </code> </pre> </section> <section> <h2>Chef</h2> <ul> <li>http://www.getchef.com/</li> <li>Opscode</li> <li>Ruby</li> <li>Cookbooks @ Opscode Community</li> </ul> <pre> <code> package "mysql" do action :install end package "redis" do action :install end </code> </pre> </section> <section> <h2>Vagrant</h2> <p>http://www.vagrantup.com/</p> <pre> <code> Vagrant.configure do |config| config.vm.provision "puppet" do |puppet| puppet.manifests_path = "my_manifests" puppet.manifest_file = "default.pp" end end </code> </pre> </section> <section> <h2>You build it; you run it.</h2> <p>Deliver working code AND the environment it runs in.</p> </section> <section> <h2>T.D.D.</h2> <div> <blockquote> "If you tell the truth, you don't have to remember anything." </blockquote> <small class="author">- Mark Twain</small> </div> <p>Dev and Test are no longer separable</p> </section> <section> <h2>What we need from Ops</h2> <ul> <li class='fragment'>One button environment</li> <li class='fragment'>One button deploy</li> </ul> </section> <section> <h3>First Steps:</h3> <ul> <li class='fragment'>Automate something simple</li> <ul> <li class='fragment'>White space</li> <li class='fragment'>Dev Log rotation</li> <li class='fragment'><a href="http://dotfiles.github.io/">.Dotfiles</a></li> </ul> <li class='fragment'>Automate something not-so-simple</li> <ul> <li class='fragment'>Development machine configuration</li> <li class='fragment'>Production configuration</li> </ul> </ul> </section> <section> <h3>Questions?</h3> </section> <section> <h2>Google SRE</h2> <p class='fragment'>Hand-off Readiness Review</p> <ul> <li class='fragment'>Types/Frequency of defects</li> <li class='fragment'>Maturity of monitoring</li> <li class='fragment'>Release process</li> </ul> </section> <section> <h2><a href="http://techblog.netflix.com/2012/07/chaos-monkey-released-into-wild.html">Netflix: Chaos Monkey</a></h2> <p>April 21st, 2011 Amazon Web Service outage</p> <p>Netfilx maintained availability</p> </section> <section> <h2><a href="https://blog.twitter.com/2010/murder-fast-datacenter-code-deploys-using-bittorrent">Twitter Murder!</a></h2> <p class='fragment'>40 minute to 12 seconds!</p> </section> <section> <h2><a href="http://www.youtube.com/watch?v=-LxavzqLHj8">ChatOps at Github</a></h2> <p>Automating common operational tasks with Hu-Bot</p> <img src='img/hu-bot.jpg'> </section> <section> <h3> <a href='http://assets.en.oreilly.com/1/event/60/Velocity%20Culture%20Presentation.pdf'>Amazon @ O'rily Velocity Conf. 2011</a> </h3> <ul> <li class='fragment'>A deploy every 11.6 seconds</li> <li class='fragment'>Max deployments per hour: 10,000</li> <li class='fragment'>30,000 hosts simultaneously receiving a deployment</li> </ul> </section> <section class='links'> <ul> <li><a href="http://www.devopsdays.org/">DevOpsDays</a></li> <li><a href='http://velocityconf.com/velocity2009'>Velocity Conference 2009, San Jose</a></li> <li><a href='http://velocityconference.blip.tv/file/2284377/'>10+ Deploys Per Day: Dev and Ops Cooperation at Flickr</a></li> <li><a href='http://continuousdelivery.com/2012/10/theres-no-such-thing-as-a-devops-team/'>No such thing as a DevOps team</a></li> <li><a href='http://www.youtube.com/watch?v=disjFj4ruHg'>Why We Need DevOps Now</a></li> <li><a href='http://info.puppetlabs.com/2013-state-of-devops-report.html'>State of DevOps 2013 - Puppet Report</a></li> <li><a href="http://network.intuit.com/2011/04/20/leadership-in-the-agile-age/">Scott Cook on TurboTax @ Economist conference 2011</a></li> <li><a href="http://dotfiles.github.io/">.Dotfiles</a></li> <li><a href="http://docs.puppetlabs.com/learning/">Learning Puppet</a></li> <li><a href="http://forge.puppetlabs.com/">Puppet Forge</a></li> <li><a href='http://boxen.github.com/'>Boxen</a></li> <li><a href="http://vimeo.com/61172067">Boxen presentation: Managing an army of laptops</a></li> <li><a href='http://www.opscode.com/chef/'>Opscode</a></li> <li><a href="http://docs.opscode.com/">Learning Chef</a></li> <li><a href="https://github.com/opscode-cookbooks">Chef Cookbooks</a></li> <li><a href='http://www.youtube.com/watch?v=ZC91gZv-Uao'>Chef intro: TDDing tmux</a></li> <li><a href="http://techblog.netflix.com/2012/07/chaos-monkey-released-into-wild.html">Netflix: Chaos Monkey</a></li> <li><a href="https://blog.twitter.com/2010/murder-fast-datacenter-code-deploys-using-bittorrent">Twitter Murder!</a></li> <li><a href="http://www.youtube.com/watch?v=-LxavzqLHj8">ChatOps at Github</a></li> <li><a href="http://assets.en.oreilly.com/1/event/60/Velocity%20Culture%20Presentation.pdf">Amazon: A deploy every 11 seconds slides</a></li> <li><a href='http://vimeo.com/61172067'>Managing an Army of Laptops with Puppet</a></li> <li><a href='http://www.youtube.com/watch?v=ZC91gZv-Uao'>TDDing tmux</a></li> </ul> </section> <section> <p>Intro to DevOps</p> <p>Dinshaw Gobhai | <a href="mailto:dgobhai@constantcontact.com">dgobhai@constantcontact.com</a></p> </section> </div> </div> <script src="lib/js/head.min.js"></script> <script src="js/reveal.min.js"></script> <script> // Full list of configuration options available here: // https://github.com/hakimel/reveal.js#configuration Reveal.initialize({ controls: true, progress: true, history: true, center: true, theme: Reveal.getQueryHash().theme, // available themes are in /css/theme transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none // Optional libraries used to extend on reveal.js dependencies: [ { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, // { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, // { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } }, { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }, // { src: 'plugin/search/search.js', async: true, condition: function() { return !!document.body.classList; } } // { src: 'plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } } ] }); </script> </body> </head> </html>
dinshaw/intro-to-devops
index.html
HTML
mit
13,086
35.758427
177
0.542259
false
/* Ql builtin and external frmt command. format text */ package frmt import ( "clive/cmd" "clive/cmd/opt" "clive/nchan" "clive/zx" "errors" "fmt" "io" "strings" "unicode" ) type parFmt { rc chan string ec chan bool } func startPar(out io.Writer, indent0, indent string, max int) *parFmt { rc := make(chan string) ec := make(chan bool, 1) wc := make(chan string) pf := &parFmt{rc, ec} go func() { for s := range rc { if s == "\n" { wc <- s continue } words := strings.Fields(strings.TrimSpace(s)) for _, w := range words { wc <- w } } close(wc) }() go func() { pos, _ := fmt.Fprintf(out, "%s", indent0) firstword := true lastword := "x" for w := range wc { if len(w) == 0 { continue } if w == "\n" { fmt.Fprintf(out, "\n") firstword = true pos = 0 continue } if pos+len(w)+1 > max { fmt.Fprintf(out, "\n") pos, _ = fmt.Fprintf(out, "%s", indent) firstword = true } if !firstword && len(w)>0 && !unicode.IsPunct(rune(w[0])) { lastr := rune(lastword[len(lastword)-1]) if !strings.ContainsRune("([{", lastr) { fmt.Fprintf(out, " ") pos++ } } fmt.Fprintf(out, "%s", w) pos += len(w) firstword = false lastword = w } if !firstword { fmt.Fprintf(out, "\n") } close(ec) }() return pf } func (pf *parFmt) WriteString(s string) { pf.rc <- s } func (pf *parFmt) Close() { if pf == nil { return } close(pf.rc) <-pf.ec } type xCmd { *cmd.Ctx *opt.Flags wid int } func tabsOf(s string) int { for i := 0; i < len(s); i++ { if s[i] != '\t' { return i } } return 0 } func (x *xCmd) RunFile(d zx.Dir, dc <-chan []byte) error { if dc == nil { return nil } rc := nchan.Lines(dc, '\n') var pf *parFmt ntabs := 0 tabs := "" doselect { case <-x.Intrc: close(rc, "interrupted") pf.Close() return errors.New("interrupted") case s, ok := <-rc: if !ok { pf.Close() return cerror(rc) } if s=="\n" || s=="" { pf.Close() pf = nil x.Printf("\n") continue } nt := tabsOf(s) if nt != ntabs { pf.Close() pf = nil ntabs = nt tabs = strings.Repeat("\t", ntabs) } if pf == nil { pf = startPar(x.Stdout, tabs, tabs, x.wid) } pf.WriteString(s) } pf.Close() if err := cerror(rc); err != nil { return err } return nil } func Run(c cmd.Ctx) (err error) { argv := c.Args x := &xCmd{Ctx: &c} x.Flags = opt.New("{file}") x.Argv0 = argv[0] x.NewFlag("w", "wid: set max line width", &x.wid) args, err := x.Parse(argv) if err != nil { x.Usage(x.Stderr) return err } if x.wid < 10 { x.wid = 70 } if cmd.Ns == nil { cmd.MkNS() } return cmd.RunFiles(x, args...) }
sbinet-staging/clive
cmd/oldql/frmt/frmt.go
GO
mit
2,706
15.011834
71
0.54102
false
({ baseUrl: "../linesocial/public/js", paths: { jquery: "public/js/libs/jquery-1.9.1.js" }, name: "main", out: "main-built.js" })
jackygrahamez/LineSocialPublic
build.js
JavaScript
mit
157
18.75
48
0.515924
false
<?php namespace Usolv\TrackingBundle\Form\Model; use Doctrine\Common\Collections\ArrayCollection; class TimeRecordSearch { protected $project; public function setProject($project) { $this->project = $project; return $this; } public function getProject() { return $this->project; } }
LeQuangAnh/USVTracking
src/Usolv/TrackingBundle/Form/Model/TimeRecordSearch.php
PHP
mit
325
12.772727
48
0.676923
false
from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout from django import forms from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError from django.db import transaction from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from django_filters import FilterSet from easy_select2 import Select2 from crispy_layout_mixin import form_actions, to_row from utils import (TIPO_TELEFONE, YES_NO_CHOICES, get_medicos, get_or_create_grupo) from .models import Especialidade, EspecialidadeMedico, Usuario class EspecialidadeMedicoFilterSet(FilterSet): class Meta: model = EspecialidadeMedico fields = ['especialidade'] def __init__(self, *args, **kwargs): super(EspecialidadeMedicoFilterSet, self).__init__(*args, **kwargs) row1 = to_row([('especialidade', 12)]) self.form.helper = FormHelper() self.form.helper.form_method = 'GET' self.form.helper.layout = Layout( Fieldset(_('Pesquisar Médico'), row1, form_actions(save_label='Filtrar')) ) class MudarSenhaForm(forms.Form): nova_senha = forms.CharField( label="Nova Senha", max_length=30, widget=forms.PasswordInput( attrs={'class': 'form-control form-control-lg', 'name': 'senha', 'placeholder': 'Nova Senha'})) confirmar_senha = forms.CharField( label="Confirmar Senha", max_length=30, widget=forms.PasswordInput( attrs={'class': 'form-control form-control-lg', 'name': 'confirmar_senha', 'placeholder': 'Confirmar Senha'})) class LoginForm(AuthenticationForm): username = forms.CharField( label="Username", max_length=30, widget=forms.TextInput( attrs={'class': 'form-control form-control-lg', 'name': 'username', 'placeholder': 'Usuário'})) password = forms.CharField( label="Password", max_length=30, widget=forms.PasswordInput( attrs={'class': 'form-control', 'name': 'password', 'placeholder': 'Senha'})) class UsuarioForm(ModelForm): # Usuário password = forms.CharField( max_length=20, label=_('Senha'), widget=forms.PasswordInput()) password_confirm = forms.CharField( max_length=20, label=_('Confirmar Senha'), widget=forms.PasswordInput()) class Meta: model = Usuario fields = ['username', 'email', 'nome', 'password', 'password_confirm', 'data_nascimento', 'sexo', 'plano', 'tipo', 'cep', 'end', 'numero', 'complemento', 'bairro', 'referencia', 'primeiro_telefone', 'segundo_telefone'] widgets = {'email': forms.TextInput( attrs={'style': 'text-transform:lowercase;'})} def __init__(self, *args, **kwargs): super(UsuarioForm, self).__init__(*args, **kwargs) self.fields['primeiro_telefone'].widget.attrs['class'] = 'telefone' self.fields['segundo_telefone'].widget.attrs['class'] = 'telefone' def valida_igualdade(self, texto1, texto2, msg): if texto1 != texto2: raise ValidationError(msg) return True def clean(self): if ('password' not in self.cleaned_data or 'password_confirm' not in self.cleaned_data): raise ValidationError(_('Favor informar senhas atuais ou novas')) msg = _('As senhas não conferem.') self.valida_igualdade( self.cleaned_data['password'], self.cleaned_data['password_confirm'], msg) try: validate_password(self.cleaned_data['password']) except ValidationError as error: raise ValidationError(error) return self.cleaned_data @transaction.atomic def save(self, commit=False): usuario = super(UsuarioForm, self).save(commit) # Cria User u = User.objects.create(username=usuario.username, email=usuario.email) u.set_password(self.cleaned_data['password']) u.is_active = True u.groups.add(get_or_create_grupo(self.cleaned_data['tipo'].descricao)) u.save() usuario.user = u usuario.save() return usuario class UsuarioEditForm(ModelForm): # Primeiro Telefone primeiro_tipo = forms.ChoiceField( widget=forms.Select(), choices=TIPO_TELEFONE, label=_('Tipo Telefone')) primeiro_ddd = forms.CharField(max_length=2, label=_('DDD')) primeiro_numero = forms.CharField(max_length=10, label=_('Número')) primeiro_principal = forms.TypedChoiceField( widget=forms.Select(), label=_('Telefone Principal?'), choices=YES_NO_CHOICES) # Primeiro Telefone segundo_tipo = forms.ChoiceField( required=False, widget=forms.Select(), choices=TIPO_TELEFONE, label=_('Tipo Telefone')) segundo_ddd = forms.CharField(required=False, max_length=2, label=_('DDD')) segundo_numero = forms.CharField( required=False, max_length=10, label=_('Número')) segundo_principal = forms.ChoiceField( required=False, widget=forms.Select(), label=_('Telefone Principal?'), choices=YES_NO_CHOICES) class Meta: model = Usuario fields = ['username', 'email', 'nome', 'data_nascimento', 'sexo', 'plano', 'tipo', 'cep', 'end', 'numero', 'complemento', 'bairro', 'referencia', 'primeiro_telefone', 'segundo_telefone'] widgets = {'username': forms.TextInput(attrs={'readonly': 'readonly'}), 'email': forms.TextInput( attrs={'style': 'text-transform:lowercase;'}), } def __init__(self, *args, **kwargs): super(UsuarioEditForm, self).__init__(*args, **kwargs) self.fields['primeiro_telefone'].widget.attrs['class'] = 'telefone' self.fields['segundo_telefone'].widget.attrs['class'] = 'telefone' def valida_igualdade(self, texto1, texto2, msg): if texto1 != texto2: raise ValidationError(msg) return True def clean_primeiro_numero(self): cleaned_data = self.cleaned_data telefone = Telefone() telefone.tipo = self.data['primeiro_tipo'] telefone.ddd = self.data['primeiro_ddd'] telefone.numero = self.data['primeiro_numero'] telefone.principal = self.data['primeiro_principal'] cleaned_data['primeiro_telefone'] = telefone return cleaned_data def clean_segundo_numero(self): cleaned_data = self.cleaned_data telefone = Telefone() telefone.tipo = self.data['segundo_tipo'] telefone.ddd = self.data['segundo_ddd'] telefone.numero = self.data['segundo_numero'] telefone.principal = self.data['segundo_principal'] cleaned_data['segundo_telefone'] = telefone return cleaned_data @transaction.atomic def save(self, commit=False): usuario = super(UsuarioEditForm, self).save(commit) # Primeiro telefone tel = usuario.primeiro_telefone tel.tipo = self.data['primeiro_tipo'] tel.ddd = self.data['primeiro_ddd'] tel.numero = self.data['primeiro_numero'] tel.principal = self.data['primeiro_principal'] tel.save() usuario.primeiro_telefone = tel # Segundo telefone tel = usuario.segundo_telefone if tel: tel.tipo = self.data['segundo_tipo'] tel.ddd = self.data['segundo_ddd'] tel.numero = self.data['segundo_numero'] tel.principal = self.data['segundo_principal'] tel.save() usuario.segundo_telefone = tel # User u = usuario.user u.email = usuario.email u.groups.remove(u.groups.first()) u.groups.add(get_or_create_grupo(self.cleaned_data['tipo'].descricao)) u.save() usuario.save() return usuario class EspecialidadeMedicoForm(ModelForm): medico = forms.ModelChoiceField( queryset=get_medicos(), widget=Select2(select2attrs={'width': '535px'})) especialidade = forms.ModelChoiceField( queryset=Especialidade.objects.all(), widget=Select2(select2attrs={'width': '535px'})) class Meta: model = EspecialidadeMedico fields = ['especialidade', 'medico']
eduardoedson/scp
usuarios/forms.py
Python
mit
8,823
32.397727
79
0.605875
false
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Freeform - Control Panel * * The Control Panel master class that handles all of the CP requests and displaying. * * @package Solspace:Freeform * @author Solspace, Inc. * @copyright Copyright (c) 2008-2014, Solspace, Inc. * @link http://solspace.com/docs/freeform * @license http://www.solspace.com/license_agreement * @version 4.1.7 * @filesource freeform/mcp.freeform.php */ if ( ! class_exists('Module_builder_freeform')) { require_once 'addon_builder/module_builder.php'; } class Freeform_mcp extends Module_builder_freeform { private $migration_batch_limit = 100; private $pro_update = FALSE; // -------------------------------------------------------------------- /** * Constructor * * @access public * @param bool Enable calling of methods based on URI string * @return string */ public function __construct( $switch = TRUE ) { parent::__construct(); // Install or Uninstall Request if ((bool) $switch === FALSE) return; if ( ! function_exists('lang')) { ee()->load->helper('language'); } // -------------------------------------------- // Module Menu Items // -------------------------------------------- $menu = array( 'module_forms' => array( 'link' => $this->base, 'title' => lang('forms') ), 'module_fields' => array( 'link' => $this->base . AMP . 'method=fields', 'title' => lang('fields') ), 'module_fieldtypes' => array( 'link' => $this->base . AMP . 'method=fieldtypes', 'title' => lang('fieldtypes') ), 'module_notifications' => array( 'link' => $this->base . AMP . 'method=notifications', 'title' => lang('notifications') ), /*'module_export' => array( 'link' => $this->base . AMP . 'method=export', 'title' => lang('export') ),*/ 'module_utilities' => array( 'link' => $this->base . AMP . 'method=utilities', 'title' => lang('utilities') ), 'module_preferences' => array( 'link' => $this->base . AMP . 'method=preferences', 'title' => lang('preferences') ), 'module_documentation' => array( 'link' => FREEFORM_DOCS_URL, 'title' => lang('help'), 'new_window' => TRUE ), ); $this->cached_vars['lang_module_version'] = lang('freeform_module_version'); $this->cached_vars['module_version'] = FREEFORM_VERSION; $this->cached_vars['module_menu_highlight'] = 'module_forms'; $this->cached_vars['inner_nav_links'] = array(); // ------------------------------------- // css includes. WOOT! // ------------------------------------- $this->cached_vars['cp_stylesheet'] = array( 'chosen', 'standard_cp' ); $this->cached_vars['cp_javascript'] = array( 'standard_cp.min', 'chosen.jquery.min' ); // ------------------------------------- // custom CP? // ------------------------------------- $debug_normal = (ee()->input->get_post('debug_normal') !== FALSE); $is_crappy_ie_version = FALSE; $ua = strtolower($_SERVER['HTTP_USER_AGENT']); if (stristr($ua, 'msie 6') OR stristr($ua, 'msie 7') OR stristr($ua, 'msie 8')) { //technically this should be true for any IE version, but... $is_crappy_ie_version = TRUE; } if ( ! $debug_normal AND ! $is_crappy_ie_version AND ! $this->check_no($this->preference('use_solspace_mcp_style'))) { $this->cached_vars['cp_stylesheet'][] = 'custom_cp'; } //avoids AR collisions $this->data->get_module_preferences(); $this->data->get_global_module_preferences(); $this->data->show_all_sites(); // ------------------------------------- // run upgrade or downgrade scripts // ------------------------------------- if (FREEFORM_PRO AND $this->data->global_preference('ffp') === 'n' OR ! FREEFORM_PRO AND $this->data->global_preference('ffp') === 'y') { $_GET['method'] = 'freeform_module_update'; $this->pro_update = TRUE; } $this->cached_vars['module_menu'] = $menu; } // END Freeform_cp_base() //--------------------------------------------------------------------- // begin views //--------------------------------------------------------------------- // -------------------------------------------------------------------- /** * Module's Main Homepage * * @access public * @param string * @return null */ public function index ($message='') { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } return $this->forms($message); } // END index() // -------------------------------------------------------------------- /** * My Forms * * @access public * @param string $message incoming message for flash data * @return string html output */ public function forms($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $new_form_link = $this->mod_link(array( 'method' => 'edit_form' )); $this->cached_vars['new_form_link'] = $new_form_link; $this->add_crumb( lang('forms') ); $this->freeform_add_right_link(lang('new_form'), $new_form_link); $this->set_highlight('module_forms'); //-------------------------------------- // start vars //-------------------------------------- $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; // ------------------------------------- // pagination? // ------------------------------------- ee()->load->model('freeform_form_model'); if ( ! $this->data->show_all_sites()) { ee()->freeform_form_model->where( 'site_id', ee()->config->item('site_id') ); } $total_results = ee()->freeform_form_model->count(array(), FALSE); // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); $url = $this->mod_link(array( 'method' => 'forms' )); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $url), 'query_string_segment' => 'row' )); ee()->freeform_form_model->limit( $row_limit, $pagination_data['pagination_page'] ); $paginate = $pagination_data['pagination_links']; } ee()->freeform_form_model->order_by('form_label'); $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // Did they upgrade from FF3? // ------------------------------------- $this->cached_vars['legacy'] = FALSE; $this->cached_vars['migrate_link'] = ''; ee()->load->library('freeform_migration'); if ( ee()->freeform_migration->legacy() === TRUE ) { $this->cached_vars['legacy'] = TRUE; $this->cached_vars['migrate_link'] = $this->mod_link(array('method' => 'utilities')); } // ------------------------------------- // data // ------------------------------------- $rows = ee()->freeform_form_model->get(); $form_data = array(); if ($rows !== FALSE) { // ------------------------------------- // check for composer for each form // ------------------------------------- $form_ids = array(); $potential_composer_ids = array(); foreach ($rows as $row) { $form_ids[] = $row['form_id']; if ($this->is_positive_intlike($row['composer_id'])) { $potential_composer_ids[$row['form_id']] = $row['composer_id']; } } $has_composer = array(); if ( ! empty($potential_composer_ids)) { ee()->load->model('freeform_composer_model'); $composer_ids = ee()->freeform_composer_model ->key('composer_id', 'composer_id') ->where('preview !=', 'y') ->where_in( 'composer_id', array_values($potential_composer_ids) ) ->get(); if ( ! empty($composer_ids)) { foreach ($potential_composer_ids as $form_id => $composer_id) { if (in_array($composer_id, $composer_ids)) { $has_composer[$form_id] = $composer_id; } } } } // ------------------------------------- // suppliment rows // ------------------------------------- foreach ($rows as $row) { $row['submissions_count'] = ( $this->data->get_form_submissions_count($row['form_id']) ); $row['moderate_count'] = ( $this->data->get_form_needs_moderation_count($row['form_id']) ); $row['has_composer'] = isset( $has_composer[$row['form_id']] ); // ------------------------------------- // piles o' links // ------------------------------------- $row['form_submissions_link'] = $this->mod_link(array( 'method' => 'entries', 'form_id' => $row['form_id'] )); $row['form_moderate_link'] = $this->mod_link(array( 'method' => 'moderate_entries', 'form_id' => $row['form_id'], 'search_status' => 'pending' )); $row['form_edit_composer_link'] = $this->mod_link(array( 'method' => 'form_composer', 'form_id' => $row['form_id'] )); $row['form_settings_link'] = $this->mod_link(array( 'method' => 'edit_form', 'form_id' => $row['form_id'] )); $row['form_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_form', 'duplicate_id' => $row['form_id'] )); $row['form_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_form', 'form_id' => $row['form_id'] )); $form_data[] = $row; } } $this->cached_vars['form_data'] = $form_data; $this->cached_vars['form_url'] = $this->mod_link(array( 'method' => 'delete_confirm_form' )); // ---------------------------------------- // Load vars // ---------------------------------------- // ------------------------------------- // JS // ------------------------------------- ee()->cp->add_js_script( array('plugin' => array('tooltip', 'dataTables')) ); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'forms.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END forms // -------------------------------------------------------------------- /** * delete_confirm_form * * @access public * @return string */ public function delete_confirm_form () { $form_ids = ee()->input->get_post('form_id', TRUE); if ( ! is_array($form_ids) AND ! $this->is_positive_intlike($form_ids) ) { $this->actions()->full_stop(lang('no_form_ids_submitted')); } //already checked for numeric :p if ( ! is_array($form_ids)) { $form_ids = array($form_ids); } return $this->delete_confirm( 'delete_forms', array('form_ids' => $form_ids), 'delete_form_confirmation' ); } //END delete_confirm_form // -------------------------------------------------------------------- /** * delete_forms * * @access public * @return string */ public function delete_forms ($form_ids = array()) { $message = 'delete_form_success'; if ( empty($form_ids) ) { $form_ids = ee()->input->get_post('form_ids'); } if ( ! is_array($form_ids) AND $this->is_positive_intlike($form_ids)) { $form_ids = array($form_ids); } //if everything is all nice and array like, DELORT //but one last check on each item to make sure its a number if ( is_array($form_ids)) { ee()->load->library('freeform_forms'); foreach ($form_ids as $form_id) { if ($this->is_positive_intlike($form_id)) { ee()->freeform_forms->delete_form($form_id); } } } //the voyage home ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => $message ))); } //END delete_forms // -------------------------------------------------------------------- /** * Edit Form * * @access public * @return string html output */ public function edit_form () { // ------------------------------------- // form ID? we must be editing // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $update = $this->cached_vars['update'] = ($form_id != 0); // ------------------------------------- // default data // ------------------------------------- $inputs = array( 'form_id' => '0', 'form_name' => '', 'form_label' => '', 'default_status' => $this->data->defaults['default_form_status'], 'notify_admin' => 'n', 'notify_user' => 'n', 'user_email_field' => '', 'user_notification_id' => '0', 'admin_notification_id' => '0', 'admin_notification_email' => ee()->config->item('webmaster_email'), 'form_description' => '', 'template_id' => '0', 'composer_id' => '0', 'field_ids' => '', 'field_order' => '', ); // ------------------------------------- // updating? // ------------------------------------- if ($update) { $form_data = $this->data->get_form_info($form_id); if ($form_data) { foreach ($form_data as $key => $value) { if ($key == 'admin_notification_email') { $value = str_replace('|', ', ', $value); } if ($key == 'field_ids') { $value = ( ! empty($value)) ? implode('|', $value) : ''; } $inputs[$key] = form_prep($value); } } else { $this->actions()->full_stop(lang('invalid_form_id')); } } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( $update ? lang('update_form') . ': ' . $form_data['form_label'] : lang('new_form') ); $this->set_highlight('module_forms'); // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $this->cached_vars['duplicate_id'] = $duplicate_id; $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $form_data = $this->data->get_form_info($duplicate_id); if ($form_data) { foreach ($form_data as $key => $value) { if (in_array($key, array('form_id', 'form_label', 'form_name'))) { continue; } if ($key == 'field_ids') { $value = ( ! empty($value)) ? implode('|', $value) : ''; } if ($key == 'admin_notification_email') { $value = str_replace('|', ', ', $value); } $inputs[$key] = form_prep($value); } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $form_data['form_label']; } } if (isset($form_data['field_ids']) AND ! empty($form_data['field_ids']) AND isset($form_data['field_order']) AND ! empty($form_data['field_order'])) { $field_ids = $form_data['field_ids']; if ( ! is_array($field_ids)) { $field_ids = $this->actions()->pipe_split($field_ids); } $field_order = $form_data['field_order']; if ( ! is_array($field_order)) { $field_order = $this->actions()->pipe_split($field_order); } $missing_ids = array_diff($field_ids, $field_order); $inputs['field_order'] = implode('|', array_merge($field_order, $missing_ids)); } // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } // ------------------------------------- // select boxes // ------------------------------------- $this->cached_vars['statuses'] = $this->data->get_form_statuses(); ee()->load->model('freeform_field_model'); $available_fields = ee()->freeform_field_model->get(); $available_fields = ($available_fields !== FALSE) ? $available_fields : array(); //fields $this->cached_vars['available_fields'] = $available_fields; //notifications $this->cached_vars['notifications'] = $this->data->get_available_notification_templates(); // ------------------------------------- // user email fields // ------------------------------------- $user_email_fields = array('' => lang('choose_user_email_field')); $f_rows = ee()->freeform_field_model ->select('field_id, field_label, settings') ->get(array('field_type' => 'text')); //we only want fields that are being validated as email if ($f_rows) { foreach ($f_rows as $row) { $row_settings = json_decode($row['settings'], TRUE); $row_settings = (is_array($row_settings)) ? $row_settings : array(); if (isset($row_settings['field_content_type']) AND $row_settings['field_content_type'] == 'email') { $user_email_fields[$row['field_id']] = $row['field_label']; } } } $this->cached_vars['user_email_fields'] = $user_email_fields; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_form' )); // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; ee()->cp->add_js_script(array( 'ui' => array('draggable', 'droppable', 'sortable') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'edit_form.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_form // -------------------------------------------------------------------- /** * form composer * * ajax form and field builder * * @access public * @param string message lang line * @return string html output */ public function form_composer ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; // ------------------------------------- // form_id // ------------------------------------- $form_id = ee()->input->get_post('form_id', TRUE); $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $update = $form_data['composer_id'] != 0; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->base ); $this->add_crumb( lang('composer') . ': ' . $form_data['form_label'] ); $this->set_highlight('module_forms'); // ------------------------------------- // data // ------------------------------------- $this->cached_vars['form_data'] = $form_data; // ------------------------------------- // fields for composer // ------------------------------------- ee()->load->model('freeform_field_model'); $available_fields = ee()->freeform_field_model ->where('composer_use', 'y') ->order_by('field_label') ->key('field_name') ->get(); $available_fields = ($available_fields !== FALSE) ? $available_fields : array(); // ------------------------------------- // templates // ------------------------------------- ee()->load->model('freeform_template_model'); $available_templates = ee()->freeform_template_model ->where('enable_template', 'y') ->order_by('template_label') ->key('template_id', 'template_label') ->get(); $available_templates = ($available_templates !== FALSE) ? $available_templates : array(); // ------------------------------------- // get field output for composer // ------------------------------------- ee()->load->library('freeform_fields'); $field_composer_output = array(); $field_id_list = array(); foreach ($available_fields as $field_name => $field_data) { $field_id_list[$field_data['field_id']] = $field_name; //encode to keep JS from running //camel case because its exposed in JS $field_composer_output[$field_name] = $this->composer_field_data( $field_data['field_id'], $field_data, TRUE ); } $this->cached_vars['field_id_list'] = $this->json_encode($field_id_list); $this->cached_vars['field_composer_output_json'] = $this->json_encode($field_composer_output); $this->cached_vars['available_fields'] = $available_fields; $this->cached_vars['available_templates'] = $available_templates; $this->cached_vars['prohibited_field_names'] = $this->data->prohibited_names; $this->cached_vars['notifications'] = $this->data->get_available_notification_templates(); $this->cached_vars['disable_missing_submit_warning'] = $this->check_yes( $this->preference('disable_missing_submit_warning') ); // ------------------------------------- // previous composer data? // ------------------------------------- $composer_data = '{}'; if ($form_data['composer_id'] > 0) { ee()->load->model('freeform_composer_model'); $composer = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $form_data['composer_id']) ->get_row(); if ($composer !== FALSE) { $composer_data_test = $this->json_decode($composer['composer_data']); if ($composer_data_test) { $composer_data = $composer['composer_data']; } } } $this->cached_vars['composer_layout_data'] = $composer_data; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['lang_allowed_html_tags'] = ( lang('allowed_html_tags') . "&lt;" . implode("&gt;, &lt;", $this->data->allowed_html_tags) . "&gt;" ); $this->cached_vars['captcha_dummy_url'] = $this->sc->addon_theme_url . 'images/captcha.png'; $this->cached_vars['new_field_url'] = $this->mod_link(array( 'method' => 'edit_field', //this builds a URL, so yes this is intentionally a string 'modal' => 'true' ), TRUE); $this->cached_vars['field_data_url'] = $this->mod_link(array( 'method' => 'composer_field_data' ), TRUE); $this->cached_vars['composer_preview_url'] = $this->mod_link(array( 'method' => 'composer_preview', 'form_id' => $form_id ), TRUE); $this->cached_vars['composer_ajax_save_url'] = $this->mod_link(array( 'method' => 'save_composer_data', 'form_id' => $form_id ), TRUE); // $this->cached_vars['composer_save_url'] = $this->mod_link(array( 'method' => 'save_composer_data', 'form_id' => $form_id )); $this->cached_vars['allowed_html_tags'] = "'" . implode("','", $this->data->allowed_html_tags) . "'"; // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); ee()->cp->add_js_script(array( 'ui' => array('sortable', 'draggable', 'droppable'), 'file' => array('underscore', 'json2') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['cp_javascript'][] = 'composer_cp.min'; $this->cached_vars['cp_javascript'][] = 'edit_field_cp.min'; $this->cached_vars['cp_javascript'][] = 'security.min'; $this->cached_vars['current_page'] = $this->view( 'composer.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END form_composer // -------------------------------------------------------------------- /** * Composer preview * * @access public * @return mixed ajax return if detected or else html without cp */ public function composer_preview () { $form_id = $this->get_post_or_zero('form_id'); $template_id = $this->get_post_or_zero('template_id'); $composer_id = $this->get_post_or_zero('composer_id'); $preview_id = $this->get_post_or_zero('preview_id'); $subpreview = (ee()->input->get_post('subpreview') !== FALSE); $composer_page = $this->get_post_or_zero('composer_page'); if ( ! $this->data->is_valid_form_id($form_id)) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // is this a preview? // ------------------------------------- if ($preview_id > 0) { $preview_mode = TRUE; $composer_id = $preview_id; } $page_count = 1; // ------------------------------------- // main output or sub output? // ------------------------------------- if ( ! $subpreview) { // ------------------------------------- // get composer data and build page count // ------------------------------------- if ($composer_id > 0) { ee()->load->model('freeform_composer_model'); $composer = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $composer_id) ->get_row(); if ($composer !== FALSE) { $composer_data = $this->json_decode( $composer['composer_data'], TRUE ); if ($composer_data AND isset($composer_data['rows']) AND ! empty($composer_data['rows'])) { foreach ($composer_data['rows'] as $row) { if ($row == 'page_break') { $page_count++; } } } } } $page_url = array(); for ($i = 1, $l = $page_count; $i <= $l; $i++) { $page_url[] = $this->mod_link(array( 'method' => __FUNCTION__, 'form_id' => $form_id, 'template_id' => $template_id, 'preview_id' => $preview_id, 'subpreview' => 'true', 'composer_page' => $i )); } $this->cached_vars['page_url'] = $page_url; $this->cached_vars['default_preview_css'] = $this->sc->addon_theme_url . 'css/default_composer.css'; $this->cached_vars['jquery_src'] = ee()->functions->fetch_site_index(0, 0) . QUERY_MARKER . 'ACT=jquery'; $html = $this->view('composer_preview.html', NULL, TRUE); } else { $subhtml = "{exp:freeform:composer form_id='$form_id'"; $subhtml .= ($composer_page > 1) ? " multipage_page='" . $composer_page . "'" : ''; $subhtml .= ($template_id > 0) ? " composer_template_id='" . $template_id . "'" : ''; $subhtml .= ($preview_id > 0) ? " preview_id='" . $preview_id . "'" : ''; $subhtml .= "}"; $html = $this->actions()->template()->process_string_as_template($subhtml); } if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'html' => $html )); } else { exit($html); } } //end composer preview // -------------------------------------------------------------------- /** * entries * * @access public * @param string $message message lang line * @param bool $moderate are we moderating? * @param bool $export export? * @return string html output */ public function entries ( $message = '' , $moderate = FALSE, $export = FALSE) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg', TRUE)); } $this->cached_vars['message'] = $message; // ------------------------------------- // moderate // ------------------------------------- $search_status = ee()->input->get_post('search_status'); $moderate = ( $moderate AND ($search_status == 'pending' OR $search_status === FALSE ) ); //if moderate and search status was not submitted, fake into pending if ($moderate AND $search_status === FALSE) { $_POST['search_status'] = 'pending'; } $this->cached_vars['moderate'] = $moderate; $this->cached_vars['method'] = $method = ( $moderate ? 'moderate_entries' : 'entries' ); // ------------------------------------- // user using session id instead of cookies? // ------------------------------------- $this->cached_vars['fingerprint'] = $this->get_session_id(); // ------------------------------------- // form data? legit? GTFO? // ------------------------------------- $form_id = ee()->input->get_post('form_id'); ee()->load->library('freeform_forms'); ee()->load->model('freeform_form_model'); //form data does all of the proper id validity checks for us $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { $this->actions()->full_stop(lang('invalid_form_id')); exit(); } $this->cached_vars['form_id'] = $form_id; $this->cached_vars['form_label'] = $form_data['form_label']; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( $form_data['form_label'] . ': ' . lang($moderate ? 'moderate' : 'entries') ); $this->set_highlight('module_forms'); $this->freeform_add_right_link( lang('new_entry'), $this->mod_link(array( 'method' => 'edit_entry', 'form_id' => $form_id )) ); // ------------------------------------- // status prefs // ------------------------------------- $form_statuses = $this->data->get_form_statuses(); $this->cached_vars['form_statuses'] = $form_statuses; // ------------------------------------- // rest of models // ------------------------------------- ee()->load->model('freeform_entry_model'); ee()->freeform_entry_model->id($form_id); // ------------------------------------- // custom field labels // ------------------------------------- $standard_columns = $this->get_standard_column_names(); //we want author instead of author id until we get data $possible_columns = $standard_columns; //key = value $all_columns = array_combine($standard_columns, $standard_columns); $column_labels = array(); $field_column_names = array(); //field prefix $f_prefix = ee()->freeform_form_model->form_field_prefix; //keyed labels for the front end foreach ($standard_columns as $column_name) { $column_labels[$column_name] = lang($column_name); } // ------------------------------------- // check for fields with custom views for entry tables // ------------------------------------- ee()->load->library('freeform_fields'); //fields in this form foreach ($form_data['fields'] as $field_id => $field_data) { //outputs form_field_1, form_field_2, etc for ->select() $field_id_name = $f_prefix . $field_id; $field_column_names[$field_id_name] = $field_data['field_name']; $all_columns[$field_id_name] = $field_data['field_name']; $column_labels[$field_data['field_name']] = $field_data['field_label']; $column_labels[$field_id_name] = $field_data['field_label']; $possible_columns[] = $field_id; $instance =& ee()->freeform_fields->get_field_instance(array( 'field_id' => $field_id, 'field_data' => $field_data )); if ( ! empty($instance->entry_views)) { foreach ($instance->entry_views as $e_lang => $e_method) { $this->freeform_add_right_link( $e_lang, $this->mod_link(array( 'method' => 'field_method', 'field_id' => $field_id, 'field_method' => $e_method, 'form_id' => $form_id )) ); } } } // ------------------------------------- // visible columns // ------------------------------------- $visible_columns = $this->visible_columns($standard_columns, $possible_columns); $this->cached_vars['visible_columns'] = $visible_columns; $this->cached_vars['column_labels'] = $column_labels; $this->cached_vars['possible_columns'] = $possible_columns; $this->cached_vars['all_columns'] = $all_columns; // ------------------------------------- // prep unused from from possible // ------------------------------------- //so so used $un_used = array(); foreach ($possible_columns as $pcid) { $check = ($this->is_positive_intlike($pcid)) ? $f_prefix . $pcid : $pcid; if ( ! in_array($check, $visible_columns)) { $un_used[] = $check; } } $this->cached_vars['unused_columns'] = $un_used; // ------------------------------------- // build query // ------------------------------------- //base url for pagination $pag_url = array( 'method' => $method, 'form_id' => $form_id ); //cleans out blank keys from unset $find_columns = array_merge(array(), $visible_columns); $must_haves = array('entry_id'); // ------------------------------------- // search criteria // building query // ------------------------------------- $has_search = FALSE; $search_vars = array( 'search_keywords', 'search_status', 'search_date_range', 'search_date_range_start', 'search_date_range_end', 'search_on_field' ); foreach ($search_vars as $search_var) { $$search_var = ee()->input->get_post($search_var, TRUE); //set for output $this->cached_vars[$search_var] = ( ($$search_var) ? trim($$search_var) : '' ); } // ------------------------------------- // search keywords // ------------------------------------- if ($search_keywords AND trim($search_keywords) !== '' AND $search_on_field AND in_array($search_on_field, $visible_columns)) { ee()->freeform_entry_model->like( $search_on_field, $search_keywords ); //pagination $pag_url['search_keywords'] = $search_keywords; $pag_url['search_on_field'] = $search_on_field; $has_search = TRUE; } //no search on field? guess we had better search it all *gulp* else if ($search_keywords AND trim($search_keywords) !== '') { $first = TRUE; ee()->freeform_entry_model->group_like( $search_keywords, array_values($visible_columns) ); $pag_url['search_keywords'] = $search_keywords; $has_search = TRUE; } //status search? if ($moderate) { ee()->freeform_entry_model->where('status', 'pending'); } else if ($search_status AND in_array($search_status, array_flip( $form_statuses))) { ee()->freeform_entry_model->where('status', $search_status); //pagination $pag_url['search_status'] = $search_status; $has_search = TRUE; } // ------------------------------------- // date range? // ------------------------------------- //pagination if ($search_date_range == 'date_range') { //if its the same date, lets set the time to the end of the day if ($search_date_range_start == $search_date_range_end) { $search_date_range_end .= ' 23:59'; } if ($search_date_range_start !== FALSE) { $pag_url['search_date_range_start'] = $search_date_range_start; } if ($search_date_range_end !== FALSE) { $pag_url['search_date_range_end'] = $search_date_range_end; } //pagination if ($search_date_range_start OR $search_date_range_end) { $pag_url['search_date_range'] = 'date_range'; $has_search = TRUE; } } else if ($search_date_range !== FALSE) { $pag_url['search_date_range'] = $search_date_range; $has_search = TRUE; } ee()->freeform_entry_model->date_where( $search_date_range, $search_date_range_start, $search_date_range_end ); // ------------------------------------- // any searches? // ------------------------------------- $this->cached_vars['has_search'] = $has_search; // ------------------------------------- // data from all sites? // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->freeform_entry_model->where( 'site_id', ee()->config->item('site_id') ); } //we need the counts for exports and end results $total_entries = ee()->freeform_entry_model->count(array(), FALSE); // ------------------------------------- // orderby // ------------------------------------- $order_by = 'entry_date'; $p_order_by = ee()->input->get_post('order_by'); if ($p_order_by !== FALSE AND in_array($p_order_by, $all_columns)) { $order_by = $p_order_by; $pag_url['order_by'] = $order_by; } // ------------------------------------- // sort // ------------------------------------- $sort = ($order_by == 'entry_date') ? 'desc' : 'asc'; $p_sort = ee()->input->get_post('sort'); if ($p_sort !== FALSE AND in_array(strtolower($p_sort), array('asc', 'desc'))) { $sort = strtolower($p_sort); $pag_url['sort'] = $sort; } ee()->freeform_entry_model->order_by($order_by, $sort); $this->cached_vars['order_by'] = $order_by; $this->cached_vars['sort'] = $sort; // ------------------------------------- // export button // ------------------------------------- if ($total_entries > 0) { $this->freeform_add_right_link( lang('export_entries'), '#export_entries' ); } // ------------------------------------- // export url // ------------------------------------- $export_url = $pag_url; $export_url['moderate'] = $moderate ? 'true' : 'false'; $export_url['method'] = 'export_entries'; $this->cached_vars['export_url'] = $this->mod_link($export_url); // ------------------------------------- // export? // ------------------------------------- if ($export) { $export_fields = ee()->input->get_post('export_fields'); $export_labels = $column_labels; // ------------------------------------- // build possible select alls // ------------------------------------- $select = array(); //are we sending just the selected fields? if ($export_fields != 'all') { $select = array_unique(array_merge($must_haves, $find_columns)); foreach ($export_labels as $key => $value) { //clean export labels for json if ( ! in_array($key, $select)) { unset($export_labels[$key]); } } //get real names foreach ($select as $key => $value) { if (isset($field_column_names[$value])) { $select[$key] = $field_column_names[$value]; } } } //sending all fields means we need to still clean some labels else { foreach ($all_columns as $field_id_name => $field_name) { //clean export labels for json if ($field_id_name != $field_name) { unset($export_labels[$field_id_name]); } $select[] = $field_name; } } foreach ($export_labels as $key => $value) { //fix entities $value = html_entity_decode($value, ENT_COMPAT, 'UTF-8'); $export_labels[$key] = $value; if (isset($field_column_names[$key])) { $export_labels[$field_column_names[$key]] = $value; } } ee()->freeform_entry_model->select(implode(', ', $select)); // ------------------------------------- // check for chunking, etc // ------------------------------------- ee()->load->library('freeform_export'); ee()->freeform_export->format_dates = (ee()->input->get_post('format_dates') == 'y'); ee()->freeform_export->export(array( 'method' => ee()->input->get_post('export_method'), 'form_id' => $form_id, 'form_name' => $form_data['form_name'], 'output' => 'download', 'model' => ee()->freeform_entry_model, 'remove_entry_id' => ($export_fields != 'all' AND ! in_array('entry_id', $visible_columns)), 'header_labels' => $export_labels, 'total_entries' => $total_entries )); } //END if ($export) // ------------------------------------- // selects // ------------------------------------- $needed_selects = array_unique(array_merge($must_haves, $find_columns)); ee()->freeform_entry_model->select(implode(', ', $needed_selects)); //-------------------------------------- // pagination start vars //-------------------------------------- $pag_url = $this->mod_link($pag_url); $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; //moved above exports //$total_entries = ee()->freeform_entry_model->count(array(), FALSE); $current_page = 0; // ------------------------------------- // pagination? // ------------------------------------- // do we need pagination? if ($total_entries > $row_limit ) { $row_count = $this->get_post_or_zero('row'); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_entries, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $pag_url), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; $current_page = $pagination_data['pagination_page']; ee()->freeform_entry_model->limit($row_limit, $current_page); } $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // get data // ------------------------------------- $result_array = ee()->freeform_entry_model->get(); $count = $row_count; $entries = array(); if ( ! $result_array) { $result_array = array(); } $entry_ids = array(); foreach ($result_array as $row) { $entry_ids[] = $row['entry_id']; } // ------------------------------------- // allow pre_process // ------------------------------------- ee()->freeform_fields->apply_field_method(array( 'method' => 'pre_process_entries', 'form_id' => $form_id, 'entry_id' => $entry_ids, 'form_data' => $form_data, 'field_data' => $form_data['fields'] )); foreach ( $result_array as $row) { //apply display_entry_cp to our field data $field_parse = ee()->freeform_fields->apply_field_method(array( 'method' => 'display_entry_cp', 'form_id' => $form_id, 'entry_id' => $row['entry_id'], 'form_data' => $form_data, 'field_data' => $form_data['fields'], 'field_input_data' => $row )); $row = array_merge($row, $field_parse['variables']); $entry = array(); $entry['view_entry_link'] = $this->mod_link(array( 'method' => 'view_entry', 'form_id' => $form_id, 'entry_id' => $row['entry_id'] )); $entry['edit_entry_link'] = $this->mod_link(array( 'method' => 'edit_entry', 'form_id' => $form_id, 'entry_id' => $row['entry_id'] )); $entry['approve_link'] = $this->mod_link(array( 'method' => 'approve_entries', 'form_id' => $form_id, 'entry_ids' => $row['entry_id'] )); $entry['count'] = ++$count; $entry['id'] = $row['entry_id']; // ------------------------------------- // remove entry_id and author_id if we // arent showing them // ------------------------------------- if ( ! in_array('entry_id', $visible_columns)) { unset($row['entry_id']); } // ------------------------------------- // dates // ------------------------------------- if (in_array('entry_date', $visible_columns)) { $row['entry_date'] = $this->format_cp_date($row['entry_date']); } if (in_array('edit_date', $visible_columns)) { $row['edit_date'] = ($row['edit_date'] == 0) ? '' : $this->format_cp_date($row['edit_date']); } $entry['data'] = $row; $entries[] = $entry; } $this->cached_vars['entries'] = $entries; // ------------------------------------- // ajax request? // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'entries' => $entries, 'paginate' => $paginate, 'visibleColumns' => $visible_columns, 'allColumns' => $all_columns, 'columnLabels' => $column_labels, 'success' => TRUE )); exit(); } // ------------------------------------- // moderation count? // ------------------------------------- //lets not waste the query if we are already moderating $moderation_count = ( ( ! $moderate) ? $this->data->get_form_needs_moderation_count($form_id) : 0 ); if ($moderation_count > 0) { $this->cached_vars['lang_num_items_awaiting_moderation'] = str_replace( array('%num%', '%form_label%'), array($moderation_count, $form_data['form_label']), lang('num_items_awaiting_moderation') ); } $this->cached_vars['moderation_count'] = $moderation_count; $this->cached_vars['moderation_link'] = $this->mod_link(array( 'method' => 'moderate_entries', 'form_id' => $form_id, 'search_status' => 'pending' )); // ------------------------------------- // is admin? // ------------------------------------- $this->cached_vars['is_admin'] = $is_admin = ( ee()->session->userdata('group_id') == 1 ); // ------------------------------------- // can save field layout? // ------------------------------------- //$this->cached_vars['can_edit_layout'] = $can_edit_layout = ( // $is_admin OR // $this->check_yes($this->preference('allow_user_field_layout')) //); //just in case $this->cached_vars['can_edit_layout'] = TRUE; $this->freeform_add_right_link( lang('edit_field_layout'), '#edit_field_layout' ); // ------------------------------------- // member groups // ------------------------------------- $member_groups = array(); if ($is_admin) { ee()->db->select('group_id, group_title'); $member_groups = $this->prepare_keyed_result( ee()->db->get('member_groups'), 'group_id', 'group_title' ); } $this->cached_vars['member_groups'] = $member_groups; // ------------------------------------- // lang items // ------------------------------------- // ------------------------------------- // no results lang // ------------------------------------- $this->cached_vars['lang_no_results_for_form'] = ( ($has_search) ? lang('no_results_for_search') : ( ($moderate) ? lang('no_entries_awaiting_approval') : lang('no_entries_for_form') ) ); // ------------------------------------- // moderation lang // ------------------------------------- $this->cached_vars['lang_viewing_moderation'] = str_replace( '%form_label%', $form_data['form_label'], lang('viewing_moderation') ); // ------------------------------------- // other vars // ------------------------------------- $this->cached_vars['form_url'] = $this->mod_link(array( 'method' => 'entries_action', 'return_method' => (($moderate) ? 'moderate_' : '' ) . 'entries' )); $this->cached_vars['save_layout_url'] = $this->mod_link(array( 'method' => 'save_field_layout' )); // ------------------------------------- // js libs // ------------------------------------- $this->load_fancybox(); //$this->load_datatables(); ee()->cp->add_js_script(array( 'ui' => array('datepicker', 'sortable'), 'file' => 'underscore' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'entries.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END entries // -------------------------------------------------------------------- /** * Fire a field method as a page view * * @access public * @param string $message lang line to load for a message * @return string html output */ public function field_method ($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg', TRUE)); } $this->cached_vars['message'] = $message; // ------------------------------------- // goods // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $field_id = $this->get_post_or_zero('field_id'); $field_method = ee()->input->get_post('field_method'); $instance = FALSE; if ( $field_method == FALSE OR ! $this->data->is_valid_form_id($form_id) OR $field_id == 0) { ee()->functions->redirect($this->mod_link(array('method' => 'forms'))); } ee()->load->library('freeform_fields'); $instance =& ee()->freeform_fields->get_field_instance(array( 'form_id' => $form_id, 'field_id' => $field_id )); //legit? if ( ! is_object($instance) OR empty($instance->entry_views) OR //removed so you can post to this //! in_array($field_method, $instance->entry_views) OR ! is_callable(array($instance, $field_method))) { ee()->functions->redirect($this->mod_link(array('method' => 'forms'))); } $method_lang = lang('field_entry_view'); foreach ($instance->entry_views as $e_lang => $e_method) { if ($field_method == $e_method) { $method_lang = $e_lang; } } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('entries'), $this->mod_link(array( 'method' => 'entries', 'form_id' => $form_id )) ); $this->add_crumb($method_lang); $this->set_highlight('module_forms'); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $instance->$field_method(); // ------------------------------------- // loading these after the instance // incase the instance exits // ------------------------------------- $this->load_fancybox(); return $this->ee_cp_view('index.html'); } //END field_method // -------------------------------------------------------------------- /** * migrate collections * * @access public * @return string */ public function migrate_collections ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('utilities')); $this->set_highlight('module_utilities'); //-------------------------------------- // Library //-------------------------------------- ee()->load->library('freeform_migration'); //-------------------------------------- // Variables //-------------------------------------- $migrate_empty_fields = 'n'; $migrate_attachments = 'n'; $this->cached_vars['total'] = 0; $this->cached_vars['collections'] = ''; $collections = ee()->input->post('collections'); if ( $collections !== FALSE ) { $this->cached_vars['total'] = ee()->freeform_migration ->get_migration_count( $collections ); $this->cached_vars['collections'] = implode('|', $collections); if ($this->check_yes( ee()->input->post('migrate_empty_fields') ) ) { $migrate_empty_fields = 'y'; } if ($this->check_yes( ee()->input->post('migrate_attachments') ) ) { $migrate_attachments = 'y'; } } //-------------------------------------- // Migration ajax url //-------------------------------------- $this->cached_vars['ajax_url'] = $this->base . '&method=migrate_collections_ajax' . '&migrate_empty_fields=' . $migrate_empty_fields . '&migrate_attachments=' . $migrate_attachments . '&collections=' . urlencode( $this->cached_vars['collections'] ) . '&total=' . $this->cached_vars['total'] . '&batch=0'; //-------------------------------------- // images //-------------------------------------- //Success image $this->cached_vars['success_png_url'] = $this->sc->addon_theme_url . 'images/success.png'; // Error image $this->cached_vars['error_png_url'] = $this->sc->addon_theme_url . 'images/exclamation.png'; //-------------------------------------- // Javascript //-------------------------------------- $this->cached_vars['cp_javascript'][] = 'migrate'; ee()->cp->add_js_script( array('ui' => array('core', 'progressbar')) ); //-------------------------------------- // Load page //-------------------------------------- $this->cached_vars['current_page'] = $this->view( 'migrate.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } // End migrate collections // -------------------------------------------------------------------- /** * migrate collections ajax * * @access public * @return string */ public function migrate_collections_ajax() { $upper_limit = 9999; //-------------------------------------- // Base output //-------------------------------------- $out = array( 'done' => FALSE, 'batch' => ee()->input->get('batch'), 'total' => ee()->input->get('total') ); //-------------------------------------- // Libraries //-------------------------------------- ee()->load->library('freeform_migration'); //-------------------------------------- // Validate //-------------------------------------- $collections = ee()->input->get('collections'); if ( empty( $collections ) OR ee()->input->get('batch') === FALSE ) { $out['error'] = TRUE; $out['errors'] = array( 'no_collections' => lang('no_collections') ); $this->send_ajax_response($out); exit(); } //-------------------------------------- // Done? //-------------------------------------- if ( ee()->input->get('batch') !== FALSE AND ee()->input->get('total') !== FALSE AND ee()->input->get('batch') >= ee()->input->get('total') ) { $out['done'] = TRUE; $this->send_ajax_response($out); exit(); } //-------------------------------------- // Anything? //-------------------------------------- $collections = $this->actions()->pipe_split( urldecode( ee()->input->get('collections') ) ); $counts = ee()->freeform_migration->get_collection_counts($collections); if (empty($counts)) { $out['error'] = TRUE; $out['errors'] = array( 'no_collections' => lang('no_collections') ); $this->send_ajax_response($out); exit(); } //-------------------------------------- // Do any of the submitted collections have unmigrated entries? //-------------------------------------- $migrate = FALSE; foreach ( $counts as $form_name => $val ) { if ( ! empty( $val['unmigrated'] ) ) { $migrate = TRUE; } } if ( empty( $migrate ) ) { $out['done'] = TRUE; $this->send_ajax_response($out); exit(); } //-------------------------------------- // Master arrays //-------------------------------------- $forms = array(); $form_fields = array(); //-------------------------------------- // Loop and process //-------------------------------------- foreach ( $counts as $form_name => $val ) { //-------------------------------------- // For each collection, create a form //-------------------------------------- $form_data = ee()->freeform_migration->create_form($form_name); if ( $form_data !== FALSE ) { $forms[ $form_data['form_name'] ]['form_id'] = $form_data['form_id']; $forms[ $form_data['form_name'] ]['form_label'] = $form_data['form_label']; } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } //-------------------------------------- // For each collection, determine fields //-------------------------------------- $migrate_empty_fields = ( $this->check_yes(ee()->input->get('migrate_empty_fields')) ) ? 'y': 'n'; $fields = ee()->freeform_migration->get_fields_for_collection( $form_name, $migrate_empty_fields ); if ($fields !== FALSE) { $form_fields[ $form_name ]['fields'] = $fields; } else { $errors = ee()->freeform_migration->get_errors(); if ($errors !== FALSE) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } //-------------------------------------- // For each collection, create necessary fields if they don't yet exist. //-------------------------------------- $created_field_ids = array(); if ( ! empty( $form_fields[$form_name]['fields'] ) ) { foreach ( $form_fields[$form_name]['fields'] as $name => $attr ) { $field_id = ee()->freeform_migration->create_field( $forms[$form_name]['form_id'], $name, $attr ); if ($field_id !== FALSE ) { $created_field_ids[] = $field_id; } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } } } //-------------------------------------- // For each collection, create upload fields if needed. //-------------------------------------- $attachment_profiles = ee()->freeform_migration->get_attachment_profiles( $form_name ); if ($this->check_yes( ee()->input->get('migrate_attachments') ) AND $attachment_profiles !== FALSE ) { foreach ( $attachment_profiles as $row ) { $field_id = ee()->freeform_migration->create_upload_field( $forms[ $form_name ]['form_id'], $row['name'], $row ); if ($field_id !== FALSE) { $created_field_ids[] = $field_id; $upload_pref_id_map[ $row['pref_id'] ] = array( 'field_id' => $field_id, 'field_name' => $row['name'] ); } else { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } } if ( ! empty( $upload_pref_id_map ) ) { ee()->freeform_migration->set_property( 'upload_pref_id_map', $upload_pref_id_map ); } } //-------------------------------------- // Assign the fields to our form. //-------------------------------------- ee()->freeform_migration->assign_fields_to_form( $forms[ $form_data['form_name'] ]['form_id'], $created_field_ids ); //-------------------------------------- // Safeguard? //-------------------------------------- if ( ee()->input->get('batch') == $upper_limit ) { $this->send_ajax_response(array('done' => TRUE )); exit(); } //-------------------------------------- // Pass attachments pref //-------------------------------------- if ($this->check_yes( ee()->input->get('migrate_attachments') ) ) { ee()->freeform_migration->set_property('migrate_attachments', TRUE); } //-------------------------------------- // Grab entries //-------------------------------------- ee()->freeform_migration->set_property( 'batch_limit', $this->migration_batch_limit ); $entries = ee()->freeform_migration->get_legacy_entries($form_name); if ( $entries !== FALSE ) { foreach ( $entries as $entry ) { //-------------------------------------- // Insert //-------------------------------------- $entry_id = ee()->freeform_migration->set_legacy_entry( $forms[ $form_name ]['form_id'], $entry ); if ( $entry_id === FALSE ) { $errors = ee()->freeform_migration->get_errors(); if ( $errors !== FALSE ) { $out['error'] = TRUE; $out['errors'] = $errors; $this->send_ajax_response($out); exit(); } } else { $out['batch'] = $out['batch'] + 1; } } } } //-------------------------------------- // Are we done? //-------------------------------------- $this->send_ajax_response($out); exit(); } // End migrate collections ajax // -------------------------------------------------------------------- /** * moderate entries * * almost the same as entries but with some small modifications * * @access public * @param string message lang line * @return string html output */ public function moderate_entries ( $message = '' ) { return $this->entries($message, TRUE); } //END moderate_entries // -------------------------------------------------------------------- /** * Action from submitted entries links * * @access public * @return string html output */ public function entries_action () { $action = ee()->input->get_post('submit_action'); if ($action == 'approve') { return $this->approve_entries(); } else if ($action == 'delete') { return $this->delete_confirm_entries(); } /* else if ($action == 'edit') { $this->edit_entries(); } */ } //END entries_action // -------------------------------------------------------------------- /** * [edit_entry description] * * @access public * @return string parsed html */ public function edit_entry ($message = '') { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; // ------------------------------------- // edit? // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $entry_id = $this->get_post_or_zero('entry_id'); ee()->load->model('freeform_form_model'); ee()->load->model('freeform_entry_model'); $form_data = $this->data->get_form_info($form_id); if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $entry_data = array(); $edit = FALSE; if ($entry_id > 0) { $entry_data = ee()->freeform_entry_model ->id($form_id) ->where('entry_id', $entry_id) ->get_row(); if ($entry_data == FALSE) { return $this->actions()->full_stop(lang('invalid_entry_id')); } $edit = TRUE; } //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('forms'), $this->mod_link(array('method' => 'forms')) ); $this->add_crumb( lang($edit ? 'edit_entry' : 'new_entry') . ': ' . $form_data['form_label'] ); $this->set_highlight('module_forms'); // ------------------------------------- // load the template library in case // people get upset or something // ------------------------------------- if ( ! isset(ee()->TMPL) OR ! is_object(ee()->TMPL)) { ee()->load->library('template'); $globals['TMPL'] =& ee()->template; ee()->TMPL =& ee()->template; } // ------------------------------------- // get fields // ------------------------------------- ee()->load->library('freeform_fields'); $field_output_data = array(); $field_loop_ids = array_keys($form_data['fields']); if ($form_data['field_order'] !== '') { $order_ids = $this->actions()->pipe_split($form_data['field_order']); if ( ! empty($order_ids)) { //this makes sure that any fields in 'fields' are in the //order set as well. Will add missing at the end like this $field_loop_ids = array_merge( $order_ids, array_diff($field_loop_ids, $order_ids) ); } } foreach ($field_loop_ids as $field_id) { if ( ! isset($form_data['fields'][$field_id])) { continue; } $f_data = $form_data['fields'][$field_id]; $instance =& ee()->freeform_fields->get_field_instance(array( 'field_id' => $field_id, 'field_data' => $f_data, 'form_id' => $form_id, 'entry_id' => $entry_id, 'edit' => $edit, 'extra_settings' => array( 'entry_id' => $entry_id ) )); $column_name = ee()->freeform_entry_model->form_field_prefix . $field_id; $display_field_data = ''; if ($edit) { if (isset($entry_data[$column_name])) { $display_field_data = $entry_data[$column_name]; } else if (isset($entry_data[$f_data['field_name']])) { $display_field_data = $entry_data[$f_data['field_name']]; } } $field_output_data[$field_id] = array( 'field_display' => $instance->display_edit_cp($display_field_data), 'field_label' => $f_data['field_label'], 'field_description' => $f_data['field_description'] ); } $entry_data['screen_name'] = ''; $entry_data['group_title'] = ''; if (!empty($entry_data['author_id'])) { $member_data = ee()->db ->select('group_title, screen_name') ->from('members') ->join('member_groups', 'members.group_id = member_groups.group_id', 'left') ->where('member_id', $entry_data['author_id']) ->limit(1) ->get(); if ($member_data->num_rows() > 0) { $entry_data['screen_name'] = $member_data->row('screen_name'); $entry_data['group_title'] = $member_data->row('group_title'); } } if ($entry_data['screen_name'] == '') { $entry_data['screen_name'] = lang('guest'); $entry_data['group_title'] = lang('guest'); $guest_data = ee()->db ->select('group_title') ->from('member_groups') ->where('group_id', 3) ->limit(1) ->get(); if ($guest_data->num_rows() > 0) { $entry_data['group_title'] = $guest_data->row('group_title'); } } $entry_data['entry_date'] = ( ! empty( $entry_data['entry_date'] ) ) ? $entry_data['entry_date'] : ee()->localize->now; $entry_data['entry_date'] = $this->format_cp_date($entry_data['entry_date']); $entry_data['edit_date'] = (!empty($entry_data['edit_date'])) ? $this->format_cp_date($entry_data['edit_date']) : lang('n_a'); $this->cached_vars['entry_data'] = $entry_data; $this->cached_vars['field_output_data'] = $field_output_data; $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_entry' )); $this->cached_vars['form_id'] = $form_id; $this->cached_vars['entry_id'] = $entry_id; $this->cached_vars['statuses'] = $this->data->get_form_statuses(); // -------------------------------------------- // Load page // -------------------------------------------- $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; $this->cached_vars['current_page'] = $this->view( 'edit_entry.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_entry // -------------------------------------------------------------------- /** * fields * * @access public * @param string message * @return string */ public function fields ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->cached_vars['new_field_link'] = $this->mod_link(array( 'method' => 'edit_field' )); $this->add_crumb( lang('fields') ); //optional $this->freeform_add_right_link(lang('new_field'), $this->cached_vars['new_field_link']); $this->set_highlight('module_fields'); // ------------------------------------- // data // ------------------------------------- $this->cached_vars['fingerprint'] = $this->get_session_id(); $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; $field_data = array(); $paginate_url = array('method' => 'fields'); ee()->load->model('freeform_field_model'); ee()->freeform_field_model->select( 'field_label, field_name, field_type, field_id, field_description' ); // ------------------------------------- // search? // ------------------------------------- $field_search = ''; $field_search_on = ''; $search = ee()->input->get_post('field_search', TRUE); if ($search) { $f_search_on = ee()->input->get_post('field_search_on'); if ($f_search_on == 'field_name') { ee()->freeform_field_model->like('field_name', $search); $field_search_on = 'field_name'; } else if ($f_search_on == 'field_label') { ee()->freeform_field_model->like('field_label', $search); $field_search_on = 'field_label'; } else if ($f_search_on == 'field_description') { ee()->freeform_field_model->like('field_description', $search); $field_search_on = 'field_description'; } else //if ($f_search_on == 'all') { ee()->freeform_field_model->like('field_name', $search); ee()->freeform_field_model->or_like('field_label', $search); ee()->freeform_field_model->or_like('field_description', $search); $field_search_on = 'all'; } $field_search = $search; $paginate_url['field_search'] = $search; $paginate_url['field_search_on'] = $field_search_on; } $this->cached_vars['field_search'] = $field_search; $this->cached_vars['field_search_on'] = $field_search_on; // ------------------------------------- // all sites? // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->freeform_field_model->where( 'site_id', ee()->config->item('site_id') ); } ee()->freeform_field_model->order_by('field_name', 'asc'); $total_results = ee()->freeform_field_model->count(array(), FALSE); $row_count = 0; // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $this->mod_link($paginate_url)), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; ee()->freeform_field_model->limit( $row_limit, $pagination_data['pagination_page'] ); } $query = ee()->freeform_field_model->get(); $count = $row_count; if ($query !== FALSE) { foreach ($query as $row) { $row['count'] = ++$count; $row['field_edit_link'] = $this->mod_link(array( 'method' => 'edit_field', 'field_id' => $row['field_id'] )); $row['field_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_field', 'duplicate_id' => $row['field_id'] )); $row['field_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_fields', 'field_id' => $row['field_id'] )); $field_data[] = $row; } } $this->cached_vars['field_data'] = $field_data; $this->cached_vars['paginate'] = $paginate; // ------------------------------------- // ajax? // ------------------------------------- if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'field_data' => $field_data, 'paginate' => $paginate )); } // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'delete_confirm_fields' )); // ------------------------------------- // js // ------------------------------------- ee()->cp->add_js_script(array( 'file' => array('underscore', 'json2') )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'fields.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END fields // -------------------------------------------------------------------- /** * Edit Field * * @access public * @param bool $modal is this a modal version? * @return string */ public function edit_field ($modal = FALSE) { // ------------------------------------- // field ID? we must be editing // ------------------------------------- $field_id = $this->get_post_or_zero('field_id'); $update = ($field_id != 0); $modal = ( ! $modal AND $this->check_yes(ee()->input->get_post('modal'))) ? TRUE : $modal; $this->cached_vars['modal'] = $modal; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('fields') , $this->base . AMP . 'method=fields'); $this->add_crumb( lang(($update ? 'update_field' : 'new_field')) ); //optional //$this->freeform_add_right_link(lang('home'), $this->base . AMP . 'method=some_method'); $this->set_highlight('module_fields'); // ------------------------------------- // default values // ------------------------------------- $inputs = array( 'field_id' => '0', 'field_name' => '', 'field_label' => '', 'field_order' => '0', 'field_type' => $this->data->defaults['field_type'], 'field_length' => $this->data->defaults['field_length'], 'field_description' => '', 'submissions_page' => 'y', 'moderation_page' => 'y', 'composer_use' => 'y', ); // ------------------------------------- // defaults // ------------------------------------- $this->cached_vars['edit_warning'] = FALSE; $field_in_forms = array(); $incoming_settings = FALSE; if ($update) { $field_data = $this->data->get_field_info_by_id($field_id); if (empty($field_data)) { $this->actions()->full_stop(lang('invalid_field_id')); } foreach ($field_data as $key => $value) { $inputs[$key] = $value; } // ------------------------------------- // is this change going to affect any // forms that use this field? // ------------------------------------- $form_info = $this->data->get_form_info_by_field_id($field_id); if ($form_info AND ! empty($form_info)) { $this->cached_vars['edit_warning'] = TRUE; $form_names = array(); foreach ($form_info as $row) { $field_in_forms[] = $row['form_id']; $form_names[] = $row['form_label']; } $this->cached_vars['lang_field_edit_warning'] = lang('field_edit_warning'); $this->cached_vars['lang_field_edit_warning_desc'] = str_replace( '%form_names%', implode(', ', $form_names), lang('field_edit_warning_desc') ); } } $this->cached_vars['form_ids'] = implode('|', array_unique($field_in_forms)); // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $duplicate = FALSE; $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $field_data = $this->data->get_field_info_by_id($duplicate_id); if ($field_data) { $duplicate = TRUE; foreach ($field_data as $key => $value) { if (in_array($key, array('field_id', 'field_label', 'field_name'))) { continue; } $inputs[$key] = $value; } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $field_data['field_label']; } } // ------------------------------------- // get available field types // ------------------------------------- ee()->load->library('freeform_fields'); $this->cached_vars['fieldtypes'] = ee()->freeform_fields->get_available_fieldtypes(); // ------------------------------------- // get available forms to add this to // ------------------------------------- if ( ! $this->data->show_all_sites()) { ee()->db->where('site_id', ee()->config->item('site_id')); } $this->cached_vars['available_forms'] = $this->prepare_keyed_result( ee()->db->get('freeform_forms'), 'form_id' ); // ------------------------------------- // add desc and lang for field types // ------------------------------------- foreach($this->cached_vars['fieldtypes'] as $fieldtype => $field_data) { //settings? $settings = ( ($update OR $duplicate ) AND $inputs['field_type'] == $fieldtype AND isset($inputs['settings']) ) ? json_decode($inputs['settings'], TRUE) : array(); //we are encoding this and decoding in JS because leaving the //fields intact while in storage in the html makes dupes of fields. //I could do some html moving around, but that would keep running //individual settings JS over and over again when it should //only be run on display. $this->cached_vars['fieldtypes'][$fieldtype]['settings_output'] = base64_encode( ee()->freeform_fields->fieldtype_display_settings_output( $fieldtype, $settings ) ); } if (isset($inputs['field_label'])) { $inputs['field_label'] = form_prep($inputs['field_label']); } if (isset($inputs['field_description'])) { $inputs['field_description'] = form_prep($inputs['field_description']); } // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_field' )); //---------------------------------------- // Load vars //---------------------------------------- $this->cached_vars['lang_submit_word'] = lang( ($update ? 'update_field' : 'create_field') ); $this->cached_vars['prohibited_field_names'] = $this->data->prohibited_names; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['cp_javascript'][] = 'edit_field_cp.min'; $this->cached_vars['current_page'] = $this->view( 'edit_field.html', NULL, TRUE ); if ($modal) { exit($this->cached_vars['current_page']); } $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; return $this->ee_cp_view('index.html'); } //END edit_field // -------------------------------------------------------------------- /** * Field Types * * @access public * @param message * @return string */ public function fieldtypes ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->add_crumb( lang('fieldtypes') ); $this->set_highlight('module_fieldtypes'); //-------------------------------------- // start vars //-------------------------------------- $fieldtypes = array(); ee()->load->library('freeform_fields'); ee()->load->model('freeform_field_model'); ee()->load->model('freeform_fieldtype_model'); if ( ( $installed_fieldtypes = ee()->freeform_fieldtype_model->installed_fieldtypes() ) === FALSE ) { $installed_fieldtypes = array(); } $fieldtypes = ee()->freeform_fields->get_installable_fieldtypes(); // ------------------------------------- // missing fieldtype folders? // ------------------------------------- $missing_fieldtypes = array(); foreach ($installed_fieldtypes as $name => $version) { if ( ! array_key_exists($name, $fieldtypes)) { $missing_fieldtypes[] = $name; } } // ------------------------------------- // add urls and crap // ------------------------------------- $action_url = $this->base . AMP . 'method=freeform_fieldtype_action'; foreach ($fieldtypes as $name => $data) { $fieldtypes[$name]['installed_lang'] = lang($data['installed'] ? 'installed' : 'not_installed'); $action = ($data['installed'] ? 'uninstall' : 'install'); $fieldtypes[$name]['action_lang'] = lang($action); $fieldtypes[$name]['action_url'] = $this->mod_link(array( 'method' => 'freeform_fieldtype_action', 'name' => $name, 'action' => $action, //some other time -gf //'folder' => base64_encode($data['folder']) )); } $this->cached_vars['fieldtypes'] = $fieldtypes; $this->cached_vars['freeform_ft_docs_url'] = $this->data->doc_links['custom_fields']; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'fieldtypes.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END field_types // -------------------------------------------------------------------- /** * notifications * * @access public * @param string message to output * @return string outputted template */ public function notifications ( $message = '' ) { // ------------------------------------- // Messages // ------------------------------------- if ($message == '' AND ! in_array(ee()->input->get('msg'), array(FALSE, '')) ) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------------- // Crumbs and tab highlight //-------------------------------------------- $this->cached_vars['new_notification_link'] = $this->mod_link(array( 'method' => 'edit_notification' )); $this->add_crumb( lang('notifications') ); $this->freeform_add_right_link( lang('new_notification'), $this->cached_vars['new_notification_link'] ); $this->set_highlight('module_notifications'); // ------------------------------------- // data // ------------------------------------- $row_limit = $this->data->defaults['mcp_row_limit']; $paginate = ''; $row_count = 0; $notification_data = array(); ee()->db->start_cache(); ee()->db->order_by('notification_name', 'asc'); if ( ! $this->data->show_all_sites()) { ee()->db->where('site_id', ee()->config->item('site_id')); } ee()->db->from('freeform_notification_templates'); ee()->db->stop_cache(); $total_results = ee()->db->count_all_results(); // do we need pagination? if ( $total_results > $row_limit ) { $row_count = $this->get_post_or_zero('row'); $url = $this->mod_link(array( 'method' => 'notifications' )); //get pagination info $pagination_data = $this->universal_pagination(array( 'total_results' => $total_results, 'limit' => $row_limit, 'current_page' => $row_count, 'pagination_config' => array('base_url' => $url), 'query_string_segment' => 'row' )); $paginate = $pagination_data['pagination_links']; ee()->db->limit($row_limit, $pagination_data['pagination_page']); } $query = ee()->db->get(); ee()->db->flush_cache(); if ($query->num_rows() > 0) { foreach ($query->result_array() as $row) { $row['notification_edit_link'] = $this->mod_link(array( 'method' => 'edit_notification', 'notification_id' => $row['notification_id'], )); $row['notification_duplicate_link'] = $this->mod_link(array( 'method' => 'edit_notification', 'duplicate_id' => $row['notification_id'], )); $row['notification_delete_link'] = $this->mod_link(array( 'method' => 'delete_confirm_notification', 'notification_id' => $row['notification_id'], )); $notification_data[] = $row; } } $this->cached_vars['notification_data'] = $notification_data; $this->cached_vars['paginate'] = $paginate; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'delete_confirm_notification' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'notifications.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END notifications // -------------------------------------------------------------------- /** * edit_notification * * @access public * @return string */ public function edit_notification () { // ------------------------------------- // notification ID? we must be editing // ------------------------------------- $notification_id = $this->get_post_or_zero('notification_id'); $update = ($notification_id != 0); //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb( lang('notifications'), $this->base . AMP . 'method=notifications' ); $this->add_crumb( lang(($update ? 'update_notification' : 'new_notification')) ); $this->set_highlight('module_notifications'); // ------------------------------------- // data items // ------------------------------------- $inputs = array( 'notification_id' => '0', 'notification_name' => '', 'notification_label' => '', 'notification_description' => '', 'wordwrap' => $this->data->defaults['wordwrap'], 'allow_html' => $this->data->defaults['allow_html'], 'from_name' => form_prep(ee()->config->item('webmaster_name')), 'from_email' => ee()->config->item('webmaster_email'), 'reply_to_email' => ee()->config->item('webmaster_email'), 'email_subject' => '', 'template_data' => '', 'include_attachments' => 'n' ); // ------------------------------------- // defaults // ------------------------------------- $this->cached_vars['edit_warning'] = FALSE; if ($update) { $notification_data = $this->data->get_notification_info_by_id($notification_id); foreach ($notification_data as $key => $value) { $inputs[$key] = form_prep($value); } // ------------------------------------- // is this change going to affect any // forms that use this field? // ------------------------------------- $form_info = $this->data->get_form_info_by_notification_id($notification_id); if ($form_info AND ! empty($form_info)) { $this->cached_vars['edit_warning'] = TRUE; $form_names = array(); foreach ($form_info as $row) { $form_names[] = $row['form_label']; } $this->cached_vars['lang_notification_edit_warning'] = str_replace( '%form_names%', implode(', ', $form_names), lang('notification_edit_warning') ); } } // ------------------------------------- // duplicating? // ------------------------------------- $duplicate_id = $this->get_post_or_zero('duplicate_id'); $this->cached_vars['duplicated'] = FALSE; if ( ! $update AND $duplicate_id > 0) { $notification_data = $this->data->get_notification_info_by_id($duplicate_id); if ($notification_data) { foreach ($notification_data as $key => $value) { //TODO: remove other items that dont need to be duped? if (in_array($key, array( 'notification_id', 'notification_label', 'notification_name' ))) { continue; } $inputs[$key] = form_prep($value); } $this->cached_vars['duplicated'] = TRUE; $this->cached_vars['duplicated_from'] = $notification_data['notification_label']; } } // ------------------------------------- // get available fields // ------------------------------------- ee()->load->model('freeform_field_model'); $this->cached_vars['available_fields'] = array(); if ( ( $fields = ee()->freeform_field_model->get() ) !== FALSE ) { $this->cached_vars['available_fields'] = $fields; } $this->cached_vars['standard_tags'] = $this->data->standard_notification_tags; // ------------------------------------- // load inputs // ------------------------------------- foreach ($inputs as $key => $value) { $this->cached_vars[$key] = $value; } $this->cached_vars['form_uri'] = $this->base . AMP . 'method=save_notification'; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['lang_submit_word'] = lang( ($update ? 'update_notification' : 'create_notification') ); $this->load_fancybox(); $this->cached_vars['cp_javascript'][] = 'jquery.smooth-scroll.min'; // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'edit_notification.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END edit_notification // -------------------------------------------------------------------- /** * preferences * * @access public * @return string */ public function preferences ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('preferences')); $this->set_highlight('module_preferences'); // ------------------------------------- // global prefs // ------------------------------------- $this->cached_vars['msm_enabled'] = $msm_enabled = $this->data->msm_enabled; $is_admin = (ee()->session->userdata('group_id') == 1); $this->cached_vars['show_global_prefs'] = ($is_admin AND $msm_enabled); $global_pref_data = array(); $global_prefs = $this->data->get_global_module_preferences(); $default_global_prefs = array_keys($this->data->default_global_preferences); //dynamically get prefs and lang so we can just add them to defaults foreach( $global_prefs as $key => $value ) { //this skips things that don't need to be shown on this page //so we can use the prefs table for other areas of the addon if ( ! in_array($key, $default_global_prefs)) { continue; } $pref = array(); $pref['name'] = $key; $pref['lang_label'] = lang($key); $key_desc = $key . '_desc'; $pref['lang_desc'] = (lang($key_desc) == $key_desc) ? '' : lang($key_desc); $pref['value'] = form_prep($value); $pref['type'] = $this->data->default_global_preferences[$key]['type']; $global_pref_data[] = $pref; } $this->cached_vars['global_pref_data'] = $global_pref_data; // ------------------------------------- // these two will only be used if MSM // is enabled, but setting them // anyway to avoid potential PHP errors // ------------------------------------- $prefs_all_sites = ! $this->check_no( $this->data->global_preference('prefs_all_sites') ); $this->cached_vars['lang_site_prefs_for_site'] = ( lang('site_prefs_for') . ' ' . ( ($prefs_all_sites) ? lang('all_sites') : ee()->config->item('site_label') ) ); //-------------------------------------- // per site prefs //-------------------------------------- $pref_data = array(); $prefs = $this->data->get_module_preferences(); $default_prefs = array_keys($this->data->default_preferences); //dynamically get prefs and lang so we can just add them to defaults foreach( $prefs as $key => $value ) { //this skips things that don't need to be shown on this page //so we can use the prefs table for other areas of the addon if ( ! in_array($key, $default_prefs)) { continue; } //admin only pref? //MSM pref and no MSM? if ( (ee()->session->userdata('group_id') != 1 AND in_array($key, $this->data->admin_only_prefs)) OR ( ! $msm_enabled AND in_array($key, $this->data->msm_only_prefs)) ) { continue; } $pref = array(); $pref['name'] = $key; $pref['lang_label'] = lang($key); $key_desc = $key . '_desc'; $pref['lang_desc'] = (lang($key_desc) == $key_desc) ? '' : lang($key_desc); $pref['value'] = form_prep($value); $pref['type'] = $this->data->default_preferences[$key]['type']; $pref_data[] = $pref; } $this->cached_vars['pref_data'] = $pref_data; // ---------------------------------------- // Load vars // ---------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'save_preferences' )); // -------------------------------------------- // Load page // -------------------------------------------- $this->cached_vars['current_page'] = $this->view( 'preferences.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END preferences // -------------------------------------------------------------------- /** * delete confirm page abstractor * * @access private * @param string method you want to post data to after confirm * @param array all of the values you want to carry over to post * @param string the lang line of the warning message to display * @param string the lang line of the submit button for confirm * @param bool $message_use_lang use the lang wrapper for the message? * @return string */ private function delete_confirm ($method, $hidden_values, $message_line, $submit_line = 'delete', $message_use_lang = TRUE) { $this->cached_vars = array_merge($this->cached_vars, array( 'hidden_values' => $hidden_values, 'lang_message' => ($message_use_lang ? lang($message_line) : $message_line), 'lang_submit' => lang($submit_line), 'form_url' => $this->mod_link(array('method' => $method)) )); $this->cached_vars['current_page'] = $this->view( 'delete_confirm.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } //END delete_confirm //-------------------------------------------------------------------- // end views //-------------------------------------------------------------------- // -------------------------------------------------------------------- /** * Clean up inputted paragraph html * * @access public * @param string $string string to clean * @return mixed string if html or json if not */ public function clean_paragraph_html ($string = '', $allow_ajax = TRUE) { if ( ! $string OR trim($string == '')) { $string = ee()->input->get_post('clean_string'); if ( $string === FALSE OR trim($string) === '') { $string = ''; } } $allowed_tags = '<' . implode('><', $this->data->allowed_html_tags) . '>'; $string = strip_tags($string, $allowed_tags); $string = ee()->security->xss_clean($string); return $string; } //END clean_paragraph_html // -------------------------------------------------------------------- /** * Fieldtype Actions * * this installs or uninstalles depending on the sent action * this will redirect no matter what * * @access public * @return null */ public function freeform_fieldtype_action () { $return_url = array('method' => 'fieldtypes'); $name = ee()->input->get_post('name', TRUE); $action = ee()->input->get_post('action'); if ($name AND $action) { ee()->load->library('freeform_fields'); if ($action === 'install') { if (ee()->freeform_fields->install_fieldtype($name)) { $return_url['msg'] = 'fieldtype_installed'; } else { return $this->actions()->full_stop(lang('fieldtype_install_error')); } } else if ($action === 'uninstall') { $uninstall = $this->uninstall_confirm_fieldtype($name); //if its not a boolean true, its a confirmation if ($uninstall !== TRUE) { return $uninstall; } else { $return_url['msg'] = 'fieldtype_uninstalled'; } } } if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'success' => TRUE, 'message' => lang('fieldtype_uninstalled') )); } else { ee()->functions->redirect($this->mod_link($return_url)); } } //END freeform_fieldtype_action // -------------------------------------------------------------------- /** * save field layout * * ajax called method for saving field layout in the entries screen * * @access public * @return string */ public function save_field_layout () { ee()->load->library('freeform_forms'); ee()->load->model('freeform_form_model'); $save_for = ee()->input->get_post('save_for', TRUE); $shown_fields = ee()->input->get_post('shown_fields', TRUE); $form_id = $this->get_post_or_zero('form_id'); $form_data = $this->data->get_form_info($form_id); // ------------------------------------- // valid // ------------------------------------- if ( ! $this->is_ajax_request() OR ! is_array($save_for) OR ! is_array($shown_fields) OR ! $form_data ) { return $this->send_ajax_response(array( 'success' => FALSE, 'message' => lang('invalid_input') )); } // ------------------------------------- // permissions? // ------------------------------------- //if (ee()->session->userdata('group_id') != 1 AND // ! $this->check_yes($this->preference('allow_user_field_layout')) //) //{ // return $this->send_ajax_response(array( // 'success' => FALSE, // 'message' => lang('invalid_permissions') // )); //} // ------------------------------------- // save // ------------------------------------- $field_layout_prefs = $this->preference('field_layout_prefs'); $original_prefs = ( is_array($field_layout_prefs) ? $field_layout_prefs : array() ); // ------------------------------------- // who is it for? // ------------------------------------- $for = array(); foreach ($save_for as $item) { //if this is for everyone, we can stop if (in_array($item, array('just_me', 'everyone'))) { $for = $item; break; } if ($this->is_positive_intlike($item)) { $for[] = $item; } } // ------------------------------------- // what do they want to see? // ------------------------------------- $standard_columns = $this->get_standard_column_names(); $possible_columns = $standard_columns; //build possible columns foreach ($form_data['fields'] as $field_id => $field_data) { $possible_columns[] = $field_id; } $data = array(); $prefix = ee()->freeform_form_model->form_field_prefix; //check for field validity, no funny business foreach ($shown_fields as $field_name) { $field_id = str_replace($prefix, '', $field_name); if (in_array($field_name, $standard_columns)) { $data[] = $field_name; unset( $possible_columns[ array_search( $field_name, $possible_columns ) ] ); } else if (in_array($field_id , array_keys($form_data['fields']))) { $data[] = $field_id; unset( $possible_columns[ array_search( $field_id, $possible_columns ) ] ); } } //removes holes sort($possible_columns); // ------------------------------------- // insert the data per group or all // ------------------------------------- $settings = array( 'visible' => $data, 'hidden' => $possible_columns ); if ($for == 'just_me') { $id = ee()->session->userdata('member_id'); $original_prefs['entry_layout_prefs']['member'][$id] = $settings; } else if ($for == 'everyone') { $original_prefs['entry_layout_prefs']['all']['visible'] = $settings; } else { foreach ($for as $who) { $original_prefs['entry_layout_prefs']['group'][$who]['visible'] = $settings; } } // ------------------------------------- // save // ------------------------------------- $this->data->set_module_preferences(array( 'field_layout_prefs' => json_encode($original_prefs) )); // ------------------------------------- // success! // ------------------------------------- //TODO test for ajax request or redirect back //don't want JS erorrs preventing this from //working $this->send_ajax_response(array( 'success' => TRUE, 'message' => lang('layout_saved'), 'update_fields' => array() )); //prevent EE CP default spit out exit(); } //END save_field_layout // -------------------------------------------------------------------- /** * save_form * * @access public * @return null */ public function save_form () { // ------------------------------------- // form ID? we must be editing // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $update = ($form_id != 0); // ------------------------------------- // default status // ------------------------------------- $default_status = ee()->input->get_post('default_status', TRUE); $default_status = ($default_status AND trim($default_status) != '') ? $default_status : $this->data->defaults['default_form_status']; // ------------------------------------- // composer return? // ------------------------------------- $do_composer = (FREEFORM_PRO AND ee()->input->get_post('ret') == 'composer'); $composer_save_finish = (FREEFORM_PRO AND ee()->input->get_post('ret') == 'composer_save_finish'); if ($composer_save_finish) { $do_composer = TRUE; } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // field name // ------------------------------------- $form_name = ee()->input->get_post('form_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $form_name OR ! trim($form_name)) { $errors['form_name'] = lang('form_name_required'); } else { $form_name = strtolower(trim($form_name)); if ( in_array($form_name, $this->data->prohibited_names ) ) { $errors['form_name'] = str_replace( '%name%', $form_name, lang('reserved_form_name') ); } //if the form_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $form_name) OR is_numeric($form_name)) { $errors['form_name'] = lang('form_name_can_only_contain'); } ee()->load->model('freeform_form_model'); //get dupe from field names $dupe_data = ee()->freeform_form_model->get_row(array( 'form_name' => $form_name )); //if we are updating, we don't want to error on the same field id if ( ! empty($dupe_data) AND ! ($update AND $dupe_data['form_id'] == $form_id)) { $errors['form_name'] = str_replace( '%name%', $form_name, lang('form_name_exists') ); } } // ------------------------------------- // form label // ------------------------------------- $form_label = ee()->input->get_post('form_label', TRUE); if ( ! $form_label OR ! trim($form_label) ) { $errors['form_label'] = lang('form_label_required'); } // ------------------------------------- // admin notification email // ------------------------------------- $admin_notification_email = ee()->input->get_post('admin_notification_email', TRUE); if ($admin_notification_email AND trim($admin_notification_email) != '') { ee()->load->helper('email'); $emails = preg_split( '/(\s+)?\,(\s+)?/', $admin_notification_email, -1, PREG_SPLIT_NO_EMPTY ); $errors['admin_notification_email'] = array(); foreach ($emails as $key => $email) { $emails[$key] = trim($email); if ( ! valid_email($email)) { $errors['admin_notification_email'][] = str_replace('%email%', $email, lang('non_valid_email')); } } if (empty($errors['admin_notification_email'])) { unset($errors['admin_notification_email']); } $admin_notification_email = implode('|', $emails); } else { $admin_notification_email = ''; } // ------------------------------------- // user email field // ------------------------------------- $user_email_field = ee()->input->get_post('user_email_field'); ee()->load->model('freeform_field_model'); $field_ids = ee()->freeform_field_model->key('field_id', 'field_id')->get(); if ($user_email_field AND $user_email_field !== '--' AND trim($user_email_field) !== '' AND ! in_array($user_email_field, $field_ids )) { $errors['user_email_field'] = lang('invalid_user_email_field'); } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } //send ajax response exists //but this is in case someone is using a replacer //that uses if ($this->check_yes(ee()->input->get_post('validate_only'))) { if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'errors' => array() )); } exit(); } // ------------------------------------- // field ids // ------------------------------------- $field_ids = array_filter( $this->actions()->pipe_split( ee()->input->get_post('field_ids', TRUE) ), array($this, 'is_positive_intlike') ); $sorted_field_ids = $field_ids; sort($sorted_field_ids); // ------------------------------------- // insert data // ------------------------------------- $data = array( 'form_name' => strip_tags($form_name), 'form_label' => strip_tags($form_label), 'default_status' => $default_status, 'user_notification_id' => $this->get_post_or_zero('user_notification_id'), 'admin_notification_id' => $this->get_post_or_zero('admin_notification_id'), 'admin_notification_email' => $admin_notification_email, 'form_description' => strip_tags(ee()->input->get_post('form_description', TRUE)), 'author_id' => ee()->session->userdata('member_id'), 'field_ids' => implode('|', $sorted_field_ids), 'field_order' => implode('|', $field_ids), 'notify_admin' => ( (ee()->input->get_post('notify_admin') == 'y') ? 'y' : 'n' ), 'notify_user' => ( (ee()->input->get_post('notify_user') == 'y') ? 'y' : 'n' ), 'user_email_field' => $user_email_field, ); //load the forms model if its not been already ee()->load->library('freeform_forms'); if ($do_composer) { unset($data['field_ids']); unset($data['field_order']); } if ($update) { unset($data['author_id']); if ( ! $do_composer) { $data['composer_id'] = 0; } ee()->freeform_forms->update_form($form_id, $data); } else { //we don't want this running on update, will only happen for dupes $composer_id = $this->get_post_or_zero('composer_id'); //this is a dupe and they want composer to dupe too? if ($do_composer AND $composer_id > 0) { ee()->load->model('freeform_composer_model'); $composer_data = ee()->freeform_composer_model ->select('composer_data') ->where('composer_id', $composer_id) ->get_row(); if ($composer_data !== FALSE) { $data['composer_id'] = ee()->freeform_composer_model->insert( array( 'composer_data' => $composer_data['composer_data'], 'site_id' => ee()->config->item('site_id') ) ); } } $form_id = ee()->freeform_forms->create_form($data); } // ------------------------------------- // return // ------------------------------------- if ( ! $composer_save_finish AND $do_composer) { ee()->functions->redirect($this->mod_link(array( 'method' => 'form_composer', 'form_id' => $form_id, 'msg' => 'edit_form_success' ))); } //'save and finish, default' else { ee()->functions->redirect($this->mod_link(array( 'method' => 'forms', 'msg' => 'edit_form_success' ))); } } //END save_form // -------------------------------------------------------------------- /** * Save Entry * * @access public * @return null redirect */ public function save_entry () { // ------------------------------------- // edit? // ------------------------------------- $form_id = $this->get_post_or_zero('form_id'); $entry_id = $this->get_post_or_zero('entry_id'); ee()->load->model('freeform_form_model'); ee()->load->model('freeform_entry_model'); ee()->load->library('freeform_forms'); ee()->load->library('freeform_fields'); $form_data = $this->data->get_form_info($form_id); // ------------------------------------- // valid form id // ------------------------------------- if ( ! $form_data) { return $this->actions()->full_stop(lang('invalid_form_id')); } $previous_inputs = array(); if ( $entry_id > 0) { $entry_data = ee()->freeform_entry_model ->id($form_id) ->where('entry_id', $entry_id) ->get_row(); if ( ! $entry_data) { return $this->actions()->full_stop(lang('invalid_entry_id')); } $previous_inputs = $entry_data; } // ------------------------------------- // form data // ------------------------------------- $field_labels = array(); $valid_fields = array(); foreach ( $form_data['fields'] as $row) { $field_labels[$row['field_name']] = $row['field_label']; $valid_fields[] = $row['field_name']; } // ------------------------------------- // is this an edit? entry_id // ------------------------------------- $edit = ($entry_id AND $entry_id != 0); // ------------------------------------- // for hooks // ------------------------------------- $this->edit = $edit; $this->multipage = FALSE; $this->last_page = TRUE; // ------------------------------------- // prevalidate hook // ------------------------------------- $errors = array(); //to assist backward compat $this->field_errors = array(); if (ee()->extensions->active_hook('freeform_module_validate_begin') === TRUE) { $backup_errors = $errors; $errors = ee()->extensions->universal_call( 'freeform_module_validate_begin', $errors, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($errors) AND $this->check_yes($this->preference('hook_data_protection'))) { $errors = $backup_errors; } } // ------------------------------------- // validate // ------------------------------------- $field_input_data = array(); $field_list = array(); // ------------------------------------- // status? // ------------------------------------- $available_statuses = $this->data->get_form_statuses(); $status = ee()->input->get_post('status'); if ( ! array_key_exists($status, $available_statuses)) { $field_input_data['status'] = $this->data->defaults['default_form_status']; } else { $field_input_data['status'] = $status; } foreach ($form_data['fields'] as $field_id => $field_data) { $field_list[$field_data['field_name']] = $field_data['field_label']; $field_post = ee()->input->get_post($field_data['field_name']); //if it's not even in $_POST or $_GET, lets skip input //unless its an uploaded file, then we'll send false anyway //because its fieldtype will handle the rest of that work if ($field_post !== FALSE OR isset($_FILES[$field_data['field_name']])) { $field_input_data[$field_data['field_name']] = $field_post; } } //form fields do thier own validation, //so lets just get results! (sexy results?) $this->field_errors = array_merge( $this->field_errors, ee()->freeform_fields->validate( $form_id, $field_input_data ) ); // ------------------------------------- // post validate hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_validate_end') === TRUE) { $backup_errors = $errors; $errors = ee()->extensions->universal_call( 'freeform_module_validate_end', $errors, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($errors) AND $this->check_yes($this->preference('hook_data_protection'))) { $errors = $backup_errors; } } $errors = array_merge($errors, $this->field_errors); // ------------------------------------- // halt on errors // ------------------------------------- if (count($errors) > 0) { $this->actions()->full_stop($errors); } //send ajax response exists //but this is in case someone is using a replacer //that uses if ($this->check_yes(ee()->input->get_post('validate_only'))) { if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'errors' => array() )); } exit(); } // ------------------------------------- // entry insert begin hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_insert_begin') === TRUE) { $backup_field_input_data = $field_input_data; $field_input_data = ee()->extensions->universal_call( 'freeform_module_insert_begin', $field_input_data, $entry_id, $form_id, $this ); if (ee()->extensions->end_script === TRUE) return; //valid data? if ( ! is_array($field_input_data) AND $this->check_yes($this->preference('hook_data_protection'))) { $field_input_data = $backup_field_input_data; } } // ------------------------------------- // insert/update data into db // ------------------------------------- if ($edit) { ee()->freeform_forms->update_entry( $form_id, $entry_id, $field_input_data ); } else { $entry_id = ee()->freeform_forms->insert_new_entry( $form_id, $field_input_data ); } // ------------------------------------- // entry insert begin hook // ------------------------------------- if (ee()->extensions->active_hook('freeform_module_insert_end') === TRUE) { ee()->extensions->universal_call( 'freeform_module_insert_end', $field_input_data, $entry_id, $form_id, $this ); if (ee()->extensions->end_script === TRUE) return; } // ------------------------------------- // return // ------------------------------------- $success_line = ($edit) ? 'edit_entry_success' : 'new_entry_success'; if ($this->is_ajax_request()) { return $this->send_ajax_response(array( 'form_id' => $form_id, 'entry_id' => $entry_id, 'message' => lang($success_line), 'success' => TRUE )); } //'save and finish, default' else { ee()->functions->redirect($this->mod_link(array( 'method' => 'entries', 'form_id' => $form_id, 'msg' => $success_line ))); } } //END edit_entry // -------------------------------------------------------------------- /** * approve entries * * accepts ajax call to approve entries * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to approve * @return string */ public function approve_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // valid form id? // ------------------------------------- if ( ! $form_id OR $form_id <= 0) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->actions()->full_stop(lang('invalid_entry_id')); } // ------------------------------------- // approve! // ------------------------------------- $updates = array(); foreach($entry_ids as $entry_id) { $updates[] = array( 'entry_id' => $entry_id, 'status' => 'open' ); } ee()->load->model('freeform_form_model'); ee()->db->update_batch( ee()->freeform_form_model->table_name($form_id), $updates, 'entry_id' ); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); exit(); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'moderate_entries'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'form_id' => $form_id, 'msg' => 'entries_approved' ))); } } //END approve_entry // -------------------------------------------------------------------- /** * get/post form_id * * gets and validates the current form_id possibly passed * * @access private * @param bool validate form_id * @return mixed integer of passed in form_id or bool false */ private function get_post_form_id ($validate = TRUE) { $form_id = $this->get_post_or_zero('form_id'); if ($form_id == 0 OR ($validate AND ! $this->data->is_valid_form_id($form_id)) ) { return FALSE; } return $form_id; } //ENd get_post_form_id // -------------------------------------------------------------------- /** * get/post entry_ids * * gets and validates the current entry possibly passed * * @access private * @return mixed array of passed in entry_ids or bool false */ private function get_post_entry_ids () { $entry_ids = ee()->input->get_post('entry_ids'); if ( ! is_array($entry_ids) AND ! $this->is_positive_intlike($entry_ids)) { return FALSE; } if ( ! is_array($entry_ids)) { $entry_ids = array($entry_ids); } //clean and validate each as int $entry_ids = array_filter($entry_ids, array($this, 'is_positive_intlike')); if (empty($entry_ids)) { return FALSE; } return $entry_ids; } //END get_post_entry_ids // -------------------------------------------------------------------- /** * delete_confirm_entries * * accepts ajax call to delete entry * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to delete * @return string */ public function delete_confirm_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // ajax requests should be doing front // end delete confirm. This also handles // the ajax errors properly // ------------------------------------- if ( $this->is_ajax_request()) { return $this->delete_entries(); } // ------------------------------------- // form id? // ------------------------------------- if ( ! $form_id OR $form_id <= 0) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->show_error(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->show_error(lang('invalid_entry_id')); } // ------------------------------------- // return method? // ------------------------------------- $return_method = ee()->input->get_post('return_method'); $return_method = ($return_method AND is_callable(array($this, $return_method))) ? $return_method : 'entries'; // ------------------------------------- // confirmation page // ------------------------------------- return $this->delete_confirm( 'delete_entries', array( 'form_id' => $form_id, 'entry_ids' => $entry_ids, 'return_method' => $return_method ), 'confirm_delete_entries' ); } //END delete_confirm_entries // -------------------------------------------------------------------- /** * delete entries * * accepts ajax call to delete entry * or can be called via another view function on post * * @access public * @param int form id * @param mixed array or int of entry ids to delete * @return string */ public function delete_entries ($form_id = 0, $entry_ids = array()) { // ------------------------------------- // valid form id? // ------------------------------------- if ( ! $this->is_positive_intlike($form_id)) { $form_id = $this->get_post_form_id(); } if ( ! $form_id) { $this->actions()->full_stop(lang('invalid_form_id')); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! $entry_ids OR empty($entry_ids) ) { $entry_ids = $this->get_post_entry_ids(); } //check if ( ! $entry_ids) { $this->actions()->full_stop(lang('invalid_entry_id')); } ee()->load->library('freeform_forms'); $success = ee()->freeform_forms->delete_entries($form_id, $entry_ids); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success )); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'entries'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'form_id' => $form_id, 'msg' => 'entries_deleted' ))); } } //END delete_entries // -------------------------------------------------------------------- /** * Confirm Delete Fields * * @access public * @return html */ public function delete_confirm_fields () { //the following fields will be deleted //the following forms will be affected //they contain the forms.. $field_ids = ee()->input->get_post('field_id', TRUE); if ( ! is_array($field_ids) AND ! $this->is_positive_intlike($field_ids) ) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } //already checked for numeric :p if ( ! is_array($field_ids)) { $field_ids = array($field_ids); } $delete_field_confirmation = ''; $clean_field_ids = array(); foreach ($field_ids as $field_id) { if ($this->is_positive_intlike($field_id)) { $clean_field_ids[] = $field_id; } } if (empty($clean_field_ids)) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } // ------------------------------------- // build a list of forms affected by fields // ------------------------------------- ee()->db->where_in('field_id', $clean_field_ids); $all_field_data = ee()->db->get('freeform_fields'); $delete_field_confirmation = lang('delete_field_confirmation'); $extra_form_data = ''; foreach ($all_field_data->result_array() as $row) { //this doesn't get field data, so we had to above; $field_form_data = $this->data->get_form_info_by_field_id($row['field_id']); // ------------------------------------- // get each form affected by each field listed // and show the user what forms will be affected // ------------------------------------- if ( $field_form_data !== FALSE ) { $freeform_affected = array(); foreach ($field_form_data as $form_id => $form_data) { $freeform_affected[] = $form_data['form_label']; } $extra_form_data .= '<p>' . '<strong>' . $row['field_label'] . '</strong>: ' . implode(', ', $freeform_affected) . '</p>'; } } //if we have anything, add some extra warnings if ($extra_form_data != '') { $delete_field_confirmation .= '<p>' . lang('freeform_will_lose_data') . '</p>' . $extra_form_data; } return $this->delete_confirm( 'delete_fields', array('field_id' => $clean_field_ids), $delete_field_confirmation, 'delete', FALSE ); } //END delete_confirm_fields // -------------------------------------------------------------------- /** * utilities * * @access public * @return string */ public function utilities ( $message = '' ) { if ($message == '' AND ee()->input->get('msg') !== FALSE) { $message = lang(ee()->input->get('msg')); } $this->cached_vars['message'] = $message; //-------------------------------------- // Title and Crumbs //-------------------------------------- $this->add_crumb(lang('utilities')); $this->set_highlight('module_utilities'); //-------------------------------------- // Counts //-------------------------------------- ee()->load->library('freeform_migration'); $this->cached_vars['counts'] = ee()->freeform_migration->get_collection_counts(); // $test = ee()->freeform_migration->create_upload_field( 1, 'goff', array( 'file_upload_location' => '1' ) ); // print_r( $test ); print_r( ee()->freeform_migration->get_errors() ); //-------------------------------------- // File upload field installed? //-------------------------------------- $this->cached_vars['file_upload_installed'] = ee()->freeform_migration->get_field_type_installed('file_upload'); $query = ee()->db->query( "SELECT * FROM exp_freeform_fields WHERE field_type = 'file_upload'" ); //-------------------------------------- // Load vars //-------------------------------------- $this->cached_vars['form_uri'] = $this->mod_link(array( 'method' => 'migrate_collections' )); //-------------------------------------- // Load page //-------------------------------------- $this->cached_vars['current_page'] = $this->view( 'utilities.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } // End utilities // -------------------------------------------------------------------- /** * Confirm Uninstall Fieldtypes * * @access public * @return html */ public function uninstall_confirm_fieldtype ($name = '') { $name = trim($name); if ($name == '') { ee()->functions->redirect($this->base); } ee()->load->model('freeform_field_model'); $items = ee()->freeform_field_model ->key('field_label', 'field_label') ->get(array('field_type' => $name)); if ($items == FALSE) { return $this->uninstall_fieldtype($name); } else { $confirmation = '<p>' . lang('following_fields_converted') . ': <strong>'; $confirmation .= implode(', ', $items) . '</strong></p>'; return $this->delete_confirm( 'uninstall_fieldtype', array('fieldtype' => $name), $confirmation, 'uninstall', FALSE ); } } //END uninstall_confirm_fieldtype // -------------------------------------------------------------------- /** * Uninstalls fieldtypes * * @access public * @param string $name fieldtype name to remove * @return void */ public function uninstall_fieldtype ($name = '', $redirect = TRUE) { if ($name == '') { $name = ee()->input->get_post('fieldtype', TRUE); } if ( ! $name) { $this->actions()->full_stop(lang('no_fieldtypes_submitted')); } ee()->load->library('freeform_fields'); $success = ee()->freeform_fields->uninstall_fieldtype($name); if ( ! $redirect) { return $success; } if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success, 'message' => lang('fieldtype_uninstalled'), )); } else { ee()->functions->redirect($this->mod_link(array( 'method' => 'fieldtypes', 'msg' => 'fieldtype_uninstalled' ))); } } //END uninstall_fieldtype // -------------------------------------------------------------------- /** * Delete Fields * * @access public * @return void */ public function delete_fields () { // ------------------------------------- // safety goggles // ------------------------------------- // $field_ids = ee()->input->get_post('field_id', TRUE); if ( ! is_array($field_ids) AND ! $this->is_positive_intlike($field_ids) ) { $this->actions()->full_stop(lang('no_field_ids_submitted')); } //already checked for numeric :p if ( ! is_array($field_ids)) { $field_ids = array($field_ids); } // ------------------------------------- // delete fields // ------------------------------------- ee()->load->library('freeform_fields'); ee()->freeform_fields->delete_field($field_ids); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); } else { ee()->functions->redirect($this->mod_link(array( 'method' => 'fields', 'msg' => 'fields_deleted' ))); } } //END delete_fields // -------------------------------------------------------------------- /** * Confirm deletion of notifications * * accepts ajax call to delete notification * * @access public * @param int form id * @param mixed array or int of notification ids to delete * @return string */ public function delete_confirm_notification ($notification_id = 0) { // ------------------------------------- // ajax requests should be doing front // end delete confirm. This also handles // the ajax errors properly // ------------------------------------- if ( $this->is_ajax_request()) { return $this->delete_notification(); } // ------------------------------------- // entry ids? // ------------------------------------- if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $notification_id = ee()->input->get_post('notification_id'); } if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $this->actions()->full_stop(lang('invalid_notification_id')); } if ( is_array($notification_id)) { $notification_id = array_filter( $notification_id, array($this, 'is_positive_intlike') ); } else { $notification_id = array($notification_id); } // ------------------------------------- // confirmation page // ------------------------------------- return $this->delete_confirm( 'delete_notification', array( 'notification_id' => $notification_id, 'return_method' => 'notifications' ), 'confirm_delete_notification' ); } //END delete_confirm_notification // -------------------------------------------------------------------- /** * Delete Notifications * * @access public * @param integer $notification_id notification * @return null */ public function delete_notification ($notification_id = 0) { // ------------------------------------- // entry ids? // ------------------------------------- if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $notification_id = ee()->input->get_post('notification_id'); } if ( ! is_array($notification_id) AND ! $this->is_positive_intlike($notification_id)) { $this->actions()->full_stop(lang('invalid_notification_id')); } if ( is_array($notification_id)) { $notification_id = array_filter( $notification_id, array($this, 'is_positive_intlike') ); } else { $notification_id = array($notification_id); } ee()->load->model('freeform_notification_model'); $success = ee()->freeform_notification_model ->where_in('notification_id', $notification_id) ->delete(); // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => $success )); } else { $method = ee()->input->get_post('return_method'); $method = ($method AND is_callable(array($this, $method))) ? $method : 'notifications'; ee()->functions->redirect($this->mod_link(array( 'method' => $method, 'msg' => 'delete_notification_success' ))); } } //END delete_notification // -------------------------------------------------------------------- /** * save_field * * @access public * @return void (redirect) */ public function save_field () { // ------------------------------------- // field ID? we must be editing // ------------------------------------- $field_id = $this->get_post_or_zero('field_id'); $update = ($field_id != 0); // ------------------------------------- // yes or no items (all default yes) // ------------------------------------- $y_or_n = array('submissions_page', 'moderation_page', 'composer_use'); foreach ($y_or_n as $item) { //set as local var $$item = $this->check_no(ee()->input->get_post($item)) ? 'n' : 'y'; } // ------------------------------------- // field instance // ------------------------------------- $field_type = ee()->input->get_post('field_type', TRUE); ee()->load->library('freeform_fields'); ee()->load->model('freeform_field_model'); $available_fieldtypes = ee()->freeform_fields->get_available_fieldtypes(); //get the update with previous settings if this is an edit if ($update) { $field = ee()->freeform_field_model ->where('field_id', $field_id) ->where('field_type', $field_type) ->count(); //make sure that we have the correct type just in case they //are changing type like hooligans if ($field) { $field_instance =& ee()->freeform_fields->get_field_instance($field_id); } else { $field_instance =& ee()->freeform_fields->get_fieldtype_instance($field_type); } } else { $field_instance =& ee()->freeform_fields->get_fieldtype_instance($field_type); } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // field name // ------------------------------------- $field_name = ee()->input->get_post('field_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $field_name OR ! trim($field_name)) { $errors['field_name'] = lang('field_name_required'); } else { $field_name = strtolower(trim($field_name)); if ( in_array($field_name, $this->data->prohibited_names ) ) { $errors['field_name'] = str_replace( '%name%', $field_name, lang('freeform_reserved_field_name') ); } //if the field_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $field_name) OR is_numeric($field_name)) { $errors['field_name'] = lang('field_name_can_only_contain'); } //get dupe from field names $f_query = ee()->db->select('field_name, field_id')->get_where( 'freeform_fields', array('field_name' => $field_name) ); //if we are updating, we don't want to error on the same field id if ($f_query->num_rows() > 0 AND ! ($update AND $f_query->row('field_id') == $field_id)) { $errors['field_name'] = str_replace( '%name%', $field_name, lang('field_name_exists') ); } } // ------------------------------------- // field label // ------------------------------------- $field_label = ee()->input->get_post('field_label', TRUE); if ( ! $field_label OR ! trim($field_label) ) { $errors['field_label'] = lang('field_label_required'); } // ------------------------------------- // field type // ------------------------------------- if ( ! $field_type OR ! array_key_exists($field_type, $available_fieldtypes)) { $errors['field_type'] = lang('invalid_fieldtype'); } // ------------------------------------- // field settings errors? // ------------------------------------- $field_settings_validate = $field_instance->validate_settings(); if ( $field_settings_validate !== TRUE) { if (is_array($field_settings_validate)) { $errors['field_settings'] = $field_settings_validate; } else if (! empty($field_instance->errors)) { $errors['field_settings'] = $field_instance->errors; } else { $errors['field_settings'] = lang('field_settings_error'); } } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } if ($this->check_yes(ee()->input->get_post('validate_only')) AND $this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE )); } // ------------------------------------- // insert data // ------------------------------------- $data = array( 'field_name' => strip_tags($field_name), 'field_label' => strip_tags($field_label), 'field_type' => $field_type, 'edit_date' => '0', //overridden if update 'field_description' => strip_tags(ee()->input->get_post('field_description', TRUE)), 'submissions_page' => $submissions_page, 'moderation_page' => $moderation_page, 'composer_use' => $composer_use, 'settings' => json_encode($field_instance->save_settings()) ); if ($update) { ee()->freeform_field_model->update( array_merge( $data, array( 'edit_date' => ee()->localize->now ) ), array('field_id' => $field_id) ); } else { $field_id = ee()->freeform_field_model->insert( array_merge( $data, array( 'author_id' => ee()->session->userdata('member_id'), 'entry_date' => ee()->localize->now, 'site_id' => ee()->config->item('site_id') ) ) ); } $field_instance->field_id = $field_id; $field_instance->post_save_settings(); $field_in_forms = array(); if ($update) { $field_in_forms = $this->data->get_form_info_by_field_id($field_id); if ($field_in_forms) { $field_in_forms = array_keys($field_in_forms); } else { $field_in_forms = array(); } } $form_ids = ee()->input->get_post('form_ids'); if ($form_ids !== FALSE) { $form_ids = preg_split( '/\|/', $form_ids, -1, PREG_SPLIT_NO_EMPTY ); } else { $form_ids = array(); } if ( ! (empty($form_ids) AND empty($field_in_forms))) { $remove = array_unique(array_diff($field_in_forms, $form_ids)); $add = array_unique(array_diff($form_ids, $field_in_forms)); ee()->load->library('freeform_forms'); foreach ($add as $add_id) { ee()->freeform_forms->add_field_to_form($add_id, $field_id); } foreach ($remove as $remove_id) { ee()->freeform_forms->remove_field_from_form($remove_id, $field_id); } } // ------------------------------------- // success // ------------------------------------- if ($this->is_ajax_request()) { $return = array( 'success' => TRUE, 'field_id' => $field_id, ); if ($this->check_yes(ee()->input->get_post('include_field_data'))) { $return['composerFieldData'] = $this->composer_field_data($field_id, NULL, TRUE); } $this->send_ajax_response($return); } else { //redirect back to fields on success ee()->functions->redirect($this->mod_link(array( 'method' => 'fields', 'msg' => 'edit_field_success' ))); } } //END save_field // -------------------------------------------------------------------- /** * save_notification * * @access public * @return null (redirect) */ public function save_notification () { // ------------------------------------- // notification ID? we must be editing // ------------------------------------- $notification_id = $this->get_post_or_zero('notification_id'); $update = ($notification_id != 0); // ------------------------------------- // yes or no items (default yes) // ------------------------------------- $y_or_n = array('wordwrap'); foreach ($y_or_n as $item) { //set as local var $$item = $this->check_no(ee()->input->get_post($item)) ? 'n' : 'y'; } // ------------------------------------- // yes or no items (default no) // ------------------------------------- $n_or_y = array('allow_html', 'include_attachments'); foreach ($n_or_y as $item) { //set as local var $$item = $this->check_yes(ee()->input->get_post($item)) ? 'y' : 'n'; } // ------------------------------------- // error on empty items or bad data // (doing this via ajax in the form as well) // ------------------------------------- $errors = array(); // ------------------------------------- // notification name // ------------------------------------- $notification_name = ee()->input->get_post('notification_name', TRUE); //if the field label is blank, make one for them //we really dont want to do this, but here we are if ( ! $notification_name OR ! trim($notification_name)) { $errors['notification_name'] = lang('notification_name_required'); } else { $notification_name = strtolower(trim($notification_name)); if ( in_array($notification_name, $this->data->prohibited_names ) ) { $errors['notification_name'] = str_replace( '%name%', $notification_name, lang('reserved_notification_name') ); } //if the field_name they submitted isn't like how a URL title may be //also, cannot be numeric if (preg_match('/[^a-z0-9\_\-]/i', $notification_name) OR is_numeric($notification_name)) { $errors['notification_name'] = lang('notification_name_can_only_contain'); } //get dupe from field names ee()->db->select('notification_name, notification_id'); $f_query = ee()->db->get_where( 'freeform_notification_templates', array( 'notification_name' => $notification_name ) ); //if we are updating, we don't want to error on the same field id if ($f_query->num_rows() > 0 AND ! ($update AND $f_query->row('notification_id') == $notification_id)) { $errors['notification_name'] = str_replace( '%name%', $notification_name, lang('notification_name_exists') ); } } // ------------------------------------- // notification label // ------------------------------------- $notification_label = ee()->input->get_post('notification_label', TRUE); if ( ! $notification_label OR ! trim($notification_label) ) { $errors['notification_label'] = lang('notification_label_required'); } ee()->load->helper('email'); // ------------------------------------- // notification email // ------------------------------------- $from_email = ee()->input->get_post('from_email', TRUE); if ($from_email AND trim($from_email) != '') { $from_email = trim($from_email); //allow tags if ( ! preg_match('/' . LD . '([a-zA-Z0-9\_]+)' . RD . '/is', $from_email)) { if ( ! valid_email($from_email)) { $errors['from_email'] = str_replace( '%email%', $from_email, lang('non_valid_email') ); } } } // ------------------------------------- // from name // ------------------------------------- $from_name = ee()->input->get_post('from_name', TRUE); if ( ! $from_name OR ! trim($from_name) ) { //$errors['from_name'] = lang('from_name_required'); } // ------------------------------------- // reply to email // ------------------------------------- $reply_to_email = ee()->input->get_post('reply_to_email', TRUE); if ($reply_to_email AND trim($reply_to_email) != '') { $reply_to_email = trim($reply_to_email); //allow tags if ( ! preg_match('/' . LD . '([a-zA-Z0-9\_]+)' . RD . '/is', $reply_to_email)) { if ( ! valid_email($reply_to_email)) { $errors['reply_to_email'] = str_replace( '%email%', $reply_to_email, lang('non_valid_email') ); } } } else { $reply_to_email = ''; } // ------------------------------------- // email subject // ------------------------------------- $email_subject = ee()->input->get_post('email_subject', TRUE); if ( ! $email_subject OR ! trim($email_subject) ) { $errors['email_subject'] = lang('email_subject_required'); } // ------------------------------------- // errors? For shame :( // ------------------------------------- if ( ! empty($errors)) { return $this->actions()->full_stop($errors); } //ajax checking? else if ($this->check_yes(ee()->input->get_post('validate_only'))) { return $this->send_ajax_response(array( 'success' => TRUE )); } // ------------------------------------- // insert data // ------------------------------------- $data = array( 'notification_name' => strip_tags($notification_name), 'notification_label' => strip_tags($notification_label), 'notification_description' => strip_tags(ee()->input->get_post('notification_description', TRUE)), 'wordwrap' => $wordwrap, 'allow_html' => $allow_html, 'from_name' => $from_name, 'from_email' => $from_email, 'reply_to_email' => $reply_to_email, 'email_subject' => strip_tags($email_subject), 'template_data' => ee()->input->get_post('template_data'), 'include_attachments' => $include_attachments ); ee()->load->model('freeform_notification_model'); if ($update) { ee()->freeform_notification_model->update( $data, array('notification_id' => $notification_id) ); } else { $notification_id = ee()->freeform_notification_model->insert( array_merge( $data, array( 'site_id' => ee()->config->item('site_id') ) ) ); } // ------------------------------------- // ajax? // ------------------------------------- if ($this->is_ajax_request()) { $this->send_ajax_response(array( 'success' => TRUE, 'notification_id' => $notification_id )); } else { //redirect back to fields on success ee()->functions->redirect($this->mod_link(array( 'method' => 'notifications', 'msg' => 'edit_notification_success' ))); } } //END save_notification // -------------------------------------------------------------------- /** * Sets the menu highlight and assists with permissions (Freeform Pro) * * @access protected * @param string $menu_item The menu item to highlight */ protected function set_highlight($menu_item = 'module_forms') { $this->cached_vars['module_menu_highlight'] = $menu_item; } //END set_highlight // -------------------------------------------------------------------- /** * save_preferences * * @access public * @return null (redirect) */ public function save_preferences() { //defaults are in data.freeform.php $prefs = array(); $all_prefs = array_merge( $this->data->default_preferences, $this->data->default_global_preferences ); //check post input for all existing prefs and default if not present foreach($all_prefs as $pref_name => $data) { $input = ee()->input->get_post($pref_name, TRUE); //default $output = $data['value']; //int if ($data['type'] == 'int' AND $this->is_positive_intlike($input, -1)) { $output = $input; } //yes or no elseif ($data['type'] == 'y_or_n' AND in_array(trim($input), array('y', 'n'), TRUE)) { $output = trim($input); } //list of items //this seems nutty, but this serializes the list of items elseif ($data['type'] == 'list') { //lotses? if (is_array($input)) { $temp_input = array(); foreach ($input as $key => $value) { if (trim($value) !== '') { $temp_input[] = trim($value); } } $output = json_encode($temp_input); } //just one :/ else if (trim($input) !== '') { $output = json_encode(array(trim($input))); } } //text areas elseif ($data['type'] == 'text' OR $data['type'] == 'textarea' ) { $output = trim($input); } $prefs[$pref_name] = $output; } //send all prefs to DB $this->data->set_module_preferences($prefs); // ---------------------------------- // Redirect to Homepage with Message // ---------------------------------- ee()->functions->redirect( $this->base . AMP . 'method=preferences' . AMP . 'msg=preferences_updated' ); } //END save_preferences // -------------------------------------------------------------------- /** * Export Entries * * Calls entries with proper flags to cue export * * @access public * @return mixed forces a download of the exported items or error */ public function export_entries () { $moderate = (ee()->input->get_post('moderate') == 'true'); return $this->entries(NULL, $moderate, TRUE); } //END export_entries // -------------------------------------------------------------------- /** * get_standard_column_names * * gets the standard column names and replaces author_id with author * * @access private * @return null */ private function get_standard_column_names() { $standard_columns = array_keys( ee()->freeform_form_model->default_form_table_columns ); array_splice( $standard_columns, array_search('author_id', $standard_columns), 1, 'author' ); return $standard_columns; } //END get_standard_column_names // -------------------------------------------------------------------- /** * mod_link * * makes $this->base . AMP . 'key=value' out of arrays * * @access public * @param array key value pair of get vars to add to base * @param bool $real_amp use a real ampersand? * @return string */ private function mod_link ($vars = array(), $real_amp = FALSE) { $link = $this->base; $amp = $real_amp ? '&' : AMP; if ($real_amp) { $link = str_replace(AMP, '&', $link); } else { //Swap all to regular amp first so we don't get false //positives. Could do this with negative lookups, but //those are spottier than this. $link = str_replace('&', AMP, str_replace(AMP, '&', $link)); } if ( ! empty($vars)) { foreach ($vars as $key => $value) { $link .= $amp . $key . '=' . $value; } } return $link; } //END mod_link // -------------------------------------------------------------------- /** * load_fancybox * * loads fancybox jquery UI plugin and its needed css * * @access private * @return null */ private function load_fancybox() { //so currently the fancybox setup inlucded in EE doesn't get built //automaticly and requires relying on the current CP theme. //Dislike. Inlcuding our own version instead. //Seems fancy box has also been removed from some later versions //of EE, so instinct here was correct. $css_link = $this->sc->addon_theme_url . 'fancybox/jquery.fancybox-1.3.4.css'; $js_link = $this->sc->addon_theme_url . 'fancybox/jquery.fancybox-1.3.4.pack.js'; ee()->cp->add_to_head('<link href="' . $css_link . '" type="text/css" rel="stylesheet" media="screen" />'); ee()->cp->add_to_foot('<script src="' . $js_link . '" type="text/javascript"></script>'); } //END load_fancybox // -------------------------------------------------------------------- /** * freeform_add_right_link * * abstractor for cp add_right_link so freeform can move it how it needs * when an alternate style is chosen * * @access private * @param string words of link to display * @param string link to display * @return null */ private function freeform_add_right_link ($lang, $link) { $this->cached_vars['inner_nav_links'][$lang] = $link; //return $this->add_right_link($lang, $link); } //END freeform_add_right_link // -------------------------------------------------------------------- /** * Module Upgrading * * This function is not required by the 1.x branch of ExpressionEngine by default. However, * as the install and deinstall ones are, we are just going to keep the habit and include it * anyhow. * - Originally, the $current variable was going to be passed via parameter, but as there might * be a further use for such a variable throughout the module at a later date we made it * a class variable. * * * @access public * @return bool */ public function freeform_module_update() { if ( ! isset($_POST['run_update']) OR $_POST['run_update'] != 'y') { $this->add_crumb(lang('update_freeform_module')); $this->build_crumbs(); $this->cached_vars['form_url'] = $this->base . '&msg=update_successful'; if ($this->pro_update) { $this->cached_vars['form_url'] .= "&update_pro=true"; } $this->cached_vars['current_page'] = $this->view( 'update_module.html', NULL, TRUE ); return $this->ee_cp_view('index.html'); } require_once $this->addon_path . 'upd.freeform.php'; $U = new Freeform_upd(); if ($U->update() !== TRUE) { return ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => lang('update_failure') ))); } else { return ee()->functions->redirect($this->mod_link(array( 'method' => 'index', 'msg' => lang('update_successful') ))); } } // END freeform_module_update() // -------------------------------------------------------------------- /** * Visible Columns * * @access protected * @param $possible_columns possible columns * @return array array of visible columns */ protected function visible_columns ($standard_columns = array(), $possible_columns = array()) { // ------------------------------------- // get column settings // ------------------------------------- $column_settings = array(); ee()->load->model('freeform_form_model'); $field_layout_prefs = $this->preference('field_layout_prefs'); $member_id = ee()->session->userdata('member_id'); $group_id = ee()->session->userdata('group_id'); $f_prefix = ee()->freeform_form_model->form_field_prefix; //¿existe? Member? Group? all? if ($field_layout_prefs) { //$field_layout_prefs = json_decode($field_layout_prefs, TRUE); $entry_layout_prefs = ( isset($field_layout_prefs['entry_layout_prefs']) ? $field_layout_prefs['entry_layout_prefs'] : FALSE ); if ($entry_layout_prefs) { if (isset($entry_layout_prefs['member'][$member_id])) { $column_settings = $entry_layout_prefs['member'][$member_id]; } else if (isset($entry_layout_prefs['all'])) { $column_settings = $entry_layout_prefs['all']; } else if (isset($entry_layout_prefs['group'][$group_id])) { $column_settings = $entry_layout_prefs['group'][$group_id]; } } } //if a column is missing, we don't want to error //and if its newer than the settings, show it by default //settings are also in order of appearence here. //we also store the field ids without the prefix //in case someone changed it. That would probably //hose everything, but who knows? ;) if ( ! empty($column_settings)) { $to_sort = array(); //we are going over possible instead of settings in case something //is new or an old column is missing foreach ($possible_columns as $cid) { //if these are new, put them at the end if (! in_array($cid, $column_settings['visible']) AND ! in_array($cid, $column_settings['hidden']) ) { $to_sort[$cid] = $cid; } } //now we want columns from the settings order to go first //this way stuff thats not been removed gets to keep settings foreach ($column_settings['visible'] as $ecid) { if (in_array($ecid, $possible_columns)) { //since we are getting our real results now //we can add the prefixes if ( ! in_array($ecid, $standard_columns) ) { $ecid = $f_prefix . $ecid; } $visible_columns[] = $ecid; } } //and if we have anything left over (new fields probably) //its at the end if (! empty($to_sort)) { foreach ($to_sort as $tsid) { //since we are getting our real results now //we can add the prefixes if ( ! in_array($tsid, $standard_columns) ) { $tsid = $f_prefix . $tsid; } $visible_columns[] = $tsid; } } } //if we don't have any settings, just toss it all in in order else { foreach ($possible_columns as $pcid) { if ( ! in_array($pcid, $standard_columns) ) { $pcid = $f_prefix . $pcid; } $visible_columns[] = $pcid; } //in theory it should always be there if prefs are empty ... $default_hide = array('site_id', 'entry_id', 'complete'); foreach ($default_hide as $hide_me_seymour) { if (in_array($hide_me_seymour, $visible_columns)) { unset( $visible_columns[ array_search( $hide_me_seymour, $visible_columns ) ] ); } } //fix keys, but preserve order $visible_columns = array_merge(array(), $visible_columns); } return $visible_columns; } //END visible_columns // -------------------------------------------------------------------- /** * Format CP date * * @access public * @param mixed $date unix time * @return string unit time formatted to cp date formatting pref */ public function format_cp_date($date) { return $this->actions()->format_cp_date($date); } //END format_cp_date // -------------------------------------------------------------------- /** * Send AJAX response * * Outputs and exit either an HTML string or a * JSON array with the Profile disabled and correct * headers sent. * * @access public * @param string|array String is sent as HTML, Array is sent as JSON * @param bool Is this an error message? * @param bool bust cache for JSON? * @return void */ public function send_ajax_response($msg, $error = FALSE, $cache_bust = TRUE) { $this->restore_xid(); parent::send_ajax_response($msg, $error, $cache_bust); } //END send_ajax_response // -------------------------------------------------------------------- /** * EE 2.7+ restore xid with version check * @access public * @return voic */ public function restore_xid() { //deprecated in 2.8. Weeee! if (version_compare($this->ee_version, '2.7', '>=') && version_compare($this->ee_version, '2.8', '<')) { ee()->security->restore_xid(); } } //END restore_xid } // END CLASS Freeform
cfox89/EE-Integration-to-API
system/expressionengine/third_party/freeform/mcp.freeform.php
PHP
mit
159,782
23.132608
114
0.482223
false
/* exported Qualifications */ function Qualifications(skills, items) { var requirements = { 'soldier': { meta: { passPercentage: 100 }, classes: { 'Heavy Assault': { certifications: [ { skill: skills.heavyAssault.flakArmor, level: 3 } ], equipment: [] }, 'Light Assault': { certifications: [ { skill: skills.lightAssault.flakArmor, level: 3 } ], equipment: [] }, 'Engineer': { certifications: [ { skill: skills.engineer.flakArmor, level: 3 }, { skill: skills.engineer.nanoArmorKit, level: 4 }, { skill: skills.engineer.tankMine, level: 1 } ], equipment: [] }, 'Medic': { certifications: [ { skill: skills.medic.flakArmor, level: 3 }, { skill: skills.medic.medicalApplicator, level: 4 } ], equipment: [] }, 'Infiltrator': { certifications: [ { skill: skills.infiltrator.flakArmor, level: 3 } ], equipment: [] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.advancedMobileStation, level: 1 } ], equipment: [] }, 'Squad Leader': { certifications: [ { skill: skills.squadLeader.priorityDeployment, level: 0 } ], equipment: [] } } }, 'veteran': { meta: { passPercentage: 100 }, classes: { 'Heavy Assault': { certifications: [ { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.antiVehicleGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 1 } ], equipment: [] }, 'Light Assault': { certifications: [ { skill: skills.lightAssault.c4, level: 2 }, { skill: skills.lightAssault.drifterJumpJets, level: 2 } ], equipment: [] }, 'Engineer': { certifications: [ { skill: skills.engineer.nanoArmorKit, level: 6 }, { skill: skills.engineer.claymoreMine, level: 2 }, { skill: skills.engineer.tankMine, level: 2 }, { skill: skills.engineer.ammunitionPackage, level: 3 }, { skill: skills.engineer.stickyGrenade, level: 1 } ], equipment: [ items.weapon.trac5s, items.engineer.avManaTurret ] }, 'Medic': { certifications: [ { skill: skills.medic.medicalApplicator, level: 6 }, { skill: skills.medic.nanoRegenDevice, level: 6 } ], equipment: [] }, 'Infiltrator': { certifications: [ { skill: skills.infiltrator.advancedEquipmentTerminalHacking, level: 3 } ], equipment: [] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.vehicleAmmoDispenser, level: 1 }, { skill: skills.sunderer.blockadeArmor, level: 3 }, { skill: skills.sunderer.gateShieldDiffuser, level: 2 } ], equipment: [] }, 'Squad Leader': { certifications: [ { skill: skills.squadLeader.priorityDeployment, level: 2 } ], equipment: [] } } }, 'medic': { meta: { passPercentage: 100 }, classes: { 'Loadout: Offensive Medic': { certifications: [ { skill: skills.medic.grenadeBandolier, level: 2 }, { skill: skills.medic.naniteReviveGrenade, level: 1 }, { skill: skills.medic.nanoRegenDevice, level: 6 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [] }, 'Loadout: Defensive Medic': { certifications: [ { skill: skills.medic.flakArmor, level: 4 }, { skill: skills.medic.naniteReviveGrenade, level: 1 }, { skill: skills.medic.regenerationField, level: 5 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [] } } }, 'engineer': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry MANA Turret': { certifications: [ { skill: skills.engineer.flakArmor, level: 4 }, { skill: skills.engineer.claymoreMine, level: 2 } ], equipment: [ items.weapon.trac5s ] }, 'Loadout: Anti-Vehicle MANA Turret': { certifications: [ { skill: skills.engineer.flakArmor, level: 4 }, { skill: skills.engineer.tankMine, level: 2 }, { skill: skills.engineer.avManaTurret, level: 1 } ], equipment: [ items.weapon.trac5s, items.engineer.avManaTurret ] } } }, 'lightAssault': { meta: { passPercentage: 100 }, classes: { 'Loadout: Bounty Hunter': { certifications: [ { skill: skills.lightAssault.flakArmor, level: 4 }, { skill: skills.lightAssault.jumpJets, level: 6 }, { skill: skills.lightAssault.flashGrenade, level: 1 } ], equipment: [] }, 'Loadout: Death From Above': { certifications: [ { skill: skills.lightAssault.grenadeBandolier, level: 2 }, { skill: skills.lightAssault.drifterJumpJets, level: 5 }, { skill: skills.lightAssault.smokeGrenade, level: 1 } ], equipment: [] } } }, 'infiltrator': { meta: { passPercentage: 100 }, classes: { 'Loadout: Close Quarters': { certifications: [ { skill: skills.infiltrator.flakArmor, level: 4 }, { skill: skills.infiltrator.grenadeBandolier, level: 2 }, { skill: skills.infiltrator.reconDetectDevice, level: 6 }, { skill: skills.infiltrator.claymoreMine, level: 2 }, { skill: skills.infiltrator.empGrenade, level: 1 } ], equipment: [ items.weapon.ns7pdw ] }, 'Loadout: Assassin': { certifications: [ { skill: skills.infiltrator.ammunitionBelt, level: 3 }, { skill: skills.infiltrator.motionSpotter, level: 5 }, { skill: skills.infiltrator.claymoreMine, level: 2 }, { skill: skills.infiltrator.decoyGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [ items.weapon.rams ] } } }, 'heavyAssault': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry': { certifications: [ { skill: skills.heavyAssault.grenadeBandolier, level: 2 }, { skill: skills.heavyAssault.flakArmor, level: 4 }, { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.concussionGrenade, level: 1 }, { skill: skills.universal.medicalKit, level: 3 } ], equipment: [ items.weapon.decimator ] }, 'Loadout: Anti-Armor': { certifications: [ { skill: skills.heavyAssault.flakArmor, level: 4 }, { skill: skills.heavyAssault.resistShield, level: 1 }, { skill: skills.heavyAssault.c4, level: 1 }, { skill: skills.heavyAssault.antiVehicleGrenade, level: 1 } ], equipment: [ items.weapon.skep, items.weapon.grounder ] } } }, 'maxUnit': { meta: { passPercentage: 100 }, classes: { 'Loadout: Anti-Infantry': { certifications: [ { skill: skills.max.kineticArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftMercy, items.max.rightMercy ] }, 'Loadout: Anti-Armor': { certifications: [ { skill: skills.max.flakArmor, level: 5 }, { skill: skills.max.kineticArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftPounder, items.max.rightPounder ] }, 'Loadout: Anti-Air': { certifications: [ { skill: skills.max.flakArmor, level: 5 }, { skill: skills.max.lockdown, level: 2 } ], equipment: [ items.max.leftBurster, items.max.rightBurster ] } } }, 'basicTanks': { meta: { passPercentage: 100 }, classes: { 'Prowler': { certifications: [ { skill: skills.prowler.anchoredMode, level: 1 } ], equipment: [ items.prowler.walker ] }, 'Sunderer': { certifications: [ { skill: skills.sunderer.vehicleAmmoDispenser, level: 1 }, { skill: skills.sunderer.gateShieldDiffuser, level: 2 } ], equipment: [] } } }, 'sunderer': { meta: { passPercentage: 100 }, classes: { 'Sunderer': { certifications: [ { skill: skills.sunderer.mineGuard, level: 4 }, { skill: skills.sunderer.blockadeArmor, level: 4 }, { skill: skills.sunderer.gateShieldDiffuser, level: 3 }, { skill: skills.sunderer.naniteProximityRepairSystem, level: 6 } ], equipment: [] } } }, 'prowler': { meta: { passPercentage: 100 }, classes: { 'Prowler': { certifications: [ { skill: skills.prowler.anchoredMode, level: 4 }, { skill: skills.prowler.mineGuard, level: 4 } ], equipment: [ items.prowler.p2120ap, items.prowler.halberd ] } } }, 'lightning': { meta: { passPercentage: 100 }, classes: { 'Lightning': { certifications: [ { skill: skills.lightning.reinforcedTopArmor, level: 1 } ], equipment: [ items.lightning.skyguard ] } } }, 'harasser': { meta: { passPercentage: 100 }, classes: { 'Harasser': { certifications: [ { skill: skills.harasser.fireSuppressionSystem, level: 4 }, { skill: skills.harasser.compositeArmor, level: 4 }, { skill: skills.harasser.turbo, level: 5 } ], equipment: [ items.harasser.halberd ] } } }, 'commander': { meta: { passPercentage: 100 }, classes: { 'Squad Leader': { certifications: [ { skill: skills.squadLeader.commandCommChannel, level: 1 }, { skill: skills.squadLeader.requestReinforcements, level: 1 }, { skill: skills.squadLeader.rallyPointGreen, level: 1 }, { skill: skills.squadLeader.rallyPointOrange, level: 1 }, { skill: skills.squadLeader.rallyPointPurple, level: 1 }, { skill: skills.squadLeader.rallyPointYellow, level: 1 }, { skill: skills.squadLeader.priorityDeployment, level: 4 } ], equipment: [] } } } }, echoHavoc = qual('Echo Havoc', null, null, true), max = qual('MAX', echoHavoc, requirements.maxUnit), heavyAssault = qual('Heavy Assault', max, requirements.heavyAssault), echoCovertOps = qual('Echo Covert Ops', null, null, true), infiltrator = qual('Infiltrator', echoCovertOps, requirements.infiltrator), lightAssault = qual('Light Assault', infiltrator, requirements.lightAssault), echoSpecialist = qual('Echo Specialist', null, null, true), engineer = qual('Engineer', echoSpecialist, requirements.engineer), combatMedic = qual('Combat Medic', engineer, requirements.medic), commander = qual('Commander', null, requirements.commander, true), sunderer = qual('Sunderer', [ echoSpecialist, echoCovertOps, echoHavoc ], requirements.sunderer), harasser = qual('Harasser', null, requirements.harasser), lightning = qual('Lightning', harasser, requirements.lightning), prowler = qual('Prowler', lightning, requirements.prowler), basicTanks = qual('Basic Tanks', [ sunderer, prowler ], requirements.basicTanks), veteran = qual('Veteran', [ combatMedic, lightAssault, heavyAssault, commander ], requirements.veteran, true), soldier = qual('Soldier', [ veteran, basicTanks ], requirements.soldier, true); addParentRelationships(soldier); return soldier; function qual(name, child, certs, isRank) { var obj = {}; obj.name = name; if (child) { if ($.isArray(child)) { obj.child = child; } else { obj.child = [ child ]; } } if (certs) { obj.cert = certs; } if (isRank) { obj.isRank = true; } return obj; } function addParentRelationships(rank, parent) { if (parent) { if (rank.parent) { rank.parent.push(parent); } else { rank.parent = [ parent ]; } } if (rank.child) { $.each(rank.child, function() { addParentRelationships(this, rank); }); } } }
stevenbenner/ps2-equipment-check
js/qualifications.js
JavaScript
mit
12,343
26.067982
112
0.573604
false
package addonloader.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Properties; /** * Simple wrapper around {@link Properites}, * allowing to easily access objects. * @author Enginecrafter77 */ public class ObjectSettings extends Properties{ private static final long serialVersionUID = -8939834947658913650L; private final File path; public ObjectSettings(File path) throws FileNotFoundException, IOException { this.path = path; this.load(new FileReader(path)); } public ObjectSettings(String path) throws FileNotFoundException, IOException { this(new File(path)); } public boolean getBoolean(String key, boolean def) { return Boolean.parseBoolean(this.getProperty(key, String.valueOf(def))); } public int getInteger(String key, int def) { return Integer.parseInt(this.getProperty(key, String.valueOf(def))); } public float getFloat(String key, float def) { return Float.parseFloat(this.getProperty(key, String.valueOf(def))); } public void set(String key, Object val) { this.setProperty(key, val.toString()); } public void store(String comment) { try { this.store(new FileOutputStream(path), comment); } catch(IOException e) { e.printStackTrace(); } } }
Enginecrafter77/LMPluger
src/addonloader/util/ObjectSettings.java
Java
mit
1,423
20.234375
77
0.703443
false
print ARGF.read.gsub!(/\B[a-z]+\B/) {|x| x.split('').sort_by{rand}.join}
J-Y/RubyQuiz
ruby_quiz/quiz76_sols/solutions/Himadri Choudhury/scramble.rb
Ruby
mit
73
72
72
0.575342
false
require 'minitest/autorun' require 'minitest/pride' require 'bundler/setup' Bundler.require(:default) require 'active_record' require File.dirname(__FILE__) + '/../lib/where_exists' ActiveRecord::Base.default_timezone = :utc ActiveRecord::Base.time_zone_aware_attributes = true ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => File.dirname(__FILE__) + "/db/test.db" )
EugZol/where_exists
test/test_helper.rb
Ruby
mit
402
27.714286
55
0.731343
false
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const ConfigLoader = require( 'easy/core/ConfigLoader' ) const EventsEmitter = require( 'events' ) /** * @class Database */ class Database { /** * @constructor */ constructor( config ) { this._config = config this.stateEmitter = new EventsEmitter() this.name = config.config.name this.init() } /** * init - init attributes */ init() { this._instance = null this._connector = this._config.connector this.resetProperties() } /** * Reset instance and connected state * * @memberOf Database */ resetProperties() { this._connected = false this._connectionError = null } /** * load - load database config */ async start() { await this.connect() } /** * restart - restart database component */ async restart() { this.resetProperties() await this.start() } /** * connect - connect database to instance */ async connect() { const { instance, connected, error } = await this.config.connector() const oldConnected = this.connected this.instance = instance this.connected = connected this.connectionError = error if ( this.connected !== oldConnected ) { this.stateEmitter.emit( 'change', this.connected ) } if ( error ) { throw new Error( error ) } } /** * Reset database connection and instance * * @memberOf Database */ disconnect() { const oldConnected = this.connected this.resetProperties() if ( this.connected !== oldConnected ) { this.stateEmitter.emit( 'change', this.connected ) } } /** * verifyConnectionHandler - handler called by daemon which indicates if database still available or not * * @returns {Promise} * * @memberOf Database */ verifyConnectionHandler() { return this.config.verifyConnectionHandler() } /** * Branch handler on database state events * * @param {Function} handler * * @memberOf Database */ connectToStateEmitter( handler ) { this.stateEmitter.on( 'change', handler ) } /** * get - get database instance * * @returns {Object} */ get instance() { return this._instance } /** * set - set database instance * * @param {Object} instance * @returns {Object} */ set instance( instance ) { this._instance = instance return this._instance } /** * get - get database connection state * * @returns {Object} */ get connected() { return this._connected } /** * set - set database connection state * * @param {boolean} connected * @returns {Database} */ set connected( connected ) { this._connected = connected return this } /** * get - get database configurations * * @returns {Object} */ get config() { return this._config } /** * Get connection error * * @readonly * * @memberOf Database */ get connectionError() { return this._connectionError } /** * Set connection error * * @returns {Database} * * @memberOf Database */ set connectionError( error ) { this._connectionError = error return this } } module.exports = Database
MadDeveloper/easy.js
easy/database/Database.js
JavaScript
mit
3,837
19.089005
108
0.547563
false
import { useEffect, useRef, useState } from "react" import * as React from "react" import { RelayPaginationProp, RelayRefetchProp, createPaginationContainer, } from "react-relay" import { graphql } from "relay-runtime" import Waypoint from "react-waypoint" import { Box, Flex, Spacer, Spinner } from "@artsy/palette" import compact from "lodash/compact" import styled from "styled-components" import { extractNodes } from "v2/Utils/extractNodes" import { ItemFragmentContainer } from "./Item" import { Reply } from "./Reply" import { ConversationMessagesFragmentContainer as ConversationMessages } from "./ConversationMessages" import { ConversationHeader } from "./ConversationHeader" import { ConfirmArtworkModalQueryRenderer } from "./ConfirmArtworkModal" import { BuyerGuaranteeMessage } from "./BuyerGuaranteeMessage" import { returnOrderModalDetails } from "../Utils/returnOrderModalDetails" import { OrderModal } from "./OrderModal" import { UnreadMessagesToastQueryRenderer } from "./UnreadMessagesToast" import useOnScreen from "../Utils/useOnScreen" import { UpdateConversation } from "../Mutation/UpdateConversationMutation" import { Conversation_conversation } from "v2/__generated__/Conversation_conversation.graphql" import { useRouter } from "v2/System/Router/useRouter" export interface ConversationProps { conversation: Conversation_conversation showDetails: boolean setShowDetails: (showDetails: boolean) => void relay: RelayPaginationProp refetch: RelayRefetchProp["refetch"] } export const PAGE_SIZE: number = 15 const Loading: React.FC = () => ( <SpinnerContainer> <Spinner /> </SpinnerContainer> ) const Conversation: React.FC<ConversationProps> = props => { const { conversation, relay, showDetails, setShowDetails } = props const liveArtwork = conversation?.items?.[0]?.liveArtwork const artwork = liveArtwork?.__typename === "Artwork" ? liveArtwork : null const isOfferable = !!artwork && !!artwork?.isOfferableFromInquiry const [showConfirmArtworkModal, setShowConfirmArtworkModal] = useState< boolean >(false) const inquiryItemBox = compact(conversation.items).map((i, idx) => { const isValidType = i.item?.__typename === "Artwork" || i.item?.__typename === "Show" return ( <ItemFragmentContainer item={i.item!} key={isValidType ? i.item?.id : idx} /> ) }) // ORDERS const [showOrderModal, setShowOrderModal] = useState<boolean>(false) const activeOrder = extractNodes(conversation.orderConnection)[0] let orderID let kind if (activeOrder) { kind = activeOrder.buyerAction orderID = activeOrder.internalID } const { url, modalTitle } = returnOrderModalDetails({ kind: kind!, orderID: orderID, }) // SCROLLING AND FETCHING // States and Refs const bottomOfMessageContainer = useRef<HTMLElement>(null) const initialMount = useRef(true) const initialScroll = useRef(true) const scrollContainer = useRef<HTMLDivElement>(null) const [fetchingMore, setFetchingMore] = useState<boolean>(false) const [lastMessageID, setLastMessageID] = useState<string | null>() const [lastOrderUpdate, setLastOrderUpdate] = useState<string | null>() const isBottomVisible = useOnScreen(bottomOfMessageContainer) // Functions const loadMore = (): void => { if (relay.isLoading() || !relay.hasMore() || !initialMount.current) return setFetchingMore(true) const scrollCursor = scrollContainer.current ? scrollContainer.current?.scrollHeight - scrollContainer.current?.scrollTop : 0 relay.loadMore(PAGE_SIZE, error => { if (error) console.error(error) setFetchingMore(false) if (scrollContainer.current) { // Scrolling to former position scrollContainer.current?.scrollTo({ top: scrollContainer.current?.scrollHeight - scrollCursor, behavior: "smooth", }) } }) } const { match } = useRouter() const conversationID = match?.params?.conversationID // TODO: refactor useEffect(() => { initialScroll.current = false }, [conversationID]) useEffect(() => { initialScroll.current = !fetchingMore }, [fetchingMore]) useEffect(() => { if (!fetchingMore && !initialScroll.current) { scrollToBottom() } }) const scrollToBottom = () => { if (!!bottomOfMessageContainer?.current) { bottomOfMessageContainer.current?.scrollIntoView?.({ block: "end", inline: "nearest", behavior: initialMount.current ? "auto" : "smooth", }) if (isBottomVisible) initialMount.current = false setLastMessageID(conversation?.lastMessageID) setOrderKey() } } const refreshData = () => { props.refetch({ conversationID: conversation.internalID }, null, error => { if (error) console.error(error) scrollToBottom() }) } const setOrderKey = () => { setLastOrderUpdate(activeOrder?.updatedAt) } const [toastBottom, setToastBottom] = useState(0) // Behaviours // -Navigation useEffect(() => { setLastMessageID(conversation?.fromLastViewedMessageID) initialMount.current = true setOrderKey() }, [ conversation.internalID, conversation.fromLastViewedMessageID, setOrderKey, ]) // -Last message opened useEffect(() => { // Set on a timeout so the user sees the "new" flag setTimeout( () => { UpdateConversation(relay.environment, conversation) }, !!conversation.isLastMessageToUser ? 3000 : 0 ) }, [lastMessageID]) // -Workaround Reply render resizing race condition useEffect(() => { if (initialMount.current) scrollToBottom() const rect = scrollContainer.current?.getBoundingClientRect() setToastBottom(window.innerHeight - (rect?.bottom ?? 0) + 30) }, [scrollContainer?.current?.clientHeight]) // -On scroll down useEffect(() => { if (isBottomVisible) refreshData() }, [isBottomVisible]) return ( <Flex flexDirection="column" flexGrow={1}> <ConversationHeader partnerName={conversation.to.name} showDetails={showDetails} setShowDetails={setShowDetails} /> <NoScrollFlex flexDirection="column" width="100%"> <MessageContainer ref={scrollContainer as any}> <Box pb={[6, 6, 6, 0]} pr={1}> <Spacer mt={["75px", "75px", 2]} /> <Flex flexDirection="column" width="100%" px={1}> {isOfferable && <BuyerGuaranteeMessage />} {inquiryItemBox} <Waypoint onEnter={loadMore} /> {fetchingMore ? <Loading /> : null} <ConversationMessages messages={conversation.messagesConnection!} events={conversation.orderConnection} lastViewedMessageID={conversation?.fromLastViewedMessageID} setShowDetails={setShowDetails} /> <Box ref={bottomOfMessageContainer as any} /> </Flex> </Box> <UnreadMessagesToastQueryRenderer conversationID={conversation?.internalID!} lastOrderUpdate={lastOrderUpdate} bottom={toastBottom} hasScrolled={!isBottomVisible} onClick={scrollToBottom} refreshCallback={refreshData} /> </MessageContainer> <Reply onScroll={scrollToBottom} conversation={conversation} refetch={props.refetch} environment={relay.environment} openInquiryModal={() => setShowConfirmArtworkModal(true)} openOrderModal={() => setShowOrderModal(true)} /> </NoScrollFlex> {isOfferable && ( <ConfirmArtworkModalQueryRenderer artworkID={artwork?.internalID!} conversationID={conversation.internalID!} show={showConfirmArtworkModal} closeModal={() => setShowConfirmArtworkModal(false)} /> )} {isOfferable && ( <OrderModal path={url!} orderID={orderID} title={modalTitle!} show={showOrderModal} closeModal={() => { refreshData() setShowOrderModal(false) }} /> )} </Flex> ) } const MessageContainer = styled(Box)` flex-grow: 1; overflow-y: auto; ` const NoScrollFlex = styled(Flex)` overflow: hidden; flex-grow: 1; ` const SpinnerContainer = styled.div` width: 100%; height: 100px; position: relative; ` export const ConversationPaginationContainer = createPaginationContainer( Conversation, { conversation: graphql` fragment Conversation_conversation on Conversation @argumentDefinitions( count: { type: "Int", defaultValue: 30 } after: { type: "String" } ) { id internalID from { name email } to { name initials } initialMessage lastMessageID fromLastViewedMessageID isLastMessageToUser unread orderConnection( first: 10 states: [APPROVED, FULFILLED, SUBMITTED, REFUNDED, CANCELED] participantType: BUYER ) { edges { node { internalID updatedAt ... on CommerceOfferOrder { buyerAction } } } ...ConversationMessages_events } unread messagesConnection(first: $count, after: $after, sort: DESC) @connection(key: "Messages_messagesConnection", filters: []) { pageInfo { startCursor endCursor hasPreviousPage hasNextPage } edges { node { id } } totalCount ...ConversationMessages_messages } items { item { __typename ... on Artwork { id isOfferableFromInquiry internalID } ...Item_item } liveArtwork { ... on Artwork { isOfferableFromInquiry internalID __typename } } } ...ConversationCTA_conversation } `, }, { direction: "forward", getConnectionFromProps(props) { return props.conversation?.messagesConnection }, getFragmentVariables(prevVars, count) { return { ...prevVars, count, } }, getVariables(props, { cursor, count }) { return { count, cursor, after: cursor, conversationID: props.conversation.id, } }, query: graphql` query ConversationPaginationQuery( $count: Int $after: String $conversationID: ID! ) { node(id: $conversationID) { ...Conversation_conversation @arguments(count: $count, after: $after) } } `, } )
artsy/force
src/v2/Apps/Conversation/Components/Conversation.tsx
TypeScript
mit
11,098
27.239186
102
0.614435
false
--- layout: post title: Hybrid重构框架 color: blue width: 3 height: 1 category: hybrid --- #### Hybrid重构框架结构 !["框架结构"]({{"/assets/framework/1.png" | prepend: site.baseurl }}) 框架结构是基于业务模型定制的 分为 【公共模块】 和 【业务模块】 #### 公共模块(Common ) 组成 公共模块 由两部分组成 分别是 【Scss】 和 【Widget】 !["公共模块结构"]({{"/assets/framework/2.png" | prepend: site.baseurl }}) *** **Scss 放着框架公用代码** 【component】 * _button(按钮) * _list-item(列表 包括带箭头的) * _name-gender(性别样式 主要用在理财师业务模块中) * _notice-bar(小黄条) * _value(代表收益涨、跌的公共色值类) 【mixins】 * _border-line(兼容ios9 和 Android 关于1px显示的粗细问题 现已统一采用1px/*no*/) * _button(按钮 + 状态) * _clearfix(清除浮动) * _cus-font-height(自定义字号 高度 和button 合作用的) * _ellipse(省略号缩写) * _list-item(列表样式 供 component里的的list-item调用) * _value(涨跌样式 供 component里的的value调用) * _way-step-v(类似时间轴一样的 竖列步骤结构) 【themes】 定义了全站通用的颜色值 * 字体 * 基本色 橙色、白色、蓝色 * 蓝色、灰色的灰度级 * 线条色 * 文本色 * 按钮色 * 收益涨跌色值 【core】是以上通用 样式的集合出口 *** **Widget 存放框架组件样式代码** 暂时抽出的组件有 * animate(动画) * banner(广告banner) * baseloading(加载样式) * fundItem(基金模块) * indexCrowdfunding(理财首页的众筹模块) * newsItem(发现频道的 新闻模块) * prodfixItem (固收页的 产品模块 包括新手 和 加息类产品) * slick (轮播组件样式) * tab ( tab 导航) *** #### 业务模块(Pages) 组成 目前业务模块 有众筹、白拿、基金、理财、发现、积分商城、新手引导、邀请、理财师 后续会根据业务内容的增加而变化 !["业务模块"]({{"/assets/framework/3.png" | prepend: site.baseurl }})
Angelkuga/h5-standard-spec
_posts/2016-10-23-hybrid-refactor-framework.markdown
Markdown
mit
2,288
11.045045
67
0.58852
false
<?php class LinterTests extends PHPUnit_Framework_TestCase { /** * @param string $source * @param \Superbalist\Money\Linter\Tests\LinterTestInterface $test */ protected function assertLinterThrowsWarnings($source, \Superbalist\Money\Linter\Tests\LinterTestInterface $test) { $result = $test->analyse($source); $this->assertNotEmpty($result); } /** * */ public function testMatchesAbsFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo abs(-37);', new \Superbalist\Money\Linter\Tests\AbsFunctionCallTest() ); } /** * */ public function testMatchesArraySumFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $values = array(0, 1, 2, 3); $sum = array_sum($values);', new \Superbalist\Money\Linter\Tests\ArraySumFunctionCallTest() ); } /** * */ public function testMatchesCeilFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo ceil(3.3);', new \Superbalist\Money\Linter\Tests\CeilFunctionCallTest() ); } /** * */ public function testMatchesDivideOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 / 0.1;', new \Superbalist\Money\Linter\Tests\DivideOperatorTest() ); } /** * */ public function testMatchesFloatCastTest() { $this->assertLinterThrowsWarnings( '<?php $test = "3.3"; echo (float) $test;', new \Superbalist\Money\Linter\Tests\FloatCastTest() ); } /** * */ public function testMatchesFloatParamDocBlockTest() { $source = <<<'EOT' <?php /** * @param float $number this is a test * @return float test */ public function getFloatNumber($number) { return $number; } EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatParamDocBlockTest()); } /** * */ public function testMatchesFloatReturnDocBlockTest() { $source = <<<'EOT' <?php /** * @param float $number this is a test * @return float test */ public function getFloatNumber($number) { return $number; } EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatReturnDocBlockTest()); } /** * */ public function testMatchesFloatvalFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo floatval("3.3");', new \Superbalist\Money\Linter\Tests\FloatvalFunctionCallTest() ); } /** * */ public function testMatchesFloatVarDocBlockTest() { $source = <<<'EOT' <?php /** * @var float */ protected $number = 0.0; EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\FloatVarDocBlockTest()); } /** * */ public function testMatchesFloorFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo floor(3.3);', new \Superbalist\Money\Linter\Tests\FloorFunctionCallTest() ); } /** * */ public function testMatchesGreaterThanOperatorTest() { $this->assertLinterThrowsWarnings( '<?php if (4 > 3) { echo "true"; } else { echo "false"; }', new \Superbalist\Money\Linter\Tests\GreaterThanOperatorTest() ); } /** * */ public function testMatchesGreaterThanOrEqualsOperatorTest() { $this->assertLinterThrowsWarnings( '<?php if (4 >= 3) { echo "true"; } else { echo "false"; }', new \Superbalist\Money\Linter\Tests\GreaterThanOrEqualsOperatorTest() ); } /** * */ public function testMatchesIntCastTest() { $this->assertLinterThrowsWarnings( '<?php $test = "3.3"; echo (int) $test;', new \Superbalist\Money\Linter\Tests\IntCastTest() ); } /** * */ public function testMatchesIntParamDocBlockTest() { $source = <<<'EOT' <?php /** * @param int $number this is a test * @return int test */ public function getIntNumber($number) { return $number; } EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntParamDocBlockTest()); } /** * */ public function testMatchesIntReturnDocBlockTest() { $source = <<<'EOT' <?php /** * @param int $number this is a test * @return int test */ public function getIntNumber($number) { return $number; } EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntReturnDocBlockTest()); } /** * */ public function testMatchesIntvalFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo intval("3.3");', new \Superbalist\Money\Linter\Tests\IntvalFunctionCallTest() ); } /** * */ public function testMatchesIntVarDocBlockTest() { $source = <<<'EOT' <?php /** * @var int */ protected $number = 0; EOT; $this->assertLinterThrowsWarnings($source, new \Superbalist\Money\Linter\Tests\IntVarDocBlockTest()); } /** * */ public function testMatchesIsFloatFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $a = 3.3; var_dump(is_float($a));', new \Superbalist\Money\Linter\Tests\IsFloatFunctionCallTest() ); } /** * */ public function testMatchesIsIntegerFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $a = 3; var_dump(is_integer($a));', new \Superbalist\Money\Linter\Tests\IsIntegerFunctionCallTest() ); } /** * */ public function testMatchesIsIntFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $a = 3; var_dump(is_int($a));', new \Superbalist\Money\Linter\Tests\IsIntFunctionCallTest() ); } /** * */ public function testMatchesIsNumericFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php $a = 3; var_dump(is_numeric($a));', new \Superbalist\Money\Linter\Tests\IsNumericFunctionCallTest() ); } /** * */ public function testMatchesMaxFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo max(0, 3.3);', new \Superbalist\Money\Linter\Tests\MaxFunctionCallTest() ); } /** * */ public function testMatchesMinFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo min(0, 3.3);', new \Superbalist\Money\Linter\Tests\MinFunctionCallTest() ); } /** * */ public function testMatchesMinusOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 - 0.1;', new \Superbalist\Money\Linter\Tests\MinusOperatorTest() ); } /** * */ public function testMatchesModOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 4 % 2;', new \Superbalist\Money\Linter\Tests\ModOperatorTest() ); } /** * */ public function testMatchesMoneyFormatCallTest() { $this->assertLinterThrowsWarnings( '<?php echo money_format("%.2n", 2.4562)', new \Superbalist\Money\Linter\Tests\MoneyFormatCallTest() ); } /** * */ public function testMatchesMultiplyOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 * 0.1;', new \Superbalist\Money\Linter\Tests\MultiplyOperatorTest() ); } /** * */ public function testMatchesNumberFloatTest() { $this->assertLinterThrowsWarnings( '<?php $test = 0.2 + 0.1;', new \Superbalist\Money\Linter\Tests\NumberFloatTest() ); } /** * */ public function testMatchesNumberFormatCallTest() { $this->assertLinterThrowsWarnings( '<?php echo number_format(1.3, 2)', new \Superbalist\Money\Linter\Tests\NumberFormatCallTest() ); } /** * */ public function testMatchesNumberIntTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 + 0.1;', new \Superbalist\Money\Linter\Tests\NumberIntTest() ); } /** * */ public function testMatchesPlusOperatorTest() { $this->assertLinterThrowsWarnings( '<?php $test = 1 + 0.1;', new \Superbalist\Money\Linter\Tests\PlusOperatorTest() ); } /** * */ public function testMatchesPowFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo pow(2, 8);', new \Superbalist\Money\Linter\Tests\PowFunctionCallTest() ); } /** * */ public function testMatchesRoundFunctionCallTest() { $this->assertLinterThrowsWarnings( '<?php echo round(9.93434, 2);', new \Superbalist\Money\Linter\Tests\RoundFunctionCallTest() ); } /** * */ public function testMatchesSmallerThanOperatorTest() { $this->assertLinterThrowsWarnings( '<?php if (4 < 3) { echo "true"; } else { echo "false"; }', new \Superbalist\Money\Linter\Tests\SmallerThanOperatorTest() ); } /** * */ public function testMatchesSmallerThanOrEqualsOperatorTest() { $this->assertLinterThrowsWarnings( '<?php if (4 <= 3) { echo "true"; } else { echo "false"; }', new \Superbalist\Money\Linter\Tests\SmallerThanOrEqualsOperatorTest() ); } /** * */ public function testMatchesSprintfFormatFloatTest() { $this->assertLinterThrowsWarnings( '<?php echo sprintf("%f", 4.55555);', new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest() ); $this->assertLinterThrowsWarnings( '<?php echo sprintf("%.2f %s", 4.55555, "test");', new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest() ); $this->assertLinterThrowsWarnings( '<?php echo sprintf("%.2f %s", 4.55555, sprintf("%s", "test")); $test = intval(1.1);', new \Superbalist\Money\Linter\Tests\SprintfFormatFloatTest() ); } /** * */ public function testMatchesVariableDecrementTest() { $this->assertLinterThrowsWarnings( '<?php $n = 3; $n--;', new \Superbalist\Money\Linter\Tests\VariableDecrementTest() ); } /** * */ public function testMatchesVariableDivideEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 21; $n /= 3;', new \Superbalist\Money\Linter\Tests\VariableDivideEqualsTest() ); } /** * */ public function testMatchesVariableIncrementTest() { $this->assertLinterThrowsWarnings( '<?php $n = 3; $n++;', new \Superbalist\Money\Linter\Tests\VariableIncrementTest() ); } /** * */ public function testMatchesVariableMinusEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 21; $n -= 2;', new \Superbalist\Money\Linter\Tests\VariableMinusEqualsTest() ); } /** * */ public function testMatchesVariableModEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 24; $n %= 2;', new \Superbalist\Money\Linter\Tests\VariableModEqualsTest() ); } /** * */ public function testMatchesVariablePlusEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 21; $n += 2;', new \Superbalist\Money\Linter\Tests\VariablePlusEqualsTest() ); } /** * */ public function testMatchesVariableTimesEqualsTest() { $this->assertLinterThrowsWarnings( '<?php $n = 21; $n *= 2;', new \Superbalist\Money\Linter\Tests\VariableTimesEqualsTest() ); } }
Superbalist/php-money
tests/LinterTests.php
PHP
mit
12,597
22.284658
117
0.558863
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>hammer: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.1 / hammer - 1.3+8.12</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> hammer <small> 1.3+8.12 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-10 07:56:43 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-10 07:56:43 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;palmskog@gmail.com&quot; homepage: &quot;https://github.com/lukaszcz/coqhammer&quot; dev-repo: &quot;git+https://github.com/lukaszcz/coqhammer.git&quot; bug-reports: &quot;https://github.com/lukaszcz/coqhammer/issues&quot; license: &quot;LGPL-2.1-only&quot; synopsis: &quot;General-purpose automated reasoning hammer tool for Coq&quot; description: &quot;&quot;&quot; A general-purpose automated reasoning hammer tool for Coq that combines learning from previous proofs with the translation of problems to the logics of automated systems and the reconstruction of successfully found proofs. &quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot; {ocaml:version &gt;= &quot;4.06&quot;} &quot;plugin&quot;] install: [ [make &quot;install-plugin&quot;] [make &quot;test-plugin&quot;] {with-test} ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.12&quot; &amp; &lt; &quot;8.13~&quot;} (&quot;conf-g++&quot; {build} | &quot;conf-clang&quot; {build}) &quot;coq-hammer-tactics&quot; {= version} ] tags: [ &quot;category:Miscellaneous/Coq Extensions&quot; &quot;keyword:automation&quot; &quot;keyword:hammer&quot; &quot;logpath:Hammer.Plugin&quot; &quot;date:2020-07-28&quot; ] authors: [ &quot;Lukasz Czajka &lt;lukaszcz@mimuw.edu.pl&gt;&quot; &quot;Cezary Kaliszyk &lt;cezary.kaliszyk@uibk.ac.at&gt;&quot; ] url { src: &quot;https://github.com/lukaszcz/coqhammer/archive/v1.3-coq8.12.tar.gz&quot; checksum: &quot;sha512=666ea825c122319e398efb7287f429ebfb5d35611b4cabe4b88732ffb5c265ef348b53d5046c958831ac0b7a759b44ce1ca04220ca68b1915accfd23435b479c&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-hammer.1.3+8.12 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-hammer -&gt; coq &gt;= 8.12 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hammer.1.3+8.12</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.07.1-2.0.6/released/8.8.1/hammer/1.3+8.12.html
HTML
mit
7,338
39.854749
159
0.555996
false
package ch.bisi.koukan.job; import ch.bisi.koukan.provider.XMLExchangeRatesProvider; import ch.bisi.koukan.repository.DataAccessException; import ch.bisi.koukan.repository.ExchangeRatesRepository; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * Executes scheduled tasks for updating the in memory exchange rates * by querying the European Central Bank endpoints. */ @Component public class ECBDataLoaderScheduler { private static final Logger logger = LoggerFactory.getLogger(ECBDataLoaderScheduler.class); private final XMLExchangeRatesProvider xmlExchangeRatesProvider; private final ExchangeRatesRepository exchangeRatesRepository; private final URL dailyEndpoint; private final URL pastDaysEndpoint; /** * Instantiates a new {@link ECBDataLoaderScheduler}. * * @param xmlExchangeRatesProvider the provider of exchange rates * @param exchangeRatesRepository the repository * @param dailyEndpoint the ECB daily endpoint {@link URL} * @param pastDaysEndpoint the ECB endpoint {@link URL} for retrieving past days data */ @Autowired public ECBDataLoaderScheduler( @Qualifier("ECBProvider") final XMLExchangeRatesProvider xmlExchangeRatesProvider, final ExchangeRatesRepository exchangeRatesRepository, @Qualifier("dailyEndpoint") final URL dailyEndpoint, @Qualifier("pastDaysEndpoint") final URL pastDaysEndpoint) { this.xmlExchangeRatesProvider = xmlExchangeRatesProvider; this.exchangeRatesRepository = exchangeRatesRepository; this.dailyEndpoint = dailyEndpoint; this.pastDaysEndpoint = pastDaysEndpoint; } /** * Retrieves the whole exchange rates daily data. * * @throws IOException in case of the problems accessing the ECB endpoint * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ @Scheduled(initialDelay = 0, fixedRateString = "${daily.rates.update.rate}") public void loadDailyData() throws IOException, XMLStreamException, DataAccessException { try (final InputStream inputStream = dailyEndpoint.openStream()) { logger.info("Updating ECB daily exchange rates data"); loadData(inputStream); } } /** * Retrieves the whole exchange rates data for past days. * * @throws IOException in case of the problems accessing the ECB endpoint * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ @Scheduled(initialDelay = 0, fixedRateString = "${past.days.rates.update.rate}") public void loadPastDaysData() throws IOException, XMLStreamException, DataAccessException { try (final InputStream inputStream = pastDaysEndpoint.openStream()) { logger.info("Updating ECB exchange rates data for the past 90 days"); loadData(inputStream); } } /** * Loads exchange rates data from the given {@link InputStream}. * * @param inputStream the {@link InputStream} * @throws XMLStreamException in case of problems parsing the ECB XML * @throws DataAccessException in case of problems accessing the underlying data */ private void loadData(final InputStream inputStream) throws XMLStreamException, DataAccessException { final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance() .createXMLStreamReader(inputStream); exchangeRatesRepository.save(xmlExchangeRatesProvider.retrieveAll(xmlStreamReader)); } }
bisignam/koukan
src/main/java/ch/bisi/koukan/job/ECBDataLoaderScheduler.java
Java
mit
3,982
40.051546
94
0.775992
false
<?php namespace JetMinds\Job\Updates; use Schema; use October\Rain\Database\Schema\Blueprint; use October\Rain\Database\Updates\Migration; class CreateResumesTable extends Migration { public function up() { Schema::create('jetminds_job_resumes', function(Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('first_name')->nullable(); $table->string('last_name')->nullable(); $table->string('email')->nullable(); $table->string('phone')->nullable(); $table->string('position')->nullable(); $table->longText('location')->nullable(); $table->string('resume_category')->nullable(); $table->string('resume_education')->nullable(); $table->longText('education_note')->nullable(); $table->string('resume_experience')->nullable(); $table->longText('experience_note')->nullable(); $table->string('resume_language')->nullable(); $table->string('resume_skill')->nullable(); $table->longText('resume_note')->nullable(); $table->boolean('is_invite')->default(1); $table->timestamps(); }); } public function down() { Schema::dropIfExists('jetminds_job_resumes'); } }
jetmindsgroup/job-plugin
updates/create_resumes_table.php
PHP
mit
1,311
34.432432
75
0.591915
false
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace SpartaHack { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public static ObservableValue<string> Title { get; set; } public static ObservableValue<bool> LoggedIn { get; set; } public static ObservableValue<string> Time { get; set; } public static MainPage root; private DateTime DoneTime; public MainPage(Frame frame) { this.InitializeComponent(); Title = new ObservableValue<string>(); LoggedIn = new ObservableValue<bool>(); Time = new ObservableValue<string>(); this.MySplitView.Content = frame; DataContext = this; DoneTime = DateTime.Parse("1/22/2017 17:00:00 GMT"); DispatcherTimer dt = new DispatcherTimer(); dt.Interval = TimeSpan.FromSeconds(1); dt.Tick += Dt_Tick; this.Loaded += (s,e) => { rdAnnouncements.IsChecked = true; dt.Start(); }; MySplitView.PaneClosed += (s, e) => { grdHideView.Visibility = Visibility.Collapsed; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); }; } private void Dt_Tick(object sender, object e) { TimeSpan dt = DoneTime.ToUniversalTime().Subtract(DateTime.Now.ToUniversalTime()); if (dt.TotalSeconds <= 0) Time.Value = "FINISHED"; else //txtCountDown.Text = dt.ToString(@"hh\:mm\:ss"); //Time.Value = $"{(int)dt.TotalHours}H {dt.Minutes}M {dt.Seconds}S"; Time.Value= string.Format("{0:##}h {1:##}m {2:##}s", ((int)dt.TotalHours), dt.Minutes.ToString(), dt.Seconds.ToString()); } private void OnAnnouncementsChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(AnnouncementsPage)); } catch { } } private void OnScheduleChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(SchedulePage)); } catch { } } private void OnTicketChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(TicketPage)); } catch { } } private void OnMapChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(MapPage)); } catch { } } private void OnSponsorChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(SponsorPage)); } catch { } } private void OnPrizeChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(PrizePage)); } catch { } } private void OnLoginChecked(object sender, RoutedEventArgs e) { try { MySplitView.IsPaneOpen = false; if (MySplitView.Content != null) ((Frame)MySplitView.Content).Navigate(typeof(ProfilePage)); } catch { } } private void HambButton_Click(object sender, RoutedEventArgs e) { try { grdHideView.Visibility = grdHideView.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible; MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); } catch { } } private void grdHideView_Tapped(object sender, TappedRoutedEventArgs e) { try { grdHideView.Visibility = grdHideView.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible; MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen; bgPane.Margin = new Thickness(MySplitView.IsPaneOpen ? MySplitView.OpenPaneLength : MySplitView.CompactPaneLength, bgPane.Margin.Top, bgPane.Margin.Right, bgPane.Margin.Bottom); } catch { } } } }
SpartaHack/SpartaHack2016-Windows
2017/SpartaHack/SpartaHack/MainPage.xaml.cs
C#
mit
6,063
33.634286
193
0.561623
false
using System; using System.Diagnostics; namespace Oragon.Architecture.IO.Path { partial class PathHelpers { #region Private Classes private sealed class RelativeFilePath : RelativePathBase, IRelativeFilePath { #region Internal Constructors internal RelativeFilePath(string pathString) : base(pathString) { Debug.Assert(pathString != null); Debug.Assert(pathString.Length > 0); Debug.Assert(pathString.IsValidRelativeFilePath()); } #endregion Internal Constructors #region Public Properties public string FileExtension { get { return FileNameHelpers.GetFileNameExtension(m_PathString); } } // // File Name and File Name Extension // public string FileName { get { return FileNameHelpers.GetFileName(m_PathString); } } public string FileNameWithoutExtension { get { return FileNameHelpers.GetFileNameWithoutExtension(m_PathString); } } // // IsFilePath ; IsDirectoryPath // public override bool IsDirectoryPath { get { return false; } } public override bool IsFilePath { get { return true; } } #endregion Public Properties #region Public Methods public override IAbsolutePath GetAbsolutePathFrom(IAbsoluteDirectoryPath path) { return (this as IRelativeFilePath).GetAbsolutePathFrom(path); } public IRelativeDirectoryPath GetBrotherDirectoryWithName(string directoryName) { Debug.Assert(directoryName != null); // Enforced by contract Debug.Assert(directoryName.Length > 0); // Enforced by contract IDirectoryPath path = PathBrowsingHelpers.GetBrotherDirectoryWithName(this, directoryName); var pathTyped = path as IRelativeDirectoryPath; Debug.Assert(pathTyped != null); return pathTyped; } public IRelativeFilePath GetBrotherFileWithName(string fileName) { Debug.Assert(fileName != null); // Enforced by contract Debug.Assert(fileName.Length > 0); // Enforced by contract IFilePath path = PathBrowsingHelpers.GetBrotherFileWithName(this, fileName); var pathTyped = path as IRelativeFilePath; Debug.Assert(pathTyped != null); return pathTyped; } public bool HasExtension(string extension) { // All these 3 assertions have been checked by contract! Debug.Assert(extension != null); Debug.Assert(extension.Length >= 2); Debug.Assert(extension[0] == '.'); return FileNameHelpers.HasExtension(m_PathString, extension); } IDirectoryPath IFilePath.GetBrotherDirectoryWithName(string directoryName) { Debug.Assert(directoryName != null); // Enforced by contract Debug.Assert(directoryName.Length > 0); // Enforced by contract return this.GetBrotherDirectoryWithName(directoryName); } // Explicit Impl methods IFilePath IFilePath.GetBrotherFileWithName(string fileName) { Debug.Assert(fileName != null); // Enforced by contract Debug.Assert(fileName.Length > 0); // Enforced by contract return this.GetBrotherFileWithName(fileName); } IFilePath IFilePath.UpdateExtension(string newExtension) { // All these 3 assertions have been checked by contract! Debug.Assert(newExtension != null); Debug.Assert(newExtension.Length >= 2); Debug.Assert(newExtension[0] == '.'); return this.UpdateExtension(newExtension); } // // Absolute/Relative pathString conversion // IAbsoluteFilePath IRelativeFilePath.GetAbsolutePathFrom(IAbsoluteDirectoryPath path) { Debug.Assert(path != null); // Enforced by contracts! string pathAbsolute, failureReason; if (!AbsoluteRelativePathHelpers.TryGetAbsolutePathFrom(path, this, out pathAbsolute, out failureReason)) { throw new ArgumentException(failureReason); } Debug.Assert(pathAbsolute != null); Debug.Assert(pathAbsolute.Length > 0); return (pathAbsolute + MiscHelpers.DIR_SEPARATOR_CHAR + this.FileName).ToAbsoluteFilePath(); } // // Path Browsing facilities // public IRelativeFilePath UpdateExtension(string newExtension) { // All these 3 assertions have been checked by contract! Debug.Assert(newExtension != null); Debug.Assert(newExtension.Length >= 2); Debug.Assert(newExtension[0] == '.'); string pathString = PathBrowsingHelpers.UpdateExtension(this, newExtension); Debug.Assert(pathString.IsValidRelativeFilePath()); return new RelativeFilePath(pathString); } #endregion Public Methods } #endregion Private Classes } }
luizcarlosfaria/Oragon.Architecture
[source]/Oragon.Architecture/IO/Path/PathHelpers+RelativeFilePath.cs
C#
mit
4,445
30.985612
119
0.728459
false
--- layout: page title: Guardian Quality Technologies Award Ceremony date: 2016-05-24 author: Peter Simmons tags: weekly links, java status: published summary: Sed consequat quis sapien eget malesuada. Morbi semper tempor nunc. banner: images/banner/meeting-01.jpg booking: startDate: 12/25/2019 endDate: 12/28/2019 ctyhocn: MSLOHHX groupCode: GQTAC published: true --- Aliquam bibendum sit amet nibh et feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam feugiat dictum sapien, eget vestibulum mauris tincidunt ut. Quisque suscipit diam vel aliquet suscipit. Donec at sollicitudin orci. Integer est nulla, elementum quis viverra non, semper nec nibh. Mauris pellentesque ligula ac nisl mollis, sit amet semper sapien luctus. Aenean dignissim in lacus sed convallis. Quisque ac dignissim tellus, vel blandit diam. Maecenas consequat ligula ut purus semper, a condimentum tellus volutpat. Aliquam quis lorem ante. Quisque tempus pretium urna. Proin justo nisi, maximus et velit vitae, dictum pretium dui. Ut ut luctus magna. Phasellus lectus justo, varius sed ultrices nec, malesuada id massa. Mauris nulla justo, finibus commodo lobortis sed, pulvinar id ipsum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla fermentum lobortis arcu, id elementum diam tempor vitae. Aliquam erat volutpat. Nulla lacinia metus sit amet cursus lacinia. * Suspendisse congue velit sed varius malesuada * Nulla et ante luctus, sollicitudin justo ullamcorper, aliquet nulla * Proin tincidunt sem quis venenatis cursus * Pellentesque a ipsum tincidunt nisi aliquet varius in sit amet metus * Vestibulum eu ante sit amet lectus vestibulum pretium ut et libero. Nullam molestie felis quis nunc tincidunt, at vestibulum enim tempus. Vivamus imperdiet nec est non tempor. Curabitur at scelerisque leo. Morbi tempor arcu at ex finibus pulvinar. Curabitur ullamcorper tincidunt hendrerit. Donec quam nibh, viverra non feugiat sit amet, dictum ac libero. Ut dignissim neque sit amet tortor lobortis efficitur. Curabitur id consectetur turpis, quis facilisis augue. Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas sit amet rhoncus erat, nec pulvinar metus.
KlishGroup/prose-pogs
pogs/M/MSLOHHX/GQTAC/index.md
Markdown
mit
2,265
86.115385
576
0.812804
false
--- layout: page title: Protector Purple Group Show date: 2016-05-24 author: Barbara Riddle tags: weekly links, java status: published summary: In lacinia libero vitae ullamcorper malesuada. banner: images/banner/wedding.jpg booking: startDate: 05/06/2019 endDate: 05/07/2019 ctyhocn: PTNHHHX groupCode: PPGS published: true --- Quisque fermentum nibh lorem, non feugiat nunc dignissim nec. Praesent sed neque sollicitudin, fermentum purus a, porttitor urna. Nullam placerat varius ipsum, quis porttitor sem gravida et. Pellentesque porta interdum luctus. Cras dolor tellus, tristique non efficitur id, ultrices vel nisi. Pellentesque viverra quam vitae est tincidunt, ac lobortis nulla dictum. Vestibulum ornare turpis erat, et porta magna imperdiet sed. Phasellus auctor dui sed ipsum venenatis, ornare porttitor magna varius. * Aliquam porttitor elit at ipsum feugiat, in vehicula elit hendrerit * Morbi quis ligula non nulla sollicitudin sollicitudin eu sed mi * Ut accumsan nisi nec nisl varius, at euismod mi sodales * Nulla tristique magna nec accumsan posuere. Cras ultricies tellus in elit congue pretium. Sed efficitur quam feugiat orci tincidunt finibus. Praesent consectetur sed purus ut condimentum. Suspendisse tincidunt condimentum viverra. In porta rhoncus arcu, a lacinia risus maximus non. Pellentesque et gravida velit. Suspendisse a aliquet mauris. Pellentesque tempor interdum elit sed aliquam. Praesent semper est a metus aliquet, nec ornare nunc sollicitudin. Aliquam non orci dictum, bibendum mi eu, pellentesque mi. Nulla risus odio, blandit in auctor vel, sagittis eu nisi. Curabitur porttitor purus nisi. In eget accumsan erat.
KlishGroup/prose-pogs
pogs/P/PTNHHHX/PPGS/index.md
Markdown
mit
1,665
68.375
585
0.809009
false
--- layout: page title: Liberated Peace Electronics Party date: 2016-05-24 author: Charles Hunt tags: weekly links, java status: published summary: Sed sit amet facilisis elit. banner: images/banner/leisure-01.jpg booking: startDate: 11/07/2018 endDate: 11/12/2018 ctyhocn: NCLHXHX groupCode: LPEP published: true --- Ut consequat tortor non eros interdum consectetur. Vestibulum porta gravida nisi, ac laoreet sem imperdiet sit amet. Curabitur dictum elit nisl. Fusce sit amet nulla magna. Nulla risus erat, aliquam sit amet mattis in, placerat sed massa. In dolor ante, ornare at tristique non, rhoncus ac diam. In augue urna, ultrices sed commodo in, pellentesque ut dolor. Vestibulum cursus consectetur odio, lobortis malesuada lectus. Nullam dignissim gravida tristique. 1 Donec eleifend neque blandit enim auctor, ut pellentesque est pulvinar 1 In vitae erat efficitur, rhoncus sem ac, auctor leo 1 Nulla eget est non metus vestibulum convallis 1 Aenean eu purus malesuada, mollis enim nec, aliquet lectus 1 Phasellus nec nisi efficitur, accumsan neque ut, mollis dolor. Praesent tincidunt vulputate elit. Aliquam erat volutpat. Proin placerat nisi ut diam posuere, a laoreet enim luctus. Vestibulum luctus urna a nisi commodo congue. Donec sit amet sem et augue placerat sodales a eget nibh. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum vel ullamcorper urna. Donec cursus imperdiet erat, at finibus velit egestas iaculis. Duis malesuada laoreet leo, in aliquam neque faucibus in. Praesent faucibus diam eget odio lobortis, iaculis laoreet ligula rhoncus. Aliquam erat volutpat. Curabitur hendrerit nibh in orci volutpat egestas. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In volutpat semper mattis. Sed euismod quam id mi consequat, nec consectetur turpis imperdiet. Nunc tristique ultricies enim, vel venenatis quam porta quis. Sed ligula tortor, fringilla ac ultrices vel, vulputate eu nunc. Duis laoreet suscipit turpis ac tempus. Pellentesque nunc nisi, interdum sed bibendum ac, rutrum eu magna. Praesent ac lacinia purus. Phasellus facilisis consequat finibus. Etiam semper dolor nec neque egestas, sed tincidunt odio interdum. Etiam ut ipsum pellentesque, rutrum urna non, pharetra mi. Sed in diam non mauris sodales iaculis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi quis aliquam arcu, eget euismod arcu. Aenean et efficitur nisi. Morbi eu magna ut ligula tempus maximus eu quis nulla.
KlishGroup/prose-pogs
pogs/N/NCLHXHX/LPEP/index.md
Markdown
mit
2,566
97.692308
865
0.81099
false
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.05.03 at 03:15:27 PM EDT // package API.amazon.mws.xml.JAXB; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="value"> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;>String200Type"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="delete" type="{}BooleanType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "cdrh_classification") public class CdrhClassification { @XmlElement(required = true) protected CdrhClassification.Value value; @XmlAttribute(name = "delete") protected BooleanType delete; /** * Gets the value of the value property. * * @return * possible object is * {@link CdrhClassification.Value } * */ public CdrhClassification.Value getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link CdrhClassification.Value } * */ public void setValue(CdrhClassification.Value value) { this.value = value; } /** * Gets the value of the delete property. * * @return * possible object is * {@link BooleanType } * */ public BooleanType getDelete() { return delete; } /** * Sets the value of the delete property. * * @param value * allowed object is * {@link BooleanType } * */ public void setDelete(BooleanType value) { this.delete = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;>String200Type"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) public static class Value { @XmlValue protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } } }
VDuda/SyncRunner-Pub
src/API/amazon/mws/xml/JAXB/CdrhClassification.java
Java
mit
3,909
23.584906
111
0.56485
false
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> namespace Marius.Html.Hap { /// <summary> /// Represents a base class for fragments in a mixed code document. /// </summary> public abstract class MixedCodeDocumentFragment { #region Fields internal MixedCodeDocument Doc; private string _fragmentText; internal int Index; internal int Length; private int _line; internal int _lineposition; internal MixedCodeDocumentFragmentType _type; #endregion #region Constructors internal MixedCodeDocumentFragment(MixedCodeDocument doc, MixedCodeDocumentFragmentType type) { Doc = doc; _type = type; switch (type) { case MixedCodeDocumentFragmentType.Text: Doc._textfragments.Append(this); break; case MixedCodeDocumentFragmentType.Code: Doc._codefragments.Append(this); break; } Doc._fragments.Append(this); } #endregion #region Properties /// <summary> /// Gets the fragement text. /// </summary> public string FragmentText { get { if (_fragmentText == null) { _fragmentText = Doc._text.Substring(Index, Length); } return FragmentText; } internal set { _fragmentText = value; } } /// <summary> /// Gets the type of fragment. /// </summary> public MixedCodeDocumentFragmentType FragmentType { get { return _type; } } /// <summary> /// Gets the line number of the fragment. /// </summary> public int Line { get { return _line; } internal set { _line = value; } } /// <summary> /// Gets the line position (column) of the fragment. /// </summary> public int LinePosition { get { return _lineposition; } } /// <summary> /// Gets the fragment position in the document's stream. /// </summary> public int StreamPosition { get { return Index; } } #endregion } }
marius-klimantavicius/marius-html
Marius.Html/Hap/MixedCodeDocumentFragment.cs
C#
mit
2,555
24.915789
101
0.485714
false
import React from 'react' import { User } from '../../lib/accounts/users' import styled from '../../lib/styled' import MdiIcon from '@mdi/react' import { mdiAccount } from '@mdi/js' import { SectionPrimaryButton } from './styled' import { useTranslation } from 'react-i18next' interface UserProps { user: User signout: (user: User) => void } const Container = styled.div` margin-bottom: 8px; ` export default ({ user, signout }: UserProps) => { const { t } = useTranslation() return ( <Container> <MdiIcon path={mdiAccount} size='80px' /> <p>{user.name}</p> <SectionPrimaryButton onClick={() => signout(user)}> {t('general.signOut')} </SectionPrimaryButton> </Container> ) }
Sarah-Seo/Inpad
src/components/PreferencesModal/UserInfo.tsx
TypeScript
mit
731
23.366667
58
0.641587
false
#include "TextItem.h" #include <QPainter> #include <QFont> #include <QDebug> //////////////////////////////////////////////////////////////// TextItem::TextItem(const QString& text, QGraphicsLayoutItem *parent) : BaseItem(parent) { _text = text; QFont font; font.setPointSize(11); font.setBold(false); setFont(font); } //////////////////////////////////////////////////////////////// TextItem::~TextItem() { } //////////////////////////////////////////////////////////////// void TextItem::setFont(const QFont &font) { _font = font; QFontMetrics fm(_font); } //////////////////////////////////////////////////////////////// QSizeF TextItem::measureSize() const { QFontMetrics fm(_font); const QSizeF& size = fm.size(Qt::TextExpandTabs, _text); // NOTE: flag Qt::TextSingleLine ignores newline characters. return size; } //////////////////////////////////////////////////////////////// void TextItem::draw(QPainter *painter, const QRectF& bounds) { painter->setFont(_font); // TODO: mozno bude treba specialne handlovat novy riadok painter->drawText(bounds, _text); }
AdUki/GraphicEditor
GraphicEditor/Ui/Items/TextItem.cpp
C++
mit
1,137
22.204082
68
0.48197
false
/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #ifndef _Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_ #define _Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_ #include "../../StroikaPreComp.h" #include "../../Configuration/Common.h" #include "../../Configuration/Concepts.h" #include "../../Debug/AssertExternallySynchronizedMutex.h" #include "../Common.h" /** * \file * * Description: * This module genericly wraps STL containers (such as map, vector etc), and facilitates * using them as backends for Stroika containers. * * TODO: * * @todo Replace Contains() with Lookup () - as we did for LinkedList<T> * * @todo Redo Contains1 versus Contains using partial template specialization of STLContainerWrapper - easy * cuz such a trivial class. I can use THAT trick to handle the case of forward_list too. And size... * * @todo Add special subclass of ForwardIterator that tracks PREVPTR - and use to cleanup stuff * that uses forward_list code... * */ namespace Stroika::Foundation::Containers::DataStructures { namespace Private_ { template <typename T> using has_erase_t = decltype (declval<T&> ().erase (begin (declval<T&> ()), end (declval<T&> ()))); template <typename T> constexpr inline bool has_erase_v = Configuration::is_detected_v<has_erase_t, T>; } /** * Use this to wrap an underlying stl container (like std::vector or stl:list, etc) to adapt * it for Stroika containers. * * \note \em Thread-Safety <a href="Thread-Safety.md#C++-Standard-Thread-Safety">C++-Standard-Thread-Safety</a> * */ template <typename STL_CONTAINER_OF_T> class STLContainerWrapper : public STL_CONTAINER_OF_T, public Debug::AssertExternallySynchronizedMutex { private: using inherited = STL_CONTAINER_OF_T; public: using value_type = typename STL_CONTAINER_OF_T::value_type; using iterator = typename STL_CONTAINER_OF_T::iterator; using const_iterator = typename STL_CONTAINER_OF_T::const_iterator; public: /** * Basic (mostly internal) element used by ForwardIterator. Abstract name so can be referenced generically across 'DataStructure' objects */ using UnderlyingIteratorRep = const_iterator; public: /** * pass through CTOR args to underlying container */ template <typename... EXTRA_ARGS> STLContainerWrapper (EXTRA_ARGS&&... args); public: class ForwardIterator; public: /* * Take iteartor 'pi' which is originally a valid iterator from 'movedFrom' - and replace *pi with a valid * iterator from 'this' - which points at the same logical position. This requires that this container * was just 'copied' from 'movedFrom' - and is used to produce an eqivilennt iterator (since iterators are tied to * the container they were iterating over). */ nonvirtual void MoveIteratorHereAfterClone (ForwardIterator* pi, const STLContainerWrapper* movedFrom) const; public: nonvirtual bool Contains (ArgByValueType<value_type> item) const; public: /** * \note Complexity: * Always: O(N) */ template <typename FUNCTION> nonvirtual void Apply (FUNCTION doToElement) const; public: /** * \note Complexity: * Worst Case: O(N) * Typical: O(N), but can be less if systematically finding entries near start of container */ template <typename FUNCTION> nonvirtual iterator Find (FUNCTION doToElement); template <typename FUNCTION> nonvirtual const_iterator Find (FUNCTION doToElement) const; public: template <typename PREDICATE> nonvirtual bool FindIf (PREDICATE pred) const; public: nonvirtual void Invariant () const noexcept; public: nonvirtual iterator remove_constness (const_iterator it); }; /** * STLContainerWrapper::ForwardIterator is a private utility class designed * to promote source code sharing among the patched iterator implementations. * * \note ForwardIterator takes a const-pointer the the container as argument since this * iterator never MODIFIES the container. * * However, it does a const-cast to maintain a non-const pointer since that is needed to * option a non-const iterator pointer, which is needed by some classes that use this, and * there is no zero (or even low for forward_list) cost way to map from const to non const * iterators (needed to perform the update). * * @see https://stroika.atlassian.net/browse/STK-538 */ template <typename STL_CONTAINER_OF_T> class STLContainerWrapper<STL_CONTAINER_OF_T>::ForwardIterator { public: /** */ explicit ForwardIterator (const STLContainerWrapper* data); explicit ForwardIterator (const STLContainerWrapper* data, UnderlyingIteratorRep startAt); explicit ForwardIterator (const ForwardIterator& from) = default; public: nonvirtual bool Done () const noexcept; public: nonvirtual ForwardIterator& operator++ () noexcept; public: nonvirtual value_type Current () const; public: /** * Only legal to call if underlying iterator is random_access */ nonvirtual size_t CurrentIndex () const; public: nonvirtual UnderlyingIteratorRep GetUnderlyingIteratorRep () const; public: nonvirtual void SetUnderlyingIteratorRep (UnderlyingIteratorRep l); public: nonvirtual bool Equals (const ForwardIterator& rhs) const; public: nonvirtual const STLContainerWrapper* GetReferredToData () const; private: const STLContainerWrapper* fData_; const_iterator fStdIterator_; private: friend class STLContainerWrapper; }; } /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "STLContainerWrapper.inl" #endif /*_Stroika_Foundation_Containers_DataStructures_STLContainerWrapper_h_ */
SophistSolutions/Stroika
Library/Sources/Stroika/Foundation/Containers/DataStructures/STLContainerWrapper.h
C
mit
6,578
34.556757
146
0.630587
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>LCOV - coverage.infosrc/core</title> <link rel="stylesheet" type="text/css" href="../../gcov.css"> </head> <body> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="title">LCOV - code coverage report</td></tr> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> <tr> <td width="100%"> <table cellpadding=1 border=0 width="100%"> <tr> <td width="10%" class="headerItem">Current view:</td> <td width="35%" class="headerValue"><a href="../../index.html">top level</a> - src/core</td> <td width="5%"></td> <td width="15%"></td> <td width="10%" class="headerCovTableHead">Hit</td> <td width="10%" class="headerCovTableHead">Total</td> <td width="15%" class="headerCovTableHead">Coverage</td> </tr> <tr> <td class="headerItem">Test:</td> <td class="headerValue">coverage.info</td> <td></td> <td class="headerItem">Lines:</td> <td class="headerCovTableEntry">193</td> <td class="headerCovTableEntry">220</td> <td class="headerCovTableEntryMed">87.7 %</td> </tr> <tr> <td class="headerItem">Date:</td> <td class="headerValue">2013-01-10</td> <td></td> <td class="headerItem">Functions:</td> <td class="headerCovTableEntry">23</td> <td class="headerCovTableEntry">26</td> <td class="headerCovTableEntryMed">88.5 %</td> </tr> <tr> <td></td> <td></td> <td></td> <td class="headerItem">Branches:</td> <td class="headerCovTableEntry">20</td> <td class="headerCovTableEntry">24</td> <td class="headerCovTableEntryMed">83.3 %</td> </tr> <tr><td><img src="../../glass.png" width=3 height=3 alt=""></td></tr> </table> </td> </tr> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> </table> <center> <table width="80%" cellpadding=1 cellspacing=1 border=0> <tr> <td width="44%"><br></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> <td width="8%"></td> </tr> <tr> <td class="tableHead">Filename <span class="tableHeadSort"><img src="../../glass.png" width=10 height=14 alt="Sort by name" title="Sort by name" border=0></span></td> <td class="tableHead" colspan=3>Line Coverage <span class="tableHeadSort"><a href="index-sort-l.html"><img src="../../updown.png" width=10 height=14 alt="Sort by line coverage" title="Sort by line coverage" border=0></a></span></td> <td class="tableHead" colspan=2>Functions <span class="tableHeadSort"><a href="index-sort-f.html"><img src="../../updown.png" width=10 height=14 alt="Sort by function coverage" title="Sort by function coverage" border=0></a></span></td> <td class="tableHead" colspan=2>Branches <span class="tableHeadSort"><a href="index-sort-b.html"><img src="../../updown.png" width=10 height=14 alt="Sort by branch coverage" title="Sort by branch coverage" border=0></a></span></td> </tr> <tr> <td class="coverFile"><a href="dvm.c.gcov.html">dvm.c</a></td> <td class="coverBar" align="center"> <table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../emerald.png" width=91 height=10 alt="91.4%"><img src="../../snow.png" width=9 height=10 alt="91.4%"></td></tr></table> </td> <td class="coverPerHi">91.4&nbsp;%</td> <td class="coverNumHi">128 / 140</td> <td class="coverPerHi">92.3&nbsp;%</td> <td class="coverNumHi">12 / 13</td> <td class="coverPerMed">88.9&nbsp;%</td> <td class="coverNumMed">16 / 18</td> </tr> <tr> <td class="coverFile"><a href="vmbase.c.gcov.html">vmbase.c</a></td> <td class="coverBar" align="center"> <table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="../../amber.png" width=81 height=10 alt="81.2%"><img src="../../snow.png" width=19 height=10 alt="81.2%"></td></tr></table> </td> <td class="coverPerMed">81.2&nbsp;%</td> <td class="coverNumMed">65 / 80</td> <td class="coverPerMed">84.6&nbsp;%</td> <td class="coverNumMed">11 / 13</td> <td class="coverPerLo">66.7&nbsp;%</td> <td class="coverNumLo">4 / 6</td> </tr> </table> </center> <br> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> <tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php">LCOV version 1.9</a></td></tr> </table> <br> </body> </html>
rumblesan/diddy-vm
cdiddy/coverage/src/core/index.html
HTML
mit
5,152
42.294118
242
0.562694
false
import {writeFile} from 'fs-promise'; import {get, has, merge, set} from 'lodash/fp'; import flatten from 'flat'; import fs from 'fs'; import path from 'path'; const data = new WeakMap(); const initial = new WeakMap(); export default class Config { constructor(d) { data.set(this, d); initial.set(this, Object.assign({}, d)); } clone() { return Object.assign({}, data.get(this)); } get(keypath) { return get(keypath, data.get(this)); } has(keypath) { return has(keypath, data.get(this)); } inspect() { return data.get(this); } merge(extra) { data.set(this, merge(data.get(this), extra)); } set(keypath, value) { return set(keypath, data.get(this), value); } async save() { const out = this.toString(); return await writeFile(`.boilerizerc`, out); } toJSON() { const keys = Object.keys(flatten(data.get(this), {safe: true})); const init = initial.get(this); let target; try { const filepath = path.join(process.cwd(), `.boilerizerc`); // Using sync here because toJSON can't have async functions in it // eslint-disable-next-line no-sync const raw = fs.readFileSync(filepath, `utf8`); target = JSON.parse(raw); } catch (e) { if (e.code !== `ENOENT`) { console.error(e); throw e; } target = {}; } return keys.reduce((acc, key) => { if (!has(key, init) || has(key, target)) { const val = this.get(key); acc = set(key, val, acc); } return acc; }, target); } toString() { return JSON.stringify(this, null, 2); } }
ianwremmel/boilerize
src/lib/config.js
JavaScript
mit
1,639
20.565789
72
0.577181
false
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.dfa.report; public class ClassNode extends AbstractReportNode { private String className; public ClassNode(String className) { this.className = className; } public String getClassName() { return className; } public boolean equalsNode(AbstractReportNode arg0) { if (!(arg0 instanceof ClassNode)) { return false; } return ((ClassNode) arg0).getClassName().equals(className); } }
byronka/xenos
utils/pmd-bin-5.2.2/src/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ClassNode.java
Java
mit
585
21.5
79
0.654701
false
<?php namespace Helpers; /** *This class handles rendering of view files * *@author Geoffrey Oliver <geoffrey.oliver2@gmail.com> *@copyright Copyright (c) 2015 - 2020 Geoffrey Oliver *@link http://libraries.gliver.io *@category Core *@package Core\Helpers\View */ use Drivers\Templates\Implementation; use Exceptions\BaseException; use Drivers\Cache\CacheBase; use Drivers\Registry; class View { /** *This is the constructor class. We make this private to avoid creating instances of *this object * *@param null *@return void */ private function __construct() {} /** *This method stops creation of a copy of this object by making it private * *@param null *@return void * */ private function __clone(){} /** *This method parses the input variables and loads the specified views * *@param string $filePath the string that specifies the view file to load *@param array $data an array with variables to be passed to the view file *@return void This method does not return anything, it directly loads the view file *@throws */ public static function render($filePath, array $data = null) { //this try block is excecuted to enable throwing and catching of errors as appropriate try { //get the variables passed and make them available to the view if ( $data != null) { //loop through the array setting the respective variables foreach ($data as $key => $value) { $$key = $value; } } //get the parsed contents of the template file $contents = self::getContents($filePath); //start the output buffer ob_start(); //evaluate the contents of this view file eval("?>" . $contents . "<?"); //get the evaluated contents $contents = ob_get_contents(); //clean the output buffer ob_end_clean(); //return the evaluated contents echo $contents; //stop further script execution exit(); } catch(BaseException $e) { //echo $e->getMessage(); $e->show(); } catch(Exception $e) { echo $e->getMessage(); } } /** *This method converts the code into valid php code * *@param string $file The name of the view whose contant is to be parsed *@return string $parsedContent The parsed content of the template file */ public static function getContents($filePath) { //compose the file full path $path = Path::view($filePath); //get an instance of the view template class $template = Registry::get('template'); //get the compiled file contents $contents = $template->compiled($path); //return the compiled template file contents return $contents; } }
ggiddy/documentation
system/Helpers/View.php
PHP
mit
3,113
24.112903
94
0.573081
false
package pl.mmorpg.prototype.server.objects.monsters.properties.builders; import pl.mmorpg.prototype.clientservercommon.packets.monsters.properties.MonsterProperties; public class SnakePropertiesBuilder extends MonsterProperties.Builder { @Override public MonsterProperties build() { experienceGain(100) .hp(100) .strength(5) .level(1); return super.build(); } }
Pankiev/MMORPG_Prototype
Server/core/src/pl/mmorpg/prototype/server/objects/monsters/properties/builders/SnakePropertiesBuilder.java
Java
mit
384
23
92
0.778646
false
using Microsoft.DataTransfer.AzureTable.Source; using System; using System.Globalization; namespace Microsoft.DataTransfer.AzureTable { /// <summary> /// Contains dynamic resources for data adapters configuration. /// </summary> public static class DynamicConfigurationResources { /// <summary> /// Gets the description for source internal fields configuration property. /// </summary> public static string Source_InternalFields { get { return Format(ConfigurationResources.Source_InternalFieldsFormat, Defaults.Current.SourceInternalFields, String.Join(", ", Enum.GetNames(typeof(AzureTableInternalFields)))); } } private static string Format(string format, params object[] args) { return String.Format(CultureInfo.InvariantCulture, format, args); } } }
innovimax/azure-documentdb-datamigrationtool
AzureTable/Microsoft.DataTransfer.AzureTable/DynamicConfigurationResources.cs
C#
mit
948
31.62069
120
0.635307
false
// Karma configuration // Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'], plugins: [ 'karma-mocha', 'karma-chai', 'karma-sinon-chai', 'karma-chrome-launcher', 'karma-phantomjs-launcher', 'karma-jquery', 'karma-chai-jquery', 'karma-mocha-reporter' ], // list of files / patterns to load in the browser files: [ 'bower/angular/angular.js', 'bower/angular-sanitize/angular-sanitize.js', 'bower/angular-mocks/angular-mocks.js', 'dist/ac-components.min.js', 'test/unit/**/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
avalanche-canada/ac-components
karma-dist-minified.conf.js
JavaScript
mit
2,019
24.556962
120
0.641902
false
#! python3 """ GUI for Ultrasonic Temperature Controller Copyright (c) 2015 by Stefan Lehmann """ import os import datetime import logging import json import serial from qtpy.QtWidgets import QAction, QDialog, QMainWindow, QMessageBox, \ QDockWidget, QLabel, QFileDialog, QApplication from qtpy.QtGui import QIcon from qtpy.QtCore import QSettings, QCoreApplication, Qt, QThread, \ Signal from serial.serialutil import SerialException from jsonwatch.jsonitem import JsonItem from jsonwatch.jsonnode import JsonNode from jsonwatchqt.logger import LoggingWidget from pyqtconfig.config import QSettingsManager from jsonwatchqt.plotsettings import PlotSettingsWidget from jsonwatchqt.objectexplorer import ObjectExplorer from jsonwatchqt.plotwidget import PlotWidget from jsonwatchqt.serialdialog import SerialDialog, PORT_SETTING, \ BAUDRATE_SETTING from jsonwatchqt.utilities import critical, pixmap from jsonwatchqt.recorder import RecordWidget from jsonwatchqt.csvsettings import CSVSettingsDialog, DECIMAL_SETTING, \ SEPARATOR_SETTING logger = logging.getLogger("jsonwatchqt.mainwindow") WINDOWSTATE_SETTING = "mainwindow/windowstate" GEOMETRY_SETTING = "mainwindow/geometry" FILENAME_SETTING = "mainwindow/filename" def strip(s): return s.strip() def utf8_to_bytearray(x): return bytearray(x, 'utf-8') def bytearray_to_utf8(x): return x.decode('utf-8') def set_default_settings(settings: QSettingsManager): settings.set_defaults({ DECIMAL_SETTING: ',', SEPARATOR_SETTING: ';' }) class SerialWorker(QThread): data_received = Signal(datetime.datetime, str) def __init__(self, ser: serial.Serial, parent=None): super().__init__(parent) self.serial = ser self._quit = False def run(self): while not self._quit: try: if self.serial.isOpen() and self.serial.inWaiting(): self.data_received.emit( datetime.datetime.now(), strip(bytearray_to_utf8(self.serial.readline())) ) except SerialException: pass def quit(self): self._quit = True class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.recording_enabled = False self.serial = serial.Serial() self.rootnode = JsonNode('') self._connected = False self._dirty = False self._filename = None # settings self.settings = QSettingsManager() set_default_settings(self.settings) # Controller Settings self.settingsDialog = None # object explorer self.objectexplorer = ObjectExplorer(self.rootnode, self) self.objectexplorer.nodevalue_changed.connect(self.send_serialdata) self.objectexplorer.nodeproperty_changed.connect(self.set_dirty) self.objectexplorerDockWidget = QDockWidget(self.tr("object explorer"), self) self.objectexplorerDockWidget.setObjectName( "objectexplorer_dockwidget") self.objectexplorerDockWidget.setWidget(self.objectexplorer) # plot widget self.plot = PlotWidget(self.rootnode, self.settings, self) # plot settings self.plotsettings = PlotSettingsWidget(self.settings, self.plot, self) self.plotsettingsDockWidget = QDockWidget(self.tr("plot settings"), self) self.plotsettingsDockWidget.setObjectName("plotsettings_dockwidget") self.plotsettingsDockWidget.setWidget(self.plotsettings) # log widget self.loggingWidget = LoggingWidget(self) self.loggingDockWidget = QDockWidget(self.tr("logger"), self) self.loggingDockWidget.setObjectName("logging_dockwidget") self.loggingDockWidget.setWidget(self.loggingWidget) # record widget self.recordWidget = RecordWidget(self.rootnode, self) self.recordDockWidget = QDockWidget(self.tr("data recording"), self) self.recordDockWidget.setObjectName("record_dockwidget") self.recordDockWidget.setWidget(self.recordWidget) # actions and menus self._init_actions() self._init_menus() # statusbar statusbar = self.statusBar() statusbar.setVisible(True) self.connectionstateLabel = QLabel(self.tr("Not connected")) statusbar.addPermanentWidget(self.connectionstateLabel) statusbar.showMessage(self.tr("Ready")) # layout self.setCentralWidget(self.plot) self.addDockWidget(Qt.LeftDockWidgetArea, self.objectexplorerDockWidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.plotsettingsDockWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.loggingDockWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.recordDockWidget) self.load_settings() def _init_actions(self): # Serial Dialog self.serialdlgAction = QAction(self.tr("Serial Settings..."), self) self.serialdlgAction.setShortcut("F6") self.serialdlgAction.setIcon(QIcon(pixmap("configure.png"))) self.serialdlgAction.triggered.connect(self.show_serialdlg) # Connect self.connectAction = QAction(self.tr("Connect"), self) self.connectAction.setShortcut("F5") self.connectAction.setIcon(QIcon(pixmap("network-connect-3.png"))) self.connectAction.triggered.connect(self.toggle_connect) # Quit self.quitAction = QAction(self.tr("Quit"), self) self.quitAction.setShortcut("Alt+F4") self.quitAction.setIcon(QIcon(pixmap("window-close-3.png"))) self.quitAction.triggered.connect(self.close) # Save Config as self.saveasAction = QAction(self.tr("Save as..."), self) self.saveasAction.setShortcut("Ctrl+Shift+S") self.saveasAction.setIcon(QIcon(pixmap("document-save-as-5.png"))) self.saveasAction.triggered.connect(self.show_savecfg_dlg) # Save file self.saveAction = QAction(self.tr("Save"), self) self.saveAction.setShortcut("Ctrl+S") self.saveAction.setIcon(QIcon(pixmap("document-save-5.png"))) self.saveAction.triggered.connect(self.save_file) # Load file self.loadAction = QAction(self.tr("Open..."), self) self.loadAction.setShortcut("Ctrl+O") self.loadAction.setIcon(QIcon(pixmap("document-open-7.png"))) self.loadAction.triggered.connect(self.show_opencfg_dlg) # New self.newAction = QAction(self.tr("New"), self) self.newAction.setShortcut("Ctrl+N") self.newAction.setIcon(QIcon(pixmap("document-new-6.png"))) self.newAction.triggered.connect(self.new) # start recording self.startrecordingAction = QAction(self.tr("Start recording"), self) self.startrecordingAction.setShortcut("F9") self.startrecordingAction.setIcon(QIcon(pixmap("media-record-6.png"))) self.startrecordingAction.triggered.connect(self.start_recording) # stop recording self.stoprecordingAction = QAction(self.tr("Stop recording"), self) self.stoprecordingAction.setShortcut("F10") self.stoprecordingAction.setIcon(QIcon(pixmap("media-playback-stop-8.png"))) self.stoprecordingAction.setEnabled(False) self.stoprecordingAction.triggered.connect(self.stop_recording) # clear record self.clearrecordAction = QAction(self.tr("Clear"), self) self.clearrecordAction.setIcon(QIcon(pixmap("editclear.png"))) self.clearrecordAction.triggered.connect(self.clear_record) # export record self.exportcsvAction = QAction(self.tr("Export to csv..."), self) self.exportcsvAction.setIcon(QIcon(pixmap("text_csv.png"))) self.exportcsvAction.triggered.connect(self.export_csv) # show record settings self.recordsettingsAction = QAction(self.tr("Settings..."), self) self.recordsettingsAction.setIcon(QIcon(pixmap("configure.png"))) self.recordsettingsAction.triggered.connect(self.show_recordsettings) # Info self.infoAction = QAction(self.tr("Info"), self) self.infoAction.setShortcut("F1") self.infoAction.triggered.connect(self.show_info) def _init_menus(self): # file menu self.fileMenu = self.menuBar().addMenu(self.tr("File")) self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.loadAction) self.fileMenu.addAction(self.saveAction) self.fileMenu.addAction(self.saveasAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.connectAction) self.fileMenu.addAction(self.serialdlgAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.quitAction) # view menu self.viewMenu = self.menuBar().addMenu(self.tr("View")) self.viewMenu.addAction( self.objectexplorerDockWidget.toggleViewAction()) self.viewMenu.addAction(self.plotsettingsDockWidget.toggleViewAction()) self.viewMenu.addAction(self.loggingDockWidget.toggleViewAction()) self.viewMenu.addAction(self.recordDockWidget.toggleViewAction()) # record menu self.recordMenu = self.menuBar().addMenu(self.tr("Record")) self.recordMenu.addAction(self.startrecordingAction) self.recordMenu.addAction(self.stoprecordingAction) self.recordMenu.addAction(self.exportcsvAction) self.recordMenu.addSeparator() self.recordMenu.addAction(self.clearrecordAction) self.recordMenu.addSeparator() self.recordMenu.addAction(self.recordsettingsAction) # info menu self.menuBar().addAction(self.infoAction) def show_info(self): QMessageBox.about( self, QApplication.applicationName(), "%s %s\n" "Copyright (c) by %s" % ( QCoreApplication.applicationName(), QCoreApplication.applicationVersion(), QCoreApplication.organizationName(), ) ) def load_file(self, filename): old_filename = self.filename if self.filename != filename else None self.filename = filename try: with open(filename, 'rb') as f: try: self.objectexplorer.model().beginResetModel() self.rootnode.load(bytearray_to_utf8(f.read())) self.objectexplorer.model().endResetModel() except ValueError as e: critical(self, "File '%s' is not a valid config file." % filename) logger.error(str(e)) if old_filename is not None: self.load_file(old_filename) else: self.filename = None except FileNotFoundError as e: logger.error(str(e)) self.filename = None self.objectexplorer.refresh() def load_settings(self): settings = QSettings() # window geometry try: self.restoreGeometry(settings.value(GEOMETRY_SETTING)) except: logger.debug("error restoring window geometry") # window state try: self.restoreState(settings.value(WINDOWSTATE_SETTING)) except: logger.debug("error restoring window state") # filename self.filename = settings.value(FILENAME_SETTING) if self.filename is not None: self.load_file(self.filename) def save_settings(self): settings = QSettings() settings.setValue(WINDOWSTATE_SETTING, self.saveState()) settings.setValue(GEOMETRY_SETTING, self.saveGeometry()) settings.setValue(FILENAME_SETTING, self.filename) def closeEvent(self, event): if self.dirty: res = QMessageBox.question( self, QCoreApplication.applicationName(), self.tr("Save changes to file '%s'?" % self.filename if self.filename is not None else "unknown"), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel ) if res == QMessageBox.Cancel: event.ignore() return elif res == QMessageBox.Yes: self.save_file() self.save_settings() try: self.worker.quit() except AttributeError: pass try: self.serial.close() except (SerialException, AttributeError): pass def new(self): self.objectexplorer.model().beginResetModel() self.rootnode.clear() self.objectexplorer.model().endResetModel() def send_reset(self): jsonstring = json.dumps({"resetpid": 1}) self.serial.write(bytearray(jsonstring, 'utf-8')) def receive_serialdata(self, time, data): self.loggingWidget.log_input(data) try: self.rootnode.from_json(data) except ValueError as e: logger.error(str(e)) # refresh widgets self.objectexplorer.refresh() self.plot.refresh(time) if self.recording_enabled: self.recordWidget.add_data(time, self.rootnode) def send_serialdata(self, node): if isinstance(node, JsonItem): if self.serial.isOpen(): s = node.to_json() self.serial.write(utf8_to_bytearray(s + '\n')) self.loggingWidget.log_output(s.strip()) def show_serialdlg(self): dlg = SerialDialog(self.settings, self) dlg.exec_() def toggle_connect(self): if self.serial.isOpen(): self.disconnect() else: self.connect() def connect(self): # Load port setting port = self.settings.get(PORT_SETTING) baudrate = self.settings.get(BAUDRATE_SETTING) # If no port has been selected before show serial settings dialog if port is None: if self.show_serialdlg() == QDialog.Rejected: return port = self.settings.get(PORT_SETTING) baudrate = self.settings.get(BAUDRATE_SETTING) # Serial connection try: self.serial.port = port self.serial.baudrate = baudrate self.serial.open() except ValueError: QMessageBox.critical( self, QCoreApplication.applicationName(), self.tr("Serial parameters e.g. baudrate, databits are out " "of range.") ) except SerialException: QMessageBox.critical( self, QCoreApplication.applicationName(), self.tr("The device '%s' can not be found or can not be " "configured." % port) ) else: self.worker = SerialWorker(self.serial, self) self.worker.data_received.connect(self.receive_serialdata) self.worker.start() self.connectAction.setText(self.tr("Disconnect")) self.connectAction.setIcon(QIcon(pixmap("network-disconnect-3.png"))) self.serialdlgAction.setEnabled(False) self.connectionstateLabel.setText( self.tr("Connected to %s") % port) self._connected = True self.objectexplorer.refresh() def disconnect(self): self.worker.quit() self.serial.close() self.connectAction.setText(self.tr("Connect")) self.connectAction.setIcon(QIcon(pixmap("network-connect-3.png"))) self.serialdlgAction.setEnabled(True) self.connectionstateLabel.setText(self.tr("Not connected")) self._connected = False self.objectexplorer.refresh() def show_savecfg_dlg(self): filename, _ = QFileDialog.getSaveFileName( self, self.tr("Save configuration file..."), directory=os.path.expanduser("~"), filter="Json file (*.json)" ) if filename: self.filename = filename self.save_file() def save_file(self): if self.filename is not None: config_string = self.rootnode.dump() with open(self.filename, 'w') as f: f.write(config_string) self.dirty = False else: self.show_savecfg_dlg() def show_opencfg_dlg(self): # show file dialog filename, _ = QFileDialog.getOpenFileName( self, self.tr("Open configuration file..."), directory=os.path.expanduser("~"), filter=self.tr("Json file (*.json);;All files (*.*)") ) # load config file if filename: self.load_file(filename) def refresh_window_title(self): s = "%s %s" % (QCoreApplication.applicationName(), QCoreApplication.applicationVersion()) if self.filename is not None: s += " - " + self.filename if self.dirty: s += "*" self.setWindowTitle(s) def start_recording(self): self.recording_enabled = True self.startrecordingAction.setEnabled(False) self.stoprecordingAction.setEnabled(True) def stop_recording(self): self.recording_enabled = False self.startrecordingAction.setEnabled(True) self.stoprecordingAction.setEnabled(False) def export_csv(self): filename, _ = QFileDialog.getSaveFileName( self, QCoreApplication.applicationName(), filter="CSV files(*.csv);;All files (*.*)" ) if filename == "": return # get current dataframe and export to csv df = self.recordWidget.dataframe decimal = self.settings.get(DECIMAL_SETTING) df = df.applymap(lambda x: str(x).replace(".", decimal)) df.to_csv( filename, index_label="time", sep=self.settings.get(SEPARATOR_SETTING) ) def clear_record(self): self.recordWidget.clear() def show_recordsettings(self): dlg = CSVSettingsDialog(self) dlg.exec_() # filename property @property def filename(self): return self._filename @filename.setter def filename(self, value=""): self._filename = value self.refresh_window_title() # dirty property @property def dirty(self): return self._dirty @dirty.setter def dirty(self, value): self._dirty = value self.refresh_window_title() def set_dirty(self): self.dirty = True # connected property @property def connected(self): return self._connected
MrLeeh/jsonwatchqt
jsonwatchqt/mainwindow.py
Python
mit
19,071
33.611615
84
0.620104
false
This returns the resolution of the cone (rather than the cap)
workergnome/ofdocs_markdown
3d/ofConePrimitive.getResolution.md
Markdown
mit
62
61
61
0.790323
false
using System.Threading; using CodeTiger; using Xunit; namespace UnitTests.CodeTiger { public class LazyTests { public class Create1 { [Fact] public void SetsIsValueCreatedToFalse() { var target = Lazy.Create<object>(); Assert.False(target.IsValueCreated); } [Fact] public void ReturnsDefaultValueOfObject() { var target = Lazy.Create<object>(); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Fact] public void ReturnsDefaultValueOfBoolean() { var target = Lazy.Create<bool>(); Assert.Equal(new bool(), target.Value); } [Fact] public void ReturnsDefaultValueOfDecimal() { var target = Lazy.Create<decimal>(); Assert.Equal(new decimal(), target.Value); } } public class Create1_Boolean { [Theory] [InlineData(false)] [InlineData(true)] public void SetsIsValueCreatedToFalse(bool isThreadSafe) { var target = Lazy.Create<object>(isThreadSafe); Assert.False(target.IsValueCreated); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfObject(bool isThreadSafe) { var target = Lazy.Create<object>(isThreadSafe); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfBoolean(bool isThreadSafe) { var target = Lazy.Create<bool>(isThreadSafe); Assert.Equal(new bool(), target.Value); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfDecimal(bool isThreadSafe) { var target = Lazy.Create<decimal>(isThreadSafe); Assert.Equal(new decimal(), target.Value); } } public class Create1_LazyThreadSafetyMode { [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode) { var target = Lazy.Create<object>(mode); Assert.False(target.IsValueCreated); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfObject(LazyThreadSafetyMode mode) { var target = Lazy.Create<object>(mode); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfBoolean(LazyThreadSafetyMode mode) { var target = Lazy.Create<bool>(mode); Assert.Equal(new bool(), target.Value); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfDecimal(LazyThreadSafetyMode mode) { var target = Lazy.Create<decimal>(mode); Assert.Equal(new decimal(), target.Value); } } public class Create1_FuncOfTaskOfT1 { [Fact] public void SetsIsValueCreatedToFalse() { object expected = new object(); var target = Lazy.Create(() => expected); Assert.False(target.IsValueCreated); } [Fact] public void SetsValueToProvidedObject() { object expected = new object(); var target = Lazy.Create(() => expected); Assert.Same(expected, target.Value); } } public class Create1_FuncOfTaskOfT1_Boolean { [Theory] [InlineData(false)] [InlineData(true)] public void SetsIsValueCreatedToFalse(bool isThreadSafe) { object expected = new object(); var target = Lazy.Create(() => expected, isThreadSafe); Assert.False(target.IsValueCreated); } [Theory] [InlineData(false)] [InlineData(true)] public void SetsValueToProvidedTask(bool isThreadSafe) { object expected = new object(); var target = Lazy.Create(() => expected, isThreadSafe); Assert.Same(expected, target.Value); } } public class Create1_FuncOfTaskOfT1_LazyThreadSafetyMode { [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode) { object expected = new object(); var target = Lazy.Create(() => expected, mode); Assert.False(target.IsValueCreated); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsValueToProvidedTask(LazyThreadSafetyMode mode) { object expected = new object(); var target = Lazy.Create(() => expected, mode); Assert.Same(expected, target.Value); } } } }
csdahlberg/CodeTigerLib
UnitTests/UnitTests.CodeTiger.Core/LazyTests.cs
C#
mit
6,719
30.101852
95
0.54176
false
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt--> <title>Function awe_webview_set_callback_change_target_url</title> <link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/> <link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/> <script type="text/javascript" src="../../scripts/jquery.js">/**/</script> <script type="text/javascript" src="../../prettify/prettify.js">/**/</script> <script type="text/javascript" src="../../scripts/ddox.js">/**/</script> </head> <body onload="prettyPrint(); setupDdox();"> <nav id="main-nav"><!-- using block navigation in layout.dt--> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">components</a> <ul class="tree-view"> <li> <a href="../../components/animation.html" class=" module">animation</a> </li> <li> <a href="../../components/assets.html" class=" module">assets</a> </li> <li> <a href="../../components/camera.html" class=" module">camera</a> </li> <li> <a href="../../components/component.html" class=" module">component</a> </li> <li> <a href="../../components/lights.html" class=" module">lights</a> </li> <li> <a href="../../components/material.html" class=" module">material</a> </li> <li> <a href="../../components/mesh.html" class=" module">mesh</a> </li> <li> <a href="../../components/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">core</a> <ul class="tree-view"> <li> <a href="../../core/dgame.html" class=" module">dgame</a> </li> <li> <a href="../../core/gameobject.html" class=" module">gameobject</a> </li> <li> <a href="../../core/prefabs.html" class=" module">prefabs</a> </li> <li> <a href="../../core/properties.html" class=" module">properties</a> </li> <li> <a href="../../core/reflection.html" class=" module">reflection</a> </li> <li> <a href="../../core/scene.html" class=" module">scene</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">graphics</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">adapters</a> <ul class="tree-view"> <li> <a href="../../graphics/adapters/adapter.html" class=" module">adapter</a> </li> <li> <a href="../../graphics/adapters/linux.html" class=" module">linux</a> </li> <li> <a href="../../graphics/adapters/mac.html" class=" module">mac</a> </li> <li> <a href="../../graphics/adapters/win32.html" class=" module">win32</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">shaders</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">glsl</a> <ul class="tree-view"> <li> <a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a> </li> <li> <a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a> </li> <li> <a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a> </li> <li> <a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a> </li> <li> <a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a> </li> <li> <a href="../../graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a> </li> <li> <a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li> <a href="../../graphics/shaders/glsl.html" class=" module">glsl</a> </li> <li> <a href="../../graphics/shaders/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li> <a href="../../graphics/adapters.html" class=" module">adapters</a> </li> <li> <a href="../../graphics/graphics.html" class=" module">graphics</a> </li> <li> <a href="../../graphics/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li class=" tree-view"> <a href="#" class="package">utility</a> <ul class="tree-view"> <li> <a href="../../utility/awesomium.html" class="selected module">awesomium</a> </li> <li> <a href="../../utility/concurrency.html" class=" module">concurrency</a> </li> <li> <a href="../../utility/config.html" class=" module">config</a> </li> <li> <a href="../../utility/filepath.html" class=" module">filepath</a> </li> <li> <a href="../../utility/input.html" class=" module">input</a> </li> <li> <a href="../../utility/output.html" class=" module">output</a> </li> <li> <a href="../../utility/resources.html" class=" module">resources</a> </li> <li> <a href="../../utility/string.html" class=" module">string</a> </li> <li> <a href="../../utility/tasks.html" class=" module">tasks</a> </li> <li> <a href="../../utility/time.html" class=" module">time</a> </li> </ul> </li> <li> <a href="../../components.html" class=" module">components</a> </li> <li> <a href="../../core.html" class=" module">core</a> </li> <li> <a href="../../graphics.html" class=" module">graphics</a> </li> <li> <a href="../../utility.html" class=" module">utility</a> </li> </ul> <noscript> <p style="color: red">The search functionality needs JavaScript enabled</p> </noscript> <div id="symbolSearchPane" style="display: none"> <p> <input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/> </p> <ul id="symbolSearchResults" style="display: none"></ul> <script type="application/javascript" src="../../symbols.js"></script> <script type="application/javascript"> //<![CDATA[ var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show(); //]]> </script> </div> </nav> <div id="main-contents"> <h1>Function awe_webview_set_callback_change_target_url</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt--> <p> Assign a <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a> function to be notified when the target URL has changed. This is usually the result of hovering over a link on the page. </p> <section> <p> @param <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#webview"><code class="prettyprint lang-d">webview</code></a> The WebView instance. </p> <p> @param <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a> A function pointer to the <a href="../../utility/awesomium/awe_webview_set_callback_change_target_url.html#callback"><code class="prettyprint lang-d">callback</code></a>. </p> </section> <section> <h2>Prototype</h2> <pre class="code prettyprint lang-d prototype"> void awe_webview_set_callback_change_target_url( &nbsp;&nbsp;<a href="../../utility/awesomium/awe_webview.html">awe_webview</a>* webview, &nbsp;&nbsp;extern(C) void function(<a href="../../utility/awesomium/awe_webview.html">awe_webview</a>*, const(<a href="../../utility/awesomium/awe_string.html">awe_string</a>)*) callback ) extern(C);</pre> </section> <section> <h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt--> </section> <section> <h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt--> </section> <section> <h2>License</h2><!-- using block ddox.license in ddox.layout.dt--> </section> </div> </body> </html>
Circular-Studios/Dash-Docs
api/v0.9.0/utility/awesomium/awe_webview_set_callback_change_target_url.html
HTML
mit
8,881
36.476793
330
0.555906
false
all: g++ lpf.cpp -o lpf.o .PHONY: clean clean: rm *.o
jmeline/secret-meme
pe/Makefile
Makefile
mit
58
7.285714
21
0.568966
false
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { sc := bufio.NewScanner(os.Stdin) sc.Split(bufio.ScanWords) n := nextInt(sc) a := nextInt(sc) b := nextInt(sc) answer := 0 for i := 1; i <= n; i++ { sum := 0 for _, s := range fmt.Sprintf("%d", i) { x, _ := strconv.Atoi(string(s)) sum = sum + x } if a <= sum && sum <= b { answer = answer + i } } fmt.Println(answer) } // ---------- func nextString(sc *bufio.Scanner) string { sc.Scan() return sc.Text() } func nextNumber(sc *bufio.Scanner) float64 { sc.Scan() f, err := strconv.ParseFloat(sc.Text(), 32) if err != nil { panic(err) } return f } func nextInt(sc *bufio.Scanner) int { sc.Scan() n, err := strconv.Atoi(sc.Text()) if err != nil { panic(err) } return n } func printArray(xs []int) { fmt.Println(strings.Trim(fmt.Sprint(xs), "[]")) } func debugPrintf(format string, a ...interface{}) { fmt.Fprintf(os.Stderr, format, a...) }
bati11/study-algorithm
at_coder/abc/ABC083B_SomeSums/ABC083B.go
GO
mit
973
14.203125
51
0.580678
false
export default function _isString(obj) { return toString.call(obj) === '[object String]' }
jrpool/js-utility-underscore
src/objects/_isString.js
JavaScript
mit
93
30
49
0.698925
false
# cortex-ls [![NPM version](https://badge.fury.io/js/cortex-ls.svg)](http://badge.fury.io/js/cortex-ls) [![Build Status](https://travis-ci.org/cortexjs/cortex-ls.svg?branch=master)](https://travis-ci.org/cortexjs/cortex-ls) [![Dependency Status](https://gemnasium.com/cortexjs/cortex-ls.svg)](https://gemnasium.com/cortexjs/cortex-ls) <!-- description --> ## Install ```bash $ npm install cortex-ls --save ``` ## Usage ```js var cortex_ls = require('cortex-ls); ``` ## Licence MIT <!-- do not want to make nodeinit to complicated, you can edit this whenever you want. -->
cortexjs/cortex-ls
README.md
Markdown
mit
579
27.95
334
0.689119
false
import Vue from 'vue' import Router from 'vue-router' import index from '../components/index' import project from '../components/project/index' import proAdd from '../components/project/proAdd' import proList from '../components/project/proList' import apiList from '../components/project/apiList' import apiView from '../components/project/apiView' import apiEdit from '../components/project/apiEdit' import apiHistory from '../components/project/apiHistory' import test from '../components/test' import message from '../components/message' import member from '../components/member' import doc from '../components/doc' import set from '../components/set' import userSet from '../components/user/set' import login from '../components/user/login' Vue.use(Router) const router:any = new Router({ mode: 'history', routes: [ { path: '/', name: 'index', component: index }, { path: '/project', name: 'project', component: project, children: [ { path: 'list', name: 'proList', component: proList, meta: { requireLogin: true } }, { path: 'add', name: 'proAdd', component: proAdd, meta: { requireLogin: true } }, { path: ':proId/edit', name: 'proEdit', component: proAdd, meta: { requireLogin: true } }, { path: ':proId/api', name: 'proApiList', component: apiList, children: [ { path: 'add', name: 'apiAdd', component: apiEdit, meta: { requireLogin: true } }, { path: ':apiId/detail', name: 'apiView', component: apiView, meta: { requireLogin: true }, }, { path: ':apiId/edit', name: 'apiEdit', component: apiEdit, meta: { requireLogin: true } }, { path: ':apiId/history', name: 'apiHistory', component: apiHistory, meta: { requireLogin: true } } ] } ] }, { path: '/test', name: 'test', component: test, meta: { requireLogin: true } }, { path: '/message', name: 'message', component: message, meta: { requireLogin: true } }, { path: '/member', name: 'member', component: member, meta: { requireLogin: true } }, { path: '/doc', name: 'doc', component: doc }, { path: '/set', name: 'set', component: set, meta: { requireLogin: true } }, { path: '/user/set', name: 'userSet', component: userSet, meta: { requireLogin: true } }, { path: '/user/login', name: 'login', component: login } ] }) router.beforeEach((to:any, from:any, next:any) => { if (to.matched.some((res:any) => res.meta.requireLogin)) { if (localStorage.getItem('token')) { next() } else { next('/user/login') } } else { next() } }) export default router
studyweb2017/best-api
web/src/service/router.ts
TypeScript
mit
3,538
20.705521
60
0.462408
false
var class_mock = [ [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "MOCK_METHOD0", "class_mock.html#ae710f23cafb1a2f17772e8805d6312d2", null ], [ "MOCK_METHOD1", "class_mock.html#ada59eea6991953353f332e3ea1e74444", null ], [ "MOCK_METHOD1", "class_mock.html#a2db4d82b6f92b4e462929f651ac4c3b1", null ], [ "MOCK_METHOD1", "class_mock.html#ae73b4ee90bf6d84205d2b1c17f0b8433", null ], [ "MOCK_METHOD1", "class_mock.html#a2cece30a3ea92b34f612f8032fe3a0f9", null ], [ "MOCK_METHOD1", "class_mock.html#ac70c052254fa9816bd759c006062dc47", null ], [ "MOCK_METHOD1", "class_mock.html#ae2379efbc030f1adf8b032be3bdf081d", null ], [ "MOCK_METHOD1", "class_mock.html#a3fd62026610c5d3d3aeaaf2ade3e18aa", null ], [ "MOCK_METHOD1", "class_mock.html#a890668928abcd28d4d39df164e7b6dd8", null ], [ "MOCK_METHOD1", "class_mock.html#a50e2bda4375a59bb89fd5652bd33eb0f", null ] ];
bhargavipatel/808X_VO
docs/html/class_mock.js
JavaScript
mit
1,000
65.733333
82
0.73
false
#include "StdAfx.h" #include ".\datawriter.h" using namespace std; DataWriter::DataWriter(const std::string &fileName) { this->fileName = fileName; fileStream = NULL; //Initialize the filestream fileStream = new fstream(fileName.c_str(), ios::out|ios::binary|ios::trunc); } void DataWriter::Write(int data, const size_t size) { if (fileStream) { if (fileStream->is_open()) { int sizeCount = 0; while (data > 0) { fileStream->put(char(data%256)); data /= 256; ++sizeCount; } while (sizeCount < size) //Fill the remaining characters { fileStream->put(char(0)); ++sizeCount; } } } } void DataWriter::Write(const char data) { if (fileStream) { if (fileStream->is_open()) { fileStream->put(data); } } } void DataWriter::Write(const char* data, const size_t size) { if (!data) { std::cout << "Warning: attempted to write null pointer\n"; return; } if (fileStream) { if (fileStream->is_open()) { if (strlen(data) > size) { cout << "Warning: Attempting to write data to area larger than specified size\n"; return; } fileStream->write(data,strlen(data)); if (strlen(data) < size) { for (unsigned int i = 0; i < size - strlen(data); ++i) { fileStream->put(char(0));//The files we're dealing with are little-endian, so fill after the placement of the data } } } } }
AngryLawyer/SiegeUnitConverterCpp
DataWriter.cpp
C++
mit
1,869
21.961538
134
0.462814
false
# Material-UI Versions <p class="description">You can come back to this page and switch the version of the docs you're reading at any time.</p> ## Stable versions The most recent version is recommended in production. {{"demo": "pages/versions/StableVersions.js", "hideHeader": true}} ## Последние версии Here you can find the latest unreleased documentation and code. You can use it to see what changes are coming and provide better feedback to Material-UI contributors. {{"demo": "pages/versions/LatestVersion.js", "hideHeader": true}} ## Versioning strategy We recognize that you need **stability** from the Material-UI library. Stability ensures that reusable components and libraries, tutorials, tools, and learned practices don't become obsolete unexpectedly. Stability is essential for the ecosystem around Material-UI to thrive. This document contains **the practices that we follow** to provide you with a leading-edge UI library, balanced with stability. We strive to ensure that future changes are always introduced in a predictable way. We want everyone who depends on Material-UI to know when and how new features are added, and to be well-prepared when obsolete ones are removed. Material-UI strictly follows [Semantic Versioning 2.0.0](https://semver.org/). Material-UI version numbers have three parts: `major.minor.patch`. The version number is incremented based on the level of change included in the release. - **Major releases** contain significant new features, some but minimal developer assistance is expected during the update. When updating to a new major release, you may need to run update scripts, refactor code, run additional tests, and learn new APIs. - **Minor releases** contain important new features. Minor releases are fully backward-compatible; no developer assistance is expected during update, but you can optionally modify your apps and libraries to begin using new APIs, features, and capabilities that were added in the release. - **Patch releases** are low risk, contain bug fixes and small new features. No developer assistance is expected during update. ## Release frequency We work toward a regular schedule of releases, so that you can plan and coordinate your updates with the continuing evolution of Material-UI. In general, you can expect the following release cycle: - A **major** release every 6 months. - 1-3 **minor** releases for each major release. - A **patch** release every week (anytime for urgent bugfix). ## Release schedule > Disclaimer: The dates are offered as general guidance and may be adjusted by us when necessary to ensure delivery of a high-quality code. | Date | Version | |:------------- |:-------------------------- | | May 2019 | `@material-ui/core` v4.0.0 | | December 2019 | `@material-ui/core` v5.0.0 | You can follow [our milestones](https://github.com/mui-org/material-ui/milestones) for a more detailed overview. ## Support policy We only support the latest version of Material-UI. We don't yet have the resources to offer [LTS](https://en.wikipedia.org/wiki/Long-term_support) releases. ## Deprecation practices Sometimes **"breaking changes"**, such as the removal of support for select APIs and features, are necessary. To make these transitions as easy as possible, we make two commitments to you: - We work hard to minimize the number of breaking changes and to provide migration tools when possible. - We follow the deprecation policy described here, so you have time to update your apps to the latest APIs and best practices. To help ensure that you have sufficient time and a clear path to update, this is our deprecation policy: - We announce deprecated features in the changelog, and when possible, with warnings at runtime. - When we announce a deprecation, we also announce a recommended update path. - We support existing use of a stable API during the deprecation period, so your code will keep working during that period. - We only make peer dependency updates (React) that require changes to your apps in a major release.
allanalexandre/material-ui
docs/src/pages/versions/versions-ru.md
Markdown
mit
4,094
59
356
0.764648
false
namespace mazes.Core.Grids { using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using mazes.Core.Cells; using mazes.Core.Grids.Cartesian; public class WeaveGrid : Grid { private readonly List<UnderCell> _underCells = new List<UnderCell>(); public WeaveGrid(int rows, int cols) : base(rows, cols) { PrepareGrid(); ConfigureCells(); } private void PrepareGrid() { var rows = new List<List<Cell>>(); for (var row = 0; row < Rows; row++) { var newRow = new List<Cell>(); for (var column = 0; column < Columns; column++) { newRow.Add(new OverCell(row, column, this)); } rows.Add(newRow); } _grid = rows; } private void ConfigureCells() { foreach (var cell in Cells.Cast<OverCell>()) { var row = cell.Row; var col = cell.Column; cell.North = (OverCell)this[row - 1, col]; cell.South = (OverCell)this[row + 1, col]; cell.West = (OverCell)this[row, col - 1]; cell.East = (OverCell)this[row, col + 1]; } } public void TunnelUnder(OverCell overCell) { var underCell = new UnderCell(overCell); _underCells.Add(underCell); } public override IEnumerable<Cell> Cells => base.Cells.Union(_underCells); public override Image ToImg(int cellSize = 50, float insetPrc = 0) { return base.ToImg(cellSize, insetPrc == 0 ? 0.1f : insetPrc); } protected override void ToImgWithInset(Graphics g, CartesianCell cell, DrawMode mode, int cellSize, int x, int y, int inset) { if (cell is UnderCell) { var (x1, x2, x3, x4, y1, y2, y3, y4) = CellCoordinatesWithInset(x, y, cellSize, inset); if (cell.VerticalPassage) { g.DrawLine(Pens.Black, x2, y1, x2, y2); g.DrawLine(Pens.Black, x3, y1, x3, y2); g.DrawLine(Pens.Black, x2, y3, x2, y4); g.DrawLine(Pens.Black, x3, y3, x3, y4); } else { g.DrawLine(Pens.Black, x1, y2, x2, y2); g.DrawLine(Pens.Black, x1, y3, x2, y3); g.DrawLine(Pens.Black, x3, y2, x4, y2); g.DrawLine(Pens.Black, x3, y3, x4, y3); } } else { base.ToImgWithInset(g, cell, mode, cellSize, x, y, inset); } } } }
ericrrichards/mazes
mazes/Core/Grids/WeaveGrid.cs
C#
mit
2,678
35.671233
134
0.504858
false
package stream.flarebot.flarebot.mod.modlog; public enum ModAction { BAN(true, ModlogEvent.USER_BANNED), SOFTBAN(true, ModlogEvent.USER_SOFTBANNED), FORCE_BAN(true, ModlogEvent.USER_BANNED), TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED), UNBAN(false, ModlogEvent.USER_UNBANNED), KICK(true, ModlogEvent.USER_KICKED), TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED), MUTE(true, ModlogEvent.USER_MUTED), UNMUTE(false, ModlogEvent.USER_UNMUTED), WARN(true, ModlogEvent.USER_WARNED); private boolean infraction; private ModlogEvent event; ModAction(boolean infraction, ModlogEvent modlogEvent) { this.infraction = infraction; this.event = modlogEvent; } public boolean isInfraction() { return infraction; } @Override public String toString() { return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " "); } public String getLowercaseName() { return toString().toLowerCase(); } public ModlogEvent getEvent() { return event; } }
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/mod/modlog/ModAction.java
Java
mit
1,090
24.348837
89
0.666972
false
<?php /** * @package Update * @category modules * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2013-2014, Nazar Mokrynskyi * @license MIT License, see license.txt */ namespace cs; use h; $Config = Config::instance(); $db = DB::instance(); $Index = Index::instance(); $module_object = $Config->module('Update'); if (!$module_object->version) { $module_object->version = 0; } if (isset($Config->route[0]) && $Config->route[0] == 'process') { $version = (int)$module_object->version; for ($i = 1; file_exists(MFOLDER."/sql/$i.sql") || file_exists(MFOLDER."/php/$i.php"); ++$i) { if ($version < $i) { if (file_exists(MFOLDER."/sql/$i.sql")) { foreach (explode(';', file_get_contents(MFOLDER."/sql/$i.sql")) as $s) { if ($s) { $db->{'0'}()->q($s); } } } if (file_exists(MFOLDER."/php/$i.php")) { include MFOLDER."/php/$i.php"; } $module_object->version = $i; } } $Index->save(true); } $Index->buttons = false; $Index->content( h::{'p.cs-center'}("Current revision: $module_object->version"). h::{'a.cs-button.cs-center'}( 'Update System structure', [ 'href' => 'admin/Update/process' ] ) );
nazar-pc/cherrytea.org-old
components/modules/Update/admin/index.php
PHP
mit
1,229
25.717391
95
0.57201
false
<!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.6.0_18) on Thu Dec 18 17:18:41 PST 2014 --> <title>Uses of Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction (Java Platform SE 7 )</title> <meta name="date" content="2014-12-18"> <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 Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction (Java Platform SE 7 )"; } //--> </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><a href="../../../../../javax/swing/plaf/basic/BasicFileChooserUI.UpdateAction.html" title="class in javax.swing.plaf.basic">Class</a></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-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?javax/swing/plaf/basic/class-use/BasicFileChooserUI.UpdateAction.html" target="_top">Frames</a></li> <li><a href="BasicFileChooserUI.UpdateAction.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"> <h2 title="Uses of Class javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction" class="title">Uses of Class<br>javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction</h2> </div> <div class="classUseContainer">No usage of javax.swing.plaf.basic.BasicFileChooserUI.UpdateAction</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><a href="../../../../../javax/swing/plaf/basic/BasicFileChooserUI.UpdateAction.html" title="class in javax.swing.plaf.basic">Class</a></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-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?javax/swing/plaf/basic/class-use/BasicFileChooserUI.UpdateAction.html" target="_top">Frames</a></li> <li><a href="BasicFileChooserUI.UpdateAction.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><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../../legal/cpyr.html">Copyright</a> &#x00a9; 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
fbiville/annotation-processing-ftw
doc/java/jdk7/javax/swing/plaf/basic/class-use/BasicFileChooserUI.UpdateAction.html
HTML
mit
5,212
43.169492
602
0.643707
false
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us"> <head> <link href="http://gmpg.org/xfn/11" rel="profile"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="/public/font-awesome/css/font-awesome.min.css"> <!-- Enable responsiveness on mobile devices--> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <title> 404: Page not found &middot; Home </title> <!-- CSS --> <link rel="stylesheet" href="/public/css/poole.css"> <link rel="stylesheet" href="/public/css/syntax.css"> <link rel="stylesheet" href="/public/css/hyde.css"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface"> <!-- Icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png"> <link rel="shortcut icon" href="/public/favicon.ico"> <!-- RSS --> <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml"> </head> <body> <div class="sidebar"> <div class="container sidebar-sticky"> <div class="sidebar-about"> <img src="/public/logo.png"> <p class="lead"></p> </div> <ul class="sidebar-nav"> <li class="sidebar-nav-item"> <a href="/"> Home</a> </li> <li class="sidebar-nav-item"> <a href="/about.html">About</a> </li> <li class="sidebar-nav-item"> <a href="/projects.html">Projects</a> </li> <li class="sidebar-nav-item"> <a href="/feedback.html">Feedback</a> </li> </ul> <p>&copy; 2014. All rights reserved.</p> </div> </div> <div class="content container"> <div class="page"> <h1 class="page-title">404: Page not found</h1> <p class="lead">Sorry, we've misplaced that URL or it's pointing to something that doesn't exist. <a href="/">Head back home</a> to try finding it again.</p> </div> </div> </body> </html>
b4z/b4z.github.io
_site/404/index.html
HTML
mit
2,396
21.185185
159
0.524624
false
#pragma once #include "dg/enums.h" #include "json/json.h" namespace eule{ /** * @brief Provide a mapping between input file and named parameters */ struct Parameters { unsigned n; //!< \# of polynomial coefficients in R and Z unsigned Nx; //!< \# of cells in x -direction unsigned Ny; //!< \# of cells in y -direction unsigned Nz; //!< \# of cells in z -direction double dt; //!< timestep unsigned n_out; //!< \# of polynomial coefficients in output file unsigned Nx_out; //!< \# of cells in x-direction in output file unsigned Ny_out; //!< \# of cells in y-direction in output file unsigned Nz_out; //!< \# of cells in z-direction in output file unsigned itstp; //!< \# of steps between outputs unsigned maxout; //!< \# of outputs excluding first double eps_pol; //!< accuracy of polarization double jfactor; //jump factor € [1,0.01] double eps_maxwell; //!< accuracy of induction equation double eps_gamma; //!< accuracy of gamma operator double eps_time;//!< accuracy of implicit timestep double eps_hat;//!< 1 double mu[2]; //!< mu[0] = mu_e, m[1] = mu_i double tau[2]; //!< tau[0] = -1, tau[1] = tau_i double beta; //!< plasma beta double nu_perp; //!< perpendicular diffusion double nu_parallel; //!< parallel diffusion double c; //!< parallel resistivity double amp; //!< blob amplitude double sigma; //!< perpendicular blob width double posX; //!< perpendicular position relative to box width double posY; //!< perpendicular position relative to box height double sigma_z; //!< parallel blob width in units of pi double k_psi; //!< mode number double omega_source; //!< source amplitude double nprofileamp; //!< amplitude of profile double bgprofamp; //!< background profile amplitude double boxscaleRp; //!< box can be larger double boxscaleRm;//!< box can be larger double boxscaleZp;//!< box can be larger double boxscaleZm;//!< box can be larger enum dg::bc bc; //!< global perpendicular boundary condition unsigned pollim; //!< 0= no poloidal limiter, 1 = poloidal limiter unsigned pardiss; //!< 0 = adjoint parallel dissipation, 1 = nonadjoint parallel dissipation unsigned mode; //!< 0 = blob simulations (several rounds fieldaligned), 1 = straight blob simulation( 1 round fieldaligned), 2 = turbulence simulations ( 1 round fieldaligned), unsigned initcond; //!< 0 = zero electric potential, 1 = ExB vorticity equals ion diamagnetic vorticity unsigned curvmode; //!< 0 = low beta, 1 = toroidal field line Parameters( const Json::Value& js) { n = js["n"].asUInt(); Nx = js["Nx"].asUInt(); Ny = js["Ny"].asUInt(); Nz = js["Nz"].asUInt(); dt = js["dt"].asDouble(); n_out = js["n_out"].asUInt(); Nx_out = js["Nx_out"].asUInt(); Ny_out = js["Ny_out"].asUInt(); Nz_out = js["Nz_out"].asUInt(); itstp = js["itstp"].asUInt(); maxout = js["maxout"].asUInt(); eps_pol = js["eps_pol"].asDouble(); jfactor = js["jumpfactor"].asDouble(); eps_maxwell = js["eps_maxwell"].asDouble(); eps_gamma = js["eps_gamma"].asDouble(); eps_time = js["eps_time"].asDouble(); eps_hat = 1.; mu[0] = js["mu"].asDouble(); mu[1] = +1.; tau[0] = -1.; tau[1] = js["tau"].asDouble(); beta = js["beta"].asDouble(); nu_perp = js["nu_perp"].asDouble(); nu_parallel = js["nu_parallel"].asDouble(); c = js["resistivity"].asDouble(); amp = js["amplitude"].asDouble(); sigma = js["sigma"].asDouble(); posX = js["posX"].asDouble(); posY = js["posY"].asDouble(); sigma_z = js["sigma_z"].asDouble(); k_psi = js["k_psi"].asDouble(); omega_source = js["source"].asDouble(); bc = dg::str2bc(js["bc"].asString()); nprofileamp = js["nprofileamp"].asDouble(); bgprofamp = js["bgprofamp"].asDouble(); boxscaleRp = js.get("boxscaleRp",1.05).asDouble(); boxscaleRm = js.get("boxscaleRm",1.05).asDouble(); boxscaleZp = js.get("boxscaleZp",1.05).asDouble(); boxscaleZm = js.get("boxscaleZm",1.05).asDouble(); pollim = js.get( "pollim", 0).asUInt(); pardiss = js.get( "pardiss", 0).asUInt(); mode = js.get( "mode", 0).asUInt(); initcond = js.get( "initial", 0).asUInt(); curvmode = js.get( "curvmode", 0).asUInt(); } /** * @brief Display parameters * * @param os Output stream */ void display( std::ostream& os = std::cout ) const { os << "Physical parameters are: \n" <<" mu_e = "<<mu[0]<<"\n" <<" mu_i = "<<mu[1]<<"\n" <<" beta = "<<beta<<"\n" <<" El.-temperature: = "<<tau[0]<<"\n" <<" Ion-temperature: = "<<tau[1]<<"\n" <<" perp. Viscosity: = "<<nu_perp<<"\n" <<" par. Resistivity: = "<<c<<"\n" <<" par. Viscosity: = "<<nu_parallel<<"\n"; os <<"Blob parameters are: \n" << " amplitude: "<<amp<<"\n" << " width: "<<sigma<<"\n" << " posX: "<<posX<<"\n" << " posY: "<<posY<<"\n" << " sigma_z: "<<sigma_z<<"\n"; os << "Profile parameters are: \n" <<" omega_source: "<<omega_source<<"\n" <<" density profile amplitude: "<<nprofileamp<<"\n" <<" background profile amplitude: "<<bgprofamp<<"\n" <<" boxscale R+: "<<boxscaleRp<<"\n" <<" boxscale R-: "<<boxscaleRm<<"\n" <<" boxscale Z+: "<<boxscaleZp<<"\n" <<" boxscale Z-: "<<boxscaleZm<<"\n"; os << "Algorithmic parameters are: \n" <<" n = "<<n<<"\n" <<" Nx = "<<Nx<<"\n" <<" Ny = "<<Ny<<"\n" <<" Nz = "<<Nz<<"\n" <<" dt = "<<dt<<"\n"; os << " Stopping for Polar CG: "<<eps_pol<<"\n" <<" Jump scale factor: "<<jfactor<<"\n" <<" Stopping for Maxwell CG: "<<eps_maxwell<<"\n" <<" Stopping for Gamma CG: "<<eps_gamma<<"\n" <<" Stopping for Time CG: "<<eps_time<<"\n"; os << "Output parameters are: \n" <<" n_out = "<<n_out<<"\n" <<" Nx_out = "<<Nx_out<<"\n" <<" Ny_out = "<<Ny_out<<"\n" <<" Nz_out = "<<Nz_out<<"\n" <<" Steps between output: "<<itstp<<"\n" <<" Number of outputs: "<<maxout<<"\n"; os << "Boundary condition is: \n" <<" global BC = "<<dg::bc2str(bc)<<"\n" <<" Poloidal limiter = "<<pollim<<"\n" <<" Parallel dissipation = "<<pardiss<<"\n" <<" Computation mode = "<<mode<<"\n" <<" init cond = "<<initcond<<"\n" <<" curvature mode = "<<curvmode<<"\n"; os << std::flush; } }; }//namespace eule
e3reiter/feltor
src/feltor/parameters.h
C
mit
7,654
42.725714
181
0.476477
false
import PartyBot from 'partybot-http-client'; import React, { PropTypes, Component } from 'react'; import cssModules from 'react-css-modules'; import styles from './index.module.scss'; import Heading from 'grommet/components/Heading'; import Box from 'grommet/components/Box'; import Footer from 'grommet/components/Footer'; import Button from 'grommet/components/Button'; import Form from 'grommet/components/Form'; import FormField from 'grommet/components/FormField'; import FormFields from 'grommet/components/FormFields'; import NumberInput from 'grommet/components/NumberInput'; import CloseIcon from 'grommet/components/icons/base/Close'; import Dropzone from 'react-dropzone'; import Layer from 'grommet/components/Layer'; import Header from 'grommet/components/Header'; import Section from 'grommet/components/Section'; import Paragraph from 'grommet/components/Paragraph'; import request from 'superagent'; import Select from 'react-select'; import { CLOUDINARY_UPLOAD_PRESET, CLOUDINARY_NAME, CLOUDINARY_KEY, CLOUDINARY_SECRET, CLOUDINARY_UPLOAD_URL } from '../../constants'; import Immutable from 'immutable'; import _ from 'underscore'; class ManageTablesPage extends Component { constructor(props) { super(props); this.handleMobile = this.handleMobile.bind(this); this.closeSetup = this.closeSetup.bind(this); this.onDrop = this.onDrop.bind(this); this.addVariant = this.addVariant.bind(this); this.submitSave = this.submitSave.bind(this); this.submitDelete = this.submitDelete.bind(this); this.state = { isMobile: false, tableId: props.params.table_id || null, confirm: false, name: '', variants: [], organisationId: '5800471acb97300011c68cf7', venues: [], venueId: '', events: [], eventId: '', selectedEvents: [], tableTypes: [], tableTypeId: undefined, tags: 'table', image: null, prevImage: null, isNewImage: null, prices: [] }; } componentWillMount() { if (this.state.tableId) { this.setState({variants: []}); } } componentDidMount() { if (typeof window !== 'undefined') { window.addEventListener('resize', this.handleMobile); } let options = { organisationId: this.state.organisationId }; this.getVenues(options); // IF TABLE ID EXISTS if(this.props.params.table_id) { let tOptions = { organisationId: this.state.organisationId, productId: this.props.params.table_id } this.getTable(tOptions); } } componentWillUnmount() { if (typeof window !== 'undefined') { window.removeEventListener('resize', this.handleMobile); } } handleMobile() { const isMobile = window.innerWidth <= 768; this.setState({ isMobile, }); }; getVenues = (options) => { PartyBot.venues.getAllInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({venueId: body[0]._id}); let ttOptions = { organisationId: this.state.organisationId, venue_id: this.state.venueId } // this.getEvents(ttOptions); this.getTableTypes(ttOptions); } this.setState({venues: body, events: []}); } }); } getEvents = (options) => { PartyBot.events.getEventsInOrganisation(options, (err, response, body) => { if(!err && response.statusCode == 200) { if(body.length > 0) { this.setState({eventId: body[0]._id}); } body.map((value, index) =>{ this.setState({events: this.state.events.concat({ _event: value._id, name: value.name, selected: false })}); }); } }); } getTableTypes = (options) => { PartyBot.tableTypes.getTableTypesInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({tableTypes: body}); let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: body[0]._id } PartyBot.tableTypes.getTableType(params, (aerr, aresponse, abody) => { let events = abody._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: body[0]._id, events: _.flatten(events) }); }); } } }); } getTable = (options) => { PartyBot.products.getProductsInOrganisation(options, (error, response, body) => { if(response.statusCode == 200) { this.setState({ name: body.name, image: { preview: body.image }, prevImage: { preview: body.image }, variants: body.prices.map((value, index) => { return { _event: value._event, price: value.price } }) }); } }); } onVenueChange = (event) => { let id = event.target.value; this.setState({ venueId: id, events: [], variants: []}); let options = { organisationId: this.state.organisationId, venue_id: id }; this.getTableTypes(options); // this.getEvents(options); } onEventChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: event.target.value, price: item.price}); this.setState( { variants: mutated.toArray() } ); } onPriceChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: item._event, price: event.target.value}); this.setState( { variants: mutated.toArray() } ); } closeSetup(){ this.setState({ confirm: false }); this.context.router.push('/tables'); } addVariant() { // will create then get? var newArray = this.state.variants.slice(); newArray.push({ _event_id: [], description: "", image: null, imageUrl: "" }); this.setState({variants:newArray}) } removeVariant(index, event){ // delete variant ID let variants = Immutable.List(this.state.variants); let mutated = variants.remove(index); // let selectedEvents = Immutable.List(this.state.selectedEvents); // let mutatedEvents = selectedEvents.remove(index); this.setState({ variants: mutated.toJS(), }); } onEventAdd = (index, selectedEvents) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('_event_id', selectedEvents); let newClone = cloned.set(index, anIndex); let selectedEventState = Immutable.List(this.state.selectedEvents); let newSelectedEventState = selectedEventState.set(index, selectedEvents); this.setState({selectedEvents: newSelectedEventState.toJS(), variants: newClone.toJS()}); } setDescrpiption = (index, event) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('description', event.target.value); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS()}); } onDrop = (index, file) => { this.setState({ isBusy: true }); let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file[0]); console.log('dragged'); upload.end((err, response) => { if (err) { } else { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('image', file[0]); anIndex = anIndex.set('imageUrl', response.body.secure_url); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS(), isBusy: false}); } }); } onTypeChange = (event) => { var id = event.target.value; let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: id } PartyBot.tableTypes.getTableType(params, (err, response, body) => { let events = body._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: id, variants: [], events: _.flatten(events) }); }); } setName = (event) => { this.setState({name: event.target.value}); } getTypeOptions = () => { return this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; }); } getTableVariants = () => { return this.state.variants.map((value, index) => { return ( <Box key={index} separator="all"> <FormField label="Event" htmlFor="events" /> <Select name="events" options={this.state.events.filter((x) => { let a = _.contains(_.uniq(_.flatten(this.state.selectedEvents)), x); return !a; })} value={value._event_id} onChange={this.onEventAdd.bind(this, index)} multi={true} /> <FormField label="Description" htmlFor="tableTypedescription"> <input id="tableTypedescription" type="text" onChange={this.setDescrpiption.bind(this, index)} value={value.description}/> </FormField> <FormField label="Image"> {value.image ? <Box size={{ width: 'large' }} align="center" justify="center"> <div> <img src={value.image.preview} width="200" /> </div> <Box size={{ width: 'large' }}> <Button label="Cancel" onClick={this.onRemoveImage.bind(this)} plain={true} icon={<CloseIcon />}/> </Box> </Box> : <Box align="center" justify="center" size={{ width: 'large' }}> <Dropzone multiple={false} ref={(node) => { this.dropzone = node; }} onDrop={this.onDrop.bind(this, index)} accept='image/*'> Drop image here or click to select image to upload. </Dropzone> </Box> } <Button label="Remove" onClick={this.removeVariant.bind(this, index)} primary={true} float="right"/> </FormField> </Box>) }); // return this.state.variants.map( (item, index) => { // return <div key={index}> // <FormField label="Event" htmlFor="tableName"> // <select id="tableVenue" onChange={this.onEventChange.bind(this, item, index)} value={item._event||this.state.events[0]._event}> // { // this.state.events.map( (value, index) => { // return (<option key={index} value={value._event}>{value.name}</option>) // }) // } // </select> // </FormField> // <FormField label="Price(Php)" htmlFor="tablePrice"> // <input type="number" onChange={this.onPriceChange.bind(this, item, index)} value={item.price}/> // </FormField> // <Footer pad={{"vertical": "small"}}> // <Heading align="center"> // <Button className={styles.eventButton} label="Update" primary={true} onClick={() => {}} /> // <Button className={styles.eventButton} label="Remove" onClick={this.removeVariant.bind(this, index)} /> // </Heading> // </Footer> // </div>; // }); } onDrop(file) { this.setState({ image: file[0], isNewImage: true }); } onRemoveImage = () => { this.setState({ image: null, isNewImage: false }); } handleImageUpload(file, callback) { if(this.state.isNewImage) { let options = { url: CLOUDINARY_UPLOAD_URL, formData: { file: file } }; let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file); upload.end((err, response) => { if (err) { console.error(err); } if (response.body.secure_url !== '') { callback(null, response.body.secure_url) } else { callback(err, ''); } }); } else { callback(null, null); } } submitDelete (event) { event.preventDefault(); let delParams = { organisationId: this.state.organisationId, productId: this.state.tableId }; PartyBot.products.deleteProduct(delParams, (error, response, body) => { if(!error && response.statusCode == 200) { this.setState({ confirm: true }); } else { } }); } submitSave() { event.preventDefault(); this.handleImageUpload(this.state.image, (err, imageLink) => { if(err) { console.log(err); } else { let updateParams = { name: this.state.name, organisationId: this.state.organisationId, productId: this.state.tableId, venueId: this.state.venueId, table_type: this.state.tableTypeId, image: imageLink || this.state.prevImage.preview, prices: this.state.variants }; PartyBot.products.update(updateParams, (errors, response, body) => { if(response.statusCode == 200) { this.setState({ confirm: true }); } }); } }); } submitCreate = () => { event.preventDefault(); console.log(this.state); let params = {}; // this.handleImageUpload(this.state.image, (err, imageLink) => { // if(err) { // console.log(err); // } else { // let createParams = { // name: this.state.name, // organisationId: this.state.organisationId, // venueId: this.state.venueId, // tags: this.state.tags, // table_type: this.state.tableTypeId, // image: imageLink, // prices: this.state.variants // }; // PartyBot.products.create(createParams, (errors, response, body) => { // if(response.statusCode == 200) { // this.setState({ // confirm: true // }); // } // }); // } // }); } render() { const { router, } = this.context; const { isMobile, } = this.state; const { files, variants, } = this.state; return ( <div className={styles.container}> <link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css"/> {this.state.confirm !== false ? <Layer align="center"> <Header> Table successfully created. </Header> <Section> <Button label="Close" onClick={this.closeSetup} plain={true} icon={<CloseIcon />}/> </Section> </Layer> : null } <Box> {this.state.tableId !== null ? <Heading align="center"> Edit Table </Heading> : <Heading align="center"> Add Table </Heading> } </Box> <Box size={{ width: 'large' }} direction="row" justify="center" align="center" wrap={true} margin="small"> <Form> <FormFields> <fieldset> <FormField label="Venue" htmlFor="tableVenue"> <select id="tableVenue" onChange={this.onVenueChange} value={this.state.venueId}> {this.state.venues.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label="Table Type" htmlFor="tableType"> <select id="tableType" onChange={this.onTypeChange} value={this.state.tableTypeId}> {this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label=" Name" htmlFor="tableName"> <input id="tableName" type="text" onChange={this.setName} value={this.state.name}/> </FormField> { //Dynamic Price/Event Component this.getTableVariants() } <Button label="Add Event" primary={true} onClick={this.addVariant} /> </fieldset> </FormFields> <Footer pad={{"vertical": "medium"}}> { this.state.tableId !== null ? <Heading align="center"> <Button label="Save Changes" primary={true} onClick={this.submitSave} /> <Button label="Delete" primary={true} onClick={this.submitDelete} /> </Heading> : <Heading align="center"> <Button label="Create Table" primary={true} onClick={this.submitCreate} /> </Heading> } </Footer> </Form> </Box> </div> ); } } ManageTablesPage.contextTypes = { router: PropTypes.object.isRequired, }; export default cssModules(ManageTablesPage, styles);
JaySmartwave/palace-bot-sw
app/src/pages/ManageTablesPage/index.js
JavaScript
mit
17,890
30.496479
148
0.553661
false
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. I2db::Application.config.secret_token = 'f30c2c606ad3fe5dee77ef556c72975365eecdaf0d7487c8944e755182923e1b29d57c90c64b4015705a25c000d989975ff1dd08abb608ebebde302bc4991582'
panjunction/i2db
config/initializers/secret_token.rb
Ruby
mit
495
69.714286
170
0.830303
false
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Interfaces { public static class IApplicationCommandConstants { /// <summary> /// This application name represents default commands - when there is no /// command for specific application /// </summary> public const string DEFAULT_APPLICATION = "DEFAULT"; } /// <summary> /// Represents simple association that connects application, remote command and feedback to this command. /// If ApplicationName is null - this is a default behaviour. /// </summary> public interface IApplicationCommand { /// <summary> /// Name of the application /// </summary> string ApplicationName { get; } /// <summary> /// Remote command /// </summary> RemoteCommand RemoteCommand { get; } /// <summary> /// Command to be executed /// </summary> ICommand Command { get; } /// <summary> /// Executes associated command /// </summary> void Do(); } }
StanislavUshakov/ArduinoWindowsRemoteControl
Core/Interfaces/IApplicationCommand.cs
C#
mit
1,174
25.044444
109
0.593857
false
module HealthSeven::V2_3 class QryQ02 < ::HealthSeven::Message attribute :msh, Msh, position: "MSH", require: true attribute :qrd, Qrd, position: "QRD", require: true attribute :qrf, Qrf, position: "QRF" attribute :dsc, Dsc, position: "DSC" end end
niquola/health_seven
lib/health_seven/2.3/messages/qry_q02.rb
Ruby
mit
256
31.125
53
0.707031
false
<?php namespace seregazhuk\tests\Bot\Providers; use seregazhuk\PinterestBot\Api\Providers\User; use seregazhuk\PinterestBot\Helpers\UrlBuilder; /** * Class ProfileSettingsTest * @method User getProvider() */ class ProfileSettingsTest extends ProviderBaseTest { /** @test */ public function it_retrieves_current_user_sessions_history() { $provider = $this->getProvider(); $provider->sessionsHistory(); $this->assertWasGetRequest(UrlBuilder::RESOURCE_SESSIONS_HISTORY); } /** @test */ public function it_returns_list_of_available_locales() { $provider = $this->getProvider(); $provider->getLocales(); $this->assertWasGetRequest(UrlBuilder::RESOURCE_AVAILABLE_LOCALES); } /** @test */ public function it_returns_list_of_available_countries() { $provider = $this->getProvider(); $provider->getCountries(); $this->assertWasGetRequest(UrlBuilder::RESOURCE_AVAILABLE_COUNTRIES); } /** @test */ public function it_returns_list_of_available_account_types() { $provider = $this->getProvider(); $provider->getAccountTypes(); $this->assertWasGetRequest(UrlBuilder::RESOURCE_AVAILABLE_ACCOUNT_TYPES); } protected function getProviderClass() { return User::class; } }
seregazhuk/php-pinterest-bot
tests/Bot/Providers/ProfileSettingsTest.php
PHP
mit
1,348
23.962963
81
0.653561
false
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.Runtime.Internal.Transform { public static class CustomMarshallTransformations { public static long ConvertDateTimeToEpochMilliseconds(DateTime dateTime) { TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - Amazon.Util.AWSSDKUtils.EPOCH_START.Ticks); return (long)ts.TotalMilliseconds; } } }
Shogan/Unity3D.CharacterCreator
Assets/AWSSDK/src/Core/Amazon.Runtime/Internal/Transform/CustomMarshallTransformations.cs
C#
mit
1,054
31.9375
117
0.713472
false
<wicket:extend> <div class="row"> <div class="col-md-12"> <h3>Ergebnisse</h3> <br/> </div> </div> <div class="row"> <div class="col-md-12 result-border"> <div class="row"> <div class="col-md-12"> <h4> Erkannte Version: <wicket:container wicket:id="schemaVersion"/> </h4> </div> </div> <div wicket:id="schemvalidationOK"> <div class="row"> <div class="col-md-12"> <br/> <h4>Schemavalidierung</h4> </div> </div> <div class="row"> <div class="col-md-12 alert alert-success"> <p>Die gew&auml;hlte ebInterface Instanz entspricht den Vorgaben des ebInterface Schemas.</p> </div> </div> </div> <div wicket:id="schemvalidationNOK"> <div class="row"> <div class="col-md-12"> <br/> <h4>Schemavalidierung</h4> </div> </div> <div class="row"> <div class="col-md-12 alert alert-danger"> <p>Die gew&auml;hlte ebInterface Instanz entspricht nicht den Vorgaben des ebInterface Schemas.</p> <p> <strong>Fehlerdetails: </strong> <wicket:container wicket:id="schemaValidationError"/> </p> </div> </div> </div> <div wicket:id="signatureResultContainer"> <div class="row"> <div class="col-md-12"> <br/> <h4>Validierung der XML Signatur</h4> </div> </div> <div class="row"> <div class="col-md-12"> <h5>Signatur</h5> <div wicket:id="signatureDetails"/> <h5>Zertifikat:</h5> <div wicket:id="certificateDetails"/> <h5>Manifest:</h5> <div wicket:id="manifestDetails"/> </div> </div> </div> <div wicket:id="schematronOK"> <div class="row"> <div class="col-md-12"> <br/> <h4> Schematronvalidierung <wicket:container wicket:id="selectedSchematron"/> </h4> </div> </div> <div class="row"> <div class="col-md-12 alert alert-success"> <p>Die gew&auml;hlte ebInterface Instanz verletzt keine der Schematronregeln</p> </div> </div> </div> <div wicket:id="schematronNOK"> <div class="row"> <div class="col-md-12"> <br/> <h4> Schematronvalidierung <wicket:container wicket:id="selectedSchematron"/> </h4> </div> </div> <div class="row"> <div class="col-md-12 alert alert-danger"> <p>Die gew&auml;hlte ebInterface Instanz verletzt Schematron Regeln:</p> <div wicket:id="errorDetailsPanel"></div> </div> </div> </div> <div wicket:id="zugferdMappingLog"> <div class="row"> <div class="col-md-12"> <br/> <h4> ZUGFeRD-Konvertierung </h4> </div> </div> <div class="row"> <div wicket:id="zugferdMappingLogSuccess"> <div class="col-md-12 alert alert-success"> <div wicket:id="zugferdLogSuccessPanel"></div> </div> </div> <div wicket:id="zugferdMappingLogError"> <div class="col-md-12 alert alert-danger"> <div wicket:id="zugferdLogErrorPanel"></div> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <br/> <br/> <a class="btn btn-ghost btn-ghost--red" type="submit" wicket:id="linkZugferdXMLDownload">Download ZUGFeRD XML</a> <a class="btn btn-ghost btn-ghost--red" type="submit" wicket:id="linkZugferdPDFDownload">Download ZUGFeRD PDF</a> </div> <div class="col-md-12"> <br/> <br/> <a class="btn btn-ghost btn-ghost--red" wicket:id="returnLink">Neue Anfrage starten</a> <br/> <br/> <br/> <br/> </div> </div> </wicket:extend>
austriapro/ebinterface-web
ebinterface-web/src/main/java/at/ebinterface/validation/web/pages/resultpages/ResultPageZugferd.html
HTML
mit
5,589
28.734043
91
0.37216
false
package edu.isep.sixcolors.view.listener; import edu.isep.sixcolors.model.Config; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * A popup window asking if the player want's to exit Six Colors */ public class Exit implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int option = JOptionPane.showConfirmDialog( null, Config.EXIT_MESSAGE, Config.EXIT_TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE ); if (option == JOptionPane.YES_OPTION){ System.exit(0); } } }
ohhopi/six-couleurs
6Colors/src/edu/isep/sixcolors/view/listener/Exit.java
Java
mit
702
24.071429
64
0.623932
false
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using gView.Framework.IO; using gView.Framework.Data; using gView.Framework.UI; namespace gView.Framework.UI.Dialogs { public partial class FormMetadata : Form { private Metadata _metadata; private object _metadataObject; public FormMetadata(XmlStream xmlStream, object metadataObject) { InitializeComponent(); _metadata = new Metadata(); _metadata.ReadMetadata(xmlStream); _metadataObject = metadataObject; } private void FormMetadata_Load(object sender, EventArgs e) { if (_metadata.Providers == null) return; foreach (IMetadataProvider provider in _metadata.Providers) { if (provider == null) continue; TabPage page = new TabPage(provider.Name); if (provider is IPropertyPage) { Control ctrl = ((IPropertyPage)provider).PropertyPage(null) as Control; if (ctrl != null) { page.Controls.Add(ctrl); ctrl.Dock = DockStyle.Fill; } if (ctrl is IMetadataObjectParameter) ((IMetadataObjectParameter)ctrl).MetadataObject = _metadataObject; } tabControl1.TabPages.Add(page); } } public XmlStream Stream { get { XmlStream stream = new XmlStream("Metadata"); if (_metadata != null) _metadata.WriteMetadata(stream); return stream; } } } }
jugstalt/gViewGisOS
gView.Explorer.UI/Framework/UI/Dialogs/FormMetadata.cs
C#
mit
1,880
27.074627
91
0.537234
false
eslint-plugin-extjs ============ [![npm](https://img.shields.io/npm/v/eslint-plugin-extjs.svg)](https://npmjs.org/package/eslint-plugin-extjs) [![Travis](https://img.shields.io/travis/burnnat/eslint-plugin-extjs.svg)](https://travis-ci.org/burnnat/eslint-plugin-extjs) [![Gemnasium](https://img.shields.io/gemnasium/burnnat/eslint-plugin-extjs.svg)](https://gemnasium.com/burnnat/eslint-plugin-extjs) ESLint rules for projects using the ExtJS framework. These rules are targeted for use with ExtJS 4.x. Pull requests for compatibility with 5.x are welcome! ## Rule Details ### ext-array-foreach The two main array iterator functions provided by ExtJS, [`Ext.Array.forEach`][ext-array-foreach] and [`Ext.Array.each`][ext-array-each], differ in that `each` provides extra functionality for early termination and reverse iteration. The `forEach` method, however, will delegate to the browser's native [`Array.forEach`][array-foreach] implementation where available, for performance. So, in situations where the extra features of `each` are not needed, `forEach` should be preferred. As the `forEach` documentation says: > [Ext.Array.forEach] will simply delegate to the native Array.prototype.forEach > method if supported. It doesn't support stopping the iteration by returning > false in the callback function like each. However, performance could be much > better in modern browsers comparing with each. The following patterns are considered warnings: Ext.Array.each( ['a', 'b'], function() { // do something } ); Ext.Array.each( ['a', 'b'], function() { // do something }, this, false ); The following patterns are not considered warnings: Ext.Array.forEach( ['a', 'b'], function() { // do something } ); Ext.Array.each( ['a', 'b'], function(item) { if (item === 'a') { return false; } } ); Ext.Array.each( ['a', 'b'], function() { // do something }, this, true ); ### ext-deps One problem with larger ExtJS projects is keeping the [`uses`][ext-uses] and [`requires`][ext-requires] configs for a class synchronized as its body changes over time and dependencies are added and removed. This rule checks that all external references within a particular class have a corresponding entry in the `uses` or `requires` config, and that there are no extraneous dependencies listed in the class configuration that are not referenced in the class body. The following patterns are considered warnings: Ext.define('App', { requires: ['Ext.panel.Panel'] }); Ext.define('App', { constructor: function() { this.panel = new Ext.panel.Panel(); } }); The following patterns are not considered warnings: Ext.define('App', { requires: ['Ext.panel.Panel'], constructor: function() { this.panel = new Ext.panel.Panel(); } }); Ext.define('App', { extend: 'Ext.panel.Panel' }); ### no-ext-create While using [`Ext.create`][ext-create] for instantiation has some benefits during development, mainly synchronous loading of missing classes, it remains slower than the `new` operator due to its extra overhead. For projects with properly configured [`uses`][ext-uses] and [`requires`][ext-requires] blocks, the extra features of `Ext.create` are not needed, so the `new` keyword should be preferred in cases where the class name is static. This is confirmed by Sencha employees, one of whom has [said][ext-create-forum]: > 'Ext.create' is slower than 'new'. Its chief benefit is for situations where > the class name is a dynamic value and 'new' is not an option. As long as the > 'requires' declarations are correct, the overhead of 'Ext.create' is simply > not needed. The following patterns are considered warnings: var panel = Ext.create('Ext.util.Something', { someConfig: true }); The following patterns are not considered warnings: var panel = new Ext.util.Something({ someConfig: true }); var panel = Ext.create(getDynamicClassName(), { config: true }); ### no-ext-multi-def Best practices for ExtJS 4 [dictate][ext-class-system] that each class definition be placed in its own file, and that the filename should correspond to the class being defined therein. This rule checks that there is no more than one top-level class definition included per file. The following patterns are considered warnings: // all in one file Ext.define('App.First', { // ... }); Ext.define('App.Second', { // ... }); The following patterns are not considered warnings: // file a Ext.define('App', { // class definition }); // file b Ext.define('App', { dynamicDefine: function() { Ext.define('Dynamic' + Ext.id(), { // class definition }); } }); [array-foreach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach [ext-array-foreach]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Array-method-forEach [ext-array-each]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Array-method-each [ext-class-system]: http://docs.sencha.com/extjs/4.2.1/#!/guide/class_system-section-2%29-source-files [ext-create]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext-method-create [ext-create-forum]: http://www.sencha.com/forum/showthread.php?166536-Ext.draw-Ext.create-usage-dropped-why&p=700522&viewfull=1#post700522 [ext-requires]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Class-cfg-requires [ext-uses]: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Class-cfg-uses
burnnat/eslint-plugin-extjs
README.md
Markdown
mit
5,895
32.685714
367
0.660051
false
This is an example from `pst-solides3d` documentation. Compiled example ---------------- ![Example](sphere-cylinder.png)
MartinThoma/LaTeX-examples
pstricks/sphere-cylinder/README.md
Markdown
mit
122
23.4
54
0.680328
false
namespace EgaViewer_v2 { partial class CustomPictureBox { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
ChainedLupine/BSAVEViewer
EgaViewer_v2/CustomPictureBox.Designer.cs
C#
mit
1,033
27.638889
107
0.553831
false
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2019 Marco Antognini (antognini.marco@gmail.com), // Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #import <Cocoa/Cocoa.h> #import <SFML/Graphics.hpp> /* * NB: We need pointers for C++ objects fields in Obj-C interface ! * The recommended way is to use PIMPL idiom. * * It's elegant. Moreover, we do no constrain * other file including this one to be Obj-C++. */ struct SFMLmainWindow; @interface CocoaAppDelegate : NSObject <NSApplicationDelegate> { @private NSWindow* m_window; NSView* m_sfmlView; NSTextField* m_textField; SFMLmainWindow* m_mainWindow; NSTimer* m_renderTimer; BOOL m_visible; BOOL m_initialized; } @property (retain) IBOutlet NSWindow* window; @property (assign) IBOutlet NSView* sfmlView; @property (assign) IBOutlet NSTextField* textField; -(IBAction)colorChanged:(NSPopUpButton*)sender; -(IBAction)rotationChanged:(NSSlider*)sender; -(IBAction)visibleChanged:(NSButton*)sender; -(IBAction)textChanged:(NSTextField*)sender; -(IBAction)updateText:(NSButton*)sender; @end /* * This interface is used to prevent the system alert produced when the SFML view * has the focus and the user press a key. */ @interface SilentWindow : NSWindow -(void)keyDown:(NSEvent*)theEvent; @end
Senryoku/NESen
ext/SFML/examples/cocoa/CocoaAppDelegate.h
C
mit
2,396
32.746479
101
0.671953
false
namespace StudentClass { public class Course { public Course(string name) : this() { this.Name = name; } public Course() { } public string Name { get; private set; } public override string ToString() { return this.Name; } } }
TomaNikolov/TelerikAcademy
OOP/06.CommonTypeSystem/StudentClass/Course.cs
C#
mit
361
14.608696
48
0.442897
false
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "CDStructures.h" @interface IDEEditorDocumentValidatedUserInterfaceItem : NSObject <NSValidatedUserInterfaceItem> { SEL _action; long long _tag; } @property long long tag; // @synthesize tag=_tag; @property SEL action; // @synthesize action=_action; @end
kolinkrewinkel/Multiplex
Multiplex/IDEHeaders/IDEHeaders/IDEKit/IDEEditorDocumentValidatedUserInterfaceItem.h
C
mit
415
19.75
96
0.696386
false
<!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 (1.8.0_112-google-v7) on Thu Mar 02 16:51:04 PST 2017 --> <title>ResourceTableFactory</title> <meta name="date" content="2017-03-02"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ResourceTableFactory"; } } catch(err) { } //--> var methods = {"i0":9,"i1":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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="navBarCell1Rev">Class</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><a href="../../../org/robolectric/res/ResourceTable.Visitor.html" title="interface in org.robolectric.res"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/robolectric/res/ResourceValueConverter.html" title="interface in org.robolectric.res"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/res/ResourceTableFactory.html" target="_top">Frames</a></li> <li><a href="ResourceTableFactory.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.robolectric.res</div> <h2 title="Class ResourceTableFactory" class="title">Class ResourceTableFactory</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.robolectric.res.ResourceTableFactory</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">ResourceTableFactory</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../org/robolectric/res/ResourceTableFactory.html#ResourceTableFactory--">ResourceTableFactory</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>static <a href="../../../org/robolectric/res/PackageResourceTable.html" title="class in org.robolectric.res">PackageResourceTable</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/res/ResourceTableFactory.html#newFrameworkResourceTable-org.robolectric.res.ResourcePath-">newFrameworkResourceTable</a></span>(<a href="../../../org/robolectric/res/ResourcePath.html" title="class in org.robolectric.res">ResourcePath</a>&nbsp;resourcePath)</code> <div class="block">Builds an Android framework resource table in the "android" package space.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static <a href="../../../org/robolectric/res/PackageResourceTable.html" title="class in org.robolectric.res">PackageResourceTable</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/res/ResourceTableFactory.html#newResourceTable-java.lang.String-org.robolectric.res.ResourcePath...-">newResourceTable</a></span>(java.lang.String&nbsp;packageName, <a href="../../../org/robolectric/res/ResourcePath.html" title="class in org.robolectric.res">ResourcePath</a>...&nbsp;resourcePaths)</code> <div class="block">Creates an application resource table which can be constructed with multiple resources paths representing overlayed resource libraries.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ResourceTableFactory--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ResourceTableFactory</h4> <pre>public&nbsp;ResourceTableFactory()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="newFrameworkResourceTable-org.robolectric.res.ResourcePath-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>newFrameworkResourceTable</h4> <pre>public static&nbsp;<a href="../../../org/robolectric/res/PackageResourceTable.html" title="class in org.robolectric.res">PackageResourceTable</a>&nbsp;newFrameworkResourceTable(<a href="../../../org/robolectric/res/ResourcePath.html" title="class in org.robolectric.res">ResourcePath</a>&nbsp;resourcePath)</pre> <div class="block">Builds an Android framework resource table in the "android" package space.</div> </li> </ul> <a name="newResourceTable-java.lang.String-org.robolectric.res.ResourcePath...-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>newResourceTable</h4> <pre>public static&nbsp;<a href="../../../org/robolectric/res/PackageResourceTable.html" title="class in org.robolectric.res">PackageResourceTable</a>&nbsp;newResourceTable(java.lang.String&nbsp;packageName, <a href="../../../org/robolectric/res/ResourcePath.html" title="class in org.robolectric.res">ResourcePath</a>...&nbsp;resourcePaths)</pre> <div class="block">Creates an application resource table which can be constructed with multiple resources paths representing overlayed resource libraries.</div> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <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="navBarCell1Rev">Class</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><a href="../../../org/robolectric/res/ResourceTable.Visitor.html" title="interface in org.robolectric.res"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/robolectric/res/ResourceValueConverter.html" title="interface in org.robolectric.res"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/res/ResourceTableFactory.html" target="_top">Frames</a></li> <li><a href="ResourceTableFactory.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
robolectric/robolectric.github.io
javadoc/3.3/org/robolectric/res/ResourceTableFactory.html
HTML
mit
11,438
38.171233
389
0.66113
false
//Generated by the Argon Build System /*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "opus/silk/float/main_FLP.h" /* Autocorrelations for a warped frequency axis */ void silk_warped_autocorrelation_FLP( silk_float *corr, /* O Result [order + 1] */ const silk_float *input, /* I Input data to correlate */ const silk_float warping, /* I Warping coefficient */ const opus_int length, /* I Length of input */ const opus_int order /* I Correlation order (even) */ ) { opus_int n, i; double tmp1, tmp2; double state[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; double C[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; /* Order must be even */ silk_assert( ( order & 1 ) == 0 ); /* Loop over samples */ for( n = 0; n < length; n++ ) { tmp1 = input[ n ]; /* Loop over allpass sections */ for( i = 0; i < order; i += 2 ) { /* Output of allpass section */ tmp2 = state[ i ] + warping * ( state[ i + 1 ] - tmp1 ); state[ i ] = tmp1; C[ i ] += state[ 0 ] * tmp1; /* Output of allpass section */ tmp1 = state[ i + 1 ] + warping * ( state[ i + 2 ] - tmp2 ); state[ i + 1 ] = tmp2; C[ i + 1 ] += state[ 0 ] * tmp2; } state[ order ] = tmp1; C[ order ] += state[ 0 ] * tmp1; } /* Copy correlations in silk_float output format */ for( i = 0; i < order + 1; i++ ) { corr[ i ] = ( silk_float )C[ i ]; } }
skylersaleh/ArgonEngine
common/opus/silk/float/warped_autocorrelation_FLP.c
C
mit
3,596
46.946667
126
0.564516
false
# encoding: UTF-8 module DocuBot::LinkTree; end class DocuBot::LinkTree::Node attr_accessor :title, :link, :page, :parent def initialize( title=nil, link=nil, page=nil ) @title,@link,@page = title,link,page @children = [] end def anchor @link[/#(.+)/,1] end def file @link.sub(/#.+/,'') end def leaf? !@children.any?{ |node| node.page != @page } end # Add a new link underneath a link to its logical parent def add_to_link_hierarchy( title, link, page=nil ) node = DocuBot::LinkTree::Node.new( title, link, page ) parent_link = if node.anchor node.file elsif File.basename(link)=='index.html' File.dirname(File.dirname(link))/'index.html' else (File.dirname(link) / 'index.html') end #puts "Adding #{title.inspect} (#{link}) to hierarchy under #{parent_link}" parent = descendants.find{ |n| n.link==parent_link } || self parent << node end def <<( node ) node.parent = self @children << node end def []( child_index ) @children[child_index] end def children( parent_link=nil, &block ) if parent_link root = find( parent_link ) root ? root.children( &block ) : [] else @children end end def descendants ( @children + @children.map{ |child| child.descendants } ).flatten end def find( link ) # TODO: this is eminently cachable descendants.find{ |node| node.link==link } end def depth # Cached assuming no one is going to shuffle the nodes after placement @depth ||= ancestors.length end def ancestors # Cached assuming no one is going to shuffle the nodes after placement return @ancestors if @ancestors @ancestors = [] node = self @ancestors << node while node = node.parent @ancestors.reverse! end def to_s "#{@title} (#{@link}) - #{@page && @page.title}" end def to_txt( depth=0 ) indent = " "*depth [ indent+to_s, children.map{|kid|kid.to_txt(depth+1)} ].flatten.join("\n") end end class DocuBot::LinkTree::Root < DocuBot::LinkTree::Node undef_method :title undef_method :link undef_method :page attr_reader :bundle def initialize( bundle ) @bundle = bundle @children = [] end def <<( node ) node.parent = nil @children << node end def to_s "(Table of Contents)" end end
Phrogz/docubot
lib/docubot/link_tree.rb
Ruby
mit
2,249
19.261261
77
0.649622
false
"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBefore(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["always-single-line"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a { background-size: 0 ,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0 ,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\n}", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\r\n}", description: "CRLF", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never-single-line"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a { background-size: 0,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0 ,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0 ,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\n}", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\r\n}", description: "CRLF", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, } ], })
hudochenkov/stylelint
lib/rules/value-list-comma-space-before/__tests__/index.js
JavaScript
mit
5,084
23.094787
64
0.54819
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login Page - Photon Admin Panel Theme</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <link rel="shortcut icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/favicon.ico"/> <link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/iosicon.png"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all"/> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" /> <![endif]--> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" /> <script type="text/javascript" src="js/plugins/excanvas.js"></script> <script type="text/javascript" src="js/plugins/html5shiv.js"></script> <script type="text/javascript" src="js/plugins/respond.min.js"></script> <script type="text/javascript" src="js/plugins/fixFontIcons.js"></script> <![endif]--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/bootstrap/bootstrap.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/modernizr.custom.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.pnotify.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/less-1.3.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/xbreadcrumbs.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/charCount.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.textareaCounter.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/elrte.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/elrte.en.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/select2.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery-picklist.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.validate.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/additional-methods.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.form.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.metadata.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.mockjax.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.uniform.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.tagsinput.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.rating.pack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/farbtastic.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.timeentry.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.dataTables.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.jstree.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/dataTables.bootstrap.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.stack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.pie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.flot.resize.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/raphael.2.1.0.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/justgage.1.0.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.qrcode.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.clock.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.countdown.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.jqtweet.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/jquery.cookie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/prettify/prettify.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/bootstrapSwitch.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/plugins/mfupload.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/js/common.js"></script> </head> <body class="body-login"> <div class="nav-fixed-topright" style="visibility: hidden"> <ul class="nav nav-user-menu"> <li class="user-sub-menu-container"> <a href="javascript:;"> <i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i> </a> <ul class="nav user-sub-menu"> <li class="light"> <a href="javascript:;"> <i class='icon-photon stop'></i>Light Version </a> </li> <li class="dark"> <a href="javascript:;"> <i class='icon-photon stop'></i>Dark Version </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-photon mail"></i> </a> </li> <li> <a href="javascript:;"> <i class="icon-photon comment_alt2_stroke"></i> <div class="notification-count">12</div> </a> </li> </ul> </div> <script> $(function(){ setTimeout(function(){ $('.nav-fixed-topright').removeAttr('style'); }, 300); $(window).scroll(function(){ if($('.breadcrumb-container').length){ var scrollState = $(window).scrollTop(); if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released'); else $('.nav-fixed-topright').removeClass('nav-released') } }); $('.user-sub-menu-container').on('click', function(){ $(this).toggleClass('active-user-menu'); }); $('.user-sub-menu .light').on('click', function(){ if ($('body').is('.light-version')) return; $('body').addClass('light-version'); setTimeout(function() { $.cookie('themeColor', 'light', { expires: 7, path: '/' }); }, 500); }); $('.user-sub-menu .dark').on('click', function(){ if ($('body').is('.light-version')) { $('body').removeClass('light-version'); $.cookie('themeColor', 'dark', { expires: 7, path: '/' }); } }); }); </script> <div class="container-login"> <div class="form-centering-wrapper"> <div class="form-window-login"> <div class="form-window-login-logo"> <div class="login-logo"> <img src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/images/photon/login-logo@2x.png" alt="Photon UI"/> </div> <h2 class="login-title">Welcome to Photon UI!</h2> <div class="login-member">Not a Member?&nbsp;<a href="jquery.autotab-1.1b.js.html#">Sign Up &#187;</a> <a href="jquery.autotab-1.1b.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a> </div> <div class="login-or">Or</div> <div class="login-input-area"> <form method="POST" action="dashboard.php"> <span class="help-block">Login With Your Photon Account</span> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit" class="btn btn-large btn-success btn-login">Login</button> </form> <a href="jquery.autotab-1.1b.js.html#" class="forgot-pass">Forgot Your Password?</a> </div> </div> </div> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1936460-27']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
user-tony/photon-rails
lib/assets/css/css_compiled/@{photonImagePath}plugins/elrte/js/plugins/js/bootstrap/js/plugins/prettify/js/plugins/jquery.autotab-1.1b.js.html
HTML
mit
15,506
84.197802
233
0.742938
false
/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript+bash+css-extras+git+php+php-extras+jsx+scss+twig+yaml&plugins=line-highlight+line-numbers */ /** * prism.js default theme for JavaScript, CSS and HTML * Based on dabblet (http://dabblet.com) * @author Lea Verou */ code[class*="language-"], pre[class*="language-"] { color: black; text-shadow: 0 1px white; font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; direction: ltr; text-align: left; white-space: pre; word-spacing: normal; word-break: normal; line-height: 1.5; -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none; } pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { text-shadow: none; background: #b3d4fc; } pre[class*="language-"]::selection, pre[class*="language-"] ::selection, code[class*="language-"]::selection, code[class*="language-"] ::selection { text-shadow: none; background: #b3d4fc; } @media print { code[class*="language-"], pre[class*="language-"] { text-shadow: none; } } /* Code blocks */ pre[class*="language-"] { padding: 1em; margin: .5em 0; overflow: auto; } :not(pre) > code[class*="language-"], pre[class*="language-"] { background: #f5f2f0; } /* Inline code */ :not(pre) > code[class*="language-"] { padding: .1em; border-radius: .3em; } .token.comment, .token.prolog, .token.doctype, .token.cdata { color: slategray; } .token.punctuation { color: #999; } .namespace { opacity: .7; } .token.property, .token.tag, .token.boolean, .token.number, .token.constant, .token.symbol, .token.deleted { color: #905; } .token.selector, .token.attr-name, .token.string, .token.char, .token.builtin, .token.inserted { color: #690; } .token.operator, .token.entity, .token.url, .language-css .token.string, .style .token.string { color: #a67f59; background: hsla(0, 0%, 100%, .5); } .token.atrule, .token.attr-value, .token.keyword { color: #07a; } .token.function { color: #DD4A68; } .token.regex, .token.important, .token.variable { color: #e90; } .token.important, .token.bold { font-weight: bold; } .token.italic { font-style: italic; } .token.entity { cursor: help; } pre[data-line] { position: relative; padding: 1em 0 1em 3em; } .line-highlight { position: absolute; left: 0; right: 0; padding: inherit 0; margin-top: 1em; /* Same as .prism’s padding-top */ background: hsla(24, 20%, 50%,.08); background: -moz-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); background: -webkit-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); background: -o-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); background: linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); pointer-events: none; line-height: inherit; white-space: pre; } .line-highlight:before, .line-highlight[data-end]:after { content: attr(data-start); position: absolute; top: .4em; left: .6em; min-width: 1em; padding: 0 .5em; background-color: hsla(24, 20%, 50%,.4); color: hsl(24, 20%, 95%); font: bold 65%/1.5 sans-serif; text-align: center; vertical-align: .3em; border-radius: 999px; text-shadow: none; box-shadow: 0 1px white; } .line-highlight[data-end]:after { content: attr(data-end); top: auto; bottom: .4em; } pre.line-numbers { position: relative; padding-left: 3.8em; counter-reset: linenumber; } pre.line-numbers > code { position: relative; } .line-numbers .line-numbers-rows { position: absolute; pointer-events: none; top: 0; font-size: 100%; left: -3.8em; width: 3em; /* works for line-numbers below 1000 lines */ letter-spacing: -1px; border-right: 1px solid #999; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .line-numbers-rows > span { pointer-events: none; display: block; counter-increment: linenumber; } .line-numbers-rows > span:before { content: counter(linenumber); color: #999; display: block; padding-right: 0.8em; text-align: right; }
wesruv/reveal.js
plugin/prism/prism.css
CSS
mit
4,266
18.035714
179
0.660178
false
# -*- coding: utf-8 -*- """ """ from datetime import datetime, timedelta import os from flask import request from flask import Flask import pytz import db from utils import get_remote_addr, get_location_data app = Flask(__name__) @app.route('/yo-water/', methods=['POST', 'GET']) def yowater(): payload = request.args if request.args else request.get_json(force=True) username = payload.get('username') reminder = db.reminders.find_one({'username': username}) reply_object = payload.get('reply') if reply_object is None: if db.reminders.find_one({'username': username}) is None: address = get_remote_addr(request) data = get_location_data(address) if not data: return 'Timezone needed' user_data = {'created': datetime.now(pytz.utc), 'username': username} if data.get('time_zone'): user_data.update({'timezone': data.get('time_zone')}) db.reminders.insert(user_data) return 'OK' else: reply_text = reply_object.get('text') if reply_text == u'Can\'t right now 😖': reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15) else: reminder['step'] += 1 reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60) reminder['last_reply_date'] = datetime.now(pytz.utc) db.reminders.update({'username': username}, reminder) db.replies.insert({'username': username, 'created': datetime.now(pytz.utc), 'reply': reply_text}) return 'OK' if __name__ == "__main__": app.debug = True app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
YoApp/yo-water-tracker
server.py
Python
mit
1,851
24.315068
85
0.563312
false
<html> <head> <title>Terry George's panel show appearances</title> <script type="text/javascript" src="../common.js"></script> <link rel="stylesheet" media="all" href="../style.css" type="text/css"/> <script type="text/javascript" src="../people.js"></script> <!--#include virtual="head.txt" --> </head> <body> <!--#include virtual="nav.txt" --> <div class="page"> <h1>Terry George's panel show appearances</h1> <p>Terry George has appeared in <span class="total">1</span> episodes between 2009-2009. <a href="http://www.imdb.com/name/nm313623">Terry George on IMDB</a>. <a href="https://en.wikipedia.org/wiki/Terry_George">Terry George on Wikipedia</a>.</p> <div class="performerholder"> <table class="performer"> <tr style="vertical-align:bottom;"> <td><div style="height:100px;" class="performances male" title="1"></div><span class="year">2009</span></td> </tr> </table> </div> <ol class="episodes"> <li><strong>2009-06-26</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> </ol> </div> </body> </html>
slowe/panelshows
people/ne3kzguz.html
HTML
mit
1,049
33.966667
248
0.662536
false
{% extends "base.html" %} {% block title %} new statement {% endblock title %} {% load crispy_forms_tags %} {% block content %} <h1>Create a new {{ model_name_lower }}!</h1> {% if request.user.is_anonymous %} Only signed-in users can create {{ model_name_lower }}s! {% else %} {% crispy form form.helper %} {% endif %} {% endblock content %} {% block javascript %} {{ block.super }} {{ form.media }} {% endblock javascript %}
amstart/demo
demoslogic/templates/blockobjects/new.html
HTML
mit
428
22.777778
56
0.630841
false
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() import views urlpatterns = patterns('', url(r'^pis', views.pis), url(r'^words', views.words, { 'titles': False }), url(r'^projects', views.projects), url(r'^posters', views.posters), url(r'^posterpresenters', views.posterpresenters), url(r'^pigraph', views.pigraph), url(r'^institutions', views.institutions), url(r'^institution/(?P<institutionid>\d+)', views.institution), url(r'^profile/$', views.profile), url(r'^schedule/(?P<email>\S+)', views.schedule), url(r'^ratemeeting/(?P<rmid>\d+)/(?P<email>\S+)', views.ratemeeting), url(r'^submitrating/(?P<rmid>\d+)/(?P<email>\S+)', views.submitrating), url(r'^feedback/(?P<email>\S+)', views.after), url(r'^breakouts', views.breakouts), url(r'^breakout/(?P<bid>\d+)', views.breakout), url(r'^about', views.about), url(r'^buginfo', views.buginfo), url(r'^allrms', views.allrms), url(r'^allratings', views.allratings), url(r'^login', views.login), url(r'^logout', views.logout), url(r'^edit_home_page', views.edit_home_page), url(r'^pi/(?P<userid>\d+)', views.pi), # , name = 'pi'), url(r'^pi/(?P<email>\S+)', views.piEmail), # , name = 'pi'), url(r'^project/(?P<abstractid>\S+)', views.project, name = 'project'), url(r'^scope=(?P<scope>\w+)/(?P<url>.+)$', views.set_scope), url(r'^active=(?P<active>\d)/(?P<url>.+)$', views.set_active), url(r'^admin/', include(admin.site.urls)), (r'', include('django_browserid.urls')), url(r'^$', views.index, name = 'index'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
ctames/conference-host
webApp/urls.py
Python
mit
1,850
44.121951
87
0.604324
false
var test = require('tap').test; var CronExpression = require('../lib/expression'); test('Fields are exposed', function(t){ try { var interval = CronExpression.parse('0 1 2 3 * 1-3,5'); t.ok(interval, 'Interval parsed'); CronExpression.map.forEach(function(field) { interval.fields[field] = []; t.throws(function() { interval.fields[field].push(-1); }, /Cannot add property .*?, object is not extensible/, field + ' is frozen'); delete interval.fields[field]; }); interval.fields.dummy = []; t.same(interval.fields.dummy, undefined, 'Fields is frozen'); t.same(interval.fields.second, [0], 'Second matches'); t.same(interval.fields.minute, [1], 'Minute matches'); t.same(interval.fields.hour, [2], 'Hour matches'); t.same(interval.fields.dayOfMonth, [3], 'Day of month matches'); t.same(interval.fields.month, [1,2,3,4,5,6,7,8,9,10,11,12], 'Month matches'); t.same(interval.fields.dayOfWeek, [1,2,3,5], 'Day of week matches'); } catch (err) { t.error(err, 'Interval parse error'); } t.end(); });
harrisiirak/cron-parser
test/fields.js
JavaScript
mit
1,093
33.15625
84
0.628545
false