code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
declare module 'fast-memoize' { declare type Cache<K, V> = { get: (key: K) => V, set: (key: K, value: V) => void, has: (key: K) => boolean } declare type Options = { cache?: Cache<*, *>; serializer?: (...args: any[]) => any; strategy?: <T>(fn: T, options?: Options) => T; } declare module.exports: <T>(fn: T, options?: Options) => T; }
splodingsocks/FlowTyped
definitions/npm/fast-memoize_v2.x.x/flow_v0.53.x-v0.103.x/fast-memoize_v2.x.x.js
JavaScript
mit
374
angular.module('ualib.imageCarousel', ['angular-carousel']) .constant('VIEW_IMAGES_URL', '//wwwdev2.lib.ua.edu/erCarousel/api/slides/active') .factory('imageCarouselFactory', ['$http', 'VIEW_IMAGES_URL', function imageCarouselFactory($http, url){ return { getData: function(){ return $http({method: 'GET', url: url, params: {}}); } }; }]) .controller('imageCarouselCtrl', ['$scope', '$q', 'imageCarouselFactory', function imageCarouselCtrl($scope, $q, imageCarouselFactory){ $scope.slides = null; function loadImages(slides, i, len, deferred){ i = i ? i : 0; len = len ? len : slides.length; deferred = deferred ? deferred : $q.defer(); if (len < 1){ deferred.resolve(slides); } else{ var image = new Image(); image.onload = function(){ slides[i].styles = 'url('+this.src+')'; slides[i].image = this; if (i+1 === len){ deferred.resolve(slides); } else { i++; loadImages(slides, i, len, deferred); } }; image.src = slides[i].image; } return deferred.promise; } imageCarouselFactory.getData() .success(function(data) { loadImages(data.slides).then(function(slides){ $scope.slides = slides; }); }) .error(function(data, status, headers, config) { console.log(data); }); }]) .directive('ualibImageCarousel', [ function() { return { restrict: 'AC', controller: 'imageCarouselCtrl', link: function(scope, elm, attrs, Ctrl){ var toggleLock = false; scope.isLocked = false; scope.pause = function(){ toggleLock = true; scope.isLocked = true; }; scope.play = function(){ toggleLock = false; scope.isLocked = false; }; scope.mouseToggle = function(){ if (!toggleLock){ scope.isLocked = !scope.isLocked; } }; } }; }]);
8bitsquid/roots-ualib
assets/js/_ualib_imageCarousel.js
JavaScript
mit
2,702
import { ListWrapper } from 'angular2/src/facade/collection'; import { stringify, isBlank } from 'angular2/src/facade/lang'; import { BaseException, WrappedException } from 'angular2/src/facade/exceptions'; function findFirstClosedCycle(keys) { var res = []; for (var i = 0; i < keys.length; ++i) { if (ListWrapper.contains(res, keys[i])) { res.push(keys[i]); return res; } else { res.push(keys[i]); } } return res; } function constructResolvingPath(keys) { if (keys.length > 1) { var reversed = findFirstClosedCycle(ListWrapper.reversed(keys)); var tokenStrs = reversed.map(k => stringify(k.token)); return " (" + tokenStrs.join(' -> ') + ")"; } else { return ""; } } /** * Base class for all errors arising from misconfigured providers. */ export class AbstractProviderError extends BaseException { constructor(injector, key, constructResolvingMessage) { super("DI Exception"); this.keys = [key]; this.injectors = [injector]; this.constructResolvingMessage = constructResolvingMessage; this.message = this.constructResolvingMessage(this.keys); } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); this.message = this.constructResolvingMessage(this.keys); } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the * {@link Injector} does not have a {@link Provider} for {@link Key}. * * ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview)) * * ```typescript * class A { * constructor(b:B) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` */ export class NoProviderError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { var first = stringify(ListWrapper.first(keys).token); return `No provider for ${first}!${constructResolvingPath(keys)}`; }); } } /** * Thrown when dependencies form a cycle. * * ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info)) * * ```typescript * var injector = Injector.resolveAndCreate([ * provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}), * provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]}) * ]); * * expect(() => injector.get("one")).toThrowError(); * ``` * * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed. */ export class CyclicDependencyError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`; }); } } /** * Thrown when a constructing type returns with an Error. * * The `InstantiationError` class contains the original error plus the dependency graph which caused * this object to be instantiated. * * ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview)) * * ```typescript * class A { * constructor() { * throw new Error('message'); * } * } * * var injector = Injector.resolveAndCreate([A]); * try { * injector.get(A); * } catch (e) { * expect(e instanceof InstantiationError).toBe(true); * expect(e.originalException.message).toEqual("message"); * expect(e.originalStack).toBeDefined(); * } * ``` */ export class InstantiationError extends WrappedException { constructor(injector, originalException, originalStack, key) { super("DI Exception", originalException, originalStack, null); this.keys = [key]; this.injectors = [injector]; } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); } get wrapperMessage() { var first = stringify(ListWrapper.first(this.keys).token); return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`; } get causeKey() { return this.keys[0]; } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector} * creation. * * ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview)) * * ```typescript * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError(); * ``` */ export class InvalidProviderError extends BaseException { constructor(provider) { super("Invalid provider - only instances of Provider and Type are allowed, got: " + provider.toString()); } } /** * Thrown when the class has no annotation information. * * Lack of annotation information prevents the {@link Injector} from determining which dependencies * need to be injected into the constructor. * * ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview)) * * ```typescript * class A { * constructor(b) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` * * This error is also thrown when the class not marked with {@link Injectable} has parameter types. * * ```typescript * class B {} * * class A { * constructor(b:B) {} // no information about the parameter types of A is available at runtime. * } * * expect(() => Injector.resolveAndCreate([A,B])).toThrowError(); * ``` */ export class NoAnnotationError extends BaseException { constructor(typeOrFunc, params) { super(NoAnnotationError._genMessage(typeOrFunc, params)); } static _genMessage(typeOrFunc, params) { var signature = []; for (var i = 0, ii = params.length; i < ii; i++) { var parameter = params[i]; if (isBlank(parameter) || parameter.length == 0) { signature.push('?'); } else { signature.push(parameter.map(stringify).join(' ')); } } return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" + signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.'; } } /** * Thrown when getting an object by index. * * ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview)) * * ```typescript * class A {} * * var injector = Injector.resolveAndCreate([A]); * * expect(() => injector.getAt(100)).toThrowError(); * ``` */ export class OutOfBoundsError extends BaseException { constructor(index) { super(`Index ${index} is out-of-bounds.`); } } // TODO: add a working example after alpha38 is released /** * Thrown when a multi provider and a regular provider are bound to the same token. * * ### Example * * ```typescript * expect(() => Injector.resolveAndCreate([ * new Provider("Strings", {useValue: "string1", multi: true}), * new Provider("Strings", {useValue: "string2", multi: false}) * ])).toThrowError(); * ``` */ export class MixingMultiProvidersWithRegularProvidersError extends BaseException { constructor(provider1, provider2) { super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " + provider2.toString()); } } //# sourceMappingURL=exceptions.js.map
binariedMe/blogging
node_modules/angular2/es6/prod/src/core/di/exceptions.js
JavaScript
mit
7,494
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ENTER} from '@angular/cdk/keycodes'; import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import { ErrorStateMatcher, MatCommonModule, MatRippleModule, } from '@angular/material-experimental/mdc-core'; import {MatChip, MatChipCssInternalOnly} from './chip'; import {MAT_CHIPS_DEFAULT_OPTIONS, MatChipsDefaultOptions} from './chip-default-options'; import {MatChipEditInput} from './chip-edit-input'; import {MatChipGrid} from './chip-grid'; import {MatChipAvatar, MatChipRemove, MatChipTrailingIcon} from './chip-icons'; import {MatChipInput} from './chip-input'; import {MatChipListbox} from './chip-listbox'; import {MatChipRow} from './chip-row'; import {MatChipOption} from './chip-option'; import {MatChipSet} from './chip-set'; const CHIP_DECLARATIONS = [ MatChip, MatChipAvatar, MatChipCssInternalOnly, MatChipEditInput, MatChipGrid, MatChipInput, MatChipListbox, MatChipOption, MatChipRemove, MatChipRow, MatChipSet, MatChipTrailingIcon, ]; @NgModule({ imports: [MatCommonModule, CommonModule, MatRippleModule], exports: [MatCommonModule, CHIP_DECLARATIONS], declarations: CHIP_DECLARATIONS, providers: [ ErrorStateMatcher, { provide: MAT_CHIPS_DEFAULT_OPTIONS, useValue: { separatorKeyCodes: [ENTER] } as MatChipsDefaultOptions } ] }) export class MatChipsModule { }
josephperrott/material2
src/material-experimental/mdc-chips/module.ts
TypeScript
mit
1,601
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2014 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Net; using System.Net.Http; using System.Threading; using System.Web; using System.Web.Http; using DotNetNuke.Application; using DotNetNuke.Common; using DotNetNuke.Entities.Controllers; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.Localization; using DotNetNuke.Web.Api; namespace DotNetNuke.Web.InternalServices { [RequireHost] public class GettingStartedController : DnnApiController { private const string GettingStartedHideKey = "GettingStarted_Hide_{0}"; private const string GettingStartedDisplayKey = "GettingStarted_Display_{0}"; public class ClosePageDto { public bool IsHidden { get; set; } } public class EmailDto { public string Email { get; set; } } [HttpGet] public HttpResponseMessage GetGettingStartedPageSettings() { var isHidden = HostController.Instance.GetBoolean(String.Format(GettingStartedHideKey, PortalSettings.UserId), false); var userEmailAddress = PortalSettings.UserInfo.Email; var request = HttpContext.Current.Request; var builder = new UriBuilder { Scheme = request.Url.Scheme, Host = "www.dnnsoftware.com", Path = "Community/Download/Manuals", Query = "src=dnn" // parameter to judge the effectiveness of this as a channel (i.e. the number of click through) }; var userManualUrl = builder.Uri.AbsoluteUri; return Request.CreateResponse(HttpStatusCode.OK, new { IsHidden = isHidden, EmailAddress = userEmailAddress, UserManualUrl = userManualUrl }); } [HttpPost] public HttpResponseMessage CloseGettingStartedPage(ClosePageDto dto) { HostController.Instance.Update(String.Format(GettingStartedHideKey, PortalSettings.UserId), dto.IsHidden.ToString()); HostController.Instance.Update(String.Format(GettingStartedDisplayKey, PortalSettings.UserId), "false"); return Request.CreateResponse(HttpStatusCode.OK, "Success"); } [HttpPost] public HttpResponseMessage SubscribeToNewsletter(EmailDto dto) { HostController.Instance.Update("NewsletterSubscribeEmail", dto.Email); return Request.CreateResponse(HttpStatusCode.OK, "Success"); } [HttpGet] public HttpResponseMessage GetContentUrl() { var request = HttpContext.Current.Request; var builder = new UriBuilder { Scheme = request.Url.Scheme, Host = "www.dnnsoftware.com", Path = String.Format("DesktopModules/DNNCorp/GettingStarted/{0}/{1}/index.html", DotNetNukeContext.Current.Application.Name.Replace(".", "_"), DotNetNukeContext.Current.Application.Version.ToString(3)), Query = String.Format("locale={0}", Thread.CurrentThread.CurrentUICulture) }; var contentUrl = builder.Uri.AbsoluteUri; var fallbackUrl = Globals.AddHTTP(request.Url.Host + Globals.ResolveUrl("~/Portals/_default/GettingStartedFallback.htm")); var isValid = IsValidUrl(contentUrl); return Request.CreateResponse(HttpStatusCode.OK, new { Url = isValid ? contentUrl : fallbackUrl }); } /// <summary> /// Checks if url does not return server or protocol errors /// </summary> /// <param name="url">Url to check</param> /// <returns></returns> private static bool IsValidUrl(string url) { HttpWebResponse response = null; try { var request = WebRequest.Create(url); request.Timeout = 5000; // set the timeout to 5 seconds to keep the user from waiting too long for the page to load request.Method = "HEAD"; // get only the header information - no need to download any content response = request.GetResponse() as HttpWebResponse; if (response == null) { return false; } var statusCode = (int)response.StatusCode; if (statusCode >= 500 && statusCode <= 510) // server errors { return false; } } catch { return false; } finally { if (response != null) { response.Close(); } } return true; } } }
raphael-m/Dnn.Platform
DNN Platform/DotNetNuke.Web/InternalServices/GettingStartedController.cs
C#
mit
6,016
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function getHelp(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDescription); } framework.addJavaScriptHelp("help", "substring, fileName", "output all the helper functions whose name contains the given 'substring'"); function help(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, false), fileName); } else if (arguments.length > 0) { write(getHelp(substring, false)); } else { write(getHelp("", false)); } } framework.addJavaScriptHelp("apropos", "substring, fileName", "output all the helper functions whose name or description contains the given 'substring'"); function apropos(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, true), fileName); } else if (arguments.length > 0) { write(getHelp(substring, true)); } else { write(getHelp("", true)); } } framework.addJavaScriptHelp("helpRegex", "regex, fileName", "output all helper functions whose name matches 'regex'"); function helpRegex(regex, fileName) { if (arguments.length > 1) { write(framework.getJavaScriptHelp(regex, false), fileName); } else if (arguments.length > 0) { write(framework.getJavaScriptHelp(regex, false)); } }
workcraft/workcraft
workcraft/WorkcraftCore/res/scripts/core-help.js
JavaScript
mit
1,523
FullCalendar.globalLocales.push(function () { 'use strict'; var it = { code: 'it', week: { dow: 1, // Monday is the first day of the week. doy: 4, // The week that contains Jan 4th is the first week of the year. }, buttonText: { prev: 'Prec', next: 'Succ', today: 'Oggi', month: 'Mese', week: 'Settimana', day: 'Giorno', list: 'Agenda', }, weekText: 'Sm', allDayText: 'Tutto il giorno', moreLinkText(n) { return '+altri ' + n }, noEventsText: 'Non ci sono eventi da visualizzare', }; return it; }());
unaio/una
upgrade/files/11.0.4-12.0.0.B1/files/plugins_public/fullcalendar/locale/it.js
JavaScript
mit
612
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package get import ( "errors" "internal/testenv" "io/ioutil" "os" "path" "path/filepath" "testing" "cmd/go/internal/web" ) // Test that RepoRootForImportPath creates the correct RepoRoot for a given importPath. // TODO(cmang): Add tests for SVN and BZR. func TestRepoRootForImportPath(t *testing.T) { testenv.MustHaveExternalNetwork(t) tests := []struct { path string want *repoRoot }{ { "github.com/golang/groupcache", &repoRoot{ vcs: vcsGit, repo: "https://github.com/golang/groupcache", }, }, // Unicode letters in directories (issue 18660). { "github.com/user/unicode/испытание", &repoRoot{ vcs: vcsGit, repo: "https://github.com/user/unicode", }, }, // IBM DevOps Services tests { "hub.jazz.net/git/user1/pkgname", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user1/pkgname", }, }, { "hub.jazz.net/git/user1/pkgname/submodule/submodule/submodule", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user1/pkgname", }, }, { "hub.jazz.net", nil, }, { "hub2.jazz.net", nil, }, { "hub.jazz.net/someotherprefix", nil, }, { "hub.jazz.net/someotherprefix/user1/pkgname", nil, }, // Spaces are not valid in user names or package names { "hub.jazz.net/git/User 1/pkgname", nil, }, { "hub.jazz.net/git/user1/pkg name", nil, }, // Dots are not valid in user names { "hub.jazz.net/git/user.1/pkgname", nil, }, { "hub.jazz.net/git/user/pkg.name", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user/pkg.name", }, }, // User names cannot have uppercase letters { "hub.jazz.net/git/USER/pkgname", nil, }, // OpenStack tests { "git.openstack.org/openstack/swift", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift", }, }, // Trailing .git is less preferred but included for // compatibility purposes while the same source needs to // be compilable on both old and new go { "git.openstack.org/openstack/swift.git", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift.git", }, }, { "git.openstack.org/openstack/swift/go/hummingbird", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift", }, }, { "git.openstack.org", nil, }, { "git.openstack.org/openstack", nil, }, // Spaces are not valid in package name { "git.apache.org/package name/path/to/lib", nil, }, // Should have ".git" suffix { "git.apache.org/package-name/path/to/lib", nil, }, { "git.apache.org/package-name.git", &repoRoot{ vcs: vcsGit, repo: "https://git.apache.org/package-name.git", }, }, { "git.apache.org/package-name_2.x.git/path/to/lib", &repoRoot{ vcs: vcsGit, repo: "https://git.apache.org/package-name_2.x.git", }, }, { "chiselapp.com/user/kyle/repository/fossilgg", &repoRoot{ vcs: vcsFossil, repo: "https://chiselapp.com/user/kyle/repository/fossilgg", }, }, { // must have a user/$name/repository/$repo path "chiselapp.com/kyle/repository/fossilgg", nil, }, { "chiselapp.com/user/kyle/fossilgg", nil, }, } for _, test := range tests { got, err := repoRootForImportPath(test.path, web.Secure) want := test.want if want == nil { if err == nil { t.Errorf("repoRootForImportPath(%q): Error expected but not received", test.path) } continue } if err != nil { t.Errorf("repoRootForImportPath(%q): %v", test.path, err) continue } if got.vcs.name != want.vcs.name || got.repo != want.repo { t.Errorf("repoRootForImportPath(%q) = VCS(%s) Repo(%s), want VCS(%s) Repo(%s)", test.path, got.vcs, got.repo, want.vcs, want.repo) } } } // Test that vcsFromDir correctly inspects a given directory and returns the right VCS and root. func TestFromDir(t *testing.T) { tempDir, err := ioutil.TempDir("", "vcstest") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) for j, vcs := range vcsList { dir := filepath.Join(tempDir, "example.com", vcs.name, "."+vcs.cmd) if j&1 == 0 { err := os.MkdirAll(dir, 0755) if err != nil { t.Fatal(err) } } else { err := os.MkdirAll(filepath.Dir(dir), 0755) if err != nil { t.Fatal(err) } f, err := os.Create(dir) if err != nil { t.Fatal(err) } f.Close() } want := repoRoot{ vcs: vcs, root: path.Join("example.com", vcs.name), } var got repoRoot got.vcs, got.root, err = vcsFromDir(dir, tempDir) if err != nil { t.Errorf("FromDir(%q, %q): %v", dir, tempDir, err) continue } if got.vcs.name != want.vcs.name || got.root != want.root { t.Errorf("FromDir(%q, %q) = VCS(%s) Root(%s), want VCS(%s) Root(%s)", dir, tempDir, got.vcs, got.root, want.vcs, want.root) } } } func TestIsSecure(t *testing.T) { tests := []struct { vcs *vcsCmd url string secure bool }{ {vcsGit, "http://example.com/foo.git", false}, {vcsGit, "https://example.com/foo.git", true}, {vcsBzr, "http://example.com/foo.bzr", false}, {vcsBzr, "https://example.com/foo.bzr", true}, {vcsSvn, "http://example.com/svn", false}, {vcsSvn, "https://example.com/svn", true}, {vcsHg, "http://example.com/foo.hg", false}, {vcsHg, "https://example.com/foo.hg", true}, {vcsGit, "ssh://user@example.com/foo.git", true}, {vcsGit, "user@server:path/to/repo.git", false}, {vcsGit, "user@server:", false}, {vcsGit, "server:repo.git", false}, {vcsGit, "server:path/to/repo.git", false}, {vcsGit, "example.com:path/to/repo.git", false}, {vcsGit, "path/that/contains/a:colon/repo.git", false}, {vcsHg, "ssh://user@example.com/path/to/repo.hg", true}, {vcsFossil, "http://example.com/foo", false}, {vcsFossil, "https://example.com/foo", true}, } for _, test := range tests { secure := test.vcs.isSecure(test.url) if secure != test.secure { t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure) } } } func TestIsSecureGitAllowProtocol(t *testing.T) { tests := []struct { vcs *vcsCmd url string secure bool }{ // Same as TestIsSecure to verify same behavior. {vcsGit, "http://example.com/foo.git", false}, {vcsGit, "https://example.com/foo.git", true}, {vcsBzr, "http://example.com/foo.bzr", false}, {vcsBzr, "https://example.com/foo.bzr", true}, {vcsSvn, "http://example.com/svn", false}, {vcsSvn, "https://example.com/svn", true}, {vcsHg, "http://example.com/foo.hg", false}, {vcsHg, "https://example.com/foo.hg", true}, {vcsGit, "user@server:path/to/repo.git", false}, {vcsGit, "user@server:", false}, {vcsGit, "server:repo.git", false}, {vcsGit, "server:path/to/repo.git", false}, {vcsGit, "example.com:path/to/repo.git", false}, {vcsGit, "path/that/contains/a:colon/repo.git", false}, {vcsHg, "ssh://user@example.com/path/to/repo.hg", true}, // New behavior. {vcsGit, "ssh://user@example.com/foo.git", false}, {vcsGit, "foo://example.com/bar.git", true}, {vcsHg, "foo://example.com/bar.hg", false}, {vcsSvn, "foo://example.com/svn", false}, {vcsBzr, "foo://example.com/bar.bzr", false}, } defer os.Unsetenv("GIT_ALLOW_PROTOCOL") os.Setenv("GIT_ALLOW_PROTOCOL", "https:foo") for _, test := range tests { secure := test.vcs.isSecure(test.url) if secure != test.secure { t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure) } } } func TestMatchGoImport(t *testing.T) { tests := []struct { imports []metaImport path string mi metaImport err error }{ { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/fooa", mi: metaImport{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz/qux", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz/", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com", err: errors.New("pathologically short path"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "different.example.com/user/foo", err: errors.New("meta tags do not match import path"), }, } for _, test := range tests { mi, err := matchGoImport(test.imports, test.path) if mi != test.mi { t.Errorf("unexpected metaImport; got %v, want %v", mi, test.mi) } got := err want := test.err if (got == nil) != (want == nil) { t.Errorf("unexpected error; got %v, want %v", got, want) } } } func TestValidateRepoRootScheme(t *testing.T) { tests := []struct { root string err string }{ { root: "", err: "no scheme", }, { root: "http://", err: "", }, { root: "a://", err: "", }, { root: "a#://", err: "invalid scheme", }, { root: "-config://", err: "invalid scheme", }, } for _, test := range tests { err := validateRepoRootScheme(test.root) if err == nil { if test.err != "" { t.Errorf("validateRepoRootScheme(%q) = nil, want %q", test.root, test.err) } } else if test.err == "" { if err != nil { t.Errorf("validateRepoRootScheme(%q) = %q, want nil", test.root, test.err) } } else if err.Error() != test.err { t.Errorf("validateRepoRootScheme(%q) = %q, want %q", test.root, err, test.err) } } }
christopher-henderson/Go
src/cmd/go/internal/get/vcs_test.go
GO
mit
12,175
<?php namespace Hateoas\Tests\Expression; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\Node\Node; use Symfony\Component\ExpressionLanguage\ParsedExpression; use Hateoas\Tests\TestCase; use Hateoas\Expression\ExpressionEvaluator; use Hateoas\Expression\ExpressionFunctionInterface; class ExpressionEvaluatorTest extends TestCase { public function testNullEvaluate() { $expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $expressionLanguageProphecy ->parse($this->arg->any()) ->shouldNotBeCalled() ; $expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal()); $this ->string($expressionEvaluator->evaluate('hello', null)) ->isEqualTo('hello') ; } public function testEvaluate() { $data = new \StdClass(); $expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $expressionLanguageProphecy ->parse('"42"', array('object')) ->willReturn($parsedExpression = new ParsedExpression('', new Node())) ; $expressionLanguageProphecy ->evaluate($parsedExpression, array('object' => $data)) ->willReturn('42') ; $expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal()); $this ->string($expressionEvaluator->evaluate('expr("42")', $data)) ->isEqualTo('42') ; } public function testEvaluateArray() { $parsedExpressions = array( new ParsedExpression('a', new Node()), new ParsedExpression('aa', new Node()), new ParsedExpression('aaa', new Node()), ); $data = new \StdClass(); $ELProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $ELProphecy->parse('a', array('object'))->willReturn($parsedExpressions[0])->shouldBeCalledTimes(1); $ELProphecy->parse('aa', array('object'))->willReturn($parsedExpressions[1])->shouldBeCalledTimes(1); $ELProphecy->parse('aaa', array('object'))->willReturn($parsedExpressions[2])->shouldBeCalledTimes(1); $ELProphecy->evaluate($parsedExpressions[0], array('object' => $data))->willReturn(1); $ELProphecy->evaluate($parsedExpressions[1], array('object' => $data))->willReturn(2); $ELProphecy->evaluate($parsedExpressions[2], array('object' => $data))->willReturn(3); $expressionEvaluator = new ExpressionEvaluator($ELProphecy->reveal()); $array = array( 'expr(a)' => 'expr(aa)', 'hello' => array('expr(aaa)'), ); $this ->array($expressionEvaluator->evaluateArray($array, $data)) ->isEqualTo(array( 1 => 2, 'hello' => array(3), )) ; } public function testSetContextVariable() { $data = new \StdClass(); $expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $expressionLanguageProphecy ->parse('name', array('name', 'object')) ->willReturn($parsedExpression = new ParsedExpression('', new Node())) ->shouldBeCalledTimes(1) ; $expressionLanguageProphecy ->evaluate($parsedExpression, array('object' => $data, 'name' => 'Adrien')) ->willReturn('Adrien') ->shouldBeCalledTimes(1) ; $expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal()); $expressionEvaluator->setContextVariable('name', 'Adrien'); $this ->string($expressionEvaluator->evaluate('expr(name)', $data)) ->isEqualTo('Adrien') ; } public function testRegisterFunction() { $expressionEvaluator = new ExpressionEvaluator(new ExpressionLanguage()); $expressionEvaluator->registerFunction(new HelloExpressionFunction()); $this ->string($expressionEvaluator->evaluate('expr(hello("toto"))', null)) ->isEqualTo('Hello, toto!') ; } } class HelloExpressionFunction implements ExpressionFunctionInterface { public function getName() { return 'hello'; } public function getCompiler() { return function ($value) { return sprintf('$hello_helper->hello(%s)', $value); }; } public function getEvaluator() { return function (array $context, $value) { return $context['hello_helper']->hello($value); }; } public function getContextVariables() { return array('hello_helper' => $this); } public function hello($name) { return sprintf('Hello, %s!', $name); } }
witalikkowal/Store
vendor/willdurand/hateoas/tests/Hateoas/Tests/Expression/ExpressionEvaluatorTest.php
PHP
mit
5,029
<?php /** * Pro customizer section. * * @since 1.0.0 * @access public */ class Epsilon_Section_Pro extends WP_Customize_Section { /** * The type of customize section being rendered. * * @since 1.0.0 * @access public * @var string */ public $type = 'epsilon-section-pro'; /** * Custom pro button URL. * * @since 1.0.0 * @access public * @var string */ public $button_url = ''; /** * Custom pro button text. * * @since 1.0.0 * @access public * @var string */ public $button_text = ''; /** * Used to disable the upsells * * @var bool */ public $allowed = true; /** * Epsilon_Section_Pro constructor. * * @param WP_Customize_Manager $manager * @param string $id * @param array $args */ public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) { $this->allowed = apply_filters( 'epsilon_upsell_section_display', true ); $manager->register_section_type( 'Epsilon_Section_Pro' ); parent::__construct( $manager, $id, $args ); } /** * Add custom parameters to pass to the JS via JSON. * * @since 1.0.0 * @access public */ public function json() { $json = parent::json(); $json['button_url'] = $this->button_url; $json['button_text'] = esc_html( $this->button_text ); $json['allowed'] = $this->allowed; return $json; } /** * Outputs the Underscore.js template. * * @since 1.0.0 * @access public * @return void */ protected function render_template() { ?> <?php if ( $this->allowed ) : //@formatter:off ?> <li id="accordion-section-{{ data.id }}" class="accordion-section control-section control-section-{{ data.type }} cannot-expand"> <h3 class="accordion-section-title epsilon-pro-section-title"> {{ data.title }} <# if ( data.button_url ) { #> <a href="{{ data.button_url }}" class="button alignright" target="_blank"> {{ data.button_text }}</a> <# } #> </h3> </li> <?php //@formatter:on ?> <?php endif; ?> <?php } }
jmelgarejo/Clan
wordpress/wp-content/themes/sparkling/inc/libraries/epsilon-framework/sections/class-epsilon-section-pro.php
PHP
mit
2,068
/// <summary> /// This class handles user ID, session ID, time stamp, and sends a user message, optionally including system specs, when the game starts /// </summary> using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System; using System.Net; #if !UNITY_WEBPLAYER && !UNITY_NACL && !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO && !UNITY_PS3 using System.Net.NetworkInformation; using System.Security.Cryptography; using System.Text; #endif public class GA_GenericInfo { #region public values /// <summary> /// The ID of the user/player. A unique ID will be determined the first time the player plays. If an ID has already been created for a player this ID will be used. /// </summary> public string UserID { get { if ((_userID == null || _userID == string.Empty) && !GA.SettingsGA.CustomUserID) { _userID = GetUserUUID(); } return _userID; } } /// <summary> /// The ID of the current session. A unique ID will be determined when the game starts. This ID will be used for the remainder of the play session. /// </summary> public string SessionID { get { if (_sessionID == null) { _sessionID = GetSessionUUID(); } return _sessionID; } } /// <summary> /// The current UTC date/time in seconds /// </summary> /*public string TimeStamp { get { return ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); } }*/ #endregion #region private values private string _userID = string.Empty; private string _sessionID; private bool _settingUserID; #endregion #region public methods /// <summary> /// Gets generic system information at the beginning of a play session /// </summary> /// <param name="inclSpecs"> /// Determines if all the system specs should be included <see cref="System.Bool"/> /// </param> /// <returns> /// The message to submit to the GA server is a dictionary of all the relevant parameters (containing user ID, session ID, system information, language information, date/time, build version) <see cref="Dictionary<System.String, System.Object>"/> /// </returns> public List<Hashtable> GetGenericInfo(string message) { List<Hashtable> systemspecs = new List<Hashtable>(); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "unity_sdk " + GA_Settings.VERSION, message)); /* * Apple does not allow tracking of device specific data: * "You may not use analytics software in your application to collect and send device data to a third party" * - iOS Developer Program License Agreement: http://www.scribd.com/doc/41213383/iOS-Developer-Program-License-Agreement */ #if !UNITY_IPHONE systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:"+SystemInfo.operatingSystem, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "processor_type:"+SystemInfo.processorType, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_name:"+SystemInfo.graphicsDeviceName, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_version:"+SystemInfo.graphicsDeviceVersion, message)); // Unity provides lots of additional system info which might be worth tracking for some games: //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "process_count:"+SystemInfo.processorCount.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sys_mem_size:"+SystemInfo.systemMemorySize.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_mem_size:"+SystemInfo.graphicsMemorySize.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor:"+SystemInfo.graphicsDeviceVendor, message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_id:"+SystemInfo.graphicsDeviceID.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor_id:"+SystemInfo.graphicsDeviceVendorID.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_shader_level:"+SystemInfo.graphicsShaderLevel.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_pixel_fillrate:"+SystemInfo.graphicsPixelFillrate.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_shadows:"+SystemInfo.supportsShadows.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_render_textures:"+SystemInfo.supportsRenderTextures.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_image_effects:"+SystemInfo.supportsImageEffects.ToString(), message)); #else systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:iOS", message)); #endif return systemspecs; } /// <summary> /// Gets a universally unique ID to represent the user. User ID should be device specific to allow tracking across different games on the same device: /// -- Android uses deviceUniqueIdentifier. /// -- iOS/PC/Mac uses the first MAC addresses available. /// -- Webplayer uses deviceUniqueIdentifier. /// Note: The unique user ID is based on the ODIN specifications. See http://code.google.com/p/odinmobile/ for more information on ODIN. /// </summary> /// <returns> /// The generated UUID <see cref="System.String"/> /// </returns> public static string GetUserUUID() { #if UNITY_IPHONE && !UNITY_EDITOR string uid = GA.SettingsGA.GetUniqueIDiOS(); if (uid == null) { return ""; } else if (uid != "OLD") { if (uid.StartsWith("VENDOR-")) return uid.Remove(0, 7); else return uid; } #endif #if UNITY_ANDROID && !UNITY_EDITOR string uid = GA.SettingsGA.GetAdvertisingIDAndroid(); if (!string.IsNullOrEmpty(uid)) { return uid; } #endif #if UNITY_WEBPLAYER || UNITY_NACL || UNITY_WP8 || UNITY_METRO || UNITY_PS3 return SystemInfo.deviceUniqueIdentifier; #elif !UNITY_FLASH try { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); string mac = ""; foreach (NetworkInterface adapter in nics) { PhysicalAddress address = adapter.GetPhysicalAddress(); if (address.ToString() != "" && mac == "") { mac = GA_Submit.CreateSha1Hash(address.ToString()); } } return mac; } catch { return SystemInfo.deviceUniqueIdentifier; } #else return GetSessionUUID(); #endif } /// <summary> /// Gets a universally unique ID to represent the session. /// </summary> /// <returns> /// The generated UUID <see cref="System.String"/> /// </returns> public static string GetSessionUUID() { #if !UNITY_FLASH return Guid.NewGuid().ToString(); #else string returnValue = ""; for (int i = 0; i < 12; i++) { returnValue += UnityEngine.Random.Range(0, 10).ToString(); } return returnValue; #endif } /// <summary> /// Sets the session ID. If newSessionID is null then a random UUID will be generated, otherwise newSessionID will be used as the session ID. /// </summary> /// <param name="newSessionID">New session I.</param> public void SetSessionUUID(string newSessionID) { if (newSessionID == null) { _sessionID = GetSessionUUID(); } else { _sessionID = newSessionID; } } /// <summary> /// Do not call this method (instead use GA_static_api.Settings.SetCustomUserID)! Only the GA class should call this method. /// </summary> /// <param name="customID"> /// The custom user ID - this should be unique for each user /// </param> public void SetCustomUserID(string customID) { _userID = customID; } #endregion #region private methods /// <summary> /// Adds detailed system specifications regarding the users/players device to the parameters. /// </summary> /// <param name="parameters"> /// The parameters which will be sent to the server <see cref="Dictionary<System.String, System.Object>"/> /// </param> private Hashtable AddSystemSpecs(GA_Error.SeverityType severity, string type, string message) { string addmessage = ""; if (message != "") addmessage = ": " + message; Hashtable parameters = new Hashtable() { { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Severity], severity.ToString() }, { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Message], type + addmessage }, { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Level], GA.SettingsGA.CustomArea.Equals(string.Empty)?Application.loadedLevelName:GA.SettingsGA.CustomArea } }; return parameters; } /// <summary> /// Gets the users system type /// </summary> /// <returns> /// String determining the system the user is currently running <see cref="System.String"/> /// </returns> public static string GetSystem() { #if UNITY_STANDALONE_OSX return "MAC"; #elif UNITY_STANDALONE_WIN return "PC"; #elif UNITY_WEBPLAYER return "WEBPLAYER"; #elif UNITY_WII return "WII"; #elif UNITY_IPHONE return "IPHONE"; #elif UNITY_ANDROID return "ANDROID"; #elif UNITY_PS3 return "PS3"; #elif UNITY_XBOX360 return "XBOX"; #elif UNITY_FLASH return "FLASH"; #elif UNITY_STANDALONE_LINUX return "LINUX"; #elif UNITY_NACL return "NACL"; #elif UNITY_DASHBOARD_WIDGET return "DASHBOARD_WIDGET"; #elif UNITY_METRO return "WINDOWS_STORE_APP"; #elif UNITY_WP8 return "WINDOWS_PHONE_8"; #elif UNITY_BLACKBERRY return "BLACKBERRY"; #else return "UNKNOWN"; #endif } #endregion }
samoatesgames/Ludumdare30
Unity/Assets/GameAnalytics/Plugins/Framework/Scripts/GA_GenericInfo.cs
C#
mit
9,640
import {OverlayRef, GlobalPositionStrategy} from '../core'; import {AnimationEvent} from '@angular/animations'; import {DialogPosition} from './dialog-config'; import {Observable} from 'rxjs/Observable'; import {Subject} from 'rxjs/Subject'; import {MdDialogContainer} from './dialog-container'; import 'rxjs/add/operator/filter'; // TODO(jelbourn): resizing // TODO(jelbourn): afterOpen and beforeClose /** * Reference to a dialog opened via the MdDialog service. */ export class MdDialogRef<T> { /** The instance of component opened into the dialog. */ componentInstance: T; /** Subject for notifying the user that the dialog has finished closing. */ private _afterClosed: Subject<any> = new Subject(); /** Result to be passed to afterClosed. */ private _result: any; constructor(private _overlayRef: OverlayRef, public _containerInstance: MdDialogContainer) { _containerInstance._onAnimationStateChange .filter((event: AnimationEvent) => event.toState === 'exit') .subscribe(() => { this._overlayRef.dispose(); this.componentInstance = null; }, null, () => { this._afterClosed.next(this._result); this._afterClosed.complete(); }); } /** * Close the dialog. * @param dialogResult Optional result to return to the dialog opener. */ close(dialogResult?: any): void { this._result = dialogResult; this._containerInstance._state = 'exit'; this._overlayRef.detachBackdrop(); // Transition the backdrop in parallel with the dialog. } /** * Gets an observable that is notified when the dialog is finished closing. */ afterClosed(): Observable<any> { return this._afterClosed.asObservable(); } /** * Updates the dialog's position. * @param position New dialog position. */ updatePosition(position?: DialogPosition): this { let strategy = this._getPositionStrategy(); if (position && (position.left || position.right)) { position.left ? strategy.left(position.left) : strategy.right(position.right); } else { strategy.centerHorizontally(); } if (position && (position.top || position.bottom)) { position.top ? strategy.top(position.top) : strategy.bottom(position.bottom); } else { strategy.centerVertically(); } this._overlayRef.updatePosition(); return this; } /** * Updates the dialog's width and height. * @param width New width of the dialog. * @param height New height of the dialog. */ updateSize(width = 'auto', height = 'auto'): this { this._getPositionStrategy().width(width).height(height); this._overlayRef.updatePosition(); return this; } /** Fetches the position strategy object from the overlay ref. */ private _getPositionStrategy(): GlobalPositionStrategy { return this._overlayRef.getState().positionStrategy as GlobalPositionStrategy; } }
trik/material2
src/lib/dialog/dialog-ref.ts
TypeScript
mit
2,903
// import java.util.Comparator; abc.sort(Comparator.naturalOrder()); //
general-language-syntax/GLS
test/integration/ListSortStrings/list sort strings.java
Java
mit
73
module RR module Errors class SpyVerificationError < RRError end end end
priit/adva_cms
test/rr/lib/rr/errors/spy_verification_error.rb
Ruby
mit
84
<?php /** * This file is part of PHPWord - A pure PHP library for reading and writing * word processing documents. * * PHPWord is free software distributed under the terms of the GNU Lesser * General Public License version 3 as published by the Free Software Foundation. * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. For the full list of * contributors, visit https://github.com/PHPOffice/PHPWord/contributors. * * @see https://github.com/PHPOffice/PHPWord * @copyright 2010-2018 PHPWord contributors * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3 */ namespace PhpOffice\PhpWord\Element; /** * Container abstract class * * @method Text addText(string $text, mixed $fStyle = null, mixed $pStyle = null) * @method TextRun addTextRun(mixed $pStyle = null) * @method Bookmark addBookmark(string $name) * @method Link addLink(string $target, string $text = null, mixed $fStyle = null, mixed $pStyle = null, boolean $internal = false) * @method PreserveText addPreserveText(string $text, mixed $fStyle = null, mixed $pStyle = null) * @method void addTextBreak(int $count = 1, mixed $fStyle = null, mixed $pStyle = null) * @method ListItem addListItem(string $txt, int $depth = 0, mixed $font = null, mixed $list = null, mixed $para = null) * @method ListItemRun addListItemRun(int $depth = 0, mixed $listStyle = null, mixed $pStyle = null) * @method Footnote addFootnote(mixed $pStyle = null) * @method Endnote addEndnote(mixed $pStyle = null) * @method CheckBox addCheckBox(string $name, $text, mixed $fStyle = null, mixed $pStyle = null) * @method Title addTitle(mixed $text, int $depth = 1) * @method TOC addTOC(mixed $fontStyle = null, mixed $tocStyle = null, int $minDepth = 1, int $maxDepth = 9) * @method PageBreak addPageBreak() * @method Table addTable(mixed $style = null) * @method Image addImage(string $source, mixed $style = null, bool $isWatermark = false, $name = null) * @method OLEObject addOLEObject(string $source, mixed $style = null) * @method TextBox addTextBox(mixed $style = null) * @method Field addField(string $type = null, array $properties = array(), array $options = array(), mixed $text = null) * @method Line addLine(mixed $lineStyle = null) * @method Shape addShape(string $type, mixed $style = null) * @method Chart addChart(string $type, array $categories, array $values, array $style = null, $seriesName = null) * @method FormField addFormField(string $type, mixed $fStyle = null, mixed $pStyle = null) * @method SDT addSDT(string $type) * * @method \PhpOffice\PhpWord\Element\OLEObject addObject(string $source, mixed $style = null) deprecated, use addOLEObject instead * * @since 0.10.0 */ abstract class AbstractContainer extends AbstractElement { /** * Elements collection * * @var \PhpOffice\PhpWord\Element\AbstractElement[] */ protected $elements = array(); /** * Container type Section|Header|Footer|Footnote|Endnote|Cell|TextRun|TextBox|ListItemRun|TrackChange * * @var string */ protected $container; /** * Magic method to catch all 'addElement' variation * * This removes addText, addTextRun, etc. When adding new element, we have to * add the model in the class docblock with `@method`. * * Warning: This makes capitalization matters, e.g. addCheckbox or addcheckbox won't work. * * @param mixed $function * @param mixed $args * @return \PhpOffice\PhpWord\Element\AbstractElement */ public function __call($function, $args) { $elements = array( 'Text', 'TextRun', 'Bookmark', 'Link', 'PreserveText', 'TextBreak', 'ListItem', 'ListItemRun', 'Table', 'Image', 'Object', 'OLEObject', 'Footnote', 'Endnote', 'CheckBox', 'TextBox', 'Field', 'Line', 'Shape', 'Title', 'TOC', 'PageBreak', 'Chart', 'FormField', 'SDT', 'Comment', ); $functions = array(); foreach ($elements as $element) { $functions['add' . strtolower($element)] = $element == 'Object' ? 'OLEObject' : $element; } // Run valid `add` command $function = strtolower($function); if (isset($functions[$function])) { $element = $functions[$function]; // Special case for TextBreak // @todo Remove the `$count` parameter in 1.0.0 to make this element similiar to other elements? if ($element == 'TextBreak') { list($count, $fontStyle, $paragraphStyle) = array_pad($args, 3, null); if ($count === null) { $count = 1; } for ($i = 1; $i <= $count; $i++) { $this->addElement($element, $fontStyle, $paragraphStyle); } } else { // All other elements array_unshift($args, $element); // Prepend element name to the beginning of args array return call_user_func_array(array($this, 'addElement'), $args); } } return null; } /** * Add element * * Each element has different number of parameters passed * * @param string $elementName * @return \PhpOffice\PhpWord\Element\AbstractElement */ protected function addElement($elementName) { $elementClass = __NAMESPACE__ . '\\' . $elementName; $this->checkValidity($elementName); // Get arguments $args = func_get_args(); $withoutP = in_array($this->container, array('TextRun', 'Footnote', 'Endnote', 'ListItemRun', 'Field')); if ($withoutP && ($elementName == 'Text' || $elementName == 'PreserveText')) { $args[3] = null; // Remove paragraph style for texts in textrun } // Create element using reflection $reflection = new \ReflectionClass($elementClass); $elementArgs = $args; array_shift($elementArgs); // Shift the $elementName off the beginning of array /** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */ $element = $reflection->newInstanceArgs($elementArgs); // Set parent container $element->setParentContainer($this); $element->setElementIndex($this->countElements() + 1); $element->setElementId(); $this->elements[] = $element; return $element; } /** * Get all elements * * @return \PhpOffice\PhpWord\Element\AbstractElement[] */ public function getElements() { return $this->elements; } /** * Returns the element at the requested position * * @param int $index * @return \PhpOffice\PhpWord\Element\AbstractElement|null */ public function getElement($index) { if (array_key_exists($index, $this->elements)) { return $this->elements[$index]; } return null; } /** * Removes the element at requested index * * @param int|\PhpOffice\PhpWord\Element\AbstractElement $toRemove */ public function removeElement($toRemove) { if (is_int($toRemove) && array_key_exists($toRemove, $this->elements)) { unset($this->elements[$toRemove]); } elseif ($toRemove instanceof \PhpOffice\PhpWord\Element\AbstractElement) { foreach ($this->elements as $key => $element) { if ($element->getElementId() === $toRemove->getElementId()) { unset($this->elements[$key]); return; } } } } /** * Count elements * * @return int */ public function countElements() { return count($this->elements); } /** * Check if a method is allowed for the current container * * @param string $method * * @throws \BadMethodCallException * @return bool */ private function checkValidity($method) { $generalContainers = array( 'Section', 'Header', 'Footer', 'Footnote', 'Endnote', 'Cell', 'TextRun', 'TextBox', 'ListItemRun', 'TrackChange', ); $validContainers = array( 'Text' => $generalContainers, 'Bookmark' => $generalContainers, 'Link' => $generalContainers, 'TextBreak' => $generalContainers, 'Image' => $generalContainers, 'OLEObject' => $generalContainers, 'Field' => $generalContainers, 'Line' => $generalContainers, 'Shape' => $generalContainers, 'FormField' => $generalContainers, 'SDT' => $generalContainers, 'TrackChange' => $generalContainers, 'TextRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox', 'TrackChange', 'ListItemRun'), 'ListItem' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), 'ListItemRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), 'Table' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), 'CheckBox' => array('Section', 'Header', 'Footer', 'Cell', 'TextRun'), 'TextBox' => array('Section', 'Header', 'Footer', 'Cell'), 'Footnote' => array('Section', 'TextRun', 'Cell', 'ListItemRun'), 'Endnote' => array('Section', 'TextRun', 'Cell'), 'PreserveText' => array('Section', 'Header', 'Footer', 'Cell'), 'Title' => array('Section', 'Cell'), 'TOC' => array('Section'), 'PageBreak' => array('Section'), 'Chart' => array('Section', 'Cell'), ); // Special condition, e.g. preservetext can only exists in cell when // the cell is located in header or footer $validSubcontainers = array( 'PreserveText' => array(array('Cell'), array('Header', 'Footer', 'Section')), 'Footnote' => array(array('Cell', 'TextRun'), array('Section')), 'Endnote' => array(array('Cell', 'TextRun'), array('Section')), ); // Check if a method is valid for current container if (isset($validContainers[$method])) { if (!in_array($this->container, $validContainers[$method])) { throw new \BadMethodCallException("Cannot add {$method} in {$this->container}."); } } // Check if a method is valid for current container, located in other container if (isset($validSubcontainers[$method])) { $rules = $validSubcontainers[$method]; $containers = $rules[0]; $allowedDocParts = $rules[1]; foreach ($containers as $container) { if ($this->container == $container && !in_array($this->getDocPart(), $allowedDocParts)) { throw new \BadMethodCallException("Cannot add {$method} in {$this->container}."); } } } return true; } /** * Create textrun element * * @deprecated 0.10.0 * * @param mixed $paragraphStyle * * @return \PhpOffice\PhpWord\Element\TextRun * * @codeCoverageIgnore */ public function createTextRun($paragraphStyle = null) { return $this->addTextRun($paragraphStyle); } /** * Create footnote element * * @deprecated 0.10.0 * * @param mixed $paragraphStyle * * @return \PhpOffice\PhpWord\Element\Footnote * * @codeCoverageIgnore */ public function createFootnote($paragraphStyle = null) { return $this->addFootnote($paragraphStyle); } }
keithbox/AngularJS-CRUD-PHP
vendor/phpoffice/phpword/src/PhpWord/Element/AbstractContainer.php
PHP
mit
11,930
using OfficeDevPnP.MSGraphAPIDemo.Components; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using OfficeDevPnP.MSGraphAPIDemo.Models; using System.Threading; namespace OfficeDevPnP.MSGraphAPIDemo.Controllers { public class FilesController : Controller { // GET: Files public ActionResult Index() { return View(); } public ActionResult PlayWithFiles() { var drive = FilesHelper.GetUserPersonalDrive(); var root = FilesHelper.GetUserPersonalDriveRoot(); var childrenItems = FilesHelper.ListFolderChildren(drive.Id, root.Id); var newFileOnRoot = UploadSampleFile(drive, root, Server.MapPath("~/AppIcon.png")); // Collect information about children items in the root folder StringBuilder sb = new StringBuilder(); String oneFolderId = null; foreach (var item in childrenItems) { if (item.Folder != null) { sb.AppendFormat("Found folder {0} with {1} child items.\n", item.Name, item.Folder.ChildCount); if (item.Name == "One Folder") { oneFolderId = item.Id; } } else { sb.AppendFormat("Found file {0}.\n", item.Name); } } var filesLog = sb.ToString(); // Create a new folder in the root folder var newFolder = FilesHelper.CreateFolder(drive.Id, root.Id, new Models.DriveItem { Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}", Folder = new Models.Folder { }, }); var newFile = UploadSampleFile(drive, newFolder, Server.MapPath("~/AppIcon.png")); UpdateSampleFile(drive, newFile, Server.MapPath("~/SP2016-MinRoles.jpg")); // Create another folder in the root folder var anotherFolder = FilesHelper.CreateFolder(drive.Id, root.Id, new Models.DriveItem { Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}", Folder = new Models.Folder { }, }); var movedItem = FilesHelper.MoveDriveItem(drive.Id, newFile.Id, "moved.jpg", anotherFolder.Name); var movedFolder = FilesHelper.MoveDriveItem(drive.Id, anotherFolder.Id, "Moved Folder", newFolder.Name); var searchResult = FilesHelper.Search("PnPLogo", drive.Id, root.Id); if (searchResult != null && searchResult.Count > 0) { var firstFileResult = searchResult.FirstOrDefault(i => i.File != null); try { var thumbnails = FilesHelper.GetFileThumbnails(drive.Id, firstFileResult.Id); var thumbnailMedium = FilesHelper.GetFileThumbnail(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium); var thumbnailImage = FilesHelper.GetFileThumbnailImage(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium); } catch (Exception) { // Something wrong while getting the thumbnail, // We will have to handle it properly ... } } if (newFileOnRoot != null) { var permission = FilesHelper.GetDriveItemPermission(newFileOnRoot.Id, "0"); FilesHelper.DeleteFile(drive.Id, newFileOnRoot.Id); } try { var sharingPermission = FilesHelper.CreateSharingLink(newFolder.Id, SharingLinkType.View, SharingLinkScope.Anonymous); } catch (Exception) { // Something wrong while getting the sharing link, // We will have to handle it properly ... } if (!String.IsNullOrEmpty(oneFolderId)) { var newFolderChildren = FilesHelper.ListFolderChildren(drive.Id, newFolder.Id); var file = newFolderChildren.FirstOrDefault(f => f.Name == "moved.jpg"); if (file != null) { String jpegContentType = "image/jpeg"; Stream fileContent = FilesHelper.GetFileContent(drive.Id, file.Id, jpegContentType); return (base.File(fileContent, jpegContentType, file.Name)); } } return View("Index"); } private Models.DriveItem UploadSampleFile(Models.Drive drive, Models.DriveItem newFolder, String filePath) { Models.DriveItem result = null; Stream memPhoto = getFileContent(filePath); try { if (memPhoto.Length > 0) { String contentType = "image/png"; result = FilesHelper.UploadFile(drive.Id, newFolder.Id, new Models.DriveItem { File = new Models.File { }, Name = "PnPLogo.png", ConflictBehavior = "rename", }, memPhoto, contentType); } } catch (Exception ex) { // Handle the exception } return (result); } private void UpdateSampleFile(Drive drive, DriveItem newFile, String filePath) { FilesHelper.RenameFile(drive.Id, newFile.Id, "SP2016-MinRoles.jpg"); Stream memPhoto = getFileContent(filePath); try { if (memPhoto.Length > 0) { String contentType = "image/jpeg"; FilesHelper.UpdateFileContent( drive.Id, newFile.Id, memPhoto, contentType); } } catch (Exception ex) { // Handle the exception } } private static Stream getFileContent(String filePath) { MemoryStream memPhoto = new MemoryStream(); using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { Byte[] newPhoto = new Byte[fs.Length]; fs.Read(newPhoto, 0, (Int32)(fs.Length - 1)); memPhoto.Write(newPhoto, 0, newPhoto.Length); memPhoto.Position = 0; } return memPhoto; } } }
comblox/PnP
Samples/MicrosoftGraph.Office365.Generic/OfficeDevPnP.MSGraphAPIDemo/Controllers/FilesController.cs
C#
mit
6,983
/* @flow */ /*eslint-disable no-undef, no-unused-vars, no-console*/ import _, { compose, pipe, curry, filter, find, isNil, repeat, replace, zipWith } from "ramda"; import { describe, it } from 'flow-typed-test'; const ns: Array<number> = [1, 2, 3, 4, 5]; const ss: Array<string> = ["one", "two", "three", "four"]; const obj: { [k: string]: number } = { a: 1, c: 2 }; const objMixed: { [k: string]: mixed } = { a: 1, c: "d" }; const os: Array<{ [k: string]: * }> = [{ a: 1, c: "d" }, { b: 2 }]; const str: string = "hello world"; // Math { const partDiv: (a: number) => number = _.divide(6); const div: number = _.divide(6, 2); //$FlowExpectedError const div2: number = _.divide(6, true); } // String { const ss: Array<string | void> = _.match(/h/, "b"); describe('replace', () => { it('should supports replace by string', () => { const r1: string = replace(",", "|", "b,d,d"); const r2: string = replace(",")("|", "b,d,d"); const r3: string = replace(",")("|")("b,d,d"); const r4: string = replace(",", "|")("b,d,d"); }); it('should supports replace by RegExp', () => { const r1: string = replace(/[,]/, "|", "b,d,d"); const r2: string = replace(/[,]/)("|", "b,d,d"); const r3: string = replace(/[,]/)("|")("b,d,d"); const r4: string = replace(/[,]/, "|")("b,d,d"); }); it('should supports replace by RegExp with replacement fn', () => { const fn = (match: string, g1: string): string => g1; const r1: string = replace(/([,])d/, fn, "b,d,d"); const r2: string = replace(/([,])d/)(fn, "b,d,d"); const r3: string = replace(/([,])d/)(fn)("b,d,d"); const r4: string = replace(/([,])d/, fn)("b,d,d"); }); }); const ss2: Array<string> = _.split(",", "b,d,d"); const ss1: boolean = _.test(/h/, "b"); const s: string = _.trim("s"); const x: string = _.head("one"); const sss: string = _.concat("H", "E"); const sss1: string = _.concat("H")("E"); const ssss: string = _.drop(1, "EF"); const ssss1: string = _.drop(1)("E"); const ssss2: string = _.dropLast(1, "EF"); const ys: string = _.nth(2, "curry"); const ys1: string = _.nth(2)("curry"); } //Type { const x: boolean = _.is(Number, 1); const x1: boolean = isNil(1); // should refine type const x1a: ?{ a: number } = { a: 1 }; //$FlowExpectedError x1a.a; if (!isNil(x1a)) { x1a.a; } const x2: boolean = _.propIs(1, "num", { num: 1 }); }
flowtype/flow-typed
definitions/npm/ramda_v0.27.x/flow_v0.76.x-v0.103.x/test_ramda_v0.27.x_misc.js
JavaScript
mit
2,464
""" A directive for including a matplotlib plot in a Sphinx document. By default, in HTML output, `plot` will include a .png file with a link to a high-res .png and .pdf. In LaTeX output, it will include a .pdf. The source code for the plot may be included in one of three ways: 1. **A path to a source file** as the argument to the directive:: .. plot:: path/to/plot.py When a path to a source file is given, the content of the directive may optionally contain a caption for the plot:: .. plot:: path/to/plot.py This is the caption for the plot Additionally, one my specify the name of a function to call (with no arguments) immediately after importing the module:: .. plot:: path/to/plot.py plot_function1 2. Included as **inline content** to the directive:: .. plot:: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np img = mpimg.imread('_static/stinkbug.png') imgplot = plt.imshow(img) 3. Using **doctest** syntax:: .. plot:: A plotting example: >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3], [4,5,6]) Options ------- The ``plot`` directive supports the following options: format : {'python', 'doctest'} Specify the format of the input include-source : bool Whether to display the source code. The default can be changed using the `plot_include_source` variable in conf.py encoding : str If this source file is in a non-UTF8 or non-ASCII encoding, the encoding must be specified using the `:encoding:` option. The encoding will not be inferred using the ``-*- coding -*-`` metacomment. context : bool If provided, the code will be run in the context of all previous plot directives for which the `:context:` option was specified. This only applies to inline code plot directives, not those run from files. nofigs : bool If specified, the code block will be run, but no figures will be inserted. This is usually useful with the ``:context:`` option. Additionally, this directive supports all of the options of the `image` directive, except for `target` (since plot will add its own target). These include `alt`, `height`, `width`, `scale`, `align` and `class`. Configuration options --------------------- The plot directive has the following configuration options: plot_include_source Default value for the include-source option plot_pre_code Code that should be executed before each plot. plot_basedir Base directory, to which ``plot::`` file names are relative to. (If None or empty, file names are relative to the directoly where the file containing the directive is.) plot_formats File formats to generate. List of tuples or strings:: [(suffix, dpi), suffix, ...] that determine the file format and the DPI. For entries whose DPI was omitted, sensible defaults are chosen. plot_html_show_formats Whether to show links to the files in HTML. plot_rcparams A dictionary containing any non-standard rcParams that should be applied before each plot. plot_apply_rcparams By default, rcParams are applied when `context` option is not used in a plot directive. This configuration option overrides this behaviour and applies rcParams before each plot. plot_working_directory By default, the working directory will be changed to the directory of the example, so the code can get at its data files, if any. Also its path will be added to `sys.path` so it can import any helper modules sitting beside it. This configuration option can be used to specify a central directory (also added to `sys.path`) where data files and helper modules for all code are located. plot_template Provide a customized template for preparing resturctured text. """ from __future__ import print_function import sys, os, glob, shutil, imp, warnings, cStringIO, re, textwrap import traceback from docutils.parsers.rst import directives from docutils import nodes from docutils.parsers.rst.directives.images import Image align = Image.align import sphinx sphinx_version = sphinx.__version__.split(".") # The split is necessary for sphinx beta versions where the string is # '6b1' sphinx_version = tuple([int(re.split('[a-z]', x)[0]) for x in sphinx_version[:2]]) try: # Sphinx depends on either Jinja or Jinja2 import jinja2 def format_template(template, **kw): return jinja2.Template(template).render(**kw) except ImportError: import jinja def format_template(template, **kw): return jinja.from_string(template, **kw) import matplotlib import matplotlib.cbook as cbook matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib import _pylab_helpers __version__ = 2 #------------------------------------------------------------------------------ # Relative pathnames #------------------------------------------------------------------------------ # os.path.relpath is new in Python 2.6 try: from os.path import relpath except ImportError: # Copied from Python 2.7 if 'posix' in sys.builtin_module_names: def relpath(path, start=os.path.curdir): """Return a relative version of a path""" from os.path import sep, curdir, join, abspath, commonprefix, \ pardir if not path: raise ValueError("no path specified") start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) # Work out how much of the filepath is shared by start and path. i = len(commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) elif 'nt' in sys.builtin_module_names: def relpath(path, start=os.path.curdir): """Return a relative version of a path""" from os.path import sep, curdir, join, abspath, commonprefix, \ pardir, splitunc if not path: raise ValueError("no path specified") start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) if start_list[0].lower() != path_list[0].lower(): unc_path, rest = splitunc(path) unc_start, rest = splitunc(start) if bool(unc_path) ^ bool(unc_start): raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_list[0], start_list[0])) # Work out how much of the filepath is shared by start and path. for i in range(min(len(start_list), len(path_list))): if start_list[i].lower() != path_list[i].lower(): break else: i += 1 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) else: raise RuntimeError("Unsupported platform (no relpath available!)") #------------------------------------------------------------------------------ # Registration hook #------------------------------------------------------------------------------ def plot_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(arguments, content, options, state_machine, state, lineno) plot_directive.__doc__ = __doc__ def _option_boolean(arg): if not arg or not arg.strip(): # no argument given, assume used as a flag return True elif arg.strip().lower() in ('no', '0', 'false'): return False elif arg.strip().lower() in ('yes', '1', 'true'): return True else: raise ValueError('"%s" unknown boolean' % arg) def _option_format(arg): return directives.choice(arg, ('python', 'doctest')) def _option_align(arg): return directives.choice(arg, ("top", "middle", "bottom", "left", "center", "right")) def mark_plot_labels(app, document): """ To make plots referenceable, we need to move the reference from the "htmlonly" (or "latexonly") node to the actual figure node itself. """ for name, explicit in document.nametypes.iteritems(): if not explicit: continue labelid = document.nameids[name] if labelid is None: continue node = document.ids[labelid] if node.tagname in ('html_only', 'latex_only'): for n in node: if n.tagname == 'figure': sectname = name for c in n: if c.tagname == 'caption': sectname = c.astext() break node['ids'].remove(labelid) node['names'].remove(name) n['ids'].append(labelid) n['names'].append(name) document.settings.env.labels[name] = \ document.settings.env.docname, labelid, sectname break def setup(app): setup.app = app setup.config = app.config setup.confdir = app.confdir options = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': _option_align, 'class': directives.class_option, 'include-source': _option_boolean, 'format': _option_format, 'context': directives.flag, 'nofigs': directives.flag, 'encoding': directives.encoding } app.add_directive('plot', plot_directive, True, (0, 2, False), **options) app.add_config_value('plot_pre_code', None, True) app.add_config_value('plot_include_source', False, True) app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True) app.add_config_value('plot_basedir', None, True) app.add_config_value('plot_html_show_formats', True, True) app.add_config_value('plot_rcparams', {}, True) app.add_config_value('plot_apply_rcparams', False, True) app.add_config_value('plot_working_directory', None, True) app.add_config_value('plot_template', None, True) app.connect('doctree-read', mark_plot_labels) #------------------------------------------------------------------------------ # Doctest handling #------------------------------------------------------------------------------ def contains_doctest(text): try: # check if it's valid Python as-is compile(text, '<string>', 'exec') return False except SyntaxError: pass r = re.compile(r'^\s*>>>', re.M) m = r.search(text) return bool(m) def unescape_doctest(text): """ Extract code from a piece of text, which contains either Python code or doctests. """ if not contains_doctest(text): return text code = "" for line in text.split("\n"): m = re.match(r'^\s*(>>>|\.\.\.) (.*)$', line) if m: code += m.group(2) + "\n" elif line.strip(): code += "# " + line.strip() + "\n" else: code += "\n" return code def split_code_at_show(text): """ Split code at plt.show() """ parts = [] is_doctest = contains_doctest(text) part = [] for line in text.split("\n"): if (not is_doctest and line.strip() == 'plt.show()') or \ (is_doctest and line.strip() == '>>> plt.show()'): part.append(line) parts.append("\n".join(part)) part = [] else: part.append(line) if "\n".join(part).strip(): parts.append("\n".join(part)) return parts #------------------------------------------------------------------------------ # Template #------------------------------------------------------------------------------ TEMPLATE = """ {{ source_code }} {{ only_html }} {% if source_link or (html_show_formats and not multi_image) %} ( {%- if source_link -%} `Source code <{{ source_link }}>`__ {%- endif -%} {%- if html_show_formats and not multi_image -%} {%- for img in images -%} {%- for fmt in img.formats -%} {%- if source_link or not loop.first -%}, {% endif -%} `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ {%- endfor -%} {%- endfor -%} {%- endif -%} ) {% endif %} {% for img in images %} .. figure:: {{ build_dir }}/{{ img.basename }}.png {%- for option in options %} {{ option }} {% endfor %} {% if html_show_formats and multi_image -%} ( {%- for fmt in img.formats -%} {%- if not loop.first -%}, {% endif -%} `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ {%- endfor -%} ) {%- endif -%} {{ caption }} {% endfor %} {{ only_latex }} {% for img in images %} .. image:: {{ build_dir }}/{{ img.basename }}.pdf {% endfor %} {{ only_texinfo }} {% for img in images %} .. image:: {{ build_dir }}/{{ img.basename }}.png {%- for option in options %} {{ option }} {% endfor %} {% endfor %} """ exception_template = """ .. htmlonly:: [`source code <%(linkdir)s/%(basename)s.py>`__] Exception occurred rendering plot. """ # the context of the plot for all directives specified with the # :context: option plot_context = dict() class ImageFile(object): def __init__(self, basename, dirname): self.basename = basename self.dirname = dirname self.formats = [] def filename(self, format): return os.path.join(self.dirname, "%s.%s" % (self.basename, format)) def filenames(self): return [self.filename(fmt) for fmt in self.formats] def out_of_date(original, derived): """ Returns True if derivative is out-of-date wrt original, both of which are full file paths. """ return (not os.path.exists(derived) or (os.path.exists(original) and os.stat(derived).st_mtime < os.stat(original).st_mtime)) class PlotError(RuntimeError): pass def run_code(code, code_path, ns=None, function_name=None): """ Import a Python module from a path, and run the function given by name, if function_name is not None. """ # Change the working directory to the directory of the example, so # it can get at its data files, if any. Add its path to sys.path # so it can import any helper modules sitting beside it. pwd = os.getcwd() old_sys_path = list(sys.path) if setup.config.plot_working_directory is not None: try: os.chdir(setup.config.plot_working_directory) except OSError as err: raise OSError(str(err) + '\n`plot_working_directory` option in' 'Sphinx configuration file must be a valid ' 'directory path') except TypeError as err: raise TypeError(str(err) + '\n`plot_working_directory` option in ' 'Sphinx configuration file must be a string or ' 'None') sys.path.insert(0, setup.config.plot_working_directory) elif code_path is not None: dirname = os.path.abspath(os.path.dirname(code_path)) os.chdir(dirname) sys.path.insert(0, dirname) # Redirect stdout stdout = sys.stdout sys.stdout = cStringIO.StringIO() # Reset sys.argv old_sys_argv = sys.argv sys.argv = [code_path] try: try: code = unescape_doctest(code) if ns is None: ns = {} if not ns: if setup.config.plot_pre_code is None: exec "import numpy as np\nfrom matplotlib import pyplot as plt\n" in ns else: exec setup.config.plot_pre_code in ns if "__main__" in code: exec "__name__ = '__main__'" in ns exec code in ns if function_name is not None: exec function_name + "()" in ns except (Exception, SystemExit), err: raise PlotError(traceback.format_exc()) finally: os.chdir(pwd) sys.argv = old_sys_argv sys.path[:] = old_sys_path sys.stdout = stdout return ns def clear_state(plot_rcparams): plt.close('all') matplotlib.rc_file_defaults() matplotlib.rcParams.update(plot_rcparams) def render_figures(code, code_path, output_dir, output_base, context, function_name, config): """ Run a pyplot script and save the low and high res PNGs and a PDF in outdir. Save the images under *output_dir* with file names derived from *output_base* """ # -- Parse format list default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200} formats = [] plot_formats = config.plot_formats if isinstance(plot_formats, (str, unicode)): plot_formats = eval(plot_formats) for fmt in plot_formats: if isinstance(fmt, str): formats.append((fmt, default_dpi.get(fmt, 80))) elif type(fmt) in (tuple, list) and len(fmt)==2: formats.append((str(fmt[0]), int(fmt[1]))) else: raise PlotError('invalid image format "%r" in plot_formats' % fmt) # -- Try to determine if all images already exist code_pieces = split_code_at_show(code) # Look for single-figure output files first # Look for single-figure output files first all_exists = True img = ImageFile(output_base, output_dir) for format, dpi in formats: if out_of_date(code_path, img.filename(format)): all_exists = False break img.formats.append(format) if all_exists: return [(code, [img])] # Then look for multi-figure output files results = [] all_exists = True for i, code_piece in enumerate(code_pieces): images = [] for j in xrange(1000): if len(code_pieces) > 1: img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir) else: img = ImageFile('%s_%02d' % (output_base, j), output_dir) for format, dpi in formats: if out_of_date(code_path, img.filename(format)): all_exists = False break img.formats.append(format) # assume that if we have one, we have them all if not all_exists: all_exists = (j > 0) break images.append(img) if not all_exists: break results.append((code_piece, images)) if all_exists: return results # We didn't find the files, so build them results = [] if context: ns = plot_context else: ns = {} for i, code_piece in enumerate(code_pieces): if not context or config.plot_apply_rcparams: clear_state(config.plot_rcparams) run_code(code_piece, code_path, ns, function_name) images = [] fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() for j, figman in enumerate(fig_managers): if len(fig_managers) == 1 and len(code_pieces) == 1: img = ImageFile(output_base, output_dir) elif len(code_pieces) == 1: img = ImageFile("%s_%02d" % (output_base, j), output_dir) else: img = ImageFile("%s_%02d_%02d" % (output_base, i, j), output_dir) images.append(img) for format, dpi in formats: try: figman.canvas.figure.savefig(img.filename(format), dpi=dpi) except Exception,err: raise PlotError(traceback.format_exc()) img.formats.append(format) results.append((code_piece, images)) if not context or config.plot_apply_rcparams: clear_state(config.plot_rcparams) return results def run(arguments, content, options, state_machine, state, lineno): # The user may provide a filename *or* Python code content, but not both if arguments and content: raise RuntimeError("plot:: directive can't have both args and content") document = state_machine.document config = document.settings.env.config nofigs = options.has_key('nofigs') options.setdefault('include-source', config.plot_include_source) context = options.has_key('context') rst_file = document.attributes['source'] rst_dir = os.path.dirname(rst_file) if len(arguments): if not config.plot_basedir: source_file_name = os.path.join(setup.app.builder.srcdir, directives.uri(arguments[0])) else: source_file_name = os.path.join(setup.confdir, config.plot_basedir, directives.uri(arguments[0])) # If there is content, it will be passed as a caption. caption = '\n'.join(content) # If the optional function name is provided, use it if len(arguments) == 2: function_name = arguments[1] else: function_name = None with open(source_file_name, 'r') as fd: code = fd.read() output_base = os.path.basename(source_file_name) else: source_file_name = rst_file code = textwrap.dedent("\n".join(map(str, content))) counter = document.attributes.get('_plot_counter', 0) + 1 document.attributes['_plot_counter'] = counter base, ext = os.path.splitext(os.path.basename(source_file_name)) output_base = '%s-%d.py' % (base, counter) function_name = None caption = '' base, source_ext = os.path.splitext(output_base) if source_ext in ('.py', '.rst', '.txt'): output_base = base else: source_ext = '' # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames output_base = output_base.replace('.', '-') # is it in doctest format? is_doctest = contains_doctest(code) if options.has_key('format'): if options['format'] == 'python': is_doctest = False else: is_doctest = True # determine output directory name fragment source_rel_name = relpath(source_file_name, setup.confdir) source_rel_dir = os.path.dirname(source_rel_name) while source_rel_dir.startswith(os.path.sep): source_rel_dir = source_rel_dir[1:] # build_dir: where to place output files (temporarily) build_dir = os.path.join(os.path.dirname(setup.app.doctreedir), 'plot_directive', source_rel_dir) # get rid of .. in paths, also changes pathsep # see note in Python docs for warning about symbolic links on Windows. # need to compare source and dest paths at end build_dir = os.path.normpath(build_dir) if not os.path.exists(build_dir): os.makedirs(build_dir) # output_dir: final location in the builder's directory dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir, source_rel_dir)) if not os.path.exists(dest_dir): os.makedirs(dest_dir) # no problem here for me, but just use built-ins # how to link to files from the RST file dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir), source_rel_dir).replace(os.path.sep, '/') build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/') source_link = dest_dir_link + '/' + output_base + source_ext # make figures try: results = render_figures(code, source_file_name, build_dir, output_base, context, function_name, config) errors = [] except PlotError, err: reporter = state.memo.reporter sm = reporter.system_message( 2, "Exception occurred in plotting %s\n from %s:\n%s" % (output_base, source_file_name, err), line=lineno) results = [(code, [])] errors = [sm] # Properly indent the caption caption = '\n'.join(' ' + line.strip() for line in caption.split('\n')) # generate output restructuredtext total_lines = [] for j, (code_piece, images) in enumerate(results): if options['include-source']: if is_doctest: lines = [''] lines += [row.rstrip() for row in code_piece.split('\n')] else: lines = ['.. code-block:: python', ''] lines += [' %s' % row.rstrip() for row in code_piece.split('\n')] source_code = "\n".join(lines) else: source_code = "" if nofigs: images = [] opts = [':%s: %s' % (key, val) for key, val in options.items() if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] only_html = ".. only:: html" only_latex = ".. only:: latex" only_texinfo = ".. only:: texinfo" if j == 0: src_link = source_link else: src_link = None result = format_template( config.plot_template or TEMPLATE, dest_dir=dest_dir_link, build_dir=build_dir_link, source_link=src_link, multi_image=len(images) > 1, only_html=only_html, only_latex=only_latex, only_texinfo=only_texinfo, options=opts, images=images, source_code=source_code, html_show_formats=config.plot_html_show_formats, caption=caption) total_lines.extend(result.split("\n")) total_lines.extend("\n") if total_lines: state_machine.insert_input(total_lines, source=source_file_name) # copy image files to builder's output directory, if necessary if not os.path.exists(dest_dir): cbook.mkdirs(dest_dir) for code_piece, images in results: for img in images: for fn in img.filenames(): destimg = os.path.join(dest_dir, os.path.basename(fn)) if fn != destimg: shutil.copyfile(fn, destimg) # copy script (if necessary) target_name = os.path.join(dest_dir, output_base + source_ext) with open(target_name, 'w') as f: if source_file_name == rst_file: code_escaped = unescape_doctest(code) else: code_escaped = code f.write(code_escaped) return errors
Solid-Mechanics/matplotlib-4-abaqus
matplotlib/sphinxext/plot_directive.py
Python
mit
27,667
/** * @author mrdoob / http://mrdoob.com/ * @author bhouston / http://exocortex.com/ */ ( function ( THREE ) { THREE.Raycaster = function ( origin, direction, near, far ) { this.ray = new THREE.Ray( origin, direction ); // normalized ray.direction required for accurate distance calculations if( this.ray.direction.lengthSq() > 0 ) { this.ray.direction.normalize(); } this.near = near || 0; this.far = far || Infinity; }; var sphere = new THREE.Sphere(); var localRay = new THREE.Ray(); var facePlane = new THREE.Plane(); var intersectPoint = new THREE.Vector3(); var matrixPosition = new THREE.Vector3(); var inverseMatrix = new THREE.Matrix4(); var descSort = function ( a, b ) { return a.distance - b.distance; }; var intersectObject = function ( object, raycaster, intersects ) { if ( object instanceof THREE.Particle ) { matrixPosition.getPositionFromMatrix( object.matrixWorld ); var distance = raycaster.ray.distanceToPoint( matrixPosition ); if ( distance > object.scale.x ) { return intersects; } intersects.push( { distance: distance, point: object.position, face: null, object: object } ); } else if ( object instanceof THREE.Mesh ) { // Checking boundingSphere distance to ray matrixPosition.getPositionFromMatrix( object.matrixWorld ); sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() ); if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) { return intersects; } // Checking faces var geometry = object.geometry; var vertices = geometry.vertices; var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; var objectMaterials = isFaceMaterial === true ? object.material.materials : null; var side = object.material.side; var a, b, c, d; var precision = raycaster.precision; object.matrixRotationWorld.extractRotation( object.matrixWorld ); inverseMatrix.getInverse( object.matrixWorld ); localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { var face = geometry.faces[ f ]; var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material; if ( material === undefined ) continue; facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] ); var planeDistance = localRay.distanceToPlane( facePlane ); // bail if raycaster and plane are parallel if ( Math.abs( planeDistance ) < precision ) continue; // if negative distance, then plane is behind raycaster if ( planeDistance < 0 ) continue; // check if we hit the wrong side of a single sided face side = material.side; if( side !== THREE.DoubleSide ) { var planeSign = localRay.direction.dot( facePlane.normal ); if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue; } // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue; intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy if ( face instanceof THREE.Face3 ) { a = vertices[ face.a ]; b = vertices[ face.b ]; c = vertices[ face.c ]; if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue; } else if ( face instanceof THREE.Face4 ) { a = vertices[ face.a ]; b = vertices[ face.b ]; c = vertices[ face.c ]; d = vertices[ face.d ]; if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) && ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue; } else { // This is added because if we call out of this if/else group when none of the cases // match it will add a point to the intersection list erroneously. throw Error( "face type not supported" ); } intersects.push( { distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't point: raycaster.ray.at( planeDistance ), face: face, faceIndex: f, object: object } ); } } }; var intersectDescendants = function ( object, raycaster, intersects ) { var descendants = object.getDescendants(); for ( var i = 0, l = descendants.length; i < l; i ++ ) { intersectObject( descendants[ i ], raycaster, intersects ); } }; // THREE.Raycaster.prototype.precision = 0.0001; THREE.Raycaster.prototype.set = function ( origin, direction ) { this.ray.set( origin, direction ); // normalized ray.direction required for accurate distance calculations if( this.ray.direction.length() > 0 ) { this.ray.direction.normalize(); } }; THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) { var intersects = []; if ( recursive === true ) { intersectDescendants( object, this, intersects ); } intersectObject( object, this, intersects ); intersects.sort( descSort ); return intersects; }; THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) { var intersects = []; for ( var i = 0, l = objects.length; i < l; i ++ ) { intersectObject( objects[ i ], this, intersects ); if ( recursive === true ) { intersectDescendants( objects[ i ], this, intersects ); } } intersects.sort( descSort ); return intersects; }; }( THREE ) );
DLar/three.js
src/core/Raycaster.js
JavaScript
mit
5,607
module Facter::Util::Virtual ## # virt_what is a delegating helper method intended to make it easier to stub # the system call without affecting other calls to # Facter::Util::Resolution.exec def self.virt_what(command = "virt-what") Facter::Util::Resolution.exec command end ## # lspci is a delegating helper method intended to make it easier to stub the # system call without affecting other calls to Facter::Util::Resolution.exec def self.lspci(command = "lspci 2>/dev/null") Facter::Util::Resolution.exec command end def self.openvz? FileTest.directory?("/proc/vz") and not self.openvz_cloudlinux? end # So one can either have #6728 work on OpenVZ or Cloudlinux. Whoo. def self.openvz_type return false unless self.openvz? return false unless FileTest.exists?( '/proc/self/status' ) envid = Facter::Util::Resolution.exec( 'grep "envID" /proc/self/status' ) if envid =~ /^envID:\s+0$/i return 'openvzhn' elsif envid =~ /^envID:\s+(\d+)$/i return 'openvzve' end end # Cloudlinux uses OpenVZ to a degree, but always has an empty /proc/vz/ and # has /proc/lve/list present def self.openvz_cloudlinux? FileTest.file?("/proc/lve/list") or Dir.glob('/proc/vz/*').empty? end def self.zone? return true if FileTest.directory?("/.SUNWnative") z = Facter::Util::Resolution.exec("/sbin/zonename") return false unless z return z.chomp != 'global' end def self.vserver? return false unless FileTest.exists?("/proc/self/status") txt = File.read("/proc/self/status") return true if txt =~ /^(s_context|VxID):[[:blank:]]*[0-9]/ return false end def self.vserver_type if self.vserver? if FileTest.exists?("/proc/virtual") "vserver_host" else "vserver" end end end def self.xen? ["/proc/sys/xen", "/sys/bus/xen", "/proc/xen" ].detect do |f| FileTest.exists?(f) end end def self.kvm? txt = if FileTest.exists?("/proc/cpuinfo") File.read("/proc/cpuinfo") elsif ["FreeBSD", "OpenBSD"].include? Facter.value(:kernel) Facter::Util::Resolution.exec("/sbin/sysctl -n hw.model") end (txt =~ /QEMU Virtual CPU/) ? true : false end def self.kvm_type # TODO Tell the difference between kvm and qemu # Can't work out a way to do this at the moment that doesn't # require a special binary "kvm" end def self.jail? path = case Facter.value(:kernel) when "FreeBSD" then "/sbin" when "GNU/kFreeBSD" then "/bin" end Facter::Util::Resolution.exec("#{path}/sysctl -n security.jail.jailed") == "1" end def self.hpvm? Facter::Util::Resolution.exec("/usr/bin/getconf MACHINE_MODEL").chomp =~ /Virtual Machine/ end def self.zlinux? "zlinux" end end
phatpenguin/boxen-belgarion
.bundle/ruby/1.9.1/gems/librarian-puppet-0.9.8/vendor/gems/ruby/1.9.1/gems/facter-1.6.17/lib/facter/util/virtual.rb
Ruby
mit
2,821
'use strict'; require('../../modules/es.weak-set'); require('../../modules/esnext.weak-set.from'); var WeakSet = require('../../internals/path').WeakSet; var weakSetfrom = WeakSet.from; module.exports = function from(source, mapFn, thisArg) { return weakSetfrom.call(typeof this === 'function' ? this : WeakSet, source, mapFn, thisArg); };
AntonyThorpe/knockout-apollo
tests/node_modules/core-js/features/weak-set/from.js
JavaScript
mit
343
/** @babel */ /** @jsx etch.dom **/ import etch from 'etch'; export default class WelcomeView { constructor(props) { this.props = props; etch.initialize(this); this.element.addEventListener('click', event => { const link = event.target.closest('a'); if (link && link.dataset.event) { this.props.reporterProxy.sendEvent( `clicked-welcome-${link.dataset.event}-link` ); } }); } didChangeShowOnStartup() { atom.config.set('welcome.showOnStartup', this.checked); } update() {} serialize() { return { deserializer: 'WelcomeView', uri: this.props.uri }; } render() { return ( <div className="welcome"> <div className="welcome-container"> <header className="welcome-header"> <a href="https://atom.io/"> <svg className="welcome-logo" width="330px" height="68px" viewBox="0 0 330 68" version="1.1" > <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" > <g transform="translate(2.000000, 1.000000)"> <g transform="translate(96.000000, 8.000000)" fill="currentColor" > <path d="M185.498,3.399 C185.498,2.417 186.34,1.573 187.324,1.573 L187.674,1.573 C188.447,1.573 189.01,1.995 189.5,2.628 L208.676,30.862 L227.852,2.628 C228.272,1.995 228.905,1.573 229.676,1.573 L230.028,1.573 C231.01,1.573 231.854,2.417 231.854,3.399 L231.854,49.403 C231.854,50.387 231.01,51.231 230.028,51.231 C229.044,51.231 228.202,50.387 228.202,49.403 L228.202,8.246 L210.151,34.515 C209.729,35.148 209.237,35.428 208.606,35.428 C207.973,35.428 207.481,35.148 207.061,34.515 L189.01,8.246 L189.01,49.475 C189.01,50.457 188.237,51.231 187.254,51.231 C186.27,51.231 185.498,50.458 185.498,49.475 L185.498,3.399 L185.498,3.399 Z" /> <path d="M113.086,26.507 L113.086,26.367 C113.086,12.952 122.99,0.941 137.881,0.941 C152.77,0.941 162.533,12.811 162.533,26.225 L162.533,26.367 C162.533,39.782 152.629,51.792 137.74,51.792 C122.85,51.792 113.086,39.923 113.086,26.507 M158.74,26.507 L158.74,26.367 C158.74,14.216 149.89,4.242 137.74,4.242 C125.588,4.242 116.879,14.075 116.879,26.225 L116.879,26.367 C116.879,38.518 125.729,48.491 137.881,48.491 C150.031,48.491 158.74,38.658 158.74,26.507" /> <path d="M76.705,5.155 L60.972,5.155 C60.06,5.155 59.287,4.384 59.287,3.469 C59.287,2.556 60.059,1.783 60.972,1.783 L96.092,1.783 C97.004,1.783 97.778,2.555 97.778,3.469 C97.778,4.383 97.005,5.155 96.092,5.155 L80.358,5.155 L80.358,49.405 C80.358,50.387 79.516,51.231 78.532,51.231 C77.55,51.231 76.706,50.387 76.706,49.405 L76.706,5.155 L76.705,5.155 Z" /> <path d="M0.291,48.562 L21.291,3.05 C21.783,1.995 22.485,1.292 23.75,1.292 L23.891,1.292 C25.155,1.292 25.858,1.995 26.348,3.05 L47.279,48.421 C47.49,48.843 47.56,49.194 47.56,49.546 C47.56,50.458 46.788,51.231 45.803,51.231 C44.961,51.231 44.329,50.599 43.978,49.826 L38.219,37.183 L9.21,37.183 L3.45,49.897 C3.099,50.739 2.538,51.231 1.694,51.231 C0.781,51.231 0.008,50.529 0.008,49.685 C0.009,49.404 0.08,48.983 0.291,48.562 L0.291,48.562 Z M36.673,33.882 L23.749,5.437 L10.755,33.882 L36.673,33.882 L36.673,33.882 Z" /> </g> <g> <path d="M40.363,32.075 C40.874,34.44 39.371,36.77 37.006,37.282 C34.641,37.793 32.311,36.29 31.799,33.925 C31.289,31.56 32.791,29.23 35.156,28.718 C37.521,28.207 39.851,29.71 40.363,32.075" fill="currentColor" /> <path d="M48.578,28.615 C56.851,45.587 58.558,61.581 52.288,64.778 C45.822,68.076 33.326,56.521 24.375,38.969 C15.424,21.418 13.409,4.518 19.874,1.221 C22.689,-0.216 26.648,1.166 30.959,4.629" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> <path d="M7.64,39.45 C2.806,36.94 -0.009,33.915 0.154,30.79 C0.531,23.542 16.787,18.497 36.462,19.52 C56.137,20.544 71.781,27.249 71.404,34.497 C71.241,37.622 68.127,40.338 63.06,42.333" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> <path d="M28.828,59.354 C23.545,63.168 18.843,64.561 15.902,62.653 C9.814,58.702 13.572,42.102 24.296,25.575 C35.02,9.048 48.649,-1.149 54.736,2.803 C57.566,4.639 58.269,9.208 57.133,15.232" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> </g> </g> </g> </svg> <h1 className="welcome-title"> A hackable text editor for the 21<sup>st</sup> Century </h1> </a> </header> <section className="welcome-panel"> <p>For help, please visit</p> <ul> <li> The{' '} <a href="https://www.atom.io/docs" dataset={{ event: 'atom-docs' }} > Atom docs </a>{' '} for Guides and the API reference. </li> <li> The Atom forum at{' '} <a href="https://github.com/atom/atom/discussions" dataset={{ event: 'discussions' }} > Github Discussions </a> </li> <li> The{' '} <a href="https://github.com/atom" dataset={{ event: 'atom-org' }} > Atom org </a> . This is where all GitHub-created Atom packages can be found. </li> </ul> </section> <section className="welcome-panel"> <label> <input className="input-checkbox" type="checkbox" checked={atom.config.get('welcome.showOnStartup')} onchange={this.didChangeShowOnStartup} /> Show Welcome Guide when opening Atom </label> </section> <footer className="welcome-footer"> <a href="https://atom.io/" dataset={{ event: 'footer-atom-io' }}> atom.io </a>{' '} <span className="text-subtle">×</span>{' '} <a className="icon icon-octoface" href="https://github.com/" dataset={{ event: 'footer-octocat' }} /> </footer> </div> </div> ); } getURI() { return this.props.uri; } getTitle() { return 'Welcome'; } isEqual(other) { return other instanceof WelcomeView; } }
PKRoma/atom
packages/welcome/lib/welcome-view.js
JavaScript
mit
7,386
/* * Copyright (c) 2014-2015 Håkan Edling * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * http://github.com/piranhacms/piranha.vnext * */ using System; using System.IO; namespace Piranha.IO { /// <summary> /// Interface for creating an media provider. /// </summary> public interface IMedia { /// <summary> /// Gets the binary data for the given media object. /// </summary> /// <param name="media">The media object</param> /// <returns>The binary data</returns> byte[] Get(Models.Media media); /// <summary> /// Saves the given binary data for the given media object. /// </summary> /// <param name="media">The media object</param> /// <param name="bytes">The binary data</param> void Put(Models.Media media, byte[] bytes); /// <summary> /// Saves the binary data available in the stream in the /// given media object. /// </summary> /// <param name="media">The media object</param> /// <param name="stream">The stream</param> void Put(Models.Media media, Stream stream); /// <summary> /// Deletes the binary data for the given media object. /// </summary> /// <param name="media">The media object</param> void Delete(Models.Media media); } }
mysticmind/Piranha.vNext
Core/Piranha/IO/IMedia.cs
C#
mit
1,345
<?php namespace PragmaRX\Tracker\Data\Repositories; use PragmaRX\Tracker\Support\RefererParser; class Referer extends Repository { /** * @var RefererParser */ private $refererParser; /** * @var */ private $currentUrl; /** * @var */ private $searchTermModel; /** * Create repository instance. * * @param RefererParser $refererParser */ public function __construct($model, $searchTermModel, $currentUrl, RefererParser $refererParser) { parent::__construct($model); $this->refererParser = $refererParser; $this->currentUrl = $currentUrl; $this->searchTermModel = $searchTermModel; } /** * @param $refererUrl * @param $host * @param $domain_id * @return mixed */ public function store($refererUrl, $host, $domain_id) { $attributes = array( 'url' => $refererUrl, 'host' => $host, 'domain_id' => $domain_id, 'medium' => null, 'source' => null, 'search_terms_hash' => null ); $parsed = $this->refererParser->parse($refererUrl, $this->currentUrl); if ($parsed->isKnown()) { $attributes['medium'] = $parsed->getMedium(); $attributes['source'] = $parsed->getSource(); $attributes['search_terms_hash'] = sha1($parsed->getSearchTerm()); } $referer = $this->findOrCreate( $attributes, array('url', 'search_terms_hash') ); $referer = $this->find($referer); if ($parsed->isKnown()) { $this->storeSearchTerms($referer, $parsed); } return $referer->id; } private function storeSearchTerms($referer, $parsed) { foreach (explode(' ', $parsed->getSearchTerm()) as $term) { $this->findOrCreate( array( 'referer_id' => $referer->id, 'search_term' => $term ), array('referer_id', 'search_term'), $created, $this->searchTermModel ); } } }
ssv445/tracker
src/Data/Repositories/Referer.php
PHP
mit
1,894
'use strict'; angular.module('sw.plugin.split', ['sw.plugins']) .factory('split', function ($q) { return { execute: execute }; function execute (url, swagger) { var deferred = $q.defer(); if (swagger && swagger.swagger && !swagger.tags) { var tags = {}; angular.forEach(swagger.paths, function (path, key) { var t = key.replace(/^\/?([^\/]+).*$/g, '$1'); tags[t] = true; angular.forEach(path, function (method) { if (!method.tags || !method.tags.length) { method.tags = [t]; } }); }); swagger.tags = []; Object.keys(tags).forEach(function (tag) { swagger.tags.push({name: tag}); }); } deferred.resolve(true); return deferred.promise; } }) .run(function (plugins, split) { plugins.add(plugins.BEFORE_PARSE, split); });
darosh/angular-swagger-ui-material
src/plugins/before-parse/split.js
JavaScript
mit
1,127
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.Engine.Incrementals { public sealed class ProcessorStepInfo { /// <summary> /// The name of processor step. /// </summary> public string Name { get; set; } /// <summary> /// The context hash for incremental. /// </summary> public string IncrementalContextHash { get; set; } /// <summary> /// The file link for context info. /// </summary> public string ContextInfoFile { get; set; } public override bool Equals(object obj) { var another = obj as ProcessorStepInfo; if (another == null) { return false; } return Name == another.Name && IncrementalContextHash == another.IncrementalContextHash; } public override int GetHashCode() { return Name?.GetHashCode() ?? 0; } } }
DuncanmaMSFT/docfx
src/Microsoft.DocAsCode.Build.Engine/Incrementals/ProcessorStepInfo.cs
C#
mit
1,123
/*----------------------------------------------------------------------------------- /* /* Main JS /* -----------------------------------------------------------------------------------*/ (function($) { /*---------------------------------------------------- */ /* Preloader ------------------------------------------------------ */ $(window).load(function() { // will first fade out the loading animation $("#status").fadeOut("slow"); // will fade out the whole DIV that covers the website. $("#preloader").delay(500).fadeOut("slow").remove(); $('.js #hero .hero-image img').addClass("animated fadeInUpBig"); $('.js #hero .buttons a.trial').addClass("animated shake"); }) /*---------------------------------------------------- */ /* Mobile Menu ------------------------------------------------------ */ var toggle_button = $("<a>", { id: "toggle-btn", html : "Menu", title: "Menu", href : "#" } ); var nav_wrap = $('nav#nav-wrap') var nav = $("ul#nav"); /* id JS is enabled, remove the two a.mobile-btns and dynamically prepend a.toggle-btn to #nav-wrap */ nav_wrap.find('a.mobile-btn').remove(); nav_wrap.prepend(toggle_button); toggle_button.on("click", function(e) { e.preventDefault(); nav.slideToggle("fast"); }); if (toggle_button.is(':visible')) nav.addClass('mobile'); $(window).resize(function(){ if (toggle_button.is(':visible')) nav.addClass('mobile'); else nav.removeClass('mobile'); }); $('ul#nav li a').on("click", function(){ if (nav.hasClass('mobile')) nav.fadeOut('fast'); }); /*----------------------------------------------------*/ /* FitText Settings ------------------------------------------------------ */ setTimeout(function() { $('h1.responsive-headline').fitText(1.2, { minFontSize: '25px', maxFontSize: '40px' }); }, 100); /*----------------------------------------------------*/ /* Smooth Scrolling ------------------------------------------------------ */ $('.smoothscroll').on('click', function (e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 800, 'swing', function () { window.location.hash = target; }); }); /*----------------------------------------------------*/ /* Highlight the current section in the navigation bar ------------------------------------------------------*/ var sections = $("section"), navigation_links = $("#nav-wrap a"); sections.waypoint( { handler: function(event, direction) { var active_section; active_section = $(this); if (direction === "up") active_section = active_section.prev(); var active_link = $('#nav-wrap a[href="#' + active_section.attr("id") + '"]'); navigation_links.parent().removeClass("current"); active_link.parent().addClass("current"); }, offset: '35%' }); /*----------------------------------------------------*/ /* FitVids /*----------------------------------------------------*/ $(".fluid-video-wrapper").fitVids(); /*----------------------------------------------------*/ /* Waypoints Animations ------------------------------------------------------ */ $('.js .design').waypoint(function() { $('.js .design .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .responsive').waypoint(function() { $('.js .responsive .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .cross-browser').waypoint(function() { $('.js .cross-browser .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .video').waypoint(function() { $('.js .video .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js #subscribe').waypoint(function() { $('.js #subscribe input[type="email"]').addClass( 'animated fadeInLeftBig show' ); $('.js #subscribe input[type="submit"]').addClass( 'animated fadeInRightBig show' ); }, { offset: 'bottom-in-view' }); /*----------------------------------------------------*/ /* Flexslider /*----------------------------------------------------*/ $('.flexslider').flexslider({ namespace: "flex-", controlsContainer: ".flex-container", animation: 'slide', controlNav: true, directionNav: false, smoothHeight: true, slideshowSpeed: 7000, animationSpeed: 600, randomize: false, }); /*----------------------------------------------------*/ /* ImageLightbox /*----------------------------------------------------*/ if($("html").hasClass('cssanimations')) { var activityIndicatorOn = function() { $( '<div id="imagelightbox-loading"><div></div></div>' ).appendTo( 'body' ); }, activityIndicatorOff = function() { $( '#imagelightbox-loading' ).remove(); }, overlayOn = function() { $( '<div id="imagelightbox-overlay"></div>' ).appendTo( 'body' ); }, overlayOff = function() { $( '#imagelightbox-overlay' ).remove(); }, closeButtonOn = function( instance ) { $( '<a href="#" id="imagelightbox-close" title="close"><i class="fa fa fa-times"></i></a>' ).appendTo( 'body' ).on( 'click touchend', function(){ $( this ).remove(); instance.quitImageLightbox(); return false; }); }, closeButtonOff = function() { $( '#imagelightbox-close' ).remove(); }, captionOn = function() { var description = $( 'a[href="' + $( '#imagelightbox' ).attr( 'src' ) + '"] img' ).attr( 'alt' ); if( description.length > 0 ) $( '<div id="imagelightbox-caption">' + description + '</div>' ).appendTo( 'body' ); }, captionOff = function() { $( '#imagelightbox-caption' ).remove(); }; var instanceA = $( 'a[data-imagelightbox="a"]' ).imageLightbox( { onStart: function() { overlayOn(); closeButtonOn( instanceA ); }, onEnd: function() { overlayOff(); captionOff(); closeButtonOff(); activityIndicatorOff(); }, onLoadStart: function() { captionOff(); activityIndicatorOn(); }, onLoadEnd: function() { captionOn(); activityIndicatorOff(); } }); } else { /*----------------------------------------------------*/ /* prettyPhoto for old IE /*----------------------------------------------------*/ $("#screenshots").find(".item-wrap a").attr("rel","prettyPhoto[pp_gal]"); $("a[rel^='prettyPhoto']").prettyPhoto( { animation_speed: 'fast', /* fast/slow/normal */ slideshow: false, /* false OR interval time in ms */ autoplay_slideshow: false, /* true/false */ opacity: 0.80, /* Value between 0 and 1 */ show_title: true, /* true/false */ allow_resize: true, /* Resize the photos bigger than viewport. true/false */ default_width: 500, default_height: 344, counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */ theme: 'pp_default', /* light_rounded / dark_rounded / light_square / dark_square / facebook */ hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */ wmode: 'opaque', /* Set the flash wmode attribute */ autoplay: true, /* Automatically start videos: True/False */ modal: false, /* If set to true, only the close button will close the window */ overlay_gallery: false, /* If set to true, a gallery will overlay the fullscreen image on mouse over */ keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */ deeplinking: false, social_tools: false }); } })(jQuery);
wassapste97/sitomio
resources/js/main.js
JavaScript
mit
8,220
/** * @license Highcharts Gantt JS v7.2.0 (2019-09-03) * * CurrentDateIndicator * * (c) 2010-2019 Lars A. V. Cabrera * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/current-date-indicator', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'parts-gantt/CurrentDateIndicator.js', [_modules['parts/Globals.js']], function (H) { /* * * * (c) 2016-2019 Highsoft AS * * Author: Lars A. V. Cabrera * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var addEvent = H.addEvent, Axis = H.Axis, PlotLineOrBand = H.PlotLineOrBand, merge = H.merge, wrap = H.wrap; var defaultConfig = { /** * Show an indicator on the axis for the current date and time. Can be a * boolean or a configuration object similar to * [xAxis.plotLines](#xAxis.plotLines). * * @sample gantt/current-date-indicator/demo * Current date indicator enabled * @sample gantt/current-date-indicator/object-config * Current date indicator with custom options * * @type {boolean|*} * @default true * @extends xAxis.plotLines * @excluding value * @product gantt * @apioption xAxis.currentDateIndicator */ currentDateIndicator: true, color: '#ccd6eb', width: 2, label: { /** * Format of the label. This options is passed as the fist argument to * [dateFormat](/class-reference/Highcharts#dateFormat) function. * * @type {string} * @default '%a, %b %d %Y, %H:%M' * @product gantt * @apioption xAxis.currentDateIndicator.label.format */ format: '%a, %b %d %Y, %H:%M', formatter: function (value, format) { return H.dateFormat(format, value); }, rotation: 0, style: { fontSize: '10px' } } }; /* eslint-disable no-invalid-this */ addEvent(Axis, 'afterSetOptions', function () { var options = this.options, cdiOptions = options.currentDateIndicator; if (cdiOptions) { cdiOptions = typeof cdiOptions === 'object' ? merge(defaultConfig, cdiOptions) : merge(defaultConfig); cdiOptions.value = new Date(); if (!options.plotLines) { options.plotLines = []; } options.plotLines.push(cdiOptions); } }); addEvent(PlotLineOrBand, 'render', function () { // If the label already exists, update its text if (this.label) { this.label.attr({ text: this.getLabelText(this.options.label) }); } }); wrap(PlotLineOrBand.prototype, 'getLabelText', function (defaultMethod, defaultLabelOptions) { var options = this.options; if (options.currentDateIndicator && options.label && typeof options.label.formatter === 'function') { options.value = new Date(); return options.label.formatter .call(this, options.value, options.label.format); } return defaultMethod.call(this, defaultLabelOptions); }); }); _registerModule(_modules, 'masters/modules/current-date-indicator.src.js', [], function () { }); }));
extend1994/cdnjs
ajax/libs/highcharts/7.2.0/modules/current-date-indicator.src.js
JavaScript
mit
4,598
<?php namespace Illuminate\Support; use stdClass; use Countable; use Exception; use ArrayAccess; use Traversable; use ArrayIterator; use CachingIterator; use JsonSerializable; use IteratorAggregate; use Illuminate\Support\Debug\Dumper; use Illuminate\Support\Traits\Macroable; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Support\Arrayable; class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable { use Macroable; /** * The items contained in the collection. * * @var array */ protected $items = []; /** * The methods that can be proxied. * * @var array */ protected static $proxies = [ 'average', 'avg', 'contains', 'each', 'every', 'filter', 'first', 'flatMap', 'keyBy', 'map', 'partition', 'reject', 'sortBy', 'sortByDesc', 'sum', ]; /** * Create a new collection. * * @param mixed $items * @return void */ public function __construct($items = []) { $this->items = $this->getArrayableItems($items); } /** * Create a new collection instance if the value isn't one already. * * @param mixed $items * @return static */ public static function make($items = []) { return new static($items); } /** * Wrap the given value in a collection if applicable. * * @param mixed $value * @return static */ public static function wrap($value) { return $value instanceof self ? new static($value) : new static(Arr::wrap($value)); } /** * Get the underlying items from the given collection if applicable. * * @param array|static $value * @return array */ public static function unwrap($value) { return $value instanceof self ? $value->all() : $value; } /** * Create a new collection by invoking the callback a given amount of times. * * @param int $number * @param callable $callback * @return static */ public static function times($number, callable $callback = null) { if ($number < 1) { return new static; } if (is_null($callback)) { return new static(range(1, $number)); } return (new static(range(1, $number)))->map($callback); } /** * Get all of the items in the collection. * * @return array */ public function all() { return $this->items; } /** * Get the average value of a given key. * * @param callable|string|null $callback * @return mixed */ public function avg($callback = null) { if ($count = $this->count()) { return $this->sum($callback) / $count; } } /** * Alias for the "avg" method. * * @param callable|string|null $callback * @return mixed */ public function average($callback = null) { return $this->avg($callback); } /** * Get the median of a given key. * * @param null $key * @return mixed */ public function median($key = null) { $count = $this->count(); if ($count == 0) { return; } $values = (isset($key) ? $this->pluck($key) : $this) ->sort()->values(); $middle = (int) ($count / 2); if ($count % 2) { return $values->get($middle); } return (new static([ $values->get($middle - 1), $values->get($middle), ]))->average(); } /** * Get the mode of a given key. * * @param mixed $key * @return array|null */ public function mode($key = null) { $count = $this->count(); if ($count == 0) { return; } $collection = isset($key) ? $this->pluck($key) : $this; $counts = new self; $collection->each(function ($value) use ($counts) { $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1; }); $sorted = $counts->sort(); $highestValue = $sorted->last(); return $sorted->filter(function ($value) use ($highestValue) { return $value == $highestValue; })->sort()->keys()->all(); } /** * Collapse the collection of items into a single array. * * @return static */ public function collapse() { return new static(Arr::collapse($this->items)); } /** * Determine if an item exists in the collection. * * @param mixed $key * @param mixed $operator * @param mixed $value * @return bool */ public function contains($key, $operator = null, $value = null) { if (func_num_args() == 1) { if ($this->useAsCallable($key)) { $placeholder = new stdClass; return $this->first($key, $placeholder) !== $placeholder; } return in_array($key, $this->items); } return $this->contains($this->operatorForWhere(...func_get_args())); } /** * Determine if an item exists in the collection using strict comparison. * * @param mixed $key * @param mixed $value * @return bool */ public function containsStrict($key, $value = null) { if (func_num_args() == 2) { return $this->contains(function ($item) use ($key, $value) { return data_get($item, $key) === $value; }); } if ($this->useAsCallable($key)) { return ! is_null($this->first($key)); } return in_array($key, $this->items, true); } /** * Cross join with the given lists, returning all possible permutations. * * @param mixed ...$lists * @return static */ public function crossJoin(...$lists) { return new static(Arr::crossJoin( $this->items, ...array_map([$this, 'getArrayableItems'], $lists) )); } /** * Dump the collection and end the script. * * @return void */ public function dd(...$args) { http_response_code(500); call_user_func_array([$this, 'dump'], $args); die(1); } /** * Dump the collection. * * @return $this */ public function dump() { (new static(func_get_args())) ->push($this) ->each(function ($item) { (new Dumper)->dump($item); }); return $this; } /** * Get the items in the collection that are not present in the given items. * * @param mixed $items * @return static */ public function diff($items) { return new static(array_diff($this->items, $this->getArrayableItems($items))); } /** * Get the items in the collection whose keys and values are not present in the given items. * * @param mixed $items * @return static */ public function diffAssoc($items) { return new static(array_diff_assoc($this->items, $this->getArrayableItems($items))); } /** * Get the items in the collection whose keys are not present in the given items. * * @param mixed $items * @return static */ public function diffKeys($items) { return new static(array_diff_key($this->items, $this->getArrayableItems($items))); } /** * Execute a callback over each item. * * @param callable $callback * @return $this */ public function each(callable $callback) { foreach ($this->items as $key => $item) { if ($callback($item, $key) === false) { break; } } return $this; } /** * Execute a callback over each nested chunk of items. * * @param callable $callback * @return static */ public function eachSpread(callable $callback) { return $this->each(function ($chunk, $key) use ($callback) { $chunk[] = $key; return $callback(...$chunk); }); } /** * Determine if all items in the collection pass the given test. * * @param string|callable $key * @param mixed $operator * @param mixed $value * @return bool */ public function every($key, $operator = null, $value = null) { if (func_num_args() == 1) { $callback = $this->valueRetriever($key); foreach ($this->items as $k => $v) { if (! $callback($v, $k)) { return false; } } return true; } return $this->every($this->operatorForWhere(...func_get_args())); } /** * Get all items except for those with the specified keys. * * @param \Illuminate\Support\Collection|mixed $keys * @return static */ public function except($keys) { if ($keys instanceof self) { $keys = $keys->all(); } elseif (! is_array($keys)) { $keys = func_get_args(); } return new static(Arr::except($this->items, $keys)); } /** * Run a filter over each of the items. * * @param callable|null $callback * @return static */ public function filter(callable $callback = null) { if ($callback) { return new static(Arr::where($this->items, $callback)); } return new static(array_filter($this->items)); } /** * Apply the callback if the value is truthy. * * @param bool $value * @param callable $callback * @param callable $default * @return mixed */ public function when($value, callable $callback, callable $default = null) { if ($value) { return $callback($this, $value); } elseif ($default) { return $default($this, $value); } return $this; } /** * Apply the callback if the value is falsy. * * @param bool $value * @param callable $callback * @param callable $default * @return mixed */ public function unless($value, callable $callback, callable $default = null) { return $this->when(! $value, $callback, $default); } /** * Filter items by the given key value pair. * * @param string $key * @param mixed $operator * @param mixed $value * @return static */ public function where($key, $operator, $value = null) { return $this->filter($this->operatorForWhere(...func_get_args())); } /** * Get an operator checker callback. * * @param string $key * @param string $operator * @param mixed $value * @return \Closure */ protected function operatorForWhere($key, $operator, $value = null) { if (func_num_args() == 2) { $value = $operator; $operator = '='; } return function ($item) use ($key, $operator, $value) { $retrieved = data_get($item, $key); $strings = array_filter([$retrieved, $value], function ($value) { return is_string($value) || (is_object($value) && method_exists($value, '__toString')); }); if (count($strings) < 2 && count(array_filter([$retrieved, $value], 'is_object')) == 1) { return in_array($operator, ['!=', '<>', '!==']); } switch ($operator) { default: case '=': case '==': return $retrieved == $value; case '!=': case '<>': return $retrieved != $value; case '<': return $retrieved < $value; case '>': return $retrieved > $value; case '<=': return $retrieved <= $value; case '>=': return $retrieved >= $value; case '===': return $retrieved === $value; case '!==': return $retrieved !== $value; } }; } /** * Filter items by the given key value pair using strict comparison. * * @param string $key * @param mixed $value * @return static */ public function whereStrict($key, $value) { return $this->where($key, '===', $value); } /** * Filter items by the given key value pair. * * @param string $key * @param mixed $values * @param bool $strict * @return static */ public function whereIn($key, $values, $strict = false) { $values = $this->getArrayableItems($values); return $this->filter(function ($item) use ($key, $values, $strict) { return in_array(data_get($item, $key), $values, $strict); }); } /** * Filter items by the given key value pair using strict comparison. * * @param string $key * @param mixed $values * @return static */ public function whereInStrict($key, $values) { return $this->whereIn($key, $values, true); } /** * Filter items by the given key value pair. * * @param string $key * @param mixed $values * @param bool $strict * @return static */ public function whereNotIn($key, $values, $strict = false) { $values = $this->getArrayableItems($values); return $this->reject(function ($item) use ($key, $values, $strict) { return in_array(data_get($item, $key), $values, $strict); }); } /** * Filter items by the given key value pair using strict comparison. * * @param string $key * @param mixed $values * @return static */ public function whereNotInStrict($key, $values) { return $this->whereNotIn($key, $values, true); } /** * Get the first item from the collection. * * @param callable|null $callback * @param mixed $default * @return mixed */ public function first(callable $callback = null, $default = null) { return Arr::first($this->items, $callback, $default); } /** * Get the first item by the given key value pair. * * @param string $key * @param mixed $operator * @param mixed $value * @return static */ public function firstWhere($key, $operator, $value = null) { return $this->first($this->operatorForWhere(...func_get_args())); } /** * Get a flattened array of the items in the collection. * * @param int $depth * @return static */ public function flatten($depth = INF) { return new static(Arr::flatten($this->items, $depth)); } /** * Flip the items in the collection. * * @return static */ public function flip() { return new static(array_flip($this->items)); } /** * Remove an item from the collection by key. * * @param string|array $keys * @return $this */ public function forget($keys) { foreach ((array) $keys as $key) { $this->offsetUnset($key); } return $this; } /** * Get an item from the collection by key. * * @param mixed $key * @param mixed $default * @return mixed */ public function get($key, $default = null) { if ($this->offsetExists($key)) { return $this->items[$key]; } return value($default); } /** * Group an associative array by a field or using a callback. * * @param callable|string $groupBy * @param bool $preserveKeys * @return static */ public function groupBy($groupBy, $preserveKeys = false) { if (is_array($groupBy)) { $nextGroups = $groupBy; $groupBy = array_shift($nextGroups); } $groupBy = $this->valueRetriever($groupBy); $results = []; foreach ($this->items as $key => $value) { $groupKeys = $groupBy($value, $key); if (! is_array($groupKeys)) { $groupKeys = [$groupKeys]; } foreach ($groupKeys as $groupKey) { $groupKey = is_bool($groupKey) ? (int) $groupKey : $groupKey; if (! array_key_exists($groupKey, $results)) { $results[$groupKey] = new static; } $results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value); } } $result = new static($results); if (! empty($nextGroups)) { return $result->map->groupBy($nextGroups, $preserveKeys); } return $result; } /** * Key an associative array by a field or using a callback. * * @param callable|string $keyBy * @return static */ public function keyBy($keyBy) { $keyBy = $this->valueRetriever($keyBy); $results = []; foreach ($this->items as $key => $item) { $resolvedKey = $keyBy($item, $key); if (is_object($resolvedKey)) { $resolvedKey = (string) $resolvedKey; } $results[$resolvedKey] = $item; } return new static($results); } /** * Determine if an item exists in the collection by key. * * @param mixed $key * @return bool */ public function has($key) { $keys = is_array($key) ? $key : func_get_args(); foreach ($keys as $value) { if (! $this->offsetExists($value)) { return false; } } return true; } /** * Concatenate values of a given key as a string. * * @param string $value * @param string $glue * @return string */ public function implode($value, $glue = null) { $first = $this->first(); if (is_array($first) || is_object($first)) { return implode($glue, $this->pluck($value)->all()); } return implode($value, $this->items); } /** * Intersect the collection with the given items. * * @param mixed $items * @return static */ public function intersect($items) { return new static(array_intersect($this->items, $this->getArrayableItems($items))); } /** * Intersect the collection with the given items by key. * * @param mixed $items * @return static */ public function intersectByKeys($items) { return new static(array_intersect_key( $this->items, $this->getArrayableItems($items) )); } /** * Determine if the collection is empty or not. * * @return bool */ public function isEmpty() { return empty($this->items); } /** * Determine if the collection is not empty. * * @return bool */ public function isNotEmpty() { return ! $this->isEmpty(); } /** * Determine if the given value is callable, but not a string. * * @param mixed $value * @return bool */ protected function useAsCallable($value) { return ! is_string($value) && is_callable($value); } /** * Get the keys of the collection items. * * @return static */ public function keys() { return new static(array_keys($this->items)); } /** * Get the last item from the collection. * * @param callable|null $callback * @param mixed $default * @return mixed */ public function last(callable $callback = null, $default = null) { return Arr::last($this->items, $callback, $default); } /** * Get the values of a given key. * * @param string|array $value * @param string|null $key * @return static */ public function pluck($value, $key = null) { return new static(Arr::pluck($this->items, $value, $key)); } /** * Run a map over each of the items. * * @param callable $callback * @return static */ public function map(callable $callback) { $keys = array_keys($this->items); $items = array_map($callback, $this->items, $keys); return new static(array_combine($keys, $items)); } /** * Run a map over each nested chunk of items. * * @param callable $callback * @return static */ public function mapSpread(callable $callback) { return $this->map(function ($chunk, $key) use ($callback) { $chunk[] = $key; return $callback(...$chunk); }); } /** * Run a dictionary map over the items. * * The callback should return an associative array with a single key/value pair. * * @param callable $callback * @return static */ public function mapToDictionary(callable $callback) { $dictionary = $this->map($callback)->reduce(function ($groups, $pair) { $groups[key($pair)][] = reset($pair); return $groups; }, []); return new static($dictionary); } /** * Run a grouping map over the items. * * The callback should return an associative array with a single key/value pair. * * @param callable $callback * @return static */ public function mapToGroups(callable $callback) { $groups = $this->mapToDictionary($callback); return $groups->map([$this, 'make']); } /** * Run an associative map over each of the items. * * The callback should return an associative array with a single key/value pair. * * @param callable $callback * @return static */ public function mapWithKeys(callable $callback) { $result = []; foreach ($this->items as $key => $value) { $assoc = $callback($value, $key); foreach ($assoc as $mapKey => $mapValue) { $result[$mapKey] = $mapValue; } } return new static($result); } /** * Map a collection and flatten the result by a single level. * * @param callable $callback * @return static */ public function flatMap(callable $callback) { return $this->map($callback)->collapse(); } /** * Map the values into a new class. * * @param string $class * @return static */ public function mapInto($class) { return $this->map(function ($value, $key) use ($class) { return new $class($value, $key); }); } /** * Get the max value of a given key. * * @param callable|string|null $callback * @return mixed */ public function max($callback = null) { $callback = $this->valueRetriever($callback); return $this->filter(function ($value) { return ! is_null($value); })->reduce(function ($result, $item) use ($callback) { $value = $callback($item); return is_null($result) || $value > $result ? $value : $result; }); } /** * Merge the collection with the given items. * * @param mixed $items * @return static */ public function merge($items) { return new static(array_merge($this->items, $this->getArrayableItems($items))); } /** * Create a collection by using this collection for keys and another for its values. * * @param mixed $values * @return static */ public function combine($values) { return new static(array_combine($this->all(), $this->getArrayableItems($values))); } /** * Union the collection with the given items. * * @param mixed $items * @return static */ public function union($items) { return new static($this->items + $this->getArrayableItems($items)); } /** * Get the min value of a given key. * * @param callable|string|null $callback * @return mixed */ public function min($callback = null) { $callback = $this->valueRetriever($callback); return $this->filter(function ($value) { return ! is_null($value); })->reduce(function ($result, $item) use ($callback) { $value = $callback($item); return is_null($result) || $value < $result ? $value : $result; }); } /** * Create a new collection consisting of every n-th element. * * @param int $step * @param int $offset * @return static */ public function nth($step, $offset = 0) { $new = []; $position = 0; foreach ($this->items as $item) { if ($position % $step === $offset) { $new[] = $item; } $position++; } return new static($new); } /** * Get the items with the specified keys. * * @param mixed $keys * @return static */ public function only($keys) { if (is_null($keys)) { return new static($this->items); } if ($keys instanceof self) { $keys = $keys->all(); } $keys = is_array($keys) ? $keys : func_get_args(); return new static(Arr::only($this->items, $keys)); } /** * "Paginate" the collection by slicing it into a smaller collection. * * @param int $page * @param int $perPage * @return static */ public function forPage($page, $perPage) { $offset = max(0, ($page - 1) * $perPage); return $this->slice($offset, $perPage); } /** * Partition the collection into two arrays using the given callback or key. * * @param callable|string $callback * @return static */ public function partition($callback) { $partitions = [new static, new static]; $callback = $this->valueRetriever($callback); foreach ($this->items as $key => $item) { $partitions[(int) ! $callback($item, $key)][$key] = $item; } return new static($partitions); } /** * Pass the collection to the given callback and return the result. * * @param callable $callback * @return mixed */ public function pipe(callable $callback) { return $callback($this); } /** * Get and remove the last item from the collection. * * @return mixed */ public function pop() { return array_pop($this->items); } /** * Push an item onto the beginning of the collection. * * @param mixed $value * @param mixed $key * @return $this */ public function prepend($value, $key = null) { $this->items = Arr::prepend($this->items, $value, $key); return $this; } /** * Push an item onto the end of the collection. * * @param mixed $value * @return $this */ public function push($value) { $this->offsetSet(null, $value); return $this; } /** * Push all of the given items onto the collection. * * @param \Traversable $source * @return $this */ public function concat($source) { $result = new static($this); foreach ($source as $item) { $result->push($item); } return $result; } /** * Get and remove an item from the collection. * * @param mixed $key * @param mixed $default * @return mixed */ public function pull($key, $default = null) { return Arr::pull($this->items, $key, $default); } /** * Put an item in the collection by key. * * @param mixed $key * @param mixed $value * @return $this */ public function put($key, $value) { $this->offsetSet($key, $value); return $this; } /** * Get one or a specified number of items randomly from the collection. * * @param int|null $number * @return mixed * * @throws \InvalidArgumentException */ public function random($number = null) { if (is_null($number)) { return Arr::random($this->items); } return new static(Arr::random($this->items, $number)); } /** * Reduce the collection to a single value. * * @param callable $callback * @param mixed $initial * @return mixed */ public function reduce(callable $callback, $initial = null) { return array_reduce($this->items, $callback, $initial); } /** * Create a collection of all elements that do not pass a given truth test. * * @param callable|mixed $callback * @return static */ public function reject($callback) { if ($this->useAsCallable($callback)) { return $this->filter(function ($value, $key) use ($callback) { return ! $callback($value, $key); }); } return $this->filter(function ($item) use ($callback) { return $item != $callback; }); } /** * Reverse items order. * * @return static */ public function reverse() { return new static(array_reverse($this->items, true)); } /** * Search the collection for a given value and return the corresponding key if successful. * * @param mixed $value * @param bool $strict * @return mixed */ public function search($value, $strict = false) { if (! $this->useAsCallable($value)) { return array_search($value, $this->items, $strict); } foreach ($this->items as $key => $item) { if (call_user_func($value, $item, $key)) { return $key; } } return false; } /** * Get and remove the first item from the collection. * * @return mixed */ public function shift() { return array_shift($this->items); } /** * Shuffle the items in the collection. * * @param int $seed * @return static */ public function shuffle($seed = null) { $items = $this->items; if (is_null($seed)) { shuffle($items); } else { srand($seed); usort($items, function () { return rand(-1, 1); }); } return new static($items); } /** * Slice the underlying collection array. * * @param int $offset * @param int $length * @return static */ public function slice($offset, $length = null) { return new static(array_slice($this->items, $offset, $length, true)); } /** * Split a collection into a certain number of groups. * * @param int $numberOfGroups * @return static */ public function split($numberOfGroups) { if ($this->isEmpty()) { return new static; } $groupSize = ceil($this->count() / $numberOfGroups); return $this->chunk($groupSize); } /** * Chunk the underlying collection array. * * @param int $size * @return static */ public function chunk($size) { if ($size <= 0) { return new static; } $chunks = []; foreach (array_chunk($this->items, $size, true) as $chunk) { $chunks[] = new static($chunk); } return new static($chunks); } /** * Sort through each item with a callback. * * @param callable|null $callback * @return static */ public function sort(callable $callback = null) { $items = $this->items; $callback ? uasort($items, $callback) : asort($items); return new static($items); } /** * Sort the collection using the given callback. * * @param callable|string $callback * @param int $options * @param bool $descending * @return static */ public function sortBy($callback, $options = SORT_REGULAR, $descending = false) { $results = []; $callback = $this->valueRetriever($callback); // First we will loop through the items and get the comparator from a callback // function which we were given. Then, we will sort the returned values and // and grab the corresponding values for the sorted keys from this array. foreach ($this->items as $key => $value) { $results[$key] = $callback($value, $key); } $descending ? arsort($results, $options) : asort($results, $options); // Once we have sorted all of the keys in the array, we will loop through them // and grab the corresponding model so we can set the underlying items list // to the sorted version. Then we'll just return the collection instance. foreach (array_keys($results) as $key) { $results[$key] = $this->items[$key]; } return new static($results); } /** * Sort the collection in descending order using the given callback. * * @param callable|string $callback * @param int $options * @return static */ public function sortByDesc($callback, $options = SORT_REGULAR) { return $this->sortBy($callback, $options, true); } /** * Splice a portion of the underlying collection array. * * @param int $offset * @param int|null $length * @param mixed $replacement * @return static */ public function splice($offset, $length = null, $replacement = []) { if (func_num_args() == 1) { return new static(array_splice($this->items, $offset)); } return new static(array_splice($this->items, $offset, $length, $replacement)); } /** * Get the sum of the given values. * * @param callable|string|null $callback * @return mixed */ public function sum($callback = null) { if (is_null($callback)) { return array_sum($this->items); } $callback = $this->valueRetriever($callback); return $this->reduce(function ($result, $item) use ($callback) { return $result + $callback($item); }, 0); } /** * Take the first or last {$limit} items. * * @param int $limit * @return static */ public function take($limit) { if ($limit < 0) { return $this->slice($limit, abs($limit)); } return $this->slice(0, $limit); } /** * Pass the collection to the given callback and then return it. * * @param callable $callback * @return $this */ public function tap(callable $callback) { $callback(new static($this->items)); return $this; } /** * Transform each item in the collection using a callback. * * @param callable $callback * @return $this */ public function transform(callable $callback) { $this->items = $this->map($callback)->all(); return $this; } /** * Return only unique items from the collection array. * * @param string|callable|null $key * @param bool $strict * @return static */ public function unique($key = null, $strict = false) { if (is_null($key)) { return new static(array_unique($this->items, SORT_REGULAR)); } $callback = $this->valueRetriever($key); $exists = []; return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) { if (in_array($id = $callback($item, $key), $exists, $strict)) { return true; } $exists[] = $id; }); } /** * Return only unique items from the collection array using strict comparison. * * @param string|callable|null $key * @return static */ public function uniqueStrict($key = null) { return $this->unique($key, true); } /** * Reset the keys on the underlying array. * * @return static */ public function values() { return new static(array_values($this->items)); } /** * Get a value retrieving callback. * * @param string $value * @return callable */ protected function valueRetriever($value) { if ($this->useAsCallable($value)) { return $value; } return function ($item) use ($value) { return data_get($item, $value); }; } /** * Zip the collection together with one or more arrays. * * e.g. new Collection([1, 2, 3])->zip([4, 5, 6]); * => [[1, 4], [2, 5], [3, 6]] * * @param mixed ...$items * @return static */ public function zip($items) { $arrayableItems = array_map(function ($items) { return $this->getArrayableItems($items); }, func_get_args()); $params = array_merge([function () { return new static(func_get_args()); }, $this->items], $arrayableItems); return new static(call_user_func_array('array_map', $params)); } /** * Pad collection to the specified length with a value. * * @param int $size * @param mixed $value * @return static */ public function pad($size, $value) { return new static(array_pad($this->items, $size, $value)); } /** * Get the collection of items as a plain array. * * @return array */ public function toArray() { return array_map(function ($value) { return $value instanceof Arrayable ? $value->toArray() : $value; }, $this->items); } /** * Convert the object into something JSON serializable. * * @return array */ public function jsonSerialize() { return array_map(function ($value) { if ($value instanceof JsonSerializable) { return $value->jsonSerialize(); } elseif ($value instanceof Jsonable) { return json_decode($value->toJson(), true); } elseif ($value instanceof Arrayable) { return $value->toArray(); } return $value; }, $this->items); } /** * Get the collection of items as JSON. * * @param int $options * @return string */ public function toJson($options = 0) { return json_encode($this->jsonSerialize(), $options); } /** * Get an iterator for the items. * * @return \ArrayIterator */ public function getIterator() { return new ArrayIterator($this->items); } /** * Get a CachingIterator instance. * * @param int $flags * @return \CachingIterator */ public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING) { return new CachingIterator($this->getIterator(), $flags); } /** * Count the number of items in the collection. * * @return int */ public function count() { return count($this->items); } /** * Get a base Support collection instance from this collection. * * @return \Illuminate\Support\Collection */ public function toBase() { return new self($this); } /** * Determine if an item exists at an offset. * * @param mixed $key * @return bool */ public function offsetExists($key) { return array_key_exists($key, $this->items); } /** * Get an item at a given offset. * * @param mixed $key * @return mixed */ public function offsetGet($key) { return $this->items[$key]; } /** * Set the item at a given offset. * * @param mixed $key * @param mixed $value * @return void */ public function offsetSet($key, $value) { if (is_null($key)) { $this->items[] = $value; } else { $this->items[$key] = $value; } } /** * Unset the item at a given offset. * * @param string $key * @return void */ public function offsetUnset($key) { unset($this->items[$key]); } /** * Convert the collection to its string representation. * * @return string */ public function __toString() { return $this->toJson(); } /** * Results array of items from Collection or Arrayable. * * @param mixed $items * @return array */ protected function getArrayableItems($items) { if (is_array($items)) { return $items; } elseif ($items instanceof self) { return $items->all(); } elseif ($items instanceof Arrayable) { return $items->toArray(); } elseif ($items instanceof Jsonable) { return json_decode($items->toJson(), true); } elseif ($items instanceof JsonSerializable) { return $items->jsonSerialize(); } elseif ($items instanceof Traversable) { return iterator_to_array($items); } return (array) $items; } /** * Add a method to the list of proxied methods. * * @param string $method * @return void */ public static function proxy($method) { static::$proxies[] = $method; } /** * Dynamically access collection proxies. * * @param string $key * @return mixed * * @throws \Exception */ public function __get($key) { if (! in_array($key, static::$proxies)) { throw new Exception("Property [{$key}] does not exist on this collection instance."); } return new HigherOrderCollectionProxy($this, $key); } }
poetimp/ltcsw
submissions/include/vendor/tightenco/collect/src/Illuminate/Support/Collection.php
PHP
mit
42,804
export interface StripeCardTokenParams { /** * Card number */ number: string; /** * Expiry month */ expMonth: number; /** * Expiry year */ expYear: number; /** * CVC / CVV */ cvc?: string; /** * Cardholder name */ name?: string; /** * Address line 1 */ address_line1?: string; /** * Address line 2 */ address_line2?: string; /** * City */ address_city?: string; /** * State / Province */ address_state?: string; /** * Country */ address_country?: string; /** * Postal code / ZIP Code */ postal_code?: string; /** * 3-letter ISO code for currency */ currency?: string; } /** * @beta * @name Stripe * @description * A plugin that allows you to use Stripe's Native SDKs for Android and iOS. * * @usage * ``` * import { Stripe } from 'ionic-native'; * * Stripe.setPublishableKey('my_publishable_key'); * * let card = { * number: '4242424242424242', * expMonth: 12, * expYear: 2020, * cvc: 220 * }; * * Stripe.createToken(card) * .then(token => console.log(token)) * .catch(error => console.error(error)); * * ``` * * @interfaces * StripeCardTokenParams */ export declare class Stripe { /** * Set publishable key * @param publishableKey {string} Publishable key * @return {Promise<void>} */ static setPublishableKey(publishableKey: string): Promise<void>; /** * Create Credit Card Token * @param params {StripeCardTokenParams} Credit card information * @return {Promise<string>} returns a promise that resolves with the token, or reject with an error */ static createCardToken(params: StripeCardTokenParams): Promise<string>; }
Spect-AR/Spect-AR
node_modules/ionic-native/dist/esm/plugins/stripe.d.ts
TypeScript
mit
1,924
<?php /** * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OC\User; use OC\Hooks\PublicEmitter; use OCP\IUserManager; /** * Class Manager * * Hooks available in scope \OC\User: * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword) * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword) * - preDelete(\OC\User\User $user) * - postDelete(\OC\User\User $user) * - preCreateUser(string $uid, string $password) * - postCreateUser(\OC\User\User $user, string $password) * * @package OC\User */ class Manager extends PublicEmitter implements IUserManager { /** * @var \OC_User_Interface[] $backends */ private $backends = array(); /** * @var \OC\User\User[] $cachedUsers */ private $cachedUsers = array(); /** * @var \OC\AllConfig $config */ private $config; /** * @param \OC\AllConfig $config */ public function __construct($config = null) { $this->config = $config; $cachedUsers = $this->cachedUsers; $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) { $i = array_search($user, $cachedUsers); if ($i !== false) { unset($cachedUsers[$i]); } }); $this->listen('\OC\User', 'postLogin', function ($user) { $user->updateLastLoginTimestamp(); }); $this->listen('\OC\User', 'postRememberedLogin', function ($user) { $user->updateLastLoginTimestamp(); }); } /** * register a user backend * * @param \OC_User_Interface $backend */ public function registerBackend($backend) { $this->backends[] = $backend; } /** * remove a user backend * * @param \OC_User_Interface $backend */ public function removeBackend($backend) { $this->cachedUsers = array(); if (($i = array_search($backend, $this->backends)) !== false) { unset($this->backends[$i]); } } /** * remove all user backends */ public function clearBackends() { $this->cachedUsers = array(); $this->backends = array(); } /** * get a user by user id * * @param string $uid * @return \OC\User\User */ public function get($uid) { if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends return $this->cachedUsers[$uid]; } foreach ($this->backends as $backend) { if ($backend->userExists($uid)) { return $this->getUserObject($uid, $backend); } } return null; } /** * get or construct the user object * * @param string $uid * @param \OC_User_Interface $backend * @return \OC\User\User */ protected function getUserObject($uid, $backend) { if (isset($this->cachedUsers[$uid])) { return $this->cachedUsers[$uid]; } $this->cachedUsers[$uid] = new User($uid, $backend, $this, $this->config); return $this->cachedUsers[$uid]; } /** * check if a user exists * * @param string $uid * @return bool */ public function userExists($uid) { $user = $this->get($uid); return ($user !== null); } /** * remove deleted user from cache * * @param string $uid * @return bool */ public function delete($uid) { if (isset($this->cachedUsers[$uid])) { unset($this->cachedUsers[$uid]); return true; } return false; } /** * Check if the password is valid for the user * * @param string $loginname * @param string $password * @return mixed the User object on success, false otherwise */ public function checkPassword($loginname, $password) { foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC_USER_BACKEND_CHECK_PASSWORD)) { $uid = $backend->checkPassword($loginname, $password); if ($uid !== false) { return $this->getUserObject($uid, $backend); } } } $remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; $forwardedFor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ''; \OC::$server->getLogger()->warning('Login failed: \''. $loginname .'\' (Remote IP: \''. $remoteAddr .'\', X-Forwarded-For: \''. $forwardedFor .'\')', array('app' => 'core')); return false; } /** * search by user id * * @param string $pattern * @param int $limit * @param int $offset * @return \OC\User\User[] */ public function search($pattern, $limit = null, $offset = null) { $users = array(); foreach ($this->backends as $backend) { $backendUsers = $backend->getUsers($pattern, $limit, $offset); if (is_array($backendUsers)) { foreach ($backendUsers as $uid) { $users[$uid] = $this->getUserObject($uid, $backend); } } } uasort($users, function ($a, $b) { /** * @var \OC\User\User $a * @var \OC\User\User $b */ return strcmp($a->getUID(), $b->getUID()); }); return $users; } /** * search by displayName * * @param string $pattern * @param int $limit * @param int $offset * @return \OC\User\User[] */ public function searchDisplayName($pattern, $limit = null, $offset = null) { $users = array(); foreach ($this->backends as $backend) { $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); if (is_array($backendUsers)) { foreach ($backendUsers as $uid => $displayName) { $users[] = $this->getUserObject($uid, $backend); } } } usort($users, function ($a, $b) { /** * @var \OC\User\User $a * @var \OC\User\User $b */ return strcmp($a->getDisplayName(), $b->getDisplayName()); }); return $users; } /** * @param string $uid * @param string $password * @throws \Exception * @return bool|\OC\User\User the created user of false */ public function createUser($uid, $password) { $l = \OC_L10N::get('lib'); // Check the name for bad characters // Allowed are: "a-z", "A-Z", "0-9" and "_.@-" if (preg_match('/[^a-zA-Z0-9 _\.@\-]/', $uid)) { throw new \Exception($l->t('Only the following characters are allowed in a username:' . ' "a-z", "A-Z", "0-9", and "_.@-"')); } // No empty username if (trim($uid) == '') { throw new \Exception($l->t('A valid username must be provided')); } // No empty password if (trim($password) == '') { throw new \Exception($l->t('A valid password must be provided')); } // Check if user already exists if ($this->userExists($uid)) { throw new \Exception($l->t('The username is already being used')); } $this->emit('\OC\User', 'preCreateUser', array($uid, $password)); foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC_USER_BACKEND_CREATE_USER)) { $backend->createUser($uid, $password); $user = $this->getUserObject($uid, $backend); $this->emit('\OC\User', 'postCreateUser', array($user, $password)); return $user; } } return false; } /** * returns how many users per backend exist (if supported by backend) * * @return array an array of backend class as key and count number as value */ public function countUsers() { $userCountStatistics = array(); foreach ($this->backends as $backend) { if ($backend->implementsActions(\OC_USER_BACKEND_COUNT_USERS)) { $backendusers = $backend->countUsers(); if($backendusers !== false) { if(isset($userCountStatistics[get_class($backend)])) { $userCountStatistics[get_class($backend)] += $backendusers; } else { $userCountStatistics[get_class($backend)] = $backendusers; } } } } return $userCountStatistics; } }
ACOKing/ArcherSys
owncloud-serv/lib/private/user/manager.php
PHP
mit
7,534
var dep = require('./dep'); dep('');
gsteacy/ts-loader
test/execution-tests/1.8.2_allowJs-entryFileIsJs/src/app.js
JavaScript
mit
37
package org.multibit.hd.ui.views.wizards.appearance_settings; import com.google.common.base.Optional; import org.multibit.hd.ui.views.wizards.AbstractWizard; import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView; import java.util.Map; /** * <p>Wizard to provide the following to UI for "appearance" wizard:</p> * <ol> * <li>Enter details</li> * </ol> * * @since 0.0.1 * */ public class AppearanceSettingsWizard extends AbstractWizard<AppearanceSettingsWizardModel> { public AppearanceSettingsWizard(AppearanceSettingsWizardModel model) { super(model, false, Optional.absent()); } @Override protected void populateWizardViewMap(Map<String, AbstractWizardPanelView> wizardViewMap) { // Use the wizard parameter to retrieve the appropriate mode wizardViewMap.put( AppearanceSettingsState.APPEARANCE_ENTER_DETAILS.name(), new AppearanceSettingsPanelView(this, AppearanceSettingsState.APPEARANCE_ENTER_DETAILS.name()) ); } }
oscarguindzberg/multibit-hd
mbhd-swing/src/main/java/org/multibit/hd/ui/views/wizards/appearance_settings/AppearanceSettingsWizard.java
Java
mit
984
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml; import com.google.common.base.Preconditions; import org.opendaylight.controller.netconf.confignetconfconnector.util.Util; import org.w3c.dom.Document; import java.util.List; import java.util.Map; public class SimpleUnionAttributeWritingStrategy extends SimpleAttributeWritingStrategy { /** * @param document * @param key */ public SimpleUnionAttributeWritingStrategy(Document document, String key) { super(document, key); } protected Object preprocess(Object value) { Util.checkType(value, Map.class); Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value); Object listOfStrings = ((Map) value).values().iterator().next(); Util.checkType(listOfStrings, List.class); StringBuilder b = new StringBuilder(); for (Object character: (List)listOfStrings) { Util.checkType(character, String.class); b.append(character); } return b.toString(); } }
aryantaheri/controller
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleUnionAttributeWritingStrategy.java
Java
epl-1.0
1,436
/******************************************************************************* * Copyright (c) 2006, 2009 David A Carlson * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David A Carlson (XMLmodeling.com) - initial API and implementation *******************************************************************************/ package org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.openhealthtools.mdht.emf.w3c.xhtml.Code; import org.openhealthtools.mdht.emf.w3c.xhtml.MifClassType; import org.openhealthtools.mdht.emf.w3c.xhtml.StyleSheet; import org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Code</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getClass_ <em>Class</em>}</li> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getLang <em>Lang</em>}</li> * <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getStyle <em>Style</em>}</li> * </ul> * </p> * * @generated */ public class CodeImpl extends InlineImpl implements Code { /** * The default value of the '{@link #getClass_() <em>Class</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getClass_() * @generated * @ordered */ protected static final MifClassType CLASS_EDEFAULT = MifClassType.INSERTED; /** * The cached value of the '{@link #getClass_() <em>Class</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getClass_() * @generated * @ordered */ protected MifClassType class_ = CLASS_EDEFAULT; /** * This is true if the Class attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean classESet; /** * The default value of the '{@link #getLang() <em>Lang</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLang() * @generated * @ordered */ protected static final String LANG_EDEFAULT = null; /** * The cached value of the '{@link #getLang() <em>Lang</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLang() * @generated * @ordered */ protected String lang = LANG_EDEFAULT; /** * The default value of the '{@link #getStyle() <em>Style</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStyle() * @generated * @ordered */ protected static final StyleSheet STYLE_EDEFAULT = StyleSheet.REQUIREMENT; /** * The cached value of the '{@link #getStyle() <em>Style</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStyle() * @generated * @ordered */ protected StyleSheet style = STYLE_EDEFAULT; /** * This is true if the Style attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean styleESet; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CodeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return XhtmlPackage.Literals.CODE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MifClassType getClass_() { return class_; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setClass(MifClassType newClass) { MifClassType oldClass = class_; class_ = newClass == null ? CLASS_EDEFAULT : newClass; boolean oldClassESet = classESet; classESet = true; if (eNotificationRequired()) { eNotify(new ENotificationImpl( this, Notification.SET, XhtmlPackage.CODE__CLASS, oldClass, class_, !oldClassESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void unsetClass() { MifClassType oldClass = class_; boolean oldClassESet = classESet; class_ = CLASS_EDEFAULT; classESet = false; if (eNotificationRequired()) { eNotify(new ENotificationImpl( this, Notification.UNSET, XhtmlPackage.CODE__CLASS, oldClass, CLASS_EDEFAULT, oldClassESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isSetClass() { return classESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLang() { return lang; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLang(String newLang) { String oldLang = lang; lang = newLang; if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.SET, XhtmlPackage.CODE__LANG, oldLang, lang)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StyleSheet getStyle() { return style; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStyle(StyleSheet newStyle) { StyleSheet oldStyle = style; style = newStyle == null ? STYLE_EDEFAULT : newStyle; boolean oldStyleESet = styleESet; styleESet = true; if (eNotificationRequired()) { eNotify(new ENotificationImpl( this, Notification.SET, XhtmlPackage.CODE__STYLE, oldStyle, style, !oldStyleESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void unsetStyle() { StyleSheet oldStyle = style; boolean oldStyleESet = styleESet; style = STYLE_EDEFAULT; styleESet = false; if (eNotificationRequired()) { eNotify(new ENotificationImpl( this, Notification.UNSET, XhtmlPackage.CODE__STYLE, oldStyle, STYLE_EDEFAULT, oldStyleESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isSetStyle() { return styleESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case XhtmlPackage.CODE__CLASS: return getClass_(); case XhtmlPackage.CODE__LANG: return getLang(); case XhtmlPackage.CODE__STYLE: return getStyle(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case XhtmlPackage.CODE__CLASS: setClass((MifClassType) newValue); return; case XhtmlPackage.CODE__LANG: setLang((String) newValue); return; case XhtmlPackage.CODE__STYLE: setStyle((StyleSheet) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case XhtmlPackage.CODE__CLASS: unsetClass(); return; case XhtmlPackage.CODE__LANG: setLang(LANG_EDEFAULT); return; case XhtmlPackage.CODE__STYLE: unsetStyle(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case XhtmlPackage.CODE__CLASS: return isSetClass(); case XhtmlPackage.CODE__LANG: return LANG_EDEFAULT == null ? lang != null : !LANG_EDEFAULT.equals(lang); case XhtmlPackage.CODE__STYLE: return isSetStyle(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) { return super.toString(); } StringBuffer result = new StringBuffer(super.toString()); result.append(" (class: "); if (classESet) { result.append(class_); } else { result.append("<unset>"); } result.append(", lang: "); result.append(lang); result.append(", style: "); if (styleESet) { result.append(style); } else { result.append("<unset>"); } result.append(')'); return result.toString(); } } // CodeImpl
drbgfc/mdht
hl7/plugins/org.openhealthtools.mdht.emf.hl7.mif2/src/org/openhealthtools/mdht/emf/w3c/xhtml/internal/impl/CodeImpl.java
Java
epl-1.0
8,990
/******************************************************************************* * Copyright (c) 2005-2010 VecTrace (Zingo Andersen) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * John Peberdy implementation *******************************************************************************/ package com.vectrace.MercurialEclipse.commands; import java.io.File; import java.util.List; import org.eclipse.core.runtime.Assert; /** * A command to invoke hg definitely outside of an hg root. */ public class RootlessHgCommand extends AbstractShellCommand { public RootlessHgCommand(String command, String uiName) { this(command, uiName, null); } public RootlessHgCommand(String command, String uiName, File workingDir) { super(uiName, null, workingDir, false); Assert.isNotNull(command); this.command = command; } // operations /** * @see com.vectrace.MercurialEclipse.commands.AbstractShellCommand#customizeCommands(java.util.List) */ @Override protected void customizeCommands(List<String> cmd) { cmd.add(1, "-y"); } /** * @see com.vectrace.MercurialEclipse.commands.AbstractShellCommand#getExecutable() */ @Override protected String getExecutable() { return HgClients.getExecutable(); } }
boa0332/mercurialeclipse
plugin/src/com/vectrace/MercurialEclipse/commands/RootlessHgCommand.java
Java
epl-1.0
1,464
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.smoketest; import org.junit.Before; import org.junit.Test; public class ChartsPageTest extends OpenNMSSeleniumTestCase { @Before public void setUp() throws Exception { super.setUp(); clickAndWait("link=Charts"); } @Test public void testChartsPage() throws Exception { waitForText("Charts"); waitForElement("css=img[alt=sample-bar-chart]"); waitForElement("css=img[alt=sample-bar-chart2]"); waitForElement("css=img[alt=sample-bar-chart3]"); } }
rfdrake/opennms
smoke-test/src/test/java/org/opennms/smoketest/ChartsPageTest.java
Java
gpl-2.0
1,723
<?php /** * @package gantry * @subpackage core * @version 3.2.12 October 30, 2011 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system * */ defined('GANTRY_VERSION') or die(); /** * Base class for all Gantry custom features. * * @package gantry * @subpackage core */ class GantryLayout { var $render_params = array(); function render($params = array()){ global $gantry; ob_start(); return ob_get_clean(); } function _getParams($params = array()){ $ret = new stdClass(); $ret_array = array_merge($this->render_params, $params); foreach($ret_array as $param_name => $param_value){ $ret->$param_name = $param_value; } return $ret; } }
worldwideinterweb/joomla-173
libraries/gantry/core/gantrylayout.class.php
PHP
gpl-2.0
973
<?php class WikiLeaksBridge extends BridgeAbstract { const NAME = 'WikiLeaks'; const URI = 'https://wikileaks.org'; const DESCRIPTION = 'Returns the latest news or articles from WikiLeaks'; const MAINTAINER = 'logmanoriginal'; const PARAMETERS = array( array( 'category' => array( 'name' => 'Category', 'type' => 'list', 'required' => true, 'title' => 'Select your category', 'values' => array( 'News' => '-News-', 'Leaks' => array( 'All' => '-Leaks-', 'Intelligence' => '+-Intelligence-+', 'Global Economy' => '+-Global-Economy-+', 'International Politics' => '+-International-Politics-+', 'Corporations' => '+-Corporations-+', 'Government' => '+-Government-+', 'War & Military' => '+-War-Military-+' ) ), 'defaultValue' => 'news' ), 'teaser' => array( 'name' => 'Show teaser', 'type' => 'checkbox', 'required' => false, 'title' => 'If checked feeds will display the teaser', 'defaultValue' => true ) ) ); public function collectData(){ $html = getSimpleHTMLDOM($this->getURI()); // News are presented differently switch($this->getInput('category')) { case '-News-': $this->loadNewsItems($html); break; default: $this->loadLeakItems($html); } } public function getURI(){ if(!is_null($this->getInput('category'))) { return static::URI . '/' . $this->getInput('category') . '.html'; } return parent::getURI(); } public function getName(){ if(!is_null($this->getInput('category'))) { $category = array_search( $this->getInput('category'), static::PARAMETERS[0]['category']['values'] ); if($category === false) { $category = array_search( $this->getInput('category'), static::PARAMETERS[0]['category']['values']['Leaks'] ); } return $category . ' - ' . static::NAME; } return parent::getName(); } private function loadNewsItems($html){ $articles = $html->find('div.news-articles ul li'); if(is_null($articles) || count($articles) === 0) { return; } foreach($articles as $article) { $item = array(); $item['title'] = $article->find('h3', 0)->plaintext; $item['uri'] = static::URI . $article->find('h3 a', 0)->href; $item['content'] = $article->find('div.introduction', 0)->plaintext; $item['timestamp'] = strtotime($article->find('div.timestamp', 0)->plaintext); $this->items[] = $item; } } private function loadLeakItems($html){ $articles = $html->find('li.tile'); if(is_null($articles) || count($articles) === 0) { return; } foreach($articles as $article) { $item = array(); $item['title'] = $article->find('h2', 0)->plaintext; $item['uri'] = static::URI . $article->find('a', 0)->href; $teaser = static::URI . '/' . $article->find('div.teaser img', 0)->src; if($this->getInput('teaser')) { $item['content'] = '<img src="' . $teaser . '" /><p>' . $article->find('div.intro', 0)->plaintext . '</p>'; } else { $item['content'] = $article->find('div.intro', 0)->plaintext; } $item['timestamp'] = strtotime($article->find('div.timestamp', 0)->plaintext); $item['enclosures'] = array($teaser); $this->items[] = $item; } } }
stupiddingo/boisewaldorf
web/UXsQTutSQY7w7u6s/bridges/WikiLeaksBridge.php
PHP
gpl-2.0
3,255
/** * @file DllLoader.cpp * @author Minmin Gong * * @section DESCRIPTION * * This source file is part of KFL, a subproject of KlayGE * For the latest info, see http://www.klayge.org * * @section LICENSE * * 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; either version 2 of the License, or * (at your option) any later version. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * You may alternatively use this source under the terms of * the KlayGE Proprietary License (KPL). You can obtained such a license * from http://www.klayge.org/licensing/. */ #include <KFL/KFL.hpp> #include <KFL/ResIdentifier.hpp> #ifdef KLAYGE_PLATFORM_WINDOWS #include <windows.h> #else #include <dlfcn.h> #endif #include <KFL/DllLoader.hpp> namespace KlayGE { DllLoader::DllLoader() : dll_handle_(nullptr) { } DllLoader::~DllLoader() { this->Free(); } bool DllLoader::Load(std::string const & dll_name) { #ifdef KLAYGE_PLATFORM_WINDOWS #ifdef KLAYGE_PLATFORM_WINDOWS_DESKTOP dll_handle_ = static_cast<void*>(::LoadLibraryExA(dll_name.c_str(), nullptr, 0)); #else std::wstring wname; Convert(wname, dll_name); dll_handle_ = static_cast<void*>(::LoadPackagedLibrary(wname.c_str(), 0)); #endif #else dll_handle_ = ::dlopen(dll_name.c_str(), RTLD_LAZY); #endif return (dll_handle_ != nullptr); } void DllLoader::Free() { if (dll_handle_) { #ifdef KLAYGE_PLATFORM_WINDOWS ::FreeLibrary(static_cast<HMODULE>(dll_handle_)); #else ::dlclose(dll_handle_); #endif } } void* DllLoader::GetProcAddress(std::string const & proc_name) { #ifdef KLAYGE_PLATFORM_WINDOWS return reinterpret_cast<void*>(::GetProcAddress(static_cast<HMODULE>(dll_handle_), proc_name.c_str())); #else return ::dlsym(dll_handle_, proc_name.c_str()); #endif } }
qiankanglai/KlayGE
KFL/src/Kernel/DllLoader.cpp
C++
gpl-2.0
2,405
/** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'magicline', 'it', { title: 'Inserisci paragrafo qui' } );
SeeyaSia/www
web/libraries/ckeditor/plugins/magicline/lang/it.js
JavaScript
gpl-2.0
247
/* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/> * 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; either version 2 of the License, or * (at your option) any later version. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Instance_Hellfire_Ramparts SD%Complete: 50 SDComment: SDCategory: Hellfire Ramparts EndScriptData */ #include "precompiled.h" #include "hellfire_ramparts.h" instance_ramparts::instance_ramparts(Map* pMap) : ScriptedInstance(pMap), m_uiSentryCounter(0) { Initialize(); } void instance_ramparts::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); } void instance_ramparts::OnCreatureCreate(Creature* pCreature) { switch (pCreature->GetEntry()) { case NPC_VAZRUDEN_HERALD: case NPC_VAZRUDEN: m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid(); break; case NPC_HELLFIRE_SENTRY: m_lSentryGUIDs.push_back(pCreature->GetObjectGuid()); break; } } void instance_ramparts::OnObjectCreate(GameObject* pGo) { switch (pGo->GetEntry()) { case GO_FEL_IRON_CHEST: case GO_FEL_IRON_CHEST_H: m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); break; } } void instance_ramparts::SetData(uint32 uiType, uint32 uiData) { debug_log("SD2: Instance Ramparts: SetData received for type %u with data %u",uiType,uiData); switch (uiType) { case TYPE_VAZRUDEN: if (uiData == DONE && m_auiEncounter[1] == DONE) DoRespawnGameObject(instance->IsRegularDifficulty() ? GO_FEL_IRON_CHEST : GO_FEL_IRON_CHEST_H, HOUR); if (uiData == FAIL && m_auiEncounter[0] != FAIL) DoFailVazruden(); m_auiEncounter[0] = uiData; break; case TYPE_NAZAN: if (uiData == SPECIAL) { ++m_uiSentryCounter; if (m_uiSentryCounter == 2) m_auiEncounter[1] = uiData; return; } if (uiData == DONE && m_auiEncounter[0] == DONE) { DoRespawnGameObject(instance->IsRegularDifficulty() ? GO_FEL_IRON_CHEST : GO_FEL_IRON_CHEST_H, HOUR); DoToggleGameObjectFlags(instance->IsRegularDifficulty() ? GO_FEL_IRON_CHEST : GO_FEL_IRON_CHEST_H, GO_FLAG_NO_INTERACT, false); } if (uiData == FAIL && m_auiEncounter[1] != FAIL) DoFailVazruden(); m_auiEncounter[1] = uiData; break; } } uint32 instance_ramparts::GetData(uint32 uiType) { if (uiType == TYPE_VAZRUDEN) return m_auiEncounter[0]; if (uiType == TYPE_NAZAN) return m_auiEncounter[1]; return 0; } void instance_ramparts::DoFailVazruden() { // Store FAIL for both types m_auiEncounter[0] = FAIL; m_auiEncounter[1] = FAIL; // Restore Sentries (counter and respawn them) m_uiSentryCounter = 0; for (GuidList::const_iterator itr = m_lSentryGUIDs.begin(); itr != m_lSentryGUIDs.end(); ++itr) { if (Creature* pSentry = instance->GetCreature(*itr)) pSentry->Respawn(); } // Respawn or Reset Vazruden the herald if (Creature* pVazruden = GetSingleCreatureFromStorage(NPC_VAZRUDEN_HERALD)) { if (!pVazruden->isAlive()) pVazruden->Respawn(); else { if (ScriptedAI* pVazrudenAI = dynamic_cast<ScriptedAI*> (pVazruden->AI())) pVazrudenAI->Reset(); } } // Despawn Vazruden if (Creature* pVazruden = GetSingleCreatureFromStorage(NPC_VAZRUDEN)) pVazruden->ForcedDespawn(); } InstanceData* GetInstanceData_instance_ramparts(Map* pMap) { return new instance_ramparts(pMap); } void AddSC_instance_ramparts() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "instance_ramparts"; pNewScript->GetInstanceData = &GetInstanceData_instance_ramparts; pNewScript->RegisterSelf(); }
Remix99/MaNGOS
src/bindings/scriptdev2/scripts/outland/hellfire_citadel/hellfire_ramparts/instance_hellfire_ramparts.cpp
C++
gpl-2.0
4,618
<?php /* V4.81 3 May 2006 (c) 2000-2006 John Lim. All rights reserved. Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Set tabs to 4 for best viewing. Latest version is available at http://adodb.sourceforge.net Sybase driver contributed by Toni (toni.tunkkari@finebyte.com) - MSSQL date patch applied. Date patch by Toni 15 Feb 2002 */ // security - hide paths if (!defined('ADODB_DIR')) die(); class ADODB_sybase extends ADOConnection { var $databaseType = "sybase"; var $dataProvider = 'sybase'; var $replaceQuote = "''"; // string to use to replace quotes var $fmtDate = "'Y-m-d'"; var $fmtTimeStamp = "'Y-m-d H:i:s'"; var $hasInsertID = true; var $hasAffectedRows = true; var $metaTablesSQL="select name from sysobjects where type='U' or type='V'"; // see http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8 var $metaColumnsSQL = "SELECT c.column_name, c.column_type, c.width FROM syscolumn c, systable t WHERE t.table_name='%s' AND c.table_id=t.table_id AND t.table_type='BASE'"; /* "select c.name,t.name,c.length from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'"; */ var $concat_operator = '+'; var $arrayClass = 'ADORecordSet_array_sybase'; var $sysDate = 'GetDate()'; var $leftOuter = '*='; var $rightOuter = '=*'; function ADODB_sybase() { } // might require begintrans -- committrans function _insertid() { return $this->GetOne('select @@identity'); } // might require begintrans -- committrans function _affectedrows() { return $this->GetOne('select @@rowcount'); } function BeginTrans() { if ($this->transOff) return true; $this->transCnt += 1; $this->Execute('BEGIN TRAN'); return true; } function CommitTrans($ok=true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); $this->transCnt -= 1; $this->Execute('COMMIT TRAN'); return true; } function RollbackTrans() { if ($this->transOff) return true; $this->transCnt -= 1; $this->Execute('ROLLBACK TRAN'); return true; } // http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4 function RowLock($tables,$where,$flds='top 1 null as ignore') { if (!$this->_hastrans) $this->BeginTrans(); $tables = str_replace(',',' HOLDLOCK,',$tables); return $this->GetOne("select $flds from $tables HOLDLOCK where $where"); } function SelectDB($dbName) { $this->database = $dbName; $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions if ($this->_connectionID) { return @sybase_select_db($dbName); } else return false; } /* Returns: the last error message from previous database operation Note: This function is NOT available for Microsoft SQL Server. */ function ErrorMsg() { if ($this->_logsql) return $this->_errorMsg; if (function_exists('sybase_get_last_message')) $this->_errorMsg = sybase_get_last_message(); else $this->_errorMsg = isset($php_errormsg) ? $php_errormsg : 'SYBASE error messages not supported on this platform'; return $this->_errorMsg; } // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('sybase_connect')) return null; $this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword); if ($this->_connectionID === false) return false; if ($argDatabasename) return $this->SelectDB($argDatabasename); return true; } // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('sybase_connect')) return null; $this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword); if ($this->_connectionID === false) return false; if ($argDatabasename) return $this->SelectDB($argDatabasename); return true; } // returns query ID if successful, otherwise false function _query($sql,$inputarr) { global $ADODB_COUNTRECS; if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300) return sybase_unbuffered_query($sql,$this->_connectionID); else return sybase_query($sql,$this->_connectionID); } // See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12 function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) { if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); return $rs; } $nrows = (integer) $nrows; $offset = (integer) $offset; $cnt = ($nrows >= 0) ? $nrows : 999999999; if ($offset > 0 && $cnt) $cnt += $offset; $this->Execute("set rowcount $cnt"); $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,0); $this->Execute("set rowcount 0"); return $rs; } // returns true or false function _close() { return @sybase_close($this->_connectionID); } function UnixDate($v) { return ADORecordSet_array_sybase::UnixDate($v); } function UnixTimeStamp($v) { return ADORecordSet_array_sybase::UnixTimeStamp($v); } # Added 2003-10-05 by Chris Phillipson # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=16756?target=%25N%15_12018_START_RESTART_N%25 # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version // Format date column in sql string given an input format that understands Y M D function SQLDate($fmt, $col=false) { if (!$col) $col = $this->sysTimeStamp; $s = ''; $len = strlen($fmt); for ($i=0; $i < $len; $i++) { if ($s) $s .= '+'; $ch = $fmt[$i]; switch($ch) { case 'Y': case 'y': $s .= "datename(yy,$col)"; break; case 'M': $s .= "convert(char(3),$col,0)"; break; case 'm': $s .= "replace(str(month($col),2),' ','0')"; break; case 'Q': case 'q': $s .= "datename(qq,$col)"; break; case 'D': case 'd': $s .= "replace(str(datepart(dd,$col),2),' ','0')"; break; case 'h': $s .= "substring(convert(char(14),$col,0),13,2)"; break; case 'H': $s .= "replace(str(datepart(hh,$col),2),' ','0')"; break; case 'i': $s .= "replace(str(datepart(mi,$col),2),' ','0')"; break; case 's': $s .= "replace(str(datepart(ss,$col),2),' ','0')"; break; case 'a': case 'A': $s .= "substring(convert(char(19),$col,0),18,2)"; break; default: if ($ch == '\\') { $i++; $ch = substr($fmt,$i,1); } $s .= $this->qstr($ch); break; } } return $s; } # Added 2003-10-07 by Chris Phillipson # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8 # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version function MetaPrimaryKeys($table) { $sql = "SELECT c.column_name " . "FROM syscolumn c, systable t " . "WHERE t.table_name='$table' AND c.table_id=t.table_id " . "AND t.table_type='BASE' " . "AND c.pkey = 'Y' " . "ORDER BY c.column_id"; $a = $this->GetCol($sql); if ($a && sizeof($a)>0) return $a; return false; } } /*-------------------------------------------------------------------------------------- Class Name: Recordset --------------------------------------------------------------------------------------*/ global $ADODB_sybase_mths; $ADODB_sybase_mths = array( 'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6, 'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); class ADORecordset_sybase extends ADORecordSet { var $databaseType = "sybase"; var $canSeek = true; // _mths works only in non-localised system var $_mths = array('JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); function ADORecordset_sybase($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC; else $this->fetchMode = $mode; $this->ADORecordSet($id,$mode); } /* Returns: an object containing field information. Get column information in the Recordset object. fetchField() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by fetchField() is retrieved. */ function &FetchField($fieldOffset = -1) { if ($fieldOffset != -1) { $o = @sybase_fetch_field($this->_queryID, $fieldOffset); } else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ $o = @sybase_fetch_field($this->_queryID); } // older versions of PHP did not support type, only numeric if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar'; return $o; } function _initrs() { global $ADODB_COUNTRECS; $this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1; $this->_numOfFields = @sybase_num_fields($this->_queryID); } function _seek($row) { return @sybase_data_seek($this->_queryID, $row); } function _fetch($ignore_fields=false) { if ($this->fetchMode == ADODB_FETCH_NUM) { $this->fields = @sybase_fetch_row($this->_queryID); } else if ($this->fetchMode == ADODB_FETCH_ASSOC) { $this->fields = @sybase_fetch_row($this->_queryID); if (is_array($this->fields)) { $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); return true; } return false; } else { $this->fields = @sybase_fetch_array($this->_queryID); } if ( is_array($this->fields)) { return true; } return false; } /* close() only needs to be called if you are worried about using too much memory while your script is running. All associated result memory for the specified result identifier will automatically be freed. */ function _close() { return @sybase_free_result($this->_queryID); } // sybase/mssql uses a default date like Dec 30 2000 12:00AM function UnixDate($v) { return ADORecordSet_array_sybase::UnixDate($v); } function UnixTimeStamp($v) { return ADORecordSet_array_sybase::UnixTimeStamp($v); } } class ADORecordSet_array_sybase extends ADORecordSet_array { function ADORecordSet_array_sybase($id=-1) { $this->ADORecordSet_array($id); } // sybase/mssql uses a default date like Dec 30 2000 12:00AM function UnixDate($v) { global $ADODB_sybase_mths; //Dec 30 2000 12:00AM if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})" ,$v, $rr)) return parent::UnixDate($v); if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $themth = substr(strtoupper($rr[1]),0,3); $themth = $ADODB_sybase_mths[$themth]; if ($themth <= 0) return false; // h-m-s-MM-DD-YY return mktime(0,0,0,$themth,$rr[2],$rr[3]); } function UnixTimeStamp($v) { global $ADODB_sybase_mths; //11.02.2001 Toni Tunkkari toni.tunkkari@finebyte.com //Changed [0-9] to [0-9 ] in day conversion if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})" ,$v, $rr)) return parent::UnixTimeStamp($v); if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0; $themth = substr(strtoupper($rr[1]),0,3); $themth = $ADODB_sybase_mths[$themth]; if ($themth <= 0) return false; switch (strtoupper($rr[6])) { case 'P': if ($rr[4]<12) $rr[4] += 12; break; case 'A': if ($rr[4]==12) $rr[4] = 0; break; default: break; } // h-m-s-MM-DD-YY return mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]); } } ?>
omerta/huayra
shared/class_folder/adodb/drivers/adodb-sybase.inc.php
PHP
gpl-2.0
12,524
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * * 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; either version 2 of the License, or (at your * option) any later version. * * 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, see <http://www.gnu.org/licenses/>. */ /* * Scripts for spells with SPELLFAMILY_DEATHKNIGHT and SPELLFAMILY_GENERIC spells used by deathknight players. * Ordered alphabetically using scriptname. * Scriptnames of files in this file should be prefixed with "spell_dk_". */ #include "ScriptMgr.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "Unit.h" #include "Player.h" #include "Pet.h" enum HunterPetCalculate { SPELL_TAMED_PET_PASSIVE_06 = 19591, SPELL_TAMED_PET_PASSIVE_07 = 20784, SPELL_TAMED_PET_PASSIVE_08 = 34666, SPELL_TAMED_PET_PASSIVE_09 = 34667, SPELL_TAMED_PET_PASSIVE_10 = 34675, SPELL_HUNTER_PET_SCALING_01 = 34902, SPELL_HUNTER_PET_SCALING_02 = 34903, SPELL_HUNTER_PET_SCALING_03 = 34904, SPELL_HUNTER_PET_SCALING_04 = 61017, SPELL_HUNTER_ANIMAL_HANDLER = 34453, }; enum WarlockPetCalculate { SPELL_PET_PASSIVE_CRIT = 35695, SPELL_PET_PASSIVE_DAMAGE_TAKEN = 35697, SPELL_WARLOCK_PET_SCALING_01 = 34947, SPELL_WARLOCK_PET_SCALING_02 = 34956, SPELL_WARLOCK_PET_SCALING_03 = 34957, SPELL_WARLOCK_PET_SCALING_04 = 34958, SPELL_WARLOCK_PET_SCALING_05 = 61013, ENTRY_FELGUARD = 17252, ENTRY_VOIDWALKER = 1860, ENTRY_FELHUNTER = 417, ENTRY_SUCCUBUS = 1863, ENTRY_IMP = 416, SPELL_WARLOCK_GLYPH_OF_VOIDWALKER = 56247, }; enum DKPetCalculate { SPELL_DEATH_KNIGHT_RUNE_WEAPON_02 = 51906, SPELL_DEATH_KNIGHT_PET_SCALING_01 = 54566, SPELL_DEATH_KNIGHT_PET_SCALING_02 = 51996, SPELL_DEATH_KNIGHT_PET_SCALING_03 = 61697, SPELL_NIGHT_OF_THE_DEAD = 55620, ENTRY_ARMY_OF_THE_DEAD_GHOUL = 24207, SPELL_DEATH_KNIGHT_GLYPH_OF_GHOUL = 58686, }; enum ShamanPetCalculate { SPELL_FERAL_SPIRIT_PET_UNK_01 = 35674, SPELL_FERAL_SPIRIT_PET_UNK_02 = 35675, SPELL_FERAL_SPIRIT_PET_UNK_03 = 35676, SPELL_FERAL_SPIRIT_PET_SCALING_04 = 61783, }; enum MiscPetCalculate { SPELL_MAGE_PET_PASSIVE_ELEMENTAL = 44559, SPELL_PET_HEALTH_SCALING = 61679, SPELL_PET_UNK_01 = 67561, SPELL_PET_UNK_02 = 67557, }; class spell_gen_pet_calculate : public SpellScriptLoader { public: spell_gen_pet_calculate() : SpellScriptLoader("spell_gen_pet_calculate") { } class spell_gen_pet_calculate_AuraScript : public AuraScript { PrepareAuraScript(spell_gen_pet_calculate_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountCritSpell(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritSpell = 0.0f; // Crit from Intellect CritSpell += owner->GetSpellCritFromIntellect(); // Increase crit from SPELL_AURA_MOD_SPELL_CRIT_CHANCE CritSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_CRIT_CHANCE); // Increase crit from SPELL_AURA_MOD_CRIT_PCT CritSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); // Increase crit spell from spell crit ratings CritSpell += owner->GetRatingBonusValue(CR_CRIT_SPELL); amount += int32(CritSpell); } } void CalculateAmountCritMelee(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritMelee = 0.0f; // Crit from Agility CritMelee += owner->GetMeleeCritFromAgility(); // Increase crit from SPELL_AURA_MOD_WEAPON_CRIT_PERCENT CritMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); // Increase crit from SPELL_AURA_MOD_CRIT_PCT CritMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); // Increase crit melee from melee crit ratings CritMelee += owner->GetRatingBonusValue(CR_CRIT_MELEE); amount += int32(CritMelee); } } void CalculateAmountMeleeHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from SPELL_AURA_MOD_HIT_CHANCE HitMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_HIT_CHANCE); // Increase hit melee from meele hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_MELEE); amount += int32(HitMelee); } } void CalculateAmountSpellHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from SPELL_AURA_MOD_SPELL_HIT_CHANCE HitSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_HIT_CHANCE); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void CalculateAmountExpertise(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float Expertise = 0.0f; // Increase hit from SPELL_AURA_MOD_EXPERTISE Expertise += owner->GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE); // Increase Expertise from Expertise ratings Expertise += owner->GetRatingBonusValue(CR_EXPERTISE); amount += int32(Expertise); } } void Register() OVERRIDE { switch (m_scriptSpellId) { case SPELL_TAMED_PET_PASSIVE_06: DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountCritMelee, EFFECT_0, SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountCritSpell, EFFECT_1, SPELL_AURA_MOD_SPELL_CRIT_CHANCE); break; case SPELL_PET_PASSIVE_CRIT: DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountCritSpell, EFFECT_0, SPELL_AURA_MOD_SPELL_CRIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountCritMelee, EFFECT_1, SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); break; case SPELL_WARLOCK_PET_SCALING_05: case SPELL_HUNTER_PET_SCALING_04: DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountMeleeHit, EFFECT_0, SPELL_AURA_MOD_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountSpellHit, EFFECT_1, SPELL_AURA_MOD_SPELL_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountExpertise, EFFECT_2, SPELL_AURA_MOD_EXPERTISE); break; case SPELL_DEATH_KNIGHT_PET_SCALING_03: // case SPELL_SHAMAN_PET_HIT: DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountMeleeHit, EFFECT_0, SPELL_AURA_MOD_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_gen_pet_calculate_AuraScript::CalculateAmountSpellHit, EFFECT_1, SPELL_AURA_MOD_SPELL_HIT_CHANCE); break; default: break; } } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_gen_pet_calculate_AuraScript(); } }; class spell_warl_pet_scaling_01 : public SpellScriptLoader { public: spell_warl_pet_scaling_01() : SpellScriptLoader("spell_warl_pet_scaling_01") { } class spell_warl_pet_scaling_01_AuraScript : public AuraScript { PrepareAuraScript(spell_warl_pet_scaling_01_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; _tempBonus = 0; return true; } void CalculateStaminaAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = CalculatePct(owner->GetStat(STAT_STAMINA), 75); amount += ownerBonus; } } void ApplyEffect(AuraEffect const* /* aurEff */, AuraEffectHandleModes /*mode*/) { if (Unit* pet = GetUnitOwner()) if (_tempBonus) { PetLevelInfo const* pInfo = sObjectMgr->GetPetLevelInfo(pet->GetEntry(), pet->getLevel()); uint32 healthMod = 0; uint32 baseHealth = pInfo->health; switch (pet->GetEntry()) { case ENTRY_IMP: healthMod = uint32(_tempBonus * 8.4f); break; case ENTRY_FELGUARD: case ENTRY_VOIDWALKER: healthMod = _tempBonus * 11; break; case ENTRY_SUCCUBUS: healthMod = uint32(_tempBonus * 9.1f); break; case ENTRY_FELHUNTER: healthMod = uint32(_tempBonus * 9.5f); break; default: healthMod = 0; break; } if (healthMod) pet->ToPet()->SetCreateHealth(baseHealth + healthMod); } } void RemoveEffect(AuraEffect const* /* aurEff */, AuraEffectHandleModes /*mode*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) { PetLevelInfo const* pInfo = sObjectMgr->GetPetLevelInfo(pet->GetEntry(), pet->getLevel()); pet->ToPet()->SetCreateHealth(pInfo->health); } } void CalculateAttackPowerAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { int32 fire = int32(owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE)) - owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_FIRE); int32 shadow = int32(owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW)) - owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_SHADOW); int32 maximum = (fire > shadow) ? fire : shadow; if (maximum < 0) maximum = 0; float bonusAP = maximum * 0.57f; amount += bonusAP; // Glyph of felguard if (pet->GetEntry() == ENTRY_FELGUARD) { if (AuraEffect* /* aurEff */ect = owner->GetAuraEffect(56246, EFFECT_0)) { float base_attPower = pet->GetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_VALUE) * pet->GetModifierValue(UNIT_MOD_ATTACK_POWER, BASE_PCT); amount += CalculatePct(amount+base_attPower, /* aurEff */ect->GetAmount()); } } } } void CalculateDamageDoneAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { //the damage bonus used for pets is either fire or shadow damage, whatever is higher int32 fire = int32(owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FIRE)) - owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_FIRE); int32 shadow = int32(owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW)) - owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_SHADOW); int32 maximum = (fire > shadow) ? fire : shadow; float bonusDamage = 0.0f; if (maximum > 0) bonusDamage = maximum * 0.15f; amount += bonusDamage; } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(spell_warl_pet_scaling_01_AuraScript::RemoveEffect, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK); AfterEffectApply += AuraEffectApplyFn(spell_warl_pet_scaling_01_AuraScript::ApplyEffect, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_01_AuraScript::CalculateStaminaAmount, EFFECT_0, SPELL_AURA_MOD_STAT); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_01_AuraScript::CalculateAttackPowerAmount, EFFECT_1, SPELL_AURA_MOD_ATTACK_POWER); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_01_AuraScript::CalculateDamageDoneAmount, EFFECT_2, SPELL_AURA_MOD_DAMAGE_DONE); } private: uint32 _tempBonus; }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_warl_pet_scaling_01_AuraScript(); } }; class spell_warl_pet_scaling_02 : public SpellScriptLoader { public: spell_warl_pet_scaling_02() : SpellScriptLoader("spell_warl_pet_scaling_02") { } class spell_warl_pet_scaling_02_AuraScript : public AuraScript { PrepareAuraScript(spell_warl_pet_scaling_02_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; _tempBonus = 0; return true; } void CalculateIntellectAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetStat(STAT_INTELLECT), 30); amount += ownerBonus; _tempBonus = ownerBonus; } } void ApplyEffect(AuraEffect const* /* aurEff */, AuraEffectHandleModes /*mode*/) { if (Unit* pet = GetUnitOwner()) if (_tempBonus) { PetLevelInfo const* pInfo = sObjectMgr->GetPetLevelInfo(pet->GetEntry(), pet->getLevel()); uint32 manaMod = 0; uint32 baseMana = pInfo->mana; switch (pet->GetEntry()) { case ENTRY_IMP: manaMod = uint32(_tempBonus * 4.9f); break; case ENTRY_VOIDWALKER: case ENTRY_SUCCUBUS: case ENTRY_FELHUNTER: case ENTRY_FELGUARD: manaMod = uint32(_tempBonus * 11.5f); break; default: manaMod = 0; break; } if (manaMod) pet->ToPet()->SetCreateMana(baseMana + manaMod); } } void RemoveEffect(AuraEffect const* /* aurEff */, AuraEffectHandleModes /*mode*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) { PetLevelInfo const* pInfo = sObjectMgr->GetPetLevelInfo(pet->GetEntry(), pet->getLevel()); pet->ToPet()->SetCreateMana(pInfo->mana); } } void CalculateArmorAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetArmor(), 35); amount += ownerBonus; } } void CalculateFireResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_FIRE), 40); amount += ownerBonus; } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(spell_warl_pet_scaling_02_AuraScript::RemoveEffect, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK); AfterEffectApply += AuraEffectApplyFn(spell_warl_pet_scaling_02_AuraScript::ApplyEffect, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_02_AuraScript::CalculateIntellectAmount, EFFECT_0, SPELL_AURA_MOD_STAT); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_02_AuraScript::CalculateArmorAmount, EFFECT_1, SPELL_AURA_MOD_RESISTANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_02_AuraScript::CalculateFireResistanceAmount, EFFECT_2, SPELL_AURA_MOD_RESISTANCE); } private: uint32 _tempBonus; }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_warl_pet_scaling_02_AuraScript(); } }; class spell_warl_pet_scaling_03 : public SpellScriptLoader { public: spell_warl_pet_scaling_03() : SpellScriptLoader("spell_warl_pet_scaling_03") { } class spell_warl_pet_scaling_03_AuraScript : public AuraScript { PrepareAuraScript(spell_warl_pet_scaling_03_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateFrostResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_FROST), 40); amount += ownerBonus; } } void CalculateArcaneResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_ARCANE), 40); amount += ownerBonus; } } void CalculateNatureResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_NATURE), 40); amount += ownerBonus; } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_03_AuraScript::CalculateFrostResistanceAmount, EFFECT_0, SPELL_AURA_MOD_RESISTANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_03_AuraScript::CalculateArcaneResistanceAmount, EFFECT_1, SPELL_AURA_MOD_RESISTANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_03_AuraScript::CalculateNatureResistanceAmount, EFFECT_2, SPELL_AURA_MOD_RESISTANCE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_warl_pet_scaling_03_AuraScript(); } }; class spell_warl_pet_scaling_04 : public SpellScriptLoader { public: spell_warl_pet_scaling_04() : SpellScriptLoader("spell_warl_pet_scaling_04") { } class spell_warl_pet_scaling_04_AuraScript : public AuraScript { PrepareAuraScript(spell_warl_pet_scaling_04_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateShadowResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_SHADOW), 40); amount += ownerBonus; } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_04_AuraScript::CalculateShadowResistanceAmount, EFFECT_0, SPELL_AURA_MOD_RESISTANCE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_warl_pet_scaling_04_AuraScript(); } }; class spell_warl_pet_scaling_05 : public SpellScriptLoader { public: spell_warl_pet_scaling_05() : SpellScriptLoader("spell_warl_pet_scaling_05") { } class spell_warl_pet_scaling_05_AuraScript : public AuraScript { PrepareAuraScript(spell_warl_pet_scaling_05_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountMeleeHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from SPELL_AURA_MOD_SPELL_HIT_CHANCE HitMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_HIT_CHANCE); // Increase hit spell from spell hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitMelee); } } void CalculateAmountSpellHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from SPELL_AURA_MOD_SPELL_HIT_CHANCE HitSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_HIT_CHANCE); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void CalculateAmountExpertise(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float Expertise = 0.0f; // Increase hit from SPELL_AURA_MOD_SPELL_HIT_CHANCE Expertise += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_HIT_CHANCE); // Increase hit spell from spell hit ratings Expertise += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(Expertise); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_05_AuraScript::CalculateAmountMeleeHit, EFFECT_0, SPELL_AURA_MOD_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_05_AuraScript::CalculateAmountSpellHit, EFFECT_1, SPELL_AURA_MOD_SPELL_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_scaling_05_AuraScript::CalculateAmountExpertise, EFFECT_2, SPELL_AURA_MOD_EXPERTISE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_warl_pet_scaling_05_AuraScript(); } }; class spell_warl_pet_passive : public SpellScriptLoader { public: spell_warl_pet_passive() : SpellScriptLoader("spell_warl_pet_passive") { } class spell_warl_pet_passive_AuraScript : public AuraScript { PrepareAuraScript(spell_warl_pet_passive_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountCritSpell(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritSpell = 0.0f; // Crit from Intellect CritSpell += owner->GetSpellCritFromIntellect(); // Increase crit from SPELL_AURA_MOD_SPELL_CRIT_CHANCE CritSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_CRIT_CHANCE); // Increase crit from SPELL_AURA_MOD_CRIT_PCT CritSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); // Increase crit spell from spell crit ratings CritSpell += owner->GetRatingBonusValue(CR_CRIT_SPELL); if (AuraApplication* improvedDemonicTacticsApp = owner->GetAuraApplicationOfRankedSpell(54347)) if (Aura* improvedDemonicTactics = improvedDemonicTacticsApp->GetBase()) if (AuraEffect* improvedDemonicTacticsEffect = improvedDemonicTactics->GetEffect(EFFECT_0)) amount += CalculatePct(CritSpell, improvedDemonicTacticsEffect->GetAmount()); } } void CalculateAmountCritMelee(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritMelee = 0.0f; // Crit from Agility CritMelee += owner->GetMeleeCritFromAgility(); // Increase crit from SPELL_AURA_MOD_WEAPON_CRIT_PERCENT CritMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); // Increase crit from SPELL_AURA_MOD_CRIT_PCT CritMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); // Increase crit melee from melee crit ratings CritMelee += owner->GetRatingBonusValue(CR_CRIT_MELEE); if (AuraApplication* improvedDemonicTacticsApp = owner->GetAuraApplicationOfRankedSpell(54347)) if (Aura* improvedDemonicTactics = improvedDemonicTacticsApp->GetBase()) if (AuraEffect* improvedDemonicTacticsEffect = improvedDemonicTactics->GetEffect(EFFECT_0)) amount += CalculatePct(CritMelee, improvedDemonicTacticsEffect->GetAmount()); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_passive_AuraScript::CalculateAmountCritSpell, EFFECT_0, SPELL_AURA_MOD_SPELL_CRIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_passive_AuraScript::CalculateAmountCritMelee, EFFECT_1, SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_warl_pet_passive_AuraScript(); } }; // this doesnt actually fit in here class spell_warl_pet_passive_damage_done : public SpellScriptLoader { public: spell_warl_pet_passive_damage_done() : SpellScriptLoader("spell_warl_pet_passive_damage_done") { } class spell_warl_pet_passive_damage_done_AuraScript : public AuraScript { PrepareAuraScript(spell_warl_pet_passive_damage_done_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountDamageDone(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (GetCaster()->GetOwner()->ToPlayer()) { switch (GetCaster()->GetEntry()) { case ENTRY_VOIDWALKER: amount += -16; break; case ENTRY_FELHUNTER: amount += -20; break; case ENTRY_SUCCUBUS: case ENTRY_FELGUARD: amount += 5; break; } } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_passive_damage_done_AuraScript::CalculateAmountDamageDone, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_passive_damage_done_AuraScript::CalculateAmountDamageDone, EFFECT_1, SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_warl_pet_passive_damage_done_AuraScript(); } }; class spell_warl_pet_passive_voidwalker : public SpellScriptLoader { public: spell_warl_pet_passive_voidwalker() : SpellScriptLoader("spell_warl_pet_passive_voidwalker") { } class spell_warl_pet_passive_voidwalker_AuraScript : public AuraScript { PrepareAuraScript(spell_warl_pet_passive_voidwalker_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) if (AuraEffect* /* aurEff */ect = owner->GetAuraEffect(SPELL_WARLOCK_GLYPH_OF_VOIDWALKER, EFFECT_0)) amount += /* aurEff */ect->GetAmount(); } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_warl_pet_passive_voidwalker_AuraScript::CalculateAmount, EFFECT_0, SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_warl_pet_passive_voidwalker_AuraScript(); } }; class spell_sha_pet_scaling_04 : public SpellScriptLoader { public: spell_sha_pet_scaling_04() : SpellScriptLoader("spell_sha_pet_scaling_04") { } class spell_sha_pet_scaling_04_AuraScript : public AuraScript { PrepareAuraScript(spell_sha_pet_scaling_04_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountMeleeHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from SPELL_AURA_MOD_HIT_CHANCE HitMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_HIT_CHANCE); // Increase hit melee from meele hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_MELEE); amount += int32(HitMelee); } } void CalculateAmountSpellHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from SPELL_AURA_MOD_SPELL_HIT_CHANCE HitSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_HIT_CHANCE); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_sha_pet_scaling_04_AuraScript::CalculateAmountMeleeHit, EFFECT_0, SPELL_AURA_MOD_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_sha_pet_scaling_04_AuraScript::CalculateAmountSpellHit, EFFECT_1, SPELL_AURA_MOD_SPELL_HIT_CHANCE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_sha_pet_scaling_04_AuraScript(); } }; class spell_hun_pet_scaling_01 : public SpellScriptLoader { public: spell_hun_pet_scaling_01() : SpellScriptLoader("spell_hun_pet_scaling_01") { } class spell_hun_pet_scaling_01_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_pet_scaling_01_AuraScript); void CalculateStaminaAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) if (pet->IsPet()) if (Unit* owner = pet->ToPet()->GetOwner()) { float mod = 0.45f; float ownerBonus = 0.0f; PetSpellMap::const_iterator itr = (pet->ToPet()->m_spells.find(62758)); // Wild Hunt rank 1 if (itr == pet->ToPet()->m_spells.end()) itr = pet->ToPet()->m_spells.find(62762); // Wild Hunt rank 2 if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value AddPct(mod, spellInfo->Effects[EFFECT_0].CalcValue()); } ownerBonus = owner->GetStat(STAT_STAMINA)*mod; amount += ownerBonus; } } void ApplyEffect(AuraEffect const* /* aurEff */, AuraEffectHandleModes /*mode*/) { if (Unit* pet = GetUnitOwner()) if (_tempHealth) pet->SetHealth(_tempHealth); } void RemoveEffect(AuraEffect const* /* aurEff */, AuraEffectHandleModes /*mode*/) { if (Unit* pet = GetUnitOwner()) _tempHealth = pet->GetHealth(); } void CalculateAttackPowerAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float mod = 1.0f; //Hunter contribution modifier float bonusAP = 0.0f; PetSpellMap::const_iterator itr = (pet->ToPet()->m_spells.find(62758)); // Wild Hunt rank 1 if (itr == pet->ToPet()->m_spells.end()) itr = pet->ToPet()->m_spells.find(62762); // Wild Hunt rank 2 if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value mod += CalculatePct(1.0f, spellInfo->Effects[EFFECT_1].CalcValue()); } bonusAP = owner->GetTotalAttackPowerValue(RANGED_ATTACK) * 0.22f * mod; amount += bonusAP; } } void CalculateDamageDoneAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float mod = 1.0f; //Hunter contribution modifier float bonusDamage = 0.0f; PetSpellMap::const_iterator itr = (pet->ToPet()->m_spells.find(62758)); // Wild Hunt rank 1 if (itr == pet->ToPet()->m_spells.end()) itr = pet->ToPet()->m_spells.find(62762); // Wild Hunt rank 2 if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value mod += CalculatePct(1.0f, spellInfo->Effects[EFFECT_1].CalcValue()); } bonusDamage = owner->GetTotalAttackPowerValue(RANGED_ATTACK) * 0.1287f * mod; amount += bonusDamage; } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(spell_hun_pet_scaling_01_AuraScript::RemoveEffect, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK); AfterEffectApply += AuraEffectApplyFn(spell_hun_pet_scaling_01_AuraScript::ApplyEffect, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_01_AuraScript::CalculateStaminaAmount, EFFECT_0, SPELL_AURA_MOD_STAT); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_01_AuraScript::CalculateAttackPowerAmount, EFFECT_1, SPELL_AURA_MOD_ATTACK_POWER); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_01_AuraScript::CalculateDamageDoneAmount, EFFECT_2, SPELL_AURA_MOD_DAMAGE_DONE); } private: uint32 _tempHealth; }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_hun_pet_scaling_01_AuraScript(); } }; class spell_hun_pet_scaling_02 : public SpellScriptLoader { public: spell_hun_pet_scaling_02() : SpellScriptLoader("spell_hun_pet_scaling_02") { } class spell_hun_pet_scaling_02_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_pet_scaling_02_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateFrostResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_FROST), 40); amount += ownerBonus; } } void CalculateFireResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_FIRE), 40); amount += ownerBonus; } } void CalculateNatureResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_NATURE), 40); amount += ownerBonus; } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_02_AuraScript::CalculateFrostResistanceAmount, EFFECT_1, SPELL_AURA_MOD_RESISTANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_02_AuraScript::CalculateFireResistanceAmount, EFFECT_0, SPELL_AURA_MOD_RESISTANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_02_AuraScript::CalculateNatureResistanceAmount, EFFECT_2, SPELL_AURA_MOD_RESISTANCE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_hun_pet_scaling_02_AuraScript(); } }; class spell_hun_pet_scaling_03 : public SpellScriptLoader { public: spell_hun_pet_scaling_03() : SpellScriptLoader("spell_hun_pet_scaling_03") { } class spell_hun_pet_scaling_03_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_pet_scaling_03_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateShadowResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_SHADOW), 40); amount += ownerBonus; } } void CalculateArcaneResistanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetResistance(SPELL_SCHOOL_ARCANE), 40); amount += ownerBonus; } } void CalculateArmorAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsPet()) return; Unit* owner = pet->ToPet()->GetOwner(); if (!owner) return; float ownerBonus = 0.0f; ownerBonus = CalculatePct(owner->GetArmor(), 35); amount += ownerBonus; } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_03_AuraScript::CalculateShadowResistanceAmount, EFFECT_0, SPELL_AURA_MOD_RESISTANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_03_AuraScript::CalculateArcaneResistanceAmount, EFFECT_1, SPELL_AURA_MOD_RESISTANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_03_AuraScript::CalculateArmorAmount, EFFECT_2, SPELL_AURA_MOD_RESISTANCE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_hun_pet_scaling_03_AuraScript(); } }; class spell_hun_pet_scaling_04 : public SpellScriptLoader { public: spell_hun_pet_scaling_04() : SpellScriptLoader("spell_hun_pet_scaling_04") { } class spell_hun_pet_scaling_04_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_pet_scaling_04_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountMeleeHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from SPELL_AURA_MOD_HIT_CHANCE HitMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_HIT_CHANCE); // Increase hit melee from meele hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_MELEE); amount += int32(HitMelee); } } void CalculateAmountSpellHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from SPELL_AURA_MOD_SPELL_HIT_CHANCE HitSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_HIT_CHANCE); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void CalculateAmountExpertise(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float Expertise = 0.0f; // Increase hit from SPELL_AURA_MOD_EXPERTISE Expertise += owner->GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE); // Increase Expertise from Expertise ratings Expertise += owner->GetRatingBonusValue(CR_EXPERTISE); amount += int32(Expertise); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_04_AuraScript::CalculateAmountMeleeHit, EFFECT_0, SPELL_AURA_MOD_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_04_AuraScript::CalculateAmountSpellHit, EFFECT_1, SPELL_AURA_MOD_SPELL_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_04_AuraScript::CalculateAmountExpertise, EFFECT_2, SPELL_AURA_MOD_EXPERTISE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_hun_pet_scaling_04_AuraScript(); } }; class spell_hun_pet_passive_crit : public SpellScriptLoader { public: spell_hun_pet_passive_crit() : SpellScriptLoader("spell_hun_pet_passive_crit") { } class spell_hun_pet_passive_crit_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_pet_passive_crit_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountCritSpell(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritSpell = 0.0f; // Crit from Intellect // CritSpell += owner->GetSpellCritFromIntellect(); // Increase crit from SPELL_AURA_MOD_SPELL_CRIT_CHANCE // CritSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_CRIT_CHANCE); // Increase crit from SPELL_AURA_MOD_CRIT_PCT // CritSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); // Increase crit spell from spell crit ratings // CritSpell += owner->GetRatingBonusValue(CR_CRIT_SPELL); amount += (CritSpell*0.8f); } } void CalculateAmountCritMelee(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float CritMelee = 0.0f; // Crit from Agility // CritMelee += owner->GetMeleeCritFromAgility(); // Increase crit from SPELL_AURA_MOD_WEAPON_CRIT_PERCENT // CritMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); // Increase crit from SPELL_AURA_MOD_CRIT_PCT // CritMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PCT); // Increase crit melee from melee crit ratings // CritMelee += owner->GetRatingBonusValue(CR_CRIT_MELEE); amount += (CritMelee*0.8f); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_passive_crit_AuraScript::CalculateAmountCritSpell, EFFECT_1, SPELL_AURA_MOD_SPELL_CRIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_passive_crit_AuraScript::CalculateAmountCritMelee, EFFECT_0, SPELL_AURA_MOD_WEAPON_CRIT_PERCENT); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_hun_pet_passive_crit_AuraScript(); } }; class spell_hun_pet_passive_damage_done : public SpellScriptLoader { public: spell_hun_pet_passive_damage_done() : SpellScriptLoader("spell_hun_pet_passive_damage_done") { } class spell_hun_pet_passive_damage_done_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_pet_passive_damage_done_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountDamageDone(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (GetCaster()->GetOwner()->ToPlayer()) { // Pet's base damage changes depending on happiness if (GetCaster()->IsPet() && GetCaster()->ToPet()->IsHunterPet()) { switch (GetCaster()->ToPet()->GetHappinessState()) { case HAPPY: // 125% of normal damage amount += 25.0f; break; case CONTENT: // 100% of normal damage, nothing to modify break; case UNHAPPY: // 75% of normal damage amount += -25.0f; break; } } // Cobra Reflexes if (AuraEffect* cobraReflexes = GetCaster()->GetAuraEffectOfRankedSpell(61682, EFFECT_0)) amount -= cobraReflexes->GetAmount(); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_passive_damage_done_AuraScript::CalculateAmountDamageDone, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_hun_pet_passive_damage_done_AuraScript(); } }; class spell_hun_animal_handler : public SpellScriptLoader { public: spell_hun_animal_handler() : SpellScriptLoader("spell_hun_animal_handler") { } class spell_hun_animal_handler_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_animal_handler_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountDamageDone(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { if (AuraEffect* /* aurEff */ect = owner->GetAuraEffectOfRankedSpell(SPELL_HUNTER_ANIMAL_HANDLER, EFFECT_1)) amount = /* aurEff */ect->GetAmount(); else amount = 0; } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_animal_handler_AuraScript::CalculateAmountDamageDone, EFFECT_0, SPELL_AURA_MOD_ATTACK_POWER_PCT); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_hun_animal_handler_AuraScript(); } }; class spell_dk_avoidance_passive : public SpellScriptLoader { public: spell_dk_avoidance_passive() : SpellScriptLoader("spell_dk_avoidance_passive") { } class spell_dk_avoidance_passive_AuraScript : public AuraScript { PrepareAuraScript(spell_dk_avoidance_passive_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAvoidanceAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (Unit* owner = pet->GetOwner()) { // Army of the dead ghoul if (pet->GetEntry() == ENTRY_ARMY_OF_THE_DEAD_GHOUL) amount = -90; // Night of the dead else if (Aura* aur = owner->GetAuraOfRankedSpell(SPELL_NIGHT_OF_THE_DEAD)) amount = aur->GetSpellInfo()->Effects[EFFECT_2].CalcValue(); } } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_avoidance_passive_AuraScript::CalculateAvoidanceAmount, EFFECT_0, SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_dk_avoidance_passive_AuraScript(); } }; class spell_dk_pet_scaling_01 : public SpellScriptLoader { public: spell_dk_pet_scaling_01() : SpellScriptLoader("spell_dk_pet_scaling_01") { } class spell_dk_pet_scaling_01_AuraScript : public AuraScript { PrepareAuraScript(spell_dk_pet_scaling_01_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; _tempHealth = 0; return true; } void CalculateStaminaAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (pet->IsGuardian()) { if (Unit* owner = pet->GetOwner()) { float mod = 0.3f; // Ravenous Dead. Check just if owner has Ravenous Dead since it's effect is not an aura if (AuraEffect const* aurEff = owner->GetAuraEffect(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE, SPELLFAMILY_DEATHKNIGHT, 3010, 0)) mod += aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue()/100; // Ravenous Dead edits the original scale // Glyph of the Ghoul if (AuraEffect const* aurEff = owner->GetAuraEffect(SPELL_DEATH_KNIGHT_GLYPH_OF_GHOUL, 0)) mod += aurEff->GetAmount()/100; float ownerBonus = float(owner->GetStat(STAT_STAMINA)) * mod; amount += ownerBonus; } } } } void ApplyEffect(AuraEffect const* /* aurEff */, AuraEffectHandleModes /*mode*/) { if (Unit* pet = GetUnitOwner()) if (_tempHealth) pet->SetHealth(_tempHealth); } void RemoveEffect(AuraEffect const* /* aurEff */, AuraEffectHandleModes /*mode*/) { if (Unit* pet = GetUnitOwner()) _tempHealth = pet->GetHealth(); } void CalculateStrengthAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { if (!pet->IsGuardian()) return; Unit* owner = pet->GetOwner(); if (!owner) return; float mod = 0.7f; // Ravenous Dead AuraEffect const* aurEff = NULL; // Check just if owner has Ravenous Dead since it's effect is not an aura aurEff = owner->GetAuraEffect(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE, SPELLFAMILY_DEATHKNIGHT, 3010, 0); if (aurEff) { mod += CalculatePct(mod, aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue()); // Ravenous Dead edits the original scale } // Glyph of the Ghoul aurEff = owner->GetAuraEffect(58686, 0); if (aurEff) mod += CalculatePct(1.0f, aurEff->GetAmount()); // Glyph of the Ghoul adds a flat value to the scale mod float ownerBonus = float(owner->GetStat(STAT_STRENGTH)) * mod; amount += ownerBonus; } } void Register() OVERRIDE { OnEffectRemove += AuraEffectRemoveFn(spell_dk_pet_scaling_01_AuraScript::RemoveEffect, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK); AfterEffectApply += AuraEffectApplyFn(spell_dk_pet_scaling_01_AuraScript::ApplyEffect, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_pet_scaling_01_AuraScript::CalculateStaminaAmount, EFFECT_0, SPELL_AURA_MOD_STAT); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_pet_scaling_01_AuraScript::CalculateStrengthAmount, EFFECT_1, SPELL_AURA_MOD_STAT); } private: uint32 _tempHealth; }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_dk_pet_scaling_01_AuraScript(); } }; class spell_dk_pet_scaling_02 : public SpellScriptLoader { public: spell_dk_pet_scaling_02() : SpellScriptLoader("spell_dk_pet_scaling_02") { } class spell_dk_pet_scaling_02_AuraScript : public AuraScript { PrepareAuraScript(spell_dk_pet_scaling_02_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountMeleeHaste(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HasteMelee = 0.0f; // Increase hit from SPELL_AURA_MOD_HIT_CHANCE HasteMelee += (1-owner->m_modAttackSpeedPct[BASE_ATTACK])*100; amount += int32(HasteMelee); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_pet_scaling_02_AuraScript::CalculateAmountMeleeHaste, EFFECT_1, SPELL_AURA_MELEE_SLOW); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_dk_pet_scaling_02_AuraScript(); } }; class spell_dk_pet_scaling_03 : public SpellScriptLoader { public: spell_dk_pet_scaling_03() : SpellScriptLoader("spell_dk_pet_scaling_03") { } class spell_dk_pet_scaling_03_AuraScript : public AuraScript { PrepareAuraScript(spell_dk_pet_scaling_03_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateAmountMeleeHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitMelee = 0.0f; // Increase hit from SPELL_AURA_MOD_HIT_CHANCE HitMelee += owner->GetTotalAuraModifier(SPELL_AURA_MOD_HIT_CHANCE); // Increase hit melee from meele hit ratings HitMelee += owner->GetRatingBonusValue(CR_HIT_MELEE); amount += int32(HitMelee); } } void CalculateAmountSpellHit(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HitSpell = 0.0f; // Increase hit from SPELL_AURA_MOD_SPELL_HIT_CHANCE HitSpell += owner->GetTotalAuraModifier(SPELL_AURA_MOD_SPELL_HIT_CHANCE); // Increase hit spell from spell hit ratings HitSpell += owner->GetRatingBonusValue(CR_HIT_SPELL); amount += int32(HitSpell); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_pet_scaling_03_AuraScript::CalculateAmountMeleeHit, EFFECT_0, SPELL_AURA_MOD_HIT_CHANCE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_pet_scaling_03_AuraScript::CalculateAmountSpellHit, EFFECT_1, SPELL_AURA_MOD_SPELL_HIT_CHANCE); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_dk_pet_scaling_03_AuraScript(); } }; class spell_dk_rune_weapon_scaling_02 : public SpellScriptLoader { public: spell_dk_rune_weapon_scaling_02() : SpellScriptLoader("spell_dk_rune_weapon_scaling_02") { } class spell_dk_rune_weapon_scaling_02_AuraScript : public AuraScript { PrepareAuraScript(spell_dk_rune_weapon_scaling_02_AuraScript); bool Load() OVERRIDE { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) return false; return true; } void CalculateDamageDoneAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) { Unit* owner = pet->GetOwner(); if (!owner) return; if (pet->IsGuardian()) ((Guardian*)pet)->SetBonusDamage(owner->GetTotalAttackPowerValue(BASE_ATTACK)); amount += owner->CalculateDamage(BASE_ATTACK, true, true); } } void CalculateAmountMeleeHaste(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (!GetCaster() || !GetCaster()->GetOwner()) return; if (Player* owner = GetCaster()->GetOwner()->ToPlayer()) { // For others recalculate it from: float HasteMelee = 0.0f; // Increase hit from SPELL_AURA_MOD_HIT_CHANCE HasteMelee += (1-owner->m_modAttackSpeedPct[BASE_ATTACK])*100; amount += int32(HasteMelee); } } void Register() OVERRIDE { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_rune_weapon_scaling_02_AuraScript::CalculateDamageDoneAmount, EFFECT_0, SPELL_AURA_MOD_DAMAGE_DONE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_rune_weapon_scaling_02_AuraScript::CalculateAmountMeleeHaste, EFFECT_1, SPELL_AURA_MELEE_SLOW); } }; AuraScript* GetAuraScript() const OVERRIDE { return new spell_dk_rune_weapon_scaling_02_AuraScript(); } }; void AddSC_pet_spell_scripts() { new spell_gen_pet_calculate(); }
mynew6/blabblaba
src/server/scripts/Spells/spell_pet.cpp
C++
gpl-2.0
70,765
/* * Jeremy Compostella <jeremy.compostella@gmail.com> * * 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; either version 2 of the License, or (at * your option) any later version. * * 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., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include "htckbdhandler.h" #include <QFile> #include <QTextStream> #include <QSocketNotifier> #include <QDebug> #include <fcntl.h> #include <unistd.h> #include <htckbdmap.h> #include <linux/input.h> htcKbdHandler::htcKbdHandler(const QString &device) : modifiers(Qt::NoModifier), capsLock(false) { setObjectName("Htc keyboard Handler"); kbdFD = ::open(device.toLocal8Bit().constData(), O_RDONLY, 0); if (kbdFD >= 0) { m_notify = new QSocketNotifier(kbdFD, QSocketNotifier::Read, this); connect(m_notify, SIGNAL(activated(int)), this, SLOT(processEvent())); } else qWarning("Cannot open %s", device.toLocal8Bit().constData()); } htcKbdHandler::~htcKbdHandler() { } void htcKbdHandler::processEvent() { #define MAX_EVENT 10 struct input_event events[MAX_EVENT]; unsigned int i; int n = read(kbdFD, &events, sizeof(struct input_event) * MAX_EVENT); for (i = 0 ; i < n / sizeof(struct input_event) ; ++i) processEvent(events[i]); } void htcKbdHandler::processEvent(struct input_event event) { static struct input_event previous = { {0, 0}, 0, 0, 0}; static uint previous_nb = 0; struct QWSKeyMap key; if (event.code > keyMSize || event.code == 0) return; #define MIN_REPEAT 5 key = htcuniversalKeyMap[event.code]; if ((event.code == previous.code && (previous.value == 0 ? !event.value : event.value)) && (key.key_code == Qt::Key_Control || key.key_code == Qt::Key_Shift || key.key_code == Qt::Key_CapsLock || key.key_code == Qt::Key_Alt || previous_nb++ <= MIN_REPEAT)) return; if (event.code != previous.code) previous_nb = 0; if (key.key_code == Qt::Key_Control) modifiers ^= Qt::ControlModifier; if (key.key_code == Qt::Key_Shift) modifiers ^= Qt::ShiftModifier; if (key.key_code == Qt::Key_Alt) modifiers ^= Qt::AltModifier; if (key.key_code == Qt::Key_CapsLock && event.value == 0) capsLock = !capsLock; ushort unicode = key.unicode; if (modifiers & Qt::ShiftModifier && !capsLock) unicode = key.shift_unicode; else if (modifiers & Qt::ControlModifier) unicode = key.ctrl_unicode; else if (modifiers & Qt::AltModifier) unicode = key.alt_unicode; else if (capsLock && !(modifiers & Qt::ShiftModifier)) unicode = key.shift_unicode; processKeyEvent(unicode, key.key_code, modifiers, event.value != 0, false); previous = event; }
Trim/qtmoko
devices/htcuniversal/src/plugins/qtopiacore/kbddrivers/htckeyboard/htckbdhandler.cpp
C++
gpl-2.0
3,174
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_CatalogInventory * @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ $installer = $this; /* @var $installer Mage_Core_Model_Resource_Setup */ $installer->startSetup(); $installer->getConnection()->addColumn($this->getTable('cataloginventory_stock_item'), 'stock_status_changed_automatically', 'tinyint(1) unsigned NOT NULL DEFAULT 0'); $installer->endSetup();
T0MM0R/magento
web/app/code/core/Mage/CatalogInventory/sql/cataloginventory_setup/mysql4-upgrade-0.7.2-0.7.3.php
PHP
gpl-2.0
1,249
<?php /** * Redux Framework 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, either version 2 of the License, or * any later version. * Redux Framework 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 Redux Framework. If not, see <http://www.gnu.org/licenses/>. * * @package ReduxFramework * @subpackage Field_thinkup_section * @author Tobias Karnetze (athoss.de) * @version 1.0.0 */ // Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) { exit; } // Don't duplicate me! if ( ! class_exists( 'ReduxFramework_thinkup_section' ) ) { /** * Main ReduxFramework_thinkup_section class * * @since 1.0.0 */ class ReduxFramework_thinkup_section { /** * Field Constructor. * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function * * @since 1.0.0 * @access public * @return void */ public function __construct( $field = array(), $value = '', $parent ) { $this->parent = $parent; $this->field = $field; $this->value = $value; if ( empty( $this->_extension_dir ) ) { $this->_extension_dir = trailingslashit( str_replace( '\\', '/', dirname( __FILE__ ) ) ); $this->_extension_url = site_url( str_replace( trailingslashit( str_replace( '\\', '/', ABSPATH ) ), '/', $this->_extension_dir ) ); } } /** * Field Render Function. * Takes the vars and outputs the HTML for the field in the settings * * @since 1.0.0 * @access public * @return void */ public function render() { // Default Redux title field is used to output section title // delete the tr afterwards } public function enqueue() { } } }
JulioKno/Portal-UNIVIM-2016
wp-content/themes/sento/admin/main/inc/extensions/thinkup_section/thinkup_section/field_thinkup_section.php
PHP
gpl-2.0
2,177
""" accounts.test_views =================== Tests the REST API calls. Add more specific social registration tests """ import responses from django.core.urlresolvers import reverse from django.core import mail from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from django.test.utils import override_settings from rest_framework import status from rest_framework.test import APIClient, APITestCase from allauth.account import app_settings from allauth.socialaccount.models import SocialApp from allauth.socialaccount.providers.facebook.provider import GRAPH_API_URL from .serializers import LoginSerializer class TestAccounts(APITestCase): """ Tests normal use - non social login. """ def setUp(self): self.login_url = reverse('accounts:rest_login') self.logout_url = reverse('accounts:rest_logout') self.register_url = reverse('accounts:rest_register') self.password_reset_url = reverse('accounts:rest_password_reset') self.rest_password_reset_confirm_url = reverse('accounts:rest_password_reset_confirm') self.password_change_url = reverse('accounts:rest_password_change') self.verify_url = reverse('accounts:rest_verify_email') self.user_url = reverse('accounts:rest_user_details') self.client = APIClient() self.reusable_user_data = {'username': 'admin', 'email': 'admin@email.com', 'password': 'password12'} self.reusable_user_data_change_password = {'username': 'admin', 'email': 'admin@email.com', 'password': 'password_same'} self.reusable_register_user_data = {'username': 'admin', 'email': 'admin@email.com', 'password1': 'password12', 'password2': 'password12'} self.reusable_register_user_data1 = {'username': 'admin1', 'email': 'admin1@email.com', 'password1': 'password12', 'password2': 'password12'} self.reusable_register_user_data_no_username = {'email': 'admin@email.com', 'password1': 'password12', 'password2': 'password12'} self.reusable_register_user_data_no_email = {'username': 'admin', 'password1': 'password12', 'password2': 'password12'} self.change_password_data_incorrect = {"new_password1": "password_not_same", "new_password2": "password_same"} self.change_password_data = {"new_password1": "password_same", "new_password2": "password_same"} self.change_password_data_old_password_field_enabled = {"old_password": "password12", "new_password1": "password_same", "new_password2": "password_same"} def create_user_and_login(self): """ Helper function to create a basic user, login and assign token credentials. """ get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') response = self.client.post(self.login_url, self.reusable_user_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK, "Snap! Basic Login has failed with a helper function 'create_user_and_login'. Something is really wrong here.") self.client.credentials(HTTP_AUTHORIZATION='Token ' + response.data['key']) def _generate_uid_and_token(self, user): result = {} from django.utils.encoding import force_bytes from django.contrib.auth.tokens import default_token_generator from django import VERSION if VERSION[1] == 5: from django.utils.http import int_to_base36 result['uid'] = int_to_base36(user.pk) else: from django.utils.http import urlsafe_base64_encode result['uid'] = urlsafe_base64_encode(force_bytes(user.pk)) result['token'] = default_token_generator.make_token(user) return result def cleanUp(self): pass @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_login_basic_username_auth_method(self): """ Tests basic functionality of login with authentication method of username. """ # Assumes you provide username,password and returns a token get_user_model().objects.create_user('admin3', '', 'password12') data = {"username": 'admin3', "email": "", "password": 'password12'} response = self.client.post(self.login_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertIn('key', response.content) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL, ACCOUNT_EMAIL_REQUIRED=True) def test_login_basic_email_auth_method(self): """ Tests basic functionality of login with authentication method of email. """ # Assumes you provide username,password and returns a token get_user_model().objects.create_user('admin', 'email.login@gmail.com', 'password12') data = {"username": '', "email": "email.login@gmail.com", "password": 'password12'} response = self.client.post(self.login_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertIn('key', response.content) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_login_basic_username_email_auth_method(self): """ Tests basic functionality of login with authentication method of username or email. """ # Assumes you provide username,password and returns a token get_user_model().objects.create_user('admin', 'email.login@gmail.com', 'password12') # Check email data = {"username": '', "email": "email.login@gmail.com", "password": 'password12'} response = self.client.post(self.login_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) # Check username data = {"username": 'admin', "email": '', "password": 'password12'} response = self.client.post(self.login_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertIn('key', response.content) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_login_auth_method_username_fail_no_users_in_db(self): """ Tests login fails with a 400 when no users in db for login auth method of 'username'. """ serializer = LoginSerializer({'username': 'admin', 'password': 'password12'}) response = self.client.post(self.login_url, serializer.data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL) def test_login_email_auth_method_fail_no_users_in_db(self): """ Tests login fails with a 400 when no users in db for login auth method of 'email'. """ serializer = LoginSerializer({'username': 'admin', 'password': 'password12'}) response = self.client.post(self.login_url, serializer.data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_login_username_email_auth_method_fail_no_users_in_db(self): """ Tests login fails with a 400 when no users in db for login auth method of 'username_email'. """ serializer = LoginSerializer({'username': 'admin', 'password': 'password12'}) response = self.client.post(self.login_url, serializer.data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) def common_test_login_fail_incorrect_change(self): # Create user, login and try and change password INCORRECTLY self.create_user_and_login() self.client.post(self.password_change_url, data=self.change_password_data_incorrect, format='json') # Remove credentials self.client.credentials() response = self.client.post(self.login_url, self.reusable_user_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertIn('key', response.content) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_login_username_auth_method_fail_incorrect_password_change(self): """ Tests login fails with an incorrect/invalid password change (login auth username). """ self.common_test_login_fail_incorrect_change() @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL) def test_login_email_auth_method_fail_incorrect_password_change(self): """ Tests login fails with an incorrect/invalid password change (login auth email). """ self.common_test_login_fail_incorrect_change() @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_login_username_email_auth_method_fail_incorrect_password_change(self): """ Tests login fails with an incorrect/invalid password change (login auth username_email). """ self.common_test_login_fail_incorrect_change() def common_test_login_correct_password_change(self): # Create user, login and try and change password successfully self.create_user_and_login() response = self.client.post(self.password_change_url, data=self.change_password_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) # Remove credentials self.client.credentials() response = self.client.post(self.login_url, self.reusable_user_data_change_password, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertIn('key', response.content) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_login_username_auth_method_correct_password_change(self): """ Tests login is succesful with a correct password change (login auth username). """ self.common_test_login_correct_password_change() @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL) def test_login_email_auth_method_correct_password_change(self): """ Tests login is succesful with a correct password change (login auth email). """ self.common_test_login_correct_password_change() @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_login_username_email_auth_method_correct_password_change(self): """ Tests login is succesful with a correct password change (login auth username_email). """ self.common_test_login_correct_password_change() def test_login_fail_no_input(self): """ Tests login fails when you provide no username and no email (login auth username_email). """ get_user_model().objects.create_user('admin', 'email.login@gmail.com', 'password12') data = {"username": '', "email": '', "password": ''} response = self.client.post(self.login_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_login_username_auth_method_fail_no_input(self): """ Tests login fails when you provide no username (login auth username). """ get_user_model().objects.create_user('admin', 'email.login@gmail.com', 'password12') data = {"username": '', "email": "email.login@gmail.com", "password": 'password12'} response = self.client.post(self.login_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL) def test_login_email_auth_method_fail_no_input(self): """ Tests login fails when you provide no username (login auth email). """ get_user_model().objects.create_user('admin', 'email.login@gmail.com', 'password12') data = {"username": "admin", "email": '', "password": 'password12'} response = self.client.post(self.login_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) @override_settings(ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_login_username_email_auth_method_fail_no_input(self): """ Tests login fails when you provide no username and no email (login auth username_email). """ get_user_model().objects.create_user('admin', 'email.login@gmail.com', 'password12') data = {"username": '', "email": '', "password": 'password12'} response = self.client.post(self.login_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) # need to check for token # test login with password change # test login with wrong password chaneg if fails def test_logout(self): """ Tests basic logout functionality. """ self.create_user_and_login() response = self.client.post(self.logout_url, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"success":"Successfully logged out."}') def test_logout_but_already_logged_out(self): """ Tests logout when already logged out. """ self.create_user_and_login() response = self.client.post(self.logout_url, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"success":"Successfully logged out."}') self.client.credentials() # remember to remove manual token credential response = self.client.post(self.logout_url, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK, response.content) self.assertEquals(response.content, '{"success":"Successfully logged out."}') def test_change_password_basic(self): """ Tests basic functionality of 'change of password'. """ self.create_user_and_login() response = self.client.post(self.password_change_url, data=self.change_password_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"success":"New password has been saved."}') def test_change_password_basic_fails_not_authorised(self): """ Tests basic functionality of 'change of password' fails if not authorised. """ get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') response = self.client.post(self.password_change_url, data=self.change_password_data, format='json') self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED) self.assertEquals(response.content, '{"detail":"Authentication credentials were not provided."}') def common_change_password_login_fail_with_old_password(self, password_change_data): self.create_user_and_login() response = self.client.post(self.password_change_url, data=password_change_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.client.credentials() # Remove credentials response = self.client.post(self.login_url, self.reusable_user_data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) def common_change_password_login_pass_with_new_password(self, password_change_data): self.create_user_and_login() response = self.client.post(self.password_change_url, password_change_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.client.credentials() # Remove credentials response = self.client.post(self.login_url, self.reusable_user_data_change_password, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) def common_change_password_login_fail_with_old_password_pass_with_new_password(self, password_change_data): """ Tests change of password with old password fails but new password successes. """ self.create_user_and_login() response = self.client.post(self.password_change_url, password_change_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK, response.content) self.client.credentials() # Remove credentials response = self.client.post(self.login_url, self.reusable_user_data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) response = self.client.post(self.login_url, self.reusable_user_data_change_password, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK, response.content) def test_change_password_login_fail_with_old_password(self): """ Tests change of password with old password. """ self.common_change_password_login_fail_with_old_password(self.change_password_data) def test_change_password_login_pass_with_new_password(self): """ Tests change of password with new password. """ self.common_change_password_login_pass_with_new_password(self.change_password_data) def test_change_password_login_fail_with_old_password_pass_with_new_password(self): """ Tests change of password with old password fails but new password successes. """ self.common_change_password_login_fail_with_old_password_pass_with_new_password(self.change_password_data) @override_settings(OLD_PASSWORD_FIELD_ENABLED=True) def test_change_password_old_password_field_required_old_password_field_enabled(self): """ Tests basic functionality of 'change of password' fails if old password not given as part of input (old password field enabled). """ self.create_user_and_login() response = self.client.post(self.password_change_url, data=self.change_password_data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEquals(response.content, '{"old_password":["This field is required."]}') @override_settings(OLD_PASSWORD_FIELD_ENABLED=True) def test_change_password_basic_old_password_field_enabled(self): """ Tests basic functionality of 'change of password' (old password enabled). """ self.create_user_and_login() response = self.client.post(self.password_change_url, data=self.change_password_data_old_password_field_enabled, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"success":"New password has been saved."}') @override_settings(OLD_PASSWORD_FIELD_ENABLED=True) def test_change_password_basic_fails_not_authorised_old_password_field_enabled(self): """ Tests basic functionality of 'change of password' fails if not authorised (old password field enabled). """ get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') response = self.client.post(self.password_change_url, data=self.change_password_data_old_password_field_enabled, format='json') self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED) self.assertEquals(response.content, '{"detail":"Authentication credentials were not provided."}') @override_settings(OLD_PASSWORD_FIELD_ENABLED=True) def test_change_password_login_fail_with_old_password_old_password_field_enabled(self): """ Tests change of password with old password (old password field enabled). """ self.common_change_password_login_fail_with_old_password(self.change_password_data_old_password_field_enabled) @override_settings(OLD_PASSWORD_FIELD_ENABLED=True) def test_change_password_login_pass_with_new_password_old_password_field_enabled(self): """ Tests change of password with new password (old password field enabled). """ self.common_change_password_login_pass_with_new_password(self.change_password_data_old_password_field_enabled) @override_settings(OLD_PASSWORD_FIELD_ENABLED=True) def test_change_password_login_fail_with_old_password_pass_with_new_password_old_password_field_enabled(self): """ Tests change of password with old password fails but new password successes (old password field enabled). """ self.common_change_password_login_fail_with_old_password_pass_with_new_password(self.change_password_data_old_password_field_enabled) """ Registrations Tests =================== """ def common_test_registration_basic(self, data): response = self.client.post(self.register_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_201_CREATED, response.content) return response @override_settings(ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_USERNAME_REQUIRED=True) def test_registration_basic(self): """ Tests basic functionality of registration. """ self.common_test_registration_basic(self.reusable_register_user_data) @override_settings(ACCOUNT_EMAIL_REQUIRED=True, ACCOUNT_USERNAME_REQUIRED=False) def test_registration_basic_no_username(self): """ Tests basic functionality of registration (no username required). """ self.common_test_registration_basic(self.reusable_register_user_data_no_username) @override_settings(ACCOUNT_EMAIL_REQUIRED=False, ACCOUNT_USERNAME_REQUIRED=True) def test_registration_basic_no_email(self): """ Tests basic functionality of registration (no username required). """ self.common_test_registration_basic(self.reusable_register_user_data_no_email) @override_settings(ACCOUNTS_REGISTRATION_OPEN=False) def test_registration_basic_registration_not_open(self): """ Tests basic registration fails if registration is closed. """ response = self.client.post(self.register_url, self.reusable_register_user_data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST, response.content) @override_settings(ACCOUNT_EMAIL_VERIFICATION="none") def test_registration_email_verification_not_necessary(self): """ Tests you can log in without email verification """ self.common_test_registration_basic(self.reusable_register_user_data) response = self.client.post(self.login_url, self.reusable_user_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) @override_settings(ACCOUNT_EMAIL_VERIFICATION="optional") def test_registration_email_verification_neccessary(self): """ Tests you can log in without email verification """ self.common_test_registration_basic(self.reusable_register_user_data) response = self.client.post(self.login_url, self.reusable_user_data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) def common_test_registration(self): self.common_test_registration_basic(self.reusable_register_user_data1) response = self.client.post(self.login_url, {'email': 'admin1@email.com', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) def common_test_registration_email_verification_not_necessary_email(self): self.common_test_registration_basic(self.reusable_register_user_data1) response = self.client.post(self.login_url, {'email': 'admin1@email.com', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) def common_test_registration_email_verification_not_necessary_username(self): self.common_test_registration_basic(self.reusable_register_user_data1) response = self.client.post(self.login_url, {'username': 'admin1', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) @override_settings(ACCOUNT_EMAIL_VERIFICATION="none", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL) def test_registration_email_verification_neccessary_email(self): """ Tests you can log in without email verification """ self.common_test_registration_email_verification_not_necessary_email() @override_settings(ACCOUNT_EMAIL_VERIFICATION="optional", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL) def test_registration_email_verification_neccessary_optional_email(self): """ Tests you can log in without email verification """ self.common_test_registration_email_verification_not_necessary_email() @override_settings(ACCOUNT_EMAIL_VERIFICATION="none", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_registration_email_verification_neccessary_username(self): """ Tests you can log in without email verification """ self.common_test_registration_email_verification_not_necessary_username() @override_settings(ACCOUNT_EMAIL_VERIFICATION="optional", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_registration_email_verification_neccessary_optional_username(self): """ Tests you can log in without email verification """ self.common_test_registration_email_verification_not_necessary_username() @override_settings(ACCOUNT_EMAIL_VERIFICATION="none", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_registration_email_verification_neccessary_username_email(self): """ Tests you canT log in without email verification for username & email auth. """ self.common_test_registration_basic(self.reusable_register_user_data1) response = self.client.post(self.login_url, {'username': 'admin1', 'email': 'admin1@email.com', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) @override_settings(ACCOUNT_EMAIL_VERIFICATION="optional", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_registration_email_verification_neccessary_optional_username_email(self): """ Tests you canT log in without email verification for username & email auth. """ self.common_test_registration_basic(self.reusable_register_user_data1) response = self.client.post(self.login_url, {'username': 'admin1', 'email': 'admin1@email.com', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) @override_settings(ACCOUNT_EMAIL_VERIFICATION="mandatory", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_registration_email_verification_necessary_login_fail_username(self): """ Tests you can log in without email verification """ self.common_test_registration_basic(self.reusable_register_user_data1) response = self.client.post(self.login_url, {'username': 'admin1', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST, response.content) @override_settings(ACCOUNT_EMAIL_VERIFICATION="mandatory", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL) def test_registration_email_verification_necessary_login_fail_email(self): """ Tests you can log in without email verification """ self.common_test_registration_basic(self.reusable_register_user_data1) response = self.client.post(self.login_url, {'email': 'admin1@email.com', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST, response.content) @override_settings(ACCOUNT_EMAIL_VERIFICATION="mandatory", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_registration_email_verification_necessary_login_fail_username_email(self): """ Tests you can log in without email verification """ self.common_test_registration_basic({'username': 'admin_man', 'email': 'admin1@email.com', 'password1': 'password12', 'password2': 'password12'}) response = self.client.post(self.login_url, {'username': 'admin_man', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) def common_registration_email_verification_neccessary_verified_login(self, login_data): mail_count = len(mail.outbox) reg_response = self.common_test_registration_basic(self.reusable_register_user_data1) self.assertEquals(len(mail.outbox), mail_count + 1) new_user = get_user_model().objects.latest('id') login_response = self.client.post(self.login_url, login_data, format='json') self.assertEquals(login_response.status_code, status.HTTP_400_BAD_REQUEST) # verify email email_confirmation = new_user.emailaddress_set.get(email=self.reusable_register_user_data1['email']).emailconfirmation_set.order_by('-created')[0] verify_response = self.client.post(self.verify_url, {'key': email_confirmation.key}, format='json') self.assertEquals(verify_response.status_code, status.HTTP_200_OK) login_response = self.client.post(self.login_url, login_data, format='json') self.assertEquals(login_response.status_code, status.HTTP_200_OK) @override_settings(ACCOUNT_EMAIL_VERIFICATION="mandatory", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME) def test_registration_email_verification_neccessary_verified_login_username(self): """ Tests you can log in without email verification """ self.common_registration_email_verification_neccessary_verified_login({'username': 'admin1', 'password': 'password12'}) @override_settings(ACCOUNT_EMAIL_VERIFICATION="mandatory", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL) def test_registration_email_verification_neccessary_verified_login_email(self): """ Tests you can log in without email verification """ self.common_registration_email_verification_neccessary_verified_login({'email': 'admin1@email.com', 'password': 'password12'}) @override_settings(ACCOUNT_EMAIL_VERIFICATION="mandatory", ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL) def test_registration_email_verification_neccessary_verified_login_username_email(self): """ Tests you can log in without email verification """ self.common_registration_email_verification_neccessary_verified_login({'username': 'admin1', 'password': 'password12'}) """ Password Reset Tests ==================== """ def test_password_reset(self): """ Test basic functionality of password reset. """ get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') payload = {'email': 'admin@email.com'} response = self.client.post(self.password_reset_url, payload, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"success":"Password reset e-mail has been sent."}') @override_settings(ACCOUNTS_PASSWORD_RESET_NOTIFY_EMAIL_NOT_IN_SYSTEM=True) def test_password_reset_fail_no_user_with_email_no_notify_not_in_system(self): """ Test basic functionality of password reset fails when there is no email on record (notify email not in system). """ payload = {'email': 'admin@email.com'} response = self.client.post(self.password_reset_url, payload, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEquals(response.content, '{"error":"User with email doesn\'t exist. Did not send reset email."}') @override_settings(ACCOUNTS_PASSWORD_RESET_NOTIFY_EMAIL_NOT_IN_SYSTEM=False) def test_password_reset_no_user_with_email_no_notify_not_in_system(self): """ Test basic functionality of password reset fails when there is no email on record. """ payload = {'email': 'admin@email.com'} response = self.client.post(self.password_reset_url, payload, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"success":"Password reset e-mail has been sent."}') def test_password_reset_confirm_fail_invalid_token(self): """ Test password reset confirm fails if token is invalid. """ user = get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') url_kwargs = self._generate_uid_and_token(user) data = { 'new_password1': 'new_password', 'new_password2': 'new_password', 'uid': url_kwargs['uid'], 'token': '-wrong-token-' } response = self.client.post(self.rest_password_reset_confirm_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEquals(response.content, '{"token":["Invalid value"]}') def test_password_reset_confirm_fail_invalid_uid(self): """ Test password reset confirm fails if uid is invalid. """ user = get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') url_kwargs = self._generate_uid_and_token(user) data = { 'new_password1': 'new_password', 'new_password2': 'new_password', 'uid': 0, 'token': url_kwargs['token'] } response = self.client.post(self.rest_password_reset_confirm_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEquals(response.content, '{"uid":["Invalid value"]}') def test_password_reset_confirm_fail_passwords_not_the_same(self): """ Test password reset confirm fails if uid is invalid. """ user = get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') url_kwargs = self._generate_uid_and_token(user) data = { 'new_password1': 'new_password', 'new_password2': 'new_not_the_same_password', 'uid': url_kwargs['uid'], 'token': url_kwargs['token'] } response = self.client.post(self.rest_password_reset_confirm_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEquals(response.content, '{"new_password2":["The two password fields didn\'t match."]}') def test_password_reset_confirm_login(self): """ Tests password reset confirm works -> can login afterwards. """ user = get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') url_kwargs = self._generate_uid_and_token(user) data = { 'new_password1': 'new_password', 'new_password2': 'new_password', 'uid': url_kwargs['uid'], 'token': url_kwargs['token'] } response = self.client.post(self.rest_password_reset_confirm_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) response = self.client.post(self.login_url, {'username': 'admin', 'email': 'admin@email.com', 'password': 'new_password'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) def test_password_reset_confirm_login_fails_with_old_password(self): """ Tests password reset confirm fails with old password. """ user = get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') url_kwargs = self._generate_uid_and_token(user) data = { 'new_password1': 'new_password', 'new_password2': 'new_password', 'uid': url_kwargs['uid'], 'token': url_kwargs['token'] } response = self.client.post(self.rest_password_reset_confirm_url, data, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) response = self.client.post(self.login_url, {'username': 'admin', 'email': 'admin@email.com', 'password': 'password12'}, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST) """ User Detail Tests ================= """ def test_user_details_get(self): """ Test to retrieve user details. """ self.create_user_and_login() response = self.client.get(self.user_url, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"username":"admin","email":"admin@email.com","first_name":"","last_name":""}') def test_user_details_put(self): """ Test to put update user details. """ self.create_user_and_login() response = self.client.put(self.user_url, {"username":"changed","email":"changed@email.com","first_name":"changed","last_name":"name"}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"username":"changed","email":"changed@email.com","first_name":"changed","last_name":"name"}') def test_user_details_patch(self): """ Test to patch update user details. """ self.create_user_and_login() response = self.client.patch(self.user_url, {'username': 'changed_username', 'email': 'changed@email.com'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.content, '{"username":"changed_username","email":"changed@email.com","first_name":"","last_name":""}') def test_user_details_put_not_authenticated(self): """ Test to put update user details. """ get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') response = self.client.put(self.user_url, {"username":"changed","email":"changed@email.com","first_name":"changed","last_name":"name"}, format='json') self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_user_details_patch_not_authenticated(self): """ Test to patch update user details. """ get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') response = self.client.patch(self.user_url, {'username': 'changed_username', 'email': 'changed@email.com'}, format='json') self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_user_details_get_not_authenticated(self): """ Test to retrieve user details. """ get_user_model().objects.create_user('admin', 'admin@email.com', 'password12') response = self.client.get(self.user_url, format='json') self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED) class TestAccountsSocial(APITestCase): """ Tests normal for social login. """ urls = 'accounts.test_social_urls' def setUp(self): self.fb_login_url = reverse('fb_login') social_app = SocialApp.objects.create( provider='facebook', name='Facebook', client_id='123123123', secret='321321321', ) site = Site.objects.get_current() social_app.sites.add(site) self.graph_api_url = GRAPH_API_URL + '/me' @responses.activate def test_social_auth(self): """ Tests Social Login. """ resp_body = '{"id":"123123123123","first_name":"John","gender":"male","last_name":"Smith","link":"https:\\/\\/www.facebook.com\\/john.smith","locale":"en_US","name":"John Smith","timezone":2,"updated_time":"2014-08-13T10:14:38+0000","username":"john.smith","verified":true}' # noqa responses.add( responses.GET, self.graph_api_url, body=resp_body, status=200, content_type='application/json' ) users_count = get_user_model().objects.all().count() response = self.client.post(self.fb_login_url, {'access_token': 'abc123'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertIn('key', response.data) self.assertEqual(get_user_model().objects.all().count(), users_count + 1) @responses.activate def test_social_auth_only_one_user_created(self): """ Tests Social Login. """ resp_body = '{"id":"123123123123","first_name":"John","gender":"male","last_name":"Smith","link":"https:\\/\\/www.facebook.com\\/john.smith","locale":"en_US","name":"John Smith","timezone":2,"updated_time":"2014-08-13T10:14:38+0000","username":"john.smith","verified":true}' # noqa responses.add( responses.GET, self.graph_api_url, body=resp_body, status=200, content_type='application/json' ) users_count = get_user_model().objects.all().count() response = self.client.post(self.fb_login_url, {'access_token': 'abc123'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertIn('key', response.data) self.assertEqual(get_user_model().objects.all().count(), users_count + 1) # make sure that second request will not create a new user response = self.client.post(self.fb_login_url, {'access_token': 'abc123'}, format='json') self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertIn('key', response.data) self.assertEqual(get_user_model().objects.all().count(), users_count + 1) @responses.activate def test_failed_social_auth(self): # fake response responses.add( responses.GET, self.graph_api_url, body='', status=400, content_type='application/json' ) response = self.client.post(self.fb_login_url, {'access_token': 'abc123'}, format='json') self.assertEquals(response.status_code, status.HTTP_400_BAD_REQUEST)
JTarball/docker-django-polymer
docker/app/app/backend/apps/accounts/test_views.py
Python
gpl-2.0
42,275
/* * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> * * 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; either version 2 of the License, or (at your * option) any later version. * * 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, see <http://www.gnu.org/licenses/>. */ /* * Comment: The event with the Living Mojos is not implemented, just is done that when one of the mojos around the boss take damage will make the boss enter in combat! */ #include "ScriptPCH.h" #include "gundrak.h" enum Spells { SPELL_EMERGE = 54850, SPELL_MIGHTY_BLOW = 54719, SPELL_MERGE = 54878, SPELL_SURGE = 54801, SPELL_FREEZE_ANIM = 16245, SPELL_MOJO_PUDDLE = 55627, H_SPELL_MOJO_PUDDLE = 58994, SPELL_MOJO_WAVE = 55626, H_SPELL_MOJO_WAVE = 58993 }; struct boss_drakkari_colossusAI : public ScriptedAI { boss_drakkari_colossusAI(Creature* pCreature) : ScriptedAI(pCreature) { pInstance = pCreature->GetInstanceData(); } ScriptedInstance* pInstance; bool bHealth; bool bHealth1; uint32 MightyBlowTimer; void Reset() { if (pInstance) pInstance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, NOT_STARTED); if (!me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE)) me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->clearUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT); me->SetReactState(REACT_PASSIVE); MightyBlowTimer = 10*IN_MILLISECONDS; bHealth = false; bHealth1 = false; } void EnterCombat(Unit* /*who*/) { if (pInstance) pInstance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, IN_PROGRESS); } void CreatureState(Creature* pWho, bool bRestore = false) { if (!pWho) return; if (bRestore) { pWho->clearUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT); pWho->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); if (pWho == me) me->RemoveAura(SPELL_FREEZE_ANIM); }else { pWho->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pWho->addUnitState(UNIT_STAT_STUNNED | UNIT_STAT_ROOT); if (pWho == me) DoCast(me,SPELL_FREEZE_ANIM); } } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (!bHealth && HealthBelowPct(50) && !HealthBelowPct(5)) { CreatureState(me, false); DoCast(me,SPELL_FREEZE_ANIM); DoCast(me,SPELL_EMERGE); bHealth = true; } if (!bHealth1 && HealthBelowPct(5)) { DoCast(me,SPELL_EMERGE); CreatureState(me, false); bHealth1 = true; me->RemoveAllAuras(); } if (MightyBlowTimer <= diff) { DoCast(me->getVictim(), SPELL_MIGHTY_BLOW, true); MightyBlowTimer = 10*IN_MILLISECONDS; } else MightyBlowTimer -= diff; if (!me->hasUnitState(UNIT_STAT_STUNNED)) DoMeleeAttackIfReady(); } void JustDied(Unit* /*killer*/) { if (pInstance) pInstance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, DONE); } void JustSummoned(Creature* pSummon) { if (HealthBelowPct(5)) pSummon->DealDamage(pSummon, pSummon->GetHealth() * 0.5 , NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); pSummon->AI()->AttackStart(me->getVictim()); } }; struct boss_drakkari_elementalAI : public ScriptedAI { boss_drakkari_elementalAI(Creature* pCreature) : ScriptedAI(pCreature) { pInstance = pCreature->GetInstanceData(); } ScriptedInstance* pInstance; uint32 uiSurgeTimer; bool bGoToColossus; void Reset() { if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0)) CAST_AI(boss_drakkari_colossusAI, pColossus->AI())->CreatureState(me, true); uiSurgeTimer = 7*IN_MILLISECONDS; bGoToColossus = false; } void EnterEvadeMode() { me->RemoveFromWorld(); } void MovementInform(uint32 uiType, uint32 /*uiId*/) { if (uiType != POINT_MOTION_TYPE) return; if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0)) { CAST_AI(boss_drakkari_colossusAI, pColossus->AI())->CreatureState(pColossus, true); CAST_AI(boss_drakkari_colossusAI, pColossus->AI())->bHealth1 = false; } me->RemoveFromWorld(); } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (!bGoToColossus && HealthBelowPct(50)) { if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0)) { if (!CAST_AI(boss_drakkari_colossusAI,pColossus->AI())->HealthBelowPct(6)) { me->InterruptNonMeleeSpells(true); DoCast(pColossus, SPELL_MERGE); bGoToColossus = true; } } } if (uiSurgeTimer <= diff) { DoCast(me->getVictim(), SPELL_SURGE); uiSurgeTimer = 7*IN_MILLISECONDS; } else uiSurgeTimer -= diff; DoMeleeAttackIfReady(); } void JustDied(Unit* /*killer*/) { if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0)) pColossus->Kill(pColossus); } }; struct npc_living_mojoAI : public ScriptedAI { npc_living_mojoAI(Creature* pCreature) : ScriptedAI(pCreature) { pInstance = pCreature->GetInstanceData(); } ScriptedInstance* pInstance; uint32 uiMojoWaveTimer; uint32 uiMojoPuddleTimer; void Reset() { uiMojoWaveTimer = 2*IN_MILLISECONDS; uiMojoPuddleTimer = 7*IN_MILLISECONDS; } void EnterCombat(Unit* /*who*/) { //Check if the npc is near of Drakkari Colossus. if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0)) { if (pColossus->isAlive() && me->IsInRange3d(pColossus->GetHomePosition().GetPositionX(),pColossus->GetHomePosition().GetPositionY(),pColossus->GetHomePosition().GetPositionZ(),0.0f,17.0f)) me->SetReactState(REACT_PASSIVE); else me->SetReactState(REACT_AGGRESSIVE); } } void DamageTaken(Unit* pDone_by, uint32& /*uiDamage*/) { if (me->HasReactState(REACT_PASSIVE)) { if (Creature *pColossus = Unit::GetCreature(*me, pInstance ? pInstance->GetData64(DATA_DRAKKARI_COLOSSUS) : 0)) { if (pColossus->isAlive() && !pColossus->isInCombat()) { pColossus->RemoveAura(SPELL_FREEZE_ANIM); pColossus->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); pColossus->SetReactState(REACT_AGGRESSIVE); if (pDone_by && pDone_by->isAlive()) pColossus->AI()->AttackStart(pDone_by); EnterEvadeMode(); } } } } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (uiMojoWaveTimer <= diff) { DoCast(me->getVictim(), SPELL_MOJO_WAVE); uiMojoWaveTimer = 15*IN_MILLISECONDS; } else uiMojoWaveTimer -= diff; if (uiMojoPuddleTimer <= diff) { DoCast(me->getVictim(), SPELL_MOJO_PUDDLE); uiMojoPuddleTimer = 18*IN_MILLISECONDS; } else uiMojoPuddleTimer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_drakkari_colossus(Creature* pCreature) { return new boss_drakkari_colossusAI (pCreature); } CreatureAI* GetAI_boss_drakkari_elemental(Creature* pCreature) { return new boss_drakkari_elementalAI (pCreature); } CreatureAI* GetAI_npc_living_mojo(Creature* pCreature) { return new npc_living_mojoAI (pCreature); } void AddSC_boss_drakkari_colossus() { Script* newscript; newscript = new Script; newscript->Name = "boss_drakkari_colossus"; newscript->GetAI = &GetAI_boss_drakkari_colossus; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "boss_drakkari_elemental"; newscript->GetAI = &GetAI_boss_drakkari_elemental; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "npc_living_mojo"; newscript->GetAI = &GetAI_npc_living_mojo; newscript->RegisterSelf(); }
Archives/ro_core
src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp
C++
gpl-2.0
9,756
/* * The Mana Server * Copyright (C) 2006-2010 The Mana World Development Team * * This file is part of The Mana Server. * * The Mana Server 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; either version 2 of the License, or * any later version. * * The Mana Server 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 The Mana Server. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <zlib.h> #include "utils/zlib.h" #include "utils/logger.h" static void logZlibError(int error) { switch (error) { case Z_MEM_ERROR: LOG_ERROR("Out of memory while decompressing data!"); break; case Z_VERSION_ERROR: LOG_ERROR("Incompatible zlib version!"); break; case Z_DATA_ERROR: LOG_ERROR("Incorrect zlib compressed data!"); break; default: LOG_ERROR("Unknown error while decompressing data!"); } } bool inflateMemory(char *in, unsigned inLength, char *&out, unsigned &outLength) { int bufferSize = 256 * 1024; int ret; z_stream strm; out = (char *)malloc(bufferSize); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = (Bytef *)in; strm.avail_in = inLength; strm.next_out = (Bytef *)out; strm.avail_out = bufferSize; ret = inflateInit2(&strm, 15 + 32); if (ret != Z_OK) { logZlibError(ret); free(out); return false; } do { ret = inflate(&strm, Z_SYNC_FLUSH); switch (ret) { case Z_NEED_DICT: case Z_STREAM_ERROR: ret = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&strm); logZlibError(ret); free(out); return false; } if (ret != Z_STREAM_END) { out = (char *)realloc(out, bufferSize * 2); if (!out) { inflateEnd(&strm); logZlibError(Z_MEM_ERROR); free(out); return false; } strm.next_out = (Bytef *)(out + bufferSize); strm.avail_out = bufferSize; bufferSize *= 2; } } while (ret != Z_STREAM_END); if (strm.avail_in != 0) { logZlibError(Z_DATA_ERROR); free(out); return false; } outLength = bufferSize - strm.avail_out; inflateEnd(&strm); return true; }
mana/manaserv
src/utils/zlib.cpp
C++
gpl-2.0
2,951
<?php class InstallDocFormatterTest extends \MediaWikiUnitTestCase { /** * @covers InstallDocFormatter * @dataProvider provideDocFormattingTests */ public function testFormat( $expected, $unformattedText, $message = '' ) { $this->assertEquals( $expected, InstallDocFormatter::format( $unformattedText ), $message ); } /** * Provider for testFormat() */ public static function provideDocFormattingTests() { # Format: (expected string, unformattedText string, optional message) return [ # Escape some wikitext [ 'Install &lt;tag>', 'Install <tag>', 'Escaping <' ], [ 'Install &#123;&#123;template}}', 'Install {{template}}', 'Escaping [[' ], [ 'Install &#91;&#91;page]]', 'Install [[page]]', 'Escaping {{' ], [ 'Install &#95;&#95;TOC&#95;&#95;', 'Install __TOC__', 'Escaping __' ], [ 'Install ', "Install \r", 'Removing \r' ], # Transform \t{1,2} into :{1,2} [ ':One indentation', "\tOne indentation", 'Replacing a single \t' ], [ '::Two indentations', "\t\tTwo indentations", 'Replacing 2 x \t' ], # Transform 'T123' links [ '<span class="config-plainlink">[https://phabricator.wikimedia.org/T123 T123]</span>', 'T123', 'Testing T123 links' ], [ 'bug <span class="config-plainlink">[https://phabricator.wikimedia.org/T123 T123]</span>', 'bug T123', 'Testing bug T123 links' ], [ '(<span class="config-plainlink">[https://phabricator.wikimedia.org/T987654 T987654]</span>)', '(T987654)', 'Testing (T987654) links' ], # "Tabc" shouldn't work [ 'Tfoobar', 'Tfoobar', "Don't match T followed by non-digits" ], [ 'T!!fakefake!!', 'T!!fakefake!!', "Don't match T followed by non-digits" ], # Transform 'bug 123' links [ '<span class="config-plainlink">[https://bugzilla.wikimedia.org/123 bug 123]</span>', 'bug 123', 'Testing bug 123 links' ], [ '(<span class="config-plainlink">[https://bugzilla.wikimedia.org/987654 bug 987654]</span>)', '(bug 987654)', 'Testing (bug 987654) links' ], # "bug abc" shouldn't work [ 'bug foobar', 'bug foobar', "Don't match bug followed by non-digits" ], [ 'bug !!fakefake!!', 'bug !!fakefake!!', "Don't match bug followed by non-digits" ], # Transform '$wgFooBar' links [ '<span class="config-plainlink">' . '[https://www.mediawiki.org/wiki/Manual:$wgFooBar $wgFooBar]</span>', '$wgFooBar', 'Testing basic $wgFooBar' ], [ '<span class="config-plainlink">' . '[https://www.mediawiki.org/wiki/Manual:$wgFooBar45 $wgFooBar45]</span>', '$wgFooBar45', 'Testing $wgFooBar45 (with numbers)' ], [ '<span class="config-plainlink">' . '[https://www.mediawiki.org/wiki/Manual:$wgFoo_Bar $wgFoo_Bar]</span>', '$wgFoo_Bar', 'Testing $wgFoo_Bar (with underscore)' ], # Icky variables that shouldn't link [ '$myAwesomeVariable', '$myAwesomeVariable', 'Testing $myAwesomeVariable (not starting with $wg)' ], [ '$()not!a&Var', '$()not!a&Var', 'Testing $()not!a&Var (obviously not a variable)' ], ]; } }
pierres/archlinux-mediawiki
tests/phpunit/unit/includes/installer/InstallDocFormatterTest.php
PHP
gpl-2.0
3,039
import React from "react"; import PropTypes from "prop-types"; import Box from "grommet/components/Box"; import Paragraph from "grommet/components/Paragraph"; import Label from "grommet/components/Label"; import FormLayer from "../components/FormLayer"; class LayerObjectFieldTemplate extends React.Component { constructor(props) { super(props); this.state = { layerActive: false }; } _onClick() { this.setState({ layerActive: true }); } render() { if (this.props.idSchema["$id"] == "root") { return <Box>{this.props.properties.map(prop => prop.content)}</Box>; } else { return ( <Box className="grommetux-form-field" direction="row" wrap={false}> { <FormLayer layerActive={this.state.layerActive} onClose={(() => { this.setState({ layerActive: false }); }).bind(this)} properties={this.props.properties.map(prop => prop.content)} /> } <Box flex={true}> <Box align="center"> <Label size="small" strong="none" uppercase={true}> {this.props.title} </Label> </Box> {this.props.description ? ( <Paragraph size="small">{this.props.description}</Paragraph> ) : null} </Box> </Box> ); } } } LayerObjectFieldTemplate.propTypes = { title: PropTypes.string, description: PropTypes.string, required: PropTypes.bool, idSchema: PropTypes.object, uiSchema: PropTypes.object, properties: PropTypes.object }; export default LayerObjectFieldTemplate;
pamfilos/data.cern.ch
ui/cap-react/src/components/drafts/form/themes/grommet-preview/templates/LayerObjectFieldTemplate.js
JavaScript
gpl-2.0
1,677
// 20020717 gdr // Copyright (C) 2002-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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; either version 3, or (at your option) // any later version. // This library 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 library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // Test slice class invariants #include <valarray> #include <cstdlib> #include <testsuite_hooks.h> bool construction(std::size_t start, std::size_t size, std::size_t stride) { std::slice s(start, size, stride); return s.start() == start && s.size() == size && s.stride() == stride; } bool copy(std::size_t start, std::size_t size, std::size_t stride) { std::slice s(start, size, stride); std::slice t = s; return t.start() == start && t.size() == size && t.stride() == stride; } bool assignment(std::size_t start, std::size_t size, std::size_t stride) { std::slice s(start, size, stride); std::slice t; t = s; return t.start() == start && t.size() == size && t.stride() == stride; } int main() { std::srand(20020717); using std::rand; VERIFY(construction(rand(), rand(), rand())); VERIFY(copy(rand(), rand(), rand())); VERIFY(assignment(rand(), rand(), rand())); return 0; }
Gurgel100/gcc
libstdc++-v3/testsuite/26_numerics/slice/1.cc
C++
gpl-2.0
1,704
<?php /** * This file represents an example of the code that themes would use to register * the required plugins. * * It is expected that theme authors would copy and paste this code into their * functions.php file, and amend to suit. * * @package TGM-Plugin-Activation * @subpackage Example * @version 2.3.6 * @author Thomas Griffin <thomas@thomasgriffinmedia.com> * @author Gary Jones <gamajo@gamajo.com> * @copyright Copyright (c) 2012, Thomas Griffin * @license http://opensource.org/licenses/gpl-2.0.php GPL v2 or later * @link https://github.com/thomasgriffin/TGM-Plugin-Activation */ /** * Include the TGM_Plugin_Activation class. */ require_once ( get_template_directory() .'/functions/class-tgm-plugin-activation.php' ); add_action( 'tgmpa_register', 'my_theme_register_required_plugins' ); /** * Register the required plugins for this theme. * * In this example, we register two plugins - one included with the TGMPA library * and one from the .org repo. * * The variable passed to tgmpa_register_plugins() should be an array of plugin * arrays. * * This function is hooked into tgmpa_init, which is fired within the * TGM_Plugin_Activation class constructor. */ function my_theme_register_required_plugins() { /** * Array of plugin arrays. Required keys are name and slug. * If the source is NOT from the .org repo, then source is also required. */ $plugins = array( array( 'name' => 'Symple Shortcodes', 'slug' => 'symple-shortcodes', 'source' => 'http://www.wpexplorer.com/symple-shortcodes-download', 'required' => false, 'force_activation' => false, 'force_deactivation' => false, ), array( 'name' => 'ZillaLikes', 'slug' => 'zilla-likes', 'source' => get_template_directory_uri() . '/plugins/zilla-likes.zip', 'Required' => true, 'version' => '1.0', 'force_activation' => false, 'force_deactivation' => false, 'external_url' => '', ) ); // Change this to your theme text domain, used for internationalising strings $theme_text_domain = 'tgmpa'; /** * Array of configuration settings. Amend each line as needed. * If you want the default strings to be available under your own theme domain, * leave the strings uncommented. * Some of the strings are added into a sprintf, so see the comments at the * end of each line for what each argument will be. */ $config = array( 'domain' => $theme_text_domain, // Text domain - likely want to be the same as your theme. 'default_path' => '', // Default absolute path to pre-packaged plugins 'parent_menu_slug' => 'themes.php', // Default parent menu slug 'parent_url_slug' => 'themes.php', // Default parent URL slug 'menu' => 'install-required-plugins', // Menu slug 'has_notices' => true, // Show admin notices or not 'is_automatic' => false, // Automatically activate plugins after installation or not 'message' => '', // Message to output right before the plugins table 'strings' => array( 'page_title' => __( 'Install Required Plugins', $theme_text_domain ), 'menu_title' => __( 'Install Plugins', $theme_text_domain ), 'installing' => __( 'Installing Plugin: %s', $theme_text_domain ), // %1$s = plugin name 'oops' => __( 'Something went wrong with the plugin API.', $theme_text_domain ), 'notice_can_install_required' => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.' ), // %1$s = plugin name(s) 'notice_can_install_recommended' => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.' ), // %1$s = plugin name(s) 'notice_cannot_install' => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.' ), // %1$s = plugin name(s) 'notice_can_activate_required' => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.' ), // %1$s = plugin name(s) 'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.' ), // %1$s = plugin name(s) 'notice_cannot_activate' => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.' ), // %1$s = plugin name(s) 'notice_ask_to_update' => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.' ), // %1$s = plugin name(s) 'notice_cannot_update' => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.' ), // %1$s = plugin name(s) 'install_link' => _n_noop( 'Begin installing plugin', 'Begin installing plugins' ), 'activate_link' => _n_noop( 'Activate installed plugin', 'Activate installed plugins' ), 'return' => __( 'Return to Required Plugins Installer', $theme_text_domain ), 'plugin_activated' => __( 'Plugin activated successfully.', $theme_text_domain ), 'complete' => __( 'All plugins installed and activated successfully. %s', $theme_text_domain ), // %1$s = dashboard link 'nag_type' => 'updated' // Determines admin notice type - can only be 'updated' or 'error' ) ); tgmpa( $plugins, $config ); }
ucommerzdev3/activities_lwdwn
wp-content/themes/wpex-fashionista/functions/recommend-plugins.php
PHP
gpl-2.0
6,543
""" This page is in the table of contents. Plugin to home the tool at beginning of each layer. The home manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home ==Operation== The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, nothing will be done. ==Settings== ===Name of Home File=== Default: home.gcode At the beginning of a each layer, home will add the commands of a gcode script with the name of the "Name of Home File" setting, if one exists. Home does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names. Home looks for those files in the alterations folder in the .skeinforge folder in the home directory. If it doesn't find the file it then looks in the alterations folder in the skeinforge_plugins folder. ==Examples== The following examples home the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and home.py. > python home.py This brings up the home dialog. > python home.py Screw Holder Bottom.stl The home tool is parsing the file: Screw Holder Bottom.stl .. The home tool has created the file: .. Screw Holder Bottom_home.gcode """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret from fabmetheus_utilities.vector3 import Vector3 from fabmetheus_utilities import archive from fabmetheus_utilities import euclidean from fabmetheus_utilities import gcodec from fabmetheus_utilities import settings from skeinforge_application.skeinforge_utilities import skeinforge_craft from skeinforge_application.skeinforge_utilities import skeinforge_polyfile from skeinforge_application.skeinforge_utilities import skeinforge_profile import math import os import sys __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getCraftedText( fileName, text, repository = None ): "Home a gcode linear move file or text." return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) def getCraftedTextFromText( gcodeText, repository = None ): "Home a gcode linear move text." if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'home'): return gcodeText if repository == None: repository = settings.getReadRepository( HomeRepository() ) if not repository.activateHome.value: return gcodeText return HomeSkein().getCraftedGcode(gcodeText, repository) def getNewRepository(): 'Get new repository.' return HomeRepository() def writeOutput(fileName, shouldAnalyze=True): "Home a gcode linear move file. Chain home the gcode if it is not already homed." skeinforge_craft.writeChainTextWithNounMessage(fileName, 'home', shouldAnalyze) class HomeRepository: "A class to handle the home settings." def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.home.html', self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Home', self, '') self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home') self.activateHome = settings.BooleanSetting().getFromValue('Activate Home', self, True ) self.nameOfHomeFile = settings.StringSetting().getFromValue('Name of Home File:', self, 'home.gcode') self.executeTitle = 'Home' def execute(self): "Home button has been clicked." fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled) for fileName in fileNames: writeOutput(fileName) class HomeSkein: "A class to home a skein of extrusions." def __init__(self): self.distanceFeedRate = gcodec.DistanceFeedRate() self.extruderActive = False self.highestZ = None self.homeLines = [] self.layerCount = settings.LayerCount() self.lineIndex = 0 self.lines = None self.oldLocation = None self.shouldHome = False self.travelFeedRateMinute = 957.0 def addFloat( self, begin, end ): "Add dive to the original height." beginEndDistance = begin.distance(end) alongWay = self.absolutePerimeterWidth / beginEndDistance closeToEnd = euclidean.getIntermediateLocation( alongWay, end, begin ) closeToEnd.z = self.highestZ self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, closeToEnd.dropAxis(), closeToEnd.z ) ) def addHomeTravel( self, splitLine ): "Add the home travel gcode." location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) self.highestZ = max( self.highestZ, location.z ) if not self.shouldHome: return self.shouldHome = False if self.oldLocation == None: return if self.extruderActive: self.distanceFeedRate.addLine('M103') self.addHopUp( self.oldLocation ) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.homeLines) self.addHopUp( self.oldLocation ) self.addFloat( self.oldLocation, location ) if self.extruderActive: self.distanceFeedRate.addLine('M101') def addHopUp(self, location): "Add hop to highest point." locationUp = Vector3( location.x, location.y, self.highestZ ) self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, locationUp.dropAxis(), locationUp.z ) ) def getCraftedGcode( self, gcodeText, repository ): "Parse gcode text and store the home gcode." self.repository = repository self.homeLines = settings.getAlterationFileLines(repository.nameOfHomeFile.value) if len(self.homeLines) < 1: return gcodeText self.lines = archive.getTextLines(gcodeText) self.parseInitialization( repository ) for self.lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[self.lineIndex] self.parseLine(line) return self.distanceFeedRate.output.getvalue() def parseInitialization( self, repository ): 'Parse gcode initialization and store the parameters.' for self.lineIndex in xrange(len(self.lines)): line = self.lines[self.lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) self.distanceFeedRate.parseSplitLine(firstWord, splitLine) if firstWord == '(</extruderInitialization>)': self.distanceFeedRate.addTagBracketedProcedure('home') return elif firstWord == '(<perimeterWidth>': self.absolutePerimeterWidth = abs(float(splitLine[1])) elif firstWord == '(<travelFeedRatePerSecond>': self.travelFeedRateMinute = 60.0 * float(splitLine[1]) self.distanceFeedRate.addLine(line) def parseLine(self, line): "Parse a gcode line and add it to the bevel gcode." splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == 'G1': self.addHomeTravel(splitLine) self.oldLocation = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) elif firstWord == '(<layer>': self.layerCount.printProgressIncrement('home') if len(self.homeLines) > 0: self.shouldHome = True elif firstWord == 'M101': self.extruderActive = True elif firstWord == 'M103': self.extruderActive = False self.distanceFeedRate.addLine(line) def main(): "Display the home dialog." if len(sys.argv) > 1: writeOutput(' '.join(sys.argv[1 :])) else: settings.startMainLoopFromConstructor(getNewRepository()) if __name__ == "__main__": main()
makerbot/ReplicatorG
skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/home.py
Python
gpl-2.0
8,040
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * 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; either version 2 of the License, or (at your * option) any later version. * * 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, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "scholomance.h" #include "ScriptedCreature.h" enum Spells { SPELL_CURSE_OF_BLOOD = 24673, SPELL_ILLUSION = 17773, SPELL_DROP_JOURNAL = 26096 }; enum Events { EVENT_CURSE_OF_BLOOD = 1, EVENT_ILLUSION, EVENT_CLEAVE, EVENT_SET_VISIBILITY }; class boss_jandice_barov : public CreatureScript { public: boss_jandice_barov() : CreatureScript("boss_jandice_barov") { } struct boss_jandicebarovAI : public ScriptedAI { boss_jandicebarovAI(Creature* creature) : ScriptedAI(creature), Summons(me) { } void Reset() override { events.Reset(); Summons.DespawnAll(); } void JustSummoned(Creature* summoned) override { // Illusions should attack a random target. if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) summoned->AI()->AttackStart(target); summoned->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_MAGIC, true); // Not sure if this is correct. Summons.Summon(summoned); } void JustEngagedWith(Unit* /*who*/) override { events.ScheduleEvent(EVENT_CURSE_OF_BLOOD, 15s); events.ScheduleEvent(EVENT_ILLUSION, 30s); } void JustDied(Unit* /*killer*/) override { Summons.DespawnAll(); DoCastSelf(SPELL_DROP_JOURNAL, true); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_CURSE_OF_BLOOD: DoCastVictim(SPELL_CURSE_OF_BLOOD); events.ScheduleEvent(EVENT_CURSE_OF_BLOOD, 30s); break; case EVENT_ILLUSION: DoCast(SPELL_ILLUSION); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->SetDisplayId(11686); // Invisible Model ModifyThreatByPercent(me->GetVictim(), -99); events.ScheduleEvent(EVENT_SET_VISIBILITY, 3s); events.ScheduleEvent(EVENT_ILLUSION, 25s); break; case EVENT_SET_VISIBILITY: me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->SetDisplayId(11073); //Jandice Model break; default: break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } DoMeleeAttackIfReady(); } private: EventMap events; SummonList Summons; }; CreatureAI* GetAI(Creature* creature) const override { return GetScholomanceAI<boss_jandicebarovAI>(creature); } }; void AddSC_boss_jandicebarov() { new boss_jandice_barov(); }
Exitare/TrinityCore
src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp
C++
gpl-2.0
3,997
<?php /** * @package AkeebaBackup * * @license GNU General Public License, version 2 or later * @author Nicholas K. Dionysopoulos * @copyright Copyright 2006-2009 Nicholas K. Dionysopoulos * @since 1.3 */ defined('_JEXEC') or die(); /** * Database Table filter Model class * */ class AkeebaModelDbefs extends FOFModel { /** * Returns a list of the database tables, views, procedures, functions and triggers, * along with their filter status in array format, for use in the GUI * @return array */ public function make_listing($root) { // Get database inclusion filters $filters = AEFactory::getFilters(); $database_list = $filters->getInclusions('db'); // Load the database object for the selected database $config = $database_list[$root]; $config['user'] = $config['username']; $db = AEFactory::getDatabase($config); // Load the table data $table_data = $db->getTables(); // Process filters $tables = array(); if(!empty($table_data)) { foreach($table_data as $table_name => $table_type) { $status = array(); // Add table type $status['type'] = $table_type; // Check dbobject/all filter (exclude) $result = $filters->isFilteredExtended($table_name, $root, 'dbobject', 'all', $byFilter); $status['tables'] = (!$result) ? 0 : (( $byFilter == 'tables' ) ? 1 : 2 ); // Check dbobject/content filter (skip table data) $result = $filters->isFilteredExtended($table_name, $root, 'dbobject', 'content', $byFilter); $status['tabledata'] = (!$result) ? 0 : (( $byFilter == 'tabledata' ) ? 1 : 2 ); if( $table_type != 'table' ) $status['tabledata'] = 2; // We can't filter contents of views, merge tables, black holes, procedures, functions and triggers :) $tables[$table_name] = $status; } } return array( 'tables' => $tables, 'root' => $root ); } /** * Returns an array containing a mapping of db root names and their human-readable representation * @return array Array of objects; "value" contains the root name, "text" the human-readable text */ public function get_roots() { // Get database inclusion filters $filters = AEFactory::getFilters(); $database_list = $filters->getInclusions('db'); $ret = array(); foreach($database_list as $name => $definition) { $root = $definition['host']; if(!empty($definition['port'])) $root.=':'.$definition['port']; $root.='/'.$definition['database']; if($name == '[SITEDB]') $root = JText::_('DBFILTER_LABEL_SITEDB'); $entry = new stdClass(); $entry->value = $name; $entry->text = $root; $ret[] = $entry; } return $ret; } /** * Toggle a filter * @param string $root Root directory * @param string $item The child item of the current directory we want to toggle the filter for * @param string $filter The name of the filter to apply (directories, skipfiles, skipdirs, files) * @return array */ public function toggle($root, $item, $filter) { if(empty($item)) return array( 'success' => false, 'newstate'=> false ); // Get a reference to the global Filters object $filters = AEFactory::getFilters(); // Get the specific filter object $filter = AEFactory::getFilterObject($filter); // Toggle the filter $success = $filter->toggle($root, $item, $new_status); // Save the data on success if($success) $filters->save(); // Make a return array return array( 'success' => $success, 'newstate' => $new_status ); } /** * Set a filter * @param string $root Root directory * @param string $item The child item of the current directory we want to set the filter for * @param string $filter The name of the filter to apply (directories, skipfiles, skipdirs, files) * @return array */ public function remove($root, $item, $filter) { if(empty($item)) return array( 'success' => false, 'newstate'=> false ); // Get a reference to the global Filters object $filters = AEFactory::getFilters(); // Get the specific filter object $filter = AEFactory::getFilterObject($filter); // Toggle the filter $success = $filter->remove($root, $item); // Save the data on success if($success) $filters->save(); // Make a return array return array( 'success' => $success, 'newstate' => !$success // The new state of the filter. It is removed if and only if the transaction succeeded ); } /** * Set a filter * @param string $root Root directory * @param string $item The child item of the current directory we want to set the filter for * @param string $filter The name of the filter to apply (directories, skipfiles, skipdirs, files) * @return array */ public function set($root, $item, $filter) { if(empty($item)) return array( 'success' => false, 'newstate'=> false ); // Get a reference to the global Filters object $filters = AEFactory::getFilters(); // Get the specific filter object $filter = AEFactory::getFilterObject($filter); // Toggle the filter $success = $filter->set($root, $item); // Save the data on success if($success) $filters->save(); // Make a return array return array( 'success' => $success, 'newstate' => $success // The new state of the filter. It is set if and only if the transaction succeeded ); } /** * Swap a filter * @param string $root Root directory * @param string $item The child item of the current directory we want to set the filter for * @param string $filter The name of the filter to apply (directories, skipfiles, skipdirs, files) * @return array */ public function swap($root, $old_item, $new_item, $filter) { if(empty($new_item)) return array( 'success' => false, 'newstate'=> false ); // Get a reference to the global Filters object $filters = AEFactory::getFilters(); // Get the specific filter object $filter = AEFactory::getFilterObject($filter); // Toggle the filter if(!empty($old_item)) { $success = $filter->remove($root, $old_item); } else { $success = true; } if($success) { $success = $filter->set($root, $new_item); } // Save the data on success if($success) $filters->save(); // Make a return array return array( 'success' => $success, 'newstate' => $success // The new state of the filter. It is set if and only if the transaction succeeded ); } /** * Retrieves the filters as an array. Used for the tabular filter editor. * @param string $root The root node to search filters on * @return array A collection of hash arrays containing node and type for each filtered element */ public function &get_filters($root) { // A reference to the global Akeeba Engine filter object $filters = AEFactory::getFilters(); // Initialize the return array $ret = array(); // Define the known filter types and loop through them $filter_types = array('tables', 'tabledata'); foreach($filter_types as $type) { $rawFilterData = $filters->getFilterData($type); if( array_key_exists($root, $rawFilterData) ) { if(!empty($rawFilterData[$root])) { foreach($rawFilterData[$root] as $node) { $ret[] = array ( 'node' => substr($node,0), // Make sure we get a COPY, not a reference to the original data 'type' => $type ); } } } } /* * Return array format: * [array] : * [array] : * 'node' => 'somedir' * 'type' => 'directories' * [array] : * 'node' => 'somefile' * 'type' => 'files' * ... */ return $ret; } /** * Resets the filters * @param string $root Root directory * @return array */ public function resetFilters($root) { // Get a reference to the global Filters object $filters = AEFactory::getFilters(); $filter = AEFactory::getFilterObject('tables'); $filter->reset($root); $filter = AEFactory::getFilterObject('tabledata'); $filter->reset($root); $filters->save(); return $this->make_listing($root); } function doAjax() { $action = $this->getState('action'); $verb = array_key_exists('verb', get_object_vars($action)) ? $action->verb : null; $ret_array = array(); switch($verb) { // Return a listing for the normal view case 'list': $ret_array = $this->make_listing($action->root, $action->node); break; // Toggle a filter's state case 'toggle': $ret_array = $this->toggle($action->root, $action->node, $action->filter); break; // Set a filter (used by the editor) case 'set': $ret_array = $this->set($action->root, $action->node, $action->filter); break; // Remove a filter (used by the editor) case 'remove': $ret_array = $this->remove($action->root, $action->node, $action->filter); break; // Swap a filter (used by the editor) case 'swap': $ret_array = $this->swap($action->root, $action->old_node, $action->new_node, $action->filter); break; // Tabular view case 'tab': $ret_array = $this->get_filters($action->root); break; // Reset filters case 'reset': $ret_array = $this->resetFilters($action->root); break; } return $ret_array; } }
dannysaban/store
administrator/components/com_akeeba/models/dbefs.php
PHP
gpl-2.0
9,104
<?php /** * File containing the MultipleObjectConverter class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version //autogentag// */ namespace eZ\Publish\Core\MVC\Legacy\Templating\Converter; /** * Interface for multiple object converters. * This is useful if one needs to convert several objects at once. */ interface MultipleObjectConverter extends ObjectConverter { /** * Registers an object to the converter. * $alias is the variable name that will be exposed in the legacy template. * * @param mixed $object * @param string $alias * * @throws \InvalidArgumentException If $object is not an object * * @return void */ public function register( $object, $alias ); /** * Converts all registered objects and returns them in a hash where the object's alias is the key. * * @return array|\eZ\Publish\Core\MVC\Legacy\Templating\LegacyCompatible[] */ public function convertAll(); }
TestingCI/php_mysql_build
eZ/Publish/Core/MVC/Legacy/Templating/Converter/MultipleObjectConverter.php
PHP
gpl-2.0
1,109
var UserInformation_AccountStore = new Ext.data.Store({ fields:[ {name : 'Name'}, {name : 'ID'}, {name : 'Mail'}, {name : 'Roles'} ], reader : AccountReader }); var UserInformationItem = [ { fieldLabel : 'User ID', name : 'id', readOnly : true }, { fieldLabel : 'User Name', name : 'username', allowBlank : false, regex : /^[^"'\\><&]*$/, regexText : 'deny following char " < > \\ & \'' }, { id : 'UserInformation_Form_Password', fieldLabel : 'Password', name : 'passwd', inputType : 'password', listeners : { 'change': function() { if (this.getValue() == "") { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(false); Ext.getCmp("UserInformation_Form_reenter").allowBlank = true; } else { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(true); Ext.getCmp("UserInformation_Form_reenter").allowBlank = false; } } } }, { id : 'UserInformation_Form_reenter', fieldLabel : 'Re-enter', initialPassField : 'passwd', name : 'reenter', inputType : 'password', initialPassField: 'UserInformation_Form_Password', vtype : 'pwdvalid', listeners : { 'change': function() { if (Ext.getCmp("UserInformation_Form_Password").getValue() == "") { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(true); this.allowBlank = true; } else { Ext.getCmp('UserInformationManagement_Page').getTopToolbar().get('UserInformation_UpdateAccountBtn').setDisabled(false); this.allowBlank = false; } } } }, { fieldLabel : 'E-mail Address', name : 'email', vtype : 'email', allowBlank : false } ]; // the form is for UserInformation Page ezScrum.UserInformationForm = Ext.extend(ezScrum.layout.InfoForm, { id : 'UserInformation_Management_From', url : 'getUserData.do', modifyurl : 'updateAccount.do' , store : UserInformation_AccountStore, width:500, bodyStyle:'padding:50px', monitorValid : true, buttonAlign:'center', initComponent : function() { var config = { items : [UserInformationItem], buttons : [{ formBind : true, text : 'Submit', scope : this, handler : this.submit, disabled : true }] } Ext.apply(this, Ext.apply(this.initialConfig, config)); ezScrum.UserInformationForm.superclass.initComponent.apply(this, arguments); }, submit : function() { Ext.getCmp('UserInformationManagement_Page').doModify(); }, loadDataModel: function() { UserManagementMainLoadMaskShow(); Ext.Ajax.request({ scope : this, url : this.url, success: function(response) { UserInformation_AccountStore.loadData(response.responseXML); var record = UserInformation_AccountStore.getAt(0); this.setDataModel(record); UserManagementMainLoadMaskHide(); }, failure: function(response) { UserManagementMainLoadMaskHide(); Ext.example.msg('Server Error', 'Sorry, the connection is failure.'); } }); }, setDataModel: function(record) { this.getForm().reset(); this.getForm().setValues({ id : record.data['ID'], username: record.data['Name'], passwd : '', reenter : '', email : record.data['Mail'] }); }, doModify: function() { UserManagementMainLoadMaskShow(); Ext.Ajax.request({ scope : this, url : this.modifyurl, params : this.getForm().getValues(), success : function(response) { UserInformation_AccountStore.loadData(response.responseXML); var record = UserInformation_AccountStore.getAt(0); if (record) { Ext.example.msg('Update Account', 'Update Account Success'); } else { Ext.example.msg('Update Account', 'Update Account Failure'); } UserManagementMainLoadMaskHide(); }, failure:function(response){ UserManagementMainLoadMaskHide(); Ext.example.msg('Server Error', 'Sorry, the connection is failure.'); } }); } }); Ext.reg('UserInformationForm', ezScrum.UserInformationForm);
chusiang/ezScrum_Ubuntu
WebContent/javascript/ezScrumPanel/UserInformationManagementFormPanel.js
JavaScript
gpl-2.0
4,497
/* * This file is part of JPhotoAlbum. * Copyright 2004 Jari Karjala <jpkware.com> & Tarja Hakala <hakalat.net> * * @version $Id: JPhotoDirectory.java,v 1.1.1.1 2004/05/21 18:24:59 jkarjala Exp $ */ /** Container for a single photo, may not always contain a real photo, but * just text element. * @see JPhotoAlbumLink.java */ package fi.iki.jka; import java.awt.image.BufferedImage; import java.io.File; import java.io.InputStream; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.FileCacheImageInputStream; import com.drew.metadata.exif.ExifDirectory; public class JPhotoDirectory extends JPhoto { public JPhotoDirectory() { this(defaultOwner, null); } public JPhotoDirectory(JPhotoCollection owner) { this(owner, null); } public JPhotoDirectory(File original) { this(defaultOwner, original); } public JPhotoDirectory(JPhotoCollection owner, File original) { super(owner, original); } public BufferedImage getThumbImage() { InputStream ins = getClass().getClassLoader().getResourceAsStream("pics/directory.png"); Iterator readers = ImageIO.getImageReadersBySuffix("png"); ImageReader imageReader = (ImageReader)readers.next(); BufferedImage thumb = null; try { imageReader.setInput(new FileCacheImageInputStream(ins, null)); thumb = imageReader.read(0); ins.close(); } catch (Exception e) { System.out.println("getThumbImage:"+e); } imageReader.dispose(); return thumb; } public BufferedImage getCachedThumb() { return getThumbImage(); } public BufferedImage getThumbImageAsync() { return getThumbImage(); } public BufferedImage getFullImage() { return null; } public ExifDirectory getExifDirectory() { return null; } public String toString() { return "Directory='"+getImageName()+"'"; } }
91wzhang/sei-jphotoalbum
src/fi/iki/jka/JPhotoDirectory.java
Java
gpl-2.0
2,070
(function ($) { providers_small.mailru = { name: 'mail.ru', url: "javascript: $('#mail_ru_auth_login a').click();" }; openid.getBoxHTML__mailru = openid.getBoxHTML; openid.getBoxHTML = function (box_id, provider, box_size, index) { if (box_id == 'mailru') { var no_sprite = this.no_sprite; this.no_sprite = true; var result = this.getBoxHTML__mailru(box_id, provider, box_size, index); this.no_sprite = no_sprite; return result; } return this.getBoxHTML__mailru(box_id, provider, box_size, index); } Drupal.behaviors.openid_selector_mailru = { attach: function (context) { $('#mail_ru_auth_login').hide(); }} })(jQuery);
janicak/C-Db
sites/all/modules/openid_selector/openid_selector_mailru.js
JavaScript
gpl-2.0
650
/* * "$Id: tcpstream.cc,v 1.11 2007-03-01 01:09:39 rmf24 Exp $" * * TCP-on-UDP (tou) network interface for RetroShare. * * Copyright 2004-2006 by Robert Fernie. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License Version 2 as published by the Free Software Foundation. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. * * Please report all bugs and problems to "retroshare@lunamutt.com". * */ #include <stdlib.h> #include <string.h> #include "tcpstream.h" #include <iostream> #include <iomanip> #include <assert.h> #include <errno.h> #include <math.h> #include <limits.h> #include <sys/time.h> #include <time.h> /* Debugging for STATE change, and Startup SYNs */ #include "util/rsdebug.h" #include "util/rsstring.h" #include "util/rsrandom.h" static struct RsLog::logInfo rstcpstreamzoneInfo = {RsLog::Default, "rstcpstream"}; #define rstcpstreamzone &rstcpstreamzoneInfo /* * #define DEBUG_TCP_STREAM 1 * #define DEBUG_TCP_STREAM_RETRANS 1 * #define DEBUG_TCP_STREAM_CLOSE 1 */ //#define DEBUG_TCP_STREAM_RETRANS 1 //#define DEBUG_TCP_STREAM_CLOSE 1 /* *#define DEBUG_TCP_STREAM_EXTRA 1 */ /* * #define TCP_NO_PARTIAL_READ 1 */ #ifdef DEBUG_TCP_STREAM int checkData(uint8 *data, int size, int idx); int setupBinaryCheck(std::string fname); #endif static const uint32 kMaxQueueSize = 300; // Was 100, which means max packet size of 100k (smaller than max packet size). static const uint32 kMaxPktRetransmit = 10; static const uint32 kMaxSynPktRetransmit = 100; // 100 => 200secs = over 3 minutes startup static const int TCP_STD_TTL = 64; static const int TCP_DEFAULT_FIREWALL_TTL = 4; static const double RTT_ALPHA = 0.875; int dumpPacket(std::ostream &out, unsigned char *pkt, uint32_t size); // platform independent fractional timestamp. static double getCurrentTS(); TcpStream::TcpStream(UdpSubReceiver *lyr) : tcpMtx("TcpStream"), inSize(0), outSizeRead(0), outSizeNet(0), state(TCP_CLOSED), inStreamActive(false), outStreamActive(false), outSeqno(0), outAcked(0), outWinSize(0), inAckno(0), inWinSize(0), maxWinSize(TCP_MAX_WIN), keepAliveTimeout(TCP_ALIVE_TIMEOUT), retransTimerOn(false), retransTimeout(TCP_RETRANS_TIMEOUT), retransTimerTs(0), keepAliveTimer(0), lastIncomingPkt(0), lastSentAck(0), lastSentWinSize(0), initOurSeqno(0), initPeerSeqno(0), lastWriteTF(0),lastReadTF(0), wcount(0), rcount(0), errorState(0), /* retranmission variables - init to large */ rtt_est(TCP_RETRANS_TIMEOUT), rtt_dev(0), congestThreshold(TCP_MAX_WIN), congestWinSize(MAX_SEG), congestUpdate(0), ttl(0), mTTL_period(0), mTTL_start(0), mTTL_end(0), peerKnown(false), udp(lyr) { sockaddr_clear(&peeraddr); return; } /* Stream Control! */ int TcpStream::connect(const struct sockaddr_in &raddr, uint32_t conn_period) { tcpMtx.lock(); /********** LOCK MUTEX *********/ setRemoteAddress(raddr); /* check state */ if (state != TCP_CLOSED) { if (state == TCP_ESTABLISHED) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 0; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; } else { // major issues! errorState = EFAULT; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } /* setup Seqnos */ outSeqno = genSequenceNo(); initOurSeqno = outSeqno; outAcked = outSeqno; /* min - 1 expected */ inWinSize = maxWinSize; congestThreshold = TCP_MAX_WIN; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; /* Init Connection */ /* send syn packet */ TcpPacket *pkt = new TcpPacket(); pkt -> setSyn(); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::connect() Send Init Pkt" << std::endl; #endif /* ********* SLOW START ************* * As this is the only place where a syn * is sent ..... we switch the ttl to 0, * and increment it as we retransmit the packet.... * This should help the firewalls along. */ setTTL(1); mTTL_start = getCurrentTS(); mTTL_period = conn_period; mTTL_end = mTTL_start + mTTL_period; toSend(pkt); /* change state */ state = TCP_SYN_SENT; errorState = EAGAIN; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_SYN_SENT" << std::endl; #endif { rslog(RSL_WARNING,rstcpstreamzone,"TcpStream::state => TCP_SYN_SENT (Connect)"); } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } int TcpStream::listenfor(const struct sockaddr_in &raddr) { tcpMtx.lock(); /********** LOCK MUTEX *********/ setRemoteAddress(raddr); /* check state */ if (state != TCP_CLOSED) { if (state == TCP_ESTABLISHED) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 0; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; } else { // major issues! errorState = EFAULT; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } errorState = EAGAIN; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } /* Stream Control! */ int TcpStream::close() { tcpMtx.lock(); /********** LOCK MUTEX *********/ cleanup(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 0; } int TcpStream::closeWrite() { tcpMtx.lock(); /********** LOCK MUTEX *********/ /* check state */ /* will always close socket.... */ /* if in TCP_ESTABLISHED.... * -> to state: TCP_FIN_WAIT_1 * and shutdown outward stream. */ /* if in CLOSE_WAIT.... * -> to state: TCP_LAST_ACK * and shutdown outward stream. * do this one first!. */ outStreamActive = false; if (state == TCP_CLOSE_WAIT) { /* don't think we need to be * graceful at this point... * connection already closed by other end. * XXX might fix later with scheme * * flag stream closed, and when outqueue * emptied then fin will be sent. */ /* do nothing */ } if (state == TCP_ESTABLISHED) { /* fire off the damned thing. */ /* by changing state */ /* again this is handled by internals * the flag however indicates that * no more data can be send, * and once the queue empties * the FIN will be sent. */ } if (state == TCP_CLOSED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::close() Flag Set" << std::endl; #endif tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 0; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::close() pending" << std::endl; #endif errorState = EAGAIN; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } bool TcpStream::isConnected() { tcpMtx.lock(); /********** LOCK MUTEX *********/ bool isConn = (state == TCP_ESTABLISHED); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return isConn; } int TcpStream::status(std::ostream &out) { tcpMtx.lock(); /********** LOCK MUTEX *********/ int s = status_locked(out); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return s; } int TcpStream::status_locked(std::ostream &out) { int tmpstate = state; // can leave the timestamp here as time()... rough but okay. out << "TcpStream::status @ (" << time(NULL) << ")" << std::endl; out << "TcpStream::state = " << (int) state << std::endl; out << std::endl; out << "writeBuffer: " << inSize << " + MAX_SEG * " << inQueue.size(); out << " bytes Queued for transmission" << std::endl; out << "readBuffer: " << outSizeRead << " + MAX_SEG * "; out << outQueue.size() << " + " << outSizeNet; out << " incoming bytes waiting" << std::endl; out << std::endl; out << "inPkts: " << inPkt.size() << " packets waiting for processing"; out << std::endl; out << "outPkts: " << outPkt.size() << " packets waiting for acks"; out << std::endl; out << "us -> peer: nextSeqno: " << outSeqno << " lastAcked: " << outAcked; out << " winsize: " << outWinSize; out << std::endl; out << "peer -> us: Expected SeqNo: " << inAckno; out << " winsize: " << inWinSize; out << std::endl; out << std::endl; return tmpstate; } int TcpStream::write_allowed() { tcpMtx.lock(); /********** LOCK MUTEX *********/ int ret = 1; if (state == TCP_CLOSED) { errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; ret = -1; } else if (!outStreamActive) { errorState = EBADF; ret = -1; } if (ret < 1) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return ret; } int maxwrite = (kMaxQueueSize - inQueue.size()) * MAX_SEG; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return maxwrite; } int TcpStream::read_pending() { tcpMtx.lock(); /********** LOCK MUTEX *********/ /* error should be detected next time */ int maxread = int_read_pending(); if (state == TCP_CLOSED) { errorState = EBADF; maxread = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; maxread = -1; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return maxread; } /* INTERNAL */ int TcpStream::int_read_pending() { return outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; } /* stream Interface */ int TcpStream::write(char *dta, int size) /* write -> pkt -> net */ { tcpMtx.lock(); /********** LOCK MUTEX *********/ int ret = 1; /* initial error checking */ #ifdef DEBUG_TCP_STREAM_EXTRA static uint32 TMPtotalwrite = 0; #endif if (state == TCP_CLOSED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP_CLOSED" << std::endl; #endif errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP Not Established" << std::endl; #endif errorState = EAGAIN; ret = -1; } else if (inQueue.size() > kMaxQueueSize) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error EAGAIN" << std::endl; #endif errorState = EAGAIN; ret = -1; } else if (!outStreamActive) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP_CLOSED" << std::endl; #endif errorState = EBADF; ret = -1; } if (ret < 1) /* check for initial error */ { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return ret; } #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() = Will Succeed " << size << std::endl; std::cerr << "TcpStream::write() Write Start: " << TMPtotalwrite << std::endl; std::cerr << printPktOffset(TMPtotalwrite, dta, size) << std::endl; TMPtotalwrite += size; #endif if (size + inSize < MAX_SEG) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() Add Itty Bit" << std::endl; std::cerr << "TcpStream::write() inData: " << (void *) inData; std::cerr << " inSize: " << inSize << " dta: " << (void *) dta; std::cerr << " size: " << size << " dest: " << (void *) &(inData[inSize]); std::cerr << std::endl; #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() = " << size << std::endl; #endif memcpy((void *) &(inData[inSize]), dta, size); inSize += size; //std::cerr << "Small Packet - write to net:" << std::endl; //std::cerr << printPkt(dta, size) << std::endl; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } /* otherwise must construct a dataBuffer. */ #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() filling 1 dataBuffer" << std::endl; std::cerr << "TcpStream::write() from inData(" << inSize << ")" << std::endl; std::cerr << "TcpStream::write() + dta(" << MAX_SEG - inSize; std::cerr << "/" << size << ")" << std::endl; #endif /* first create 1. */ dataBuffer *db = new dataBuffer; memcpy((void *) db->data, (void *) inData, inSize); int remSize = size; memcpy((void *) &(db->data[inSize]), dta, MAX_SEG - inSize); inQueue.push_back(db); remSize -= (MAX_SEG - inSize); #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() remaining " << remSize << " bytes to load" << std::endl; #endif while(remSize >= MAX_SEG) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() filling whole dataBuffer" << std::endl; std::cerr << "TcpStream::write() from dta[" << size-remSize << "]" << std::endl; #endif db = new dataBuffer; memcpy((void *) db->data, (void *) &(dta[size-remSize]), MAX_SEG); inQueue.push_back(db); remSize -= MAX_SEG; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() = " << size << std::endl; #endif if (remSize > 0) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() putting last bit in inData" << std::endl; std::cerr << "TcpStream::write() from dta[" << size-remSize << "] size: "; std::cerr << remSize << std::endl; #endif memcpy((void *) inData, (void *) &(dta[size-remSize]), remSize); inSize = remSize; } else { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::write() Data fitted exactly in dataBuffer!" << std::endl; #endif inSize = 0; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } int TcpStream::read(char *dta, int size) /* net -> pkt -> read */ { tcpMtx.lock(); /********** LOCK MUTEX *********/ #ifdef DEBUG_TCP_STREAM_EXTRA static uint32 TMPtotalread = 0; #endif /* max available data is * outDataRead + outQueue + outDataNet */ int maxread = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; int ret = 1; /* used only for initial errors */ if (state == TCP_CLOSED) { errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; ret = -1; } else if ((!inStreamActive) && (maxread == 0)) { // finished stream. ret = 0; } else if (maxread == 0) { /* must wait for more data */ errorState = EAGAIN; ret = -1; } if (ret < 1) /* if ret has been changed */ { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return ret; } if (maxread < size) { #ifdef TCP_NO_PARTIAL_READ if (inStreamActive) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::read() No Partial Read! "; std::cerr << "Can only supply " << maxread << " of "; std::cerr << size; std::cerr << std::endl; #endif errorState = EAGAIN; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return -1; } #endif /* TCP_NO_PARTIAL_READ */ size = maxread; } /* if less than outDataRead size */ if (((unsigned) (size) < outSizeRead) && (outSizeRead)) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Add Itty Bit" << std::endl; std::cerr << "TcpStream::read() outSizeRead: " << outSizeRead; std::cerr << " size: " << size << " remaining: " << outSizeRead - size; std::cerr << std::endl; #endif memcpy(dta,(void *) outDataRead, size); memmove((void *) outDataRead, (void *) &(outDataRead[size]), outSizeRead - (size)); outSizeRead -= size; #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef DEBUG_TCP_STREAM_EXTRA checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } /* move the whole of outDataRead. */ if (outSizeRead) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Move All outSizeRead" << std::endl; std::cerr << "TcpStream::read() outSizeRead: " << outSizeRead; std::cerr << " size: " << size; std::cerr << std::endl; #endif memcpy(dta,(void *) outDataRead, outSizeRead); } int remSize = size - outSizeRead; outSizeRead = 0; #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() remaining size: " << remSize << std::endl; #endif while((outQueue.size() > 0) && (remSize > 0)) { dataBuffer *db = outQueue.front(); outQueue.pop_front(); /* remove */ #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Taking Data from outQueue" << std::endl; #endif /* load into outDataRead */ if (remSize < MAX_SEG) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Partially using Segment" << std::endl; std::cerr << "TcpStream::read() moving: " << remSize << " to dta @: " << size-remSize; std::cerr << std::endl; std::cerr << "TcpStream::read() rest to outDataRead: " << MAX_SEG - remSize; std::cerr << std::endl; #endif memcpy((void *) &(dta[(size)-remSize]), (void *) db->data, remSize); memcpy((void *) outDataRead, (void *) &(db->data[remSize]), MAX_SEG - remSize); outSizeRead = MAX_SEG - remSize; delete db; #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef DEBUG_TCP_STREAM_EXTRA checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Move Whole Segment to dta @ " << size-remSize << std::endl; #endif /* else copy whole segment */ memcpy((void *) &(dta[(size)-remSize]), (void *) db->data, MAX_SEG); remSize -= MAX_SEG; delete db; } /* assumes that outSizeNet >= remSize due to initial * constraint */ if ((remSize > 0)) { #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() Using up : " << remSize; std::cerr << " last Bytes, leaving: " << outSizeNet - remSize << std::endl; #endif memcpy((void *) &(dta[(size)-remSize]),(void *) outDataNet, remSize); outSizeNet -= remSize; if (outSizeNet > 0) { /* move to the outDataRead */ memcpy((void *) outDataRead,(void *) &(outDataNet[remSize]), outSizeNet); outSizeRead = outSizeNet; outSizeNet = 0; #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() moving last of outSizeNet to outSizeRead: " << outSizeRead; std::cerr << std::endl; #endif } #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef DEBUG_TCP_STREAM_EXTRA checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } #ifdef DEBUG_TCP_STREAM_EXTRA std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef DEBUG_TCP_STREAM_EXTRA checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return size; } /* Callback from lower Layers */ void TcpStream::recvPkt(void *data, int size) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recvPkt()"; std::cerr << std::endl; #endif tcpMtx.lock(); /********** LOCK MUTEX *********/ uint8 *input = (uint8 *) data; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recvPkt() Past Lock!"; std::cerr << std::endl; #endif #ifdef DEBUG_TCP_STREAM if (state > TCP_SYN_RCVD) { int availRead = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; std::cerr << "TcpStream::recvPkt() CC: "; std::cerr << " iWS: " << inWinSize; std::cerr << " aRead: " << availRead; std::cerr << " iAck: " << inAckno; std::cerr << std::endl; } else { std::cerr << "TcpStream::recv() Not Connected"; std::cerr << std::endl; } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recv() ReadPkt(" << size << ")" << std::endl; //std::cerr << printPkt(input, size); //std::cerr << std::endl; #endif TcpPacket *pkt = new TcpPacket(); if (0 < pkt -> readPacket(input, size)) { lastIncomingPkt = getCurrentTS(); handleIncoming(pkt); } else { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recv() Bad Packet Deleting!"; std::cerr << std::endl; #endif delete pkt; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return; } int TcpStream::tick() { tcpMtx.lock(); /********** LOCK MUTEX *********/ //std::cerr << "TcpStream::tick()" << std::endl; recv_check(); /* recv is async */ send(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 1; } bool TcpStream::getRemoteAddress(struct sockaddr_in &raddr) { tcpMtx.lock(); /********** LOCK MUTEX *********/ if (peerKnown) { raddr = peeraddr; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return peerKnown; } uint8 TcpStream::TcpState() { tcpMtx.lock(); /********** LOCK MUTEX *********/ uint8 err = state; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return err; } int TcpStream::TcpErrorState() { tcpMtx.lock(); /********** LOCK MUTEX *********/ int err = errorState; tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return err; } /********************* SOME EXPOSED DEBUGGING FNS ******************/ static int ilevel = 100; bool TcpStream::widle() { tcpMtx.lock(); /********** LOCK MUTEX *********/ /* init */ if (!lastWriteTF) { lastWriteTF = int_wbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } if ((lastWriteTF == int_wbytes()) && (inSize == 0) && inQueue.empty()) { wcount++; if (wcount > ilevel) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return true; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } wcount = 0; lastWriteTF = int_wbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } bool TcpStream::ridle() { tcpMtx.lock(); /********** LOCK MUTEX *********/ /* init */ if (!lastReadTF) { lastReadTF = int_rbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } if ((lastReadTF == int_rbytes()) && (outSizeRead + outQueue.size() + outSizeNet== 0)) { rcount++; if (rcount > ilevel) { tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return true; } tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } rcount = 0; lastReadTF = int_rbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return false; } uint32 TcpStream::wbytes() { tcpMtx.lock(); /********** LOCK MUTEX *********/ uint32 wb = int_wbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return wb; } uint32 TcpStream::rbytes() { tcpMtx.lock(); /********** LOCK MUTEX *********/ uint32 rb = int_rbytes(); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return rb; } /********************* ALL BELOW HERE IS INTERNAL ****************** ******************* AND ALWAYS PROTECTED BY A MUTEX ***************/ int TcpStream::recv_check() { double cts = getCurrentTS(); // fractional seconds. #ifdef DEBUG_TCP_STREAM if (state > TCP_SYN_RCVD) { int availRead = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; std::cerr << "TcpStream::recv_check() CC: "; std::cerr << " iWS: " << inWinSize; std::cerr << " aRead: " << availRead; std::cerr << " iAck: " << inAckno; std::cerr << std::endl; } else { std::cerr << "TcpStream::recv_check() Not Connected"; std::cerr << std::endl; } #endif // make sure we've rcvd something! if ((state > TCP_SYN_RCVD) && (cts - lastIncomingPkt > kNoPktTimeout)) { /* shut it all down */ /* this period should be equivalent * to the firewall timeouts ??? * * for max efficiency */ #ifdef DEBUG_TCP_STREAM_CLOSE std::cerr << "TcpStream::recv_check() state = CLOSED (NoPktTimeout)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (kNoPktTimeout)"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; cleanup(); } return 1; } int TcpStream::cleanup() { // This shuts it all down! no matter what. rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::cleanup() state = TCP_CLOSED"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_CLOSED" << std::endl; #endif //peerKnown = false; //??? NOT SURE -> for a rapid reconnetion this might be key?? /* reset TTL */ setTTL(TCP_STD_TTL); // clear arrays. inSize = 0; while(inQueue.size() > 0) { dataBuffer *db = inQueue.front(); inQueue.pop_front(); delete db; } while(outPkt.size() > 0) { TcpPacket *pkt = outPkt.front(); outPkt.pop_front(); delete pkt; } // clear arrays. outSizeRead = 0; outSizeNet = 0; while(outQueue.size() > 0) { dataBuffer *db = outQueue.front(); outQueue.pop_front(); delete db; } while(inPkt.size() > 0) { TcpPacket *pkt = inPkt.front(); inPkt.pop_front(); delete pkt; } return 1; } int TcpStream::handleIncoming(TcpPacket *pkt) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::handleIncoming()" << std::endl; #endif switch(state) { case TCP_CLOSED: case TCP_LISTEN: /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * else Discard. */ return incoming_Closed(pkt); break; case TCP_SYN_SENT: /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * if receive SYN+ACK * -> respond ACK * To State: TCP_ESTABLISHED * * else Discard. */ return incoming_SynSent(pkt); break; case TCP_SYN_RCVD: /* if receive ACK * To State: TCP_ESTABLISHED */ return incoming_SynRcvd(pkt); break; case TCP_ESTABLISHED: /* if receive FIN * -> respond ACK * To State: TCP_CLOSE_WAIT * else Discard. */ return incoming_Established(pkt); break; case TCP_FIN_WAIT_1: /* state entered by close() call. * if receive FIN * -> respond ACK * To State: TCP_CLOSING * * if receive ACK * -> no response * To State: TCP_FIN_WAIT_2 * * if receive FIN+ACK * -> respond ACK * To State: TCP_TIMED_WAIT * */ return incoming_Established(pkt); //return incoming_FinWait1(pkt); break; case TCP_FIN_WAIT_2: /* if receive FIN * -> respond ACK * To State: TCP_TIMED_WAIT */ return incoming_Established(pkt); //return incoming_FinWait2(pkt); break; case TCP_CLOSING: /* if receive ACK * To State: TCP_TIMED_WAIT */ /* all handled in Established */ return incoming_Established(pkt); //return incoming_Closing(pkt); break; case TCP_CLOSE_WAIT: /* * wait for our close to be called. */ /* all handled in Established */ return incoming_Established(pkt); //return incoming_CloseWait(pkt); break; case TCP_LAST_ACK: /* entered by the local close() after sending FIN. * if receive ACK * To State: TCP_CLOSED */ /* all handled in Established */ return incoming_Established(pkt); /* return incoming_LastAck(pkt); */ break; /* this is actually the only * final state where packets not expected! */ case TCP_TIMED_WAIT: /* State: TCP_TIMED_WAIT * * discard all -> both connections FINed * timeout of this state. * */ #ifdef DEBUG_TCP_STREAM_CLOSE std::cerr << "TcpStream::handleIncoming() state = CLOSED (TimedWait)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif state = TCP_CLOSED; // return incoming_TimedWait(pkt); { rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (recvd TCP_TIMED_WAIT?)"); } break; } delete pkt; return 1; } int TcpStream::incoming_Closed(TcpPacket *pkt) { /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * else Discard. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Closed()" << std::endl; #endif if ((pkt -> hasSyn()) && (!pkt -> hasAck())) { /* Init Connection */ /* save seqno */ initPeerSeqno = pkt -> seqno; inAckno = initPeerSeqno + 1; outWinSize = pkt -> winsize; inWinSize = maxWinSize; /* we can get from SynSent as well, * but only send one SYN packet */ /* start packet */ TcpPacket *rsp = new TcpPacket(); if (state == TCP_CLOSED) { outSeqno = genSequenceNo(); initOurSeqno = outSeqno; outAcked = outSeqno; /* min - 1 expected */ /* setup Congestion Charging */ congestThreshold = TCP_MAX_WIN; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; rsp -> setSyn(); } rsp -> setAck(inAckno); /* seq + winsize set in toSend() */ /* as we have received something ... we can up the TTL */ setTTL(TCP_STD_TTL); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Closed() Sending reply" << std::endl; std::cerr << "SeqNo: " << rsp->seqno << " Ack: " << rsp->ackno; std::cerr << std::endl; #endif toSend(rsp); /* change state */ state = TCP_SYN_RCVD; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_SYN_RCVD" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_SYN_RECVD (recvd SYN & !ACK)"); } delete pkt; return 1; } int TcpStream::incoming_SynSent(TcpPacket *pkt) { /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * if receive SYN+ACK * -> respond ACK * To State: TCP_ESTABLISHED * * else Discard. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynSent()" << std::endl; #endif if ((pkt -> hasSyn()) && (pkt -> hasAck())) { /* check stuff */ if (pkt -> getAck() != outSeqno) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynSent() Bad Ack - Deleting " << std::endl; #endif /* bad ignore */ delete pkt; return -1; } /* Complete Connection */ /* save seqno */ initPeerSeqno = pkt -> seqno; inAckno = initPeerSeqno + 1; outWinSize = pkt -> winsize; outAcked = pkt -> getAck(); /* before ACK, reset the TTL * As they have sent something, and we have received * through the firewall, set to STD. */ setTTL(TCP_STD_TTL); /* ack the Syn Packet */ sendAck(); /* change state */ state = TCP_ESTABLISHED; outStreamActive = true; inStreamActive = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_ESTABLISHED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_ESTABLISHED (recvd SUN & ACK)"); delete pkt; } else /* same as if closed! (simultaneous open) */ { return incoming_Closed(pkt); } return 1; } int TcpStream::incoming_SynRcvd(TcpPacket *pkt) { /* if receive ACK * To State: TCP_ESTABLISHED */ if (pkt -> hasRst()) { /* trouble */ state = TCP_CLOSED; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_CLOSED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (recvd RST)"); delete pkt; return 1; } bool ackWithData = false; if (pkt -> hasAck()) { if (pkt -> hasSyn()) { /* has resent syn -> check it matches */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Pkt with ACK + SYN" << std::endl; #endif } /* check stuff */ if (pkt -> getAck() != outSeqno) { /* bad ignore */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Ignoring Pkt with bad ACK" << std::endl; #endif delete pkt; return -1; } /* Complete Connection */ /* save seqno */ if (pkt -> datasize > 0) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynRcvd() ACK with Data!" << std::endl; std::cerr << "TcpStream::incoming_SynRcvd() Shoudn't recv ... unless initACK lost!" << std::endl; #endif // managed to trigger this under windows... // perhaps the initial Ack was lost, // believe we should just pass this packet // directly to the incoming_Established... once // the following has been done. // and it should all work! //exit(1); ackWithData = true; } inAckno = pkt -> seqno; /* + pkt -> datasize; */ outWinSize = pkt -> winsize; outAcked = pkt -> getAck(); /* As they have sent something, and we have received * through the firewall, set to STD. */ setTTL(TCP_STD_TTL); /* change state */ state = TCP_ESTABLISHED; outStreamActive = true; inStreamActive = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_ESTABLISHED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_ESTABLISHED (have SYN, recvd ACK)"); } if (ackWithData) { /* connection Established -> handle normally */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Handling Data with Ack Pkt!"; std::cerr << std::endl; #endif incoming_Established(pkt); } else { #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Ignoring Pkt!" << std::endl; #endif /* else nothing */ delete pkt; } return 1; } int TcpStream::incoming_Established(TcpPacket *pkt) { /* first handle the Ack ... * this must be done before the queue, * to keep the values as up-to-date as possible. * * must sanity check ..... * make sure that the sequence number is within the correct range. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Established() "; std::cerr << " Pkt->seqno: " << std::hex << pkt->seqno; std::cerr << " Pkt->datasize: " << std::hex << pkt->datasize; std::cerr << std::dec << std::endl; #endif if ((!isOldSequence(pkt->seqno, inAckno)) && // seq >= inAckno isOldSequence(pkt->seqno, inAckno + maxWinSize)) // seq < inAckno + maxWinSize. { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Established() valid Packet Seqno."; std::cerr << std::endl; #endif if (pkt->hasAck()) { #ifdef DEBUG_TCP_STREAM if (outAcked != pkt->ackno) { std::cerr << "TcpStream::incoming_Established() valid Packet Seqno & new Ackno."; std::cerr << std::endl; std::cerr << "\tUpdating OutAcked to: " << outAcked; std::cerr << std::endl; } #endif outAcked = pkt->ackno; } outWinSize = pkt->winsize; #ifdef DEBUG_TCP_STREAM std::cerr << "\tUpdating OutWinSize to: " << outWinSize; std::cerr << std::endl; #endif } else { /* what we do! (This is actually okay - and happens occasionally) */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Established() ERROR out-of-range Packet Seqno."; std::cerr << std::endl; std::cerr << "\t Pkt->SeqNo: " << std::hex << pkt->seqno; std::cerr << std::endl; std::cerr << "\t inAckno: " << std::hex << inAckno; std::cerr << std::endl; std::cerr << "\t inAckno + maxWinSize: " << std::hex << inAckno + maxWinSize; std::cerr << std::endl; std::cerr << "\t outAcked: " << std::hex << outAcked; std::cerr << std::endl; std::cerr << "\t Pkt->SeqNo: " << std::hex << pkt->seqno; std::cerr << std::dec << std::endl; std::cerr << "\t !isOldSequence(pkt->seqno, inAckno): " << (!isOldSequence(pkt->seqno, inAckno)); std::cerr << std::endl; std::cerr << "\t isOldSequence(pkt->seqno, inAckno + maxWinSize): " << isOldSequence(pkt->seqno, inAckno + maxWinSize); std::cerr << std::endl; std::cerr << std::endl; std::cerr << "TcpStream::incoming_Established() Sending Ack to update Peer"; std::cerr << std::endl; #endif sendAck(); } /* add to queue */ inPkt.push_back(pkt); if (inPkt.size() > kMaxQueueSize) { TcpPacket *pkt = inPkt.front(); inPkt.pop_front(); delete pkt; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Established() inPkt reached max size...Discarding Oldest Pkt"; std::cerr << std::endl; #endif } /* use as many packets as possible */ return check_InPkts(); } int TcpStream::check_InPkts() { bool found = true; TcpPacket *pkt; std::list<TcpPacket *>::iterator it; while(found) { found = false; for(it = inPkt.begin(); (!found) && (it != inPkt.end());) { #ifdef DEBUG_TCP_STREAM std::cerr << "Checking expInAck: " << std::hex << inAckno; std::cerr << " vs: " << std::hex << (*it)->seqno << std::dec << std::endl; #endif pkt = *it; if ((*it)->seqno == inAckno) { //std::cerr << "\tFOUND MATCH!"; //std::cerr << std::endl; found = true; it = inPkt.erase(it); } /* see if we can discard it */ /* if smaller seqno, and not wrapping around */ else if (isOldSequence((*it)->seqno, inAckno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "Discarding Old Packet expAck: " << std::hex << inAckno; std::cerr << " seqno: " << std::hex << (*it)->seqno; std::cerr << " pkt->size: " << std::hex << (*it)->datasize; std::cerr << " pkt->seqno+size: " << std::hex << (*it)->seqno + (*it)->datasize; std::cerr << std::dec << std::endl; #endif /* discard */ it = inPkt.erase(it); delete pkt; } else { ++it; } } if (found) { #ifdef DEBUG_TCP_STREAM_EXTRA if (pkt->datasize) { checkData(pkt->data, pkt->datasize, pkt->seqno-initPeerSeqno-1); } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() Updating inAckno from: " << std::hex << inAckno; #endif /* update ack number - let it rollover */ inAckno = pkt->seqno + pkt->datasize; #ifdef DEBUG_TCP_STREAM std::cerr << " to: " << std::hex << inAckno; std::cerr << std::dec << std::endl; #endif /* XXX This shouldn't be here, as it prevents * the Ack being used until the packet is. * This means that a dropped packet will stop traffic in both * directions.... * * Moved it to incoming_Established .... but extra * check here to be sure! */ if (pkt->hasAck()) { if (isOldSequence(outAcked, pkt->ackno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() ERROR Ack Not Already Used!"; std::cerr << std::endl; std::cerr << "\t Pkt->ackno: " << std::hex << pkt->ackno; std::cerr << std::endl; std::cerr << "\t outAcked: " << std::hex << outAcked; std::cerr << std::endl; std::cerr << "\t Pkt->winsize: " << std::hex << pkt->winsize; std::cerr << std::endl; std::cerr << "\t outWinSize: " << std::hex << outWinSize; std::cerr << std::endl; std::cerr << "\t isOldSequence(outAcked, pkt->ackno): " << isOldSequence(outAcked, pkt->ackno); std::cerr << std::endl; std::cerr << std::endl; #endif outAcked = pkt->ackno; outWinSize = pkt->winsize; #ifdef DEBUG_TCP_STREAM std::cerr << "\tUpdating OutAcked to: " << outAcked; std::cerr << std::endl; std::cerr << "\tUpdating OutWinSize to: " << outWinSize; std::cerr << std::endl; #endif } else { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() GOOD Ack Already Used!"; std::cerr << std::endl; #endif } } /* push onto queue */ if (outSizeNet + pkt->datasize < MAX_SEG) { /* move onto outSizeNet */ if (pkt->datasize) { memcpy((void *) &(outDataNet[outSizeNet]), pkt->data, pkt->datasize); outSizeNet += pkt->datasize; } } else { /* if it'll overflow the buffer. */ dataBuffer *db = new dataBuffer(); /* move outDatNet -> buffer */ memcpy((void *) db->data, (void *) outDataNet, outSizeNet); /* fill rest of space */ int remSpace = MAX_SEG - outSizeNet; memcpy((void *) &(db->data[outSizeNet]), (void *) pkt->data, remSpace); /* push packet onto queue */ outQueue.push_back(db); /* any big chunks that will take up a full dataBuffer */ int remData = pkt->datasize - remSpace; while(remData >= MAX_SEG) { db = new dataBuffer(); memcpy((void *) db->data, (void *) &(pkt->data[remSpace]), MAX_SEG); remData -= MAX_SEG; outQueue.push_back(db); } /* remove any remaining to outDataNet */ outSizeNet = remData; if (outSizeNet > 0) { memcpy((void *) outDataNet, (void *) &(pkt->data[pkt->datasize - remData]), outSizeNet); } } /* can allow more in! - update inWinSize */ UpdateInWinSize(); /* if pkt is FIN */ /* these must be here -> at the end of the reliable stream */ /* if the fin is set, ack it specially close stream */ if (pkt->hasFin()) { /* send final ack */ sendAck(); /* closedown stream */ inStreamActive = false; if (state == TCP_ESTABLISHED) { state = TCP_CLOSE_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_CLOSE_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSE_WAIT (recvd FIN)"); } else if (state == TCP_FIN_WAIT_1) { state = TCP_CLOSING; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_CLOSING"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSING (FIN_WAIT_1, recvd FIN)"); } else if (state == TCP_FIN_WAIT_2) { state = TCP_TIMED_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_TIMED_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_TIMED_WAIT (FIN_WAIT_2, recvd FIN)"); cleanup(); } } /* if ack for our FIN */ if ((pkt->hasAck()) && (!outStreamActive) && (pkt->ackno == outSeqno)) { if (state == TCP_FIN_WAIT_1) { state = TCP_FIN_WAIT_2; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_FIN_WAIT_2"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_FIN_WAIT_2 (FIN_WAIT_1, recvd ACK)"); } else if (state == TCP_LAST_ACK) { #ifdef DEBUG_TCP_STREAM_CLOSE std::cerr << "TcpStream::state = TCP_CLOSED (LastAck)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif state = TCP_CLOSED; rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (LAST_ACK, recvd ACK)"); cleanup(); } else if (state == TCP_CLOSING) { state = TCP_TIMED_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_TIMED_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_TIMED_WAIT (TCP_CLOSING, recvd ACK)"); cleanup(); } } delete pkt; } /* end of found */ } /* while(found) */ return 1; } /* This Fn should be called after each read, or recvd data (thats added to the buffer) */ int TcpStream::UpdateInWinSize() { /* InWinSize = maxWinSze - QueuedData, * actually we can allow a lot more to queue up... * inWinSize = 65536, unless QueuedData > 65536. * inWinSize = 2 * maxWinSize - QueuedData; * */ uint32 queuedData = int_read_pending(); if (queuedData < maxWinSize) { inWinSize = maxWinSize; } else if (queuedData < 2 * maxWinSize) { inWinSize = 2 * maxWinSize - queuedData; } else { inWinSize = 0; } return inWinSize; } int TcpStream::sendAck() { /* simple -> toSend fills in ack/winsize * and the rest is history */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::sendAck()"; std::cerr << std::endl; #endif return toSend(new TcpPacket(), false); } void TcpStream::setRemoteAddress(const struct sockaddr_in &raddr) { peeraddr = raddr; peerKnown = true; } int TcpStream::toSend(TcpPacket *pkt, bool retrans) { int outPktSize = MAX_SEG + TCP_PSEUDO_HDR_SIZE; char tmpOutPkt[outPktSize]; if (!peerKnown) { /* Major Error! */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() peerUnknown ERROR!!!"; std::cerr << std::endl; #endif delete pkt; return 0; } /* get accurate timestamp */ double cts = getCurrentTS(); pkt -> winsize = inWinSize; pkt -> seqno = outSeqno; /* increment seq no */ if (pkt->datasize) { #ifdef DEBUG_TCP_STREAM_EXTRA checkData(pkt->data, pkt->datasize, outSeqno-initOurSeqno-1); #endif outSeqno += pkt->datasize; } if (pkt->hasSyn()) { /* should not have data! */ if (pkt->datasize) { #ifdef DEBUG_TCP_STREAM std::cerr << "SYN Packet shouldn't contain data!" << std::endl; #endif } outSeqno++; } else { /* cannot auto Ack SynPackets */ pkt -> setAck(inAckno); } pkt -> winsize = inWinSize; /* store old info */ lastSentAck = pkt -> ackno; lastSentWinSize = pkt -> winsize; keepAliveTimer = cts; pkt -> writePacket(tmpOutPkt, outPktSize); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << " Ackno: "; std::cerr << pkt->ackno << " winsize: " << pkt->winsize; std::cerr << std::endl; //std::cerr << printPkt(tmpOutPkt, outPktSize) << std::endl; #endif udp -> sendPkt(tmpOutPkt, outPktSize, peeraddr, ttl); if (retrans) { /* restart timers */ pkt -> ts = cts; pkt -> retrans = 0; startRetransmitTimer(); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() Adding to outPkt --> Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif outPkt.push_back(pkt); } else { delete pkt; } return 1; } /* single retransmit timer. * */ void TcpStream::startRetransmitTimer() { if (retransTimerOn) { return; } retransTimerTs = getCurrentTS(); retransTimerOn = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::startRetransmitTimer() peer: " << peeraddr; std::cerr << " retransTimeout: " << retransTimeout; std::cerr << " retransTimerTs: " << std::setprecision(12) <<retransTimerTs; std::cerr << std::endl; #endif } void TcpStream::restartRetransmitTimer() { stopRetransmitTimer(); startRetransmitTimer(); } void TcpStream::stopRetransmitTimer() { if (!retransTimerOn) { return; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::stopRetransmitTimer() peer: " << peeraddr; std::cerr << std::endl; #endif retransTimerOn = false; } void TcpStream::resetRetransmitTimer() { retransTimerOn = false; retransTimeout = 2.0 * (rtt_est + 4.0 * rtt_dev); // happens too often for RETRANS debugging. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::resetRetransmitTimer() peer: " << peeraddr; std::cerr << " retransTimeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; #endif } void TcpStream::incRetransmitTimeout() { retransTimeout = 2 * retransTimeout; if (retransTimeout > TCP_RETRANS_MAX_TIMEOUT) { retransTimeout = TCP_RETRANS_MAX_TIMEOUT; } #ifdef DEBUG_TCP_STREAM_RETRANS std::cerr << "TcpStream::incRetransmitTimer() peer: " << peeraddr; std::cerr << " retransTimeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; #endif } int TcpStream::retrans() { int outPktSize = MAX_SEG + TCP_PSEUDO_HDR_SIZE; char tmpOutPkt[outPktSize]; if (!peerKnown) { /* Major Error! */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::retrans() peerUnknown ERROR!!!"; std::cerr << std::endl; #endif return 0; } if (!retransTimerOn) { return 0; } double cts = getCurrentTS(); if (cts - retransTimerTs < retransTimeout) { return 0; } if (outPkt.begin() == outPkt.end()) { resetRetransmitTimer(); return 0; } TcpPacket *pkt = outPkt.front(); if (!pkt) { /* error */ return 0; } /* retransmission -> adjust the congestWinSize and congestThreshold */ congestThreshold = congestWinSize / 2; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; // point when we can up the winSize. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::retrans() Adjusting Congestion Parameters: "; std::cerr << std::endl; std::cerr << "\tcongestWinSize: " << congestWinSize; std::cerr << " congestThreshold: " << congestThreshold; std::cerr << " congestUpdate: " << congestUpdate; std::cerr << std::endl; #endif /* update ackno and winsize */ if (!(pkt->hasSyn())) { pkt->setAck(inAckno); lastSentAck = pkt -> ackno; } pkt->winsize = inWinSize; lastSentWinSize = pkt -> winsize; keepAliveTimer = cts; pkt->writePacket(tmpOutPkt, outPktSize); #ifdef DEBUG_TCP_STREAM_RETRANS std::cerr << "TcpStream::retrans()"; std::cerr << " peer: " << peeraddr; std::cerr << " hasSyn: " << pkt->hasSyn(); std::cerr << " Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << " Ackno: "; std::cerr << pkt->ackno << " winsize: " << pkt->winsize; std::cerr << " retrans: " << (int) pkt->retrans; std::cerr << " timeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; //std::cerr << printPkt(tmpOutPkt, outPktSize) << std::endl; #endif /* if its a syn packet ** thats been * transmitting for a while, maybe * we should increase the ttl. */ if ((pkt->hasSyn()) && (getTTL() < TCP_STD_TTL)) { /* calculate a new TTL */ if (mTTL_end > cts) { setTTL(TCP_DEFAULT_FIREWALL_TTL); } else { setTTL(getTTL() + 1); } std::string out; rs_sprintf(out, "TcpStream::retrans() Startup SYNs retrans count: %u New TTL: %d", pkt->retrans, getTTL()); rslog(RSL_WARNING, rstcpstreamzone, out); #ifdef DEBUG_TCP_STREAM std::cerr << out.str() << std::endl; #endif } /* catch excessive retransmits * - Allow Syn case more.... * - if not SYN or TTL has reached STD then timeout quickly. * OLD 2nd Logic (below) has been replaced with lower logic. * (((!pkt->hasSyn()) || (TCP_STD_TTL == getTTL())) * && (pkt->retrans > kMaxPktRetransmit))) * Problem was that the retransmit of Syn packet had STD_TTL, and was triggering Close (and SeqNo change). * It seemed to work anyway.... But might cause coonnection failures. Will reduce the MaxSyn Retransmit * so something more reasonable as well. * ((!pkt->hasSyn()) && (pkt->retrans > kMaxPktRetransmit))) */ if ((pkt->hasSyn() && (pkt->retrans > kMaxSynPktRetransmit)) || ((!pkt->hasSyn()) && (pkt->retrans > kMaxPktRetransmit))) { /* too many attempts close stream */ #ifdef DEBUG_TCP_STREAM_CLOSE std::cerr << "TcpStream::retrans() Too many Retransmission Attempts ("; std::cerr << (int) pkt->retrans << ") for Peer: " << peeraddr << std::endl; std::cerr << "TcpStream::retrans() Closing Socket Connection"; std::cerr << std::endl; //dumpPacket(std::cerr, (unsigned char *) tmpOutPkt, outPktSize); dumpstate_locked(std::cerr); #endif rslog(RSL_WARNING,rstcpstreamzone,"TcpStream::state => TCP_CLOSED (Too Many Retransmits)"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; cleanup(); return 0; } udp -> sendPkt(tmpOutPkt, outPktSize, peeraddr, ttl); /* restart timers */ pkt->ts = cts; pkt->retrans++; /* * finally - double the retransTimeout ... (Karn's Algorithm) * except if we are starting a connection... i.e. hasSyn() */ if (!pkt->hasSyn()) { incRetransmitTimeout(); restartRetransmitTimer(); } else { resetRetransmitTimer(); startRetransmitTimer(); } return 1; } void TcpStream::acknowledge() { /* cleans up acknowledge packets */ /* packets are pushed back in order */ std::list<TcpPacket *>::iterator it; double cts = getCurrentTS(); bool updateRTT = true; bool clearedPkts = false; for(it = outPkt.begin(); (it != outPkt.end()) && (isOldSequence((*it)->seqno, outAcked)); it = outPkt.erase(it)) { TcpPacket *pkt = (*it); clearedPkts = true; /* adjust the congestWinSize and congestThreshold * congestUpdate <= outAcked * ***/ if (!isOldSequence(outAcked, congestUpdate)) { if (congestWinSize < congestThreshold) { /* double it baby! */ congestWinSize *= 2; } else { /* linear increase */ congestWinSize += MAX_SEG; } if (congestWinSize > maxWinSize) { congestWinSize = maxWinSize; } congestUpdate = outAcked + congestWinSize; // point when we can up the winSize. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Adjusting Congestion Parameters: "; std::cerr << std::endl; std::cerr << "\tcongestWinSize: " << congestWinSize; std::cerr << " congestThreshold: " << congestThreshold; std::cerr << " congestUpdate: " << congestUpdate; std::cerr << std::endl; #endif } /* update the RoundTripTime, * using Jacobson's values. * RTT = a RTT + (1-a) M * where * RTT is RoundTripTime estimate. * a = 7/8, * M = time for ack. * * D = a D + (1 - a) | RTT - M | * where * D is approx Deviation. * a,RTT & M are the same as above. * * Timeout = RTT + 4 * D. * * And Karn's Algorithm... * which says * (1) do not update RTT or D for retransmitted packets. * + the ones that follow .... (the ones whos ack was * delayed by the retranmission) * (2) double timeout, when packets fail. (done in retrans). */ if (pkt->retrans) { updateRTT = false; } if (updateRTT) /* can use for RTT calc */ { double ack_time = cts - pkt->ts; rtt_est = RTT_ALPHA * rtt_est + (1.0 - RTT_ALPHA) * ack_time; rtt_dev = RTT_ALPHA * rtt_dev + (1.0 - RTT_ALPHA) * fabs(rtt_est - ack_time); retransTimeout = rtt_est + 4.0 * rtt_dev; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Updating RTT: "; std::cerr << std::endl; std::cerr << "\tAckTime: " << ack_time; std::cerr << std::endl; std::cerr << "\tRRT_est: " << rtt_est; std::cerr << std::endl; std::cerr << "\tRTT_dev: " << rtt_dev; std::cerr << std::endl; std::cerr << "\tTimeout: " << retransTimeout; std::cerr << std::endl; #endif } #ifdef DEBUG_TCP_STREAM else { std::cerr << "TcpStream::acknowledge() Not Updating RTT for retransmitted Pkt Sequence"; std::cerr << std::endl; } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Removing Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif delete pkt; } /* This is triggered if we have recieved acks for retransmitted packets.... * In this case we want to reset the timeout, and remove the doubling. * * If we don't do this, and there have been more dropped packets, * the the timeout gets continually doubled. which will virtually stop * all communication. * * This will effectively trigger the retransmission of the next dropped packet. */ /* * if have acked all data - resetRetransTimer() */ if (it == outPkt.end()) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() peer: " << peeraddr; std::cerr << " Backlog cleared, resetRetransmitTimer"; std::cerr << std::endl; #endif resetRetransmitTimer(); } else if (clearedPkts) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() peer: " << peeraddr; std::cerr << " Cleared some packets -> resetRetransmitTimer + start"; std::cerr << std::endl; #endif resetRetransmitTimer(); startRetransmitTimer(); } return; } int TcpStream::send() { /* handle network interface always */ /* clean up as much as possible */ acknowledge(); /* send any old packets */ retrans(); if (state < TCP_ESTABLISHED) { return -1; } /* get the inQueue, can send */ /* determine exactly how much we can send */ uint32 maxsend = congestWinSize; uint32 inTransit; if (outWinSize < congestWinSize) { maxsend = outWinSize; } if (outSeqno < outAcked) { inTransit = (TCP_MAX_SEQ - outAcked) + outSeqno; } else { inTransit = outSeqno - outAcked; } if (maxsend > inTransit) { maxsend -= inTransit; } else { maxsend = 0; } #ifdef DEBUG_TCP_STREAM int availSend = inQueue.size() * MAX_SEG + inSize; std::cerr << "TcpStream::send() CC: "; std::cerr << "oWS: " << outWinSize; std::cerr << " cWS: " << congestWinSize; std::cerr << " | inT: " << inTransit; std::cerr << " mSnd: " << maxsend; std::cerr << " aSnd: " << availSend; std::cerr << " | oSeq: " << outSeqno; std::cerr << " oAck: " << outAcked; std::cerr << " cUpd: " << congestUpdate; std::cerr << std::endl; #endif int sent = 0; while((inQueue.size() > 0) && (maxsend >= MAX_SEG)) { dataBuffer *db = inQueue.front(); inQueue.pop_front(); TcpPacket *pkt = new TcpPacket(db->data, MAX_SEG); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Segment ===> Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif sent++; maxsend -= MAX_SEG; toSend(pkt); delete db; } /* if inqueue empty, and enough window space, send partial stuff */ if ((!sent) && (inQueue.empty()) && (maxsend >= inSize) && (inSize)) { TcpPacket *pkt = new TcpPacket(inData, inSize); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Remaining ===>"; std::cerr << std::endl; #endif inSize = 0; sent++; maxsend -= inSize; toSend(pkt); } /* if send nothing */ bool needsAck = false; if (!sent) { double cts = getCurrentTS(); /* if needs ack */ if (isOldSequence(lastSentAck,inAckno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (Ackno)"; std::cerr << std::endl; #endif needsAck = true; } /* if needs window * if added enough space for packet, or * (this case is equivalent to persistence timer) * haven't sent anything for a while, and the * window size has drastically increased. * */ if (((lastSentWinSize < MAX_SEG) && (inWinSize > MAX_SEG)) || ((cts - keepAliveTimer > retransTimeout * 4) && (inWinSize > lastSentWinSize + 4 * MAX_SEG))) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (Window)"; std::cerr << std::endl; #endif needsAck = true; } /* if needs keepalive */ if (cts - keepAliveTimer > keepAliveTimeout) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (KAlive)"; std::cerr << std::endl; #endif needsAck = true; } /* if end of stream -> switch mode -> send fin (with ack) */ if ((!outStreamActive) && (inQueue.size() + inSize == 0) && ((state == TCP_ESTABLISHED) || (state == TCP_CLOSE_WAIT))) { /* finish the stream */ TcpPacket *pkt = new TcpPacket(); pkt -> setFin(); needsAck = false; toSend(pkt, false); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Fin Triggered"; std::cerr << std::endl; #endif if (state == TCP_ESTABLISHED) { state = TCP_FIN_WAIT_1; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_FIN_WAIT_1"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_FIN_WAIT_1 (End of Stream)"); } else if (state == TCP_CLOSE_WAIT) { state = TCP_LAST_ACK; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_LAST_ACK"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_LAST_ACK (CLOSE_WAIT, End of Stream)"); } } if (needsAck) { sendAck(); } #ifdef DEBUG_TCP_STREAM_EXTRA else { std::cerr << "TcpStream::send() No Ack"; std::cerr << std::endl; } #endif } #ifdef DEBUG_TCP_STREAM_EXTRA else { std::cerr << "TcpStream::send() Stuff Sent"; std::cerr << std::endl; } #endif return 1; } uint32 TcpStream::genSequenceNo() { return RSRandom::random_u32(); //return 1000; // TCP_MAX_SEQ - 1000; //1000; //(rand() - 100000) + time(NULL) % 100000; //return (rand() - 100000) + time(NULL) % 100000; } bool TcpStream::isOldSequence(uint32 tst, uint32 curr) { return ((int)((tst)-(curr)) < 0); std::cerr << "TcpStream::isOldSequence(): Case "; /* if tst < curr */ if ((int)((tst)-(curr)) < 0) { if (curr - tst < TCP_MAX_SEQ/2) /* diff less than half span -> old */ { std::cerr << "1T" << std::endl; return true; } std::cerr << "2F" << std::endl; return false; } else if ((tst - curr) > TCP_MAX_SEQ/2) { std::cerr << "3T: tst-curr:" << (tst-curr) << std::endl; return true; } std::cerr << "4F: tst-curr:" << (tst-curr) << std::endl; return false; } #ifdef WINDOWS_SYS #include <time.h> #include <sys/timeb.h> #endif // Little fn to get current timestamp in an independent manner. static double getCurrentTS() { #ifndef WINDOWS_SYS struct timeval cts_tmp; gettimeofday(&cts_tmp, NULL); double cts = (cts_tmp.tv_sec) + ((double) cts_tmp.tv_usec) / 1000000.0; #else struct _timeb timebuf; _ftime( &timebuf); double cts = (timebuf.time) + ((double) timebuf.millitm) / 1000.0; #endif return cts; } uint32 TcpStream::int_wbytes() { return outSeqno - initOurSeqno - 1; } uint32 TcpStream::int_rbytes() { return inAckno - initPeerSeqno - 1; } /********* Special debugging stuff *****/ #ifdef DEBUG_TCP_STREAM_EXTRA #include <stdio.h> static FILE *bc_fd = 0; int setupBinaryCheck(std::string fname) { bc_fd = RsDirUtil::rs_fopen(fname.c_str(), "r"); return 1; } /* uses seq number to track position -> ensure no rollover */ int checkData(uint8 *data, int size, int idx) { if (bc_fd <= 0) { return -1; } std::cerr << "checkData(" << idx << "+" << size << ")"; int tmpsize = size; uint8 tmpdata[tmpsize]; if (-1 == fseek(bc_fd, idx, SEEK_SET)) { std::cerr << "Fseek Issues!" << std::endl; exit(1); return -1; } if (1 != fread(tmpdata, tmpsize, 1, bc_fd)) { std::cerr << "Length Difference!" << std::endl; exit(1); return -1; } for(int i = 0; i < size; i++) { if (data[i] != tmpdata[i]) { std::cerr << "Byte Difference!" << std::endl; exit(1); return -1; } } std::cerr << "OK" << std::endl; return 1; } #endif /***** Dump state of TCP Stream - to workout why it was closed ****/ int TcpStream::dumpstate_locked(std::ostream &out) { out << "TcpStream::dumpstate()"; out << "======================================================="; out << std::endl; out << "state: " << (int) state; out << " errorState: " << (int) errorState; out << std::endl; out << "(Streams) inStreamActive: " << inStreamActive; out << " outStreamActive: " << outStreamActive; out << std::endl; out << "(Timeouts) maxWinSize: " << maxWinSize; out << " keepAliveTimeout: " << keepAliveTimeout; out << " retransTimeout: " << retransTimeout; out << std::endl; out << "(Timers) keepAliveTimer: " << std::setprecision(12) << keepAliveTimer; out << " lastIncomingPkt: " << std::setprecision(12) << lastIncomingPkt; out << std::endl; out << "(Tracking) lastSendAck: " << lastSentAck; out << " lastSendWinSize: " << lastSentWinSize; out << std::endl; out << "(Init) initOutSeqno: " << initOurSeqno; out << " initPeerSeqno: " << initPeerSeqno; out << std::endl; out << "(r/w) lastWriteTF: " << lastWriteTF; out << " lastReadTF: " << lastReadTF; out << " wcount: " << wcount; out << " rcount: " << rcount; out << std::endl; out << "(rtt) rtt_est: " << rtt_est; out << " rtt_dev: " << rtt_dev; out << std::endl; out << "(congestion) congestThreshold: " << congestThreshold; out << " congestWinSize: " << congestWinSize; out << " congestUpdate: " << congestUpdate; out << std::endl; out << "(TTL) mTTL_period: " << mTTL_period; out << " mTTL_start: " << std::setprecision(12) << mTTL_start; out << " mTTL_end: " << std::setprecision(12) << mTTL_end; out << std::endl; out << "(Peer) peerKnown: " << peerKnown; out << " peerAddr: " << peeraddr; out << std::endl; out << "-------------------------------------------------------"; out << std::endl; status_locked(out); out << "======================================================="; out << std::endl; return 1; } int TcpStream::dumpstate(std::ostream &out) { tcpMtx.lock(); /********** LOCK MUTEX *********/ dumpstate_locked(out); tcpMtx.unlock(); /******** UNLOCK MUTEX *********/ return 1; } int dumpPacket(std::ostream &out, unsigned char *pkt, uint32_t size) { uint32_t i; out << "dumpPacket() Size: " << size; out << std::endl; out << "------------------------------------------------------"; for(i = 0; i < size; i++) { if (i % 16 == 0) { out << std::endl; } out << std::hex << std::setfill('0') << std::setw(2) << (int) pkt[i] << ":"; } if ((i - 1) % 16 != 0) { out << std::endl; } out << "------------------------------------------------------"; out << std::dec << std::endl; return 1; }
sehraf/RetroShare
libretroshare/src/tcponudp/tcpstream.cc
C++
gpl-2.0
64,510
<?php /** * Maintenance controller * * @package CSVI * @author Roland Dalmulder * @link http://www.csvimproved.com * @copyright Copyright (C) 2006 - 2013 RolandD Cyber Produksi. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html * @version $Id: maintenance.php 2275 2013-01-03 21:08:43Z RolandD $ */ defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' ); jimport('joomla.application.component.controllerform'); /** * Maintenance Controller * * @package CSVIVirtueMart */ class CsviControllerMaintenance extends JControllerForm { /** * Show the maintenance screen * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.0 */ public function Maintenance() { // Create the view object $view = $this->getView('maintenance', 'html'); // Standard model $view->setModel( $this->getModel( 'maintenance', 'CsviModel' ), true ); // Extra models $view->setModel( $this->getModel( 'log', 'CsviModel' )); $view->setModel( $this->getModel( 'availablefields', 'CsviModel' )); // View if (!JRequest::getBool('cron', false)) { if (JRequest::getInt('run_id') > 0) $view->setLayout('log'); } else $view->setLayout('cron'); // Now display the view $view->display(); } /** * Redirect to the log screen * * @copyright * @author RolandD * @todo * @see * @access private * @param * @return * @since 3.3 */ private function _outputHtml() { $this->setRedirect('index.php?option=com_csvi&task=maintenance.maintenance&run_id='.JRequest::getInt('import_id')); } /** * Handle the cron output * * @copyright * @author RolandD * @todo * @see * @access private * @param * @return * @since 3.3 */ private function _outputCron() { // Create the view object $view = $this->getView('maintenance', 'html'); // Standard model $view->setModel( $this->getModel( 'maintenance', 'CsviModel' ), true ); // Extra models $view->setModel( $this->getModel( 'log', 'CsviModel' )); // View $view->setLayout('cron'); // Now display the view $view->display(); } /** * Update available fields * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function updateAvailableFields() { // Prepare $jinput = JFactory::getApplication()->input; $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Check if we are running a cron job if ($jinput->get('cron', false, 'bool')) { // Pre-configuration $available_fields = $this->getModel('availablefields', 'CsviModel'); $available_fields->prepareAvailableFields(); // Update the available fields $available_fields->getFillAvailableFields(); // Finish $model->getFinishProcess(); // Redirect $this->_outputCron(); } else { // Create the view object $view = $this->getView('maintenance', 'json'); // Pre-configuration $available_fields = $this->getModel('availablefields', 'CsviModel'); $available_fields->prepareAvailableFields(); // View $view->setLayout('availablefields'); // Now display the view $view->display(); } } /** * Update available fields in steps * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function updateAvailableFieldsSingle() { // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('availablefields'); // Load the model $view->setModel($this->getModel('maintenance', 'CsviModel'), true); $view->setModel($this->getModel('availablefields', 'CsviModel')); // Now display the view $view->display(); } /** * Install sample templates * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function installDefaultTemplates() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getInstallDefaultTemplates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Sort categories * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function sortCategories() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getSortCategories(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Remove empty categories * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function removeEmptyCategories() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getRemoveEmptyCategories(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Load the exchange rates * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function exchangeRates() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getExchangeRates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Clean the cache folder * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function cleanTemp() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getCleanTemp(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Backup the CSVI VirtueMart templates * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function backupTemplates() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getBackupTemplates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Restore the CSVI VirtueMart templates * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function restoreTemplates() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getRestoreTemplates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Load the ICEcat index files * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function icecatIndex() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Check if we are running a cron job if (JRequest::getBool('cron', false)) { JRequest::setVar('loadtype', false); } // Perform the task $result = $model->getIcecatIndex(); // See if we need to do the staggered import of the index file switch ($result) { case 'full': // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); break; case 'single': // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('icecat'); // Now display the view $view->display(); break; case 'cancel': // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); break; } } /** * Empty the VirtueMart tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function icecatSingle() { // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('icecat'); // Load the model $view->setModel($this->getModel('maintenance', 'CsviModel'), true); $view->setModel($this->getModel( 'log', 'CsviModel' )); // Now display the view $view->display(); } /** * Optimize the database tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function optimizeTables() { // Prepare $jinput = JFactory::getApplication()->input; $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getOptimizeTables(); // Finish $model->getFinishProcess(); // Redirect if (!$jinput->get('cron', false, 'bool')) $this->_outputHtml(); else $this->_outputCron(); } /** * Backup the VirtueMart tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function backupVm() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getBackupVirtueMart(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Empty the VirtueMart tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function emptyDatabase() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getEmptyDatabase(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Unpublish products in unpublished categories * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.5 */ public function unpublishProductByCategory() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->getUnpublishProductByCategory(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } /** * Cancel the loading of the ICEcat index * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.3 */ public function cancelImport() { // Clean the session $session = JFactory::getSession(); $option = JRequest::getVar('option'); $session->set($option.'.icecat_index_file', serialize('0')); $session->set($option.'.icecat_rows', serialize('0')); $session->set($option.'.icecat_position', serialize('0')); $session->set($option.'.icecat_records', serialize('0')); $session->set($option.'.icecat_wait', serialize('0')); // Redirect back to the maintenance page $this->setRedirect('index.php?option='.JRequest::getCmd('option').'&view=maintenance'); } /** * Delete all CSVI VirtueMart backup tables * * @copyright * @author RolandD * @todo * @see * @access public * @param * @return * @since 3.5 */ public function removeCsviTables() { // Prepare $model = $this->getModel('maintenance'); $model->getPrepareMaintenance(); // Perform the task $model->removeCsviTables(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } } ?>
adrian2020my/vichi
administrator/components/com_csvi/controllers/maintenance.php
PHP
gpl-2.0
12,960
/* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * 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; version 2 * of the License only. * * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.encoders; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.factories.Borders; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import net.pms.Messages; import net.pms.PMS; import net.pms.configuration.DeviceConfiguration; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.*; import net.pms.formats.Format; import net.pms.io.*; import net.pms.newgui.GuiUtil; import net.pms.util.CodecUtil; import net.pms.util.FormLayoutUtil; import net.pms.util.PlayerUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TsMuxeRVideo extends Player { private static final Logger LOGGER = LoggerFactory.getLogger(TsMuxeRVideo.class); private static final String COL_SPEC = "left:pref, 0:grow"; private static final String ROW_SPEC = "p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, 0:grow"; public static final String ID = "tsmuxer"; @Deprecated public TsMuxeRVideo(PmsConfiguration configuration) { this(); } public TsMuxeRVideo() { } @Override public boolean excludeFormat(Format format) { String extension = format.getMatchedExtension(); return extension != null && !extension.equals("mp4") && !extension.equals("mkv") && !extension.equals("ts") && !extension.equals("tp") && !extension.equals("m2ts") && !extension.equals("m2t") && !extension.equals("mpg") && !extension.equals("evo") && !extension.equals("mpeg") && !extension.equals("vob") && !extension.equals("m2v") && !extension.equals("mts") && !extension.equals("mov"); } @Override public int purpose() { return VIDEO_SIMPLEFILE_PLAYER; } @Override public String id() { return ID; } @Override public boolean isTimeSeekable() { return true; } @Override public String[] args() { return null; } @Override public String executable() { return configuration.getTsmuxerPath(); } @Override public ProcessWrapper launchTranscode( DLNAResource dlna, DLNAMediaInfo media, OutputParams params ) throws IOException { // Use device-specific pms conf PmsConfiguration prev = configuration; configuration = (DeviceConfiguration) params.mediaRenderer; final String filename = dlna.getSystemName(); setAudioAndSubs(filename, media, params); PipeIPCProcess ffVideoPipe; ProcessWrapperImpl ffVideo; PipeIPCProcess ffAudioPipe[] = null; ProcessWrapperImpl ffAudio[] = null; String fps = media.getValidFps(false); int width = media.getWidth(); int height = media.getHeight(); if (width < 320 || height < 240) { width = -1; height = -1; } String videoType = "V_MPEG4/ISO/AVC"; if (media.getCodecV() != null && media.getCodecV().startsWith("mpeg2")) { videoType = "V_MPEG-2"; } boolean aacTranscode = false; String[] ffmpegCommands; if (this instanceof TsMuxeRAudio && media.getFirstAudioTrack() != null) { ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "fakevideo", System.currentTimeMillis() + "videoout", false, true); String timeEndValue1 = "-t"; String timeEndValue2 = "" + params.timeend; if (params.timeend < 1) { timeEndValue1 = "-y"; timeEndValue2 = "-y"; } ffmpegCommands = new String[] { configuration.getFfmpegPath(), timeEndValue1, timeEndValue2, "-loop", "1", "-i", "DummyInput.jpg", "-f", "h264", "-c:v", "libx264", "-level", "31", "-tune", "zerolatency", "-pix_fmt", "yuv420p", "-an", "-y", ffVideoPipe.getInputPipe() }; videoType = "V_MPEG4/ISO/AVC"; OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffVideo = new ProcessWrapperImpl(ffmpegCommands, ffparams); if ( filename.toLowerCase().endsWith(".flac") && media.getFirstAudioTrack().getBitsperSample() >= 24 && media.getFirstAudioTrack().getSampleRate() % 48000 == 0 ) { ffAudioPipe = new PipeIPCProcess[1]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "flacaudio", System.currentTimeMillis() + "audioout", false, true); String[] flacCmd = new String[] { configuration.getFlacPath(), "--output-name=" + ffAudioPipe[0].getInputPipe(), "-d", "-f", "-F", filename }; ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffAudio = new ProcessWrapperImpl[1]; ffAudio[0] = new ProcessWrapperImpl(flacCmd, ffparams); } else { ffAudioPipe = new PipeIPCProcess[1]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "mlpaudio", System.currentTimeMillis() + "audioout", false, true); String depth = "pcm_s16le"; String rate = "48000"; if (media.getFirstAudioTrack().getBitsperSample() >= 24) { depth = "pcm_s24le"; } if (media.getFirstAudioTrack().getSampleRate() > 48000) { rate = "" + media.getFirstAudioTrack().getSampleRate(); } String[] flacCmd = new String[] { configuration.getFfmpegPath(), "-i", filename, "-ar", rate, "-f", "wav", "-acodec", depth, "-y", ffAudioPipe[0].getInputPipe() }; ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffAudio = new ProcessWrapperImpl[1]; ffAudio[0] = new ProcessWrapperImpl(flacCmd, ffparams); } } else { params.waitbeforestart = 5000; params.manageFastStart(); ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true); ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-c", "copy", "-f", "rawvideo", "-y", ffVideoPipe.getInputPipe() }; InputFile newInput = new InputFile(); newInput.setFilename(filename); newInput.setPush(params.stdin); /** * Note: This logic is weird; on one hand we check if the renderer requires videos to be Level 4.1 or below, but then * the other function allows the video to exceed those limits. * In reality this won't cause problems since renderers typically don't support above 4.1 anyway - nor are many * videos encoded higher than that either - but it's worth acknowledging the logic discrepancy. */ if (!media.isVideoWithinH264LevelLimits(newInput, params.mediaRenderer) && params.mediaRenderer.isH264Level41Limited()) { LOGGER.info("The video will not play or will show a black screen"); } if (media.getH264AnnexB() != null && media.getH264AnnexB().length > 0) { StreamModifier sm = new StreamModifier(); sm.setHeader(media.getH264AnnexB()); sm.setH264AnnexB(true); ffVideoPipe.setModifier(sm); } OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffVideo = new ProcessWrapperImpl(ffmpegCommands, ffparams); int numAudioTracks = 1; if (media.getAudioTracksList() != null && media.getAudioTracksList().size() > 1 && configuration.isMuxAllAudioTracks()) { numAudioTracks = media.getAudioTracksList().size(); } boolean singleMediaAudio = media.getAudioTracksList().size() <= 1; if (params.aid != null) { boolean ac3Remux; boolean dtsRemux; boolean encodedAudioPassthrough; boolean pcm; if (numAudioTracks <= 1) { ffAudioPipe = new PipeIPCProcess[numAudioTracks]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true); encodedAudioPassthrough = configuration.isEncodedAudioPassthrough() && params.aid.isNonPCMEncodedAudio() && params.mediaRenderer.isWrapEncodedAudioIntoPCM(); ac3Remux = params.aid.isAC3() && configuration.isAudioRemuxAC3() && !encodedAudioPassthrough && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.isAudioEmbedDtsInPcm() && params.aid.isDTS() && params.mediaRenderer.isDTSPlayable() && !encodedAudioPassthrough; pcm = configuration.isAudioUsePCM() && media.isValidForLPCMTranscoding() && ( params.aid.isLossless() || (params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || params.aid.isTrueHD() || ( !configuration.isMencoderUsePcmForHQAudioOnly() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); int channels; if (ac3Remux) { channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux || encodedAudioPassthrough) { channels = 2; } else if (pcm) { channels = params.aid.getAudioProperties().getNumberOfChannels(); } else { channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding } if (!ac3Remux && (dtsRemux || pcm || encodedAudioPassthrough)) { // DTS remux or LPCM StreamModifier sm = new StreamModifier(); sm.setPcm(pcm); sm.setDtsEmbed(dtsRemux); sm.setEncodedAudioPassthrough(encodedAudioPassthrough); sm.setNbChannels(channels); sm.setSampleFrequency(params.aid.getSampleRate() < 48000 ? 48000 : params.aid.getSampleRate()); sm.setBitsPerSample(16); ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + sm.getNbChannels(), "-f", "ac3", "-c:a", sm.isDtsEmbed() || sm.isEncodedAudioPassthrough() ? "copy" : "pcm", "-y", ffAudioPipe[0].getInputPipe() }; // Use PCM trick when media renderer does not support DTS in MPEG if (!params.mediaRenderer.isMuxDTSToMpeg()) { ffAudioPipe[0].setModifier(sm); } } else if (!ac3Remux && params.mediaRenderer.isTranscodeToAAC()) { // AAC audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "adts", "-c:a", "aac", "-strict", "experimental", "-ab", Math.min(configuration.getAudioBitrate(), 320) + "k", "-y", ffAudioPipe[0].getInputPipe() }; aacTranscode = true; } else { // AC-3 audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "ac3", "-c:a", (ac3Remux) ? "copy" : "ac3", "-ab", String.valueOf(CodecUtil.getAC3Bitrate(configuration, params.aid)) + "k", "-y", ffAudioPipe[0].getInputPipe() }; } ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffAudio = new ProcessWrapperImpl[numAudioTracks]; ffAudio[0] = new ProcessWrapperImpl(ffmpegCommands, ffparams); } else { ffAudioPipe = new PipeIPCProcess[numAudioTracks]; ffAudio = new ProcessWrapperImpl[numAudioTracks]; for (int i = 0; i < media.getAudioTracksList().size(); i++) { DLNAMediaAudio audio = media.getAudioTracksList().get(i); ffAudioPipe[i] = new PipeIPCProcess(System.currentTimeMillis() + "ffmpeg" + i, System.currentTimeMillis() + "audioout" + i, false, true); encodedAudioPassthrough = configuration.isEncodedAudioPassthrough() && params.aid.isNonPCMEncodedAudio() && params.mediaRenderer.isWrapEncodedAudioIntoPCM(); ac3Remux = audio.isAC3() && configuration.isAudioRemuxAC3() && !encodedAudioPassthrough && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.isAudioEmbedDtsInPcm() && audio.isDTS() && params.mediaRenderer.isDTSPlayable() && !encodedAudioPassthrough; pcm = configuration.isAudioUsePCM() && media.isValidForLPCMTranscoding() && ( audio.isLossless() || (audio.isDTS() && audio.getAudioProperties().getNumberOfChannels() <= 6) || audio.isTrueHD() || ( !configuration.isMencoderUsePcmForHQAudioOnly() && ( audio.isAC3() || audio.isMP3() || audio.isAAC() || audio.isVorbis() || // audio.isWMA() || audio.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); int channels; if (ac3Remux) { channels = audio.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux || encodedAudioPassthrough) { channels = 2; } else if (pcm) { channels = audio.getAudioProperties().getNumberOfChannels(); } else { channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding } if (!ac3Remux && (dtsRemux || pcm || encodedAudioPassthrough)) { // DTS remux or LPCM StreamModifier sm = new StreamModifier(); sm.setPcm(pcm); sm.setDtsEmbed(dtsRemux); sm.setEncodedAudioPassthrough(encodedAudioPassthrough); sm.setNbChannels(channels); sm.setSampleFrequency(audio.getSampleRate() < 48000 ? 48000 : audio.getSampleRate()); sm.setBitsPerSample(16); if (!params.mediaRenderer.isMuxDTSToMpeg()) { ffAudioPipe[i].setModifier(sm); } ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + sm.getNbChannels(), "-f", "ac3", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", sm.isDtsEmbed() || sm.isEncodedAudioPassthrough() ? "copy" : "pcm", "-y", ffAudioPipe[i].getInputPipe() }; } else if (!ac3Remux && params.mediaRenderer.isTranscodeToAAC()) { // AAC audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "adts", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", "aac", "-strict", "experimental", "-ab", Math.min(configuration.getAudioBitrate(), 320) + "k", "-y", ffAudioPipe[i].getInputPipe() }; aacTranscode = true; } else { // AC-3 remux or encoding ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "ac3", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", (ac3Remux) ? "copy" : "ac3", "-ab", String.valueOf(CodecUtil.getAC3Bitrate(configuration, audio)) + "k", "-y", ffAudioPipe[i].getInputPipe() }; } ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffAudio[i] = new ProcessWrapperImpl(ffmpegCommands, ffparams); } } } } File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta"); params.log = false; try (PrintWriter pw = new PrintWriter(f)) { pw.print("MUXOPT --no-pcr-on-video-pid"); pw.print(" --new-audio-pes"); pw.print(" --no-asyncio"); pw.print(" --vbr"); pw.println(" --vbv-len=500"); String sei = "insertSEI"; if ( params.mediaRenderer.isPS3() && media.isWebDl(filename, params) ) { sei = "forceSEI"; } String videoparams = "level=4.1, " + sei + ", contSPS, track=1"; if (this instanceof TsMuxeRAudio) { videoparams = "track=224"; } if (configuration.isFix25FPSAvMismatch()) { fps = "25"; } pw.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + (fps != null ? ("fps=" + fps + ", ") : "") + (width != -1 ? ("video-width=" + width + ", ") : "") + (height != -1 ? ("video-height=" + height + ", ") : "") + videoparams); if (ffAudioPipe != null && ffAudioPipe.length == 1) { String timeshift = ""; boolean ac3Remux; boolean dtsRemux; boolean encodedAudioPassthrough; boolean pcm; encodedAudioPassthrough = configuration.isEncodedAudioPassthrough() && params.aid.isNonPCMEncodedAudio() && params.mediaRenderer.isWrapEncodedAudioIntoPCM(); ac3Remux = params.aid.isAC3() && configuration.isAudioRemuxAC3() && !encodedAudioPassthrough && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.isAudioEmbedDtsInPcm() && params.aid.isDTS() && params.mediaRenderer.isDTSPlayable() && !encodedAudioPassthrough; pcm = configuration.isAudioUsePCM() && media.isValidForLPCMTranscoding() && ( params.aid.isLossless() || (params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || params.aid.isTrueHD() || ( !configuration.isMencoderUsePcmForHQAudioOnly() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); String type = "A_AC3"; if (ac3Remux) { // AC-3 remux takes priority type = "A_AC3"; } else if (aacTranscode) { type = "A_AAC"; } else { if (pcm || this instanceof TsMuxeRAudio) { type = "A_LPCM"; } if (encodedAudioPassthrough || this instanceof TsMuxeRAudio) { type = "A_LPCM"; } if (dtsRemux || this instanceof TsMuxeRAudio) { type = "A_LPCM"; if (params.mediaRenderer.isMuxDTSToMpeg()) { type = "A_DTS"; } } } if (params.aid != null && params.aid.getAudioProperties().getAudioDelay() != 0 && params.timeseek == 0) { timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, "; } pw.println(type + ", \"" + ffAudioPipe[0].getOutputPipe() + "\", " + timeshift + "track=2"); } else if (ffAudioPipe != null) { for (int i = 0; i < media.getAudioTracksList().size(); i++) { DLNAMediaAudio lang = media.getAudioTracksList().get(i); String timeshift = ""; boolean ac3Remux; boolean dtsRemux; boolean encodedAudioPassthrough; boolean pcm; encodedAudioPassthrough = configuration.isEncodedAudioPassthrough() && params.aid.isNonPCMEncodedAudio() && params.mediaRenderer.isWrapEncodedAudioIntoPCM(); ac3Remux = lang.isAC3() && configuration.isAudioRemuxAC3() && !encodedAudioPassthrough; dtsRemux = configuration.isAudioEmbedDtsInPcm() && lang.isDTS() && params.mediaRenderer.isDTSPlayable() && !encodedAudioPassthrough; pcm = configuration.isAudioUsePCM() && media.isValidForLPCMTranscoding() && ( lang.isLossless() || (lang.isDTS() && lang.getAudioProperties().getNumberOfChannels() <= 6) || lang.isTrueHD() || ( !configuration.isMencoderUsePcmForHQAudioOnly() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); String type = "A_AC3"; if (ac3Remux) { // AC-3 remux takes priority type = "A_AC3"; } else { if (pcm) { type = "A_LPCM"; } if (encodedAudioPassthrough) { type = "A_LPCM"; } if (dtsRemux) { type = "A_LPCM"; if (params.mediaRenderer.isMuxDTSToMpeg()) { type = "A_DTS"; } } } if (lang.getAudioProperties().getAudioDelay() != 0 && params.timeseek == 0) { timeshift = "timeshift=" + lang.getAudioProperties().getAudioDelay() + "ms, "; } pw.println(type + ", \"" + ffAudioPipe[i].getOutputPipe() + "\", " + timeshift + "track=" + (2 + i)); } } } PipeProcess tsPipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts"); /** * Use the newer version of tsMuxeR on PS3 since other renderers * like Panasonic TVs don't always recognize the new output */ String executable = executable(); if (params.mediaRenderer.isPS3()) { executable = configuration.getTsmuxerNewPath(); } String[] cmdArray = new String[]{ executable, f.getAbsolutePath(), tsPipe.getInputPipe() }; cmdArray = finalizeTranscoderArgs( filename, dlna, media, params, cmdArray ); ProcessWrapperImpl p = new ProcessWrapperImpl(cmdArray, params); params.maxBufferSize = 100; params.input_pipes[0] = tsPipe; params.stdin = null; ProcessWrapper pipe_process = tsPipe.getPipeProcess(); p.attachProcess(pipe_process); pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } tsPipe.deleteLater(); ProcessWrapper ff_pipe_process = ffVideoPipe.getPipeProcess(); p.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } ffVideoPipe.deleteLater(); p.attachProcess(ffVideo); ffVideo.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } if (ffAudioPipe != null && params.aid != null) { for (int i = 0; i < ffAudioPipe.length; i++) { ff_pipe_process = ffAudioPipe[i].getPipeProcess(); p.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } ffAudioPipe[i].deleteLater(); p.attachProcess(ffAudio[i]); ffAudio[i].runInNewThread(); } } try { Thread.sleep(100); } catch (InterruptedException e) { } p.runInNewThread(); configuration = prev; return p; } @Override public String mimeType() { return "video/mpeg"; } @Override public String name() { return "tsMuxeR"; } @Override public int type() { return Format.VIDEO; } private JCheckBox tsmuxerforcefps; private JCheckBox muxallaudiotracks; @Override public JComponent config() { // Apply the orientation for the locale ComponentOrientation orientation = ComponentOrientation.getOrientation(PMS.getLocale()); String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation); FormLayout layout = new FormLayout(colSpec, ROW_SPEC); PanelBuilder builder = new PanelBuilder(layout); builder.border(Borders.EMPTY); builder.opaque(false); CellConstraints cc = new CellConstraints(); JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(2, 1, 1), colSpec, orientation)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); tsmuxerforcefps = new JCheckBox(Messages.getString("TsMuxeRVideo.2"), configuration.isTsmuxerForceFps()); tsmuxerforcefps.setContentAreaFilled(false); tsmuxerforcefps.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setTsmuxerForceFps(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(GuiUtil.getPreferredSizeComponent(tsmuxerforcefps), FormLayoutUtil.flip(cc.xy(2, 3), colSpec, orientation)); muxallaudiotracks = new JCheckBox(Messages.getString("TsMuxeRVideo.19"), configuration.isMuxAllAudioTracks()); muxallaudiotracks.setContentAreaFilled(false); muxallaudiotracks.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setMuxAllAudioTracks(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(GuiUtil.getPreferredSizeComponent(muxallaudiotracks), FormLayoutUtil.flip(cc.xy(2, 5), colSpec, orientation)); JPanel panel = builder.getPanel(); // Apply the orientation to the panel and all components in it panel.applyComponentOrientation(orientation); return panel; } @Override public boolean isInternalSubtitlesSupported() { return false; } @Override public boolean isExternalSubtitlesSupported() { return false; } @Override public boolean isPlayerCompatible(RendererConfiguration mediaRenderer) { return mediaRenderer != null && mediaRenderer.isMuxH264MpegTS(); } /** * {@inheritDoc} */ @Override public boolean isCompatible(DLNAResource resource) { DLNAMediaSubtitle subtitle = resource.getMediaSubtitle(); // Check whether the subtitle actually has a language defined, // uninitialized DLNAMediaSubtitle objects have a null language. if (subtitle != null && subtitle.getLang() != null) { // The resource needs a subtitle, but PMS does not support subtitles for tsMuxeR. return false; } try { String audioTrackName = resource.getMediaAudio().toString(); String defaultAudioTrackName = resource.getMedia().getAudioTracksList().get(0).toString(); if (!audioTrackName.equals(defaultAudioTrackName)) { // PMS only supports playback of the default audio track for tsMuxeR return false; } } catch (NullPointerException e) { LOGGER.trace("tsMuxeR cannot determine compatibility based on audio track for " + resource.getSystemName()); } catch (IndexOutOfBoundsException e) { LOGGER.trace("tsMuxeR cannot determine compatibility based on default audio track for " + resource.getSystemName()); } if ( PlayerUtil.isVideo(resource, Format.Identifier.MKV) || PlayerUtil.isVideo(resource, Format.Identifier.MPG) ) { return true; } return false; } }
bigretromike/UniversalMediaServer
src/main/java/net/pms/encoders/TsMuxeRVideo.java
Java
gpl-2.0
27,024
<?php /** * Template Name: Template Content Sidebar Sidebar * * Page template for * * @package Openstrap * @since Openstrap 0.1 */ get_header(); ?> <!-- Main Content --> <div class="col-md-6" role="main"> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php comments_template( '', true ); ?> <?php endwhile; ?> <?php else : ?> <h2><?php _e('No posts.', 'openstrap' ); ?></h2> <p class="lead"><?php _e('Sorry about this, I couldn\'t seem to find what you were looking for.', 'openstrap' ); ?></p> <?php endif; ?> <?php openstrap_custom_pagination(); ?> </div> <!-- End Main Content --> <?php get_sidebar('left'); ?> <?php get_sidebar(); ?> <?php get_footer(); ?>
IdeasFactoryPL/stef-pol
wp-content/themes/openstrap/page-templates/content-sidebar-sidebar.php
PHP
gpl-2.0
791
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace STSdb4.Data { public class DataComparer : IComparer<IData> { public readonly Func<IData, IData, int> compare; public readonly Type Type; public readonly Type DataType; public readonly CompareOption[] CompareOptions; public readonly Func<Type, MemberInfo, int> MembersOrder; public DataComparer(Type type, CompareOption[] compareOptions, Func<Type, MemberInfo, int> membersOrder = null) { Type = type; DataType = typeof(Data<>).MakeGenericType(type); CompareOption.CheckCompareOptions(type, compareOptions, membersOrder); CompareOptions = compareOptions; MembersOrder = membersOrder; compare = CreateCompareMethod().Compile(); } public DataComparer(Type type, Func<Type, MemberInfo, int> membersOrder = null) : this(type, CompareOption.GetDefaultCompareOptions(type, membersOrder), membersOrder) { } public Expression<Func<IData, IData, int>> CreateCompareMethod() { var x = Expression.Parameter(typeof(IData)); var y = Expression.Parameter(typeof(IData)); List<Expression> list = new List<Expression>(); List<ParameterExpression> parameters = new List<ParameterExpression>(); var value1 = Expression.Variable(Type, "value1"); parameters.Add(value1); list.Add(Expression.Assign(value1, Expression.Convert(x, DataType).Value())); var value2 = Expression.Variable(Type, "value2"); parameters.Add(value2); list.Add(Expression.Assign(value2, Expression.Convert(y, DataType).Value())); return Expression.Lambda<Func<IData, IData, int>>(ComparerHelper.CreateComparerBody(list, parameters, value1, value2, CompareOptions, MembersOrder), x, y); } public int Compare(IData x, IData y) { return compare(x, y); } } }
Injac/STSdb4
STSdb4/Data/DataComparer.cs
C#
gpl-2.0
2,148
<?php /** * This script is included by the barcode_img_wristband.php script for arabic languages */ # Version History: # version 0.1 : First release. created on ( 22/01/2004) By Walid Fathalla # # Bug Report and Suggestion to: # Walid Fathalla # fathalla_w@hotmail.com # # Modifications by Elpidio 2004-02-07 include_once($root_path.'include/inc_ttf_ar2uni.php'); /* Load the barcode image*/ $bc = ImageCreateFrompng($root_path.'cache/barcodes/en_'.$full_en.'.png'); /* Load the wristband images */ $wb_lrg = ImageCreateFrompng('wristband_large.png'); $wb_med = ImageCreateFrompng('wristband_medium.png'); $wb_sml = ImageCreateFrompng('wristband_small.png'); $wb_bby = ImageCreateFrompng('wristband_baby.png'); /* Get the image sizes*/ $size_lrg = GetImageSize('wristband_large.png'); $size_med = GetImageSize('wristband_medium.png'); $size_sml = GetImageSize('wristband_small.png'); $size_bby = GetImageSize('wristband_baby.png'); $w=1085; // The width of the image = equal to the DIN-A4 paper $h=700; // The height of the image = egual to the DIN-A4 paper /* Create the main image */ $im=ImageCreate($w,$h); $white = ImageColorAllocate ($im, 255,255,255); //white bkgrnd /* $background= ImageColorAllocate ($im, 205, 225, 236); $blue=ImageColorAllocate($im, 0, 127, 255); */ $black = ImageColorAllocate ($im, 0, 0, 0); # Check if ttf is ok include_once($root_path.'include/inc_ttf_check.php'); # Write the print instructions $lmargin=10; # Left margin $tmargin=2; # Top margin if($ttf_ok){ ImageTTFText($im,12,0,$lmargin,$tmargin+10,$black,$arial,ar2uni($LDPrintPortraitFormat)); ImageTTFText($im,12,0,$lmargin,$tmargin+25,$black,$arial,ar2uni($LDClickImgToPrint)); }else{ ImageString($im,2,10,2,$LDPrintPortraitFormat,$black); ImageString($im,2,10,15,$LDClickImgToPrint,$black); } # Create the name label $namelabel=ImageCreate(145,40); $nm_white = ImageColorAllocate ($namelabel, 255,255,255); //white bkgrnd $nm_black= ImageColorAllocate ($namelabel, 0, 0, 0); $lmargin=1; # Left margin $tmargin=11; # Top margin $dataline1=ar2uni($result['name_last']).', '.ar2uni($result['name_first']); $dataline2=$result['date_birth']; $dataline3=$result['current_ward'].' '.$result['current_dept'].' '.ar2uni($result['insurance_co_id']).' '.ar2uni($result['insurance_2_co_id']); //$ttf_ok=0; if($ttf_ok){ ImageTTFText($namelabel,11,0,$lmargin,$tmargin,$nm_black,$arial,$dataline1); ImageTTFText($namelabel,10,0,$lmargin,$tmargin+13,$nm_black,$arial,$dataline2); ImageTTFText($namelabel,10,0,$lmargin,$tmargin+26,$nm_black,$arial,$dataline3); }else{ ImageString($namelabel,2,1,2,$dataline1,$nm_black); ImageString($namelabel,2,1,15,$dataline2,$nm_black); ImageString($namelabel,2,1,28,$dataline3,$nm_black); } //-------------- place the wristbands $topm=$topmargin; ImageCopy($im,$wb_lrg,$leftmargin,$topm,0,0,$size_lrg[0],$size_lrg[1]); $topm+=$yoffset; ImageCopy($im,$wb_med,$leftmargin,$topm,0,0,$size_med[0],$size_med[1]); $topm+=$yoffset; ImageCopy($im,$wb_sml,$leftmargin,$topm,0,0,$size_sml[0],$size_sml[1]); $topm+=$yoffset; ImageCopy($im,$wb_bby,$leftmargin,$topm,0,0,$size_bby[0],$size_bby[1]); //* Place the barcodes */ $topm=$topmargin+15; $topm2=$topmargin+60; ImageCopy($im,$bc,$leftmargin+220,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+480,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+230,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+490,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+435,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+225,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+485,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+420,$topm+78,$full_en,$black); } $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$bc,$leftmargin+200,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+430,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+210,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+440,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+395,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+205,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+435,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+380,$topm+78,$full_en,$black); } $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$bc,$leftmargin+160,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+340,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+180,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+360,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+340,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+175,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+355,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+325,$topm+78,$full_en,$black); } $topm+=$yoffset; ImageCopy($im,$bc,$leftmargin+200,$topm,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+210,$topm-1,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+385,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+215,$topm-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+370,$topm+78,$full_en,$black); } //* Place the name labels*/ $topm=$topmargin+53; $topm2=$topmargin+5; ImageCopy($im,$namelabel,$leftmargin+225,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+485,$topm2,0,0,144,39); $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+205,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+435,$topm2,0,0,144,39); $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+175,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+355,$topm2,0,0,144,39); $topm+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+210,$topm,0,0,144,39); /* Create the final image */ Imagepng ($im); // Do not edit the following lines ImageDestroy ($wb_lrg); ImageDestroy ($wb_med); ImageDestroy ($wb_sml); ImageDestroy ($wb_bby); ImageDestroy ($im); ?>
blesko/ELCT
main/imgcreator/inc_wristband_ar.php
PHP
gpl-2.0
6,592
<?php /** * Webservices component for Joomla! CMS * * @copyright Copyright (C) 2004 - 2015 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later */ namespace Webservices\Controller; use Webservices\Helper; use Webservices\Model\WebserviceModel; /** * Apply Webservice Controller * * @package Joomla! * @subpackage Webservices * @since 1.0 */ class ApplyController extends DisplayController { /** * Execute the controller. * * @return void Redirects the application * * @since 2.0 */ public function execute() { try { $model = new WebserviceModel; // Initialize the state for the model $model->setState($this->initializeState($model)); $id = $this->getInput()->getUint('id'); $data = $this->getInput()->getArray()['jform']; if ($model->save($data)) { $msg = \JText::_('COM_WEBSERVICES_APPLY_OK'); } else { $msg = \JText::_('COM_WEBSERVICES_APPLY_ERROR'); } $type = 'message'; $url = 'index.php?option=com_webservices&task=edit&id=' . $id; } catch (\Exception $e) { $msg = $e->getMessage(); $type = 'error'; } $url = isset($this->returnurl) ? $this->returnurl : $url; $this->getApplication()->enqueueMessage($msg, $type); $this->getApplication()->redirect(\JRoute::_($url, false)); } }
joomla-projects/webservices
component/admin/Webservices/Controller/ApplyController.php
PHP
gpl-2.0
1,362
<?php /* * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> * * PERL Spreadsheet::WriteExcel module. * * The author of the Spreadsheet::WriteExcel module is John McNamara * <jmcnamara@cpan.org> * * I _DO_ maintain this code, and John McNamara has nothing to do with the * porting of this code to PHP. Any questions directly related to this * class library should be directed to me. * * License Information: * * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ require_once 'PEAR.php'; require_once dirname(__FILE__) . '/Writer/Workbook.php'; /** * Class for writing Excel Spreadsheets. This class should change COMPLETELY. * * @author Xavier Noguer <xnoguer@rezebra.com> * @category FileFormats * @package Spreadsheet_Excel_Writer */ class Spreadsheet_Excel_Writer extends Spreadsheet_Excel_Writer_Workbook { /** * The constructor. It just creates a Workbook * * @param string $filename The optional filename for the Workbook. * @return Spreadsheet_Excel_Writer_Workbook The Workbook created */ function Spreadsheet_Excel_Writer($filename = '') { $this->_filename = $filename; $this->Spreadsheet_Excel_Writer_Workbook($filename); } /** * Send HTTP headers for the Excel file. * * @param string $filename The filename to use for HTTP headers * @access public */ function send($filename) { header("Content-type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=\"$filename\""); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0,pre-check=0"); header("Pragma: public"); } /** * Utility function for writing formulas * Converts a cell's coordinates to the A1 format. * * @access public * @static * @param integer $row Row for the cell to convert (0-indexed). * @param integer $col Column for the cell to convert (0-indexed). * @return string The cell identifier in A1 format */ function rowcolToCell($row, $col) { if ($col > 255) { //maximum column value exceeded return new PEAR_Error("Maximum column value exceeded: $col"); } $int = (int)($col / 26); $frac = $col % 26; $chr1 = ''; if ($int > 0) { $chr1 = chr(ord('A') + $int - 1); } $chr2 = chr(ord('A') + $frac); $row++; return $chr1 . $chr2 . $row; } }
GeorgeStreetCoop/CORE-POS
fannie/src/Excel/xls_write/Spreadsheet_Excel_Writer/Writer.php
PHP
gpl-2.0
3,325
/***************************************************************************** * SearchFragment.java ***************************************************************************** * Copyright © 2014-2015 VLC authors, VideoLAN and VideoLabs * Author: Geoffrey Métais * * 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; either version 2 of the License, or * (at your option) any later version. * * 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 Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ package org.videolan.vlc.gui.tv; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ListRow; import android.support.v17.leanback.widget.ListRowPresenter; import android.support.v17.leanback.widget.ObjectAdapter; import android.support.v17.leanback.widget.OnItemViewClickedListener; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.Row; import android.support.v17.leanback.widget.RowPresenter; import android.text.TextUtils; import org.videolan.vlc.R; import org.videolan.vlc.VLCApplication; import org.videolan.vlc.media.MediaLibrary; import org.videolan.vlc.media.MediaWrapper; import java.util.ArrayList; public class SearchFragment extends android.support.v17.leanback.app.SearchFragment implements android.support.v17.leanback.app.SearchFragment.SearchResultProvider { private static final String TAG = "SearchFragment"; private ArrayObjectAdapter mRowsAdapter; private Handler mHandler = new Handler(); private SearchRunnable mDelayedLoad; protected Activity mActivity; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter()); setSearchResultProvider(this); setOnItemViewClickedListener(getDefaultItemClickedListener()); mDelayedLoad = new SearchRunnable(); mActivity = getActivity(); } @Override public ObjectAdapter getResultsAdapter() { return mRowsAdapter; } private void queryByWords(String words) { mRowsAdapter.clear(); if (!TextUtils.isEmpty(words) && words.length() > 2) { mDelayedLoad.setSearchQuery(words); mDelayedLoad.setSearchType(MediaWrapper.TYPE_ALL); VLCApplication.runBackground(mDelayedLoad); } } @Override public boolean onQueryTextChange(String newQuery) { queryByWords(newQuery); return true; } @Override public boolean onQueryTextSubmit(String query) { queryByWords(query); return true; } private void loadRows(String query, int type) { ArrayList<MediaWrapper> mediaList = MediaLibrary.getInstance().searchMedia(query); final ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter(mActivity)); listRowAdapter.addAll(0, mediaList); mHandler.post(new Runnable() { @Override public void run() { HeaderItem header = new HeaderItem(0, getResources().getString(R.string.search_results)); mRowsAdapter.add(new ListRow(header, listRowAdapter)); } }); } protected OnItemViewClickedListener getDefaultItemClickedListener() { return new OnItemViewClickedListener() { @Override public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { if (item instanceof MediaWrapper) { TvUtil.openMedia(mActivity, (MediaWrapper) item, row); } } }; } private class SearchRunnable implements Runnable { private volatile String searchQuery; private volatile int searchType; public SearchRunnable() {} public void run() { loadRows(searchQuery, searchType); } public void setSearchQuery(String value) { this.searchQuery = value; } public void setSearchType(int value) { this.searchType = value; } } }
hanhailong/VCL-Official
vlc-android/src/org/videolan/vlc/gui/tv/SearchFragment.java
Java
gpl-2.0
4,897
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_processing/transient/transient_detector.h" #include <sstream> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/modules/audio_processing/transient/common.h" #include "webrtc/modules/audio_processing/transient/file_utils.h" #include "webrtc/system_wrappers/include/file_wrapper.h" #include "webrtc/test/testsupport/fileutils.h" #include "webrtc/test/testsupport/gtest_disable.h" #include "webrtc/typedefs.h" namespace webrtc { static const int kSampleRatesHz[] = {ts::kSampleRate8kHz, ts::kSampleRate16kHz, ts::kSampleRate32kHz, ts::kSampleRate48kHz}; static const size_t kNumberOfSampleRates = sizeof(kSampleRatesHz) / sizeof(*kSampleRatesHz); // This test is for the correctness of the transient detector. // Checks the results comparing them with the ones stored in the detect files in // the directory: resources/audio_processing/transient/ // The files contain all the results in double precision (Little endian). // The audio files used with different sample rates are stored in the same // directory. TEST(TransientDetectorTest, DISABLED_ON_IOS(CorrectnessBasedOnFiles)) { for (size_t i = 0; i < kNumberOfSampleRates; ++i) { int sample_rate_hz = kSampleRatesHz[i]; // Prepare detect file. std::stringstream detect_file_name; detect_file_name << "audio_processing/transient/detect" << (sample_rate_hz / 1000) << "kHz"; rtc::scoped_ptr<FileWrapper> detect_file(FileWrapper::Create()); detect_file->OpenFile( test::ResourcePath(detect_file_name.str(), "dat").c_str(), true, // Read only. false, // No loop. false); // No text. bool file_opened = detect_file->Open(); ASSERT_TRUE(file_opened) << "File could not be opened.\n" << detect_file_name.str().c_str(); // Prepare audio file. std::stringstream audio_file_name; audio_file_name << "audio_processing/transient/audio" << (sample_rate_hz / 1000) << "kHz"; rtc::scoped_ptr<FileWrapper> audio_file(FileWrapper::Create()); audio_file->OpenFile( test::ResourcePath(audio_file_name.str(), "pcm").c_str(), true, // Read only. false, // No loop. false); // No text. // Create detector. TransientDetector detector(sample_rate_hz); const size_t buffer_length = sample_rate_hz * ts::kChunkSizeMs / 1000; rtc::scoped_ptr<float[]> buffer(new float[buffer_length]); const float kTolerance = 0.02f; size_t frames_read = 0; while (ReadInt16FromFileToFloatBuffer(audio_file.get(), buffer_length, buffer.get()) == buffer_length) { ++frames_read; float detector_value = detector.Detect(buffer.get(), buffer_length, NULL, 0); double file_value; ASSERT_EQ(1u, ReadDoubleBufferFromFile(detect_file.get(), 1, &file_value)) << "Detect test file is malformed.\n"; // Compare results with data from the matlab test file. EXPECT_NEAR(file_value, detector_value, kTolerance) << "Frame: " << frames_read; } detect_file->CloseFile(); audio_file->CloseFile(); } } } // namespace webrtc
raj-bhatia/grooveip-ios-public
submodules/mswebrtc/webrtc/webrtc/modules/audio_processing/transient/transient_detector_unittest.cc
C++
gpl-2.0
3,836
<?php /** * @file * This template outputs the description field. * * Variables: * - $title * - $artist * - $album * - $year * - $track * - $genre * - $id3 (Full ID3 Array) */ ?> <?php print $title .' '. t('by') .' '. $artist; ?>
benmirkhah/jadu
sites/all/modules/mp3player/filefieldmp3player/theme/description.tpl.php
PHP
gpl-2.0
241
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban 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; either version 2 of the License, or # (at your option) any later version. # # Fail2Ban 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 Fail2Ban; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Author: Cyril Jaquier # __author__ = "Cyril Jaquier" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" import logging.handlers # Custom debug levels logging.MSG = logging.INFO - 2 logging.TRACEDEBUG = 7 logging.HEAVYDEBUG = 5 logging.addLevelName(logging.MSG, 'MSG') logging.addLevelName(logging.TRACEDEBUG, 'TRACE') logging.addLevelName(logging.HEAVYDEBUG, 'HEAVY') """ Below derived from: https://mail.python.org/pipermail/tutor/2007-August/056243.html """ logging.NOTICE = logging.INFO + 5 logging.addLevelName(logging.NOTICE, 'NOTICE') # define a new logger function for notice # this is exactly like existing info, critical, debug...etc def _Logger_notice(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'NOTICE'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.notice("Houston, we have a %s", "major disaster", exc_info=1) """ if self.isEnabledFor(logging.NOTICE): self._log(logging.NOTICE, msg, args, **kwargs) logging.Logger.notice = _Logger_notice # define a new root level notice function # this is exactly like existing info, critical, debug...etc def _root_notice(msg, *args, **kwargs): """ Log a message with severity 'NOTICE' on the root logger. """ if len(logging.root.handlers) == 0: logging.basicConfig() logging.root.notice(msg, *args, **kwargs) # make the notice root level function known logging.notice = _root_notice # add NOTICE to the priority map of all the levels logging.handlers.SysLogHandler.priority_map['NOTICE'] = 'notice' from time import strptime # strptime thread safety hack-around - http://bugs.python.org/issue7980 strptime("2012", "%Y") # short names for pure numeric log-level ("Level 25" could be truncated by short formats): def _init(): for i in range(50): if logging.getLevelName(i).startswith('Level'): logging.addLevelName(i, '#%02d-Lev.' % i) _init()
nawawi/fail2ban
fail2ban/__init__.py
Python
gpl-2.0
2,770
// Copyright (C) 2019-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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; either version 3, or (at your option) // any later version. // This library 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 library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-options "-std=gnu++11" } // { dg-do compile { target c++11 } } // This macro should have no effect now #define _GLIBCXX_PROFILE 1 #include <vector>
Gurgel100/gcc
libstdc++-v3/testsuite/17_intro/headers/c++2011/profile_mode.cc
C++
gpl-2.0
921
<?php /** * @version: $Id: dbobject.php 4387 2015-02-19 12:24:35Z Radek Suski $ * @package: SobiPro Library * @author * Name: Sigrid Suski & Radek Suski, Sigsiu.NET GmbH * Email: sobi[at]sigsiu.net * Url: http://www.Sigsiu.NET * @copyright Copyright (C) 2006 - 2015 Sigsiu.NET GmbH (http://www.sigsiu.net). All rights reserved. * @license GNU/LGPL Version 3 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation, and under the additional terms according section 7 of GPL v3. * See http://www.gnu.org/licenses/lgpl.html and http://sobipro.sigsiu.net/licenses. * 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. * $Date: 2015-02-19 13:24:35 +0100 (Thu, 19 Feb 2015) $ * $Revision: 4387 $ * $Author: Radek Suski $ * $HeadURL: file:///opt/svn/SobiPro/Component/branches/SobiPro-1.1/Site/lib/models/dbobject.php $ */ defined( 'SOBIPRO' ) || exit( 'Restricted access' ); /** * @author Radek Suski * @version 1.0 * @created 10-Jan-2009 5:24:28 PM */ abstract class SPDBObject extends SPObject { /** * @var bool */ protected $approved = false; /** * @var bool */ protected $confirmed = false; /** * @var int */ protected $counter = 0; /** * @var int */ protected $section = 0; /** * @var bool */ protected $cout = false; /** * @var string */ protected $coutTime = null; /** * @var string */ protected $createdTime = null; /** * @var string */ protected $defURL = null; /** * @var int database object id */ protected $id = 0; /** * @var string */ protected $nid = null; /** * @var string */ protected $metaDesc = null; /** * @var string */ protected $metaKeys = null; /** * @var string */ protected $metaAuthor = null; /** * @var string */ protected $metaRobots = null; /** * @var string */ protected $name = null; /** * @var array */ protected $options = array(); /** * @var string */ protected $oType = null; /** * @var int */ protected $owner = 0; /** * @var string */ protected $ownerIP = null; /** * @var array */ protected $params = array(); /** * @var int */ protected $parent = 0; /** * @var string */ protected $query = null; /** * @var int */ protected $state = 0; /** * @var string */ protected $stateExpl = null; /** * @var string */ protected $template = null; /** * @var string */ protected $updatedTime = null; /** * @var int */ protected $updater = 0; /** * @var string */ protected $updaterIP = null; /** * @var string */ protected $validSince = null; /** * @var string */ protected $validUntil = null; /** * @var int */ protected $version = 0; /** * @var array */ protected $properties = array(); /** * @param string $name * @param array $data */ public function setProperty( $name, $data ) { $this->properties[ $name ] = $data; } /** * list of adjustable properties and the corresponding request method for each property. * If a property isn't declared here, it will be ignored in the getRequest method * @var array */ private static $types = array( 'approved' => 'bool', 'state' => 'int', 'confirmed' => 'bool', 'counter' => 'int', 'createdTime' => 'timestamp', 'defURL' => 'string', 'metaAuthor' => 'string', 'metaDesc' => 'string', 'metaKeys' => 'string', 'metaRobots' => 'string', 'name' => 'string', 'nid' => 'cmd', /** * the id is not needed (and it's dangerous) because if we updating an object it's being created through the id anyway * so at that point we have to already have it. If not, we don't need it because then we are creating a new object */ // 'id' => 'int', 'owner' => 'int', 'ownerIP' => 'ip', 'parent' => 'int', 'stateExpl' => 'string', 'validSince' => 'timestamp', 'validUntil' => 'timestamp', ); /** * @var array */ private static $translatable = array( 'nid', 'metaDesc', 'metaKeys' ); /** * @return \SPDBObject */ public function __construct() { $this->validUntil = SPFactory::config()->date( SPFactory::db()->getNullDate(), 'date.db_format' ); $this->createdTime = SPFactory::config()->date( gmdate( 'U' ), 'date.db_format', null, true ); $this->validSince = SPFactory::config()->date( gmdate( 'U' ), 'date.db_format', null, true ); $this->ownerIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updaterIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updater = Sobi::My( 'id' ); $this->owner = Sobi::My( 'id' ); $this->updatedTime = SPFactory::config()->date( time(), 'date.db_format' ); Sobi::Trigger( 'CreateModel', $this->name(), array( &$this ) ); } public function formatDatesToEdit() { if ( $this->validUntil ) { $this->validUntil = SPFactory::config()->date( $this->validUntil, 'date.publishing_format' ); } $this->createdTime = SPFactory::config()->date( $this->createdTime, 'date.publishing_format' ); $this->validSince = SPFactory::config()->date( $this->validSince, 'date.publishing_format' ); } /** * @param int $state * @param string $reason */ public function changeState( $state, $reason = null ) { try { SPFactory::db()->update( 'spdb_object', array( 'state' => ( int )$state, 'stateExpl' => $reason ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } SPFactory::cache() ->purgeSectionVars() ->deleteObj( $this->type(), $this->id ) ->deleteObj( 'category', $this->parent ); } /** * Checking in current object */ public function checkIn() { if ( $this->id ) { $this->cout = 0; $this->coutTime = null; try { SPFactory::db()->update( 'spdb_object', array( 'coutTime' => $this->coutTime, 'cout' => $this->cout ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } } /** * checking out current object */ public function checkOut() { if ( $this->id ) { /* @var SPdb $db */ $config =& SPFactory::config(); $this->cout = Sobi::My( 'id' ); $this->coutTime = $config->date( ( time() + $config->key( 'editing.def_cout_time', 3600 ) ), 'date.db_format' ); try { SPFactory::db()->update( 'spdb_object', array( 'coutTime' => $this->coutTime, 'cout' => $this->cout ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } } /** */ public function delete() { Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( $this->id ) ); try { SPFactory::db()->delete( 'spdb_object', array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } try { SPFactory::db()->delete( 'spdb_relations', array( 'id' => $this->id, 'oType' => $this->type() ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } try { SPFactory::db()->delete( 'spdb_language', array( 'id' => $this->id, 'oType' => $this->type() ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } /** * @param string $type * @param bool $recursive * @param int $state * @param bool $name * @return array */ public function getChilds( $type = 'entry', $recursive = false, $state = 0, $name = false ) { static $lang = null; if ( !( $lang ) ) { $lang = Sobi::Lang( false ); } $childs = SPFactory::cache()->getVar( 'childs_' . $lang . $type . ( $recursive ? '_recursive' : '' ) . ( $name ? '_full' : '' ) . $state, $this->id ); if ( $childs ) { return $childs == SPC::NO_VALUE ? array() : $childs; } $db = SPFactory::db(); $childs = array(); try { $cond = array( 'pid' => $this->id ); if ( $state ) { $cond[ 'so.state' ] = $state; $cond[ 'so.approved' ] = $state; $tables = $db->join( array( array( 'table' => 'spdb_object', 'as' => 'so', 'key' => 'id' ), array( 'table' => 'spdb_relations', 'as' => 'sr', 'key' => 'id' ) ) ); $db->select( array( 'sr.id', 'sr.oType' ), $tables, $cond ); } else { $db->select( array( 'id', 'oType' ), 'spdb_relations', $cond ); } $results = $db->loadAssocList( 'id' ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_GET_CHILDS_DB_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( $recursive && count( $results ) ) { foreach ( $results as $cid ) { $this->rGetChilds( $results, $cid, $type ); } } if ( count( $results ) ) { if ( $type == 'all' ) { foreach ( $results as $id => $r ) { $childs[ $id ] = $r[ 'id' ]; } } else { foreach ( $results as $id => $r ) { if ( $r[ 'oType' ] == $type ) { $childs[ $id ] = $id; } } } } if ( $name && count( $childs ) ) { $names = SPLang::translateObject( $childs, array( 'name', 'alias' ), $type ); if ( is_array( $names ) && !empty( $names ) ) { foreach ( $childs as $i => $id ) { $childs[ $i ] = array( 'name' => $names[ $id ][ 'value' ], 'alias' => $names[ $id ][ 'alias' ] ); } } } if ( !$state ) { SPFactory::cache()->addVar( $childs, 'childs_' . $lang . $type . ( $recursive ? '_recursive' : '' ) . ( $name ? '_full' : '' ) . $state, $this->id ); } return $childs; } /** * @param array $results * @param string $type * @param int $id */ private function rGetChilds( &$results, $id, $type = 'entry' ) { if ( is_array( $id ) ) { $id = $id[ 'id' ]; } /* @var SPdb $db */ $db =& SPFactory::db(); try { $cond = array( 'pid' => $id ); /** Tue, Mar 25, 2014 12:46:08 - it's a recursive function so we need entries and categories * See Issue #1211 * Thanks Marcel * */ // if ( $type ) { // $cond[ 'oType' ] = $type; // } $r = $db->select( array( 'id', 'oType' ), 'spdb_relations', $cond ) ->loadAssocList( 'id' ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_GET_CHILDS_DB_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( count( $r ) ) { foreach ( $r as $id => $rs ) { if ( $rs[ 'oType' ] == 'entry' ) { continue; } $results[ $id ] = $rs; $this->rGetChilds( $results, $id, $type ); } } } /** */ protected function createAlias() { /* check nid */ $c = 1; static $add = 0; $suffix = null; if ( !( strlen( $this->nid ) ) ) { $this->nid = SPLang::nid( $this->name, true ); } while ( $c ) { try { $condition = array( 'oType' => $this->oType, 'nid' => $this->nid . $suffix ); if ( $this->id ) { $condition[ '!id' ] = $this->id; } $c = SPFactory::db() ->select( 'COUNT( nid )', 'spdb_object', $condition ) ->loadResult(); if ( $c > 0 ) { $suffix = '_' . ++$add; } } catch ( SPException $x ) { } } return $this->nid . $suffix; } /** * Gettin data from request for this object * @param string $prefix * @param string $request */ public function getRequest( $prefix = null, $request = 'POST' ) { $prefix = $prefix ? $prefix . '_' : null; /* get data types of my properties */ $properties = get_object_vars( $this ); Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$properties ) ); /* and of the parent properties */ $types = array_merge( $this->types(), self::$types ); foreach ( $properties as $property => $values ) { /* if this is an internal variable */ if ( substr( $property, 0, 1 ) == '_' ) { continue; } /* if no data type has been declared */ if ( !isset( $types[ $property ] ) ) { continue; } /* if there was no data for this property ( not if it was just empty ) */ if ( !( SPRequest::exists( $prefix . $property, $request ) ) ) { continue; } /* if the declared data type has not handler in request class */ if ( !method_exists( 'SPRequest', $types[ $property ] ) ) { Sobi::Error( $this->name(), SPLang::e( 'Method %s does not exist!', $types[ $property ] ), SPC::WARNING, 0, __LINE__, __FILE__ ); continue; } /* now we get it ;) */ $this->$property = SPRequest::$types[ $property ]( $prefix . $property, null, $request ); } /* trigger plugins */ Sobi::Trigger( 'getRequest', $this->name(), array( &$this ) ); } public function countChilds( $type = null, $state = 0 ) { return count( $this->getChilds( $type, true, $state ) ); } /** * @return string */ public function type() { return $this->oType; } public function countVisit( $reset = false ) { $count = true; Sobi::Trigger( 'CountVisit', ucfirst( $this->type() ), array( &$count, $this->id ) ); if ( $this->id && $count ) { try { SPFactory::db()->insertUpdate( 'spdb_counter', array( 'sid' => $this->id, 'counter' => ( $reset ? '0' : ++$this->counter ), 'lastUpdate' => 'FUNCTION:NOW()' ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_INC_COUNTER_DB', $x->getMessage() ), SPC::ERROR, 0, __LINE__, __FILE__ ); } } } /** */ public function save( $request = 'post' ) { $this->version++; /* get current data */ $this->updatedTime = SPRequest::now(); $this->updaterIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updater = Sobi::My( 'id' ); $this->nid = SPLang::nid( $this->nid, true ); if ( !( $this->nid ) ) { $this->nid = SPLang::nid( $this->name, true ); } /* get THIS class properties */ $properties = get_class_vars( __CLASS__ ); /* if new object */ if ( !$this->id ) { /** @var the notification App is using it to recognise if it is a new entry or an update */ $this->createdTime = $this->updatedTime; $this->owner = $this->owner ? $this->owner : $this->updater; $this->ownerIP = $this->updaterIP; } /* just a security check to avoid mistakes */ else { /** Fri, Dec 19, 2014 19:33:52 * When storing it we should actually get already UTC unix time stamp * so there is not need to remove it again */ // $this->createdTime = $this->createdTime && is_numeric( $this->createdTime ) ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->createdTime - SPFactory::config()->getTimeOffset() ) : $this->createdTime; $this->createdTime = $this->createdTime && is_numeric( $this->createdTime ) ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->createdTime ) : $this->createdTime; $obj = SPFactory::object( $this->id ); if ( $obj->oType != $this->oType ) { Sobi::Error( 'Object Save', sprintf( 'Serious security violation. Trying to save an object which claims to be an %s but it is a %s. Task was %s', $this->oType, $obj->oType, SPRequest::task() ), SPC::ERROR, 403, __LINE__, __FILE__ ); exit; } } if ( is_numeric( $this->validUntil ) ) { // $this->validUntil = $this->validUntil ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validUntil - SPFactory::config()->getTimeOffset() ) : null; $this->validUntil = $this->validUntil ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validUntil ) : null; } if ( is_numeric( $this->validSince ) ) { $this->validSince = $this->validSince ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validSince ) : null; } /* @var SPdb $db */ $db = SPFactory::db(); $db->transaction(); /* get database columns and their ordering */ $cols = $db->getColumns( 'spdb_object' ); $values = array(); /* * @todo: manage own is not implemented yet */ //$this->approved = Sobi::Can( $this->type(), 'manage', 'own' ); /* if not published, check if user can manage own and if yes, publish it */ if ( !( $this->state ) && !( defined( 'SOBIPRO_ADM' ) ) ) { $this->state = Sobi::Can( $this->type(), 'publish', 'own' ); } if ( !( defined( 'SOBIPRO_ADM' ) ) ) { $this->approved = Sobi::Can( $this->type(), 'publish', 'own' ); } // elseif ( defined( 'SOBIPRO_ADM' ) ) { // $this->approved = Sobi::Can( $this->type(), 'publish', 'own' ); // } /* and sort the properties in the same order */ foreach ( $cols as $col ) { $values[ $col ] = array_key_exists( $col, $properties ) ? $this->$col : ''; } /* trigger plugins */ Sobi::Trigger( 'save', $this->name(), array( &$this ) ); /* try to save */ try { /* if new object */ if ( !$this->id ) { $db->insert( 'spdb_object', $values ); $this->id = $db->insertid(); } /* if update */ else { $db->update( 'spdb_object', $values, array( 'id' => $this->id ) ); } } catch ( SPException $x ) { $db->rollback(); Sobi::Error( $this->name(), SPLang::e( 'CANNOT_SAVE_OBJECT_DB_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } /* get translatable properties */ $attributes = array_merge( $this->translatable(), self::$translatable ); $labels = array(); $defLabels = array(); foreach ( $attributes as $attr ) { if ( $this->has( $attr ) ) { $labels[ ] = array( 'sKey' => $attr, 'sValue' => $this->$attr, 'language' => Sobi::Lang(), 'id' => $this->id, 'oType' => $this->type(), 'fid' => 0 ); if ( Sobi::Lang() != Sobi::DefLang() ) { $defLabels[ ] = array( 'sKey' => $attr, 'sValue' => $this->$attr, 'language' => Sobi::DefLang(), 'id' => $this->id, 'oType' => $this->type(), 'fid' => 0 ); } } } /* save translatable properties */ if ( count( $labels ) ) { try { if ( Sobi::Lang() != Sobi::DefLang() ) { $db->insertArray( 'spdb_language', $defLabels, false, true ); } $db->insertArray( 'spdb_language', $labels, true ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_SAVE_OBJECT_DB_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } } $db->commit(); $this->checkIn(); } /** * Dummy function */ public function update() { return $this->save(); } /** * @param stdClass $obj */ public function extend( $obj, $cache = false ) { if ( !empty( $obj ) ) { foreach ( $obj as $k => $v ) { $this->_set( $k, $v ); } } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$obj ) ); $this->loadTable( $cache ); $this->validUntil = SPFactory::config()->date( $this->validUntil, 'Y-m-d H:i:s' ); } /** * @param int $id * @return \SPDBObject * @internal param \stdClass $obj */ public function & init( $id = 0 ) { Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$id ) ); $this->id = $id ? $id : $this->id; if ( $this->id ) { try { $obj = SPFactory::object( $this->id ); if ( !empty( $obj ) ) { /* ensure that the id was right */ if ( $obj->oType == $this->oType ) { $this->extend( $obj ); } else { $this->id = 0; } } $this->createdTime = SPFactory::config()->date( $this->createdTime ); $this->validSince = SPFactory::config()->date( $this->validSince ); if ( $this->validUntil ) { $this->validUntil = SPFactory::config()->date( $this->validUntil ); } } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'CANNOT_GET_OBJECT_DB_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } $this->loadTable(); } return $this; } /** */ public function load( $id ) { return $this->init( $id ); } /** */ public function loadTable() { if ( $this->has( '_dbTable' ) && $this->_dbTable ) { try { $db = SPFactory::db(); $obj = $db->select( '*', $this->_dbTable, array( 'id' => $this->id ) ) ->loadObject(); $counter = $db->select( 'counter', 'spdb_counter', array( 'sid' => $this->id ) ) ->loadResult(); if ( $counter !== null ) { $this->counter = $counter; } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$obj ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( !empty( $obj ) ) { foreach ( $obj as $k => $v ) { $this->_set( $k, $v ); } } else { Sobi::Error( $this->name(), SPLang::e( 'NO_ENTRIES' ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } $this->translate(); } /** */ protected function translate() { $attributes = array_merge( $this->translatable(), self::$translatable ); Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$attributes ) ); $db =& SPFactory::db(); try { $labels = $db ->select( 'sValue, sKey', 'spdb_language', array( 'id' => $this->id, 'sKey' => $attributes, 'language' => Sobi::Lang(), 'oType' => $this->type() ) ) ->loadAssocList( 'sKey' ); /* get labels in the default lang first */ if ( Sobi::Lang( false ) != Sobi::DefLang() ) { $dlabels = $db ->select( 'sValue, sKey', 'spdb_language', array( 'id' => $this->id, 'sKey' => $attributes, 'language' => Sobi::DefLang(), 'oType' => $this->type() ) ) ->loadAssocList( 'sKey' ); if ( count( $dlabels ) ) { foreach ( $dlabels as $k => $v ) { if ( !( isset( $labels[ $k ] ) ) || !( $labels[ $k ] ) ) { $labels[ $k ] = $v; } } } } } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( count( $labels ) ) { foreach ( $labels as $k => $v ) { $this->_set( $k, $v[ 'sValue' ] ); } } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$labels ) ); } /** * @param string $var * @param mixed $val */ protected function _set( $var, $val ) { if ( $this->has( $var ) ) { if ( is_array( $this->$var ) && is_string( $val ) && strlen( $val ) > 2 ) { try { $val = SPConfig::unserialize( $val, $var ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '%s.', $x->getMessage() ), SPC::NOTICE, 0, __LINE__, __FILE__ ); } } $this->$var = $val; } } /** * @return bool */ public function isCheckedOut() { if ( $this->cout && $this->cout != Sobi::My( 'id' ) && strtotime( $this->coutTime ) > time() ) { return true; } else { return false; } } /** * @param string $var * @param mixed $val * @return \SPObject|void */ public function set( $var, $val ) { static $types = array(); if ( !count( $types ) ) { $types = array_merge( $this->types(), self::$types ); } if ( $this->has( $var ) && isset( $types[ $var ] ) ) { if ( is_array( $this->$var ) && is_string( $val ) && strlen( $val ) > 2 ) { try { $val = SPConfig::unserialize( $val, $var ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '%s.', $x->getMessage() ), SPC::NOTICE, 0, __LINE__, __FILE__ ); } } $this->$var = $val; } } /** * @return array */ protected function translatable() { return array(); } }
vstorm83/propertease
components/com_sobipro/lib/models/dbobject.php
PHP
gpl-2.0
23,563
/* * Copyright (c) 2016-2019 Projekt Substratum * This file is part of Substratum. * * SPDX-License-Identifier: GPL-3.0-Or-Later */ package projekt.substratum.common; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import projekt.substratum.Substratum; import projekt.substratum.services.crash.AppCrashReceiver; import projekt.substratum.services.packages.OverlayFound; import projekt.substratum.services.packages.OverlayUpdater; import projekt.substratum.services.packages.PackageModificationDetector; import projekt.substratum.services.profiles.ScheduledProfileReceiver; import projekt.substratum.services.system.InterfacerAuthorizationReceiver; import static projekt.substratum.common.Internal.ENCRYPTION_KEY_EXTRA; import static projekt.substratum.common.Internal.IV_ENCRYPTION_KEY_EXTRA; import static projekt.substratum.common.Internal.MAIN_ACTIVITY_RECEIVER; import static projekt.substratum.common.Internal.OVERLAY_REFRESH; import static projekt.substratum.common.Internal.THEME_FRAGMENT_REFRESH; import static projekt.substratum.common.References.ACTIVITY_FINISHER; import static projekt.substratum.common.References.APP_CRASHED; import static projekt.substratum.common.References.INTERFACER_PACKAGE; import static projekt.substratum.common.References.KEY_RETRIEVAL; import static projekt.substratum.common.References.MANAGER_REFRESH; import static projekt.substratum.common.References.PACKAGE_ADDED; import static projekt.substratum.common.References.PACKAGE_FULLY_REMOVED; import static projekt.substratum.common.References.SUBSTRATUM_LOG; import static projekt.substratum.common.References.TEMPLATE_RECEIVE_KEYS; import static projekt.substratum.common.References.scheduledProfileReceiver; public class Broadcasts { /** * Send a localized key message for encryption to take place * * @param context Context * @param encryptionKey Encryption key * @param ivEncryptKey IV encryption key */ private static void sendLocalizedKeyMessage(Context context, byte[] encryptionKey, byte[] ivEncryptKey) { Substratum.log("KeyRetrieval", "The system has completed the handshake for keys retrieval " + "and is now passing it to the activity..."); Intent intent = new Intent(KEY_RETRIEVAL); intent.putExtra(ENCRYPTION_KEY_EXTRA, encryptionKey); intent.putExtra(IV_ENCRYPTION_KEY_EXTRA, ivEncryptKey); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * Close Substratum as a whole * * @param context Context */ public static void sendKillMessage(Context context) { Substratum.log("SubstratumKiller", "A crucial action has been conducted by the user and " + "Substratum is now shutting down!"); Intent intent = new Intent(MAIN_ACTIVITY_RECEIVER); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the ThemeFragment * * @param context Context */ public static void sendRefreshMessage(Context context) { Substratum.log("ThemeFragmentRefresher", "A theme has been modified, sending update signal to refresh the list!"); Intent intent = new Intent(THEME_FRAGMENT_REFRESH); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the Overlays tab * * @param context Context */ public static void sendOverlayRefreshMessage(Context context) { Substratum.log("OverlayRefresher", "A theme has been modified, sending update signal to refresh the list!"); Intent intent = new Intent(OVERLAY_REFRESH); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * Activity finisher when a theme was updated * * @param context Context * @param packageName Package of theme to close */ public static void sendActivityFinisherMessage(Context context, String packageName) { Substratum.log("ThemeInstaller", "A theme has been installed, sending update signal to app for further processing!"); Intent intent = new Intent(ACTIVITY_FINISHER); intent.putExtra(Internal.THEME_PID, packageName); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the ManagerFragment * * @param context Context */ public static void sendRefreshManagerMessage(Context context) { Intent intent = new Intent(MANAGER_REFRESH); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } /** * Register the implicit intent broadcast receivers * * @param context Context */ public static void registerBroadcastReceivers(Context context) { try { IntentFilter intentPackageAdded = new IntentFilter(PACKAGE_ADDED); intentPackageAdded.addDataScheme("package"); IntentFilter intentPackageFullyRemoved = new IntentFilter(PACKAGE_FULLY_REMOVED); intentPackageFullyRemoved.addDataScheme("package"); if (Systems.checkOMS(context)) { IntentFilter intentAppCrashed = new IntentFilter(APP_CRASHED); context.getApplicationContext().registerReceiver( new AppCrashReceiver(), intentAppCrashed); context.getApplicationContext().registerReceiver( new OverlayUpdater(), intentPackageAdded); } if (Systems.checkThemeInterfacer(context)) { IntentFilter interfacerAuthorize = new IntentFilter( INTERFACER_PACKAGE + ".CALLER_AUTHORIZED"); context.getApplicationContext().registerReceiver( new InterfacerAuthorizationReceiver(), interfacerAuthorize); } context.getApplicationContext().registerReceiver( new OverlayFound(), intentPackageAdded); context.getApplicationContext().registerReceiver( new PackageModificationDetector(), intentPackageAdded); context.getApplicationContext().registerReceiver( new PackageModificationDetector(), intentPackageFullyRemoved); Substratum.log(SUBSTRATUM_LOG, "Successfully registered broadcast receivers for Substratum functionality!"); } catch (Exception e) { Log.e(SUBSTRATUM_LOG, "Failed to register broadcast receivers for Substratum functionality..."); } } /** * Register the profile screen off receiver * * @param context Context */ public static void registerProfileScreenOffReceiver(Context context) { scheduledProfileReceiver = new ScheduledProfileReceiver(); context.registerReceiver(scheduledProfileReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); } /** * Unload the profile screen off receiver * * @param context Context */ public static void unregisterProfileScreenOffReceiver(Context context) { try { context.unregisterReceiver(scheduledProfileReceiver); } catch (Exception ignored) { } } /** * Start the key retrieval receiver to obtain the key from the theme * * @param context Context */ public static void startKeyRetrievalReceiver(Context context) { try { IntentFilter intentGetKeys = new IntentFilter(TEMPLATE_RECEIVE_KEYS); context.getApplicationContext().registerReceiver( new KeyRetriever(), intentGetKeys); Substratum.log(SUBSTRATUM_LOG, "Successfully registered key retrieval receiver!"); } catch (Exception e) { Log.e(SUBSTRATUM_LOG, "Failed to register key retrieval receiver..."); } } /** * Key Retriever Receiver */ public static class KeyRetriever extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { sendLocalizedKeyMessage( context, intent.getByteArrayExtra(ENCRYPTION_KEY_EXTRA), intent.getByteArrayExtra(IV_ENCRYPTION_KEY_EXTRA)); } } }
nicholaschum/substratum
app/src/main/java/projekt/substratum/common/Broadcasts.java
Java
gpl-3.0
8,846
<?php function tous_les_fonds($dir,$pattern){ $liste = find_all_in_path($dir,$pattern); foreach($liste as $k=>$v) $liste[$k] = $dir . basename($v,'.html'); return $liste; } ?>
genova/ugb
plugins/spip-bonux/style_prive_plugins_fonctions.php
PHP
gpl-3.0
182
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.client.hook; import java.util.Map; import com.alibaba.rocketmq.client.impl.CommunicationMode; import com.alibaba.rocketmq.client.producer.SendResult; import com.alibaba.rocketmq.common.message.Message; import com.alibaba.rocketmq.common.message.MessageQueue; public class SendMessageContext { private String producerGroup; private Message message; private MessageQueue mq; private String brokerAddr; private String bornHost; private CommunicationMode communicationMode; private SendResult sendResult; private Exception exception; private Object mqTraceContext; private Map<String, String> props; public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } public Message getMessage() { return message; } public void setMessage(Message message) { this.message = message; } public MessageQueue getMq() { return mq; } public void setMq(MessageQueue mq) { this.mq = mq; } public String getBrokerAddr() { return brokerAddr; } public void setBrokerAddr(String brokerAddr) { this.brokerAddr = brokerAddr; } public CommunicationMode getCommunicationMode() { return communicationMode; } public void setCommunicationMode(CommunicationMode communicationMode) { this.communicationMode = communicationMode; } public SendResult getSendResult() { return sendResult; } public void setSendResult(SendResult sendResult) { this.sendResult = sendResult; } public Exception getException() { return exception; } public void setException(Exception exception) { this.exception = exception; } public Object getMqTraceContext() { return mqTraceContext; } public void setMqTraceContext(Object mqTraceContext) { this.mqTraceContext = mqTraceContext; } public Map<String, String> getProps() { return props; } public void setProps(Map<String, String> props) { this.props = props; } public String getBornHost() { return bornHost; } public void setBornHost(String bornHost) { this.bornHost = bornHost; } }
y123456yz/reading-and-annotate-rocketmq-3.4.6
rocketmq-src/RocketMQ-3.4.6/rocketmq-client/src/main/java/com/alibaba/rocketmq/client/hook/SendMessageContext.java
Java
gpl-3.0
3,205
<?php /** * Nooku Framework - http://www.nooku.org * * @copyright Copyright (C) 2007 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link git://git.assembla.com/nooku-framework.git for the canonical source repository */ namespace Nooku\Library; /** * Object Set * * ObjectSet implements an associative container that stores objects, and in which the object themselves are the keys. * Objects are stored in the set in FIFO order. * * @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens> * @package Nooku\Library\Object * @see http://www.php.net/manual/en/class.splobjectstorage.php */ class ObjectSet extends Object implements \IteratorAggregate, \ArrayAccess, \Countable, \Serializable { /** * Object set * * @var array */ protected $_object_set = null; /** * Constructor * * @param ObjectConfig $config A ObjectConfig object with configuration options * @return ObjectSet */ public function __construct(ObjectConfig $config) { parent::__construct($config); $this->_object_set = new \ArrayObject(); } /** * Inserts an object in the set * * @param ObjectHandlable $object * @return boolean TRUE on success FALSE on failure */ public function insert(ObjectHandlable $object) { $result = false; if ($handle = $object->getHandle()) { $this->_object_set->offsetSet($handle, $object); $result = true; } return $result; } /** * Removes an object from the set * * All numerical array keys will be modified to start counting from zero while literal keys won't be touched. * * @param ObjectHandlable $object * @return ObjectSet */ public function extract(ObjectHandlable $object) { $handle = $object->getHandle(); if ($this->_object_set->offsetExists($handle)) { $this->_object_set->offsetUnset($handle); } return $this; } /** * Checks if the set contains a specific object * * @param ObjectHandlable $object * @return bool Returns TRUE if the object is in the set, FALSE otherwise */ public function contains(ObjectHandlable $object) { return $this->_object_set->offsetExists($object->getHandle()); } /** * Merge-in another object set * * @param ObjectSet $set * @return ObjectSet */ public function merge(ObjectSet $set) { foreach ($set as $object) { $this->insert($object); } return $this; } /** * Check if the object exists in the queue * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return bool Returns TRUE if the object exists in the storage, and FALSE otherwise * @throws \InvalidArgumentException if the object doesn't implement ObjectHandlable */ public function offsetExists($object) { if (!$object instanceof ObjectHandlable) { throw new \InvalidArgumentException('Object needs to implement ObjectHandlable'); } return $this->contains($object); } /** * Returns the object from the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return ObjectHandlable * @throws \InvalidArgumentException if the object doesn't implement ObjectHandlable */ public function offsetGet($object) { if (!$object instanceof ObjectHandlable) { throw new \InvalidArgumentException('Object needs to implement ObjectHandlable'); } return $this->_object_set->offsetGet($object->getHandle()); } /** * Store an object in the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @param mixed $data The data to associate with the object [UNUSED] * @return ObjectSet * @throws \InvalidArgumentException if the object doesn't implement ObjectHandlable */ public function offsetSet($object, $data) { if (!$object instanceof ObjectHandlable) { throw new \InvalidArgumentException('Object needs to implement ObjectHandlable'); } $this->insert($object); return $this; } /** * Removes an object from the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return ObjectSet * @throws InvalidArgumentException if the object doesn't implement the ObjectHandlable interface */ public function offsetUnset($object) { if (!$object instanceof ObjectHandlable) { throw new \InvalidArgumentException('Object needs to implement ObjectHandlable'); } $this->extract($object); return $this; } /** * Return a string representation of the set * * Required by interface \Serializable * * @return string A serialized object */ public function serialize() { return serialize($this->_object_set); } /** * Unserializes a set from its string representation * * Required by interface \Serializable * * @param string $serialized The serialized data */ public function unserialize($serialized) { $this->_object_set = unserialize($serialized); } /** * Returns the number of elements in the collection. * * Required by the Countable interface * * @return int */ public function count() { return $this->_object_set->count(); } /** * Return the first object in the set * * @return ObjectHandlable or NULL is queue is empty */ public function top() { $objects = array_values($this->_object_set->getArrayCopy()); $object = null; if (isset($objects[0])) { $object = $objects[0]; } return $object; } /** * Defined by IteratorAggregate * * @return \ArrayIterator */ public function getIterator() { return $this->_object_set->getIterator(); } /** * Return an associative array of the data. * * @return array */ public function toArray() { return $this->_object_set->getArrayCopy(); } /** * Preform a deep clone of the object * * @retun void */ public function __clone() { parent::__clone(); $this->_object_set = clone $this->_object_set; } }
jowillems/internet-platform
library/object/set.php
PHP
gpl-3.0
6,776
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Standard library of functions and constants for lesson * * @package mod_lesson * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later **/ defined('MOODLE_INTERNAL') || die(); /* Do not include any libraries here! */ /** * Given an object containing all the necessary data, * (defined by the form in mod_form.php) this function * will create a new instance and return the id number * of the new instance. * * @global object * @global object * @param object $lesson Lesson post data from the form * @return int **/ function lesson_add_instance($data, $mform) { global $DB; $cmid = $data->coursemodule; $draftitemid = $data->mediafile; $context = context_module::instance($cmid); lesson_process_pre_save($data); unset($data->mediafile); $lessonid = $DB->insert_record("lesson", $data); $data->id = $lessonid; lesson_update_media_file($lessonid, $context, $draftitemid); lesson_process_post_save($data); lesson_grade_item_update($data); return $lessonid; } /** * Given an object containing all the necessary data, * (defined by the form in mod_form.php) this function * will update an existing instance with new data. * * @global object * @param object $lesson Lesson post data from the form * @return boolean **/ function lesson_update_instance($data, $mform) { global $DB; $data->id = $data->instance; $cmid = $data->coursemodule; $draftitemid = $data->mediafile; $context = context_module::instance($cmid); lesson_process_pre_save($data); unset($data->mediafile); $DB->update_record("lesson", $data); lesson_update_media_file($data->id, $context, $draftitemid); lesson_process_post_save($data); // update grade item definition lesson_grade_item_update($data); // update grades - TODO: do it only when grading style changes lesson_update_grades($data, 0, false); return true; } /** * This function updates the events associated to the lesson. * If $override is non-zero, then it updates only the events * associated with the specified override. * * @uses LESSON_MAX_EVENT_LENGTH * @param object $lesson the lesson object. * @param object $override (optional) limit to a specific override */ function lesson_update_events($lesson, $override = null) { global $CFG, $DB; require_once($CFG->dirroot . '/mod/lesson/locallib.php'); require_once($CFG->dirroot . '/calendar/lib.php'); // Load the old events relating to this lesson. $conds = array('modulename' => 'lesson', 'instance' => $lesson->id); if (!empty($override)) { // Only load events for this override. if (isset($override->userid)) { $conds['userid'] = $override->userid; } else { $conds['groupid'] = $override->groupid; } } $oldevents = $DB->get_records('event', $conds); // Now make a to-do list of all that needs to be updated. if (empty($override)) { // We are updating the primary settings for the lesson, so we need to add all the overrides. $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id)); // As well as the original lesson (empty override). $overrides[] = new stdClass(); } else { // Just do the one override. $overrides = array($override); } // Get group override priorities. $grouppriorities = lesson_get_group_override_priorities($lesson->id); foreach ($overrides as $current) { $groupid = isset($current->groupid) ? $current->groupid : 0; $userid = isset($current->userid) ? $current->userid : 0; $available = isset($current->available) ? $current->available : $lesson->available; $deadline = isset($current->deadline) ? $current->deadline : $lesson->deadline; // Only add open/close events for an override if they differ from the lesson default. $addopen = empty($current->id) || !empty($current->available); $addclose = empty($current->id) || !empty($current->deadline); if (!empty($lesson->coursemodule)) { $cmid = $lesson->coursemodule; } else { $cmid = get_coursemodule_from_instance('lesson', $lesson->id, $lesson->course)->id; } $event = new stdClass(); $event->description = format_module_intro('lesson', $lesson, $cmid); // Events module won't show user events when the courseid is nonzero. $event->courseid = ($userid) ? 0 : $lesson->course; $event->groupid = $groupid; $event->userid = $userid; $event->modulename = 'lesson'; $event->instance = $lesson->id; $event->timestart = $available; $event->timeduration = max($deadline - $available, 0); $event->visible = instance_is_visible('lesson', $lesson); $event->eventtype = 'open'; // Determine the event name and priority. if ($groupid) { // Group override event. $params = new stdClass(); $params->lesson = $lesson->name; $params->group = groups_get_group_name($groupid); if ($params->group === false) { // Group doesn't exist, just skip it. continue; } $eventname = get_string('overridegroupeventname', 'lesson', $params); // Set group override priority. if ($grouppriorities !== null) { $openpriorities = $grouppriorities['open']; if (isset($openpriorities[$available])) { $event->priority = $openpriorities[$available]; } } } else if ($userid) { // User override event. $params = new stdClass(); $params->lesson = $lesson->name; $eventname = get_string('overrideusereventname', 'lesson', $params); // Set user override priority. $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY; } else { // The parent event. $eventname = $lesson->name; } if ($addopen or $addclose) { // Separate start and end events. $event->timeduration = 0; if ($available && $addopen) { if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname.' ('.get_string('lessonopens', 'lesson').')'; // The method calendar_event::create will reuse a db record if the id field is set. calendar_event::create($event); } if ($deadline && $addclose) { if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname.' ('.get_string('lessoncloses', 'lesson').')'; $event->timestart = $deadline; $event->eventtype = 'close'; if ($groupid && $grouppriorities !== null) { $closepriorities = $grouppriorities['close']; if (isset($closepriorities[$deadline])) { $event->priority = $closepriorities[$deadline]; } } calendar_event::create($event); } } } // Delete any leftover events. foreach ($oldevents as $badevent) { $badevent = calendar_event::load($badevent); $badevent->delete(); } } /** * Calculates the priorities of timeopen and timeclose values for group overrides for a lesson. * * @param int $lessonid The quiz ID. * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides. */ function lesson_get_group_override_priorities($lessonid) { global $DB; // Fetch group overrides. $where = 'lessonid = :lessonid AND groupid IS NOT NULL'; $params = ['lessonid' => $lessonid]; $overrides = $DB->get_records_select('lesson_overrides', $where, $params, '', 'id, groupid, available, deadline'); if (!$overrides) { return null; } $grouptimeopen = []; $grouptimeclose = []; foreach ($overrides as $override) { if ($override->available !== null && !in_array($override->available, $grouptimeopen)) { $grouptimeopen[] = $override->available; } if ($override->deadline !== null && !in_array($override->deadline, $grouptimeclose)) { $grouptimeclose[] = $override->deadline; } } // Sort open times in descending manner. The earlier open time gets higher priority. rsort($grouptimeopen); // Set priorities. $opengrouppriorities = []; $openpriority = 1; foreach ($grouptimeopen as $timeopen) { $opengrouppriorities[$timeopen] = $openpriority++; } // Sort close times in ascending manner. The later close time gets higher priority. sort($grouptimeclose); // Set priorities. $closegrouppriorities = []; $closepriority = 1; foreach ($grouptimeclose as $timeclose) { $closegrouppriorities[$timeclose] = $closepriority++; } return [ 'open' => $opengrouppriorities, 'close' => $closegrouppriorities ]; } /** * This standard function will check all instances of this module * and make sure there are up-to-date events created for each of them. * If courseid = 0, then every lesson event in the site is checked, else * only lesson events belonging to the course specified are checked. * This function is used, in its new format, by restore_refresh_events() * * @param int $courseid * @return bool */ function lesson_refresh_events($courseid = 0) { global $DB; if ($courseid == 0) { if (!$lessons = $DB->get_records('lesson')) { return true; } } else { if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) { return true; } } foreach ($lessons as $lesson) { lesson_update_events($lesson); } return true; } /** * Given an ID of an instance of this module, * this function will permanently delete the instance * and any data that depends on it. * * @global object * @param int $id * @return bool */ function lesson_delete_instance($id) { global $DB, $CFG; require_once($CFG->dirroot . '/mod/lesson/locallib.php'); $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST); $lesson = new lesson($lesson); return $lesson->delete(); } /** * Return a small object with summary information about what a * user has done with a given particular instance of this module * Used for user activity reports. * $return->time = the time they did it * $return->info = a short text description * * @global object * @param object $course * @param object $user * @param object $mod * @param object $lesson * @return object */ function lesson_user_outline($course, $user, $mod, $lesson) { global $CFG, $DB; require_once("$CFG->libdir/gradelib.php"); $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id); $return = new stdClass(); if (empty($grades->items[0]->grades)) { $return->info = get_string("nolessonattempts", "lesson"); } else { $grade = reset($grades->items[0]->grades); if (empty($grade->grade)) { // Check to see if it an ungraded / incomplete attempt. $sql = "SELECT * FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid ORDER BY starttime DESC"; $params = array('lessonid' => $lesson->id, 'userid' => $user->id); if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) { $attempt = reset($attempts); if ($attempt->completed) { $return->info = get_string("completed", "lesson"); } else { $return->info = get_string("notyetcompleted", "lesson"); } $return->time = $attempt->lessontime; } else { $return->info = get_string("nolessonattempts", "lesson"); } } else { $return->info = get_string("grade") . ': ' . $grade->str_long_grade; // Datesubmitted == time created. dategraded == time modified or time overridden. // If grade was last modified by the user themselves use date graded. Otherwise use date submitted. // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704. if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) { $return->time = $grade->dategraded; } else { $return->time = $grade->datesubmitted; } } } return $return; } /** * Print a detailed representation of what a user has done with * a given particular instance of this module, for user activity reports. * * @global object * @param object $course * @param object $user * @param object $mod * @param object $lesson * @return bool */ function lesson_user_complete($course, $user, $mod, $lesson) { global $DB, $OUTPUT, $CFG; require_once("$CFG->libdir/gradelib.php"); $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id); // Display the grade and feedback. if (empty($grades->items[0]->grades)) { echo $OUTPUT->container(get_string("nolessonattempts", "lesson")); } else { $grade = reset($grades->items[0]->grades); if (empty($grade->grade)) { // Check to see if it an ungraded / incomplete attempt. $sql = "SELECT * FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid ORDER by starttime desc"; $params = array('lessonid' => $lesson->id, 'userid' => $user->id); if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) { if ($attempt->completed) { $status = get_string("completed", "lesson"); } else { $status = get_string("notyetcompleted", "lesson"); } } else { $status = get_string("nolessonattempts", "lesson"); } } else { $status = get_string("grade") . ': ' . $grade->str_long_grade; } // Display the grade or lesson status if there isn't one. echo $OUTPUT->container($status); if ($grade->str_feedback) { echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback); } } // Display the lesson progress. // Attempt, pages viewed, questions answered, correct answers, time. $params = array ("lessonid" => $lesson->id, "userid" => $user->id); $attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen"); $branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen"); if (!empty($attempts) or !empty($branches)) { echo $OUTPUT->box_start(); $table = new html_table(); // Table Headings. $table->head = array (get_string("attemptheader", "lesson"), get_string("totalpagesviewedheader", "lesson"), get_string("numberofpagesviewedheader", "lesson"), get_string("numberofcorrectanswersheader", "lesson"), get_string("time")); $table->width = "100%"; $table->align = array ("center", "center", "center", "center", "center"); $table->size = array ("*", "*", "*", "*", "*"); $table->cellpadding = 2; $table->cellspacing = 0; $retry = 0; $nquestions = 0; $npages = 0; $ncorrect = 0; // Filter question pages (from lesson_attempts). foreach ($attempts as $attempt) { if ($attempt->retry == $retry) { $npages++; $nquestions++; if ($attempt->correct) { $ncorrect++; } $timeseen = $attempt->timeseen; } else { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); $retry++; $nquestions = 1; $npages = 1; if ($attempt->correct) { $ncorrect = 1; } else { $ncorrect = 0; } } } // Filter content pages (from lesson_branch). foreach ($branches as $branch) { if ($branch->retry == $retry) { $npages++; $timeseen = $branch->timeseen; } else { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); $retry++; $npages = 1; } } if ($npages > 0) { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); } echo html_writer::table($table); echo $OUTPUT->box_end(); } return true; } /** * Prints lesson summaries on MyMoodle Page * * Prints lesson name, due date and attempt information on * lessons that have a deadline that has not already passed * and it is available for taking. * * @global object * @global stdClass * @global object * @uses CONTEXT_MODULE * @param array $courses An array of course objects to get lesson instances from * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output ) * @return void */ function lesson_print_overview($courses, &$htmlarray) { global $USER, $CFG, $DB, $OUTPUT; if (!$lessons = get_all_instances_in_courses('lesson', $courses)) { return; } // Get all of the current users attempts on all lessons. $params = array($USER->id); $sql = 'SELECT lessonid, userid, count(userid) as attempts FROM {lesson_grades} WHERE userid = ? GROUP BY lessonid, userid'; $allattempts = $DB->get_records_sql($sql, $params); $completedattempts = array(); foreach ($allattempts as $myattempt) { $completedattempts[$myattempt->lessonid] = $myattempt->attempts; } // Get the current course ID. $listoflessons = array(); foreach ($lessons as $lesson) { $listoflessons[] = $lesson->id; } // Get the last page viewed by the current user for every lesson in this course. list($insql, $inparams) = $DB->get_in_or_equal($listoflessons, SQL_PARAMS_NAMED); $dbparams = array_merge($inparams, array('userid' => $USER->id)); // Get the lesson attempts for the user that have the maximum 'timeseen' value. $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.answerid as nextpageid, p.qtype "; $from = "FROM {lesson_attempts} l JOIN ( SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id FROM {lesson_attempts} idselect JOIN ( SELECT lessonid, userid, MAX(timeseen) AS timeseen FROM {lesson_attempts} WHERE userid = :userid AND lessonid $insql GROUP BY userid, lessonid ) timeselect ON timeselect.timeseen = idselect.timeseen AND timeselect.userid = idselect.userid AND timeselect.lessonid = idselect.lessonid GROUP BY idselect.userid, idselect.lessonid ) aid ON l.id = aid.id JOIN {lesson_pages} p ON l.pageid = p.id "; $lastattempts = $DB->get_records_sql($select . $from, $dbparams); // Now, get the lesson branches for the user that have the maximum 'timeseen' value. $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.nextpageid, p.qtype "; $from = str_replace('{lesson_attempts}', '{lesson_branch}', $from); $lastbranches = $DB->get_records_sql($select . $from, $dbparams); $lastviewed = array(); foreach ($lastattempts as $lastattempt) { $lastviewed[$lastattempt->lessonid] = $lastattempt; } // Go through the branch times and record the 'timeseen' value if it doesn't exist // for the lesson, or replace it if it exceeds the current recorded time. foreach ($lastbranches as $lastbranch) { if (!isset($lastviewed[$lastbranch->lessonid])) { $lastviewed[$lastbranch->lessonid] = $lastbranch; } else if ($lastviewed[$lastbranch->lessonid]->timeseen < $lastbranch->timeseen) { $lastviewed[$lastbranch->lessonid] = $lastbranch; } } // Since we have lessons in this course, now include the constants we need. require_once($CFG->dirroot . '/mod/lesson/locallib.php'); $now = time(); foreach ($lessons as $lesson) { if ($lesson->deadline != 0 // The lesson has a deadline and $lesson->deadline >= $now // And it is before the deadline has been met and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available // Visibility. $class = (!$lesson->visible) ? 'dimmed' : ''; // Context. $context = context_module::instance($lesson->coursemodule); // Link to activity. $url = new moodle_url('/mod/lesson/view.php', array('id' => $lesson->coursemodule)); $url = html_writer::link($url, format_string($lesson->name, true, array('context' => $context)), array('class' => $class)); $str = $OUTPUT->box(get_string('lessonname', 'lesson', $url), 'name'); // Deadline. $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info'); // Attempt information. if (has_capability('mod/lesson:manage', $context)) { // This is a teacher, Get the Number of user attempts. $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id)); $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // This is a student, See if the user has at least started the lesson. if (isset($lastviewed[$lesson->id]->timeseen)) { // See if the user has finished this attempt. if (isset($completedattempts[$lesson->id]) && ($completedattempts[$lesson->id] == ($lastviewed[$lesson->id]->retry + 1))) { // Are additional attempts allowed? if ($lesson->retake) { // User can retake the lesson. $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // User has completed the lesson and no retakes are allowed. $str = ''; } } else { // The last attempt was not finished or the lesson does not contain questions. // See if the last page viewed was a branchtable. require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php'); if ($lastviewed[$lesson->id]->qtype == LESSON_PAGE_BRANCHTABLE) { // See if the next pageid is the end of lesson. if ($lastviewed[$lesson->id]->nextpageid == LESSON_EOL) { // The last page viewed was the End of Lesson. if ($lesson->retake) { // User can retake the lesson. $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // User has completed the lesson and no retakes are allowed. $str = ''; } } else { // The last page viewed was NOT the end of lesson. $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } else { // Last page was a question page, so the attempt is not completed yet. $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } } else { // User has not yet started this lesson. $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } if (!empty($str)) { if (empty($htmlarray[$lesson->course]['lesson'])) { $htmlarray[$lesson->course]['lesson'] = $str; } else { $htmlarray[$lesson->course]['lesson'] .= $str; } } } } } /** * Function to be run periodically according to the moodle cron * This function searches for things that need to be done, such * as sending out mail, toggling flags etc ... * @global stdClass * @return bool true */ function lesson_cron () { global $CFG; return true; } /** * Return grade for given user or all users. * * @global stdClass * @global object * @param int $lessonid id of lesson * @param int $userid optional user id, 0 means all users * @return array array of grades */ function lesson_get_user_grades($lesson, $userid=0) { global $CFG, $DB; $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id); if (!empty($userid)) { $params["userid"] = $userid; $params["userid2"] = $userid; $user = "AND u.id = :userid"; $fuser = "AND uu.id = :userid2"; } else { $user=""; $fuser=""; } if ($lesson->retake) { if ($lesson->usemaxgrade) { $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade FROM {user} u, {lesson_grades} g WHERE u.id = g.userid AND g.lessonid = :lessonid $user GROUP BY u.id"; } else { $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade FROM {user} u, {lesson_grades} g WHERE u.id = g.userid AND g.lessonid = :lessonid $user GROUP BY u.id"; } unset($params['lessonid2']); unset($params['userid2']); } else { // use only first attempts (with lowest id in lesson_grades table) $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted FROM {user} uu, {lesson_grades} gg WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2 $fuser GROUP BY uu.id"; $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade FROM {user} u, {lesson_grades} g, ($firstonly) f WHERE u.id = g.userid AND g.lessonid = :lessonid AND g.id = f.firstcompleted AND g.userid=f.userid $user"; } return $DB->get_records_sql($sql, $params); } /** * Update grades in central gradebook * * @category grade * @param object $lesson * @param int $userid specific user only, 0 means all * @param bool $nullifnone */ function lesson_update_grades($lesson, $userid=0, $nullifnone=true) { global $CFG, $DB; require_once($CFG->libdir.'/gradelib.php'); if ($lesson->grade == 0 || $lesson->practice) { lesson_grade_item_update($lesson); } else if ($grades = lesson_get_user_grades($lesson, $userid)) { lesson_grade_item_update($lesson, $grades); } else if ($userid and $nullifnone) { $grade = new stdClass(); $grade->userid = $userid; $grade->rawgrade = null; lesson_grade_item_update($lesson, $grade); } else { lesson_grade_item_update($lesson); } } /** * Create grade item for given lesson * * @category grade * @uses GRADE_TYPE_VALUE * @uses GRADE_TYPE_NONE * @param object $lesson object with extra cmidnumber * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook * @return int 0 if ok, error code otherwise */ function lesson_grade_item_update($lesson, $grades=null) { global $CFG; if (!function_exists('grade_update')) { //workaround for buggy PHP versions require_once($CFG->libdir.'/gradelib.php'); } if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber); } else { $params = array('itemname'=>$lesson->name); } if (!$lesson->practice and $lesson->grade > 0) { $params['gradetype'] = GRADE_TYPE_VALUE; $params['grademax'] = $lesson->grade; $params['grademin'] = 0; } else if (!$lesson->practice and $lesson->grade < 0) { $params['gradetype'] = GRADE_TYPE_SCALE; $params['scaleid'] = -$lesson->grade; // Make sure current grade fetched correctly from $grades $currentgrade = null; if (!empty($grades)) { if (is_array($grades)) { $currentgrade = reset($grades); } else { $currentgrade = $grades; } } // When converting a score to a scale, use scale's grade maximum to calculate it. if (!empty($currentgrade) && $currentgrade->rawgrade !== null) { $grade = grade_get_grades($lesson->course, 'mod', 'lesson', $lesson->id, $currentgrade->userid); $params['grademax'] = reset($grade->items)->grademax; } } else { $params['gradetype'] = GRADE_TYPE_NONE; } if ($grades === 'reset') { $params['reset'] = true; $grades = null; } else if (!empty($grades)) { // Need to calculate raw grade (Note: $grades has many forms) if (is_object($grades)) { $grades = array($grades->userid => $grades); } else if (array_key_exists('userid', $grades)) { $grades = array($grades['userid'] => $grades); } foreach ($grades as $key => $grade) { if (!is_array($grade)) { $grades[$key] = $grade = (array) $grade; } //check raw grade isnt null otherwise we erroneously insert a grade of 0 if ($grade['rawgrade'] !== null) { $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100); } else { //setting rawgrade to null just in case user is deleting a grade $grades[$key]['rawgrade'] = null; } } } return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params); } /** * List the actions that correspond to a view of this module. * This is used by the participation report. * * Note: This is not used by new logging system. Event with * crud = 'r' and edulevel = LEVEL_PARTICIPATING will * be considered as view action. * * @return array */ function lesson_get_view_actions() { return array('view','view all'); } /** * List the actions that correspond to a post of this module. * This is used by the participation report. * * Note: This is not used by new logging system. Event with * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING * will be considered as post action. * * @return array */ function lesson_get_post_actions() { return array('end','start'); } /** * Runs any processes that must run before * a lesson insert/update * * @global object * @param object $lesson Lesson form data * @return void **/ function lesson_process_pre_save(&$lesson) { global $DB; $lesson->timemodified = time(); if (empty($lesson->timelimit)) { $lesson->timelimit = 0; } if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) { $lesson->timespent = 0; } if (!isset($lesson->completed)) { $lesson->completed = 0; } if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) { $lesson->gradebetterthan = 0; } else if ($lesson->gradebetterthan > 100) { $lesson->gradebetterthan = 100; } if (empty($lesson->width)) { $lesson->width = 640; } if (empty($lesson->height)) { $lesson->height = 480; } if (empty($lesson->bgcolor)) { $lesson->bgcolor = '#FFFFFF'; } // Conditions for dependency $conditions = new stdClass; $conditions->timespent = $lesson->timespent; $conditions->completed = $lesson->completed; $conditions->gradebetterthan = $lesson->gradebetterthan; $lesson->conditions = serialize($conditions); unset($lesson->timespent); unset($lesson->completed); unset($lesson->gradebetterthan); if (empty($lesson->password)) { unset($lesson->password); } } /** * Runs any processes that must be run * after a lesson insert/update * * @global object * @param object $lesson Lesson form data * @return void **/ function lesson_process_post_save(&$lesson) { // Update the events relating to this lesson. lesson_update_events($lesson); } /** * Implementation of the function for printing the form elements that control * whether the course reset functionality affects the lesson. * * @param $mform form passed by reference */ function lesson_reset_course_form_definition(&$mform) { $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson')); $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson')); $mform->addElement('advcheckbox', 'reset_lesson_user_overrides', get_string('removealluseroverrides', 'lesson')); $mform->addElement('advcheckbox', 'reset_lesson_group_overrides', get_string('removeallgroupoverrides', 'lesson')); } /** * Course reset form defaults. * @param object $course * @return array */ function lesson_reset_course_form_defaults($course) { return array('reset_lesson' => 1, 'reset_lesson_group_overrides' => 1, 'reset_lesson_user_overrides' => 1); } /** * Removes all grades from gradebook * * @global stdClass * @global object * @param int $courseid * @param string optional type */ function lesson_reset_gradebook($courseid, $type='') { global $CFG, $DB; $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid FROM {lesson} l, {course_modules} cm, {modules} m WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course"; $params = array ("course" => $courseid); if ($lessons = $DB->get_records_sql($sql,$params)) { foreach ($lessons as $lesson) { lesson_grade_item_update($lesson, 'reset'); } } } /** * Actual implementation of the reset course functionality, delete all the * lesson attempts for course $data->courseid. * * @global stdClass * @global object * @param object $data the data submitted from the reset course. * @return array status array */ function lesson_reset_userdata($data) { global $CFG, $DB; $componentstr = get_string('modulenameplural', 'lesson'); $status = array(); if (!empty($data->reset_lesson)) { $lessonssql = "SELECT l.id FROM {lesson} l WHERE l.course=:course"; $params = array ("course" => $data->courseid); $lessons = $DB->get_records_sql($lessonssql, $params); // Get rid of attempts files. $fs = get_file_storage(); if ($lessons) { foreach ($lessons as $lessonid => $unused) { if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) { continue; } $context = context_module::instance($cm->id); $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses'); } } $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params); $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params); $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params); $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params); // remove all grades from gradebook if (empty($data->reset_gradebook_grades)) { lesson_reset_gradebook($data->courseid); } $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false); } // Remove user overrides. if (!empty($data->reset_lesson_user_overrides)) { $DB->delete_records_select('lesson_overrides', 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid)); $status[] = array( 'component' => $componentstr, 'item' => get_string('useroverridesdeleted', 'lesson'), 'error' => false); } // Remove group overrides. if (!empty($data->reset_lesson_group_overrides)) { $DB->delete_records_select('lesson_overrides', 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid)); $status[] = array( 'component' => $componentstr, 'item' => get_string('groupoverridesdeleted', 'lesson'), 'error' => false); } /// updating dates - shift may be negative too if ($data->timeshift) { $DB->execute("UPDATE {lesson_overrides} SET available = available + ? WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND available <> 0", array($data->timeshift, $data->courseid)); $DB->execute("UPDATE {lesson_overrides} SET deadline = deadline + ? WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND deadline <> 0", array($data->timeshift, $data->courseid)); shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid); $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false); } return $status; } /** * Returns all other caps used in module * @return array */ function lesson_get_extra_capabilities() { return array('moodle/site:accessallgroups'); } /** * @uses FEATURE_GROUPS * @uses FEATURE_GROUPINGS * @uses FEATURE_MOD_INTRO * @uses FEATURE_COMPLETION_TRACKS_VIEWS * @uses FEATURE_GRADE_HAS_GRADE * @uses FEATURE_GRADE_OUTCOMES * @param string $feature FEATURE_xx constant for requested feature * @return mixed True if module supports feature, false if not, null if doesn't know */ function lesson_supports($feature) { switch($feature) { case FEATURE_GROUPS: return true; case FEATURE_GROUPINGS: return true; case FEATURE_MOD_INTRO: return true; case FEATURE_COMPLETION_TRACKS_VIEWS: return true; case FEATURE_GRADE_HAS_GRADE: return true; case FEATURE_COMPLETION_HAS_RULES: return true; case FEATURE_GRADE_OUTCOMES: return true; case FEATURE_BACKUP_MOODLE2: return true; case FEATURE_SHOW_DESCRIPTION: return true; default: return null; } } /** * Obtains the automatic completion state for this lesson based on any conditions * in lesson settings. * * @param object $course Course * @param object $cm course-module * @param int $userid User ID * @param bool $type Type of comparison (or/and; can be used as return value if no conditions) * @return bool True if completed, false if not, $type if conditions not set. */ function lesson_get_completion_state($course, $cm, $userid, $type) { global $CFG, $DB; // Get lesson details. $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST); $result = $type; // Default return value. // If completion option is enabled, evaluate it and return true/false. if ($lesson->completionendreached) { $value = $DB->record_exists('lesson_timer', array( 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1)); if ($type == COMPLETION_AND) { $result = $result && $value; } else { $result = $result || $value; } } if ($lesson->completiontimespent != 0) { $duration = $DB->get_field_sql( "SELECT SUM(lessontime - starttime) FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid", array('userid' => $userid, 'lessonid' => $lesson->id)); if (!$duration) { $duration = 0; } if ($type == COMPLETION_AND) { $result = $result && ($lesson->completiontimespent < $duration); } else { $result = $result || ($lesson->completiontimespent < $duration); } } return $result; } /** * This function extends the settings navigation block for the site. * * It is safe to rely on PAGE here as we will only ever be within the module * context when this is called * * @param settings_navigation $settings * @param navigation_node $lessonnode */ function lesson_extend_settings_navigation($settings, $lessonnode) { global $PAGE, $DB; // We want to add these new nodes after the Edit settings node, and before the // Locally assigned roles node. Of course, both of those are controlled by capabilities. $keys = $lessonnode->get_children_key_list(); $beforekey = null; $i = array_search('modedit', $keys); if ($i === false and array_key_exists(0, $keys)) { $beforekey = $keys[0]; } else if (array_key_exists($i + 1, $keys)) { $beforekey = $keys[$i + 1]; } if (has_capability('mod/lesson:manageoverrides', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/overrides.php', array('cmid' => $PAGE->cm->id)); $node = navigation_node::create(get_string('groupoverrides', 'lesson'), new moodle_url($url, array('mode' => 'group')), navigation_node::TYPE_SETTING, null, 'mod_lesson_groupoverrides'); $lessonnode->add_node($node, $beforekey); $node = navigation_node::create(get_string('useroverrides', 'lesson'), new moodle_url($url, array('mode' => 'user')), navigation_node::TYPE_SETTING, null, 'mod_lesson_useroverrides'); $lessonnode->add_node($node, $beforekey); } if (has_capability('mod/lesson:edit', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id)); $lessonnode->add(get_string('preview', 'lesson'), $url); $editnode = $lessonnode->add(get_string('edit', 'lesson')); $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'collapsed')); $editnode->add(get_string('collapsed', 'lesson'), $url); $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'full')); $editnode->add(get_string('full', 'lesson'), $url); } if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) { $reportsnode = $lessonnode->add(get_string('reports', 'lesson')); $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview')); $reportsnode->add(get_string('overview', 'lesson'), $url); $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail')); $reportsnode->add(get_string('detailedstats', 'lesson'), $url); } if (has_capability('mod/lesson:grade', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id)); $lessonnode->add(get_string('manualgrading', 'lesson'), $url); } } /** * Get list of available import or export formats * * Copied and modified from lib/questionlib.php * * @param string $type 'import' if import list, otherwise export list assumed * @return array sorted list of import/export formats available */ function lesson_get_import_export_formats($type) { global $CFG; $fileformats = core_component::get_plugin_list("qformat"); $fileformatname=array(); foreach ($fileformats as $fileformat=>$fdir) { $format_file = "$fdir/format.php"; if (file_exists($format_file) ) { require_once($format_file); } else { continue; } $classname = "qformat_$fileformat"; $format_class = new $classname(); if ($type=='import') { $provided = $format_class->provide_import(); } else { $provided = $format_class->provide_export(); } if ($provided) { $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat); } } natcasesort($fileformatnames); return $fileformatnames; } /** * Serves the lesson attachments. Implements needed access control ;-) * * @package mod_lesson * @category files * @param stdClass $course course object * @param stdClass $cm course module object * @param stdClass $context context object * @param string $filearea file area * @param array $args extra arguments * @param bool $forcedownload whether or not force download * @param array $options additional options affecting the file serving * @return bool false if file not found, does not return if found - justsend the file */ function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) { global $CFG, $DB; if ($context->contextlevel != CONTEXT_MODULE) { return false; } $fileareas = lesson_get_file_areas(); if (!array_key_exists($filearea, $fileareas)) { return false; } if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) { return false; } require_course_login($course, true, $cm); if ($filearea === 'page_contents') { $pageid = (int)array_shift($args); if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args); } else if ($filearea === 'page_answers' || $filearea === 'page_responses') { $itemid = (int)array_shift($args); if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args); } else if ($filearea === 'essay_responses') { $itemid = (int)array_shift($args); if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args); } else if ($filearea === 'mediafile') { if (count($args) > 1) { // Remove the itemid when it appears to be part of the arguments. If there is only one argument // then it is surely the file name. The itemid is sometimes used to prevent browser caching. array_shift($args); } $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args); } else { return false; } $fs = get_file_storage(); if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) { return false; } // finally send the file send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security! } /** * Returns an array of file areas * * @package mod_lesson * @category files * @return array a list of available file areas */ function lesson_get_file_areas() { $areas = array(); $areas['page_contents'] = get_string('pagecontents', 'mod_lesson'); $areas['mediafile'] = get_string('mediafile', 'mod_lesson'); $areas['page_answers'] = get_string('pageanswers', 'mod_lesson'); $areas['page_responses'] = get_string('pageresponses', 'mod_lesson'); $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson'); return $areas; } /** * Returns a file_info_stored object for the file being requested here * * @package mod_lesson * @category files * @global stdClass $CFG * @param file_browse $browser file browser instance * @param array $areas file areas * @param stdClass $course course object * @param stdClass $cm course module object * @param stdClass $context context object * @param string $filearea file area * @param int $itemid item ID * @param string $filepath file path * @param string $filename file name * @return file_info_stored */ function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { global $CFG, $DB; if (!has_capability('moodle/course:managefiles', $context)) { // No peaking here for students! return null; } // Mediafile area does not have sub directories, so let's select the default itemid to prevent // the user from selecting a directory to access the mediafile content. if ($filearea == 'mediafile' && is_null($itemid)) { $itemid = 0; } if (is_null($itemid)) { return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea); } $fs = get_file_storage(); $filepath = is_null($filepath) ? '/' : $filepath; $filename = is_null($filename) ? '.' : $filename; if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) { return null; } $itemname = $filearea; if ($filearea == 'page_contents') { $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance, 'id' => $itemid)); $itemname = format_string($itemname, true, array('context' => $context)); } else { $areas = lesson_get_file_areas(); if (isset($areas[$filearea])) { $itemname = $areas[$filearea]; } } $urlbase = $CFG->wwwroot . '/pluginfile.php'; return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false); } /** * Return a list of page types * @param string $pagetype current page type * @param stdClass $parentcontext Block's parent context * @param stdClass $currentcontext Current context of block */ function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) { $module_pagetype = array( 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'), 'mod-lesson-view'=>get_string('page-mod-lesson-view', 'lesson'), 'mod-lesson-edit'=>get_string('page-mod-lesson-edit', 'lesson')); return $module_pagetype; } /** * Update the lesson activity to include any file * that was uploaded, or if there is none, set the * mediafile field to blank. * * @param int $lessonid the lesson id * @param stdClass $context the context * @param int $draftitemid the draft item */ function lesson_update_media_file($lessonid, $context, $draftitemid) { global $DB; // Set the filestorage object. $fs = get_file_storage(); // Save the file if it exists that is currently in the draft area. file_save_draft_area_files($draftitemid, $context->id, 'mod_lesson', 'mediafile', 0); // Get the file if it exists. $files = $fs->get_area_files($context->id, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false); // Check that there is a file to process. if (count($files) == 1) { // Get the first (and only) file. $file = reset($files); // Set the mediafile column in the lessons table. $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid)); } else { // Set the mediafile column in the lessons table. $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid)); } } /** * Get icon mapping for font-awesome. */ function mod_lesson_get_fontawesome_icon_map() { return [ 'mod_lesson:e/copy' => 'fa-clone', ]; }
fwsl/moodle
mod/lesson/lib.php
PHP
gpl-3.0
55,138
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_7Z_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Archive/File_7z.h" //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Buffer - File header //*************************************************************************** //--------------------------------------------------------------------------- bool File_7z::FileHeader_Begin() { // Minimum buffer size if (Buffer_Size<6) return false; // Must wait for more data // Testing if (Buffer[0]!=0x37 // "7z...." || Buffer[1]!=0x7A || Buffer[2]!=0xBC || Buffer[3]!=0xAF || Buffer[4]!=0x27 || Buffer[5]!=0x1C) { Reject("7-Zip"); return false; } // All should be OK... return true; } //*************************************************************************** // Buffer - Global //*************************************************************************** //--------------------------------------------------------------------------- void File_7z::Read_Buffer_Continue() { Skip_B6( "Magic"); Skip_XX(File_Size-6, "Data"); FILLING_BEGIN(); Accept("7-Zip"); Fill(Stream_General, 0, General_Format, "7-Zip"); Finish("7-Zip"); FILLING_END(); } } //NameSpace #endif //MEDIAINFO_7Z_YES
xucp/mpc_hc
src/thirdparty/MediaInfo/library/Source/MediaInfo/Archive/File_7z.cpp
C++
gpl-3.0
2,366
/* Class: Graphic.Ellipse Shape implementation of an ellipse. Author: Sébastien Gruhier, <http://www.xilinus.com> License: MIT-style license. See Also: <Shape> */ Graphic.Ellipse = Class.create(); Object.extend(Graphic.Ellipse.prototype, Graphic.Shape.prototype); // Keep parent initialize Graphic.Ellipse.prototype._shapeInitialize = Graphic.Shape.prototype.initialize; Object.extend(Graphic.Ellipse.prototype, { initialize: function(renderer) { this._shapeInitialize(renderer, "ellipse"); Object.extend(this.attributes, {cx: 0, cy: 0, rx: 0, ry: 0}) return this; }, getSize: function() { return {w: 2 * this.attributes.rx, h: 2 * this.attributes.ry} }, setSize: function(width, height) { var location = this.getLocation(); this._setAttributes({rx: width/2, ry: height/2}); this.setLocation(location.x, location.y); return this; }, getLocation: function() { return {x: this.attributes.cx - this.attributes.rx, y: this.attributes.cy - this.attributes.ry} }, setLocation: function(x, y) { this._setAttributes({cx: x + this.attributes.rx, cy: y + this.attributes.ry}); return this; } })
j9recurses/whirld
vendor/assets/components/cartagen/lib/prototype-graphic/src/shape/ellipse.js
JavaScript
gpl-3.0
1,191
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Setup\Module\Di\Compiler\Config; interface ModificationInterface { /** * Modifies input config * * @param array $config * @return array */ public function modify(array $config); }
rajmahesh/magento2-master
vendor/magento/magento2-base/setup/src/Magento/Setup/Module/Di/Compiler/Config/ModificationInterface.php
PHP
gpl-3.0
338
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Render an attempt at a HotPot quiz * Output format: hp_6 * * @package mod-hotpot * @copyright 2010 Gordon Bateson <gordon.bateson@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); // get parent class require_once($CFG->dirroot.'/mod/hotpot/attempt/hp/renderer.php'); /** * mod_hotpot_attempt_hp_6_renderer * * @copyright 2010 Gordon Bateson * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 */ class mod_hotpot_attempt_hp_6_renderer extends mod_hotpot_attempt_hp_renderer { /** * init * * @param xxx $hotpot */ function init($hotpot) { parent::init($hotpot); array_unshift($this->templatesfolders, 'mod/hotpot/attempt/hp/6/templates'); } /** * fix_headcontent_DragAndDrop for JMix and JMatch */ function fix_headcontent_DragAndDrop() { // replace one line functions that get and set positions of positionable elements $search = array( '/(?<=function CardGetL).*/', '/(?<=function CardGetT).*/', '/(?<=function CardGetW).*/', '/(?<=function CardGetH).*/', '/(?<=function CardGetB).*/', '/(?<=function CardGetR).*/', '/(?<=function CardSetL).*/', '/(?<=function CardSetT).*/', '/(?<=function CardSetW).*/', '/(?<=function CardSetH).*/', ); $replace = array( "(){return getOffset(this.elm, 'Left')}", "(){return getOffset(this.elm, 'Top')}", "(){return getOffset(this.elm, 'Width')}", "(){return getOffset(this.elm, 'Height')}", "(){return getOffset(this.elm, 'Bottom')}", "(){return getOffset(this.elm, 'Right')}", "(NewL){setOffset(this.elm, 'Left', NewL)}", "(NewT){setOffset(this.elm, 'Top', NewT)}", "(NewW){setOffset(this.elm, 'Width', NewW)}", "(NewH){setOffset(this.elm, 'Height', NewH)}" ); $this->headcontent = preg_replace($search, $replace, $this->headcontent, 1); } /** * fix_headcontent_rottmeier * * @param xxx $type (optional, default='') */ function fix_headcontent_rottmeier($type='') { switch ($type) { case 'dropdown': // adding missing brackets to call to Is_ExerciseFinished() in CheckAnswers() $search = '/(Finished\s*=\s*Is_ExerciseFinished)(;)/'; $this->headcontent = preg_replace($search, '$1()$2', $this->headcontent); break; case 'findit': // get position of last </style> tag and // insert CSS to make <b> and <em> tags bold // even within GapSpans added by javascript $search = '</style>'; if ($pos = strrpos($this->headcontent, $search)) { $insert = "\n" .'<!--[if IE 6]><style type="text/css">'."\n" .'span.GapSpan{'."\n" .' font-size:24px;'."\n" .'}'."\n" .'</style><![endif]-->'."\n" .'<style type="text/css">'."\n" .'b span.GapSpan,'."\n" .'em span.GapSpan{'."\n" .' font-weight:inherit;'."\n" .'}'."\n" .'</style>'."\n" ; $this->headcontent = substr_replace($this->headcontent, $insert, $pos + strlen($search), 0); } break; case 'jintro': // add TimeOver variable, so we can use standard detection of quiz completion if ($pos = strpos($this->headcontent, 'var Score = 0;')) { $insert = "var TimeOver = false;\n"; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } break; case 'jmemori': // add TimeOver variable, so we can use standard detection of quiz completion if ($pos = strpos($this->headcontent, 'var Score = 0;')) { $insert = "var TimeOver = false;\n"; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } // override table border collapse from standard Moodle styles if ($pos = strrpos($this->headcontent, '</style>')) { $insert = '' .'#'.$this->themecontainer.' form table'."\n" .'{'."\n" .' border-collapse: separate;'."\n" .' border-spacing: 2px;'."\n" .'}'."\n" ; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } break; } } /** * fix_bodycontent_rottmeier * * @param xxx $hideclozeform (optional, default=false) */ function fix_bodycontent_rottmeier($hideclozeform=false) { // fix left aligned instructions in Rottmeier-based formats // JCloze: DropDown, FindIt(a)+(b), JGloss // JMatch: JMemori $search = '/<p id="Instructions">(.*?)<\/p>/is'; $replace = '<div id="Instructions">$1</div>'; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); if ($hideclozeform) { // initially hide the Cloze text (so gaps are not revealed) $search = '/<(form id="Cloze" [^>]*)>/is'; $replace = '<$1 style="display:none;">'; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); } } /** * get_js_functionnames * * @return xxx */ function get_js_functionnames() { // return a comma-separated list of js functions to be "fixed". // Each function name requires an corresponding function called: // fix_js_{$name} return 'Client,ShowElements,GetViewportHeight,PageDim,TrimString,RemoveBottomNavBarForIE,StartUp,GetUserName,PreloadImages,ShowMessage,HideFeedback,SendResults,Finish,WriteToInstructions,ShowSpecialReadingForQuestion'; } /** * fix_js_Client * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_Client(&$str, $start, $length) { $substr = substr($str, $start, $length); // refine detection of Chrome browser $search = 'this.geckoVer < 20020000'; if ($pos = strpos($substr, $search)) { $substr = substr_replace($substr, 'this.geckoVer > 10000000 && ', $pos, 0); } // add detection of Chrome browser $search = '/(\s*)if \(this\.min == false\)\{/s'; $replace = '$1' ."this.chrome = (this.ua.indexOf('Chrome') > 0);".'$1' ."if (this.chrome) {".'$1' ." this.geckoVer = 0;".'$1' ." this.safari = false;".'$1' ." this.min = true;".'$1' ."}$0" ; $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_ShowElements * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_ShowElements(&$str, $start, $length) { $substr = substr($str, $start, $length); // hide <embed> tags (required for Chrome browser) if ($pos = strpos($substr, 'TagName == "object"')) { $substr = substr_replace($substr, 'TagName == "embed" || ', $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_PageDim * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_PageDim(&$str, $start, $length) { if ($this->usemoodletheme) { $obj = "document.getElementById('$this->themecontainer')"; // moodle } else { $obj = "document.getElementsByTagName('body')[0]"; // original } $replace = '' ."function getStyleValue(obj, property_name, propertyName){\n" ." var value = 0;\n" ." // Watch out for HTMLDocument which has no style property\n" ." // as this causes errors later in getComputedStyle() in FF\n" ." if (obj && obj.style){\n" ." // based on http://www.quirksmode.org/dom/getstyles.html\n" ." if (document.defaultView && document.defaultView.getComputedStyle){\n" ." // Firefox, Opera, Safari\n" ." value = document.defaultView.getComputedStyle(obj, null).getPropertyValue(property_name);\n" ." } else if (obj.currentStyle) {" ." // IE (and Opera)\n" ." value = obj.currentStyle[propertyName];\n" ." }\n" ." if (typeof(value)=='string'){\n" ." var r = new RegExp('([0-9.]*)([a-z]+)');\n" ." var m = value.match(r);\n" ." if (m){\n" ." switch (m[2]){\n" ." case 'em':\n" ." // as far as I can see, only IE needs this\n" ." // other browsers have getComputedStyle() in px\n" ." if (typeof(obj.EmInPx)=='undefined'){\n" ." var div = obj.parentNode.appendChild(document.createElement('div'));\n" ." div.style.margin = '0px';\n" ." div.style.padding = '0px';\n" ." div.style.border = 'none';\n" ." div.style.height = '1em';\n" ." obj.EmInPx = getOffset(div, 'Height');\n" ." obj.parentNode.removeChild(div);\n" ." }\n" ." value = parseFloat(m[1] * obj.EmInPx);\n" ." break;\n" ." case 'px':\n" ." value = parseFloat(m[1]);\n" ." break;\n" ." default:\n" ." value = 0;\n" ." }\n" ." } else {\n" ." value = 0 ;\n" ." }\n" ." } else {\n" ." value = 0;\n" ." }\n" ." }\n" ." return value;\n" ."}\n" ."function isStrict(){\n" ." return false;\n" ." if (typeof(window.cache_isStrict)=='undefined'){\n" ." if (document.compatMode) { // ie6+\n" ." window.cache_isStrict = (document.compatMode=='CSS1Compat');\n" ." } else if (document.doctype){\n" ." var s = document.doctype.systemId || document.doctype.name; // n6 OR ie5mac\n" ." window.cache_isStrict = (s && s.indexOf('strict.dtd') >= 0);\n" ." } else {\n" ." window.cache_isStrict = false;\n" ." }\n" ." }\n" ." return window.cache_isStrict;\n" ."}\n" ."function setOffset(obj, type, value){\n" ." if (! obj){\n" ." return false;\n" ." }\n" ."\n" ." switch (type){\n" ." case 'Right':\n" ." return setOffset(obj, 'Width', value - getOffset(obj, 'Left'));\n" ." case 'Bottom':\n" ." return setOffset(obj, 'Height', value - getOffset(obj, 'Top'));\n" ." }\n" ."\n" ." if (isStrict()){\n" ." // set arrays of p(roperties) and s(ub-properties)\n" ." var properties = new Array('margin', 'border', 'padding');\n" ." switch (type){\n" ." case 'Top':\n" ." var sides = new Array('Top');\n" ." break;\n" ." case 'Left':\n" ." var sides = new Array('Left');\n" ." break;\n" ." case 'Width':\n" ." var sides = new Array('Left', 'Right');\n" ." break;\n" ." case 'Height':\n" ." var sides = new Array('Top', 'Bottom');\n" ." break;\n" ." default:\n" ." return 0;\n" ." }\n" ." for (var p=0; p<properties.length; p++){\n" ." for (var s=0; s<sides.length; s++){\n" ." var propertyName = properties[p] + sides[s];\n" ." var property_name = properties[p] + '-' + sides[s].toLowerCase();\n" ." value -= getStyleValue(obj, property_name, propertyName);\n" ." }\n" ." }\n" ." value = Math.floor(value);\n" ." }\n" ." if (type=='Top' || type=='Left') {\n" ." value -= getOffset(obj.offsetParent, type);\n" ." }\n" ." if (obj.style) {\n" ." obj.style[type.toLowerCase()] = value + 'px';\n" ." }\n" ."}\n" ."function getOffset(obj, type){\n" ." if (! obj){\n" ." return 0;\n" ." }\n" ." switch (type){\n" ." case 'Width':\n" ." case 'Height':\n" ." return eval('(obj.offset'+type+'||0)');\n" ."\n" ." case 'Top':\n" ." case 'Left':\n" ." return eval('(obj.offset'+type+'||0) + getOffset(obj.offsetParent, type)');\n" ."\n" ." case 'Right':\n" ." return getOffset(obj, 'Left') + getOffset(obj, 'Width');\n" ."\n" ." case 'Bottom':\n" ." return getOffset(obj, 'Top') + getOffset(obj, 'Height');\n" ."\n" ." default:\n" ." return 0;\n" ." } // end switch\n" ."}\n" ."function PageDim(){\n" ." var obj = $obj;\n" ." this.W = getOffset(obj, 'Width');\n" ." this.H = getOffset(obj, 'Height');\n" ." this.Top = getOffset(obj, 'Top');\n" ." this.Left = getOffset(obj, 'Left');\n" ."}\n" ."function getClassAttribute(className, attributeName){\n" ." //based on http://www.shawnolson.net/a/503/\n" ." if (! document.styleSheets){\n" ." return null; // old browser\n" ." }\n" ." var css = document.styleSheets;\n" ." var rules = (document.all ? 'rules' : 'cssRules');\n" ." var regexp = new RegExp('\\\\.'+className+'\\\\b');\n" ." try {\n" ." var i_max = css.length;\n" ." } catch(err) {\n" ." var i_max = 0; // shouldn't happen !!\n" ." }\n" ." for (var i=0; i<i_max; i++){\n" ." try {\n" ." var ii_max = css[i][rules].length;\n" ." } catch(err) {\n" ." var ii_max = 0; // shouldn't happen !!\n" ." }\n" ." for (var ii=0; ii<ii_max; ii++){\n" ." if (! css[i][rules][ii].selectorText){\n" ." continue;\n" ." }\n" ." if (css[i][rules][ii].selectorText.match(regexp)){\n" ." if (css[i][rules][ii].style[attributeName]){\n" ." // class/attribute found\n" ." return css[i][rules][ii].style[attributeName];\n" ." }\n" ." }\n" ." }\n" ." }\n" ." // class/attribute not found\n" ." return null;\n" ."}\n" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_GetViewportHeight * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_GetViewportHeight(&$str, $start, $length) { $replace = '' ."function GetViewportSize(type){\n" ." if (eval('window.inner' + type)){\n" ." return eval('window.inner' + type);\n" ." }\n" ." if (document.documentElement){\n" ." if (eval('document.documentElement.client' + type)){\n" ." return eval('document.documentElement.client' + type);\n" ." }\n" ." }\n" ." if (document.body){\n" ." if (eval('document.body.client' + type)){\n" ." return eval('document.body.client' + type);\n" ." }\n" ." }\n" ." return 0;\n" ."}\n" ."function GetViewportHeight(){\n" ." return GetViewportSize('Height');\n" ."}\n" ."function GetViewportWidth(){\n" ." return GetViewportSize('Width');\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * remove_js_function * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @param xxx $function */ function remove_js_function(&$str, $start, $length, $function) { // remove this function $str = substr_replace($str, '', $start, $length); // remove all direct calls to this function $search = '/\s*'.$function.'\([^)]*\);/s'; $str = preg_replace($search, '', $str); } /** * fix_js_TrimString * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_TrimString(&$str, $start, $length) { $replace = '' ."function TrimString(InString){\n" ." if (typeof(InString)=='string'){\n" ." InString = InString.replace(new RegExp('^\\\\s+', 'g'), ''); // left\n" ." InString = InString.replace(new RegExp('\\\\s+$', 'g'), ''); // right\n" ." InString = InString.replace(new RegExp('\\\\s+', 'g'), ' '); // inner\n" ." }\n" ." return InString;\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_TypeChars * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_TypeChars(&$str, $start, $length) { if ($obj = $this->fix_js_TypeChars_obj()) { $substr = substr($str, $start, $length); if (strpos($substr, 'document.selection')===false) { $replace = '' ."function TypeChars(Chars){\n" .$this->fix_js_TypeChars_init() ." if ($obj==null || $obj.style.display=='none') {\n" ." return;\n" ." }\n" ." $obj.focus();\n" ." if (typeof($obj.selectionStart)=='number') {\n" ." // FF, Safari, Chrome, Opera\n" ." var startPos = $obj.selectionStart;\n" ." var endPos = $obj.selectionEnd;\n" ." $obj.value = $obj.value.substring(0, startPos) + Chars + $obj.value.substring(endPos);\n" ." var newPos = startPos + Chars.length;\n" ." $obj.setSelectionRange(newPos, newPos);\n" ." } else if (document.selection) {\n" ." // IE (tested on IE6, IE7, IE8)\n" ." var rng = document.selection.createRange();\n" ." rng.text = Chars;\n" ." rng = null; // prevent memory leak\n" ." } else {\n" ." // this browser can't insert text, so append instead\n" ." $obj.value += Chars;\n" ." }\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } } } /** * fix_js_TypeChars_init * * @return xxx */ function fix_js_TypeChars_init() { return ''; } /** * fix_js_TypeChars_obj * * @return xxx */ function fix_js_TypeChars_obj() { return ''; } /** * fix_js_SendResults * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_SendResults(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'SendResults'); } /** * fix_js_GetUserName * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_GetUserName(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'GetUserName'); } /** * fix_js_Finish * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_Finish(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'Finish'); } /** * fix_js_PreloadImages * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_PreloadImages(&$str, $start, $length) { $substr = substr($str, $start, $length); // fix issue in IE8 which sometimes doesn't have Image object in popups // http://moodle.org/mod/forum/discuss.php?d=134510 $search = "Imgs[i] = new Image();"; if ($pos = strpos($substr, $search)) { $replace = "Imgs[i] = (window.Image ? new Image() : document.createElement('img'));"; $substr = substr_replace($substr, $replace, $pos, strlen($search)); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_WriteToInstructions * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_WriteToInstructions(&$str, $start, $length) { $substr = substr($str, $start, $length); if ($pos = strpos($substr, '{')) { $insert = "\n" ." // check required HTML element exists\n" ." if (! document.getElementById('InstructionsDiv')) return false;\n" ; $substr = substr_replace($substr, $insert, $pos+1, 0); } if ($pos = strrpos($substr, '}')) { $append = "\n" ." StretchCanvasToCoverContent(true);\n" ; $substr = substr_replace($substr, $append, $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_ShowMessage * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_ShowMessage(&$str, $start, $length) { // the ShowMessage function is used by all HP6 quizzes $substr = substr($str, $start, $length); // only show feedback if the required HTML elements exist // this prevents JavaScript errors which block the returning of the quiz results to Moodle if ($pos = strpos($substr, '{')) { $insert = "\n" ." // check required HTML elements exist\n" ." if (! document.getElementById('FeedbackDiv')) return false;\n" ." if (! document.getElementById('FeedbackContent')) return false;\n" ." if (! document.getElementById('FeedbackOKButton')) return false;\n" ; $substr = substr_replace($substr, $insert, $pos+1, 0); } // hide <embed> elements on Chrome browser $search = "/(\s*)ShowElements\(true, 'object', 'FeedbackContent'\);/s"; $replace = '' ."$0".'$1' ."if (C.chrome) {".'$1' ." ShowElements(false, 'embed');".'$1' ." ShowElements(true, 'embed', 'FeedbackContent');".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); // fix "top" setting to position FeedbackDiv if ($this->usemoodletheme) { $canvas = "document.getElementById('$this->themecontainer')"; // moodle } else { $canvas = "document.getElementsByTagName('body')[0]"; // original } $search = "/FDiv.style.top = [^;]*;(\s*)(FDiv.style.display = [^;]*;)/s"; $replace = '' .'$1$2' .'$1'."var t = getOffset($canvas, 'Top');" .'$1'."setOffset(FDiv, 'Top', Math.max(t, TopSettingWithScrollOffset(30)));" ; $substr = preg_replace($search, $replace, $substr, 1); // append link to student feedback form, if necessary if ($this->hotpot->studentfeedback) { $search = '/(\s*)var Output = [^;]*;/'; $replace = '' ."$0".'$1' ."if (window.FEEDBACK) {".'$1' ." Output += '".'<a href="javascript:hpFeedback();">'."' + FEEDBACK[6] + '</a>';".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_RemoveBottomNavBarForIE * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_RemoveBottomNavBarForIE(&$str, $start, $length) { $replace = '' ."function RemoveBottomNavBarForIE(){\n" ." if (C.ie) {\n" ." if (document.getElementById('Reading')){\n" ." var obj = document.getElementById('BottomNavBar');\n" ." if (obj){\n" ." obj.parentNode.removeChild(obj);\n" ." }\n" ." }\n" ." }\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_StartUp_DragAndDrop * * @param xxx $substr (passed by reference) */ function fix_js_StartUp_DragAndDrop(&$substr) { // fixes for Drag and Drop (JMatch and JMix) } /** * fix_js_StartUp_DragAndDrop_DragArea * * @param xxx $substr (passed by reference) */ function fix_js_StartUp_DragAndDrop_DragArea(&$substr) { // fix LeftCol (=left side of drag area) $search = '/(LeftColPos = [^;]+);/'; $replace = '$1 + pg.Left;'; $substr = preg_replace($search, $replace, $substr, 1); // fix DragTop (=top side of Drag area) $search = '/DragTop = [^;]+;/'; $replace = "DragTop = getOffset(document.getElementById('CheckButtonDiv'),'Bottom') + 10;"; $substr = preg_replace($search, $replace, $substr, 1); } /** * fix_js_StartUp * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_StartUp(&$str, $start, $length) { $substr = substr($str, $start, $length); // if necessary, fix drag area for JMatch or JMix drag-and-drop $this->fix_js_StartUp_DragAndDrop($substr); if ($pos = strrpos($substr, '}')) { if ($this->hotpot->delay3==hotpot::TIME_DISABLE) { $forceajax = 1; } else { $forceajax = 0; } if ($this->can_continue()==hotpot::CONTINUE_RESUMEQUIZ) { $onunload_status = hotpot::STATUS_INPROGRESS; } else { $onunload_status = hotpot::STATUS_ABANDONED; } $append = "\n" ."// adjust size and position of Feedback DIV\n" ." if (! window.pg){\n" ." window.pg = new PageDim();\n" ." }\n" ." var FDiv = document.getElementById('FeedbackDiv');\n" ." if (FDiv){\n" ." var w = getOffset(FDiv, 'Width') || FDiv.style.width || getClassAttribute(FDiv.className, 'width');\n" ." if (w){\n" ." if (typeof(w)=='string' && w.indexOf('%')>=0){\n" ." var percent = parseInt(w);\n" ." } else {\n" ." var percent = Math.floor(100 * parseInt(w) / pg.W);\n" ." }\n" ." } else if (window.FeedbackWidth && window.DivWidth){\n" ." var percent = Math.floor(100 * FeedbackWidth / DivWidth);\n" ." } else {\n" ." var percent = 34; // default width as percentage\n" ." }\n" ." FDiv.style.display = 'block';\n" ." setOffset(FDiv, 'Left', pg.Left + Math.floor(pg.W * (50 - percent/2) / 100));\n" ." setOffset(FDiv, 'Width', Math.floor(pg.W * percent / 100));\n" ." FDiv.style.display = 'none';\n" ." }\n" ."\n" ."// create HP object (to collect and send responses)\n" ." window.HP = new ".$this->js_object_type."('".$this->can_clickreport()."','".$forceajax."');\n" ."\n" //."// call HP.onunload to send results when this page unloads\n" //." var s = '';\n" //." if (typeof(window.onunload)=='function'){\n" //." window.onunload_StartUp = onunload;\n" //." s += 'window.onunload_StartUp();'\n" //." }\n" //." window.onunload = new Function(s + 'if(window.HP){HP.status=$onunload_status;HP.onunload();object_destroy(HP);}return true;');\n" //."\n" ." window.onunload = function() {\n" ." if (window.HP) {\n" ." HP.status=$onunload_status;\n" ." HP.onunload();\n" ." object_destroy(HP);\n" ." }\n" ." return true;\n" ." }\n" ."\n" ; $substr = substr_replace($substr, $append, $pos, 0); } // stretch the canvas vertically down, if there is a reading if ($pos = strrpos($substr, '}')) { // Reading is contained in <div class="LeftContainer"> // MainDiv is contained in <div class="RightContainer"> // when there is a reading. Otherwise, MainDiv is not contained. // ReadingDiv is used to show different reading for each question if ($this->usemoodletheme) { $canvas = "document.getElementById('$this->themecontainer')"; // moodle } else { $canvas = "document.getElementsByTagName('body')[0]"; // original } // None: $canvas = "document.getElementById('page-mod-hotpot-attempt')" $id = $this->embed_object_id; $onload = $this->embed_object_onload; $insert = "\n" ."// fix canvas height, if necessary\n" ." if (! window.hotpot_mediafilter_loader){\n" ." StretchCanvasToCoverContent();\n" ." }\n" ."}\n" ."function StretchCanvasToCoverContent(skipTimeout){\n" ." if (! skipTimeout){\n" ." if (navigator.userAgent.indexOf('Firefox/3')>=0){\n" ." var millisecs = 1000;\n" ." } else {\n" ." var millisecs = 500;\n" ." }\n" ." setTimeout('StretchCanvasToCoverContent(true)', millisecs);\n" ." return;\n" ." }\n" ." var canvas = $canvas;\n" ." if (canvas){\n" ." var ids = new Array('Reading','ReadingDiv','MainDiv');\n" ." var i_max = ids.length;\n" ." for (var i=i_max-1; i>=0; i--){\n" ." var obj = document.getElementById(ids[i]);\n" ." if (obj){\n" ." obj.style.height = ''; // reset height\n" ." } else {\n" ." ids.splice(i, 1); // remove this id\n" ." i_max--;\n" ." }\n" ." }\n" ." var b = 0;\n" ." for (var i=0; i<i_max; i++){\n" ." var obj = document.getElementById(ids[i]);\n" ." b = Math.max(b, getOffset(obj,'Bottom'));\n" ." }\n" ." if (window.Segments) {\n" // JMix special ." var obj = document.getElementById('D'+(Segments.length-1));\n" ." if (obj) {\n" ." b = Math.max(b, getOffset(obj,'Bottom'));\n" ." }\n" ." }\n" ." if (b){\n" ." setOffset(canvas, 'Bottom', b + 21);\n" ." for (var i=0; i<i_max; i++){\n" ." var obj = document.getElementById(ids[i]);\n" ." setOffset(obj, 'Bottom', b);\n" ." }\n" ." }\n" ." }\n" ; if ($this->hotpot->navigation==hotpot::NAVIGATION_EMBED) { // stretch container object/iframe $insert .= '' ." if (parent.$onload) {\n" ." parent.$onload(null, parent.document.getElementById('".$this->embed_object_id."'));\n" ." }\n" ; } $substr = substr_replace($substr, $insert, $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_HideFeedback * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_HideFeedback(&$str, $start, $length) { global $CFG; $substr = substr($str, $start, $length); // unhide <embed> elements on Chrome browser $search = "/(\s*)ShowElements\(true, 'object'\);/s"; $replace = '' .'$0$1' ."if (C.chrome) {".'$1' ." ShowElements(true, 'embed');".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); $search = '/('.'\s*if \(Finished == true\){\s*)(?:.*?)(\s*})/s'; if ($this->hotpot->delay3==hotpot::TIME_AFTEROK) { // -1 : send form only (do not set form values, as that has already been done) $replace = '$1'.'HP.onunload(HP.status,-1);'.'$2'; } else { $replace = ''; // i.e. remove this if-block } $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_ShowSpecialReadingForQuestion * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_ShowSpecialReadingForQuestion(&$str, $start, $length) { $replace = '' ."function ShowSpecialReadingForQuestion(){\n" ." var ReadingDiv = document.getElementById('ReadingDiv');\n" ." if (ReadingDiv){\n" ." var ReadingText = null;\n" ." var divs = ReadingDiv.getElementsByTagName('div');\n" ." for (var i=0; i<divs.length; i++){\n" ." if (divs[i].className=='ReadingText' || divs[i].className=='TempReadingText'){\n" ." ReadingText = divs[i];\n" ." break;\n" ." }\n" ." }\n" ." if (ReadingText && HiddenReadingShown){\n" ." SwapReadingTexts(ReadingText, HiddenReadingShown);\n" ." ReadingText = HiddenReadingShown;\n" ." HiddenReadingShown = false;\n" ." }\n" ." var HiddenReading = null;\n" ." if (QArray[CurrQNum]){\n" ." var divs = QArray[CurrQNum].getElementsByTagName('div');\n" ." for (var i=0; i<divs.length; i++){\n" ." if (divs[i].className=='HiddenReading'){\n" ." HiddenReading = divs[i];\n" ." break;\n" ." }\n" ." }\n" ." }\n" ." if (HiddenReading){\n" ." if (! ReadingText){\n" ." ReadingText = document.createElement('div');\n" ." ReadingText.className = 'ReadingText';\n" ." ReadingDiv.appendChild(ReadingText);\n" ." }\n" ." SwapReadingTexts(ReadingText, HiddenReading);\n" ." HiddenReadingShown = ReadingText;\n" ." }\n" ." var btn = document.getElementById('ShowMethodButton');\n" ." if (btn){\n" ." if (HiddenReadingShown){\n" ." if (btn.style.display!='none'){\n" ." btn.style.display = 'none';\n" ." }\n" ." } else {\n" ." if (btn.style.display=='none'){\n" ." btn.style.display = '';\n" ." }\n" ." }\n" ." }\n" ." btn = null;\n" ." ReadingDiv = null;\n" ." ReadingText = null;\n" ." HiddenReading = null;\n" ." }\n" ."}\n" ."function SwapReadingTexts(ReadingText, HiddenReading) {\n" ." HiddenReadingParentNode = HiddenReading.parentNode;\n" ." HiddenReadingParentNode.removeChild(HiddenReading);\n" ."\n" ." // replaceChild(new_node, old_node)\n" ." ReadingText.parentNode.replaceChild(HiddenReading, ReadingText);\n" ."\n" ." if (HiddenReading.IsOriginalReadingText){\n" ." HiddenReading.className = 'ReadingText';\n" ." } else {\n" ." HiddenReading.className = 'TempReadingText';\n" ." }\n" ." HiddenReading.style.display = '';\n" ."\n" ." if (ReadingText.className=='ReadingText'){\n" ." ReadingText.IsOriginalReadingText = true;\n" ." } else {\n" ." ReadingText.IsOriginalReadingText = false;\n" ." }\n" ." ReadingText.style.display = 'none';\n" ." ReadingText.className = 'HiddenReading';\n" ."\n" ." HiddenReadingParentNode.appendChild(ReadingText);\n" ." HiddenReadingParentNode = null;\n" ."}\n" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_CheckAnswers * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_CheckAnswers(&$str, $start, $length) { // JCloze, JCross, JMatch : CheckAnswers // JMix : CheckAnswer // JQuiz : CheckFinished $substr = substr($str, $start, $length); // intercept Checks, if necessary if ($insert = $this->get_stop_function_intercept()) { if ($pos = strpos($substr, '{')) { $substr = substr_replace($substr, $insert, $pos+1, 0); } } // add extra argument to function - so it can be called from the "Give Up" button $name = $this->get_stop_function_name(); $search = '/(function '.$name.'\()(.*?)(\))/s'; $callback = array($this, 'fix_js_CheckAnswers_arguments'); $substr = preg_replace_callback($search, $callback, $substr, 1); // add call to Finish function (including QuizStatus) $search = $this->get_stop_function_search(); $replace = $this->get_stop_function_replace(); $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_CheckAnswers_arguments * * @param xxx $match * @return xxx */ function fix_js_CheckAnswers_arguments($match) { if (empty($match[2])) { return $match[1].'ForceQuizStatus'.$match[3]; } else { return $match[1].$match[2].',ForceQuizStatus'.$match[3]; } } /** * get_stop_onclick * * @return xxx */ function get_stop_onclick() { if ($name = $this->get_stop_function_name()) { return 'if('.$this->get_stop_function_confirm().')'.$name.'('.$this->get_stop_function_args().')'; } else { return 'if(window.HP)HP.onunload('.hotpot::STATUS_ABANDONED.')'; } } /** * get_stop_function_confirm * * @return xxx */ function get_stop_function_confirm() { // Note: "&&" in onclick must be encoded as html-entities for strict XHTML return '' ."confirm(" ."'".$this->hotpot->source->js_value_safe(get_string('confirmstop', 'hotpot'), true)."'" ."+'\\n\\n'+(window.onbeforeunload &amp;&amp; onbeforeunload()?(onbeforeunload()+'\\n\\n'):'')+" ."'".$this->hotpot->source->js_value_safe(get_string('pressoktocontinue', 'hotpot'), true)."'" .")" ; } /** * get_stop_function_name * * @return xxx */ function get_stop_function_name() { // the name of the javascript function into which the "give up" code should be inserted return ''; } /** * get_stop_function_args * * @return xxx */ function get_stop_function_args() { // the arguments required by the javascript function which the stop_function() code calls return hotpot::STATUS_ABANDONED; } /** * get_stop_function_intercept * * @return xxx */ function get_stop_function_intercept() { // JMix and JQuiz each have their own version of this function return "\n" ." // intercept this Check\n" ." HP.onclickCheck();\n" ; } /** * get_stop_function_search * * @return xxx */ function get_stop_function_search() { // JCloze : AllCorrect || Finished // JCross : AllCorrect || TimeOver // JMatch : AllDone || TimeOver // JMix : AllDone || TimeOver (in the CheckAnswer function) // JQuiz : AllDone (in the CheckFinished function) return '/\s*if \(\((\w+) == true\)\|\|\(\w+ == true\)\)({).*?}\s*/s'; } /** * get_stop_function_replace * * @return xxx */ function get_stop_function_replace() { // $1 : name of the "all correct/done" variable // $2 : opening curly brace of if-block plus any following text to be kept if ($this->hotpot->delay3==hotpot::TIME_AFTEROK) { $flag = 1; // set form values only } else { $flag = 0; // set form values and send form } if ($this->hotpot->delay3==hotpot::TIME_DISABLE) { $forceredirect = '(ForceQuizStatus ? 1 : 0)'; } else { $forceredirect = 1; } return "\n" ." if ($1){\n" ." var QuizStatus = 4; // completed\n" ." } else if (ForceQuizStatus){\n" ." var QuizStatus = ForceQuizStatus; // 3=abandoned\n" ." } else if (TimeOver){\n" ." var QuizStatus = 2; // timed out\n" ." } else {\n" ." var QuizStatus = 1; // in progress\n" ." }\n" ." if (QuizStatus > 1) $2\n" ." if (window.Interval) {\n" ." clearInterval(window.Interval);\n" ." }\n" ." TimeOver = true;\n" ." Locked = true;\n" ." Finished = true;\n" ." }\n" ." if (Finished || HP.sendallclicks){\n" ." var ForceRedirect = $forceredirect;\n" ." if (ForceQuizStatus || QuizStatus==1){\n" ." // send results immediately\n" ." HP.onunload(QuizStatus, 0, ForceRedirect);\n" ." } else {\n" ." // send results after delay\n" ." setTimeout('HP.onunload('+QuizStatus+',$flag,'+ForceRedirect+')', SubmissionTimeout);\n" ." }\n" ." }\n" ; } /** * postprocessing * * after headcontent and bodycontent have been setup and * before content is sent to browser, we add title edit icon, * insert submission form, adjust navigation butons (if any) * and add external javascripts (to the top of the page) */ function postprocessing() { $this->fix_title_icons(); $this->fix_submissionform(); $this->fix_navigation_buttons(); foreach ($this->javascripts as $script) { $this->page->requires->js('/'.$script, true); } } /** * fix_navigation_buttons * * @return xxx */ function fix_navigation_buttons() { if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL) { // replace relative URLs in <button class="NavButton" ... onclick="location='...'"> $search = '/'.'(?<='.'onclick="'."location='".')'."([^']*)".'(?='."'; return false;".'")'.'/is'; $callback = array($this, 'convert_url_navbutton'); $this->bodycontent = preg_replace_callback($search, $callback, $this->bodycontent); // replace history.back() in <button class="NavButton" ... onclick="history.back(); ..."> // with a link to the course page $params = array('id'=>$this->hotpot->course->id); $search = '/'.'(?<='.'onclick=")'.'history\.back\(\)'.'(?=; return false;")'.'/'; $replace = "location='".new moodle_url('/course/view.php', $params)."'"; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); } } /** * fix_TimeLimit */ function fix_TimeLimit() { if ($this->hotpot->timelimit > 0) { $search = '/(?<=var Seconds = )\d+(?=;)/'; $this->headcontent = preg_replace($search, $this->hotpot->timelimit, $this->headcontent, 1); } } /** * fix_SubmissionTimeout */ function fix_SubmissionTimeout() { if ($this->hotpot->delay3==hotpot::TIME_TEMPLATE) { // use default from source/template file (=30000 ms =30 seconds) if ($this->hasSubmissionTimeout) { $timeout = null; } else { $timeout = 30000; // = 30 secs is HP default } } else { if ($this->hotpot->delay3 >= 0) { $timeout = $this->hotpot->delay3 * 1000; // milliseconds } else { $timeout = 0; // i.e. immediately } } if (is_null($timeout)) { return; // nothing to do } if ($this->hasSubmissionTimeout) { // remove HPNStartTime $search = '/var HPNStartTime\b[^;]*?;\s*/'; $this->headcontent = preg_replace($search, '', $this->headcontent, 1); // reset the value of SubmissionTimeout $search = '/(?<=var SubmissionTimeout = )\d+(?=;)/'; $this->headcontent = preg_replace($search, $timeout, $this->headcontent, 1); } else { // Rhubarb, Sequitur and Quandary $search = '/var FinalScore = 0;/'; $replace = '$0'."\n".'var SubmissionTimeout = '.$timeout.';'; $this->headcontent = preg_replace($search, $replace, $this->headcontent, 1); } } /** * fix_navigation */ function fix_navigation() { if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL) { // do nothing - leave navigation as it is return; } // insert the stop button, if required if ($this->hotpot->stopbutton) { // replace top nav buttons with a single stop button if ($this->hotpot->stopbutton==hotpot::STOPBUTTON_LANGPACK) { if ($pos = strpos($this->hotpot->stoptext, '_')) { $mod = substr($this->hotpot->stoptext, 0, $pos); $str = substr($this->hotpot->stoptext, $pos + 1); $stoptext = get_string($str, $mod); } else if ($this->hotpot->stoptext) { $stoptext = get_string($this->hotpot->stoptext); } else { $stoptext = ''; } } else { $stoptext = $this->hotpot->stoptext; } if (trim($stoptext)=='') { $stoptext = get_string('giveup', 'hotpot'); } $confirm = get_string('confirmstop', 'hotpot'); //$search = '/<!-- BeginTopNavButtons -->'.'.*?'.'<!-- EndTopNavButtons -->/s'; $search = '/<(div class="Titles")>/s'; $replace = '<$1 style="position: relative">'."\n\t" .'<div class="hotpotstopbutton">' .'<button class="FuncButton" ' .'onclick="'.$this->get_stop_onclick().'" ' .'onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" ' .'onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" ' .'onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)">' .hotpot_textlib('utf8_to_entities', $stoptext) .'</button>' .'</div>' ; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent, 1); } // remove (remaining) navigation buttons $search = '/<!-- Begin(Top|Bottom)NavButtons -->'.'.*?'.'<!-- End'.'\\1'.'NavButtons -->/s'; $this->bodycontent = preg_replace($search, '', $this->bodycontent); } /** * fix_filters * * @return xxx */ function fix_filters() { global $CFG; if (isset($CFG->textfilters)) { $textfilters = $CFG->textfilters; } else { $textfilters = ''; } if ($this->hotpot->usefilters) { $filters = filter_get_active_in_context($this->hotpot->context); $filters = array_keys($filters); } else { $filters = array(); } if ($this->hotpot->useglossary && ! in_array('mod/glossary', $filters)) { $filters[] = 'mod/glossary'; } if ($this->hotpot->usemediafilter) { // exclude certain unnecessary or miscreant $filters // - "mediaplugins" because it duplicates work done by "usemediafilter" setting // - "asciimath" because it does not behave like a filter is supposed to behave $filters = preg_grep('/^filter\/(mediaplugin|asciimath)$/', $filters, PREG_GREP_INVERT); } $CFG->textfilters = implode(',', $filters); $this->filter_text_headcontent(); $this->filter_text_bodycontent(); $CFG->textfilters = $textfilters; // fix unwanted conversions by the Moodle's Tex filter // http://moodle.org/mod/forum/discuss.php?d=68435 // http://tracker.moodle.org/browse/MDL-7849 if (preg_match('/jcross|jmix/', get_class($this))) { $search = '/(?<=replace\(\/)'.'<a[^>]*><img[^>]*class="texrender"[^>]*title="(.*?)"[^>]*><\/a>'.'(?=\/g)/is'; $replace = '\['.'$1'.'\]'; $this->headcontent = preg_replace($search, $replace, $this->headcontent); } // make sure openpopup() function is available if needed (for glossary entries) // Note: this could also be done using filter_add_javascript($this->htmlcontent) // but that function expects entire htmlcontent, where we would prefer just the headcontent if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL && in_array('mod/glossary', $filters)) { // add openwindow() function (from lib/javascript.php) $this->headcontent .= "\n" .'<script type="text/javascript">'."\n" .'//<![CDATA['."\n" .'function openpopup(url, name, options, fullscreen) {'."\n" .' var fullurl = "'.$CFG->httpswwwroot.'" + url;'."\n" .' var windowobj = window.open(fullurl, name, options);'."\n" .' if (!windowobj) {'."\n" .' return true;'."\n" .' }'."\n" .' if (fullscreen) {'."\n" .' windowobj.moveTo(0, 0);'."\n" .' windowobj.resizeTo(screen.availWidth, screen.availHeight);'."\n" .' }'."\n" .' windowobj.focus();'."\n" .' return false;'."\n" .'}'."\n" .'//]]>'."\n" .'</script>' ; } } /** * filter_text_headcontent */ function filter_text_headcontent() { if ($names = $this->headcontent_strings) { $search = '/^'."((?:var )?(?:$names)(?:\[\d+\])*\s*=\s*')(.*)(';)".'$/m'; $callback = array($this, 'filter_text_headcontent_string'); $this->headcontent = preg_replace_callback($search, $callback, $this->headcontent); } if ($names = $this->headcontent_arrays) { $search = '/^'."((?:var )?(?:$names)(?:\[\d+\])* = new Array\()(.*)(\);)".'$/m'; $callback = array($this, 'filter_text_headcontent_array'); $this->headcontent = preg_replace_callback($search, $callback, $this->headcontent); } } /** * filter_text_headcontent_array * * @param xxx $match * @return xxx */ function filter_text_headcontent_array($match) { // I[q][0][a] = new Array('JQuiz answer text', 'feedback', 0, 0, 0) $before = $match[1]; $str = $match[count($match) - 2]; $after = $match[count($match) - 1]; $search = "/(')((?:\\\\\\\\|\\\\'|[^'])*)(')/"; $callback = array($this, 'filter_text_headcontent_string'); return $before.preg_replace_callback($search, $callback, $str).$after; } /** * filter_text_headcontent_string * * @param xxx $match * @return xxx */ function filter_text_headcontent_string($match) { // var YourScoreIs = 'Your score is'; // I[q][1][a][2] = 'JCloze clue'; global $CFG; static $replace_pairs = array( // backslashes and quotes '\\\\'=>'\\', "\\'"=>"'", '\\"'=>'"', // newlines '\\n'=>"\n", // other (closing tag is for XHTML compliance) '\\0'=>"\0", '<\\/'=>'</' ); $before = $match[1]; $str = $match[count($match) - 2]; $after = $match[count($match) - 1]; // unescape backslashes, quote and newlines $str = strtr($str, $replace_pairs); // convert javascript unicode $search = '/\\\\u([0-9a-f]{4})/i'; $str = $this->filter_text_to_utf8($str, $search); // convert html entities $search = '/&#x([0-9a-f]+);/i'; $str = $this->filter_text_to_utf8($str, $search); // fix relative urls $str = $this->fix_relativeurls($str); // filter string, // $str = filter_text($str); // return safe javascript unicode return $before.$this->hotpot->source->js_value_safe($str, true).$after; } /** * filter_text_bodycontent * * @param xxx $str * @param xxx $search * @return string $str * @return boolean $modified */ function filter_text_to_utf8($str, $search) { if (preg_match_all($search, $str, $matches, PREG_OFFSET_CAPTURE)) { $i_max = count($matches[0]) - 1; for ($i=$i_max; $i>=0; $i--) { list($match, $start) = $matches[0][$i]; $char = $matches[1][$i][0]; $char = hotpot_textlib('code2utf8', hexdec($char)); $str = substr_replace($str, $char, $start, strlen($match)); } } return $str; } /** * filter_text_bodycontent */ function filter_text_bodycontent() { // convert entities to utf8, filter text and convert back //$this->bodycontent = hotpot_textlib('entities_to_utf8', $this->bodycontent); //$this->bodycontent = filter_text($this->bodycontent); //$this->bodycontent = hotpot_textlib('utf8_to_entities', $this->bodycontent); } /** * fix_feedbackform */ function fix_feedbackform() { // we are aiming to generate the following javascript to send to the client //FEEDBACK = new Array(); //FEEDBACK[0] = ''; // url of feedback page/script //FEEDBACK[1] = ''; // array of array('teachername', 'value'); //FEEDBACK[2] = ''; // 'student name' [formmail only] //FEEDBACK[3] = ''; // 'student email' [formmail only] //FEEDBACK[4] = ''; // window width //FEEDBACK[5] = ''; // window height //FEEDBACK[6] = ''; // 'Send a message to teacher' [prompt/button text] //FEEDBACK[7] = ''; // 'Title' //FEEDBACK[8] = ''; // 'Teacher' //FEEDBACK[9] = ''; // 'Message' //FEEDBACK[10] = ''; // 'Close this window' global $CFG, $USER; $feedback = array(); switch ($this->hotpot->studentfeedback) { case hotpot::FEEDBACK_NONE: // do nothing - feedback form is not required break; case hotpot::FEEDBACK_WEBPAGE: if ($this->hotpot->studentfeedbackurl) { $feedback[0] = "'".addslashes_js($this->hotpot->studentfeedbackurl)."'"; } else { $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; case hotpot::FEEDBACK_FORMMAIL: if ($this->hotpot->studentfeedbackurl) { $teachers = $this->get_feedback_teachers(); } else { $teachers = ''; } if ($teachers) { $feedback[0] = "'".addslashes_js($this->hotpot->studentfeedbackurl)."'"; $feedback[1] = $teachers; $feedback[2] = "'".addslashes_js(fullname($USER))."'"; $feedback[3] = "'".addslashes_js($USER->email)."'"; $feedback[4] = 500; // width $feedback[5] = 300; // height } else { // no teachers (or no feedback url) $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; case hotpot::FEEDBACK_MOODLEFORUM: $cmids = array(); if ($modinfo = get_fast_modinfo($this->hotpot->course)) { foreach ($modinfo->cms as $cmid=>$mod) { if ($mod->modname=='forum' && $mod->visible) { $cmids[] = $cmid; } } } switch (count($cmids)) { case 0: $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; break; // no forums !! case 1: $feedback[0] = "'".$CFG->wwwroot.'/mod/forum/view.php?id='.$cmids[0]."'"; break; default: $feedback[0] = "'".$CFG->wwwroot.'/mod/forum/index.php?id='.$this->hotpot->course->id."'"; } break; case hotpot::FEEDBACK_MOODLEMESSAGING: if ($CFG->messaging) { $teachers = $this->get_feedback_teachers(); } else { $teachers = ''; } if ($teachers) { $feedback[0] = "'$CFG->wwwroot/message/discussion.php?id='"; $feedback[1] = $teachers; $feedback[4] = 400; // width $feedback[5] = 500; // height } else { // no teachers (or no Moodle messaging) $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; default: // unrecognized feedback setting, so reset it to something valid $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } if ($this->hotpot->studentfeedback==hotpot::FEEDBACK_NONE) { // do nothing - feedback form is not required } else { // complete remaining feedback fields if ($this->hotpot->studentfeedback==hotpot::FEEDBACK_MOODLEFORUM) { $feedback[6] = "'".addslashes_js(get_string('feedbackdiscuss', 'hotpot'))."'"; } else { // FEEDBACK_WEBPAGE, FEEDBACK_FORMMAIL, FEEDBACK_MOODLEMESSAGING $feedback[6] = "'".addslashes_js(get_string('feedbacksendmessage', 'hotpot'))."'"; } $feedback[7] = "'".addslashes_js(get_string('feedback'))."'"; $feedback[8] = "'".addslashes_js(get_string('defaultcourseteacher'))."'"; $feedback[9] = "'".addslashes_js(get_string('messagebody'))."'"; $feedback[10] = "'".addslashes_js(get_string('closewindow'))."'"; $js = ''; foreach ($feedback as $i=>$str) { $js .= 'FEEDBACK['.$i."] = $str;\n"; } $js = '<script type="text/javascript">'."\n//<![CDATA[\n"."FEEDBACK = new Array();\n".$js."//]]>\n</script>\n"; if ($this->usemoodletheme) { $this->headcontent .= $js; } else { $this->bodycontent = preg_replace('/<\/head>/i', "$js</head>", $this->bodycontent, 1); } } } /** * get_feedback_teachers * * @return xxx */ function get_feedback_teachers() { $context = hotpot_get_context(CONTEXT_COURSE, $this->hotpot->source->courseid); $teachers = get_users_by_capability($context, 'mod/hotpot:reviewallattempts'); $details = array(); if (isset($teachers) && count($teachers)) { if ($this->hotpot->studentfeedback==hotpot::FEEDBACK_MOODLEMESSAGING) { $detail = 'id'; } else { $detail = 'email'; } foreach ($teachers as $teacher) { $details[] = "new Array('".addslashes_js(fullname($teacher))."', '".addslashes_js($teacher->$detail)."')"; } } if ($details = implode(', ', $details)) { return 'new Array('.$details.')'; } else { return ''; // no teachers } } /** * fix_reviewoptions */ function fix_reviewoptions() { // enable / disable review options } /** * fix_submissionform */ function fix_submissionform() { $params = array( 'id' => $this->hotpot->create_attempt(), $this->scorefield => '0', 'detail' => '0', 'status' => '0', 'starttime' => '0', 'endtime' => '0', 'redirect' => '0', ); $attributes = array( 'id' => $this->formid, 'autocomplete' => 'off' ); $form_start = $this->form_start('submit.php', $params, $attributes); $search = '<!-- BeginSubmissionForm -->'; if (! $pos = strpos($this->bodycontent, $search)) { throw new moodle_exception('couldnotinsertsubmissionform', 'hotpot'); } $this->bodycontent = substr_replace($this->bodycontent, $form_start, $pos, strlen($search)); $search = '<!-- EndSubmissionForm -->'; if (! $pos = strpos($this->bodycontent, $search)) { throw new moodle_exception('couldnotinsertsubmissionform', 'hotpot'); } $this->bodycontent = substr_replace($this->bodycontent, $this->form_end(), $pos, strlen($search)); } /** * fix_mediafilter_onload_extra * * @return xxx */ function fix_mediafilter_onload_extra() { return '' .' if(window.StretchCanvasToCoverContent) {'."\n" .' StretchCanvasToCoverContent();'."\n" .' }'."\n" ; } // captions and messages /** * expand_AlsoCorrect * * @return xxx */ function expand_AlsoCorrect() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',also-correct'); } /** * expand_BottomNavBar * * @return xxx */ function expand_BottomNavBar() { return $this->expand_NavBar('BottomNavBar'); } /** * expand_CapitalizeFirst * * @return xxx */ function expand_CapitalizeFirst() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',capitalize-first-letter'); } /** * expand_CheckCaption * * @return xxx */ function expand_CheckCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,check-caption'); } /** * expand_ContentsURL * * @return xxx */ function expand_ContentsURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,contents-url'); } /** * expand_CorrectIndicator * * @return xxx */ function expand_CorrectIndicator() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,correct-indicator'); } /** * expand_Back * * @return xxx */ function expand_Back() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-back'); } /** * expand_BackCaption * * @return xxx */ function expand_BackCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,back-caption'); } /** * expand_CaseSensitive * * @return xxx */ function expand_CaseSensitive() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',case-sensitive'); } /** * expand_ClickToAdd * * @return xxx */ function expand_ClickToAdd() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',click-to-add'); } /** * expand_ClueCaption * * @return xxx */ function expand_ClueCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,clue-caption'); } /** * expand_Clues * * @return xxx */ function expand_Clues() { // Note: WinHotPot6 uses "include-clues", but JavaHotPotatoes6 uses "include-clue" (missing "s") return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-clues'); } /** * expand_Contents * * @return xxx */ function expand_Contents() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-contents'); } /** * expand_ContentsCaption * * @return xxx */ function expand_ContentsCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,contents-caption'); } /** * expand_Correct * * @return xxx */ function expand_Correct() { if ($this->hotpot->source->hbs_quiztype=='jcloze') { $tag = 'guesses-correct'; } else { $tag = 'guess-correct'; } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * expand_DeleteCaption * * @return xxx */ function expand_DeleteCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',delete-caption'); } /** * expand_DublinCoreMetadata * * @return xxx */ function expand_DublinCoreMetadata() { $dc = ''; if ($value = $this->hotpot->source->xml_value('', "['rdf:RDF'][0]['@']['xmlns:dc']")) { $dc .= '<link rel="schema.DC" href="'.str_replace('"', '&quot;', $value).'" />'."\n"; } if (is_array($this->hotpot->source->xml_value('rdf:RDF,rdf:Description'))) { $names = array('DC:Creator'=>'dc:creator', 'DC:Title'=>'dc:title'); foreach ($names as $name => $tag) { $i = 0; $values = array(); while($value = $this->hotpot->source->xml_value("rdf:RDF,rdf:Description,$tag", "[$i]['#']")) { if ($value = trim(strip_tags($value))) { $values[strtoupper($value)] = htmlspecialchars($value); } $i++; } if ($value = implode(', ', $values)) { $dc .= '<meta name="'.$name.'" content="'.$value.'" />'."\n"; } } } return $dc; } /** * expand_EMail * * @return xxx */ function expand_EMail() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,email'); } /** * expand_EscapedExerciseTitle * this string only used in resultsp6sendresults.js_ which is not required in Moodle * * @return xxx */ function expand_EscapedExerciseTitle() { return $this->hotpot->source->xml_value_js('data,title'); } /** * expand_ExBGColor * * @return xxx */ function expand_ExBGColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); } /** * expand_ExerciseSubtitle * * @return xxx */ function expand_ExerciseSubtitle() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',exercise-subtitle'); } /** * expand_ExerciseTitle * * @return xxx */ function expand_ExerciseTitle() { return $this->hotpot->source->xml_value('data,title'); } /** * expand_FontFace * * @return xxx */ function expand_FontFace() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,font-face'); } /** * expand_FontSize * * @return xxx */ function expand_FontSize() { $value = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,font-size'); return (empty($value) ? 'small' : $value); } /** * expand_FormMailURL * * @return xxx */ function expand_FormMailURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,formmail-url'); } /** * expand_FullVersionInfo * * @return xxx */ function expand_FullVersionInfo() { global $CFG; return $this->hotpot->source->xml_value('version').'.x (Moodle '.$CFG->release.', HotPot '.hotpot::get_version_info('release').')'; } /** * expand_FuncLightColor * * @return xxx */ function expand_FuncLightColor() { // top-left of buttons $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); return $this->expand_halfway_color($color, '#ffffff'); } /** * expand_FuncShadeColor * * @return xxx */ function expand_FuncShadeColor() { // bottom right of buttons $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); return $this->expand_halfway_color($color, '#000000'); } /** * expand_GiveHint * * @return xxx */ function expand_GiveHint() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-correct-letter'); } /** * expand_GraphicURL * * @return xxx */ function expand_GraphicURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,graphic-url'); } /** * expand_GuessCorrect * * @return xxx */ function expand_GuessCorrect() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',guess-correct'); } /** * expand_GuessIncorrect * * @return xxx */ function expand_GuessIncorrect() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',guess-incorrect'); } /** * expand_HeaderCode * * @return xxx */ function expand_HeaderCode() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,header-code'); } /** * expand_Hint * * @return xxx */ function expand_Hint() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-hint'); } /** * expand_HintCaption * * @return xxx */ function expand_HintCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,hint-caption'); } /** * expand_Incorrect * * @return xxx */ function expand_Incorrect() { if ($this->hotpot->source->hbs_quiztype=='jcloze') { $tag = 'guesses-incorrect'; } else { $tag = 'guess-incorrect'; } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * expand_IncorrectIndicator * * @return xxx */ function expand_IncorrectIndicator() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,incorrect-indicator'); } /** * expand_Instructions * * @return xxx */ function expand_Instructions() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',instructions'); } /** * expand_JSBrowserCheck * * @return xxx */ function expand_JSBrowserCheck() { return $this->expand_template('hp6browsercheck.js_'); } /** * expand_JSButtons * * @return xxx */ function expand_JSButtons() { return $this->expand_template('hp6buttons.js_'); } /** * expand_JSCard * * @return xxx */ function expand_JSCard() { return $this->expand_template('hp6card.js_'); } /** * expand_JSCheckShortAnswer * * @return xxx */ function expand_JSCheckShortAnswer() { return $this->expand_template('hp6checkshortanswer.js_'); } /** * expand_JSHotPotNet * * @return xxx */ function expand_JSHotPotNet() { return $this->expand_template('hp6hotpotnet.js_'); } /** * expand_JSSendResults * * @return xxx */ function expand_JSSendResults() { return $this->expand_template('hp6sendresults.js_'); } /** * expand_JSShowMessage * * @return xxx */ function expand_JSShowMessage() { return $this->expand_template('hp6showmessage.js_'); } /** * expand_JSTimer * * @return xxx */ function expand_JSTimer() { return $this->expand_template('hp6timer.js_'); } /** * expand_JSUtilities * * @return xxx */ function expand_JSUtilities() { return $this->expand_template('hp6utilities.js_'); } /** * expand_LastQCaption * * @return xxx */ function expand_LastQCaption() { $caption = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,last-q-caption'); return ($caption=='<=' ? '&lt;=' : $caption); } /** * expand_LinkColor * * @return xxx */ function expand_LinkColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,link-color'); } /** * expand_NamePlease * * @return xxx */ function expand_NamePlease() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,name-please'); } /** * expand_NavBar * * @param xxx $navbarid (optional, default='') * @return xxx */ function expand_NavBar($navbarid='') { $this->navbarid = $navbarid; $navbar = $this->expand_template('hp6navbar.ht_'); unset($this->navbarid); return $navbar; } /** * expand_NavBarID * * @return xxx */ function expand_NavBarID() { // $this->navbarid is set in "$this->expand_NavBar" return empty($this->navbarid) ? '' : $this->navbarid; } /** * expand_NavBarJS * * @return xxx */ function expand_NavBarJS() { return $this->expand_NavButtons(); } /** * expand_NavButtons * * @return xxx */ function expand_NavButtons() { return ($this->expand_Back() || $this->expand_NextEx() || $this->expand_Contents()); } /** * expand_NavTextColor * * @return xxx */ function expand_NavTextColor() { // might be 'title-color' ? return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,text-color'); } /** * expand_NavBarColor * * @return xxx */ function expand_NavBarColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); } /** * expand_NavLightColor * * @return xxx */ function expand_NavLightColor() { $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); return $this->expand_halfway_color($color, '#ffffff'); } /** * expand_NavShadeColor * * @return xxx */ function expand_NavShadeColor() { $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); return $this->expand_halfway_color($color, '#000000'); } /** * expand_NextCaption * * @return xxx */ function expand_NextCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-caption'); } /** * expand_NextCorrect * * @return xxx */ function expand_NextCorrect() { if ($this->hotpot->source->hbs_quiztype=='jquiz') { $tag = 'next-correct-letter'; // jquiz } else { $tag = 'next-correct-part'; // jmix } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * expand_NextEx * * @return xxx */ function expand_NextEx() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-next-ex'); } /** * expand_NextExCaption * * @return xxx */ function expand_NextExCaption() { $caption = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,next-ex-caption'); return ($caption=='=>' ? '=&gt;' : $caption); } /** * expand_NextQCaption * * @return xxx */ function expand_NextQCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,next-q-caption'); } /** * expand_NextExURL * * @return xxx */ function expand_NextExURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-ex-url'); } /** * expand_OKCaption * * @return xxx */ function expand_OKCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ok-caption'); } /** * expand_PageBGColor * * @return xxx */ function expand_PageBGColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,page-bg-color'); } /** * expand_PlainTitle * * @return xxx */ function expand_PlainTitle() { return $this->hotpot->source->xml_value('data,title'); } /** * expand_PreloadImages * * @return xxx */ function expand_PreloadImages() { $value = $this->expand_PreloadImageList(); return empty($value) ? false : true; } /** * expand_PreloadImageList * * @return xxx */ function expand_PreloadImageList() { if (! isset($this->PreloadImageList)) { $this->PreloadImageList = ''; $images = array(); // extract all src values from <img> tags in the xml file $search = '/&amp;#x003C;img.*?src=&quot;(.*?)&quot;.*?&amp;#x003E;/is'; if (preg_match_all($search, $this->hotpot->source->filecontents, $matches)) { $images = array_merge($images, $matches[1]); } // extract all urls from HotPot's [square bracket] notation // e.g. [%sitefiles%/images/screenshot.jpg image 350 265 center] $search = '/\['."([^\?\]]*\.(?:jpg|gif|png)(?:\?[^ \t\r\n\]]*)?)".'[^\]]*'.'\]/s'; if (preg_match_all($search, $this->hotpot->source->filecontents, $matches)) { $images = array_merge($images, $matches[1]); } if (count($images)) { $images = array_unique($images); $this->PreloadImageList = "\n\t\t'".implode("',\n\t\t'", $images)."'\n\t"; } } return $this->PreloadImageList; } /** * expand_Reading * * @return xxx */ function expand_Reading() { return $this->hotpot->source->xml_value_int('data,reading,include-reading'); } /** * expand_ReadingText * * @return xxx */ function expand_ReadingText() { $title = $this->expand_ReadingTitle(); if ($value = $this->hotpot->source->xml_value('data,reading,reading-text')) { $value = '<div class="ReadingText">'.$value.'</div>'; } else { $value = ''; } return $title.$value; } /** * expand_ReadingTitle * * @return xxx */ function expand_ReadingTitle() { $value = $this->hotpot->source->xml_value('data,reading,reading-title'); return empty($value) ? '' : ('<h3 class="ExerciseSubtitle">'.$value.'</h3>'); } /** * expand_Restart * * @return xxx */ function expand_Restart() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-restart'); } /** * expand_RestartCaption * * @return xxx */ function expand_RestartCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,restart-caption'); } /** * expand_Scorm12 * * @return xxx */ function expand_Scorm12() { return false; // HP scorm functionality is always disabled in Moodle } /** * expand_Seconds * * @return xxx */ function expand_Seconds() { return $this->hotpot->source->xml_value('data,timer,seconds'); } /** * expand_SendResults * * @return xxx */ function expand_SendResults() { return false; // send results (via formmail) is always disabled in Moodle // $tags = $this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',send-email'; // return $this->hotpot->source->xml_value($tags); } /** * expand_ShowAllQuestionsCaption * * @return xxx */ function expand_ShowAllQuestionsCaption($convert_to_unicode=false) { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,show-all-questions-caption'); } /** * expand_ShowAnswer * * @return xxx */ function expand_ShowAnswer() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-show-answer'); } /** * expand_SolutionCaption * * @return xxx */ function expand_SolutionCaption() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,solution-caption'); } /** * expand_ShowOneByOneCaption * * @return xxx */ function expand_ShowOneByOneCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,show-one-by-one-caption'); } /** * expand_StyleSheet * * @return xxx */ function expand_StyleSheet() { return $this->expand_template('hp6.cs_'); } /** * expand_TextColor * * @return xxx */ function expand_TextColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,text-color'); } /** * expand_TheseAnswersToo * * @return xxx */ function expand_TheseAnswersToo() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',also-correct'); } /** * expand_ThisMuch * * @return xxx */ function expand_ThisMuch() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',this-much-correct'); } /** * expand_Timer * * @return xxx */ function expand_Timer() { if ($this->hotpot->timelimit < 0) { // use setting in source file return $this->hotpot->source->xml_value_int('data,timer,include-timer'); } else { // override setting in source file return $this->hotpot->timelimit; } } /** * expand_TimesUp * * @return xxx */ function expand_TimesUp() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,times-up'); } /** * expand_TitleColor * * @return xxx */ function expand_TitleColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,title-color'); } /** * expand_TopNavBar * * @return xxx */ function expand_TopNavBar() { return $this->expand_NavBar('TopNavBar'); } /** * expand_Undo * * @return xxx */ function expand_Undo() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-undo'); } /** * expand_UndoCaption * * @return xxx */ function expand_UndoCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,undo-caption'); } /** * expand_UserDefined1 * * @return xxx */ function expand_UserDefined1() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-1'); } /** * expand_UserDefined2 * * @return xxx */ function expand_UserDefined2() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-2'); } /** * expand_UserDefined3 * * @return xxx */ function expand_UserDefined3() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-3'); } /** * expand_VLinkColor * * @return xxx */ function expand_VLinkColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,vlink-color'); } /** * expand_YourScoreIs * * @return xxx */ function expand_YourScoreIs() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,your-score-is'); } /** * expand_Keypad * * @return xxx */ function expand_Keypad() { $str = ''; if ($this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-keypad')) { // these characters must always be in the keypad $chars = array(); $this->add_keypad_chars($chars, $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,keypad-characters')); // append other characters used in the answers switch ($this->hotpot->source->hbs_quiztype) { case 'jcloze': $tags = 'data,gap-fill,question-record'; break; case 'jquiz': $tags = 'data,questions,question-record'; break; case 'rhubarb': $tags = 'data,rhubarb-text'; break; default: $tags = ''; } if ($tags) { $q = 0; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { if ($this->hotpot->source->hbs_quiztype=='jquiz') { $answers = $question."['answers'][0]['#']"; } else { $answers = $question; } $a = 0; while (($answer=$answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $this->add_keypad_chars($chars, $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']")); $a++; } $q++; } } // remove duplicate characters and sort $chars = array_unique($chars); usort($chars, array($this, 'hotpot_keypad_chars_sort')); // create keypad buttons for each character foreach ($chars as $char) { $str .= '<button onclick="'."TypeChars('".$this->hotpot->source->js_value_safe($char, true)."');".'return false;">'.$char.'</button>'; } } return $str; } /** * add_keypad_chars * * @param xxx $chars (passed by reference) * @param xxx $text */ function add_keypad_chars(&$chars, $text) { if (preg_match_all('/&[^;]+;/', $text, $more_chars)) { $chars = array_merge($chars, $more_chars[0]); } } /** * hotpot_keypad_chars_sort * * @param xxx $a_char * @param xxx $b_char * @return xxx */ function hotpot_keypad_chars_sort($a_char, $b_char) { $a_value = $this->hotpot_keypad_char_value($a_char); $b_value = $this->hotpot_keypad_char_value($b_char); if ($a_value < $b_value) { return -1; } if ($a_value > $b_value) { return 1; } // values are equal return 0; } /** * hotpot_keypad_char_value * * @param xxx $char * @return xxx */ function hotpot_keypad_char_value($char) { $char = hotpot_textlib('entities_to_utf8', $char); $ord = ord($char); // lowercase letters (plain or accented) if (($ord>=97 && $ord<=122) || ($ord>=224 && $ord<=255)) { return ($ord-31) + ($ord/1000); } // subscripts and superscripts switch ($ord) { case 0x2070: return 48.1; // super 0 = ord('0') + 0.1 case 0x00B9: return 49.1; // super 1 case 0x00B2: return 50.1; // super 2 case 0x00B3: return 51.1; // super 3 case 0x2074: return 52.1; // super 4 case 0x2075: return 53.1; // super 5 case 0x2076: return 54.1; // super 6 case 0x2077: return 55.1; // super 7 case 0x2078: return 56.1; // super 8 case 0x2079: return 57.1; // super 9 case 0x207A: return 43.1; // super + case 0x207B: return 45.1; // super - case 0x207C: return 61.1; // super = case 0x207D: return 40.1; // super ( case 0x207E: return 41.1; // super ) case 0x207F: return 110.1; // super n case 0x2080: return 47.9; // sub 0 = ord('0') - 0.1 case 0x2081: return 48.9; // sub 1 case 0x2082: return 49.9; // sub 2 case 0x2083: return 50.9; // sub 3 case 0x2084: return 51.9; // sub 4 case 0x2085: return 52.9; // sub 5 case 0x2086: return 53.9; // sub 6 case 0x2087: return 54.9; // sub 7 case 0x2088: return 55.9; // sub 8 case 0x2089: return 56.9; // sub 9 case 0x208A: return 42.9; // sub + case 0x208B: return 44.9; // sub - case 0x208C: return 60.9; // sub = case 0x208D: return 39.9; // sub ( case 0x208E: return 40.9; // sub ) case 0x208F: return 109.9; // sub n } return $ord; } // JCloze /** * expand_JSJCloze6 * * @return xxx */ function expand_JSJCloze6() { return $this->expand_template('jcloze6.js_'); } /** * expand_ClozeBody * * @return xxx */ function expand_ClozeBody() { $str = ''; // get drop down list of words, if required $dropdownlist = ''; if ($this->use_DropDownList()) { $this->set_WordList(); foreach ($this->wordlist as $word) { $dropdownlist .= '<option value="'.$word.'">'.$word.'</option>'; } } // cache clues flag and caption $includeclues = $this->expand_Clues(); $cluecaption = $this->expand_ClueCaption(); // detect if cloze starts with gap if (strpos($this->hotpot->source->filecontents, '<gap-fill><question-record>')) { $startwithgap = true; } else { $startwithgap = false; } // initialize loop values $q = 0; $tags = 'data,gap-fill'; $question_record = "$tags,question-record"; // initialize loop values $q = 0; $tags = 'data,gap-fill'; $question_record = "$tags,question-record"; // loop through text and gaps $looping = true; while ($looping) { $text = $this->hotpot->source->xml_value($tags, "[0]['#'][$q]"); $gap = ''; if (($question="[$q]['#']") && $this->hotpot->source->xml_value($question_record, $question)) { $gap .= '<span class="GapSpan" id="GapSpan'.$q.'">'; if ($this->use_DropDownList()) { $gap .= '<select id="Gap'.$q.'"><option value=""></option>'.$dropdownlist.'</select>'; } else { // minimum gap size if (! $gapsize = $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',minimum-gap-size')) { $gapsize = 6; } // increase gap size to length of longest answer for this gap $a = 0; while (($answer=$question."['answer'][$a]['#']") && $this->hotpot->source->xml_value($question_record, $answer)) { $answertext = $this->hotpot->source->xml_value($question_record, $answer."['text'][0]['#']"); $answertext = preg_replace('/&[#a-zA-Z0-9]+;/', 'x', $answertext); $gapsize = max($gapsize, strlen($answertext)); $a++; } $gap .= '<input type="text" id="Gap'.$q.'" onfocus="TrackFocus('.$q.')" onblur="LeaveGap()" class="GapBox" size="'.$gapsize.'"></input>'; } if ($includeclues) { $clue = $this->hotpot->source->xml_value($question_record, $question."['clue'][0]['#']"); if (strlen($clue)) { $gap .= '<button style="line-height: 1.0" class="FuncButton" onfocus="FuncBtnOver(this)" onmouseover="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" onclick="ShowClue('.$q.')">'.$cluecaption.'</button>'; } } $gap .= '</span>'; } if (strlen($text) || strlen($gap)) { if ($startwithgap) { $str .= $gap.$text; } else { $str .= $text.$gap; } $q++; } else { // no text or gap, so force end of loop $looping = false; } } if ($q==0) { // oops, no gaps found! return $this->hotpot->source->xml_value($tags); } else { return $str; } } /** * expand_ItemArray * * @return xxx */ function expand_ItemArray() { // this method is overridden by JCloze and JQuiz output formats } /** * expand_WordList * * @return xxx */ function expand_WordList() { $str = ''; if ($this->include_WordList()) { $this->set_WordList(); $str = implode(' &#160;&#160; ', $this->wordlist); } return $str; } /** * include_WordList * * @return xxx */ function include_WordList() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-word-list'); } /** * use_DropDownList * * @return xxx */ function use_DropDownList() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',use-drop-down-list'); } /** * set_WordList */ function set_WordList() { if (isset($this->wordlist)) { // do nothing } else { $this->wordlist = array(); // is the wordlist required if ($this->include_WordList() || $this->use_DropDownList()) { $q = 0; $tags = 'data,gap-fill,question-record'; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { $a = 0; $aa = 0; while (($answer=$question."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']"); $correct = $this->hotpot->source->xml_value_int($tags, $answer."['correct'][0]['#']"); if (strlen($text) && $correct) { // $correct is always true $this->wordlist[] = $text; $aa++; } $a++; } $q++; } $this->wordlist = array_unique($this->wordlist); sort($this->wordlist); } } } // jcross /** * expand_JSJCross6 * * @return xxx */ function expand_JSJCross6() { return $this->expand_template('jcross6.js_'); } /** * expand_CluesAcrossLabel * * @return xxx */ function expand_CluesAcrossLabel() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',clues-across'); } /** * expand_CluesDownLabel * * @return xxx */ function expand_CluesDownLabel() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',clues-down'); } /** * expand_EnterCaption * * @return xxx */ function expand_EnterCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',enter-caption'); } /** * expand_ShowHideClueList * * @return xxx */ function expand_ShowHideClueList() { $value = $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-clue-list'); return empty($value) ? ' style="display: none;"' : ''; } /** * expand_CluesDown * * @return xxx */ function expand_CluesDown() { return $this->expand_jcross_clues('D'); } /** * expand_CluesAcross * * @return xxx */ function expand_CluesAcross() { return $this->expand_jcross_clues('A'); } /** * expand_jcross_clues * * @param xxx $direction * @return xxx */ function expand_jcross_clues($direction) { // $direction: A(cross) or D(own) $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $clue_i = 0; // clue index; $str = ''; for ($r=0; $r<=$r_max; $r++) { for ($c=0; $c<=$c_max; $c++) { $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if ($aword || $dword) { $clue_i++; // increment clue index // get the definition for this word $def = ''; $word = ($direction=='A') ? $aword : $dword; $word = hotpot_textlib('utf8_to_entities', $word); $i = 0; $clues = 'data,crossword,clues,item'; while (($clue = "[$i]['#']") && $this->hotpot->source->xml_value($clues, $clue)) { if ($word==$this->hotpot->source->xml_value($clues, $clue."['word'][0]['#']")) { $def = $this->hotpot->source->xml_value($clues, $clue."['def'][0]['#']"); break; } $i++; } if ($def) { $str .= '<tr><td class="ClueNum">'.$clue_i.'. </td><td id="Clue_'.$direction.'_'.$clue_i.'" class="Clue">'.$def.'</td></tr>'; } } } } return $str; } /** * expand_LetterArray * * @return xxx */ function expand_LetterArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "L[$r] = new Array("; for ($c=0; $c<=$c_max; $c++) { $str .= ($c>0 ? ',' : '')."'".$this->hotpot->source->js_value_safe($row[$r]['cell'][$c]['#'], true)."'"; } $str .= ");\n"; } return $str; } /** * expand_GuessArray * * @return xxx */ function expand_GuessArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "G[$r] = new Array('".str_repeat("','", $c_max)."');\n"; } return $str; } /** * expand_ClueNumArray * * @return xxx */ function expand_ClueNumArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $i = 0; // clue index $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "CL[$r] = new Array("; for ($c=0; $c<=$c_max; $c++) { if ($c>0) { $str .= ','; } $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if (empty($aword) && empty($dword)) { $str .= 0; } else { $i++; // increment the clue index $str .= $i; } } $str .= ");\n"; } return $str; } /** * expand_GridBody * * @return xxx */ function expand_GridBody() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $i = 0; // clue index; $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= '<tr id="Row_'.$r.'">'; for ($c=0; $c<=$c_max; $c++) { if (empty($row[$r]['cell'][$c]['#'])) { $str .= '<td class="BlankCell">&nbsp;</td>'; } else { $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if (empty($aword) && empty($dword)) { $str .= '<td class="LetterOnlyCell"><span id="L_'.$r.'_'.$c.'">&nbsp;</span></td>'; } else { $i++; // increment clue index $str .= '<td class="NumLetterCell"><a href="javascript:void(0);" class="GridNum" onclick="ShowClue('.$i.','.$r.','.$c.')">'.$i.'</a><span class="NumLetterCellText" id="L_'.$r.'_'.$c.'" onclick="ShowClue('.$i.','.$r.','.$c.')">&nbsp;&nbsp;&nbsp;</span></td>'; } } } $str .= '</tr>'; } return $str; } /** * get_jcross_grid * * @param xxx $rows (passed by reference) * @param xxx $r_max (passed by reference) * @param xxx $c_max (passed by reference) */ function get_jcross_grid(&$rows, &$r_max, &$c_max) { $r_max = 0; $c_max = 0; $r = 0; $tags = 'data,crossword,grid,row'; while (($moretags="[$r]['#']") && $row = $this->hotpot->source->xml_value($tags, $moretags)) { $rows[$r] = $row; for ($c=0; $c<count($row['cell']); $c++) { if (! empty($row['cell'][$c]['#'])) { $r_max = max($r, $r_max); $c_max = max($c, $c_max); } } $r++; } } /** * get_jcross_dword * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @return xxx */ function get_jcross_dword(&$row, $r, $r_max, $c, $c_max) { $str = ''; if (($r==0 || empty($row[$r-1]['cell'][$c]['#'])) && $r<$r_max && !empty($row[$r+1]['cell'][$c]['#'])) { $str = $this->get_jcross_word($row, $r, $r_max, $c, $c_max, true); } return $str; } /** * get_jcross_aword * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @return xxx */ function get_jcross_aword(&$row, $r, $r_max, $c, $c_max) { $str = ''; if (($c==0 || empty($row[$r]['cell'][$c-1]['#'])) && $c<$c_max && !empty($row[$r]['cell'][$c+1]['#'])) { $str = $this->get_jcross_word($row, $r, $r_max, $c, $c_max, false); } return $str; } /** * get_jcross_word * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @param xxx $go_down (optional, default=false) * @return xxx */ function get_jcross_word(&$row, $r, $r_max, $c, $c_max, $go_down=false) { $str = ''; while ($r<=$r_max && $c<=$c_max && !empty($row[$r]['cell'][$c]['#'])) { $str .= $row[$r]['cell'][$c]['#']; if ($go_down) { $r++; } else { $c++; } } return $str; } // jmatch /** * expand_JSJMatch6 * * @return xxx */ function expand_JSJMatch6() { return $this->expand_template('jmatch6.js_'); } /** * expand_JSDJMatch6 * * @return xxx */ function expand_JSDJMatch6() { return $this->expand_template('djmatch6.js_'); } /** * expand_JSFJMatch6 * * @return xxx */ function expand_JSFJMatch6() { return $this->expand_template('fjmatch6.js_'); } /** * expand_ShuffleQs * * @return xxx */ function expand_ShuffleQs() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',shuffle-questions'); } /** * expand_QsToShow * * @return xxx */ function expand_QsToShow() { $i = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',show-limited-questions'); if ($i) { $i = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',questions-to-show'); } if (empty($i)) { $i = 0; if ($this->hotpot->source->hbs_quiztype=='jmatch') { $tags = 'data,matching-exercise,pair'; } else if ($this->hotpot->source->hbs_quiztype=='jquiz') { $tags = 'data,questions,question-record'; } else { $tags = ''; } if ($tags) { while (($moretags="[$i]['#']") && $value = $this->hotpot->source->xml_value($tags, $moretags)) { $i++; } } } return $i; } /** * expand_MatchDivItems * * @return xxx */ function expand_MatchDivItems() { $this->set_jmatch_items(); $l_keys = $this->shuffle_jmatch_items($this->l_items); $r_keys = $this->shuffle_jmatch_items($this->r_items); $options = '<option value="x">'.$this->hotpot->source->xml_value('data,matching-exercise,default-right-item').'</option>'."\n"; foreach ($r_keys as $key) { // only add the first occurrence of the text (i.e. skip duplicates) if ($key==$this->r_items[$key]['key']) { $options .= '<option value="'.$key.'">'.$this->r_items[$key]['text'].'</option>'."\n"; // Note: if the 'text' contains an image, it could be added as the background image of the option // http://www.small-software-utilities.com/design/91/html-select-with-background-image-or-icon-next-to-text/ // ... or of an optgroup ... // http://ask.metafilter.com/16153/Images-in-HTML-select-form-elements } } $str = ''; foreach ($l_keys as $key) { $str .= '<tr><td class="l_item">'.$this->l_items[$key]['text'].'</td>'; $str .= '<td class="r_item">'; if ($this->r_items[$key]['fixed']) { $str .= $this->r_items[$key]['text']; } else { $str .= '<select id="s'.$this->r_items[$key]['key'].'_'.$key.'">'.$options.'</select>'; } $str .= '</td><td></td></tr>'; } return $str; } /** * expand_FixedArray * * @return xxx */ function expand_FixedArray() { $this->set_jmatch_items(); $str = ''; foreach ($this->l_items as $i=>$item) { $str .= "F[$i] = new Array();\n"; $str .= "F[$i][0] = '".$this->hotpot->source->js_value_safe($item['text'], true)."';\n"; $str .= "F[$i][1] = ".($item['key']+1).";\n"; } return $str; } /** * expand_DragArray * * @return xxx */ function expand_DragArray() { $this->set_jmatch_items(); $str = ''; foreach ($this->r_items as $i=>$item) { $str .= "D[$i] = new Array();\n"; $str .= "D[$i][0] = '".$this->hotpot->source->js_value_safe($item['text'], true)."';\n"; $str .= "D[$i][1] = ".($item['key']+1).";\n"; $str .= "D[$i][2] = ".$item['fixed'].";\n"; } return $str; } /** * expand_Slide * * @return xxx */ function expand_Slide() { // return true if any JMatch drag-and-drop RH items are fixed and therefore need to slide to the LHS $this->set_jmatch_items(); foreach ($this->r_items as $i=>$item) { if ($item['fixed']) { return true; } } return false; } /** * set_jmatch_items */ function set_jmatch_items() { if (count($this->l_items)) { return; } $tags = 'data,matching-exercise,pair'; $i = 0; while (($item = "[$i]['#']") && $this->hotpot->source->xml_value($tags, $item)) { $l_item = $item."['left-item'][0]['#']"; $l_text = $this->hotpot->source->xml_value($tags, $l_item."['text'][0]['#']"); $l_fixed = $this->hotpot->source->xml_value_int($tags, $l_item."['fixed'][0]['#']"); $r_item = $item."['right-item'][0]['#']"; $r_text = $this->hotpot->source->xml_value($tags, $r_item."['text'][0]['#']"); $r_fixed = $this->hotpot->source->xml_value_int($tags, $r_item."['fixed'][0]['#']"); // typically all right-hand items are unique, but there may be duplicates // in which case we want the key of the first item containing this text for ($key=0; $key<$i; $key++) { if (isset($this->r_items[$key]) && $this->r_items[$key]['text']==$r_text) { break; } } if (strlen($r_text)) { $addright = true; } else { $addright = false; } if (strlen($l_text)) { $this->l_items[] = array('key' => $key, 'text' => $l_text, 'fixed' => $l_fixed); $addright = true; // force right item to be added } if ($addright) { $this->r_items[] = array('key' => $key, 'text' => $r_text, 'fixed' => $r_fixed); } $i++; } } /** * shuffle_jmatch_items * * @param xxx $items (passed by reference) * @return xxx */ function shuffle_jmatch_items(&$items) { // get moveable items $moveable_keys = array(); for ($i=0; $i<count($items); $i++) { if(! $items[$i]['fixed']) { $moveable_keys[] = $i; } } // shuffle moveable items $this->seed_random_number_generator(); shuffle($moveable_keys); $keys = array(); for ($i=0, $ii=0; $i<count($items); $i++) { if($items[$i]['fixed']) { // fixed items stay where they are $keys[] = $i; } else { // moveable items are inserted in a shuffled order $keys[] = $moveable_keys[$ii++]; } } return $keys; } /** * seed_random_number_generator */ function seed_random_number_generator() { static $seeded = false; if (! $seeded) { srand((double) microtime() * 1000000); $seeded = true; } } // JMatch flash card /** * expand_TRows * * @return xxx */ function expand_TRows() { $str = ''; $this->set_jmatch_items(); $i_max = count($this->l_items); for ($i=0; $i<$i_max; $i++) { $str .= '<tr class="FlashcardRow" id="I_'.$i.'"><td id="L_'.$i.'">'.$this->l_items[$i]['text'].'</td><td id="R_'.$i.'">'.$this->r_items[$i]['text'].'</td></tr>'."\n"; } return $str; } // jmix /** * expand_JSJMix6 * * @return xxx */ function expand_JSJMix6() { return $this->expand_template('jmix6.js_'); } /** * expand_JSFJMix6 * * @return xxx */ function expand_JSFJMix6() { return $this->expand_template('fjmix6.js_'); } /** * expand_JSDJMix6 * * @return xxx */ function expand_JSDJMix6() { return $this->expand_template('djmix6.js_'); } /** * expand_Punctuation * * @return xxx */ function expand_Punctuation() { $chars = array(); // RegExp pattern to match HTML entity $pattern = '/&#x([0-9A-F]+);/i'; // entities for all punctutation except '&#;' (because they are used in html entities) $entities = $this->jmix_encode_punctuation('!"$%'."'".'()*+,-./:<=>?@[\]^_`{|}~'); // xml tags for JMix segments and alternate answers $punctuation_tags = array( 'data,jumbled-order-exercise,main-order,segment', 'data,jumbled-order-exercise,alternate' ); foreach ($punctuation_tags as $tags) { // get next segment (or alternate answer) $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { // convert low-ascii punctuation to entities $value = strtr($value, $entities); // extract all hex HTML entities if (preg_match_all($pattern, $value, $matches)) { // loop through hex entities $m_max = count($matches[0]); for ($m=0; $m<$m_max; $m++) { // convert to hex string to number //eval('$hex=0x'.$matches[1][$m].';'); $hex = hexdec($matches[1][$m]); // is this a punctuation character? if ( ($hex>=0x0020 && $hex<=0x00BF) || // ascii punctuation ($hex>=0x2000 && $hex<=0x206F) || // general punctuation ($hex>=0x3000 && $hex<=0x303F) || // CJK punctuation ($hex>=0xFE30 && $hex<=0xFE4F) || // CJK compatability ($hex>=0xFE50 && $hex<=0xFE6F) || // small form variants ($hex>=0xFF00 && $hex<=0xFF40) || // halfwidth and fullwidth forms (1) ($hex>=0xFF5B && $hex<=0xFF65) || // halfwidth and fullwidth forms (2) ($hex>=0xFFE0 && $hex<=0xFFEE) // halfwidth and fullwidth forms (3) ) { // add this character $chars[] = $matches[0][$m]; } } } // end if HTML entity $i++; } // end while next segment (or alternate answer) } // end foreach $tags $chars = implode('', array_unique($chars)); return $this->hotpot->source->js_value_safe($chars, true); } /** * expand_OpenPunctuation * * @return xxx */ function expand_OpenPunctuation() { $chars = array(); // unicode punctuation designations (pi="initial quote", ps="open") // http://www.sql-und-xml.de/unicode-database/pi.html // http://www.sql-und-xml.de/unicode-database/ps.html $pi = '0022|0027|00AB|2018|201B|201C|201F|2039'; $ps = '0028|005B|007B|0F3A|0F3C|169B|201A|201E|2045|207D|208D|2329|23B4|2768|276A|276C|276E|2770|2772|2774|27E6|27E8|27EA|2983|2985|2987|2989|298B|298D|298F|2991|2993|2995|2997|29D8|29DA|29FC|3008|300A|300C|300E|3010|3014|3016|3018|301A|301D|FD3E|FE35|FE37|FE39|FE3B|FE3D|FE3F|FE41|FE43|FE47|FE59|FE5B|FE5D|FF08|FF3B|FF5B|FF5F|FF62'; $pattern = '/(&#x('.$pi.'|'.$ps.');)/i'; // HMTL entities of opening punctuation $entities = $this->jmix_encode_punctuation('"'."'".'(<[{'); // xml tags for JMix segments and alternate answers $punctuation_tags = array( 'data,jumbled-order-exercise,main-order,segment', 'data,jumbled-order-exercise,alternate' ); foreach ($punctuation_tags as $tags) { $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { $value = strtr($value, $entities); if (preg_match_all($pattern, $value, $matches)) { $chars = array_merge($chars, $matches[0]); } $i++; } } $chars = implode('', array_unique($chars)); return $this->hotpot->source->js_value_safe($chars, true); } /** * jmix_encode_punctuation * * @param xxx $str * @return xxx */ function jmix_encode_punctuation($str) { $entities = array(); $i_max = strlen($str); for ($i=0; $i<$i_max; $i++) { $entities[$str{$i}] = '&#x'.sprintf('%04X', ord($str{$i})).';'; } return $entities; } /* * expand_ForceLowercase * * Should we force the first letter of the first word to be lowercase? * (all other letters are assumed to have the correct case) * * When generating html files with standard JMix program, the user is prompted: * Should the word Xxxxx begin with a capital letter * even when it isn't at the beginning of a sentence? * * The "force-lowercase" xml tag implements a similar functionality * This tag does not exist in standard Hot Potatoes XML files, * but it can be added manually, for example to a HP config file * * @return xxx */ function expand_ForceLowercase() { $tag = $this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',force-lowercase'; return $this->hotpot->source->xml_value_int($tag); } /** * expand_SegmentArray * * @return xxx */ function expand_SegmentArray($more_values=array()) { $segments = array(); $values = array(); // XML tags to the start of a segment $tags = 'data,jumbled-order-exercise,main-order,segment'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { if ($i==0 && $this->expand_ForceLowercase()) { $value = strtolower(substr($value, 0, 1)).substr($value, 1); } $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key; } else { $segments[] = $i; $values[$i] = $value; } $i++; } foreach ($more_values as $value) { $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key; } else { $segments[] = $i; $values[$i] = $value; } $i++; } $this->seed_random_number_generator(); $keys = array_keys($segments); shuffle($keys); $str = ''; for ($i=0; $i<count($keys); $i++) { $key = $segments[$keys[$i]]; $str .= "Segments[$i] = new Array();\n"; $str .= "Segments[$i][0] = '".$this->hotpot->source->js_value_safe($values[$key], true)."';\n"; $str .= "Segments[$i][1] = ".($key+1).";\n"; $str .= "Segments[$i][2] = 0;\n"; } return $str; } /** * expand_AnswerArray * * @return xxx */ function expand_AnswerArray() { $segments = array(); $values = array(); $escapedvalues = array(); // XML tags to the start of a segment $tags = 'data,jumbled-order-exercise,main-order,segment'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { if ($i==0 && $this->expand_ForceLowercase()) { $value = strtolower(substr($value, 0, 1)).substr($value, 1); } $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key+1; } else { $segments[] = $i+1; $values[$i] = $value; $escapedvalues[] = preg_quote($value, '/'); } $i++; } // start the answers array $a = 0; $str = 'Answers['.($a++).'] = new Array('.implode(',', $segments).");\n"; // pattern to match the next part of an alternate answer $pattern = '/^('.implode('|', $escapedvalues).')\s*/i'; // XML tags to the start of an alternate answer $tags = 'data,jumbled-order-exercise,alternate'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i]['#']")) { $segments = array(); while (strlen($value) && preg_match($pattern, $value, $matches)) { $key = array_search($matches[1], $values); if (is_numeric($key)) { $segments[] = $key+1; $value = substr($value, strlen($matches[0])); } else { // invalid alternate sequence - shouldn't happen !! $segments = array(); break; } } if (count($segments)) { $str .= 'Answers['.($a++).'] = new Array('.implode(',', $segments).");\n"; } $i++; } return $str; } /** * expand_RemainingWords * * @return xxx */ function expand_RemainingWords() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',remaining-words'); } /** * expand_DropTotal * * @return xxx */ function expand_DropTotal() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,drop-total'); } // JQuiz /** * expand_JSJQuiz6 * * @return xxx */ function expand_JSJQuiz6() { return $this->expand_template('jquiz6.js_'); } /** * expand_QuestionOutput * * @return xxx */ function expand_QuestionOutput() { // start question list $str = '<ol class="QuizQuestions" id="Questions">'."\n"; $q = 0; $tags = 'data,questions,question-record'; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question) && ($answers = $question."['answers'][0]['#']") && $this->hotpot->source->xml_value($tags, $answers)) { // get question $question_text = $this->hotpot->source->xml_value($tags, $question."['question'][0]['#']"); $question_type = $this->hotpot->source->xml_value_int($tags, $question."['question-type'][0]['#']"); switch ($question_type) { case 1: // MULTICHOICE: $textbox = false; $liststart = '<ol class="MCAnswers">'."\n"; break; case 2: // SHORTANSWER: $textbox = true; $liststart = ''; break; case 3: // HYBRID: $textbox = true; $liststart = '<ol class="MCAnswers" id="Q_'.$q.'_Hybrid_MC" style="display: none;">'."\n"; break; case 4: // MULTISELECT: $textbox = false; $liststart = '<ol class="MSelAnswers">'."\n"; break; default: continue; // unknown question type } $first_answer_tags = $question."['answers'][0]['#']['answer'][0]['#']['text'][0]['#']"; $first_answer_text = $this->hotpot->source->xml_value($tags, $first_answer_tags, '', false); // check we have a question (or at least one answer) if (strlen($question_text) || strlen($first_answer_text)) { // start question $str .= '<li class="QuizQuestion" id="Q_'.$q.'" style="display: none;">'; $str .= '<p class="QuestionText">'.$question_text.'</p>'; if ($textbox) { // get prefix, suffix and maximum size of ShortAnswer box (default = 9) list($prefix, $suffix, $size) = $this->expand_jquiz_textbox_details($tags, $answers, $q); $str .= '<div class="ShortAnswer" id="Q_'.$q.'_SA"><form method="post" action="" onsubmit="return false;"><div>'; $str .= $prefix; if ($size<=25) { // text box $str .= '<input type="text" id="Q_'.$q.'_Guess" onfocus="TrackFocus('."'".'Q_'.$q.'_Guess'."'".')" onblur="LeaveGap()" class="ShortAnswerBox" size="'.$size.'"></input>'; } else { // textarea (29 cols wide) $str .= '<textarea id="Q_'.$q.'_Guess" onfocus="TrackFocus('."'".'Q_'.$q.'_Guess'."'".')" onblur="LeaveGap()" class="ShortAnswerBox" cols="29" rows="'.ceil($size/25).'"></textarea>'; } $str .= $suffix; $str .= '<br /><br />'; $caption = $this->expand_CheckCaption(); $str .= $this->expand_jquiz_button($caption, "CheckShortAnswer($q)"); if ($this->expand_Hint()) { $caption = $this->expand_HintCaption(); $str .= $this->expand_jquiz_button($caption, "ShowHint($q)"); } if ($this->expand_ShowAnswer()) { $caption = $this->expand_ShowAnswerCaption(); $str .= $this->expand_jquiz_button($caption, "ShowAnswers($q)"); } $str .= '</div></form></div>'; } if ($liststart) { $str .= $liststart; $a = 0; $aa = 0; while (($answer = $answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']"); if (strlen($text)) { if ($question_type==1 || $question_type==3) { // MULTICHOICE or HYBRID: button if ($this->hotpot->source->xml_value_int($tags, $answer."['include-in-mc-options'][0]['#']")) { $str .= '<li id="Q_'.$q.'_'.$aa.'"><button class="FuncButton" onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" id="Q_'.$q.'_'.$aa.'_Btn" onclick="CheckMCAnswer('.$q.','.$aa.',this)">&nbsp;&nbsp;?&nbsp;&nbsp;</button>&nbsp;&nbsp;'.$text.'</li>'."\n"; } } else if ($question_type==4) { // MULTISELECT: checkbox $str .= '<li id="Q_'.$q.'_'.$aa.'"><form method="post" action="" onsubmit="return false;"><div><input type="checkbox" id="Q_'.$q.'_'.$aa.'_Chk" class="MSelCheckbox" />'.$text.'</div></form></li>'."\n"; } $aa++; } $a++; } // finish answer list $str .= '</ol>'; if ($question_type==4) { // MULTISELECT: check button $caption = $this->expand_CheckCaption(); $str .= $this->expand_jquiz_button($caption, "CheckMultiSelAnswer($q)"); } } // finish question $str .= "</li>\n"; } $q++; } // end while $question // finish question list and finish return $str."</ol>\n"; } /** * expand_jquiz_textbox_details * * @param xxx $tags * @param xxx $answers * @param xxx $q * @param xxx $defaultsize (optional, default=9) * @return xxx */ function expand_jquiz_textbox_details($tags, $answers, $q, $defaultsize=9) { $prefix = ''; $suffix = ''; $size = $defaultsize; $a = 0; while (($answer = $answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']", '', false); $text = preg_replace('/&[#a-zA-Z0-9]+;/', 'x', $text); $size = max($size, strlen($text)); $a++; } return array($prefix, $suffix, $size); } /** * expand_jquiz_button * * @param xxx $caption * @param xxx $onclick * @return xxx */ function expand_jquiz_button($caption, $onclick) { return '<button class="FuncButton" onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" onclick="'.$onclick.'">'.$caption.'</button>'; } /** * expand_MultiChoice * * @return xxx */ function expand_MultiChoice() { return $this->jquiz_has_question_type(1); } /** * expand_ShortAnswer * * @return xxx */ function expand_ShortAnswer() { return $this->jquiz_has_question_type(2); } /** * expand_MultiSelect * * @return xxx */ function expand_MultiSelect() { return $this->jquiz_has_question_type(4); } /** * jquiz_has_question_type * * @param xxx $type * @return xxx */ function jquiz_has_question_type($type) { // does this JQuiz have any questions of the given $type? $q = 0; $tags = 'data,questions,question-record'; while (($question = "[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { $question_type = $this->hotpot->source->xml_value($tags, $question."['question-type'][0]['#']"); if ($question_type==$type || ($question_type==3 && ($type==1 || $type==2))) { // 1=MULTICHOICE 2=SHORTANSWER 3=HYBRID return true; } $q++; } return false; } /** * expand_CompletedSoFar * * @return xxx */ function expand_CompletedSoFar() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,completed-so-far'); } /** * expand_ContinuousScoring * * @return xxx */ function expand_ContinuousScoring() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',continuous-scoring'); } /** * expand_CorrectFirstTime * * @return xxx */ function expand_CorrectFirstTime() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,correct-first-time'); } /** * expand_ExerciseCompleted * * @return xxx */ function expand_ExerciseCompleted() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,exercise-completed'); } /** * expand_ShowCorrectFirstTime * * @return xxx */ function expand_ShowCorrectFirstTime() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',show-correct-first-time'); } /** * expand_ShuffleAs * * @return xxx */ function expand_ShuffleAs() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',shuffle-answers'); } /** * expand_DefaultRight * * @return xxx */ function expand_DefaultRight() { return $this->expand_GuessCorrect(); } /** * expand_DefaultWrong * * @return xxx */ function expand_DefaultWrong() { return $this->expand_GuessIncorrect(); } /** * expand_ShowAllQuestionsCaptionJS * * @return xxx */ function expand_ShowAllQuestionsCaptionJS() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,show-all-questions-caption'); } /** * expand_ShowOneByOneCaptionJS * * @return xxx */ function expand_ShowOneByOneCaptionJS() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,show-one-by-one-caption'); } /** * expand_CorrectList * * @return xxx */ function expand_CorrectList() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',correct-answers'); } /** * expand_HybridTries * * @return xxx */ function expand_HybridTries() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',short-answer-tries-on-hybrid-q'); } /** * expand_PleaseEnter * * @return xxx */ function expand_PleaseEnter() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',enter-a-guess'); } /** * expand_PartlyIncorrect * * @return xxx */ function expand_PartlyIncorrect() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',partly-incorrect'); } /** * expand_ShowAnswerCaption * * @return xxx */ function expand_ShowAnswerCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',show-answer-caption'); } /** * expand_ShowAlsoCorrect * * @return xxx */ function expand_ShowAlsoCorrect() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,global,show-also-correct'); } // Textoys stylesheets (tt3.cs_) /** * expand_isRTL * * @return xxx */ function expand_isRTL() { // this may require some clever detection of RTL languages (e.g. Hebrew) // but for now we just check the RTL setting in Options -> Configure Output return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,process-for-rtl'); } /** * expand_isLTR * * @return xxx */ function expand_isLTR() { if ($this->expand_isRTL()) { return false; } else { return true; } } /** * expand_RTLText * * @return xxx */ function expand_RTLText() { return $this->expand_isRTL(); } }
orvsd/moodle25
mod/hotpot/attempt/hp/6/renderer.php
PHP
gpl-3.0
143,352
''' Copyright (C) 2014 Travis DeWolf 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, either version 3 of the License, or (at your option) any later version. 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, see <http://www.gnu.org/licenses/>. ''' import numpy as np class Shell(object): """ """ def __init__(self, controller, target_list, threshold=.01, pen_down=False): """ control Control instance: the controller to use pen_down boolean: True if the end-effector is drawing """ self.controller = controller self.pen_down = pen_down self.target_list = target_list self.threshold = threshold self.not_at_start = True self.target_index = 0 self.set_target() def control(self, arm): """Move to a series of targets. """ if self.controller.check_distance(arm) < self.threshold: if self.target_index < len(self.target_list)-1: self.target_index += 1 self.set_target() self.controller.apply_noise = True self.not_at_start = not self.not_at_start self.pen_down = not self.pen_down self.u = self.controller.control(arm) return self.u def set_target(self): """ Set the current target for the controller. """ if self.target_index == len(self.target_list)-1: target = [1, 2] else: target = self.target_list[self.target_index] if target[0] != target[0]: # if it's NANs self.target_index += 1 self.set_target() else: self.controller.target = target
russellgeoff/blog
Control/Controllers/target_list.py
Python
gpl-3.0
2,121
using System; using System.Collections.Generic; using Antlr4.Runtime; using Rubberduck.Parsing.Symbols; using Rubberduck.UI; using Rubberduck.VBEditor; namespace Rubberduck.Inspections { public class IdentifierNotUsedInspectionResult : CodeInspectionResultBase { private readonly IEnumerable<CodeInspectionQuickFix> _quickFixes; public IdentifierNotUsedInspectionResult(IInspection inspection, Declaration target, ParserRuleContext context, QualifiedModuleName qualifiedName) : base(inspection, string.Format(inspection.Description, target.IdentifierName), qualifiedName, context) { _quickFixes = new[] { new RemoveUnusedDeclarationQuickFix(context, QualifiedSelection), }; } public override IEnumerable<CodeInspectionQuickFix> QuickFixes { get { return _quickFixes; } } } /// <summary> /// A code inspection quickfix that removes an unused identifier declaration. /// </summary> public class RemoveUnusedDeclarationQuickFix : CodeInspectionQuickFix { public RemoveUnusedDeclarationQuickFix(ParserRuleContext context, QualifiedSelection selection) : base(context, selection, RubberduckUI.Inspections_RemoveUnusedDeclaration) { } public override void Fix() { var module = Selection.QualifiedName.Component.CodeModule; var selection = Selection.Selection; var originalCodeLines = module.get_Lines(selection.StartLine, selection.LineCount) .Replace("\r\n", " ") .Replace("_", string.Empty); var originalInstruction = Context.GetText(); module.DeleteLines(selection.StartLine, selection.LineCount); var newInstruction = string.Empty; var newCodeLines = string.IsNullOrEmpty(newInstruction) ? string.Empty : originalCodeLines.Replace(originalInstruction, newInstruction); if (!string.IsNullOrEmpty(newCodeLines)) { module.InsertLines(selection.StartLine, newCodeLines); } } } }
r14r/fork_vba_rubberduck
RetailCoder.VBE/Inspections/IdentifierNotUsedInspectionResult.cs
C#
gpl-3.0
2,194
/* Copyright (c) 2001-2008, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * 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. */ package org.hsqldb.sample; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import org.hsqldb.jdbc.jdbcDataSource; /** * Title: Testdb * Description: simple hello world db example of a * standalone persistent db application * * every time it runs it adds four more rows to sample_table * it does a query and prints the results to standard out * * Author: Karl Meissner karl@meissnersd.com */ public class Testdb { Connection conn; //our connnection to the db - presist for life of program // we dont want this garbage collected until we are done public Testdb(String db_file_name_prefix) throws Exception { // note more general exception // connect to the database. This will load the db files and start the // database if it is not alread running. // db_file_name_prefix is used to open or create files that hold the state // of the db. // It can contain directory names relative to the // current working directory jdbcDataSource dataSource = new jdbcDataSource(); dataSource.setDatabase("jdbc:hsqldb:" + db_file_name_prefix); Connection c = dataSource.getConnection("sa", ""); } public void shutdown() throws SQLException { Statement st = conn.createStatement(); // db writes out to files and performs clean shuts down // otherwise there will be an unclean shutdown // when program ends st.execute("SHUTDOWN"); conn.close(); // if there are no other open connection } //use for SQL command SELECT public synchronized void query(String expression) throws SQLException { Statement st = null; ResultSet rs = null; st = conn.createStatement(); // statement objects can be reused with // repeated calls to execute but we // choose to make a new one each time rs = st.executeQuery(expression); // run the query // do something with the result set. dump(rs); st.close(); // NOTE!! if you close a statement the associated ResultSet is // closed too // so you should copy the contents to some other object. // the result set is invalidated also if you recycle an Statement // and try to execute some other query before the result set has been // completely examined. } //use for SQL commands CREATE, DROP, INSERT and UPDATE public synchronized void update(String expression) throws SQLException { Statement st = null; st = conn.createStatement(); // statements int i = st.executeUpdate(expression); // run the query if (i == -1) { System.out.println("db error : " + expression); } st.close(); } // void update() public static void dump(ResultSet rs) throws SQLException { // the order of the rows in a cursor // are implementation dependent unless you use the SQL ORDER statement ResultSetMetaData meta = rs.getMetaData(); int colmax = meta.getColumnCount(); int i; Object o = null; // the result set is a cursor into the data. You can only // point to one row at a time // assume we are pointing to BEFORE the first row // rs.next() points to next row and returns true // or false if there is no next row, which breaks the loop for (; rs.next(); ) { for (i = 0; i < colmax; ++i) { o = rs.getObject(i + 1); // Is SQL the first column is indexed // with 1 not 0 System.out.print(o.toString() + " "); } System.out.println(" "); } } //void dump( ResultSet rs ) public static void main(String[] args) { Testdb db = null; try { db = new Testdb("db_file"); } catch (Exception ex1) { ex1.printStackTrace(); // could not start db return; // bye bye } try { //make an empty table // // by declaring the id column IDENTITY, the db will automatically // generate unique values for new rows- useful for row keys db.update( "CREATE TABLE sample_table ( id INTEGER IDENTITY, str_col VARCHAR(256), num_col INTEGER)"); } catch (SQLException ex2) { //ignore //ex2.printStackTrace(); // second time we run program // should throw execption since table // already there // // this will have no effect on the db } try { // add some rows - will create duplicates if run more then once // the id column is automatically generated db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Ford', 100)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Toyota', 200)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Honda', 300)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('GM', 400)"); // do a query db.query("SELECT * FROM sample_table WHERE num_col < 250"); // at end of program db.shutdown(); } catch (SQLException ex3) { ex3.printStackTrace(); } } // main() } // class Testdb
ckaestne/LEADT
workspace/hsqldb/src/org/hsqldb/sample/Testdb.java
Java
gpl-3.0
7,388
/************************************************************************************************** Survey changes: copyright (c) 2010, Fryslan Webservices TM (http://survey.codeplex.com) NSurvey - The web survey and form engine Copyright (c) 2004, 2005 Thomas Zumbrunn. (http://www.nsurvey.org) 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; either version 2 of the License, or (at your option) any later version. 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ************************************************************************************************/ using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Votations.NSurvey.DataAccess; using Votations.NSurvey.Data; using Votations.NSurvey.UserProvider; using Votations.NSurvey.WebAdmin.UserControls; namespace Votations.NSurvey.WebAdmin { /// <summary> /// Display the user editor /// </summary> public partial class UsersManager : PageBase { protected System.Web.UI.WebControls.Label MessageLabel; new protected HeaderControl Header; Votations.NSurvey.SQLServerDAL.User UsersData; public int selectedTabIndex = 0; private void Page_Load(object sender, System.EventArgs e) { SetupSecurity(); LocalizePage(); // Get selected tab if (!string.IsNullOrEmpty(Request.Params["tabindex"])) { string[] idx = Request.Params["tabindex"].Split(','); selectedTabIndex = int.Parse(idx[idx.Length - 1]); } if (selectedTabIndex > 0) btnBack.Visible = false; UsersData = new Votations.NSurvey.SQLServerDAL.User(); SwitchModeDependingOnprevTab(); if (!Page.IsPostBack) { BindFields(); } else BindGrid(); // postback could be import users } private void SwitchModeDependingOnprevTab() { if (ViewState["UMPREVTAB"] != null && Convert.ToInt32(ViewState["UMPREVTAB"])>0 && selectedTabIndex==0) SwitchToListMode(); ViewState["UMPREVTAB"] = selectedTabIndex; } private void SetupSecurity() { CheckRight(NSurveyRights.AccessUserManager, true); IsSingleUserMode(true); } private void LocalizePage() { UserListTitleLabel.Text = ((PageBase)Page).GetPageResource("UserListTitle"); UserlistFilterOptionLiteral.Text = ((PageBase)Page).GetPageResource("UserlistFilterOptionLiteral"); } public bool IsAdmin(int userId) { return UsersData.IsAdministrator(userId); } public void OnUserEdit(Object sender, CommandEventArgs e) { UsersOptionsControl1.UserId = int.Parse(e.CommandArgument.ToString()); UsersOptionsControl1.BindFields(); phUsersList.Visible = false; btnBack.Visible = true; } public void EditBackButton(object sender, CommandEventArgs e) { SwitchToListMode(); } private void SwitchToListMode() { UsersOptionsControl1.UserId = -1; UsersOptionsControl1.BindFields(); phUsersList.Visible = true; BindGrid(); btnBack.Visible = false; } /// <summary> /// Get the current DB data and fill /// the fields with them /// </summary> private void BindFields() { // Header.SurveyId = SurveyId; ((Wap)Master).HeaderControl.SurveyId = getSurveyId(); BindGrid(); btnApplyfilter.Text = GetPageResource("UsersTabApplyFilter"); } private void BindGrid() { int ?isAdmin = chkAdmin.Checked ? 1: (int?)null; gvUsers.DataSource = UsersData.GetAllUsersListByFilter(txtUserName.Text, txtFirstName.Text, txtLastName.Text, txtEmail.Text, isAdmin); gvUsers.DataBind(); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); GridViewRow pagerRow = (GridViewRow)gvUsers.BottomPagerRow; if (pagerRow != null && pagerRow.Visible == false) pagerRow.Visible = true; } public void gvUsers_PageIndexChanged(Object sender, EventArgs e) { BindGrid(); } public void gvUsers_PageIndexChanging(Object sender, GridViewPageEventArgs e) { gvUsers.PageIndex = e.NewPageIndex; } public void OnApplyFilter(Object sender, EventArgs e) { BindGrid(); } /// <summary> /// Triggered by the type option user control /// in case anything was changed we will need to /// rebind to display the updates to the user /// </summary> private void UsersManager_OptionChanged(object sender, EventArgs e) { BindFields(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion private IUserProvider _userProvider = UserFactory.Create(); } }
samdubey/surveyproject_main_public
SurveyWAP/NSurveyAdmin/UsersManager.aspx.cs
C#
gpl-3.0
5,993
#include "FvSTLAssisstant.h"
Kiddinglife/gecoengine
thirdparty/FutureVisionCore/InnerCoreLibs/FvLogicCommon/FvSTLAssisstant.cpp
C++
gpl-3.0
34
define(["ng", "lodash"], function(ng, _){ "use strict"; var DashboardVM = function DashboardVM($scope, $rootScope){ var _self = this; this.toggleHStretch = function(isOn){ _self.setOptions(options); }; this.updateOptions = function(options){ ng.extend(_self, options); }; this.resetOptions = function(){ _self.updateOptions(_self.attr); }; this.setAttr = function(attr){ _self.attr=attr; _self.updateOptions(attr); }; this.remove = function(target){ // _.remove(_self.items, {name: target}); delete _self.items[target]; console.debug("remove _self.items", _self.items); }; this.items = $scope.dashboardItems; // this.items = [ // { // name: "survival1", // title: "survival1", // content: "moving around" // }, // { // name: "hcl1", // title: "hcl1", // content: "moving around" // }, // { // name: "ttest1", // title: "ttest1", // content: "moving around" // }, // { // name: "limma1", // title: "limma1", // content: "moving around" // }, // { // name: "deseq1", // title: "deseq1", // content: "moving around" // }, // { // name: "nmf", // title: "nmf", // content: "moving around" // }, // { // name: "kmeans1", // title: "kmeans1", // content: "moving around" // } // ]; $scope.$on("ui:dashboard:addItem", function($event, data){ var exists = _.find(_self.items, {name: data.name}); if(exists){ $rootScope.$broadcast("ui:analysisLog.append", "info", "Cannot add analysis '" + data.name + "' to the dashboard. It is already there."); }else{ _self.items.$add(data); } }); $scope.$on("ui:dashboard:removeItem", function($event, data){ console.debug("on ui:dashboard:removeItem", $event, data); _self.remove(data.name); }); }; DashboardVM.$inject=["$scope", "$rootScope"]; DashboardVM.$name="DashboardVMController"; return DashboardVM; });
apartensky/mev
web/src/main/javascript/edu/dfci/cccb/mev/web/ui/app/widgets/dashboard/controllers/DashboardVM.js
JavaScript
gpl-3.0
1,974
/* * Copyright (c) 2002-2008 LWJGL Project * 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 'LWJGL' nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ package org.lwjgl.opengl; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Canvas; import org.lwjgl.LWJGLException; /** * * @author elias_naur <elias_naur@users.sourceforge.net> * @version $Revision: 3632 $ * $Id: MacOSXCanvasImplementation.java 3632 2011-09-03 18:52:45Z spasi $ */ final class MacOSXCanvasImplementation implements AWTCanvasImplementation { public PeerInfo createPeerInfo(Canvas component, PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException { try { return new MacOSXAWTGLCanvasPeerInfo(component, pixel_format, attribs, true); } catch (LWJGLException e) { return new MacOSXAWTGLCanvasPeerInfo(component, pixel_format, attribs, false); } } /** * Find a proper GraphicsConfiguration from the given GraphicsDevice and PixelFormat. * * @return The GraphicsConfiguration corresponding to a visual that matches the pixel format. */ public GraphicsConfiguration findConfiguration(GraphicsDevice device, PixelFormat pixel_format) throws LWJGLException { /* * It seems like the best way is to simply return null */ return null; } }
kevinwang/minecarft
lwjgl-source-2.8.2/src/java/org/lwjgl/opengl/MacOSXCanvasImplementation.java
Java
gpl-3.0
2,780
<?php /* * Copyright (C) 2013 Mailgun * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ namespace Mailgun\HttpClient\Plugin; use Http\Client\Common\Plugin; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\UriInterface; /** * Replaces a URI with a new one. Good for debugging. * * @author Tobias Nyholm <tobias.nyholm@gmail.com> */ final class ReplaceUriPlugin implements Plugin { /** * @var UriInterface */ private $uri; /** * @param UriInterface $uri */ public function __construct(UriInterface $uri) { $this->uri = $uri; } /** * {@inheritdoc} */ public function handleRequest(RequestInterface $request, callable $next, callable $first) { $request = $request->withUri($this->uri); return $next($request); } }
growlingfish/giftplatform
vendor/mailgun/mailgun-php/src/Mailgun/HttpClient/Plugin/ReplaceUriPlugin.php
PHP
gpl-3.0
906
# -*- coding: utf-8 -*- # Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com> # Licensed under the MIT license. import sys import datetime from core.transmissionrpc.constants import PRIORITY, RATIO_LIMIT, IDLE_LIMIT from core.transmissionrpc.utils import Field, format_timedelta from six import integer_types, string_types, text_type, iteritems def get_status_old(code): """Get the torrent status using old status codes""" mapping = { (1 << 0): 'check pending', (1 << 1): 'checking', (1 << 2): 'downloading', (1 << 3): 'seeding', (1 << 4): 'stopped', } return mapping[code] def get_status_new(code): """Get the torrent status using new status codes""" mapping = { 0: 'stopped', 1: 'check pending', 2: 'checking', 3: 'download pending', 4: 'downloading', 5: 'seed pending', 6: 'seeding', } return mapping[code] class Torrent(object): """ Torrent is a class holding the data received from Transmission regarding a bittorrent transfer. All fetched torrent fields are accessible through this class using attributes. This class has a few convenience properties using the torrent data. """ def __init__(self, client, fields): if 'id' not in fields: raise ValueError('Torrent requires an id') self._fields = {} self._update_fields(fields) self._incoming_pending = False self._outgoing_pending = False self._client = client def _get_name_string(self, codec=None): """Get the name""" if codec is None: codec = sys.getdefaultencoding() name = None # try to find name if 'name' in self._fields: name = self._fields['name'].value # if name is unicode, try to decode if isinstance(name, text_type): try: name = name.encode(codec) except UnicodeError: name = None return name def __repr__(self): tid = self._fields['id'].value name = self._get_name_string() if isinstance(name, str): return '<Torrent {0:d} \"{1}\">'.format(tid, name) else: return '<Torrent {0:d}>'.format(tid) def __str__(self): name = self._get_name_string() if isinstance(name, str): return 'Torrent \"{0}\"'.format(name) else: return 'Torrent' def __copy__(self): return Torrent(self._client, self._fields) def __getattr__(self, name): try: return self._fields[name].value except KeyError: raise AttributeError('No attribute {0}'.format(name)) def _rpc_version(self): """Get the Transmission RPC API version.""" if self._client: return self._client.rpc_version return 2 def _dirty_fields(self): """Enumerate changed fields""" outgoing_keys = ['bandwidthPriority', 'downloadLimit', 'downloadLimited', 'peer_limit', 'queuePosition', 'seedIdleLimit', 'seedIdleMode', 'seedRatioLimit', 'seedRatioMode', 'uploadLimit', 'uploadLimited'] fields = [] for key in outgoing_keys: if key in self._fields and self._fields[key].dirty: fields.append(key) return fields def _push(self): """Push changed fields to the server""" dirty = self._dirty_fields() args = {} for key in dirty: args[key] = self._fields[key].value self._fields[key] = self._fields[key]._replace(dirty=False) if len(args) > 0: self._client.change_torrent(self.id, **args) def _update_fields(self, other): """ Update the torrent data from a Transmission JSON-RPC arguments dictionary """ if isinstance(other, dict): for key, value in iteritems(other): self._fields[key.replace('-', '_')] = Field(value, False) elif isinstance(other, Torrent): for key in list(other._fields.keys()): self._fields[key] = Field(other._fields[key].value, False) else: raise ValueError('Cannot update with supplied data') self._incoming_pending = False def _status(self): """Get the torrent status""" code = self._fields['status'].value if self._rpc_version() >= 14: return get_status_new(code) else: return get_status_old(code) def files(self): """ Get list of files for this torrent. This function returns a dictionary with file information for each file. The file information is has following fields: :: { <file id>: { 'name': <file name>, 'size': <file size in bytes>, 'completed': <bytes completed>, 'priority': <priority ('high'|'normal'|'low')>, 'selected': <selected for download> } ... } """ result = {} if 'files' in self._fields: files = self._fields['files'].value indices = range(len(files)) priorities = self._fields['priorities'].value wanted = self._fields['wanted'].value for item in zip(indices, files, priorities, wanted): selected = True if item[3] else False priority = PRIORITY[item[2]] result[item[0]] = { 'selected': selected, 'priority': priority, 'size': item[1]['length'], 'name': item[1]['name'], 'completed': item[1]['bytesCompleted']} return result @property def status(self): """ Returns the torrent status. Is either one of 'check pending', 'checking', 'downloading', 'seeding' or 'stopped'. The first two is related to verification. """ return self._status() @property def progress(self): """Get the download progress in percent.""" try: size = self._fields['sizeWhenDone'].value left = self._fields['leftUntilDone'].value return 100.0 * (size - left) / float(size) except ZeroDivisionError: return 0.0 @property def ratio(self): """Get the upload/download ratio.""" return float(self._fields['uploadRatio'].value) @property def eta(self): """Get the "eta" as datetime.timedelta.""" eta = self._fields['eta'].value if eta >= 0: return datetime.timedelta(seconds=eta) else: raise ValueError('eta not valid') @property def date_active(self): """Get the attribute "activityDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['activityDate'].value) @property def date_added(self): """Get the attribute "addedDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['addedDate'].value) @property def date_started(self): """Get the attribute "startDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['startDate'].value) @property def date_done(self): """Get the attribute "doneDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['doneDate'].value) def format_eta(self): """ Returns the attribute *eta* formatted as a string. * If eta is -1 the result is 'not available' * If eta is -2 the result is 'unknown' * Otherwise eta is formatted as <days> <hours>:<minutes>:<seconds>. """ eta = self._fields['eta'].value if eta == -1: return 'not available' elif eta == -2: return 'unknown' else: return format_timedelta(self.eta) def _get_download_limit(self): """ Get the download limit. Can be a number or None. """ if self._fields['downloadLimited'].value: return self._fields['downloadLimit'].value else: return None def _set_download_limit(self, limit): """ Get the download limit. Can be a number, 'session' or None. """ if isinstance(limit, integer_types): self._fields['downloadLimited'] = Field(True, True) self._fields['downloadLimit'] = Field(limit, True) self._push() elif limit is None: self._fields['downloadLimited'] = Field(False, True) self._push() else: raise ValueError("Not a valid limit") download_limit = property(_get_download_limit, _set_download_limit, None, "Download limit in Kbps or None. This is a mutator.") def _get_peer_limit(self): """ Get the peer limit. """ return self._fields['peer_limit'].value def _set_peer_limit(self, limit): """ Set the peer limit. """ if isinstance(limit, integer_types): self._fields['peer_limit'] = Field(limit, True) self._push() else: raise ValueError("Not a valid limit") peer_limit = property(_get_peer_limit, _set_peer_limit, None, "Peer limit. This is a mutator.") def _get_priority(self): """ Get the priority as string. Can be one of 'low', 'normal', 'high'. """ return PRIORITY[self._fields['bandwidthPriority'].value] def _set_priority(self, priority): """ Set the priority as string. Can be one of 'low', 'normal', 'high'. """ if isinstance(priority, string_types): self._fields['bandwidthPriority'] = Field(PRIORITY[priority], True) self._push() priority = property(_get_priority, _set_priority, None , "Bandwidth priority as string. Can be one of 'low', 'normal', 'high'. This is a mutator.") def _get_seed_idle_limit(self): """ Get the seed idle limit in minutes. """ return self._fields['seedIdleLimit'].value def _set_seed_idle_limit(self, limit): """ Set the seed idle limit in minutes. """ if isinstance(limit, integer_types): self._fields['seedIdleLimit'] = Field(limit, True) self._push() else: raise ValueError("Not a valid limit") seed_idle_limit = property(_get_seed_idle_limit, _set_seed_idle_limit, None , "Torrent seed idle limit in minutes. Also see seed_idle_mode. This is a mutator.") def _get_seed_idle_mode(self): """ Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ return IDLE_LIMIT[self._fields['seedIdleMode'].value] def _set_seed_idle_mode(self, mode): """ Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ if isinstance(mode, str): self._fields['seedIdleMode'] = Field(IDLE_LIMIT[mode], True) self._push() else: raise ValueError("Not a valid limit") seed_idle_mode = property(_get_seed_idle_mode, _set_seed_idle_mode, None, """ Seed idle mode as string. Can be one of 'global', 'single' or 'unlimited'. * global, use session seed idle limit. * single, use torrent seed idle limit. See seed_idle_limit. * unlimited, no seed idle limit. This is a mutator. """ ) def _get_seed_ratio_limit(self): """ Get the seed ratio limit as float. """ return float(self._fields['seedRatioLimit'].value) def _set_seed_ratio_limit(self, limit): """ Set the seed ratio limit as float. """ if isinstance(limit, (integer_types, float)) and limit >= 0.0: self._fields['seedRatioLimit'] = Field(float(limit), True) self._push() else: raise ValueError("Not a valid limit") seed_ratio_limit = property(_get_seed_ratio_limit, _set_seed_ratio_limit, None , "Torrent seed ratio limit as float. Also see seed_ratio_mode. This is a mutator.") def _get_seed_ratio_mode(self): """ Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ return RATIO_LIMIT[self._fields['seedRatioMode'].value] def _set_seed_ratio_mode(self, mode): """ Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ if isinstance(mode, str): self._fields['seedRatioMode'] = Field(RATIO_LIMIT[mode], True) self._push() else: raise ValueError("Not a valid limit") seed_ratio_mode = property(_get_seed_ratio_mode, _set_seed_ratio_mode, None, """ Seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. * global, use session seed ratio limit. * single, use torrent seed ratio limit. See seed_ratio_limit. * unlimited, no seed ratio limit. This is a mutator. """ ) def _get_upload_limit(self): """ Get the upload limit. Can be a number or None. """ if self._fields['uploadLimited'].value: return self._fields['uploadLimit'].value else: return None def _set_upload_limit(self, limit): """ Set the upload limit. Can be a number, 'session' or None. """ if isinstance(limit, integer_types): self._fields['uploadLimited'] = Field(True, True) self._fields['uploadLimit'] = Field(limit, True) self._push() elif limit is None: self._fields['uploadLimited'] = Field(False, True) self._push() else: raise ValueError("Not a valid limit") upload_limit = property(_get_upload_limit, _set_upload_limit, None, "Upload limit in Kbps or None. This is a mutator.") def _get_queue_position(self): """Get the queue position for this torrent.""" if self._rpc_version() >= 14: return self._fields['queuePosition'].value else: return 0 def _set_queue_position(self, position): """Set the queue position for this torrent.""" if self._rpc_version() >= 14: if isinstance(position, integer_types): self._fields['queuePosition'] = Field(position, True) self._push() else: raise ValueError("Not a valid position") else: pass queue_position = property(_get_queue_position, _set_queue_position, None, "Queue position") def update(self, timeout=None): """Update the torrent information.""" self._push() torrent = self._client.get_torrent(self.id, timeout=timeout) self._update_fields(torrent) def start(self, bypass_queue=False, timeout=None): """ Start the torrent. """ self._incoming_pending = True self._client.start_torrent(self.id, bypass_queue=bypass_queue, timeout=timeout) def stop(self, timeout=None): """Stop the torrent.""" self._incoming_pending = True self._client.stop_torrent(self.id, timeout=timeout) def move_data(self, location, timeout=None): """Move torrent data to location.""" self._incoming_pending = True self._client.move_torrent_data(self.id, location, timeout=timeout) def locate_data(self, location, timeout=None): """Locate torrent data at location.""" self._incoming_pending = True self._client.locate_torrent_data(self.id, location, timeout=timeout)
bbsan2k/nzbToMedia
core/transmissionrpc/torrent.py
Python
gpl-3.0
16,349
/* Android IMSI-Catcher Detector | (c) AIMSICD Privacy Project * ----------------------------------------------------------- * LICENSE: http://git.io/vki47 | TERMS: http://git.io/vki4o * ----------------------------------------------------------- */ package com.secupwn.aimsicd.ui.drawer; import android.support.annotation.DrawableRes; public interface NavDrawerItem { int getId(); String getLabel(); void setLabel(String label); void setIconId(@DrawableRes int icon); int getType(); boolean isEnabled(); boolean updateActionBarTitle(); }
CellularPrivacy/Android-IMSI-Catcher-Detector
AIMSICD/src/main/java/com/secupwn/aimsicd/ui/drawer/NavDrawerItem.java
Java
gpl-3.0
575
<?php /** * PostSendFailed * * PHP version 5 * * @category Class * @package SendinBlue\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * SendinBlue API * * SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable | * * OpenAPI spec version: 3.0.0 * Contact: contact@sendinblue.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.4.12 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace SendinBlue\Client\Model; use \ArrayAccess; use \SendinBlue\Client\ObjectSerializer; /** * PostSendFailed Class Doc Comment * * @category Class * @package SendinBlue\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class PostSendFailed implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $swaggerModelName = 'postSendFailed'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerTypes = [ 'code' => 'int', 'message' => 'string', 'unexistingEmails' => 'string[]', 'withoutListEmails' => 'string[]', 'blackListedEmails' => 'string[]' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerFormats = [ 'code' => 'int64', 'message' => null, 'unexistingEmails' => 'email', 'withoutListEmails' => 'email', 'blackListedEmails' => 'email' ]; /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function swaggerTypes() { return self::$swaggerTypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'code' => 'code', 'message' => 'message', 'unexistingEmails' => 'unexistingEmails', 'withoutListEmails' => 'withoutListEmails', 'blackListedEmails' => 'blackListedEmails' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'code' => 'setCode', 'message' => 'setMessage', 'unexistingEmails' => 'setUnexistingEmails', 'withoutListEmails' => 'setWithoutListEmails', 'blackListedEmails' => 'setBlackListedEmails' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'code' => 'getCode', 'message' => 'getMessage', 'unexistingEmails' => 'getUnexistingEmails', 'withoutListEmails' => 'getWithoutListEmails', 'blackListedEmails' => 'getBlackListedEmails' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$swaggerModelName; } /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['code'] = isset($data['code']) ? $data['code'] : null; $this->container['message'] = isset($data['message']) ? $data['message'] : null; $this->container['unexistingEmails'] = isset($data['unexistingEmails']) ? $data['unexistingEmails'] : null; $this->container['withoutListEmails'] = isset($data['withoutListEmails']) ? $data['withoutListEmails'] : null; $this->container['blackListedEmails'] = isset($data['blackListedEmails']) ? $data['blackListedEmails'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; if ($this->container['code'] === null) { $invalidProperties[] = "'code' can't be null"; } if ($this->container['message'] === null) { $invalidProperties[] = "'message' can't be null"; } return $invalidProperties; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return count($this->listInvalidProperties()) === 0; } /** * Gets code * * @return int */ public function getCode() { return $this->container['code']; } /** * Sets code * * @param int $code Response code * * @return $this */ public function setCode($code) { $this->container['code'] = $code; return $this; } /** * Gets message * * @return string */ public function getMessage() { return $this->container['message']; } /** * Sets message * * @param string $message Response message * * @return $this */ public function setMessage($message) { $this->container['message'] = $message; return $this; } /** * Gets unexistingEmails * * @return string[] */ public function getUnexistingEmails() { return $this->container['unexistingEmails']; } /** * Sets unexistingEmails * * @param string[] $unexistingEmails unexistingEmails * * @return $this */ public function setUnexistingEmails($unexistingEmails) { $this->container['unexistingEmails'] = $unexistingEmails; return $this; } /** * Gets withoutListEmails * * @return string[] */ public function getWithoutListEmails() { return $this->container['withoutListEmails']; } /** * Sets withoutListEmails * * @param string[] $withoutListEmails withoutListEmails * * @return $this */ public function setWithoutListEmails($withoutListEmails) { $this->container['withoutListEmails'] = $withoutListEmails; return $this; } /** * Gets blackListedEmails * * @return string[] */ public function getBlackListedEmails() { return $this->container['blackListedEmails']; } /** * Sets blackListedEmails * * @param string[] $blackListedEmails blackListedEmails * * @return $this */ public function setBlackListedEmails($blackListedEmails) { $this->container['blackListedEmails'] = $blackListedEmails; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode( ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } }
madeITBelgium/WordPress-Forms
vendor/sendinblue/api-v3-sdk/lib/Model/PostSendFailed.php
PHP
gpl-3.0
10,449
package view.rendes; import java.awt.Graphics; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import javax.swing.JTextField; public class RoundJTextField extends JTextField { private Shape shape; public RoundJTextField(int size) { super(size); setOpaque(false); // As suggested by @AVD in comment. } protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15); super.paintComponent(g); } protected void paintBorder(Graphics g) { g.setColor(getForeground()); g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15); } public boolean contains(int x, int y) { if (shape == null || !shape.getBounds().equals(getBounds())) { shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15); } return shape.contains(x, y); } }
gihon19/postHotelSonrisa
postHotelSonrisa/src/view/rendes/RoundJTextField.java
Java
gpl-3.0
992
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ package com.sun.star.sdbcx.comp.hsqldb; import org.hsqldb.lib.FileAccess; import org.hsqldb.lib.FileSystemRuntimeException; @SuppressWarnings("ucd") public class StorageFileAccess implements org.hsqldb.lib.FileAccess{ static { NativeLibraries.load(); } String ds_name; String key; /** Creates a new instance of StorageFileAccess */ public StorageFileAccess(Object key) throws java.lang.Exception{ this.key = (String)key; } public void createParentDirs(String filename) { } public boolean isStreamElement(String elementName) { return isStreamElement(key,elementName); } public java.io.InputStream openInputStreamElement(String streamName) throws java.io.IOException { return new NativeInputStreamHelper(key,streamName); } public java.io.OutputStream openOutputStreamElement(String streamName) throws java.io.IOException { return new NativeOutputStreamHelper(key,streamName); } public void removeElement(String filename) throws java.util.NoSuchElementException { try { if ( isStreamElement(key,filename) ) removeElement(key,filename); } catch (java.io.IOException e) { throw new FileSystemRuntimeException( e ); } } public void renameElement(String oldName, String newName) throws java.util.NoSuchElementException { try { if ( isStreamElement(key,oldName) ){ removeElement(key,newName); renameElement(key,oldName, newName); } } catch (java.io.IOException e) { throw new FileSystemRuntimeException( e ); } } private class FileSync implements FileAccess.FileSync { private final NativeOutputStreamHelper os; private FileSync(NativeOutputStreamHelper _os) { os = _os; } public void sync() throws java.io.IOException { os.sync(); } } public FileAccess.FileSync getFileSync(java.io.OutputStream os) throws java.io.IOException { return new FileSync((NativeOutputStreamHelper)os); } static native boolean isStreamElement(String key,String elementName); static native void removeElement(String key,String filename) throws java.util.NoSuchElementException, java.io.IOException; static native void renameElement(String key,String oldName, String newName) throws java.util.NoSuchElementException, java.io.IOException; }
jvanz/core
connectivity/com/sun/star/sdbcx/comp/hsqldb/StorageFileAccess.java
Java
gpl-3.0
3,316
// File: fig0621.cpp // Computer Systems, Fourth Edition // Figure 6.21 #include <iostream> using namespace std; int numPts; int value; int j; void printBar (int n) { int k; for (k = 1; k <= n; k++) { cout << '*'; } cout << endl; } int main () { cin >> numPts; for (j = 1; j <= numPts; j++) { cin >> value; printBar (value); } return 0; }
StanWarford/pep8
help/figures/fig0621.cpp
C++
gpl-3.0
385
// ---------------------------------------------------------------------- // <copyright file="TMAPcontrol.cs" company="none"> // Copyright (C) 2012 // // 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, either version 3 of the License, or // (at your option) any later version. // // 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, see <http://www.gnu.org/licenses/>. // // </copyright> // <author>pleoNeX</author> // <email>benito356@gmail.com</email> // <date>02/09/2012 3:53:19</date> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using Ekona; namespace NINOKUNI { public partial class TMAPcontrol : UserControl { TMAP tmap; IPluginHost pluginHost; public TMAPcontrol() { InitializeComponent(); } public TMAPcontrol(sFile cfile, IPluginHost pluginHost) { InitializeComponent(); this.pluginHost = pluginHost; tmap = new TMAP(cfile, pluginHost); numLayer_ValueChanged(null, null); } ~TMAPcontrol() { tmap = null; } private void numLayer_ValueChanged(object sender, EventArgs e) { picMap.Image = tmap.Get_Map((int)numLayer.Value); } private void btnSave_Click(object sender, EventArgs e) { SaveFileDialog o = new SaveFileDialog(); o.AddExtension = true; o.DefaultExt = ".png"; o.FileName = tmap.FileName + ".png"; o.Filter = "Portable Net Graphic (*.png)|*.png"; if (o.ShowDialog() != DialogResult.OK) return; picMap.Image.Save(o.FileName, System.Drawing.Imaging.ImageFormat.Png); o.Dispose(); o = null; } private void numPicMode_ValueChanged(object sender, EventArgs e) { picMap.SizeMode = (PictureBoxSizeMode)numPicMode.Value; } } }
pleonex/tinke
Plugins/NINOKUNI/NINOKUNI/TMAPcontrol.cs
C#
gpl-3.0
2,689
package cn.nukkit.redstone; import cn.nukkit.block.Block; import cn.nukkit.block.BlockRedstoneWire; import cn.nukkit.block.BlockSolid; import cn.nukkit.math.Vector3; import java.util.*; /** * author: Angelic47 * Nukkit Project */ public class Redstone { public static final int POWER_NONE = 0; public static final int POWER_WEAKEST = 1; public static final int POWER_STRONGEST = 16; //NOTICE: Here POWER_STRONGEST is 16, not 15. //I set it to 16 in order to calculate the energy in blocks, such as the redstone torch under the cobblestone. //At that time, the cobblestone's energy is 16, not 15. If you put a redstone wire next to it, the redstone wire will got 15 energy. //So, POWER_WEAKEST also means that energy in blocks, not redstone wire it self. So set it to 1. private static final Comparator<UpdateObject> orderIsdn = new Comparator<UpdateObject>() { @Override public int compare(UpdateObject o1, UpdateObject o2) { if (o1.getPopulation() > o2.getPopulation()) { return -1; } else if (o1.getPopulation() < o2.getPopulation()) { return 1; } else { return 0; } } }; public static void active(Block source) { Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); int currentLevel = source.getPowerLevel() - 1; if (currentLevel <= 0) { return; } addToQueue(updateQueue, source); while (!updateQueue.isEmpty()) { UpdateObject updatingObj = updateQueue.poll(); Block updating = updatingObj.getLocation(); currentLevel = updatingObj.getPopulation(); if (currentLevel > updating.getPowerLevel()) { updating.setPowerLevel(currentLevel); updating.getLevel().setBlock(updating, updating, true, true); addToQueue(updateQueue, updating); } } } public static void active(Block source, Map<String, Block> allBlocks) { Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); int currentLevel = source.getPowerLevel() - 1; if (currentLevel <= 0) { return; } addToQueue(updateQueue, source); while (!updateQueue.isEmpty()) { UpdateObject updatingObj = updateQueue.poll(); Block updating = updatingObj.getLocation(); currentLevel = updatingObj.getPopulation(); if (currentLevel > updating.getPowerLevel()) { updating.setPowerLevel(currentLevel); updating.getLevel().setBlock(updating, updating, true, true); if (allBlocks.containsKey(updating.getLocationHash())) { allBlocks.remove(updating.getLocationHash()); } addToQueue(updateQueue, updating); } } } public static void deactive(Block source, int updateLevel) { //Step 1: find blocks which need to update Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); Queue<UpdateObject> sourceList = new PriorityQueue<>(1, orderIsdn); Map<String, Block> updateMap = new HashMap<>(); Map<String, Block> closedMap = new HashMap<>(); int currentLevel = updateLevel; if (currentLevel <= 0) { return; } addToDeactiveQueue(updateQueue, source, closedMap, sourceList, currentLevel); while (!updateQueue.isEmpty()) { UpdateObject updateObject = updateQueue.poll(); Block updating = updateObject.getLocation(); currentLevel = updateObject.getPopulation(); if (currentLevel >= updating.getPowerLevel()) { updating.setPowerLevel(0); updateMap.put(updating.getLocationHash(), updating); addToDeactiveQueue(updateQueue, updating, closedMap, sourceList, currentLevel); } else { sourceList.add(new UpdateObject(updating.getPowerLevel(), updating)); } } //Step 2: recalculate redstone power while (!sourceList.isEmpty()) { active(sourceList.poll().getLocation(), updateMap); } for (Block block : updateMap.values()) { block.setPowerLevel(0); block.getLevel().setBlock(block, block, true, true); } } private static void addToQueue(Queue<UpdateObject> updateQueue, Block location) { if (location.getPowerLevel() <= 0) { return; } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST, Vector3.SIDE_UP, Vector3.SIDE_DOWN}) { if (location.getSide(side) instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, location.getSide(side))); } } if (location instanceof BlockRedstoneWire) { Block block = location.getSide(Vector3.SIDE_UP); if (!(block instanceof BlockSolid)) { for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { if (block.getSide(side) instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, block.getSide(side))); } } } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_WEST, Vector3.SIDE_EAST, Vector3.SIDE_SOUTH}) { block = location.getSide(side); if (!(block instanceof BlockSolid)) { Block blockDown; blockDown = block.getSide(Vector3.SIDE_DOWN); if (blockDown instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, blockDown)); } } } } } private static void addToDeactiveQueue(Queue<UpdateObject> updateQueue, Block location, Map<String, Block> closedMap, Queue<UpdateObject> sourceList, int updateLevel) { if (updateLevel < 0) { return; } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST, Vector3.SIDE_UP, Vector3.SIDE_DOWN}) { if (location.getSide(side).isPowerSource() || (updateLevel == 0 && location.getSide(side).isPowered())) { sourceList.add(new UpdateObject(location.getPowerLevel(side), location.getSide(side))); } else if (location.getSide(side) instanceof BlockRedstoneWire) { if (!closedMap.containsKey(location.getSide(side).getLocationHash())) { closedMap.put(location.getSide(side).getLocationHash(), location.getSide(side)); updateQueue.add(new UpdateObject(updateLevel - 1, location.getSide(side))); } } } if (location instanceof BlockRedstoneWire) { Block block = location.getSide(Vector3.SIDE_UP); for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { if (block.getSide(side) instanceof BlockRedstoneWire) { if (!closedMap.containsKey(block.getSide(side).getLocationHash())) { closedMap.put(block.getSide(side).getLocationHash(), block.getSide(side)); updateQueue.add(new UpdateObject(updateLevel - 1, block.getSide(side))); } } } Block blockDown; for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { block = location.getSide(side); blockDown = block.getSide(Vector3.SIDE_DOWN); if (blockDown instanceof BlockRedstoneWire) { if (!closedMap.containsKey(blockDown.getLocationHash())) { closedMap.put(blockDown.getLocationHash(), blockDown); updateQueue.add(new UpdateObject(updateLevel - 1, blockDown)); } } } } } }
Niall7459/Nukkit
src/main/java/cn/nukkit/redstone/Redstone.java
Java
gpl-3.0
8,365